// Essai de bout en bout du moteur : node backend/dark/test.mjs // Lance le moteur en mémoire sur un port libre, avec un mid et une horloge pilotés par le test, // puis joue le rôle de plusieurs desks avec la même cryptographie que le navigateur. import assert from "node:assert/strict"; import {mkdtemp,rm,readFile} from "node:fs/promises"; import {tmpdir} from "node:os"; import {join} from "node:path"; import {createLocal,createHttp} from "./server.mjs"; import {INFO} from "./engine.mjs"; const sub=globalThis.crypto.subtle,te=new TextEncoder(); const hex=b=>Buffer.from(b).toString("hex"),unhex=s=>Buffer.from(s,"hex"); let mid=60,clock=Date.now();const now=()=>clock; const dir=await mkdtemp(join(tmpdir(),"dark-")); let {engine,store}=await createLocal({dataDir:dir,getMid:()=>mid,now,test:true}); let http=createHttp(engine);await new Promise(r=>http.listen(0,r)); let base="http://localhost:"+http.address().port; const get=p=>fetch(base+p).then(r=>r.json()); const post=async(p,b)=>{const r=await fetch(base+p,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)});return {status:r.status,...await r.json()}}; async function desk(){const k=await sub.generateKey({name:"ECDSA",namedCurve:"P-256"},true,["sign","verify"]); const pub=hex(await sub.exportKey("raw",k.publicKey)); const sign=async(action,c)=>{const ts=now();return {pub,ts,sig:hex(await sub.sign({name:"ECDSA",hash:"SHA-256"},k.privateKey,te.encode("dark|"+action+"|"+c+"|"+ts)))}}; return {pub,sign}} async function seal(o,key){ const ek=await sub.importKey("jwk",key,{name:"ECDH",namedCurve:"P-256"},false,[]); const eph=await sub.generateKey({name:"ECDH",namedCurve:"P-256"},true,["deriveBits"]); const hk=await sub.importKey("raw",await sub.deriveBits({name:"ECDH",public:ek},eph.privateKey,256),"HKDF",false,["deriveKey"]); const aes=await sub.deriveKey({name:"HKDF",hash:"SHA-256",salt:new Uint8Array(0),info:te.encode(INFO)},hk,{name:"AES-GCM",length:256},false,["encrypt"]); const iv=crypto.getRandomValues(new Uint8Array(12)); const ct=await sub.encrypt({name:"AES-GCM",iv},aes,te.encode(JSON.stringify({...o,n:hex(crypto.getRandomValues(new Uint8Array(8)))}).padEnd(96," "))); return {c:hex(await sub.digest("SHA-256",ct)),env:{epk:hex(await sub.exportKey("raw",eph.publicKey)),iv:hex(iv),ct:hex(ct)}}} const place=async(d,o,exp=0,key)=>{const s=await seal(o,key||(await get("/state")).key);return {c:s.c,s,r:await post("/orders",{...s,exp,...await d.sign("seal",s.c)})}}; const mine=async d=>(await post("/mine",await d.sign("mine",""))).orders; let n=0;const step=async(name,fn)=>{await fn();n++;console.log("ok "+name)}; const A=await desk(),B=await desk(),C=await desk(),D=await desk(); let st=await get("/state"),a1; await step("state exposes the engine key and the mid, nothing else",async()=>{ assert.equal(st.ok,true);assert.equal(st.mid,60);assert.equal(st.key.kty,"EC");assert.equal(st.key.d,undefined);assert.equal(st.count,0)}); await step("a sealed sell rests; the public feed shows a fingerprint only",async()=>{ a1=await place(A,{side:"sell",size:1000,lim:0});assert.equal(a1.r.status,200);assert.equal(a1.r.order.state,"resting"); st=await get("/state");assert.equal(st.count,1);assert.deepEqual(Object.keys(st.resting[0]).sort(),["c","exp","ts"]); const pub=JSON.stringify(st);assert.ok(!pub.includes("sell")&&!pub.includes("1000")&&!pub.includes(A.pub))}); await step("bad signature, tampered block, wrong size, replay and too small are refused",async()=>{ const s=await seal({side:"buy",size:1000,lim:0},st.key),sg=await B.sign("seal",s.c); assert.equal((await post("/orders",{...s,exp:0,...sg,sig:sg.sig.replace(/^../,"00")})).status,401); assert.equal((await post("/orders",{...s,exp:0,...await A.sign("cancel",s.c)})).status,401); const t=s.env.ct.slice(0,-2)+(s.env.ct.endsWith("00")?"01":"00"); assert.equal((await post("/orders",{c:s.c,env:{...s.env,ct:t},exp:0,...sg})).error,"bad_commit"); assert.equal((await post("/orders",{c:s.c,env:{...s.env,ct:s.env.ct+"00"},exp:0,...sg})).error,"bad_envelope"); const other=await seal({side:"buy",size:1000,lim:0},(await sub.exportKey("jwk",(await sub.generateKey({name:"ECDH",namedCurve:"P-256"},true,["deriveBits"])).publicKey))); assert.equal((await post("/orders",{...other,exp:0,...await B.sign("seal",other.c)})).error,"unreadable"); assert.equal((await place(B,{side:"buy",size:100,lim:0})).r.error,"too_small"); assert.equal((await post("/orders",{c:a1.c,env:(await seal({side:"sell",size:1000,lim:0},st.key)).env,exp:0,...await A.sign("seal",a1.c)})).status,400); assert.equal((await post("/orders",{...a1.s,exp:0,...await A.sign("seal",a1.c)})).error,"duplicate"); const old={...s,exp:0,pub:B.pub,ts:now()-10*60000};old.sig=sg.sig;assert.equal((await post("/orders",old)).status,401); assert.equal((await get("/state")).count,1)}); await step("an opposite block crosses at the mid; the older block keeps its remainder",async()=>{ const b1=await place(B,{side:"buy",size:500,lim:0});assert.equal(b1.r.order.state,"filled"); st=await get("/state");assert.deepEqual(st.tape[0],{t:st.tape[0].t,size:500,px:60});assert.equal(st.crossed,1);assert.equal(st.count,1); const ma=await mine(A);assert.equal(ma[0].rem,500);assert.equal(ma[0].fills.length,1); assert.equal((await mine(B))[0].state,"filled"); assert.equal((await post("/orders",{...await seal({side:"buy",size:500,lim:0},st.key),c:b1.c,exp:0,...await B.sign("seal",b1.c)})).status,400)}); await step("a desk never crosses against itself; only the owner can cancel",async()=>{ const a2=await place(A,{side:"buy",size:500,lim:0});assert.equal(a2.r.order.state,"resting");assert.equal((await get("/state")).count,2); assert.equal((await post("/cancel",{c:a2.c,...await B.sign("cancel",a2.c)})).status,404); assert.equal((await post("/cancel",{c:a2.c,...await A.sign("cancel",a2.c)})).order.state,"cancelled"); assert.equal((await post("/cancel",{c:a2.c,...await A.sign("cancel",a2.c)})).status,404); assert.equal((await get("/state")).count,1)}); await step("a limit holds the block until the mid comes to it",async()=>{ const c1=await place(C,{side:"buy",size:500,lim:55});assert.equal(c1.r.order.state,"resting"); await get("/state");assert.equal((await get("/state")).crossed,1); mid=54;await get("/state");st=await get("/state"); assert.equal(st.crossed,2);assert.equal(st.tape[0].px,54);assert.equal(st.tape[0].size,500);assert.equal(st.count,0); assert.equal((await mine(A)).find(o=>o.c===a1.c).state,"filled");mid=60}); await step("a block expires on time; the book survives a restart",async()=>{ const d1=await place(D,{side:"sell",size:500,lim:0},now()+60000),d2=await place(D,{side:"sell",size:2000,lim:58}); assert.equal(d1.r.status,200);assert.equal(d2.r.status,200); assert.equal((await place(D,{side:"sell",size:500,lim:0},now()+1000)).r.error,"bad_expiry"); clock+=61000;await get("/state");assert.equal((await mine(D)).find(o=>o.c===d1.c).state,"expired"); await store.flush();const disk=await readFile(join(dir,"book.json"),"utf8"); assert.ok(!disk.includes('"size":2000')&&!disk.includes("sell"),"the book on disk holds no readable order"); await new Promise(r=>http.close(r)); ({engine,store}=await createLocal({dataDir:dir,getMid:()=>mid,now,test:true}));http=createHttp(engine);await new Promise(r=>http.listen(0,r));base="http://localhost:"+http.address().port; st=await get("/state");assert.equal(st.count,1);assert.equal(st.resting[0].c,d2.c);assert.equal(st.crossed,2); const b2=await place(B,{side:"buy",size:500,lim:0});assert.equal(b2.r.order.state,"filled"); assert.equal((await mine(D)).find(o=>o.c===d2.c).rem,1500)}); await step("the test counterparty respects the limit and is marked in the tape",async()=>{ const d2=(await mine(D)).find(o=>o.state==="resting");mid=57; assert.equal((await post("/test/cross",{c:d2.c,...await D.sign("cross",d2.c)})).error,"limit");mid=60; assert.equal((await post("/test/cross",{c:d2.c,...await B.sign("cross",d2.c)})).status,404); assert.equal((await post("/test/cross",{c:d2.c,...await D.sign("cross",d2.c)})).order.state,"filled"); st=await get("/state");assert.equal(st.tape[0].test,true);assert.equal(st.tape[0].size,1500);assert.equal(st.count,0)}); await step("simultaneous blocks never fill more than what rests",async()=>{ const before=(await get("/state")).crossed,S=await desk(),buyers=await Promise.all([1,2,3,4,5,6].map(()=>desk())); assert.equal((await place(S,{side:"sell",size:1000,lim:0})).r.order.state,"resting"); const key=(await get("/state")).key,rs=await Promise.all(buyers.map(d=>place(d,{side:"buy",size:500,lim:0},0,key))); assert.ok(rs.every(x=>x.r.status===200),"every simultaneous block is accepted"); st=await get("/state");assert.equal(st.crossed-before,2);assert.equal(st.count,4); assert.equal(rs.filter(x=>x.r.order.state==="filled").length,2);assert.equal((await mine(S))[0].state,"filled"); for(const [i,d] of buyers.entries()){const o=(await mine(d))[0];if(o.state==="resting")assert.equal((await post("/cancel",{c:o.c,...await d.sign("cancel",o.c)})).status,200)} assert.equal((await get("/state")).count,0)}); await step("the health check tells what is live and what is not",async()=>{ const h=await get("/health");assert.equal(h.ok,true);assert.equal(h.matching,"live");assert.equal(h.price,"live");assert.equal(h.settlement,"not live"); assert.equal(h.sealedBytes,112);assert.equal(h.resting,(await get("/state")).count); mid=0;assert.equal((await get("/health")).price,"unavailable");mid=60}); await step("unknown routes and malformed requests are refused cleanly",async()=>{ assert.equal((await fetch(base+"/nope")).status,404); assert.equal((await fetch(base+"/orders",{method:"POST",body:"{"})).status,400); assert.equal((await fetch(base+"/orders",{method:"POST",body:"x".repeat(9000)})).status,413); assert.equal((await fetch(base+"/state",{method:"OPTIONS"})).status,204)}); await store.flush();await new Promise(r=>http.close(r));await rm(dir,{recursive:true,force:true}); console.log("\n"+n+" steps passed");