Files
metin2-server/tests/features/test_cube_craft.py
T

326 lines
32 KiB
Python

"""Sealed live-owner settlement pipeline; no user craft action or actor thaw."""
import re
import subprocess
import tempfile
import unittest
from pathlib import Path
ROOT=Path(__file__).resolve().parents[2]
class CubeCraft(unittest.TestCase):
def test_actual_release_readiness_and_terminal_reply(self):
actor=(ROOT/'src/server/game/src/port_cube_actor.cpp').read_text()
start=actor.index('bool releaseReady(')
helper=actor[start:actor.index('\n}\n}\n\nPortCubeGoldPickup',start)+2]
helper=helper.replace('PortCube::HandshakeEnabled','audited').replace('PortCube::ActorMutationAuditComplete','audited')
platform=(ROOT/'tests/features/fixtures/cube_release_actor.inc').read_text()
prefix,tests=platform.split('// ACTUAL_HELPERS_HERE',1)
self.compile_run(prefix+helper+tests,['-lsqlite3'])
def compile_run(self, source, libraries=()):
with tempfile.TemporaryDirectory() as folder:
cpp=Path(folder)/'probe.cpp'; exe=Path(folder)/'probe'
cpp.write_text('#include "src/server/common/cube_presentation.h"\n'+source)
subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-fno-sanitize-recover=all','-I'+str(ROOT),str(cpp),*libraries,'-o',str(exe)],check=True)
subprocess.run([str(exe),str(Path(folder)/'cube.db')],check=True)
def test_authorized_prepare_execute_transaction(self):
self.compile_run('#include "tests/features/fixtures/cube_craft_probe.cpp"\n', ['-lsqlite3'])
def test_receipt_codec_and_craft_state(self):
self.compile_run(r'''
#define main cubeBaseMain
#include "tests/features/fixtures/cube_batch_probe.cpp"
#undef main
#include "src/server/common/cube_craft.h"
int main(){auto b=batch();const auto plan=SettlePlan(b,std::string("\1\144\1",3),proto);assert(plan.result=="ok");CraftReceipt receipt{plan.result,plan.successes,plan.fee,plan.awards};
const auto bytes=EncodeCraftReceipt(receipt);CraftReceipt parsed;assert(bytes.size()==16+117*2&&DecodeCraftReceipt(bytes,parsed)&&ValidateCraftReceipt(b,parsed,proto));
for(size_t at=0;at<bytes.size();++at)assert(!DecodeCraftReceipt(bytes.substr(0,at),parsed));assert(!DecodeCraftReceipt(bytes+"x",parsed));
auto wrong=receipt;wrong.fee++;assert(!ValidateCraftReceipt(b,wrong,proto));wrong=receipt;wrong.awards[0].value.extra[68]++;assert(!ValidateCraftReceipt(b,wrong,proto));
wrong=receipt;wrong.result="gold_changed";assert(EncodeCraftReceipt(wrong).empty());
auto identity=ArmFrame(b,8);identity.cookie=7;identity.body.clear();identity.message=Message::Poll;
CraftFlow flow;assert(!flow.Start(identity,false,true)&&!flow.Start(identity,true,false)&&flow.Start(identity,true,true));assert(flow.Request().message==Message::Prepare);
auto answer=identity;answer.message=Message::CraftAnswer;answer.status=Status::Complete;answer.body=bytes;assert(!flow.Answer(answer,b,proto)); // completion cannot bypass Prepare phase
answer.body.clear();answer.status=Status::Prepared;auto stale=answer;stale.session++;assert(!flow.Answer(stale,b,proto));assert(flow.Answer(answer,b,proto)&&flow.Request().message==Message::Execute&&flow.Answer(answer,b,proto));
answer.status=Status::Held;assert(flow.Answer(answer,b,proto)&&flow.MayRetry());answer.status=Status::Complete;answer.body=bytes;
assert(flow.Answer(answer,b,proto)&&flow.State()==CraftFlow::Complete&&!flow.MayRetry()&&flow.Answer(answer,b,proto));
const auto alternate=SettlePlan(b,std::string("\1\144\144",3),proto);answer.body=EncodeCraftReceipt({alternate.result,alternate.successes,alternate.fee,alternate.awards});assert(!flow.Answer(answer,b,proto)&&flow.State()==CraftFlow::Held);
CraftFlow lost;assert(lost.Start(identity,true,true));lost.Invalidate();answer.status=Status::Prepared;answer.body.clear();assert(!lost.Answer(answer,b,proto)&&!lost.MayRetry());
auto request=identity;request.message=Message::Prepare;assert(EncodeHandshake(request).size()==102);request.body="x";assert(!ValidHandshake(request));
assert(IsDbHandshakeReply(Message::CraftAnswer)&&!IsDbHandshakeReply(Message::Prepare)&&!IsDbHandshakeReply(Message::Execute));
puts("PASS canonical craft receipt, factory metadata/fee validation, phased identity-bound retries, conflicting receipt/lost transport held; no actor asset permission");}
''', ['-lsqlite3'])
def test_entropy_rejection_and_failure(self):
self.compile_run(r'''
#include <unistd.h>
#include <fcntl.h>
#include <cerrno>
#include <cassert>
#include <vector>
static int opened=7,closed=0;static unsigned calls=0;static bool interrupted=true,reject=false;static std::vector<unsigned char> data={200,255,199,0,99,100};
static int Open(const char*,int flags){assert(flags&O_CLOEXEC);return opened;}
static int Close(int fd){assert(fd==7);++closed;return 0;}
static ssize_t Read(int fd,void* out,size_t size){assert(fd==7&&size==1);++calls;if(interrupted){interrupted=false;errno=EINTR;return -1;}if(reject){*static_cast<unsigned char*>(out)=255;return 1;}if(data.empty())return 0;*static_cast<unsigned char*>(out)=data.front();data.erase(data.begin());return 1;}
#define open Open
#define close Close
#define read Read
#include "src/server/common/cube_random.h"
#undef open
#undef close
#undef read
int main(){{PortCube::CraftEntropy rng;assert(rng.Draw()==100&&rng.Draw()==1&&rng.Draw()==100&&rng.Draw()==1&&rng.Draw()==0);reject=true;const auto start=calls;assert(!rng.Draw()&&calls-start==1024);}assert(closed==1);opened=-1;{PortCube::CraftEntropy unavailable;assert(!unavailable.Draw());}assert(closed==1);}
''')
def test_actual_item_id_allocator_batch_reservation(self):
# Compile the actual production TU with only its platform declarations
# replaced. This exercises the bridge, cursor and spare handoff, not a
# second allocator implementation or a source-string assertion.
actual=(ROOT/'src/server/game/src/item_manager_idrange.cpp').read_text()
actual=re.sub(r'^#include .*\n','',actual,flags=re.M)
self.compile_run(r'''
#include <cassert>
#include <cstdint>
#include <cstdio>
#include <map>
#include <vector>
#include <limits>
#include "src/server/common/cube_item_ids.h"
using DWORD=uint32_t;
struct TItemIDRangeTable {DWORD dwMin=0,dwMax=0,dwUsableItemIDMin=0;};
static unsigned shutdowns=0,packets=0;static DWORD requested=0;
void thecore_shutdown(){++shutdowns;}
#define sys_err(...) ((void)0)
#define sys_log(...) ((void)0)
constexpr unsigned HEADER_GD_REQ_SPARE_ITEM_ID_RANGE=1;
struct Desc {void DBPacket(unsigned header,unsigned handle,const void* data,size_t size){assert(header==1&&!handle&&size==4);++packets;requested=*static_cast<const DWORD*>(data);}} descriptor,*db_clientdesc=&descriptor;
struct ITEM_MANAGER {
DWORD m_dwCurrentID=0;TItemIDRangeTable m_ItemIDRange,m_ItemIDSpareRange;std::map<DWORD,int> m_map_pkItemByID;
static ITEM_MANAGER& instance(){static ITEM_MANAGER manager;return manager;}
DWORD GetNewID();bool SetMaxItemID(TItemIDRangeTable);bool SetMaxSpareItemID(TItemIDRangeTable);
};
''' + actual + r'''
int main(){using namespace PortCube;ItemIDPlan plan;plan.next=77;plan.ids={9};
const ItemIDRange active{10,20,12},spare{30,40,32};
for(unsigned next=12;next<=20;++next)for(unsigned count=1;count<=20;++count){
ItemIDPlan p;const auto total=20-next+8;assert(PlanItemIDs(active,next,spare,count,p)==(count<=total));
if(count<=total){assert(p.ids.size()==count);for(unsigned i=0;i<count;++i)assert(p.ids[i]==(i<20-next?next+i:32+i-(20-next)));assert(p.next==(p.spare?p.ids.back()+1:next+count));}}
assert(!PlanItemIDs(active,11,spare,1,plan)&&plan.next==77&&plan.ids==std::vector<uint32_t>{9});
assert(!PlanItemIDs(active,21,spare,1,plan)&&!PlanItemIDs(active,12,spare,0,plan)&&!PlanItemIDs(active,12,spare,101,plan));
assert(!PlanItemIDs({10,20,9},12,spare,1,plan));
assert(!PlanItemIDs(active,19,{20,40,30},2,plan)); // inclusive boundary collision
assert(!PlanItemIDs(active,19,{1,10,2},2,plan));
assert(PlanItemIDs(active,19,{},1,plan)&&plan.next==20&&!plan.spare);
assert(PlanItemIDs({UINT32_MAX-3,UINT32_MAX,UINT32_MAX-2},UINT32_MAX-1,{},1,plan)&&plan.next==UINT32_MAX);
assert(!PlanItemIDs({UINT32_MAX-3,UINT32_MAX,UINT32_MAX-2},UINT32_MAX-1,{},2,plan));
auto& m=ITEM_MANAGER::instance();std::vector<uint32_t> ids{99};
assert(!PortCubeReserveItemIDs(1,ids)&&m.m_dwCurrentID==0&&ids[0]==99&&!shutdowns&&!packets);
m.SetMaxItemID({10,20,12});m.SetMaxSpareItemID({30,40,32});m.m_dwCurrentID=18;
m.m_map_pkItemByID[32]=1;assert(!PortCubeReserveItemIDs(4,ids)&&m.m_dwCurrentID==18&&m.m_ItemIDSpareRange.dwMin==30&&ids[0]==99&&!packets);
m.m_map_pkItemByID.clear();db_clientdesc=nullptr;assert(!PortCubeReserveItemIDs(4,ids)&&m.m_dwCurrentID==18);db_clientdesc=&descriptor;
assert(PortCubeReserveItemIDs(4,ids)&&ids==std::vector<uint32_t>({18,19,32,33})&&m.m_dwCurrentID==34&&m.m_ItemIDRange.dwMin==30&&!m.m_ItemIDSpareRange.dwMin&&packets==1&&requested==20);
assert(m.GetNewID()==34);assert(PortCubeReserveItemIDs(5,ids)&&ids==std::vector<uint32_t>({35,36,37,38,39})&&m.m_dwCurrentID==40);
auto before=ids;assert(!PortCubeReserveItemIDs(1,ids)&&ids==before&&m.m_dwCurrentID==40&&!shutdowns&&packets==1);
assert(!PortCubeReserveItemIDs(0,ids)&&!PortCubeReserveItemIDs(101,ids));
// Nested admission fails; RAII releases the bridge on exceptional unwinding.
CubeIDRequest request{1,{}};try{CubeIDScope scoped(request);assert(!PortCubeReserveItemIDs(1,ids));throw 1;}catch(int){}assert(!cubeIDRequest);
puts("PASS actual allocator: atomic bounded reservation, ordinary interleaving, exact spare handoff, collision/exhaustion/disconnect refusal without shutdown or partial cursor/output, overflow boundaries and scope cleanup");}
''')
def factory_source(self):
game=ROOT/'src/server/game/src'
manager=(game/'item_manager.cpp').read_bytes().decode('latin1')
create='LPITEM ITEM_MANAGER::CreateItem'+manager.split('LPITEM ITEM_MANAGER::CreateItem',1)[1].split('\nvoid ITEM_MANAGER::DelayedSave',1)[0]
destroy=manager.split('void ITEM_MANAGER::DestroyItem(LPITEM item)',1)[1].split('\nLPITEM ITEM_MANAGER::Find(',1)[0]
destroy='void ITEM_MANAGER::DestroyItem(LPITEM item)'+destroy.split('#endif',1)[1]
item=(game/'item.cpp').read_text();attr=(game/'item_attribute.cpp').read_text()
save='void CItem::Save()'+item.split('void CItem::Save()',1)[1].split('\n#include "port_cube_item.inc"',1)[0]
socket='void CItem::SetSocket('+item.split('void CItem::SetSocket(',1)[1].split('\nint CItem::GetGold()',1)[0]
normal='void CItem::SetAttribute('+attr.split('void CItem::SetAttribute(',1)[1].split('\nvoid CItem::SetForceAttribute(',1)[0]
force='void CItem::SetForceAttribute('+attr.split('void CItem::SetForceAttribute(',1)[1].split('\nvoid CItem::CopyAttributeTo(',1)[0]
factory=re.sub(r'^#include .*\n','',(game/'port_cube_factory.cpp').read_text(),flags=re.M)
restore='void CItem::PortCubeInitNewAttach()'+item.split('void CItem::PortCubeInitNewAttach()',1)[1].split('\nLPITEM CItem::RemoveFromGround()',1)[0]
return '#include "tests/features/fixtures/cube_factory_platform.h"\n'+create+destroy+save+socket+normal+force+restore+factory
def test_actual_new_item_factory_templates(self):
self.compile_run(self.factory_source()+'\n#include "tests/features/fixtures/cube_factory_cases.inc"\n')
def test_actual_atomic_inventory_install(self):
game=ROOT/'src/server/game/src'
registry=(game/'port_cube_registry.inc').read_text()
install=re.sub(r'^#include .*\n','',(game/'port_cube_apply.cpp').read_text(),flags=re.M)
prefix='\nstatic bool held=true;bool PortCubeActorHeld(const CHARACTER*){return held;}\n'
self.compile_run(self.factory_source()+prefix+registry+install+'\n#include "tests/features/fixtures/cube_apply_cases.inc"\n')
def test_actual_actor_apply_readback_and_duplicate_reply(self):
actor=(ROOT/'src/server/game/src/port_cube_actor.cpp').read_text()
start=actor.index('bool applyImage(');end=actor.index('\nbool releaseReady(',start)
helper=actor[start:end]
reply=actor.split(' if(f.message==PortCube::Message::LiveImageAckAnswer) {',1)[1].split(' if(f.message==PortCube::Message::CraftAnswer)',1)[0]
reply='void receive(CHARACTER* ch,Owner& o,const PortCube::Handshake& f){if(f.message==PortCube::Message::LiveImageAckAnswer){'+reply+'}'
code=r'''
#define main cubeBaseMain
#include "tests/features/fixtures/cube_batch_probe.cpp"
#undef main
#include "src/server/common/cube_live_image.h"
constexpr unsigned INVENTORY=1,INVENTORY_MAX_NUM=225;static bool audited=true,changeOther=false;static unsigned installs=0;static InventoryImage current;static uint8_t other=4;
struct TQuickslot{uint8_t type=0;uint16_t pos=0;};struct CHARACTER{TQuickslot slots[36];bool GetQuickslot(unsigned n,TQuickslot** p){*p=&slots[n];return true;}int64_t GetGold(){return current.gold;}};using LPCHARACTER=CHARACTER*;
struct Owner{Batch batch;ActorHandshake flow;CraftFlow craft;bool frozen=true;LiveImageFlow image;std::string seal,appliedSeal;std::array<PortCubeView::Quickslot,36> quickslots={};bool quickslotsCaptured=false;};
struct Snapshot{std::string seal;std::vector<Item> ordinary;};
bool capture(CHARACTER*,Snapshot& s){s.ordinary=current.items;Writer w;w.n(current.gold,8);for(const auto& i:current.items){w.n(1,1);w.n(i.cell,2);w.n(i.usable,1);w.reward(i.value);}PortEconomy::Reward r;r.id=600;r.vnum=19;r.count=1;r.extra[0]=other;w.n(2,1);w.n(300,2);w.n(1,1);w.reward(r);s.seal=w.data;return true;}
bool matches(CHARACTER*,const Owner&){return true;}bool connected(){return true;}
struct Table{unsigned bSize=1,dwFlags=0;};constexpr unsigned ITEM_FLAG_STACKABLE=1;struct ITEM_MANAGER{static ITEM_MANAGER& instance(){static ITEM_MANAGER m;return m;}Table* GetTable(unsigned v){static Table material{1,1},reward{1,0};return v==19?&reward:&material;}};
bool PortCubeInstallAuthoritative(CHARACTER*,const InventoryImage& image){++installs;current=image;if(changeOther)++other;return true;}
'''+helper+reply+r'''
Owner ready(CHARACTER* ch,Handshake& answer){Owner o;o.batch=batch();current={o.batch.gold,o.batch.inventory};other=4;changeOther=false;Snapshot s;capture(ch,s);o.seal=s.seal;
assert(o.flow.Start(o.batch,8,1,true));auto frame=ArmFrame(o.batch,8);frame.body.clear();frame.cookie=7;frame.message=Message::Answer;frame.status=Status::Armed;assert(o.flow.Armed(frame,1)&&o.flow.Submit(true,1));frame.status=Status::Frozen;assert(o.flow.Answer(frame));
assert(o.craft.Start(o.flow.Request(Message::Poll),true,true));frame.message=Message::CraftAnswer;frame.status=Status::Prepared;assert(o.craft.Answer(frame,o.batch,proto));const auto plan=SettlePlan(o.batch,std::string("\1\144\1",3),proto);frame.status=Status::Complete;frame.body=EncodeCraftReceipt({plan.result,plan.successes,plan.fee,plan.awards});assert(o.craft.Answer(frame,o.batch,proto));
assert(o.image.Start(o.flow.Request(Message::Poll),o.batch,o.craft.Receipt(),60,proto,true));answer=o.image.Request();answer.message=Message::LiveImageAnswer;answer.status=Status::LiveImageReady;answer.body=o.image.Image();return o;}
int main(){CHARACTER ch;Handshake reply;auto o=ready(&ch,reply);receive(&ch,o,reply);assert(installs==1&&current.gold==760&&o.image.State()==LiveImageFlow::Applied&&o.flow.BlocksActions()&&!o.appliedSeal.empty()&&other==4);
receive(&ch,o,reply);assert(installs==1&&o.image.State()==LiveImageFlow::Applied);InventoryImage altered;assert(DecodeInventoryImage(reply.body,altered));altered.gold++;reply.body=EncodeInventoryImage(altered);receive(&ch,o,reply);assert(installs==1&&o.image.State()==LiveImageFlow::Held&&o.flow.BlocksActions());
o=ready(&ch,reply);receive(&ch,o,reply);assert(prepareImageAck(&ch,o)&&o.image.MayAcknowledge());const auto request=o.image.Acknowledgement();assert(request.message==Message::LiveImageAck&&request.body==o.image.Image()&&ValidHandshake(request));assert(prepareImageAck(&ch,o));
assert(o.image.Answer(reply)&&o.image.MayAcknowledge());auto ack=request;ack.message=Message::LiveImageAckAnswer;ack.status=Status::Held;ack.body.clear();receive(&ch,o,ack);assert(o.image.MayAcknowledge());ack.status=Status::LiveImageAcknowledged;ack.body=request.body;auto staleAck=ack;staleAck.cookie++;receive(&ch,o,staleAck);assert(o.image.MayAcknowledge());receive(&ch,o,ack);assert(o.image.State()==LiveImageFlow::Acknowledged&&o.flow.BlocksActions());receive(&ch,o,ack);receive(&ch,o,reply);assert(o.image.State()==LiveImageFlow::Acknowledged);
o=ready(&ch,reply);receive(&ch,o,reply);assert(prepareImageAck(&ch,o));++other;assert(!prepareImageAck(&ch,o));receive(&ch,o,ack);assert(o.image.State()==LiveImageFlow::Held&&o.flow.BlocksActions());
const auto appliedCount=installs;
o=ready(&ch,reply);current.gold++;receive(&ch,o,reply);assert(installs==appliedCount&&o.image.State()==LiveImageFlow::Held&&current.gold==1001);
o=ready(&ch,reply);changeOther=true;receive(&ch,o,reply);assert(installs==appliedCount+1&&o.image.State()==LiveImageFlow::Held&&o.flow.BlocksActions()&&o.appliedSeal.empty());
puts("PASS actual image apply/ACK-preparation helpers: full pre/post seal, single application, exact ACK readback/retry, unchanged state on late duplicate, no thaw; explicit snapshot/install/actor substitutes");}
'''
code=code.replace('PortCube::HandshakeEnabled','audited').replace('PortCube::ActorMutationAuditComplete','audited')
self.compile_run(code,['-lsqlite3'])
def test_actual_trusted_batch_start(self):
actor=(ROOT/'src/server/game/src/port_cube_actor.cpp').read_text()
body='bool PortCubeStart('+actor.split('bool PortCubeStart(',1)[1].split('\nbool PortCubeActorHeld(',1)[0]
body=body.replace('PortCube::HandshakeEnabled','enabled').replace('PortCube::ActorMutationAuditComplete','audited')
source=r'''
#define main cubeBaseMain
#include "tests/features/fixtures/cube_batch_probe.cpp"
#undef main
#include "src/server/common/cube_handshake.h"
#include <ctime>
bool enabled=false,audited=false,online=true,changed=false,resolved=true,factoryFails=false,supported=true;unsigned hazard=0,factories=0,begins=0,entropy=0,entropyMode=0;Batch accepted;uint64_t acceptedSession=0;
static timespec clockNow{1700000000,1};static bool clockFails=false;
int cubeClock(clockid_t,timespec* out){*out=clockNow;return clockFails?-1:0;}
#define clock_gettime cubeClock
constexpr unsigned PHASE_GAME=1,ITEM_FLAG_STACKABLE=1;
struct Desc{struct Account{unsigned id=1;}account;bool IsPhase(unsigned){return true;}const Account& GetAccountTable(){return account;}};
struct CHARACTER{Desc desc;int64_t gold=1000;bool busy=false;bool IsPC(){return true;}Desc* GetDesc(){return &desc;}bool IsItemLoaded(){return true;}unsigned GetPlayerID(){return 1;}int64_t GetGold(){return gold;}
void* GetExchange(){return busy?this:nullptr;}void* GetShop(){return nullptr;}void* GetMyShop(){return nullptr;}bool IsOpenSafebox(){return false;}void* GetMall(){return nullptr;}bool IsSashWindowOpen(){return false;}void* DragonSoul_RefineWindow_GetOpener(){return nullptr;}};
struct Owner{Batch batch;ActorHandshake flow;};std::map<unsigned,Owner> owners;
bool PortCubePresentationSupported(CHARACTER*){return supported;}
struct MockItem;
struct Snapshot{std::vector<Item> ordinary;std::vector<MockItem*> items;};
'''+r'''
struct MockItem{bool PortCubeHasPendingMutation(){return false;}bool isLocked(){return false;}bool IsExchanging(){return false;}bool GetSkipSave(){return false;}};
bool capture(CHARACTER*,Snapshot& s){s.ordinary=batch().inventory;return true;}
bool matches(CHARACTER* c,const Owner& o){return c->desc.account.id==o.batch.account;}
const char* get_table_postfix(){return "";}bool connected(){return online;}unsigned PortCubeAdmission(CHARACTER*){return hazard;}
bool PortCubeResolveRecipe(CHARACTER*,unsigned id,const std::string& rev,Recipe& r){auto original=batch().recipe;if(!resolved||id!=original.id||rev!=Revision(original))return false;r=original;return true;}
std::string goldEvent(){++entropy;if(entropyMode==1)return {};if(entropyMode==2)return std::string(31,'0')+"1";return std::string(32,char('a'+entropy%5));}
bool PortCubeBuildRewardTemplates(uint32_t v,unsigned count,std::vector<PortEconomy::Reward>& out){++factories;if(factoryFails)return false;out=batch().rewards;out.resize(count);for(unsigned i=0;i<count;++i){out[i].id=100+i;out[i].vnum=v;out[i].count=1;}return true;}
struct Table{unsigned bSize=1,dwFlags=0;};struct ITEM_MANAGER{static ITEM_MANAGER& instance(){static ITEM_MANAGER m;return m;}Table* GetTable(unsigned v){static Table material{1,1},reward{1,0};return v==19?&reward:&material;}};
bool PortCubeBegin(CHARACTER*,const Batch& b,uint64_t session){++begins;if(changed)return false;assert(Validate(b));accepted=b;acceptedSession=session;return true;}
'''+body+r'''
int main(){CHARACTER ch;const auto rev=Revision(batch().recipe);
assert(!PortCubeStart(&ch,1,rev,3)&&!factories&&!entropy);enabled=audited=true;
supported=false;assert(!PortCubeStart(&ch,1,rev,3)&&!factories&&!entropy);supported=true;
assert(!PortCubeStart(&ch,1,"stale",3)&&!factories&&!entropy);hazard=1;assert(!PortCubeStart(&ch,1,rev,3));hazard=0;
ch.gold=1;assert(!PortCubeStart(&ch,1,rev,3)&&!factories&&!entropy);ch.gold=1000;
assert(!PortCubeStart(&ch,1,rev,0)&&!PortCubeStart(&ch,1,rev,101)&&!factories);
ch.gold=PortEconomy::GoldLimit+1;assert(!PortCubeStart(&ch,1,rev,3)&&!factories&&!entropy);ch.gold=1000;
online=false;assert(!PortCubeStart(&ch,1,rev,3)&&!factories&&!entropy);online=true;
entropyMode=1;assert(!PortCubeStart(&ch,1,rev,3)&&!factories);entropyMode=2;assert(!PortCubeStart(&ch,1,rev,3)&&!factories);entropyMode=0;
clockFails=true;assert(!PortCubeStart(&ch,1,rev,3)&&!factories);clockFails=false;
clockNow.tv_nsec=-1;assert(!PortCubeStart(&ch,1,rev,3)&&!factories);clockNow.tv_nsec=1;entropy=0;
assert(PortCubeStart(&ch,1,rev,3)&&factories==1&&begins==1&&entropy==3&&acceptedSession&&accepted.epoch);
assert(accepted.account==1&&accepted.player==1&&accepted.gold==1000&&accepted.inventory.size()==1&&accepted.inventory[0].value.extra[68]==255&&accepted.rewards[0].sockets[0]==77);
const auto firstEpoch=accepted.epoch;auto& owner=owners[1];owner.batch=accepted;assert(owner.flow.Start(accepted,acceptedSession,1,true));
assert(PortCubeStart(&ch,1,rev,3)&&factories==1&&entropy==3&&begins==1);assert(!PortCubeStart(&ch,1,rev,2)&&factories==1);
ch.desc.account.id=2;assert(!PortCubeStart(&ch,1,rev,3)&&factories==1);ch.desc.account.id=1;owner.flow.Invalidate(ItemWrite);assert(!PortCubeStart(&ch,1,rev,3));owners.clear();
clockNow.tv_sec=1;changed=true;assert(!PortCubeStart(&ch,1,rev,3)&&factories==2&&begins==2);changed=false;
assert(PortCubeStart(&ch,1,rev,3)&&accepted.epoch>firstEpoch&&factories==3&&begins==3);
factoryFails=true;assert(!PortCubeStart(&ch,1,rev,3)&&factories==4&&begins==3);
puts("PASS actual trusted Start: disabled no entropy/IDs, current recipe and asset preflight, server-only identity/full snapshots/factory metadata, strict epoch, exact retry without regeneration, foreign/invalidated/changed actor refusal; explicit actor/factory/Begin substitutes");}
'''
self.compile_run(source,['-lsqlite3'])
# Exercise the actual Start -> Begin -> owner insertion -> Arm path as
# well, rather than inferring it from a successful Begin substitute.
begin='bool PortCubeBegin('+actor.split('bool PortCubeBegin(',1)[1].split('\nbool PortCubeStart(',1)[0]
begin=begin.replace('PortCube::HandshakeEnabled','enabled').replace('PortCube::ActorMutationAuditComplete','audited')
prefix=source.split('int main(){CHARACTER ch;const auto rev=',1)[0]
stub='bool PortCubeBegin(CHARACTER*,const Batch& b,uint64_t session){++begins;if(changed)return false;assert(Validate(b));accepted=b;acceptedSession=session;return true;}'
self.assertIn(stub,prefix)
support=r'''
namespace quest {struct PC{bool IsLoaded(){return true;}bool IsRunning(){return false;}};
struct CQuestManager {static CQuestManager& instance(){static CQuestManager m;return m;}PC* PortCubeFindPC(unsigned){static PC p;return &p;}};}
bool PortCubeRecipeAllowed(CHARACTER*,const Recipe& recipe){Batch current,wanted;current.recipe=batch().recipe;wanted.recipe=recipe;return !changed&&Encode(current)==Encode(wanted);}
std::vector<Handshake> armFrames;void send(const Owner&,const Handshake& frame){assert(ValidHandshake(frame)&&frame.message==Message::Arm);armFrames.push_back(frame);}
'''
prefix=prefix.replace(stub,support+begin)
prefix=prefix.replace('unsigned GetPlayerID(){return 1;}', 'unsigned GetPlayerID(){return 1;}unsigned GetVID(){return 7;}bool IsWarping(){return false;}bool IsDead(){return false;}bool IsStun(){return false;}')
prefix=prefix.replace('bool IsPhase(unsigned){return true;}', 'bool IsPhase(unsigned){return true;}unsigned GetHandle(){return 8;}')
prefix=prefix.replace('struct Owner{Batch batch;ActorHandshake flow;}', 'struct Owner{unsigned vid=0,handle=0;std::string seal;Batch batch;ActorHandshake flow;}')
prefix=prefix.replace('struct Snapshot{std::vector<Item>', 'struct Snapshot{std::string seal="same";std::vector<Item>')
self.compile_run(prefix+r'''
int main(){CHARACTER ch;const auto rev=Revision(batch().recipe);
assert(!PortCubeStart(&ch,1,rev,3)&&owners.empty()&&!factories&&armFrames.empty());enabled=audited=true;
assert(PortCubeStart(&ch,1,rev,3)&&owners.size()==1&&factories==1&&armFrames.size()==1);
const auto& owner=owners.at(1);assert(owner.vid==7&&owner.handle==8&&owner.seal=="same"&&owner.flow.BlocksActions());
Batch decoded;assert(Decode(armFrames[0].body,decoded)&&Encode(decoded)==Encode(owner.batch)&&ch.gold==1000);
assert(PortCubeStart(&ch,1,rev,3)&&factories==1&&armFrames.size()==1);
owners.clear();changed=true;assert(!PortCubeStart(&ch,1,rev,3)&&owners.empty()&&factories==2&&armFrames.size()==1);
puts("PASS actual Start -> actual Begin -> immutable owner/Arm: hard-disabled no work, canonical recipe recheck, exact full batch bytes, no duplicate factory/Arm, unchanged local gold and changed-recipe refusal; explicit actor snapshot/factory/transport substitutes");}
''',['-lsqlite3'])
def test_actual_game_tick_calls_phased_requests_after_durable_source_ack(self):
actor=(ROOT/'src/server/game/src/port_cube_actor.cpp').read_text()
body='void PortCubeActorTick()'+actor.split('void PortCubeActorTick()',1)[1]
body=body.replace('PortCube::HandshakeEnabled','audited').replace('PortCube::ActorMutationAuditComplete','audited')
prefix=r'''
#define main cubeBaseMain
#include "tests/features/fixtures/cube_batch_probe.cpp"
#undef main
#include "src/server/common/cube_craft.h"
#include "src/server/common/cube_gold_outbox.h"
#include "src/server/common/cube_live_image.h"
static bool audited=true,online=true,sourceAck=false;
struct CHARACTER {unsigned pid=1;};
struct RestorePlan{bool prepared=false;bool Prepared()const{return prepared;}};
struct Owner {Batch batch;ActorHandshake flow;CraftFlow craft;unsigned handle=6;std::string seal="seal",appliedSeal="seal";uint64_t next=0;bool frozen=true;LiveImageFlow image;std::array<PortCubeView::Quickslot,36> quickslots={};bool quickslotsCaptured=true,published=false;RestorePlan restore;LiveReleaseFlow release;};
static std::map<unsigned,Owner> owners;static std::map<unsigned,CHARACTER*> characters;static std::vector<Handshake> sent;
struct CHARACTER_MANAGER{static CHARACTER_MANAGER& instance(){static CHARACTER_MANAGER m;return m;}CHARACTER* FindByPID(unsigned p){auto i=characters.find(p);return i==characters.end()?nullptr:i->second;}};
struct Outbox{std::vector<GoldDelivery> Pending(){return {};}std::vector<GoldSourceSeal> PendingSources(){return {};}bool SourceAcknowledged(const GoldSourceBinding&){return sourceAck;}uint64_t Total(const std::string&){return 0;}}goldOutbox;
struct Table{unsigned bSize=1,dwFlags=0;};constexpr unsigned ITEM_FLAG_STACKABLE=1;struct ITEM_MANAGER{static ITEM_MANAGER& instance(){static ITEM_MANAGER m;return m;}Table* GetTable(unsigned v){static Table reward{1,0},material{1,1};return v==19?&reward:&material;}};
struct DBDesc{void DBPacket(unsigned,unsigned,const void*,size_t){}}desc,*db_clientdesc=&desc;
bool goldReady(){return true;}bool connected(){return online;}bool matches(CHARACTER* c,const Owner&){return c;}
bool prepareImageAck(CHARACTER*,Owner& o){return o.image.MayAcknowledge()||o.image.BeginAcknowledge(o.image.Image());} // explicit readback substitute; dedicated actual helper probe above
bool localReady=true;unsigned readinessChecks=0;bool releaseReady(CHARACTER*,const Owner&){++readinessChecks;return localReady;} // actual helper tested independently
unsigned publications=0;bool PortCubePublishAuthoritative(CHARACTER*,const Batch&,const std::string&,const std::array<PortCubeView::Quickslot,36>&){++publications;return true;}
unsigned eventPreparations=0;bool PortCubePrepareRestoredInventory(CHARACTER*,RestorePlan& plan){++eventPreparations;plan.prepared=true;return true;}
struct Snapshot{std::string seal="seal";};bool capture(CHARACTER*,Snapshot&){return true;}unsigned PortCubeAdmission(CHARACTER*){return 0;}
Handshake goldFrame(const GoldDelivery&){return {};}Handshake goldCloseFrame(const GoldSourceSeal&){return {};}
void send(const Owner&,const Handshake& frame){assert(ValidHandshake(frame));sent.push_back(frame);}
'''
tests=r'''
int main(){CHARACTER ch;characters[1]=&ch;auto& o=owners[1];o.batch=batch();assert(o.flow.Start(o.batch,8,1,true));auto ack=ArmFrame(o.batch,8);ack.body.clear();ack.message=Message::Answer;ack.status=Status::Armed;ack.cookie=7;assert(o.flow.Armed(ack,1)&&o.flow.Submit(true,1));ack.status=Status::Frozen;assert(o.flow.Answer(ack));
PortCubeActorTick();assert(o.craft.State()==CraftFlow::Idle&&sent.back().message==Message::Poll);
o.next=0;sourceAck=true;PortCubeActorTick();assert(o.craft.State()==CraftFlow::WaitPrepare&&sent.back().message==Message::Prepare);
ack.message=Message::CraftAnswer;ack.status=Status::Prepared;assert(o.craft.Answer(ack,o.batch,proto));o.next=0;PortCubeActorTick();assert(sent.back().message==Message::Execute);
const auto plan=SettlePlan(o.batch,std::string("\1\144\1",3),proto);ack.status=Status::Complete;ack.body=EncodeCraftReceipt({plan.result,plan.successes,plan.fee,plan.awards});assert(o.craft.Answer(ack,o.batch,proto));o.next=0;PortCubeActorTick();assert(sent.back().message==Message::LiveImageRequest&&o.flow.BlocksActions());
ack.message=Message::LiveImageAnswer;ack.status=Status::LiveImageReady;ack.body=o.image.Image();assert(o.image.Answer(ack));const auto count=sent.size();o.next=0;PortCubeActorTick();assert(sent.size()==count&&o.flow.BlocksActions());
assert(o.image.MarkApplied(o.image.Image()));o.next=0;PortCubeActorTick();assert(sent.size()==count+1&&sent.back().message==Message::LiveImageAck&&sent.back().body==o.image.Image()&&o.image.MayAcknowledge());o.next=0;PortCubeActorTick();assert(sent.size()==count+2&&sent.back().message==Message::LiveImageAck);
ack.message=Message::LiveImageAckAnswer;ack.status=Status::LiveImageAcknowledged;assert(o.image.Answer(ack));const auto confirmedCount=sent.size();o.next=0;PortCubeActorTick();assert(sent.size()==confirmedCount&&o.flow.BlocksActions()&&publications==1&&o.published&&!eventPreparations);o.next=0;PortCubeActorTick();assert(publications==1&&sent.size()==confirmedCount&&eventPreparations==1&&o.restore.Prepared());o.next=0;PortCubeActorTick();assert(eventPreparations==1&&o.flow.BlocksActions()&&sent.back().message==Message::LiveReleaseRequest&&sent.size()==confirmedCount+1);
const auto release=EncodeHandshake(sent.back());o.next=0;PortCubeActorTick();assert(sent.size()==confirmedCount+2&&EncodeHandshake(sent.back())==release&&readinessChecks==2);
const auto waiting=o.release;auto released=sent.back();released.message=Message::LiveReleaseAnswer;released.status=Status::LiveReleased;assert(o.release.Answer(released));o.next=0;PortCubeActorTick();assert(sent.size()==confirmedCount+2&&o.release.State()==LiveReleaseFlow::Released&&o.flow.BlocksActions()&&eventPreparations==1);o.release=waiting;
localReady=false;o.next=0;PortCubeActorTick();assert(sent.size()==confirmedCount+2&&o.release.State()==LiveReleaseFlow::Held&&o.flow.BlocksActions());
online=false;PortCubeActorTick();assert(o.craft.State()==CraftFlow::Held&&o.release.State()==LiveReleaseFlow::Held&&o.flow.BlocksActions());
puts("PASS actual actor Tick: no Prepare before source ACK, original identity Prepare/Execute progression, no poll/execute loop after receipt, disconnect retains hold; explicit audit/source/actor boundaries");}
'''
self.compile_run(prefix+body+tests,['-lsqlite3'])
if __name__=='__main__':
unittest.main()