Merge remote-tracking branch 'upstream/main' into own-carrier-egress

# Conflicts:
#	CHANGELOG.md
#	src/game/80-simulation/30-compute.js
#	tests/game.test.js
This commit is contained in:
Christopher Hawker 2026-10-31 23:57:19 +11:00
commit 9dc8aac45a
40 changed files with 1043 additions and 1140 deletions

View file

@ -19,7 +19,7 @@ spill at 85%
# Maintenance window? Drain a POP's exits, or steer around a link
# drain paris
# avoid link frankfurt-amsterdam
# Under DDoS: drop the junk at the edge (takes some real traffic with it)
# Under DDoS: blackhole the target upstream (saves everyone else)
# blackhole ddos`;
function lev(a,b){const m=a.length,n=b.length,d=Array.from({length:m+1},(_,i)=>[i]);for(let j=1;j<=n;j++)d[0][j]=j;for(let i=1;i<=m;i++)for(let j=1;j<=n;j++)d[i][j]=Math.min(d[i-1][j]+1,d[i][j-1]+1,d[i-1][j-1]+(a[i-1]===b[j-1]?0:1));return d[m][n];}
function teFind(word,list,label){const w=slug(word);if(!w)return {err:tr('routescript.missing_what',{what:label})};
@ -60,7 +60,7 @@ const teUps=()=>[...new Set(S.transit.map(t=>t.net))].map(n=>({n,p:Math.min(...S
const teNm=n=>NET[n].name.toLowerCase(),teAtk=()=>ddosAll().length>0;
const teSad=()=>S.biz.some(b=>!BIZ_T[b.type].l2&&!BIZ_T[b.type].fiber&&!BIZ_T[b.type].event&&sfOf(R,b.city)<0.95);
const TE_RECIPES=[
{id:'shield',n:N_('common.shields_up'),d:N_('routescript.for_a_ddos_drop_the_junk'),fit:()=>teAtk()?9:0.3,
{id:'shield',n:N_('common.shields_up'),d:N_('routescript.for_a_ddos_rtbh_the_target'),fit:()=>teAtk()?9:0.3,
src:()=>[tr('routescript.shields_up_for_the_length_of'),'blackhole ddos','protect customers','spill at 80%']},
{id:'care',n:N_('common.customer_care'),d:N_('routescript.business_customers_first_when_links'),fit:()=>teSad()?5:0.5,
src:()=>[tr('routescript.customer_care_the_people_who_pay'),'protect customers','spill at 75%']},
@ -111,7 +111,7 @@ function teHelpModal(){const rule=(code,what)=>`<dt><code>${code}</code></dt><dd
${rule('protect customers',tr('routescript.when_links_are_congested_business'))}
${rule('drain paris',tr('routescript.move_traffic_off_a_pop_s'))}
${rule('avoid link frankfurt-amsterdam',tr('routescript.steer_traffic_around_one_link_unless'))}
${rule('blackhole ddos',tr('routescript.during_an_attack_drop_the_flood'))}
${rule('blackhole ddos',tr('routescript.during_an_attack_rtbh_the_target'))}
</dl><h3>${tr('routescript.ready_made_scripts')}</h3><p class="meta">${tr('routescript.filled_in_from_your_network_as')}</p>
${TE_RECIPES.map(r=>`<div class="terec"><div><b>${tr(r.n)}</b><div class="meta">${tr(r.d)}</div></div>${btn(tr('common.load'),'teRecipe',{id:r.id},'sm')}</div>`).join('')}</div>
<div class="btns" style="margin-top:12px">${btn(tr('routescript.back_to_the_editor'),'teBack',{},'big')}</div>`);}

View file

@ -0,0 +1,81 @@
/* ---------- where a flood goes (compute() calls these) ----------
A flood comes from botnets everywhere, so it reaches you over every network that reaches you, on the exits that
network would use: private peering first, then the exchanges, then transit, spread by port size. Each tool then
acts where it does in a real network: RTBH and clean pipes upstream, before your port; the port carries what fits
and everyone on it loses the same share; Flowspec drops matching junk on each ingress router, within that router's
rule budget; what is left rides the backbone to the target. An engaged scrubbing center takes the flood on its own
ingress instead (magnet) and cleans up to its tier (sponge); what it cannot take hurts only the target. */
// Does this private peer honour blackhole communities? About half do, the same ones in every game.
function pniHonours(n){let h=0;for(let i=0;i<n.length;i++)h=(h*31+n.charCodeAt(i))|0;return (h&2)===0;}
const ddRank=e=>e.k==='p'?1:e.k==='ix'?2:e.k==='t'?3:9;
// Adds to `out` (exit -> Gbps) the share of g that reaches you on each exit, before upstream tools.
function ddosSpread(g,E,okBy,out){if(g<=0)return;let tot=0;const pick=[];
for(const n of NETS){const s=NSH[n.id]||0,L=okBy[n.id];if(s<=0||!L||!L.length)continue;let best=9,sac=false;
for(const e of L){if(e.id==='~grace')continue;const r=ddRank(e);if(r<best)best=r;}
if(best===9)continue;if(best===1)for(const e of L)if(e.k==='p'&&e.sac)sac=true;
let cap=0;for(const e of L)if(ddRank(e)===best&&e.id!=='~grace'&&(!sac||e.sac))cap+=e.cap;
if(cap<=0)continue;tot+=s;pick.push(s,L,best,sac,cap);}
if(tot<=0)return;
for(let k=0;k<pick.length;k+=5){const s=pick[k],L=pick[k+1],best=pick[k+2],sac=pick[k+3],cap=pick[k+4],w=g*s/tot;
for(const e of L)if(ddRank(e)===best&&e.id!=='~grace'&&(!sac||e.sac))out.set(e,(out.get(e)||0)+w*e.cap/cap);}}
// How much of a scrubbing center is engaged for this attack: 0, half on the first day of on-demand diversion, or all.
function scrubEng(a){if(!hasScrub()||a.bh)return 0;if(S.scrubMode!=='ondemand')return 1;
const from=S.ddosAuto&&S.ddosAuto.scrub===false?a.eng:(a.eng??a.start);if(from===undefined||from===null)return 0;return S.day<=from?0.5:1;}
// One POP's Flowspec rule budget: its routers' TCAM.
const fsCap=c=>{const p=S.pops[c];return p?(RG[p.rgen||0].fsN||0):0;};
// The bandwidth the target itself uses: a customer's port, or a city's broadband subscribers.
function ddosTb(a,R2){if(a.tgt&&a.tgt.startsWith('bb:'))return Math.max(1,(R2.cityEye||{})[a.city]||1);const b=S.biz.find(x=>x.id===a.tgt);return b?Math.max(0.1,b.bw):1;}
/* Before routing: spread each live attack, clip it at the ports, filter it on the routers and load what is left onto
the backbone ahead of everyone's traffic. X.haul(A,B,g,ek) moves up to g from city A to city B and returns what fit. */
function ddosLoad(X){const {E,okBy,R2}=X;R2.ddos=[];R2.haul=[];R2.tgtF={};R2.bbF={};R2.fsUse={};R2.ddosHot={};
const live=ddosAll().slice().sort((a,b)=>(a.start||0)-(b.start||0)||(a.id<b.id?-1:a.id>b.id?1:0));if(!live.length)return null;
const recs=[],room={};
for(const a of live){const c=a.city,m={attack:a,tgt:a.tgt,g:a.gbps,bh:!!(a.bh||X.autoBh),ports:new Map(),up:0,fs:0,fsAt:[],fsFull:[],fsNone:[],deliv:0,pulled:0,cleaned:0,over:0,parts:[],tf:1,col:0,slowed:0,eng:0};
recs.push(m);R2.ddos.push(m);if(!popUp(c)||!S.pops[c]){m.offline=true;continue;}
m.eng=m.bh?0:scrubEng(a);const pull=a.gbps*m.eng,sp=new Map();ddosSpread(a.gbps-pull,E,okBy,sp);
for(const [e,g] of sp){let left=g;
if(m.bh)left*=e.k==='p'?(pniHonours(e.net)?0:1):RTBH_LEFT[e.k]??1;else if(e.clean)left*=0.1;
m.up+=g-left;if(left>1e-9){m.ports.set(e,{off:left,in:0});e.J+=left;}}
if(pull>0){const xs=S.scrubs.filter(x=>popUp(x.city));let tot=0;for(const x of xs)tot+=SCRUB_TIERS[x.tier||0].g;
for(const x of xs){const cap=SCRUB_TIERS[x.tier||0].g,share=pull*cap/tot,can=Math.max(0,room[x.city]??cap),cl=Math.min(share,can);room[x.city]=can-cl;
m.parts.push({city:x.city,tier:x.tier||0,a:share,cleaned:cl});m.cleaned+=cl;m.over+=share-cl;}
m.pulled=pull;}}
// The ports: each carries what fits, shared out by what each attack offers it.
for(const m of recs)for(const [e,p] of m.ports)p.in=p.off*Math.min(1,e.cap/e.J);
// Flowspec, oldest attack first, within each router's rule budget; what is left heads for the target.
const fsLeft={};
for(const m of recs){if(m.offline)continue;const a=m.attack,V=DDOS_VEC[a.vec],need=V&&V.fs?(a.carpet?FS_CARPET:1):0,byCity=new Map();
for(const [e,p] of m.ports)byCity.set(e.city,(byCity.get(e.city)||0)+p.in);
for(const [city,g] of byCity){let rest=g;
if(need&&S.pops[city]){const cap=fsCap(city),left=fsLeft[city]??cap;
if(!cap)m.fsNone.push(city);else if(left>=need){fsLeft[city]=left-need;rest=g*(1-FS_DROP);m.fs+=g-rest;m.fsAt.push(city);}else{fsLeft[city]=left;m.fsFull.push(city);}}
m.deliv+=X.haul(city,a.city,rest,'ddos:'+city,city);}
// Clean traffic comes back from each center to the target, the long way round if the center is far.
const tb=ddosTb(a,R2);
for(const x of m.parts){const v=tb*x.a/Math.max(m.pulled,1e-9),h=x.city===a.city?v:X.haul(x.city,a.city,v,'scrub:'+a.city+'>'+x.city,null,true);
R2.haul.push({city:a.city,to:x.city,tier:x.tier,a:x.a,h:v>0?h/v:1,ms:x.city===a.city?0:X.ms(a.city,x.city)*2,attack:a.id});}
// The target: blackholed, or what its own port and the scrubbing centers let through.
const fa=Math.min(1,2*tb/(m.deliv+tb)),fsc=m.pulled>0?m.cleaned/m.pulled:1;
m.tf=m.bh?0:fa*((1-m.eng)+m.eng*fsc);
if(a.tgt&&a.tgt.startsWith('bb:'))R2.bbF[a.city]=Math.min(R2.bbF[a.city]??1,m.tf);else if(a.tgt)R2.tgtF[a.tgt]=Math.min(R2.tgtF[a.tgt]??1,m.tf);}
for(const c in S.pops){const cap=fsCap(c);if(fsLeft[c]!==undefined)R2.fsUse[c]={used:cap-fsLeft[c],cap};}
if(X.autoBh)R2.teBlack=recs.reduce((n,m)=>n+m.up,0);
return recs;}
/* After routing: a port offered more than it carries drops the same share of everyone's traffic on it. Then what the
attacks cost everyone else (collateral) and the target. X.lost(ci,g,bz,e) takes served traffic away again. */
function ddosAfter(recs,X){const {E,R2}=X;if(!recs)return;const lostC={};let lost=0;
for(const e of E){if(!(e.J>0))continue;const L=e.used,fac=Math.min(1,e.cap/(e.J+L));
if(fac<1&&e.byC)for(const [ci,v] of e.byC){const x=v[0]*(1-fac),y=v[1]*(1-fac);X.lost(ci,x,y,e);lostC[ci]=(lostC[ci]||0)+x;lost+=x;}
if(fac<0.97){R2.ddosHot[e.city]=1;}
e.fac=fac;e.used=Math.min(e.cap,L+e.J);}
const tot=recs.reduce((n,m)=>n+(m.offline?0:m.attack.gbps),0)||1;
for(const m of recs){if(m.offline)continue;const a=m.attack,ci=CIDX[a.city],tb=ddosTb(a,R2),dem=R2.cityDem[a.city]||0;
// The target's own traffic lost at the ports is not collateral.
const own=dem>1e-6?(lostC[ci]||0)*Math.min(1,tb/dem):0;
m.col=Math.max(0,(lost-own+X.squeeze)*a.gbps/tot);
m.portList=[...m.ports].map(([e,p])=>({lab:e.lab,city:e.city,k:e.k,off:p.off,cap:e.cap,fac:e.fac??1})).sort((x,y)=>x.fac-y.fac||y.off-x.off);
m.full=m.portList.filter(p=>p.fac<0.97).length;
// Customers who felt it: in a city that lost more than 1% to full ports, other than the target.
let n=0;for(const c in S.pops){const i=CIDX[c],d=R2.cityDem[c]||0;if(d<=1e-6||(lostC[i]||0)/d<0.01)continue;
for(const b of S.biz)if(b.city===c&&b.id!==a.tgt&&!BIZ_T[b.type].l2&&!BIZ_T[b.type].fiber)n++;if(R2.cityEye[c]>0&&a.tgt!=='bb:'+c)n++;}
m.slowed=n;}}

View file

@ -25,14 +25,14 @@ function compute(){
for(const t of S.transit){if(!popUp(t.city)||t.down>day||!liveN(t.city,t.site,t.n))continue;
// AS-path prepending (#96) moves part of the port to a last-resort exit of its own.
const cap=Math.min(liveCap(PORT[t.tier].g,t.city,t.site,t.n)*lagF(t),TRX&&TRX.cap[t.net]!==undefined?TRX.cap[t.net]:Infinity),pf=TRX&&TRX.prep[t.net]?PREPEND_F[TRX.prep[t.net]]:0;
const ex={k:'t',net:t.net,prem:premOn(t),pref:t.pref||'normal',carry:!!t.carry,lab:labOf(N_('common.net_transit'),'net',NET[t.net].name),id:t.id,city:t.city,cap:cap*(1-pf),used:0,rank:3,ok:n=>!(depeer&&t.net==='cog'&&n==='ggl')&&n!==leak&&!(snd&&NET[n].kr)};
const ex={k:'t',net:t.net,clean:!!t.clean,prem:premOn(t),pref:t.pref||'normal',carry:!!t.carry,lab:labOf(N_('common.net_transit'),'net',NET[t.net].name),id:t.id,city:t.city,cap:cap*(1-pf),used:0,rank:3,ok:n=>!(depeer&&t.net==='cog'&&n==='ggl')&&n!==leak&&!(snd&&NET[n].kr)};
E.push(ex);if(pf)E.push({...ex,cap:cap*pf,prep:true});}
// `nets`: every network ok() can say yes to, so it need not be asked about the other hundred.
for(const c in S.ixp){const ct=ixCity(c);if(!(popUp(ct)||remote.includes(ct))||(S.ev.ixdown&&S.ev.ixdown[c]>day)||!(S.myIx[c]?myIxLive(c):liveN(ct,(S.ixSite||{})[c],(S.ixn||{})[c])))continue;const set=ixSessions(c);R2.sessions+=set.size;
// A peer announces its customers too (#85): the session reaches its cone, after the networks peering directly.
let all=set;for(const id of set)if(DOWN[id].length){if(all===set)all=new Set(set);for(const x of DOWN[id])all.add(x);}
E.push({k:'ix',pref:(S.ixPref&&S.ixPref[c])||'normal',lab:labOf(N_('common.ix_peering'),'ix',ixName(c)),id:c,city:ct,cap:ixCap(c),used:0,rank:2,ok:n=>all.has(n),nets:all,dir:all===set?null:set});}
for(const p of S.pni){if(!pniOn(p)||!popUp(p.city)||!liveN(p.city,p.site,p.n))continue;R2.sessions++;E.push({k:'p',pnc:!!NET[p.net].cn,pref:p.pref||'normal',lab:labOf(N_('common.pni_with_net'),'net',NET[p.net].name),id:p.id,city:p.city,cap:liveCap(pniG(p),p.city,p.site,p.n)*lagF(p)*(p.sacrif?0.5:1),used:0,rank:1,net:p.net,ok:n=>CONE_S[p.net].has(n),nets:CONE[p.net]});}
for(const p of S.pni){if(!pniOn(p)||!popUp(p.city)||!liveN(p.city,p.site,p.n))continue;R2.sessions++;E.push({k:'p',sac:!!p.sacrif,pnc:!!NET[p.net].cn,pref:p.pref||'normal',lab:labOf(N_('common.pni_with_net'),'net',NET[p.net].name),id:p.id,city:p.city,cap:liveCap(pniG(p),p.city,p.site,p.n)*lagF(p)*(p.sacrif?0.5:1),used:0,rank:1,net:p.net,ok:n=>CONE_S[p.net].has(n),nets:CONE[p.net]});}
for(const c of S.caches){if(!popUp(c.city)||siteDown(c.city,c.site==='b'?'b':'a'))continue;E.push({k:'c',pref:'normal',lab:labOf(N_('common.name_cache'),'name',NET[c.net].cache.name),id:c.id,city:c.city,cap:CACHE_CAP,used:0,rank:0,ok:n=>n===c.net,nets:[c.net]});}
// After an update adds networks, a free courtesy route reaches the new ones you have no other way to (#46).
R2.graceNets=0;if(S.grace&&S.grace.until>day){const gs=new Set(S.grace.nets.filter(n=>NET[n]&&!E.some(e=>e.k!=='c'&&e.ok(n)))),hc=popUp(S.home)?S.home:pops.find(popUp);
@ -45,7 +45,7 @@ function compute(){
const okBy={};for(const id of NET_IDS)okBy[id]=[];
const ekN={};for(const e of E){e.ek=e.k+':'+e.id;ekN[e.ek]=(ekN[e.ek]||0)+1;}
// dup: shares its key with another exit (a hand-edited save), so R.egDesc shows whichever pushed last.
for(const e of E){e.desc={lab:e.lab,city:e.city,k:e.k};e.dup=ekN[e.ek]>1;e.told=false;e.hp=e.pref==='high'?0:1;e.ci=CIDX[e.city];e.cn=cnCity(e.city);e.vis=0;for(const n of e.nets||NET_IDS){const L=okBy[n];if(L&&L[L.length-1]!==e&&e.ok(n))L.push(e);}}
for(const e of E){e.J=0;e.byC=null;e.desc={lab:e.lab,city:e.city,k:e.k};e.dup=ekN[e.ek]>1;e.told=false;e.hp=e.pref==='high'?0:1;e.ci=CIDX[e.city];e.cn=cnCity(e.city);e.vis=0;for(const n of e.nets||NET_IDS){const L=okBy[n];if(L&&L[L.length-1]!==e&&e.ok(n))L.push(e);}}
for(const n of NETS){R2.reachable[n.id]=okBy[n.id].some(e=>e.rank>0);if(R2.reachable[n.id])R2.reach+=NSH[n.id];if(okBy[n.id].some(e=>e.rank>0&&e.k!=='t')){R2.nt[n.id]=1;R2.reachNT+=NSH[n.id];
// Reached without transit only through the customers of networks you peer with (#85). R.cone[id]: the peer that
// carries it, the first PNI's network or else the nearest upstream that is a member of an exchange you are on.
@ -57,8 +57,7 @@ function compute(){
// Customer demand per city, added up in S.biz order (what filtering S.biz for each city would give).
const bizBw={};for(const b of S.biz){const T=BIZ_T[b.type];if(!T.l2&&!T.fiber&&(!T.event||eventLive(b))){const v=bizBw[b.city];bizBw[b.city]=(v===undefined?0:v)+b.bw;}}
// Traffic shares by network index, and their sums, for each share table (and with Russia's throttle).
const shArr=new Map(),shSum=new Map(),DEMTO=new Float64Array(NN),loc=scnRule('local'),scrubRoom={},junkGroups=[],bhCities=new Set(ddosAll().filter(a=>a.bh).map(a=>a.city));R2.haul=[];R2.ddos=[];
const VIC={};for(const a of ddosAll())(VIC[a.city]||(VIC[a.city]=[])).push(a);
const shArr=new Map(),shSum=new Map(),DEMTO=new Float64Array(NN),loc=scnRule('local');
for(const c of Object.keys(S.pops)){
const p=S.pops[c],ci=CIDX[c],cn=cnCity(c),SH=cn?NSH_CN:ruCity(c)?NSH_RU:CITY[c].kr&&S.krExit?NSH_KRX:NSH;const eye=(p.bb?p.bb.d:0)*viral*(cn&&ev.golden>day?1.4:1);const biz=bizBw[c]??0;const d0=eye+biz;
// Goggle video is throttled in Russia (#70): people there get half of it, so they ask for half. It is not
@ -67,20 +66,10 @@ function compute(){
const tt=sm[+ru]||(sm[+ru]=[NETS.reduce((t,n,j)=>t+sa[j]*thr(n.id),0),NETS.reduce((t,n,j)=>t+sa[j],0)]),lf=loc?NETS.reduce((t,n,j)=>t+(R2.reachable[n.id]?sa[j]*thr(n.id):0),0)/(tt[0]||1):1,d=d0*tt[0]/(tt[1]||1)*lf;
R2.cityEye[c]=eye;R2.cityDem[c]=d;R2.citySrv[c]=0;R2.demand+=d;
for(let j=0;j<NN;j++)DEMTO[j]=(DEMTO[j]||0)+d0*sa[j]*thr(NETS[j].id);
// A shaped attack: `rtbh` is the player pulling the plug on the victim IP (junk gone, customer dark too);
// `edge` is the crude RouteScript `blackhole ddos` filter (junk gone, 10% of real traffic with it). Flowspec
// (a standing licence) and a scrubbing center each knock the flood down before it reaches the sim.
const attacks=VIC[c]||[],rtbh=bhCities.has(c),edge=!!(attacks.length&&TRX&&TRX.blackhole&&!rtbh);
// The junk heads for the victim over its usual exits, spread like its traffic. How much is left after the edge
// tools and scrubbing is only known once hauls to remote centers are routed, so the flows are sized after that.
for(const atk of attacks){const m=ddosMitigation(atk,{},rtbh,false),group={m,flows:[]};R2.ddos.push(m);junkGroups.push(group);if(!popUp(c)){m.offline=true;continue;}
for(let j=0;j<NN;j++)group.flows.push({f:flow(c,ci,cn,j,0,false,true),share:NSH[NETS[j].id]});}
if(!popUp(c))continue;
const bh=rtbh||edge;
if(edge)R2.teBlack+=attacks.reduce((n,a)=>n+a.gbps,0)+d*0.1;if(rtbh)R2.teBlack+=attacks.reduce((n,a)=>n+a.gbps,0)+d;
R2.cityBlocked=R2.cityBlocked||{};
const mtuH=ev.pmtud&&ev.pmtud.until>day?ev.pmtud:null,kr=CITY[c].kr;
for(let j=0;j<NN;j++){const n=NETS[j],a=(loc&&!R2.reachable[n.id]?0:d0)*sa[j]*thr(n.id)*(rtbh?0:edge?0.9:1)*(mtuH&&mtuH.net===n.id?mtuH.f:1)*(kr&&ev.krroute>day&&n.id==='fbk'?0.8:1);if(a<=0)continue;
for(let j=0;j<NN;j++){const n=NETS[j],a=(loc&&!R2.reachable[n.id]?0:d0)*sa[j]*thr(n.id)*(mtuH&&mtuH.net===n.id?mtuH.f:1)*(kr&&ev.krroute>day&&n.id==='fbk'?0.8:1);if(a<=0)continue;
// With `protect customers`, the business part first, then the rest (no arrays: this runs per city and network).
const bf=d0>0?biz/d0:0,sp=!!(TRX&&TRX.protect&&bf>0),cn2=cacheNets.has(n.id);
for(let q=0;q<(sp?2:1);q++){const x=sp?(q?a*(1-bf):a*bf):a,bz=sp&&!q;if(x<=0)continue;if(cn2){flow(c,ci,cn,j,x*0.85,true,false,bz);flow(c,ci,cn,j,x*0.15,false,false,bz);}
@ -142,23 +131,14 @@ function compute(){
R2.l2lat[b.id]=noPath?Infinity:maxLat;R2.l2[b.id]=b.bw*minF;R2.egT.l2=(R2.egT.l2||0)+tot;
// Same answer as diversePaths(), which would rebuild today's live links for every customer.
if((b.reqs||[]).includes('diverse')){const k=b.city+'>'+b.city2;R2.div[b.id]=divMemo[k]??(divMemo[k]=disjointI(b.city,b.city2));}}
/* A flood for a scrubbing center elsewhere rides the backbone there, with the victim's own traffic (#117).
What the links cannot carry is not scrubbed and lands on the city after all. */
const scrubNear=new Map();
for(const m of R2.ddos){const atk=m.attack,A=atk.city,Ai=CIDX[A];
m.sp=!m.offline&&m.leak>0?scrubPlan(atk,m.leak,scrubRoom,(x,want)=>{const B=x.city,Bi=CIDX[B];if(A===B)return want;let h=0,ms=null;
if(popUp(A)&&popUp(B)&&SPD[A]&&SPD[A][Bi]<Infinity){const {path,ni}=walkI(SPP[A],Ai,Bi);let room=Infinity;for(const l of path)room=Math.min(room,l.res);for(const i of ni)if(HAS[i])room=Math.min(room,NRES[i]);
const v=R2.cityDem[A]*0.1*want/Math.max(m.leak,1)/VIC[A].length,total=want+v,take=Math.max(0,Math.min(total,room));h=total>0?want*take/total:0;ms=path.reduce((n,e)=>n+e.lat,0)*2;
// Sources sharing a center need separate labels in link breakdowns and map highlights.
const ek='scrub:'+A+'>'+B;R2.egDesc[ek]={lab:labOf(N_('compute.attack_hauled_to_scrubbing_in_city'),'city',CITY[B].name),city:A,k:'l2'};
for(const i of ni)if(HAS[i])nodeTake(i,take);for(const l of path){l.res-=take;l.ld+=take;carry(l,ek,NN,Ai,take);}}
R2.haul.push({city:A,to:B,tier:x.tier||0,a:want,h,ms,attack:atk.id});return h;}):null;
if(m.sp){m.leak=m.sp.leak;
// The card describes the victim's nearest center.
const c=atk.city;let near=scrubNear.get(c);if(near===undefined){near=null;
for(const x of S.scrubs)if(popUp(x.city)&&SPD[c]&&SPD[c][CIDX[x.city]]<Infinity){const ms=c===x.city?0:walkI(SPP[c],CIDX[c],CIDX[x.city]).path.reduce((n,e)=>n+e.lat,0);if(!near||ms<near.ms)near={city:x.city,ms};}
scrubNear.set(c,near);}m.near=near;}}
for(const group of junkGroups)for(const q of group.flows)q.f.rem=group.m.offline?0:group.m.leak*q.share;
/* Floods ride the backbone ahead of everyone's traffic (25-ddos-flood.js). haul: up to g from city A to POP B over the
shortest path, as far as links and routers have room. */
const msOf=(A,B)=>{const Bi=CIDX[B],Ai=CIDX[A];return SPD[B]&&SPD[B][Ai]<Infinity?walkI(SPP[B],Bi,Ai).path.reduce((n,e)=>n+e.lat,0):0;};
let JK=0;const haul=(A,B,g,ek,from,clean)=>{if(!(g>0))return 0;const Ai=CIDX[A],Bi=CIDX[B];if(!SPD[B]||!(SPD[B][Ai]<Infinity))return 0;
const {path,ni}=walkI(SPP[B],Bi,Ai);let amt=g;for(const l of path)amt=Math.min(amt,l.res);for(const i of ni)if(HAS[i])amt=Math.min(amt,NRES[i]);amt=Math.max(0,amt);if(amt<=1e-9)return 0;
if(!R2.egDesc[ek])R2.egDesc[ek]={lab:clean?labOf(N_('compute.scrubbed_traffic_from_city'),'city',CITY[A].name):labOf(N_('compute.attack_entering_in_city'),'city',CITY[from].name),city:B,k:'l2'};
for(const i of ni)if(HAS[i])nodeTake(i,amt);for(const l of path){l.res-=amt;l.ld+=amt;if(!clean){l.jk=(l.jk||0)+amt;JK=1;}carry(l,ek,NN,Bi,amt);}return amt;};
const DD=ddosLoad({E,okBy,R2,autoBh:!!(TRX&&TRX.blackhole),haul,ms:msOf});
const TE=!!(S.te&&S.te.on)&&coreTE(),TR=TE?teRules():null,REACH=coreTeReach();R2.teMoved=0;const teCache=new Map(),SPILL=TR&&TR.spill?TR.spill:1;
const altPath=(src,dst,base)=>{const key=src*NC+dst,c0=teCache.get(key);
if(c0===false)return null;if(c0&&c0.path.every(l=>l.res>1e-3)&&c0.ni.every(i=>!HAS[i]||NRES[i]>1e-3))return c0;
@ -213,6 +193,7 @@ function compute(){
if(path.length&&(e.k==='t'||snd&&CITIES[f.ci].kr)){let ms=P.ms;if(ms===undefined){ms=0;for(const l of path)ms+=l.lat;P.ms=ms;}const rtt=2*ms,kl=snd&&CITIES[f.ci].kr;
if(rtt>(kl?KR_LAT_OK:LAT_OK)){LATP[f.ci]+=ok*(kl?krLatLoss(rtt):latLoss(rtt));if(!P.fg){P.fg=0;FARL.push(P,f.ci,e.ci);}P.fg+=ok;}}R2.egT[e.k]=(R2.egT[e.k]||0)+ok;const ne=NEG[f.nj]||(NEG[f.nj]=R2.netEg[f.n]={c:0,p:0,ix:0,t:0});ne[e.k]+=ok;
// Where each flow left (the PNI list asks what a PNI here would take over, #175).
if(e.J>0){const m=e.byC||(e.byC=new Map()),v=m.get(f.ci);if(v){v[0]+=ok;if(f.bz)v[1]+=ok;}else m.set(f.ci,[ok,f.bz?ok:0]);}
if(e.k==='t'){f.gt+=ok;f.ti=e.id;}else if(e.k==='ix'){f.gi+=ok;f.ii=e.id;}else if(e.k==='p'){if(e.net===f.n&&e.city===f.c)f.gh+=ok;else f.gp+=ok;}}
return amt;
};
@ -277,6 +258,9 @@ function compute(){
}
}
for(const i of NORD)R2.nodeLoad[CITIES[i].id]=NLOAD[i];
if(DD){let rem=0,jf=0;for(const f of flows)if(f.rem>1e-6)rem+=f.rem;if(JK)for(const k in edges){const e=edges[k];if(e.res<=1e-6&&e.jk)jf+=e.jk;}
ddosAfter(DD,{E,R2,squeeze:Math.min(rem,jf),
lost:(ci,x,y,e)=>{SRV[ci]-=x;R2.served-=x;const c=CITIES[ci].id;if(y)R2.bizSrv[c]-=y;R2.egT[e.k]-=x;if(e.rank<=2)R2.peered-=x;}});}
for(const c of Object.keys(S.pops)){const i=CIDX[c];R2.citySrv[c]=SRV[i];
if(LATP[i]>0&&SRV[i]>0)R2.latF[c]=clamp(1-LATP[i]/SRV[i],0,1);}
// Each city's slowest big exit: (path, source, exit) triples, one per path that went far, in the order they first did.
@ -305,8 +289,8 @@ function compute(){
C.loans=(S.loans||[]).reduce((a,l)=>a+(BANKS[l.bank].equity?0:l.model==='transit'?Math.round((C.transit||0)*(l.cut||0.3)):l.pay)+loanFees(l),0);
C.extras=(S.cnLic&&S.cnLic.state==='ok'?CN_JV_MO:0)+scrubMo()+Object.keys(S.pops).filter(ruCity).length*RU_BOX_MO+Object.values(S.pops).filter(p=>p.site2).length*SITE2_MO+(S.te?TE_MO:0)+(S.ops&&S.ops.intern?INTERN_MO:0);
V.eyeballs=0;V.business=0;V.ix=0;V.grant=grantOn(R2)?GRANT_MO:0;
C.wholesale=0;C.levy=0;const lev=scnRule('levy');for(const c in S.pops){const sf=sfOf(R2,c),v=R2.cityEye[c]*sf*EYE_RATE*arpuOf(c);V.eyeballs+=v;if(CITY[c].au){if(lev)C.levy+=v*AU_LEVY;else C.wholesale+=v*AU_WHOLESALE;}}
const ids=linkIds();for(const b of S.biz){if(capPend(b))continue;const sf=BIZ_T[b.type].fiber?(fiberOk(b,ids)?1:0):BIZ_T[b.type].l2?clamp((R2.l2[b.id]||0)/b.bw,0,1):sfOf(R2,b.city);V.business+=b.bw*b.rate*Math.min(1,sf/0.95);}
C.wholesale=0;C.levy=0;const lev=scnRule('levy');for(const c in S.pops){const sf=sfOf(R2,c)*(R2.bbF[c]??1),v=R2.cityEye[c]*sf*EYE_RATE*arpuOf(c);V.eyeballs+=v;if(CITY[c].au){if(lev)C.levy+=v*AU_LEVY;else C.wholesale+=v*AU_WHOLESALE;}}
const ids=linkIds();for(const b of S.biz){if(capPend(b))continue;const sf=BIZ_T[b.type].fiber?(fiberOk(b,ids)?1:0):BIZ_T[b.type].l2?clamp((R2.l2[b.id]||0)/b.bw,0,1):sfOf(R2,b.city)*(R2.tgtF[b.id]??1);V.business+=b.bw*b.rate*Math.min(1,sf/0.95);}
for(const c in S.myIx)V.ix+=S.myIx[c].members.length*MYIX_FEE;
C.revshare=(S.loans||[]).reduce((a,l)=>a+(BANKS[l.bank].equity||l.bal>0?l.share||0:0),0)*(V.eyeballs+V.business+V.ix);
R2.costMo=Object.values(C).reduce((a,b)=>a+b,0);

View file

@ -11,7 +11,7 @@ function sanitize(s){
['pops','ixp','rs','peers','myIx','done','ev','stats','ixn','ixPref','ixSite','confReg','ach','pairMet'].forEach(obj);
s.v=1;s.name=String(s.name==null?'Packet Pals':s.name).slice(0,24);s.day=int(s.day,0,1e7,0);s.cash=num(s.cash,0);s.asn=int(s.asn,1,4294967294,200000);
s.priceMul=num(s.priceMul,1);s.nextFail=num(s.nextFail,s.day+45);s.nextEvent=num(s.nextEvent,s.day+40);s.lvl=int(s.lvl,1,LEVELS.length,1);s.neg=int(s.neg,0,1e7,0);s.loanStrikes=int(s.loanStrikes,0,1e3,0);
for(const k of Object.keys(s.stats)){const v=s.stats[k];if(k==='by'||k==='f'){if(!v||typeof v!=='object')s.stats[k]={};else for(const j of Object.keys(v))v[j]=num(v[j],0);}else if(typeof v!=='boolean')s.stats[k]=num(v,0);}
for(const k of Object.keys(s.stats)){const v=s.stats[k];if(k==='by'||k==='f'||k==='ddT'){if(!v||typeof v!=='object')s.stats[k]={};else for(const j of Object.keys(v))v[j]=num(v[j],0);}else if(typeof v!=='boolean')s.stats[k]=num(v,0);}
for(const k of ['survived','incidents','peak'])s.stats[k]=num(s.stats[k],0);
// The chaos monkey (2.0): saves without one get their first visit scheduled on the next day tick.
{const m=s.monkey&&typeof s.monkey==='object'&&!Array.isArray(s.monkey)?s.monkey:{},on=m.on?1:0,o={next:m.next==null?null:int(m.next,0,1e7,s.day+90),on};
@ -67,13 +67,19 @@ function sanitize(s){
if(!Array.isArray(s.scrubs))s.scrubs=s.scrubAt&&isCity(s.scrubAt)?[{city:s.scrubAt,tier:s.scrubTier}]:[];delete s.scrubAt;delete s.scrubTier;
{const seen=new Set();s.scrubs=s.scrubs.filter(x=>x&&typeof x==='object'&&isCity(x.city)&&s.pops[x.city]&&!seen.has(x.city)&&seen.add(x.city)).map(x=>({city:x.city,tier:int(x.tier,0,SCRUB_TIERS.length-1,0)}));}
s.scrubMode=s.scrubMode==='ondemand'?'ondemand':'always';
{const A=s.ddosAuto&&typeof s.ddosAuto==='object'?s.ddosAuto:{};s.ddosAuto={rtbh:A.rtbh===true,scrub:A.scrub!==false};}
if(s.stats&&s.stats.ddT&&typeof s.stats.ddT==='object')s.stats.ddT={port:s.stats.ddT.port?1:0,fs:s.stats.ddT.fs?1:0,rtbh:s.stats.ddT.rtbh?1:0};else if(s.stats)delete s.stats.ddT;
// Keep the legacy primary attack so old saves and imports remain compatible; additional floods overlap it.
const repairAttack=a=>{if(!a||typeof a!=='object'||!isCity(a.city)||!s.pops[a.city]||!own(DDOS_VEC,a.vec))return null;
a.id=sid(a.id);a.gbps=Math.max(0,num(a.gbps,2));a.until=num(a.until,s.day);a.bh=!!a.bh;a.ixbh=!!a.ixbh;a.start=Math.max(0,Math.min(s.day,num(a.start,s.day)));a.until=Math.min(a.until,a.start+Math.ceil(7*SPICY_LONG));
delete a.entries; // 2.0 betas spread attacks over every ingress port; they arrive on one again
a.id=sid(a.id);a.gbps=Math.max(0,num(a.gbps,2));a.until=num(a.until,s.day);a.bh=!!a.bh;a.start=Math.max(0,Math.min(s.day,num(a.start,s.day)));a.until=Math.min(a.until,a.start+Math.ceil(7*SPICY_LONG));
// Attacks before 2.2 hit a city and came in on one port: they now hit someone in it, and spread (#242).
delete a.entries;delete a.entry;delete a.ixbh;delete a.fresh;
if(typeof a.tgt!=='string'||(a.tgt.startsWith('bb:')?a.tgt!=='bb:'+a.city:!s.biz.some(b=>b.id===a.tgt&&b.city===a.city))){
const bs=s.biz.filter(b=>b.city===a.city&&BIZ_T[b.type]&&!BIZ_T[b.type].l2&&!BIZ_T[b.type].fiber).sort((x,y)=>(DD_W[y.type]||1)-(DD_W[x.type]||1)||y.bw-x.bw);a.tgt=bs.length?bs[0].id:'bb:'+a.city;}
a.carpet=!!a.carpet;a.sac=a.sac?1:0;a.colMax=clamp(num(a.colMax,0),0,1);if(a.worst!==undefined)a.worst=clamp(num(a.worst,1),0,1);
if(a.eng!==undefined){a.eng=num(a.eng,a.start);a.eng=Math.max(a.start,Math.min(s.day,a.eng));}
if(a.who!==undefined&&!FLOOD_WHO.includes(a.who))delete a.who; // a label from the list, never text from the file
a.sla=Array.isArray(a.sla)?a.sla.filter(x=>typeof x==='string').slice(0,s.biz.length):[];
if(!a.entry||typeof a.entry!=='object'||!['t','ix','p','edge'].includes(a.entry.k))a.entry={k:'edge',lab:''};else{a.entry.lab=String(a.entry.lab||'').slice(0,60);a.entry.id=a.entry.id==null?undefined:String(a.entry.id).slice(0,40);}return a;};
a.sla=Array.isArray(a.sla)?a.sla.filter(x=>typeof x==='string').slice(0,s.biz.length):[];return a;};
const attacks=[s.ev.ddos,...(Array.isArray(s.ev.ddosMore)?s.ev.ddosMore:[])].map(repairAttack).filter(Boolean).slice(0,14);
if(attacks.length)s.ev.ddos=attacks[0];else delete s.ev.ddos;s.ev.ddosMore=attacks.slice(1);
s.ddosStarts=(Array.isArray(s.ddosStarts)?s.ddosStarts:attacks.map(a=>a.start)).filter(d=>typeof d==='number'||typeof d==='string').map(Number).filter(d=>Number.isFinite(d)&&d>s.day-7&&d<=s.day).sort((a,b)=>a-b).slice(-14);

View file

@ -1,4 +1,4 @@
function bizSf(b,ids){const T=BIZ_T[b.type];return T.fiber?(fiberOk(b,ids)?1:0):T.l2?clamp((R.l2[b.id]||0)/b.bw,0,1):bizSfOf(R,b.city);}
function bizSf(b,ids){const T=BIZ_T[b.type];return T.fiber?(fiberOk(b,ids)?1:0):T.l2?clamp((R.l2[b.id]||0)/b.bw,0,1):bizSfOf(R,b.city)*((R.tgtF&&R.tgtF[b.id])??1);}
// Protected business traffic has its own served share; without the rule it shares the city's.
function bizSfOf(r,c){const d=r.bizDem&&r.bizDem[c];return teRules()&&teRules().protect&&d>1e-6?clamp(r.bizSrv[c]/d,0,1):sfOf(r,c);}
function bCities(o){return o.sites?o.sites.slice():[o.city,o.city2].filter(Boolean);}