// Logique du dark pool Dark, sans état en mémoire : chaque opération lit le carnet, agit, puis le réécrit // seulement si quelque chose a changé, avec une écriture conditionnelle (si le carnet a bougé entre-temps, on recommence). // La même logique tourne en local (server.mjs, carnet dans un fichier) et sur Vercel (api/dark.mjs, carnet dans Vercel Blob). // // Ce que le moteur garantit : // - un bloc arrive chiffré pour la clé du moteur (ECDH P-256 + HKDF + AES-GCM), toujours 112 octets ; // - le flux public (/state) ne montre qu'une empreinte par bloc, jamais le sens, la taille ou la limite ; // - chaque action (sceller, annuler, lister) est signée par la clé du desk qui a créé le bloc (ECDSA P-256) ; // - deux blocs opposés se croisent au mid HyperCore, le plus ancien d'abord, jamais contre soi-même ; // - le carnet stocké ne contient que le texte chiffré et les exécutions. // Ce qu'il ne fait pas encore : le règlement onchain. Un croisement est une exécution appariée, aucun fonds ne bouge. const sub=globalThis.crypto.subtle,te=new TextEncoder(),td=new TextDecoder(); const hex=b=>Buffer.from(b).toString("hex"),unhex=s=>Buffer.from(s,"hex"); const isHex=(s,n)=>typeof s==="string"&&s.length===n*2&&/^[0-9a-f]+$/.test(s); const r6=x=>Math.round(x*1e6)/1e6; export const MIN_USD=25000,CT_BYTES=112,INFO="dark-seal-v1",SKEW=120000,MAX_REST=30*864e5,PER_DESK=20,MAX_BOOK=500,MAX_DONE=2000; const EC={name:"ECDH",namedCurve:"P-256"},SG={name:"ECDSA",namedCurve:"P-256"}; const err=(status,error,message)=>({status,body:{ok:false,error,message}}); /* Clé privée du moteur, au format JWK. À créer une seule fois : les blocs au repos en dépendent. */ export async function newEngineKey(){return sub.exportKey("jwk",(await sub.generateKey(EC,true,["deriveBits"])).privateKey)} /* store : { load() -> {data, etag}, save(data, etag) -> true | false si le carnet a changé entre-temps } */ export function createEngine({store,keyJwk,getMid,now=()=>Date.now(),test=false}){ const pubJwk={kty:keyJwk.kty,crv:keyJwk.crv,x:keyJwk.x,y:keyJwk.y};let privP; const priv=()=>privP||(privP=sub.importKey("jwk",{kty:keyJwk.kty,crv:keyJwk.crv,x:keyJwk.x,y:keyJwk.y,d:keyJwk.d},EC,false,["deriveBits"])); const plain=new Map(); // empreinte -> ordre en clair. En mémoire seulement, reconstruit au besoin. async function open(env){ const epk=await sub.importKey("raw",unhex(env.epk),EC,false,[]); const hk=await sub.importKey("raw",await sub.deriveBits({name:"ECDH",public:epk},await priv(),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,["decrypt"]); return JSON.parse(td.decode(await sub.decrypt({name:"AES-GCM",iv:unhex(env.iv)},aes,unhex(env.ct))))} const clean=o=>{const side=o&&o.side,size=r6(+o.size),lim=r6(+o.lim||0); return (side==="buy"||side==="sell")&&Number.isFinite(size)&&size>0&&size<=1e9&&Number.isFinite(lim)&&lim>=0?{side,size,lim}:null}; /* Une opération = lire, agir, écrire si besoin. fn est synchrone et marque ctx.dirty quand il modifie le carnet. */ async function tx(fn){ for(let i=0;i<6;i++){ const got=await store.load(),B=got.data||{crossed:0,tape:[],done:[],orders:[]}; for(const s of B.orders)if(!plain.has(s.c)){let o=null;try{o=clean(await open(s.env))}catch{}plain.set(s.c,o)} const ctx={B,dirty:false}; if(B.orders.some(s=>!plain.get(s.c))){B.orders=B.orders.filter(s=>plain.get(s.c));ctx.dirty=true} const out=fn(ctx); if(!ctx.dirty||await store.save(B,got.etag))return out; await new Promise(r=>setTimeout(r,20+Math.random()*60*(i+1))); } return err(503,"busy","The engine is busy. Try again in a moment.")} const ord=s=>plain.get(s.c),rem=s=>r6(ord(s).size-s.fills.reduce((a,f)=>a+f.size,0)); const within=(s,px)=>!ord(s).lim||(ord(s).side==="sell"?px>=ord(s).lim:px<=ord(s).lim); function finish(B,s,state,t){B.orders=B.orders.filter(x=>x!==s);B.done.push({c:s.c,pub:s.pub,state,fills:s.fills,exp:s.exp,ts:s.ts,at:t});if(B.done.length>MAX_DONE)B.done=B.done.slice(-MAX_DONE)} function fill(B,a,b,q,px,t){ for(const s of [a,b])if(s){s.fills.push({t,size:q,px});if(rem(s)<=0)finish(B,s,"filled",t)} B.tape.unshift(b?{t,size:q,px}:{t,size:q,px,test:true});if(B.tape.length>50)B.tape.length=50;B.crossed++} /* Expiration, ménage, puis croisement : au mid, le plus ancien d'abord, jamais deux blocs du même desk */ function sweep(B,px,t){let ch=0; for(const s of [...B.orders])if(s.exp&&s.exp<=t){finish(B,s,"expired",t);ch++} const n=B.done.length;B.done=B.done.filter(d=>t-d.at<=7*864e5);ch+=n-B.done.length; if(!px)return ch; const live=B.orders.filter(s=>within(s,px)).sort((a,b)=>a.ts-b.ts),buys=live.filter(s=>ord(s).side==="buy"),sells=live.filter(s=>ord(s).side==="sell"); for(const b of buys)for(const s of sells){if(!B.orders.includes(b))break;if(!B.orders.includes(s)||s.pub===b.pub)continue;fill(B,b,s,Math.min(rem(b),rem(s)),px,t);ch++} return ch} async function auth(b,action,c){ if(!b||!isHex(b.pub,65)||!isHex(b.sig,64)||!Number.isFinite(b.ts))return false; if(Math.abs(now()-b.ts)>SKEW)return false; try{const k=await sub.importKey("raw",unhex(b.pub),SG,false,["verify"]); return await sub.verify({name:"ECDSA",hash:"SHA-256"},k,unhex(b.sig),te.encode("dark|"+action+"|"+c+"|"+b.ts))}catch{return false}} const view=(B,c)=>{const s=B.orders.find(x=>x.c===c);if(s)return {c,state:"resting",exp:s.exp,ts:s.ts,fills:s.fills,rem:rem(s)}; const d=B.done.find(x=>x.c===c);return d?{c,state:d.state,exp:d.exp,ts:d.ts,fills:d.fills}:null}; const known=(B,c)=>B.orders.some(x=>x.c===c)||B.done.some(x=>x.c===c); return { /* Flux public. Sert aussi d'horloge : c'est ici que les blocs expirent et que les limites sont revérifiées. */ async state(){const px=await getMid(); return tx(ctx=>{const B=ctx.B,t=now();if(sweep(B,px,t))ctx.dirty=true; return {status:200,body:{ok:true,now:t,pair:"HYPE/USDC",mid:px||0,key:pubJwk,min:MIN_USD,bytes:CT_BYTES,test,count:B.orders.length,crossed:B.crossed, resting:[...B.orders].sort((a,b)=>b.ts-a.ts).slice(0,200).map(s=>({c:s.c,ts:s.ts,exp:s.exp})),tape:B.tape.slice(0,12)}}})}, /* Contrôle public : ce qui tourne, et ce qui ne tourne pas encore. Lit vraiment le carnet et le prix. */ async health(){const px=await getMid(); return tx(({B})=>({status:200,body:{ok:true,service:"dark-engine",now:now(),matching:"live",price:px?"live":"unavailable",mid:px||0,priceSource:"Hyperliquid allMids, HYPE", book:"readable",resting:B.orders.length,crossed:B.crossed,settlement:"not live",settlementNote:"No contract is deployed. Fills are matched, no funds move.",testCounterparty:test,sealedBytes:CT_BYTES,minimumUsd:MIN_USD}}))}, async seal(b){ if(!b||!isHex(b.c,32))return err(400,"bad_request","Malformed block."); const e=b.env;if(!e||!isHex(e.epk,65)||!isHex(e.iv,12)||!isHex(e.ct,CT_BYTES))return err(400,"bad_envelope","A sealed block is exactly "+CT_BYTES+" bytes."); if(!await auth(b,"seal",b.c))return err(401,"bad_signature","Signature rejected. Check the clock of this device."); if(hex(await sub.digest("SHA-256",unhex(e.ct)))!==b.c)return err(400,"bad_commit","The fingerprint does not match the sealed block."); const t0=now(),exp=b.exp||0; if(!Number.isInteger(exp)||exp<0||(exp&&(expt0+MAX_REST)))return err(400,"bad_expiry","A block rests between 30 seconds and 30 days, or until cancelled."); const px=await getMid();if(!px)return err(503,"no_price","The HyperCore mid is not available right now. Try again in a moment."); let o;try{o=clean(await open(e))}catch{o=null} if(!o)return err(400,"unreadable","The engine could not read this block."); if(o.size*px{const B=ctx.B,t=now(); if(known(B,b.c))return err(409,"duplicate","This block was already received."); if(B.orders.length>=MAX_BOOK)return err(503,"book_full","The book is full. Try again later."); if(B.orders.filter(x=>x.pub===b.pub).length>=PER_DESK)return err(429,"too_many","A desk can rest "+PER_DESK+" blocks at a time."); plain.set(b.c,o);B.orders.push({c:b.c,pub:b.pub,env:{epk:e.epk,iv:e.iv,ct:e.ct},exp,ts:t,fills:[]});sweep(B,px,t);ctx.dirty=true; return {status:200,body:{ok:true,order:view(B,b.c)}}})}, async cancel(b){ if(!b||!isHex(b.c,32)||!await auth(b,"cancel",b.c))return err(401,"bad_signature","Signature rejected."); return tx(ctx=>{const B=ctx.B,s=B.orders.find(x=>x.c===b.c); if(!s||s.pub!==b.pub)return err(404,"not_found","No resting block with this fingerprint on this desk."); finish(B,s,"cancelled",now());ctx.dirty=true;return {status:200,body:{ok:true,order:view(B,b.c)}}})}, async mine(b){ if(!await auth(b,"mine",""))return err(401,"bad_signature","Signature rejected."); return tx(({B})=>({status:200,body:{ok:true,orders:[...B.orders,...B.done].filter(x=>x.pub===b.pub).map(x=>view(B,x.c))}}))}, /* Contrepartie de test : la maison prend le reste du bloc au mid. Marquée « test » dans le ruban. */ async cross(b){ if(!test)return err(404,"not_found","Not available."); if(!b||!isHex(b.c,32)||!await auth(b,"cross",b.c))return err(401,"bad_signature","Signature rejected."); const px=await getMid();if(!px)return err(503,"no_price","The HyperCore mid is not available right now."); return tx(ctx=>{const B=ctx.B,s=B.orders.find(x=>x.c===b.c); if(!s||s.pub!==b.pub)return err(404,"not_found","No resting block with this fingerprint on this desk."); if(!within(s,px))return err(409,"limit","The mid is past your limit. The block keeps resting."); fill(B,s,null,rem(s),px,now());ctx.dirty=true;return {status:200,body:{ok:true,order:view(B,b.c)}}})} }; } /* Aiguillage commun aux deux hébergements : (méthode, chemin, corps) -> {status, body} */ export async function route(engine,method,path,body){ const fn={"GET /state":()=>engine.state(),"GET /health":()=>engine.health(),"POST /orders":()=>engine.seal(body),"POST /cancel":()=>engine.cancel(body),"POST /mine":()=>engine.mine(body),"POST /test/cross":()=>engine.cross(body)}[method+" "+path]; return fn?fn():err(404,"not_found","Unknown route.")} /* Mid HYPE lu sur Hyperliquid, gardé quelques secondes ; 0 s'il est indisponible ou trop vieux */ export function hyperMid({ttl=2500,stale=30000}={}){let mid=0,at=0,p=null; return async()=>{const t=Date.now(); if(t-at>ttl){p=p||(async()=>{try{const r=await fetch("https://api.hyperliquid.xyz/info",{method:"POST",headers:{"Content-Type":"application/json"},body:'{"type":"allMids"}',signal:AbortSignal.timeout(4000)}); const j=await r.json();if(+j.HYPE>0){mid=+j.HYPE;at=Date.now()}}catch{}p=null})();await p} return Date.now()-at