// IPv4 address space (#150, src/game/60-features/33-address-space.js): business customers need public blocks, broadband // homes share addresses behind CGNAT when they do not fit, blocks are bought, sold, leased in and leased out, and the // whole thing is a rule (ip4): On-call and BGP at 3 a.m. only, scenarios when they opt in. const test = require('node:test'); const assert = require('node:assert/strict'); const fs = require('node:fs'); const path = require('node:path'); const { load } = require('./harness'); const { lit } = require('../scripts/lib/js-literal'); // Frankfurt on On-call, plenty of cash, nothing breaking, level 9 so every kind of customer can turn up. const BASE = "ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.rules=makeRules('oncall');S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=9;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.offers=[];S.biz=[];" + "ACT.launchBB({city:'fra'});S.pops.fra.rgen=3;ACT.buyTransit({city:'fra',net:'lvl',tier:3});compute()"; function game(t, opts) { const h = load(opts); t.after(() => h.dom.window.close()); h.ev(BASE); return h; } const J = (ev, x) => JSON.parse(ev(`JSON.stringify(${x})`)); const homes = (ev, g) => ev(`S.pops.fra.bb.d=${g};compute()`); const biz = (ev, b) => ev(`S.biz.push(${lit({ id: b.id || 'b' + Math.random().toString(36).slice(2), city: 'fra', city2: null, reqs: [], name: 'X', type: 'host', bw: 10, rate: 60, mood: 100, since: 0, ...b })});compute()`); test('what each customer needs: a block by kind and size, nothing for circuits, fiber, downstream ISPs or orbit', (t) => { const { ev, errors } = game(t); const need = (type, bw) => ev(`ip4Need({type:${lit(type)},bw:${bw}})`); assert.equal(need('dia', 1), 8, 'a small DIA port gets a /29'); assert.equal(need('dia', 10), 32); assert.equal(need('game', 5), 16); assert.equal(need('host', 10), 64); assert.equal(need('host', 80), 512, 'a big hosting company a /23'); assert.equal(need('cgame', 3200), 2048); assert.equal(need('metav', 6400), 2048); assert.equal(need('host', 1e6), 4096, 'capped at a /20'); for (const k of ['l2vpn', 'hyper', 'wwave', 'dfpair', 'isp', 'edu', 'provedor', 'event', 'pizza', 'flywifi']) assert.equal(need(k, 100), 0, k); assert.equal(ev('ip4Cidr(8)'), '/29'); assert.equal(ev('ip4Cidr(512)'), '/23'); // Every IPv4 kind is a real kind of customer that pays by the Gbps. assert.deepEqual(J(ev, 'Object.keys(IP4_BIZ).filter(k=>!BIZ_T[k]||!(BIZ_T[k].rate>0)||BIZ_T[k].l2||BIZ_T[k].fiber||BIZ_T[k].orbit)'), []); assert.deepEqual(errors, []); }); test('consumption: business first, homes take the rest, and the ones that do not fit go behind CGNAT', (t) => { const { ev, errors } = game(t); // A new network: one /21 from the RIR, held two years before it can move. assert.deepEqual(J(ev, 'S.ip4.b.map(b=>[b.len,b.k,b.d])'), [[21, 'rir', 0]]); assert.equal(ev('S.ip4.nat'), 16); homes(ev, 50); let u = J(ev, 'ip4Use()'); assert.deepEqual([u.T, u.B, u.H, u.cg, u.over, u.free], [2048, 0, 500, 0, 0, 2048 - 32], '500 homes all public; a new customer could push them all behind CGNAT'); assert.equal(ev('R.cost.ip4'), undefined, 'nothing to pay while everyone has an address'); biz(ev, { type: 'host', bw: 80 }); // a /23 homes(ev, 150); u = J(ev, 'ip4Use()'); // 1,536 left for 1,500 homes: all public. 1,600 homes: (1600-1536)*16/15 rounded up go behind CGNAT. assert.deepEqual([u.B, u.cg], [512, 0]); homes(ev, 160); u = J(ev, 'ip4Use()'); assert.equal(u.cg, Math.ceil((1600 - 1536) * 16 / 15)); assert.ok(u.H - u.cg + Math.ceil(u.cg / 16) <= 1536, 'public homes plus the CGNAT pool fit the space'); const c = J(ev, 'ip4Bill(R.rev.eyeballs)'); assert.ok(c.box > 0 && c.refund > 0, 'CGNAT boxes and refunds cost money'); assert.equal(ev('R.cost.ip4'), Math.round(c.box + c.refund)); assert.ok(Math.abs(c.refund - ev('R.rev.eyeballs') * (u.cg / u.H) * 0.015) < 1e-6, 'refunds: 1.5% of the CGNAT share of what homes pay at 1:16'); // A wider ratio frees addresses and annoys more gamers. const free16 = u.free; ev("ACT.ip4Nat({v:'64'})"); assert.equal(ev('S.ip4.nat'), 64); assert.ok(J(ev, 'ip4Use()').free > free16); assert.ok(J(ev, 'ip4Bill(R.rev.eyeballs)').refund > c.refund); ev("ACT.ip4Nat({v:'16'})"); // Business customers squeeze the homes: past the ratio, homes are squeezed out (port exhaustion) and it shows. biz(ev, { type: 'host', bw: 80, id: 'h2' }); biz(ev, { type: 'host', bw: 1e6, id: 'h3' }); u = J(ev, 'ip4Use()'); assert.equal(u.cg, u.H); assert.ok(u.over > 0 && u.free < 0); assert.ok(J(ev, 'ip4Bill(R.rev.eyeballs)').refund >= ev('R.rev.eyeballs*ip4Use().over') * 0.15, 'squeezed homes want real money back'); // Narrowing the ratio is refused when the signed customers would not fit. ev("ACT.ip4Nat({v:'8'})"); assert.equal(ev('S.ip4.nat'), 16); assert.deepEqual(errors, []); }); test('an offer that needs more IPv4 than is free cannot be signed, and says why; a block fixes it', (t) => { const { ev, dom, errors } = game(t); homes(ev, 50); ev(`S.offers.push({id:'big',city:'fra',name:'Pixel Palace',type:'cgame',bw:3200,rate:45,reqs:[],exp:S.day+30},{id:'small',city:'fra',name:'Tiny DIA',type:'dia',bw:1,rate:600,reqs:[],exp:S.day+30})`); assert.equal(ev("ip4Fits(S.offers[0])"), false, 'a /21 does not fit the starting /21 with homes on it'); assert.equal(ev("ip4Fits(S.offers[1])"), true); // The deals list and the city panel say why, with a way to the address space. ev("UI.left='deals';UI.leftOpen=true;renderLeft();selectCity('fra');UI.tab='cust';renderPanel()"); const left = dom.window.document.getElementById('leftBody').textContent; assert.match(left, /Needs a \/21 of IPv4 \(2,048 addresses\); only 2,016 free\./); assert.ok(dom.window.document.querySelector('#leftBody [data-act="ip4Open"]'), 'a button to the address space'); ev("ACT.accept({id:'big'})"); assert.equal(ev("S.offers.some(o=>o.id==='big')"), true, 'not signed'); assert.equal(ev('S.biz.length'), 0); assert.match(dom.window.document.getElementById('toasts').textContent, /Pixel Palace needs a \/21 of IPv4/); ev("ACT.accept({id:'small'})"); assert.equal(ev('S.biz.length'), 1, 'a small one fits'); // Buy a /21 and the big one signs. const cash = ev('S.cash'); ev("ACT.ip4Buy({len:21})"); assert.equal(ev('S.cash'), cash - ev('ip4Cost(21)')); assert.equal(ev('ip4Cost(21)'), Math.round(2048 * 38 * (1 - 0.015 * 3) / 100) * 100, 'about $38 an address, a little less for a bigger block'); ev("ACT.accept({id:'big'})"); assert.equal(ev('S.biz.length'), 2); assert.equal(J(ev, 'ip4Use()').B, 8 + 2048); // The bank opens at the section. ev("ACT.ip4Open()"); assert.equal(dom.window.document.getElementById('bankBox').hidden, false); assert.ok(dom.window.document.getElementById('bankIp4')); assert.deepEqual(errors, []); }); test('the sales desk and the CEO do not sign what does not fit', (t) => { const { ev, errors } = game(t); homes(ev, 50); ev("ACT.salesHire({id:'shark'});closeModal();S.slAuto.on=true"); ev("S.offers.push({id:'big',city:'fra',name:'Big One',type:'metav',bw:6400,rate:35,reqs:[],exp:S.day+30})"); ev('slAutoDay(S.day)'); assert.equal(ev("S.offers.some(o=>o.id==='big')"), true, 'the shark leaves it'); ev("ACT.salesFire({});ACT.salesFire({});closeModal();ACT.salesHire({id:'ceo'});closeModal()"); assert.equal(ev("salesOverride(S.offers.find(o=>o.id==='big'))"), false, 'no handshake on addresses you do not have'); assert.equal(ev("(()=>{const t=SALES_GOLF.find(x=>(BIZ_T[x].lv||1)<=lvl()&&ip4Fits({type:x,bw:BIZ_T[x].opts[BIZ_T[x].opts.length-1]}));return t;})()"), 'gpu', 'the golf deal is the biggest that fits (a /23 for an AI data center, not a /21 for cloud gaming)'); assert.deepEqual(errors, []); }); test('buying, leasing in, leasing out and selling move the right money', (t) => { const { ev, dom, errors } = game(t); homes(ev, 20); const rev0 = ev('R.revMo'), cost0 = ev('R.costMo'); ev("ACT.ip4Lease({len:22})"); const lin = ev("S.ip4.b.find(b=>b.k==='in').mo"); assert.equal(lin, 512, 'a /22 leases for $0.50 an address a month'); assert.equal(ev('R.costMo'), cost0 + lin); assert.equal(ev('ip4Use().T'), 3072); ev("ACT.ip4Buy({len:24})"); const bought = ev("S.ip4.b.find(b=>b.k==='buy').id"); ev(`ACT.ip4Out({id:${lit(bought)}})`); assert.equal(ev(`S.ip4.b.find(b=>b.id===${lit(bought)}).mo`), Math.round(256 * 0.4)); assert.equal(ev('R.revMo'), rev0 + Math.round(256 * 0.4), 'leased out: income every month'); assert.equal(ev('R.rev.ip4'), Math.round(256 * 0.4)); // A leased-out block cannot be sold; take it back first. A fresh block cannot move for two years. ev(`ACT.ip4Sell({id:${lit(bought)}})`); assert.equal(ev(`S.ip4.b.some(b=>b.id===${lit(bought)})`), true); ev(`ACT.ip4Back({id:${lit(bought)}})`); assert.equal(ev('R.rev.ip4'), undefined); ev(`ACT.ip4Sell({id:${lit(bought)}})`); assert.match(dom.window.document.getElementById('toasts').textContent, /won't transfer that block again/); ev('S.day+=730'); const cash = ev('S.cash'); ev(`ACT.ip4Sell({id:${lit(bought)}})`); assert.equal(ev(`S.ip4.b.some(b=>b.id===${lit(bought)})`), true, 'the first click only asks'); ev(`ACT.ip4Sell({id:${lit(bought)}})`); assert.equal(ev(`S.ip4.b.some(b=>b.id===${lit(bought)})`), false); assert.equal(ev('S.cash'), cash + ev('ip4Value(24)')); assert.ok(ev('ip4Value(24)') < ev('ip4Cost(24)'), 'the broker keeps a cut'); // Hand the leased block back: the fee stops. ev("ACT.ip4Return({id:S.ip4.b.find(b=>b.k==='in').id})"); assert.equal(ev("S.ip4.b.some(b=>b.k==='in')"), false); assert.equal(ev('R.cost.ip4'), undefined); // Space in use cannot be given away: with customers on every address, leasing out or selling the /21 is refused. biz(ev, { type: 'host', bw: 80 }); biz(ev, { type: 'host', bw: 40, id: 'h2' }); const rir = ev("S.ip4.b.find(b=>b.k==='rir').id"); ev(`ACT.ip4Out({id:${lit(rir)}})`); assert.equal(ev(`!!S.ip4.b.find(b=>b.id===${lit(rir)}).out`), false); assert.match(dom.window.document.getElementById('toasts').textContent, /Your customers need those addresses/); assert.deepEqual(errors, []); }); test('investors on a revenue share take their cut of IPv4 lease income, not of a sale', (t) => { const { ev, dom, errors } = game(t); homes(ev, 20); ev("S.loanOffers.push({id:'v1',bank:'vult',amount:500000,exp:S.day+20,covs:['blitz'],share:0.1});ACT.takeLoan({id:'v1'})"); const base = () => ev('R.rev.eyeballs+R.rev.business+R.rev.ix+(R.rev.orbit||0)'); const rs0 = ev('R.cost.revshare'); assert.ok(rs0 > 0 && Math.abs(rs0 - 0.1 * base()) < 1e-6, 'the vultures take 10% of what homes pay'); ev('ACT.ip4Buy({len:20})'); const id = ev("S.ip4.b.find(b=>b.k==='buy').id"); ev(`ACT.ip4Out({id:${lit(id)}})`); const lout = ev('R.rev.ip4'); assert.equal(lout, ev('ip4OutMo(20)')); assert.ok(Math.abs(ev('R.cost.revshare') - 0.1 * (base() + lout)) < 1e-6, 'and 10% of the lease too'); assert.ok(Math.abs(ev('R.cost.revshare') - 0.1 * (ev('R.revMo') - ev('R.rev.grant||0') - ev('R.rev.gov||0'))) < 1, 'of everything but government money'); // A bank's big loan with a revenue share takes its share of the lease while it runs, and stops once repaid. ev("S.loans.push({id:'b1',bank:'db',start:S.day,amount:2e6,got:2e6,bal:2e6,apr:0.1,apr0:0.1,pay:1,left:12,term:12,share:0.05,covs:[],base:{sub:0}});compute()"); assert.ok(Math.abs(ev('R.cost.revshare') - 0.15 * (base() + lout)) < 1e-6); ev("S.loans.find(l=>l.id==='b1').bal=0;compute()"); assert.ok(Math.abs(ev('R.cost.revshare') - 0.1 * (base() + lout)) < 1e-6); // Taking the block back ends the cut; selling it is a one-off that is all yours, like a fiber pair's up-front price. ev(`ACT.ip4Back({id:${lit(id)}})`); assert.equal(ev('R.rev.ip4'), undefined); assert.ok(Math.abs(ev('R.cost.revshare') - rs0) < 1e-6); ev('S.day+=730;compute()'); const rs1 = ev('R.cost.revshare'), cash = ev('S.cash'); ev(`ACT.ip4Sell({id:${lit(id)}});ACT.ip4Sell({id:${lit(id)}})`); assert.equal(ev(`S.ip4.b.some(b=>b.id===${lit(id)})`), false); assert.equal(ev('S.cash'), cash + ev('ip4Value(20)')); assert.ok(Math.abs(ev('R.cost.revshare') - rs1) < 1e-6); // The dashboard's Investor revenue share row shows the new amount. ev("ACT.ip4Buy({len:20});ACT.ip4Out({id:S.ip4.b.filter(b=>b.k==='buy').pop().id});UI.dtab='overview';renderDash()"); assert.ok(ev('R.cost.revshare') > rs1, 'a new lease is shared again'); assert.ok(dom.window.document.getElementById('dash').textContent.includes(ev('fmt$(R.cost.revshare)'))); assert.deepEqual(errors, []); }); test('a list of blocks stops where a save keeps them: buying and leasing past it is refused, and a full save loads whole', (t) => { const { ev, dom, errors } = load({ agent: true }); t.after(() => dom.window.close()); ev(BASE); homes(ev, 20); // The market's default size, clicked over and over (or an agent in a loop): bought and leased /24s. ev('for(let i=0;i<150;i++)ACT.ip4Buy({len:24});for(let i=0;i<150;i++)ACT.ip4Lease({len:24})'); assert.equal(ev('S.ip4.b.length'), ev('IP4_BLK'), 'stops at the most a save keeps'); assert.equal(ev('IP4_BLK'), 256); assert.match(dom.window.document.getElementById('toasts').textContent, /You hold 256 IPv4 blocks/); const cash = ev('S.cash'), T = ev('ip4Use().T'), mo = ev('R.cost.ip4'); ev('ACT.ip4Buy({len:16});ACT.ip4Lease({len:16})'); assert.deepEqual([ev('S.ip4.b.length'), ev('S.cash'), ev('ip4Use().T')], [256, cash, T], 'refused: no money spent, nothing added'); // The bank says so and greys the market out; an agent's quote says why. ev('ACT.ip4Open()'); const sec = dom.window.document.querySelector('#bankCard .bank-ip4'); assert.match(sec.textContent, /the most one network can keep track of/); assert.equal(sec.querySelector('[data-act="ip4Buy"]').disabled, true); assert.equal(sec.querySelector('[data-act="ip4Lease"]').disabled, true); assert.match(J(ev, 'API_CMD.ip4Buy.quote({len:24}).blocked')[0], /256 IPv4 blocks/); assert.match(J(ev, 'API_CMD.ip4Lease.quote({len:24}).blocked')[0], /256 IPv4 blocks/); // Saved and loaded: every block, every lease, the same space and bill. const before = ev('JSON.stringify(S.ip4)'); ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()'); assert.equal(ev('JSON.stringify(S.ip4)'), before); assert.deepEqual([ev('ip4Use().T'), ev('R.cost.ip4')], [T, mo]); // Handing one back makes room for a bigger block. ev("ACT.ip4Return({id:S.ip4.b.find(b=>b.k==='in').id});ACT.ip4Buy({len:16})"); assert.deepEqual([ev('S.ip4.b.length'), ev('S.ip4.b[255].len')], [256, 16]); assert.deepEqual(errors, []); }); test('a customer renewing bigger stays at its size when the bigger block is not free, and says why', (t) => { const { ev, dom, errors } = game(t); homes(ev, 0); // Eight 40G hosts (a /24 each) fill the /21; the ninth is refused at the door. for (let i = 0; i < 9; i++) ev(`S.offers.push({id:'o${i}',city:'fra',name:'Host ${i}',type:'host',bw:40,rate:60,reqs:[],exp:S.day+30});ACT.accept({id:'o${i}'})`); assert.equal(ev('S.biz.length'), 8); assert.equal(J(ev, 'ip4Use()').free, 0); // The next term of host 0 on a day its own rolls say: stay, and grow (to 80G, a /23). const renew = () => J(ev, `(()=>{const b=S.biz[0];for(const x of S.biz)if(x!==b)x.te=1e6; for(let k=Math.max(S.day,b.te)+1;k=(0.04+0.08*Math.min(1,clComp(b)/6))*salesLeaveMul(b)){S.day=k;document.getElementById('toasts').innerHTML='';clDay(k);compute(); return {bw:b.bw,te:b.te,in:S.biz.includes(b),free:ip4Use().free,toasts:document.getElementById('toasts').textContent};}}return null;})()`); let r = renew(); assert.ok(r, 'a growing renewal turns up'); assert.deepEqual([r.bw, r.in, r.free], [40, true, 0], 'renewed at the size it has: nobody runs on addresses you do not have'); assert.ok(r.te > ev('S.day'), 'a new term'); assert.match(r.toasts, /Host 0 \(Frankfurt\) wanted to grow to 80(\.0)? Gbps, but you had no IPv4 addresses free for it\./); assert.match(r.toasts, /renewed/); // The acquisition that would stay bigger goes through the same door. assert.equal(ev('(()=>{const out={v4:[]};return clGrow(S.biz[0],out)===false&&out.v4.length===1&&S.biz[0].bw===40;})()'), true); // A block bought, the next growing renewal grows. ev('ACT.ip4Buy({len:24})'); r = renew(); assert.deepEqual([r.bw, r.free], [80, 0]); assert.match(r.toasts, /renewed and grew to 80(\.0)? Gbps/); // Without the rule, growth is as it always was. ev("S.rules=makeRules('freeze');compute()"); r = renew(); assert.equal(r.bw, 160); assert.doesNotMatch(r.toasts, /IPv4/); assert.deepEqual(errors, []); }); test('the address space says what its numbers mean: free counts homes behind CGNAT, blocks in use say why they stay', (t) => { const { ev, dom, errors } = game(t); ev('S.day=800'); homes(ev, 50); ev('ACT.ip4Open()'); const sec = () => dom.window.document.querySelector('#bankCard .bank-ip4'); assert.match(sec().textContent, /Free for new customers \(homes move behind CGNAT first\)2,016/); // The /21 is out of its holding period, but 500 homes use it: greyed out, and the row says why. let row = sec().querySelector('[data-act="ip4Out"]').closest('.row'); assert.equal(row.querySelector('[data-act="ip4Out"]').disabled, true); assert.equal(row.querySelector('[data-act="ip4Sell"]').disabled, true); assert.match(row.querySelector('.why').textContent, /Your customers need those addresses/); // A leased-in /24 the customers need too: Give it back is greyed, with the reason. ev("ACT.ip4Lease({len:24})"); biz(ev, { type: 'host', bw: 80, id: 'h1' }); biz(ev, { type: 'host', bw: 80, id: 'h2' }); biz(ev, { type: 'host', bw: 80, id: 'h3' }); biz(ev, { type: 'host', bw: 80, id: 'h4' }); assert.equal(J(ev, 'ip4Use()').free, 224, 'fewer free than the /24 holds'); ev('UI._bh=null;renderBank()'); row = sec().querySelector('[data-act="ip4Return"]').closest('.row'); assert.equal(row.querySelector('[data-act="ip4Return"]').disabled, true); assert.match(row.querySelector('.why').textContent, /Your customers need those addresses/); // With room to spare, no reason is shown and the buttons work. ev("S.biz=[];compute();ACT.ip4Buy({len:24});UI._bh=null;renderBank()"); row = [...sec().querySelectorAll('[data-act="ip4Out"]')].pop().closest('.row'); assert.equal(row.querySelector('[data-act="ip4Out"]').disabled, false); assert.equal(row.querySelector('.why'), null); assert.deepEqual(errors, []); }); test('the AS box on the dashboard lists the blocks you announce, not a made-up count', (t) => { const { ev, dom, errors } = game(t); const asBox = () => { ev("ACT.dash({});ACT.dashTab({k:'infra'})"); const k = [...dom.window.document.querySelectorAll('#dashCard .kv')].map(e => e.textContent).find(x => /IPv6/.test(x)); ev('ACT.dashClose()'); return k; }; assert.match(asBox(), /1 × \/21 IPv4, 1 × \/32 IPv6/, 'the starting allocation'); ev("ACT.ip4Lease({len:22});ACT.ip4Buy({len:24})"); assert.match(asBox(), /1 × \/21, 1 × \/22, 1 × \/24 IPv4/, 'bought and leased-in blocks are announced too'); ev("S.rules=makeRules('freeze');compute()"); assert.match(asBox(), /1 × \/22 IPv4/, 'without the rule it stays as it always was'); assert.deepEqual(errors, []); }); test('the market price drifts gently with the day, and holds still without the market rule', (t) => { const { ev, errors } = game(t); assert.equal(ev('ip4Px(0)'), 38); assert.equal(ev('ip4Px(180)'), 38, 'flat for half a year'); const px = [400, 900, 1500, 2200].map((d) => ev(`ip4Px(${d})`)); assert.ok(px.every((p) => p > 30 && p < 50), 'realistic: $30 to $50 an address: ' + px); assert.ok(Math.abs(ev('ip4Px(546)') - ev('ip4Px(545)')) < 0.1, 'a gentle trend, not a jump'); assert.ok(ev('ip4Cost(16)') / 65536 < ev('ip4Cost(24)') / 256, 'bigger blocks a little cheaper per address'); ev("S.rules=makeRules('oncall',{market:false})"); assert.equal(ev('ip4Px(1500)'), 38); assert.deepEqual(errors, []); }); test('the day says it once when homes go behind CGNAT, and when even CGNAT cannot fit them', (t) => { const { ev, dom, errors } = game(t); const said = () => dom.window.document.getElementById('toasts').textContent; // A handful of homes over the edge (under a percent of them) is not news yet. homes(ev, 205.3); ev('ip4Day(S.day)'); const few = J(ev, 'ip4Use()'); assert.ok(few.cg > 0 && few.cg < few.H / 100, JSON.stringify(few)); assert.equal(ev('S.ip4.w'), 0); assert.doesNotMatch(said(), /IPv4/); homes(ev, 250); ev('ip4Day(S.day)'); assert.match(said(), /Your IPv4 is full\.\s*19% of your homes now share addresses behind CGNAT/); assert.equal(ev('S.ip4.w'), 1); ev("document.getElementById('toasts').innerHTML='';ip4Day(S.day)"); assert.equal(said(), '', 'only once'); // Homes hovering at the limit hear it once: dipping just under does not rearm it, real room again does. homes(ev, 204); ev('ip4Day(S.day)'); assert.deepEqual([J(ev, 'ip4Use()').cg, ev('S.ip4.w')], [0, 1]); homes(ev, 250); ev('ip4Day(S.day)'); assert.equal(said(), '', 'not again while hovering'); homes(ev, 150); ev('ip4Day(S.day)'); assert.equal(ev('S.ip4.w'), 0, 'room to spare: it rearms'); homes(ev, 250); ev('ip4Day(S.day)'); assert.match(said(), /Your IPv4 is full/); ev("document.getElementById('toasts').innerHTML=''"); biz(ev, { type: 'host', bw: 1e6 }); ev('ip4Day(S.day)'); assert.match(dom.window.document.getElementById('toasts').textContent, /Out of IPv4/); assert.equal(ev('S.ip4.w'), 3); ev("S.biz=[];S.pops.fra.bb.d=10;compute();ip4Day(S.day)"); assert.equal(ev('S.ip4.w'), 0, 'fixed: the warnings rearm'); assert.deepEqual(errors, []); }); // The notices came with an Address space button, but their line in the NOC's notifications had no Open: the log did not // know the button (openOf), so it fell back to the text, which names no POP. Open now goes where the button went. test('an address-space notice in the notifications opens the bank at its Address space, and the NOC window may ask for it', (t) => { const { ev, dom, errors } = game(t); const doc = dom.window.document; // Where the bank scrolls to: the Address space's own button scrolls it into view. ev("S.log=[];window.__into=[];(()=>{const s=Element.prototype.scrollIntoView;Element.prototype.scrollIntoView=function(){__into.push(this.id);if(s)return s.apply(this,arguments);};})()"); homes(ev, 250); ev('ip4Day(S.day)'); assert.match(ev('S.log[0].t'), /Your IPv4 is full/); assert.deepEqual(J(ev, 'S.log[0].o'), { a: 'ip4' }); ev("closeModal();ACT.leftTab({t:'noc'})"); const b = doc.querySelector(`#leftBody [data-act=logOpen][data-args='${lit({ id: ev('S.log[0].id') })}']`); assert.ok(b, 'the notice has an Open button'); b.click(); assert.equal(doc.getElementById('bankBox').hidden, false, 'the bank is open'); assert.ok(doc.getElementById('bankIp4')); assert.deepEqual(J(ev, '__into'), ['bankIp4'], 'at its Address space'); // A renewal that could not grow carries the same button. biz(ev, { id: 'h1', name: 'Hoster' }); ev("ACT.bankClose();S.log=[];ip4News([[S.biz.find(b=>b.id==='h1'),20]])"); assert.deepEqual(J(ev, 'S.log[0].o'), { a: 'ip4' }); // Kept in the save; with IPv4 off (a save from a gentler preset) it still opens the bank. ev("S=migrate(JSON.parse(JSON.stringify(S)));"); assert.deepEqual(J(ev, 'S.log[0].o'), { a: 'ip4' }); ev("ACT.bankClose();S.rules.ip4=false;__into.length=0;ACT.logOpen({id:S.log[0].id})"); assert.equal(ev('ip4On()'), false); assert.equal(doc.getElementById('bankBox').hidden, false); assert.deepEqual(J(ev, '__into'), []); // The NOC window's clicks run in the game only from its list; the address space is on it (#150). assert.ok(ev("NOC_GO.includes('ip4Open')&&!NOC_LOCAL.includes('ip4Open')")); assert.deepEqual(errors, []); }); test('rule off means no effect: gentler presets, sandbox, puzzles and scenarios unless they opt in', (t) => { const { ev, dom, errors } = game(t); assert.deepEqual(J(ev, "['soft','freeze','oncall','bgp','sandbox','puzzle'].map(p=>makeRules(p).ip4)"), [false, false, null, null, false, false], 'On-call and BGP keep the default (on), written nowhere'); assert.equal(ev('RULE_DEF.ip4'), true); ev("S.rules=makeRules('freeze');S.pops.fra.bb.d=500;compute()"); assert.equal(ev('ip4On()'), false); ev("S.offers.push({id:'big',city:'fra',name:'Big One',type:'metav',bw:6400,rate:35,reqs:[],exp:S.day+30})"); assert.equal(ev("ip4Why(S.offers[0])"), ''); ev("ACT.accept({id:'big'})"); assert.equal(ev('S.biz.length'), 1, 'signed: IPv4 is plentiful here'); assert.equal(ev('R.cost.ip4'), undefined); ev("ACT.ip4Buy({len:24})"); assert.equal(ev('S.ip4.b.length'), 1, 'the market is closed'); ev("ACT.bank()"); assert.equal(dom.window.document.getElementById('bankIp4'), null, 'no address space in the bank'); ev("ACT.bankClose()"); // Sandbox and scenarios. ev("beginGame('Box','fra',{mode:'sandbox'});if(UI.pendGame)ACT.pitchSkip()"); assert.equal(ev('ip4On()'), false, 'sandbox'); ev("beginGame('S','fra',{mode:'normal',preset:'oncall',scn:SCN.find(x=>x.city==='fra')||SCN[0]});if(UI.pendGame)ACT.pitchSkip()"); assert.equal(ev("S.mode"), 'scenario'); assert.equal(ev('ip4On()'), false, 'scenarios run On-call but stay as they were'); ev('S.scn.rules.ip4=true'); assert.equal(ev('ip4On()'), true, 'unless they opt in'); ev("beginGame('B','fra',{mode:'normal',preset:'bgp'});if(UI.pendGame)ACT.pitchSkip()"); assert.equal(ev('ip4On()'), true, 'BGP at 3 a.m.'); assert.deepEqual(errors, []); }); test('old saves: what they already use is registered to them, so nothing changes on load', (t) => { const { ev, errors } = game(t); homes(ev, 300); biz(ev, { type: 'host', bw: 80 }); biz(ev, { type: 'dia', bw: 10, id: 'd1' }); biz(ev, { type: 'l2vpn', bw: 10, id: 'l1' }); // The same network without the rule, for its money. ev("window.__r=S.rules;S.rules=makeRules('freeze');compute();window.__m=[R.revMo,R.costMo];S.rules=__r"); ev('S.day=400;delete S.ip4;S=migrate(JSON.parse(JSON.stringify(S)));compute()'); const u = J(ev, 'ip4Use()'); assert.equal(u.cg, 0, 'no home behind CGNAT'); const want = (u.B + u.H) * 1.25; assert.ok(u.T >= want && u.T - want < 256, 'what they use and a quarter more to grow into, rounded up to whole /24s: ' + JSON.stringify(u)); assert.ok(J(ev, 'S.ip4.b').every((b) => b.k === 'rir' && b.d === 400 && b.len >= 16 && b.len <= 24)); assert.deepEqual([ev('R.revMo'), ev('R.costMo')], J(ev, '__m'), 'the same money as before the feature'); // A tiny old save still gets the /21 a new one starts with. ev("S.biz=[];S.pops.fra.bb.d=1;delete S.ip4;S=sanitize(JSON.parse(JSON.stringify(S)))"); assert.deepEqual(J(ev, 'S.ip4.b.map(b=>b.len)'), [21]); // A big old network: whole /16s. ev("S.pops.fra.bb.d=20000;delete S.ip4;S=sanitize(JSON.parse(JSON.stringify(S)))"); const big = J(ev, 'ip4Use()'); assert.ok(big.T >= 200000 && big.cg === 0 && J(ev, 'S.ip4.b.filter(b=>b.len===16).length') === 3); assert.deepEqual(errors, []); }); test('the big network loads with its usage granted: routing and money as before', (t) => { const { ev, dom, errors } = load({ seed: 3 }); t.after(() => dom.window.close()); const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); ev(`S=migrate(JSON.parse(${lit(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute()`); const on = ev('ip4On()'); const digest = 'JSON.stringify([R.served,R.revMo,R.costMo,R.cost,R.rev])'; const a = ev(digest); ev("window.__r=S.rules;S.rules=Object.assign({},S.rules,{ip4:false});compute()"); assert.equal(ev(digest), a, 'the grant covers it all (rule ' + (on ? 'on' : 'off') + ')'); assert.equal(J(ev, 'S.ip4.b.length') > 0, true); assert.deepEqual(errors, []); }); test('saves: garbage is repaired, and the state round-trips', (t) => { const { ev, errors } = game(t); ev("ACT.ip4Lease({len:23});ACT.ip4Nat({v:'32'})"); const before = ev('JSON.stringify(S.ip4)'); ev('S=sanitize(JSON.parse(JSON.stringify(S)))'); assert.equal(ev('JSON.stringify(S.ip4)'), before); ev(`S.ip4={b:[{id:'a',len:12,k:'rir',d:0},{id:'b',len:24,k:'stolen',d:0},{id:'c',len:24,k:'buy',d:-5,out:'yes',mo:5},{id:'d',len:23,k:'in',d:1e9,mo:-3},null,{id:'e',len:24,k:'rir',d:0,out:true,mo:'x'}],nat:7,w:99};S=sanitize(JSON.parse(JSON.stringify(S)))`); assert.deepEqual(J(ev, 'S.ip4'), { b: [{ id: 'c', len: 24, k: 'buy', d: 0 }, { id: 'd', len: 23, k: 'in', d: ev('S.day'), mo: 0 }, { id: 'e', len: 24, k: 'rir', d: 0, out: true, mo: 0 }], nat: 16, n64: 128, w: 3 }); ev("S.ip4='nope';S=sanitize(JSON.parse(JSON.stringify(S)))"); assert.ok(J(ev, 'S.ip4.b.length') >= 1, 'a broken field is granted afresh'); assert.deepEqual(errors, []); }); test('the address space works on a phone: one column, wrapping buttons, the dropdowns stacked', (t) => { const { ev, dom, errors } = game(t); ev("window.innerWidth=360;window.innerHeight=740;S.pops.fra.bb.d=250;compute();ACT.ip4Lease({len:24});ACT.ip4Open()"); const sec = dom.window.document.querySelector('#bankCard .bank-ip4'); assert.ok(sec, 'the section is in the bank'); assert.equal(sec.querySelectorAll('select').length, 3, 'the CGNAT ratio, the NAT64 ratio and the block size'); for (const s of sec.querySelectorAll('select')) assert.ok(s.closest('.ops-sel'), 'each dropdown in a stacking label'); for (const b of sec.querySelectorAll('button')) assert.ok(b.closest('.btns'), 'every button in a wrapping row: ' + b.textContent); assert.match(sec.textContent, /2,500, \d+% behind CGNAT/); // The dropdown picks the size the buttons quote. ev("ACT.ip4Pick({v:'18'})"); assert.ok(dom.window.document.querySelector('#bankCard [data-act="ip4Buy"]').dataset.args.includes('"len":18')); assert.deepEqual(errors, []); }); test('no raw labels in the address space, in every language', (t) => { for (const lang of ['en', 'de', 'es', 'fr', 'it', 'pt']) { const { ev, dom, errors } = load(lang === 'en' ? {} : { lang }); ev(BASE); ev("S.pops.fra.bb.d=300;compute();ACT.ip4Lease({len:24});ACT.ip4Buy({len:24});S.ip4.b[2].out=true;S.ip4.b[2].mo=99;S.biz.push({id:'z',city:'fra',city2:null,reqs:[],name:'Z',type:'host',bw:1e6,rate:1,mood:100,since:0});compute();ip4Day(S.day);ACT.ip4Open()"); ev("S.offers.push({id:'o',city:'fra',name:'O',type:'host',bw:80,rate:60,reqs:[],exp:S.day+30});UI.left='deals';renderLeft()"); ev("for(let i=S.ip4.b.length;i 2, lang + ': the full list and the blocks in use say why'); const txt = dom.window.document.getElementById('bankCard').textContent + dom.window.document.getElementById('leftBody').textContent + dom.window.document.getElementById('toasts').textContent; assert.doesNotMatch(txt, /\bip4\.[a-z_]+|\{[a-z]+\}|undefined|NaN/, lang); assert.deepEqual(errors, [], lang); dom.window.close(); } }); test('buying what an offer asks for on signing (#241) buys nothing when its IPv4 block does not fit', (t) => { const { ev, errors } = game(t); homes(ev, 50); ev("S.pops.fra.gen=false;S.offers.push({id:'big',city:'fra',name:'Pixel Palace',type:'cgame',bw:3200,rate:45,reqs:['gen'],exp:S.day+30});compute()"); assert.equal(ev("ip4Fits(S.offers[0])"), false); assert.equal(ev("reqFix(S.offers[0]).cost"), ev('GEN_COST'), 'the generator is what it lacks'); assert.equal(ev("reqFixHtml(S.offers[0])"), '', 'no "Buy and sign" button for a deal that cannot be signed'); const c0 = ev('S.cash'); ev("ACT.acceptFix({id:'big',cost:GEN_COST})"); assert.equal(ev('S.cash'), c0, 'nothing spent'); assert.equal(ev('S.pops.fra.gen'), false, 'no generator bought for it'); assert.equal(ev('S.biz.length'), 0); // A block that makes it fit brings the button back, and the click buys and signs. ev("ACT.ip4Buy({len:21});renderAll()"); assert.notEqual(ev("reqFixHtml(S.offers[0])"), ''); ev("ACT.acceptFix({id:'big',cost:GEN_COST})"); assert.deepEqual([ev('S.pops.fra.gen'), ev('S.biz.length')], [true, 1]); assert.deepEqual(errors, []); });