-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode_simulator.html
More file actions
953 lines (884 loc) · 43.6 KB
/
Copy pathnode_simulator.html
File metadata and controls
953 lines (884 loc) · 43.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>CakeWallet — Node Switch Simulator</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
:root{
--bg:#0f1420; --panel:#161d2e; --panel2:#1c2438; --border:#2a3552;
--text:#e7ecf7; --muted:#8fa0c4; --accent:#5b8cff;
--green:#22c55e; --green-glow:rgba(34,197,94,.55);
--red:#ef4444; --red-glow:rgba(239,68,68,.55);
--orange:#f59e0b; --orange-glow:rgba(245,158,11,.55);
--grey:#3a445e;
}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--text);font:14px/1.5 -apple-system,Segoe UI,Roboto,Arial,sans-serif}
header{padding:18px 24px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px}
header h1{font-size:17px;margin:0;font-weight:600}
header p{margin:2px 0 0;color:var(--muted);font-size:12.5px}
main{padding:20px 24px 60px;max-width:1400px;margin:0 auto}
section{margin-bottom:28px}
h2{font-size:14px;text-transform:uppercase;letter-spacing:.04em;color:var(--muted);margin:0 0 12px;display:flex;align-items:center;gap:10px}
.controls{display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin-bottom:14px;background:var(--panel);border:1px solid var(--border);border-radius:10px;padding:12px 14px}
.controls .grp{display:flex;align-items:center;gap:6px;padding-right:12px;border-right:1px solid var(--border)}
.controls .grp:last-child{border-right:none}
button{background:var(--panel2);color:var(--text);border:1px solid var(--border);border-radius:7px;padding:7px 12px;font-size:12.5px;cursor:pointer;transition:.15s}
button:hover{background:#232d47;border-color:var(--accent)}
button.primary{background:var(--accent);border-color:var(--accent);color:#fff}
button.primary:hover{filter:brightness(1.1)}
button.warn{border-color:var(--orange)}
button.danger{border-color:var(--red)}
button:disabled{opacity:.4;cursor:not-allowed}
select{background:var(--panel2);color:var(--text);border:1px solid var(--border);border-radius:7px;padding:6px 8px;font-size:12.5px}
label.small{color:var(--muted);font-size:12px;display:flex;align-items:center;gap:5px}
.clock{font-variant-numeric:tabular-nums;font-size:13px;color:var(--text);background:var(--panel2);padding:6px 10px;border-radius:7px;border:1px solid var(--border)}
.progresswrap{flex:1;min-width:160px;display:flex;align-items:center;gap:8px}
.progressbar{flex:1;height:8px;background:var(--panel2);border-radius:5px;overflow:hidden;border:1px solid var(--border)}
.progressbar > div{height:100%;background:linear-gradient(90deg,var(--accent),var(--green));width:0%}
.events{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:6px}
.subnote{color:var(--muted);font-size:11.5px;margin:6px 0 10px}
.reopeninfo{color:var(--muted);font-size:11.5px;margin-top:8px;min-height:14px}
.nodelist{display:flex;flex-direction:column;gap:8px;margin-bottom:16px}
.nodecard{width:100%;background:var(--panel);border:1px solid var(--border);border-radius:10px;padding:10px 14px;display:flex;align-items:center;gap:22px;flex-wrap:wrap}
.nodecard .idblock{min-width:220px;flex:1 1 220px}
.nodecard .type{font-size:10px;text-transform:uppercase;letter-spacing:.05em;color:var(--muted)}
.nodecard .addr{font-family:ui-monospace,Consolas,monospace;font-size:10.5px;color:var(--muted);word-break:break-all;margin-top:2px}
.nodecard .rm{background:none;border:none;color:var(--muted);cursor:pointer;font-size:14px;padding:0 2px;line-height:1}
.nodecard .rm:hover{color:var(--red)}
.dots{display:flex;gap:16px}
.dotline{display:flex;flex-direction:column;align-items:center;gap:3px}
.dot{width:12px;height:12px;border-radius:50%;background:var(--grey)}
.dot.on{background:var(--green);box-shadow:0 0 8px var(--green-glow)}
.dot.off{background:var(--red);box-shadow:0 0 8px var(--red-glow)}
.dotline span{font-size:9px;color:var(--muted)}
.flags{display:flex;flex-wrap:wrap;gap:4px;min-width:160px}
.flag{font-size:9.5px;padding:2px 6px;border-radius:20px;border:1px solid var(--orange);color:var(--orange);white-space:nowrap}
.flag.bad{border-color:var(--red);color:var(--red)}
.lat{font-size:10.5px;color:var(--muted);min-width:150px}
.methodgrid{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:12px}
.methodcard{background:var(--panel);border:1px solid var(--border);border-radius:12px;padding:14px;display:flex;flex-direction:column;gap:10px}
.methodcard.exp{border-style:dashed;opacity:.92}
.mtitle{display:flex;justify-content:space-between;align-items:center}
.mtitle b{font-size:13px}
.mtitle .now{font-size:10.5px;color:var(--muted)}
.mdesc{font-size:11px;color:var(--muted)}
.light{width:100%;display:flex;justify-content:center;padding:14px 0}
.light .bulb{width:56px;height:56px;border-radius:50%;background:var(--grey);transition:.25s}
.light .bulb.green{background:var(--green);box-shadow:0 0 26px 6px var(--green-glow)}
.light .bulb.red{background:var(--red);box-shadow:0 0 26px 6px var(--red-glow)}
.light .bulb.orange{background:var(--orange);box-shadow:0 0 26px 6px var(--orange-glow)}
.mstat{display:flex;justify-content:space-between;font-size:11px;color:var(--muted)}
.mstat b{color:var(--text)}
.log{background:#0b0f1a;border:1px solid var(--border);border-radius:7px;padding:6px 8px;font-family:ui-monospace,Consolas,monospace;font-size:10px;color:var(--muted);height:86px;overflow-y:auto}
.log div{white-space:nowrap}
.legend{background:var(--panel);border:1px solid var(--border);border-radius:10px;padding:14px 16px;font-size:12px;color:var(--muted)}
.legend b{color:var(--text)}
.legend .row{display:flex;gap:8px;margin-bottom:4px}
footer{color:var(--muted);font-size:11.5px;text-align:center;padding:20px;border-top:1px solid var(--border)}
.empty{color:var(--muted);font-size:12px;padding:20px;text-align:center;border:1px dashed var(--border);border-radius:10px}
.banner{display:none;background:#3a2d10;border:1px solid var(--orange);color:#ffd489;padding:8px 12px;border-radius:8px;font-size:12px;margin-bottom:14px}
.banner.show{display:block}
.truthflag{font-size:10.5px;min-height:14px}
.truthflag.danger{color:var(--red)}
.truthflag.caution{color:var(--orange)}
.methodcard.dropped{opacity:.55;justify-content:center;text-align:center}
.bulb.fp{box-shadow:0 0 0 4px var(--red), 0 0 26px 6px var(--green-glow) !important}
table.rep{width:100%;border-collapse:collapse;font-size:12px}
table.rep th,table.rep td{text-align:left;padding:7px 10px;border-bottom:1px solid var(--border)}
table.rep th{color:var(--muted);font-weight:500;font-size:11px;text-transform:uppercase;letter-spacing:.03em}
table.rep tr.best td:first-child{color:var(--green)}
table.rep tr.worst td:first-child{color:var(--red)}
table.rep tr.champion td:first-child{color:var(--green);font-weight:600}
.reportbox{background:var(--panel);border:1px solid var(--border);border-radius:10px;padding:14px 16px;margin-bottom:14px;overflow-x:auto}
.reportbox h3{font-size:12.5px;margin:0 0 10px;color:var(--text)}
.implpicker{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:12px}
.implpicker button.active{background:var(--accent);border-color:var(--accent);color:#fff}
.implcode{background:#0b0f1a;border:1px solid var(--border);border-radius:10px;padding:16px 18px;font-family:ui-monospace,Consolas,monospace;font-size:12px;line-height:1.6;color:#c9d4ef;overflow-x:auto;white-space:pre;margin:0}
.implcode .kw{color:#7aa2f7}
.implcode .cm{color:#6b7690;font-style:italic}
.implnote{color:var(--muted);font-size:11.5px;margin:0 0 12px}
</style>
</head>
<body>
<header>
<div>
<h1>Node Switch Simulator — CakeWallet</h1>
<p>Educational demonstrator (100% simulated data) — comparing node-resiliency methods for a P2P wallet</p>
</div>
<div class="clock" id="clock">T+ 00:00 simulated — 0 nodes active</div>
</header>
<main>
<div class="banner" id="banner"></div>
<section>
<h2>Controls</h2>
<div class="controls">
<div class="grp">
<button id="btnPlay" class="primary">► Start</button>
<button id="btnReset">↻ Reset</button>
</div>
<div class="grp">
<label class="small">Speed </label>
<select id="speed">
<option value="1">1x (real time)</option>
<option value="4" selected>4x</option>
<option value="10">10x</option>
<option value="30">30x</option>
</select>
</div>
<div class="grp">
<label class="small">Session length </label>
<select id="sessionTarget">
<option value="5">5 sec</option>
<option value="15">15 sec</option>
<option value="30">30 sec</option>
<option value="60">1 min</option>
<option value="120">2 min</option>
<option value="300">5 min</option>
<option value="600" selected>10 min</option>
<option value="900">15 min</option>
<option value="0">unlimited</option>
</select>
</div>
<div class="progresswrap">
<label class="small">Session budget</label>
<div class="progressbar"><div id="progressFill"></div></div>
</div>
</div>
<div class="controls">
<div class="grp">
<label class="small"><input type="checkbox" id="persistToggle"> Persist method state between app opens</label>
</div>
<div class="grp">
<label class="small">Close app & reopen after </label>
<select id="gapSelect">
<option value="3600">1 hour</option>
<option value="86400">1 day</option>
<option value="604800">1 week</option>
<option value="2592000" selected>1 month</option>
<option value="63072000">2 years</option>
</select>
<button id="btnReopen" class="warn">Close & reopen</button>
</div>
</div>
<div class="reopeninfo" id="reopenInfo"></div>
</section>
<section>
<h2>1. Simulated node farm <span class="small" style="text-transform:none;font-weight:400;color:var(--muted)">(0 to 10 — clearnet + .onion)</span></h2>
<div class="controls">
<div class="grp">
<button id="addClear">+ Clearnet node</button>
<button id="addTor">+ .onion node</button>
</div>
<div class="grp small" style="color:var(--muted)">✕ on a node = remove it</div>
</div>
<div class="nodelist" id="nodegrid"></div>
<h2 style="margin-top:18px">Simulate events</h2>
<p class="subnote">Once triggered, an event lasts for the rest of the session (until Reset) — real incidents don't politely resolve themselves after a few seconds.</p>
<div class="events" id="events"></div>
</section>
<section>
<h2>2. Resiliency methods — live comparison</h2>
<div class="methodgrid" id="methodgrid"></div>
</section>
<section>
<h2>3. Report</h2>
<div id="reportLatest"></div>
<div id="reportHistory"></div>
</section>
<section>
<h2>Legend</h2>
<div class="legend" id="legend"></div>
</section>
<section>
<h2>4. Implementation sketch <span class="small" style="text-transform:none;font-weight:400;color:var(--muted)">(click a method to preview it)</span></h2>
<p class="implnote">Compact, human-readable, stubbed pseudocode — not the sim's internal code, but a sketch of how each method would actually be structured in the wallet, to plan a real implementation. <code>rpc.*</code> and <code>wallet.*</code> calls are stand-ins for the real node-RPC and wallet-state APIs.</p>
<div class="implpicker" id="implpicker"></div>
<pre class="implcode" id="implcode"><code>Select a method above to preview its implementation sketch.</code></pre>
</section>
</main>
<footer>All data (nodes, latencies, outages) is generated client-side for demonstration purposes. No real network connection is made.</footer>
<script>
/* ============================= UTILITIES ============================= */
const $=(s)=>document.querySelector(s);
const rnd=(a,b)=>a+Math.random()*(b-a);
const rndi=(a,b)=>Math.floor(rnd(a,b+1));
const pick=(arr)=>arr[Math.floor(Math.random()*arr.length)];
const clamp=(v,a,b)=>Math.max(a,Math.min(b,v));
function fmtClock(sec){
const m=Math.floor(sec/60).toString().padStart(2,'0');
const s=Math.floor(sec%60).toString().padStart(2,'0');
return `${m}:${s}`;
}
function fmtDuration(sec){
if(sec<60) return `${sec}s`;
if(sec<3600) return `${Math.round(sec/60)} min`;
return `${Math.round(sec/3600)}h`;
}
function randOnion(){
const chars='abcdefghijklmnopqrstuvwxyz234567';
let s=''; for(let i=0;i<56;i++) s+=chars[rndi(0,chars.length-1)];
return s+'.onion';
}
let clearCounter=1, torCounter=1;
/* ============================= GLOBAL STATE ============================= */
let nodes=[];
let tick=0; // simulated seconds
let running=false;
let timer=null;
let sessionEnded=false;
let runHistory=[];
const TICK_MS=300; // real ms per clock tick
const STALE_THRESHOLD_SEC=86400; // 1 day: beyond this, persisted method history is considered too stale to trust
function newNode(type){
const id='n'+Date.now()+rndi(0,999);
const isTor=type==='tor';
return {
id, type,
label:isTor?('Tor-'+(torCounter++)):('Clear-'+(clearCounter++)),
addr:isTor?randOnion():`node${clearCounter}.fakemonero.example:18081`,
transport:true, functional:true, broadcastOk:true,
height:3_241_800+rndi(-2,2),
baseLatency:isTor?rnd(700,1600):rnd(120,380),
latency:0,
flags:{hashvaulted:false,flapping:false,saturated:false,stale:false,liar:false,latencySpike:false,offline:false},
};
}
function initNodes(){
nodes=[newNode('clear'),newNode('clear'),newNode('tor'),newNode('tor')];
}
/* ===================== P2P BEHAVIOR SIMULATION ===================== */
function stepNode(n){
const torSpike = n.type==='tor' && nodes.some(x=>x.type==='tor'&&x.flags.latencySpike);
n.latency = n.baseLatency * (torSpike||n.flags.latencySpike?rnd(4,8):1) * rnd(0.85,1.15);
if(n.flags.offline){ n.transport=false; n.functional=false; n.broadcastOk=false; return; }
if(n.flags.flapping){
n.transport = (tick%2===0);
n.functional = n.transport;
n.broadcastOk = n.transport;
return;
}
if(n.flags.hashvaulted){
n.transport=true; n.functional=false; n.broadcastOk=false; return;
}
if(n.flags.liar){
n.transport=true; n.functional=true; n.broadcastOk=false; return;
}
if(n.flags.stale){
n.transport=true; n.functional=true; n.broadcastOk=true;
n.height = 3_241_800 - rndi(80,600);
return;
}
n.height = 3_241_800+rndi(-2,2);
if(n.flags.saturated){
n.transport=true;
n.functional = Math.random()<0.5;
n.broadcastOk=n.functional;
return;
}
// baseline P2P noise (transient micro-outages, more frequent over Tor)
const dropProb = n.type==='tor'?0.03:0.015;
const recoverProb = 0.45;
if(n.transport){
if(Math.random()<dropProb) n.transport=false;
} else {
if(Math.random()<recoverProb) n.transport=true;
}
n.functional=n.transport;
n.broadcastOk=n.transport;
}
function forceFlag(n,flag){
Object.keys(n.flags).forEach(f=>{ n.flags[f]=false; });
n.flags[flag]=true;
}
/* ============================= EVENTS ============================= */
const EVENTS=[
{label:'Cut a random node', fn:()=>{ const n=pick(nodes.filter(x=>x.transport)); if(n) forceFlag(n,'offline'); }},
{label:'Hashvault it (health OK, functional KO)', fn:()=>{ const n=pick(nodes); if(n) forceFlag(n,'hashvaulted'); }},
{label:'Make a node flap', fn:()=>{ const n=pick(nodes); if(n) forceFlag(n,'flapping'); }},
{label:'Tor latency spike (circuit rebuild)', fn:()=>{ nodes.filter(x=>x.type==='tor').forEach(n=>forceFlag(n,'latencySpike')); }},
{label:'Saturate / rate-limit a node', fn:()=>{ const n=pick(nodes); if(n) forceFlag(n,'saturated'); }},
{label:'Desync a node (silent, stale height)', fn:()=>{ const n=pick(nodes); if(n) forceFlag(n,'stale'); }},
{label:'Silent liar node (broadcast fails)', fn:()=>{ const n=pick(nodes); if(n) forceFlag(n,'liar'); }},
{label:'Cut the entire network', fn:()=>{ nodes.forEach(n=>forceFlag(n,'offline')); }},
{label:'A new healthy node appears', fn:()=>{ nodes.push(newNode(Math.random()<0.5?'tor':'clear')); renderNodes(); }},
];
/* ============================= METHODS ============================= */
function checkNode(n, timeoutMs){
if(!n) return {ok:false,functional:false,broadcastOk:false,height:0};
if(n.latency>timeoutMs) return {ok:false,functional:false,broadcastOk:false,height:n.height,timeout:true};
return {ok:n.transport,functional:n.functional,broadcastOk:n.broadcastOk,height:n.height};
}
function pushLog(m,msg){ m.log.unshift(`T+${fmtClock(tick)} ${msg}`); if(m.log.length>30) m.log.pop(); }
function groundTruth(n){ return !!(n && n.transport && n.functional && n.broadcastOk); }
const METHODS=[
{ key:'none', name:'None', desc:'No logic at all. The initially chosen node never changes, even if it goes down.', timeoutMs:5000,
init(){ this.currentId=nodes[0]?.id||null; this.log=[]; this.switchCount=0; },
evaluate(){
const n=nodes.find(x=>x.id===this.currentId);
if(!n) return {color:'red',now:'no node',note:'node removed',truth:false};
const c=checkNode(n,this.timeoutMs);
const ok=c.ok&&c.functional&&c.broadcastOk;
return {color:ok?'green':'red', now:n.label, note:ok?'OK':'failing — cannot switch', truth:groundTruth(n)};
}
},
{ key:'binary', name:'Binary (CakeWallet-style)', desc:'Transport ping only. Switches instantly on the first failure — no hysteresis, no functional check.', timeoutMs:1500,
init(){ this.currentId=nodes[0]?.id||null; this.log=[]; this.switchCount=0; },
evaluate(){
let n=nodes.find(x=>x.id===this.currentId);
if(!n && nodes.length){ this.currentId=nodes[0].id; n=nodes[0]; }
if(!n) return {color:'red',now:'no node',note:'—',truth:false};
const c=checkNode(n,this.timeoutMs);
if(!c.ok){
const idx=nodes.findIndex(x=>x.id===n.id);
const next=nodes[(idx+1)%nodes.length];
pushLog(this,`→ switch ${n.label} → ${next.label} (1st transport failure)`);
this.switchCount++;
this.currentId=next.id;
return {color:'orange',now:next.label,note:'switching (no hysteresis)',truth:groundTruth(next)};
}
// only checks transport: can stay "green" on a Hashvault'd or lying node
return {color:'green',now:n.label,note:'transport OK (functional not checked)',truth:groundTruth(n)};
}
},
{ key:'hyst', name:'Hysteresis + functional check', desc:'Functional check (get_height). 3 consecutive failures → down, 2 successes → up, 15s cooldown.', timeoutMs:3000,
init(){ this.currentId=nodes[0]?.id||null; this.fail=0; this.succ=0; this.state='healthy'; this.cooldownUntil=0; this.log=[]; this.switchCount=0; },
evaluate(){
let n=nodes.find(x=>x.id===this.currentId);
if(!n && nodes.length){ this.currentId=nodes[0].id; n=nodes[0]; this.fail=0; this.succ=0; this.state='healthy'; }
if(!n) return {color:'red',now:'no node',note:'—',truth:false};
const c=checkNode(n,this.timeoutMs);
const good=c.ok&&c.functional;
if(good){ this.succ++; this.fail=0; } else { this.fail++; this.succ=0; }
if(this.state==='healthy' && this.fail>=3 && tick>=this.cooldownUntil){
this.state='down';
const cand=nodes.filter(x=>x.id!==n.id);
const next=cand[0];
if(next){
pushLog(this,`→ switch ${n.label} → ${next.label} (3 consecutive functional failures)`);
this.switchCount++;
this.currentId=next.id; this.state='healthy'; this.fail=0; this.succ=0;
this.cooldownUntil=tick+15;
return {color:'orange',now:next.label,note:'switching (15s cooldown)',truth:groundTruth(next)};
}
}
const truth=groundTruth(n);
if(tick<this.cooldownUntil) return {color: good?'green':'orange', now:n.label, note:'post-switch cooldown',truth};
if(!good && this.fail<3) return {color:'orange',now:n.label,note:`degraded (${this.fail}/3 failures)`,truth};
return {color: good?'green':'red', now:n.label, note: good?'OK':'no alternative available',truth};
}
},
{ key:'score', name:'EWMA score + sticky', desc:'Rolling score (functional + latency). Only switches when the current node is genuinely down — never for a marginal gain.', timeoutMs:3000,
init(){
this.scores={}; nodes.forEach(n=>this.scores[n.id]=1);
this.currentId=nodes[0]?.id||null; this.fail=0; this.succ=0; this.cooldownUntil=0; this.log=[]; this.switchCount=0;
},
evaluate(){
nodes.forEach(n=>{ if(!(n.id in this.scores)) this.scores[n.id]=0.7; });
let n=nodes.find(x=>x.id===this.currentId);
if(!n && nodes.length){ this.currentId=nodes[0].id; n=nodes[0]; this.fail=0; this.succ=0; }
if(!n) return {color:'red',now:'no node',note:'—',truth:false};
nodes.forEach(node=>{
const c=checkNode(node,this.timeoutMs);
const good=c.ok&&c.functional;
const latPenalty=clamp((node.latency-200)/4000,0,0.5);
const obs=good?(1-latPenalty):0;
this.scores[node.id]=0.85*(this.scores[node.id]??0.7)+0.15*obs;
});
const s=this.scores[n.id];
if(s<0.35){ this.fail++; this.succ=0; } else if(s>0.6){ this.succ++; this.fail=0; }
if(this.fail>=3 && tick>=this.cooldownUntil){
const alt=nodes.filter(x=>x.id!==n.id).sort((a,b)=>(this.scores[b.id]??0)-(this.scores[a.id]??0))[0];
if(alt){
pushLog(this,`→ switch ${n.label} (score ${s.toFixed(2)}) → ${alt.label} (score ${(this.scores[alt.id]??0).toFixed(2)})`);
this.switchCount++;
this.currentId=alt.id; this.fail=0; this.succ=0; this.cooldownUntil=tick+15;
return {color:'orange',now:alt.label,note:'switching (best available score)',truth:groundTruth(alt)};
}
}
const truth=groundTruth(n);
if(tick<this.cooldownUntil) return {color:s>0.5?'green':'orange',now:n.label,note:'post-switch cooldown',truth};
if(s<0.6) return {color:'orange',now:n.label,note:`score ${s.toFixed(2)} (degraded)`,truth};
return {color:'green',now:n.label,note:`score ${s.toFixed(2)}`,truth};
}
},
{ key:'quorum', name:'Quorum (2 nodes + cross-check)', desc:'Queries 2 nodes in parallel, requires a confirmed broadcast + matching heights. Catches liars and stale nodes.', timeoutMs:4000,
init(){ this.scores={}; nodes.forEach(n=>this.scores[n.id]=1); this.log=[]; this.switchCount=0; this.top2Ids=[]; },
evaluate(){
nodes.forEach(n=>{ if(!(n.id in this.scores)) this.scores[n.id]=0.7; });
if(nodes.length===0){ this.top2Ids=[]; return {color:'red',now:'no node',note:'—',truth:false}; }
const ranked=[...nodes].sort((a,b)=>(this.scores[b.id]??0)-(this.scores[a.id]??0));
// sticky selection: only replace a queried node for a challenger that is clearly better
// (a small score-noise margin would otherwise "switch" every tick on near-ties)
let top2=this.top2Ids.map(id=>nodes.find(n=>n.id===id)).filter(Boolean);
if(top2.length<2){
top2=ranked.slice(0,2);
} else {
const outsiders=ranked.filter(n=>!top2.some(t=>t.id===n.id));
const weakest=top2.reduce((a,b)=>(this.scores[a.id]??0)<=(this.scores[b.id]??0)?a:b);
const bestOutsider=outsiders[0];
if(bestOutsider && (this.scores[bestOutsider.id]??0) > (this.scores[weakest.id]??0)+0.08){
top2=top2.filter(t=>t.id!==weakest.id).concat(bestOutsider);
}
}
const top2key=top2.map(n=>n.id).sort().join(',');
const prevKey=this.top2Ids.slice().sort().join(',');
if(this.top2Ids.length && prevKey!==top2key) this.switchCount++;
this.top2Ids=top2.map(n=>n.id);
const results=top2.map(n=>({n,c:checkNode(n,this.timeoutMs)}));
results.forEach(r=>{
const good=r.c.ok&&r.c.functional;
this.scores[r.n.id]=0.85*(this.scores[r.n.id]??0.7)+0.15*(good?1:0);
});
const trust=results.filter(r=>r.c.ok&&r.c.functional&&r.c.broadcastOk);
const now=top2.map(n=>n.label).join(' + ');
const truth=top2.some(n=>groundTruth(n));
if(trust.length===0){
pushLog(this,`⚠ neither of ${top2.length} queried nodes is trustworthy`);
return {color:'red',now,note:'quorum not satisfied',truth};
}
if(trust.length===2){
const [a,b]=trust;
if(Math.abs(a.c.height-b.c.height)>20){
pushLog(this,`⚠ height mismatch between ${a.n.label} and ${b.n.label}`);
return {color:'orange',now,note:'height mismatch — verifying',truth};
}
return {color:'green',now,note:'2/2 confirmed, heights match',truth};
}
return {color:'green',now,note:'1/2 confirmed (minimum quorum)',truth};
}
},
];
function initMethodStats(){ METHODS.forEach(m=>{ m.stats={ticks:0,green:0,orange:0,red:0,falseGreen:0,falseRed:0}; }); }
METHODS.forEach(m=>m.init());
initMethodStats();
/* ============================= IMPLEMENTATION SKETCHES ============================= */
const IMPL_CODE={
none:
`// "None" — no failover logic at all.
// Baseline anti-pattern: shows what a wallet with zero
// resiliency logic looks like. Node is picked once, never re-checked.
class NoFailover {
constructor(node) { this.node = node; }
async isUsable() {
return true; // never re-evaluated, never switches
}
}`,
binary:
`// Binary (CakeWallet-style) — naive, no hysteresis.
// Switches on the very FIRST transport failure. Never checks
// whether the node is functionally healthy (get_height / broadcast).
// This is the exact behavior the forum thread flagged as too twitchy.
class BinaryFailover {
constructor(nodePool) {
this.pool = nodePool;
this.current = nodePool[0];
}
async healthCheck() {
try {
await rpc.ping(this.current, { timeoutMs: 1500 }); // transport only
return true;
} catch {
return false;
}
}
async tick() {
if (!(await this.healthCheck())) {
this.current = this.pool.next(this.current); // instant switch
wallet.setActiveNode(this.current);
}
}
}`,
hyst:
`// Hysteresis + functional check.
// Requires N consecutive failures before declaring a node down,
// M consecutive successes before trusting it again, plus a cooldown
// so a fresh switch can't immediately trigger another one.
class HysteresisFailover {
constructor(nodePool, { failThreshold = 3, cooldownMs = 15000 } = {}) {
this.pool = nodePool;
this.current = nodePool[0];
this.failCount = 0;
this.cooldownUntil = 0;
this.failThreshold = failThreshold;
this.cooldownMs = cooldownMs;
}
async functionalCheck() {
try {
const { height } = await rpc.getHeight(this.current, { timeoutMs: 3000 });
return height > 0; // stub — real code also sanity-checks vs. peers
} catch {
return false;
}
}
async tick() {
const ok = await this.functionalCheck();
this.failCount = ok ? 0 : this.failCount + 1;
const now = Date.now();
if (!ok && this.failCount >= this.failThreshold && now >= this.cooldownUntil) {
this.current = this.pool.next(this.current);
wallet.setActiveNode(this.current);
this.failCount = 0;
this.cooldownUntil = now + this.cooldownMs;
}
}
}`,
score:
`// EWMA score + sticky selection.
// Every candidate node gets a rolling score from functional
// success + latency. Only switches when the CURRENT node's score
// truly collapses — never for a marginal ranking change (this is
// what stops near-tied scores from causing switch-count inflation).
class ScoreFailover {
constructor(nodePool, { alpha = 0.15, failThreshold = 3, cooldownMs = 15000 } = {}) {
this.pool = nodePool;
this.scores = new Map(nodePool.map(n => [n.id, 1]));
this.current = nodePool[0];
this.alpha = alpha;
this.failCount = 0;
this.failThreshold = failThreshold;
this.cooldownUntil = 0;
this.cooldownMs = cooldownMs;
}
async probe(node) {
const t0 = Date.now();
try {
await rpc.getHeight(node, { timeoutMs: 3000 });
const latencyPenalty = clamp((Date.now() - t0 - 200) / 4000, 0, 0.5);
return 1 - latencyPenalty;
} catch {
return 0; // failed probe
}
}
async tick() {
for (const node of this.pool) { // cheap background pings
const obs = await this.probe(node);
const prev = this.scores.get(node.id) ?? 0.7;
this.scores.set(node.id, (1 - this.alpha) * prev + this.alpha * obs);
}
const currentScore = this.scores.get(this.current.id);
this.failCount = currentScore < 0.35 ? this.failCount + 1 : 0;
const now = Date.now();
if (this.failCount >= this.failThreshold && now >= this.cooldownUntil) {
const best = [...this.pool]
.filter(n => n.id !== this.current.id)
.sort((a, b) => this.scores.get(b.id) - this.scores.get(a.id))[0];
if (best) {
this.current = best;
wallet.setActiveNode(best);
this.failCount = 0;
this.cooldownUntil = now + this.cooldownMs;
}
}
}
}`,
quorum:
`// Quorum (2 nodes + cross-check).
// Queries the top-2 ranked nodes in parallel, requires at least one
// trustworthy response, and cross-checks reported chain height to
// catch a single lying or stale node. Inspired by ethers.js FallbackProvider.
class QuorumFailover {
constructor(nodePool, { heightToleranceBlocks = 20 } = {}) {
this.pool = nodePool;
this.scores = new Map(nodePool.map(n => [n.id, 1]));
this.top2 = nodePool.slice(0, 2); // sticky selection —
this.tolerance = heightToleranceBlocks; // see "score" for the pattern
}
rankedPool() {
return [...this.pool].sort((a, b) => this.scores.get(b.id) - this.scores.get(a.id));
}
async queryOne(node) {
try {
const { height, broadcastOk } = await rpc.getHeight(node, { timeoutMs: 4000 });
return { node, ok: true, broadcastOk, height };
} catch {
return { node, ok: false };
}
}
async tick() {
this.top2 = this.rankedPool().slice(0, 2); // real code: sticky w/ margin
const results = await Promise.all(this.top2.map(n => this.queryOne(n)));
results.forEach(r => {
const prev = this.scores.get(r.node.id) ?? 0.7;
this.scores.set(r.node.id, 0.85 * prev + 0.15 * (r.ok && r.broadcastOk ? 1 : 0));
});
const trusted = results.filter(r => r.ok && r.broadcastOk);
if (trusted.length === 0) return { status: 'red' }; // no quorum
if (trusted.length === 2) {
const [a, b] = trusted;
if (Math.abs(a.height - b.height) > this.tolerance) {
return { status: 'orange', reason: 'height mismatch — re-querying' };
}
}
return { status: 'green', height: trusted[0].height };
}
}`,
};
function escapeHtml(s){ return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); }
function highlightKw(s){
return s.replace(/\b(class|const|let|async|await|function|return|if|else|new|this|throw|try|catch|for|of|extends|constructor)\b/g,'<span class="kw">$1</span>');
}
function highlightCode(code){
return escapeHtml(code).split('\n').map(line=>{
const idx=line.indexOf('//');
if(idx===-1) return highlightKw(line);
return highlightKw(line.slice(0,idx))+'<span class="cm">'+line.slice(idx)+'</span>';
}).join('\n');
}
function renderImplPicker(){
const wrap=$('#implpicker');
wrap.innerHTML=METHODS.map(m=>`<button data-key="${m.key}">${m.name}</button>`).join('');
wrap.querySelectorAll('button').forEach(b=>b.addEventListener('click',()=>{
wrap.querySelectorAll('button').forEach(x=>x.classList.remove('active'));
b.classList.add('active');
const code=IMPL_CODE[b.dataset.key]||'// no sketch available for this method';
$('#implcode').innerHTML='<code>'+highlightCode(code)+'</code>';
}));
}
/* ============================= RENDERING ============================= */
function renderNodes(){
const grid=$('#nodegrid');
if(nodes.length===0){ grid.innerHTML='<div class="empty">No nodes — add one above.</div>'; return; }
grid.innerHTML=nodes.map(n=>{
const flagList=Object.entries(n.flags).filter(([,v])=>v).map(([k])=>{
const bad=['hashvaulted','liar','offline'].includes(k);
const names={hashvaulted:'Hashvault\'d',flapping:'Flapping',saturated:'Saturated',stale:'Stale',liar:'Liar',latencySpike:'Latency spike',offline:'Offline'};
return `<span class="flag ${bad?'bad':''}">${names[k]}</span>`;
}).join('');
return `<div class="nodecard">
<div class="idblock">
<div class="type">${n.type==='tor'?'🥴 Tor':'🌐 Clearnet'} — ${n.label}</div>
<div class="addr">${n.addr}</div>
</div>
<div class="dots">
<div class="dotline"><div class="dot ${n.transport?'on':'off'}"></div><span>transport</span></div>
<div class="dotline"><div class="dot ${n.functional?'on':'off'}"></div><span>functional</span></div>
<div class="dotline"><div class="dot ${n.broadcastOk?'on':'off'}"></div><span>broadcast</span></div>
</div>
<div class="lat">latency ~${Math.round(n.latency||n.baseLatency)}ms · h=${n.height}</div>
<div class="flags">${flagList}</div>
<button class="rm" data-id="${n.id}" title="Remove">✕</button>
</div>`;
}).join('');
grid.querySelectorAll('.rm').forEach(b=>b.addEventListener('click',e=>{
nodes=nodes.filter(n=>n.id!==e.currentTarget.dataset.id); renderNodes();
}));
}
function renderMethods(){
const grid=$('#methodgrid');
grid.innerHTML=METHODS.map(m=>`
<div class="methodcard ${m.exp?'exp':''}">
<div class="mtitle"><b>${m.name}</b><span class="now" id="now-${m.key}"></span></div>
<div class="mdesc">${m.desc}</div>
<div class="light"><div class="bulb" id="bulb-${m.key}"></div></div>
<div class="mstat"><span>Status</span><b id="note-${m.key}">—</b></div>
<div class="truthflag" id="truth-${m.key}"></div>
<div class="log" id="log-${m.key}"></div>
</div>
`).join('') + `
<div class="methodcard dropped">
<div class="mtitle"><b>Phi-accrual</b></div>
<div class="mdesc">Method dropped — not practical in practice, and it produced no useful results in our tests (needs a history a short wallet session never has time to build).</div>
</div>
`;
}
function renderEvents(){
$('#events').innerHTML='';
EVENTS.forEach(ev=>{
const b=document.createElement('button');
b.textContent=ev.label; b.className='warn';
b.addEventListener('click',()=>{ if(nodes.length) ev.fn(); renderNodes(); });
$('#events').appendChild(b);
});
}
function renderLegend(){
$('#legend').innerHTML=`
<div class="row"><b>🟢 Green</b> = connected and operational, as far as THIS method is able to verify.</div>
<div class="row"><b>🟠 Orange</b> = switching in progress, degradation being observed, or "warming up" (not enough history yet).</div>
<div class="row"><b>🔴 Red</b> = no trustworthy node found by this method.</div>
<div class="row"><b>Red ring around a green bulb</b> = "false green" — the method believes it's fine, but the node it's using is not actually working right now. This is the omniscient-observer view the simulator gives you; a real wallet (and its user) cannot see this ring, which is exactly the danger it illustrates.</div>
<div class="row"><b>Malicious nodes:</b> you cannot stop a node from lying (it controls its own response), but you can limit the damage by cross-checking several sources (see the Quorum method) instead of trusting a single node for a critical operation.</div>
`;
}
function mean(arr){ return arr.reduce((a,b)=>a+b,0)/arr.length; }
function stdev(arr){ const m=mean(arr); return Math.sqrt(mean(arr.map(x=>(x-m)*(x-m)))); }
function buildSessionSummary(){
const summary={ timestamp:Date.now(), targetSec: parseInt($('#sessionTarget').value,10), methods:{} };
METHODS.forEach(m=>{
const s=m.stats;
const ticks=Math.max(s.ticks,1);
const uptimePct=s.green/ticks*100;
const falseGreenPct=s.falseGreen/ticks*100;
const switchesPerMin=m.switchCount/(ticks/60);
const score=clamp(uptimePct - falseGreenPct*3 - switchesPerMin*2, 0, 100);
summary.methods[m.key]={name:m.name, uptimePct, falseGreenPct, switches:m.switchCount, score};
});
return summary;
}
function renderReport(){
const latestBox=$('#reportLatest');
const histBox=$('#reportHistory');
if(runHistory.length===0){
latestBox.innerHTML='<div class="empty">No completed session yet — pick a timed session length above and let it run to the end (or wait for the current one to finish).</div>';
histBox.innerHTML='';
return;
}
const latest=runHistory[runHistory.length-1];
const rows=Object.values(latest.methods).sort((a,b)=>b.score-a.score);
const bestScore=rows[0].score, worstScore=rows[rows.length-1].score;
latestBox.innerHTML=`<div class="reportbox">
<h3>Latest run (${fmtDuration(latest.targetSec)} session)</h3>
<table class="rep"><thead><tr><th>Method</th><th>Score</th><th>Uptime (green)</th><th>Silent false-green</th><th>Switches</th></tr></thead>
<tbody>${rows.map(r=>`<tr class="${r.score===bestScore?'best':(r.score===worstScore?'worst':'')}">
<td>${r.name}</td><td>${r.score.toFixed(0)}</td><td>${r.uptimePct.toFixed(0)}%</td><td>${r.falseGreenPct.toFixed(1)}%</td><td>${r.switches}</td>
</tr>`).join('')}</tbody></table>
<p class="subnote">Score = time spent correctly green, minus a heavy penalty for "false green" (looked fine but the operation would actually have failed), minus a penalty for excessive switching. 0–100, higher is better.</p>
</div>`;
const byMethod={};
METHODS.forEach(m=>{ byMethod[m.key]={name:m.name, scores:[]}; });
runHistory.forEach(run=>{
Object.entries(run.methods).forEach(([key,v])=>{ if(byMethod[key]) byMethod[key].scores.push(v.score); });
});
const agg=Object.values(byMethod).filter(x=>x.scores.length>0).map(x=>({
name:x.name, runs:x.scores.length, m:mean(x.scores), sd:stdev(x.scores),
best:Math.max(...x.scores), worst:Math.min(...x.scores)
})).sort((a,b)=>b.m-a.m);
const champion=agg[0]?.name;
histBox.innerHTML=`<div class="reportbox">
<h3>History across ${runHistory.length} run${runHistory.length>1?'s':''}</h3>
<table class="rep"><thead><tr><th>Method</th><th>Runs</th><th>Mean score</th><th>Std dev</th><th>Best</th><th>Worst</th></tr></thead>
<tbody>${agg.map(a=>`<tr class="${a.name===champion?'champion':''}">
<td>${a.name===champion?'🏆 ':''}${a.name}</td><td>${a.runs}</td><td>${a.m.toFixed(0)}</td><td>${a.sd.toFixed(1)}</td><td>${a.best.toFixed(0)}</td><td>${a.worst.toFixed(0)}</td>
</tr>`).join('')}</tbody></table>
<p class="subnote">Ranked by mean score (higher = least-bad overall). Std dev shows consistency — a low value means the method behaves predictably run after run; a high value means it is sometimes great and sometimes terrible.</p>
<button id="btnClearHistory" class="danger">Clear history</button>
</div>`;
$('#btnClearHistory').addEventListener('click',()=>{ runHistory=[]; renderReport(); });
}
/* ============================= MAIN LOOP ============================= */
function endSession(){
sessionEnded=true;
pause();
runHistory.push(buildSessionSummary());
renderReport();
$('#btnPlay').disabled=true;
$('#btnPlay').textContent='Session complete — Reset to run again';
}
function tickAll(){
tick++;
nodes.forEach(stepNode);
renderNodes();
METHODS.forEach(m=>{
const r=m.evaluate();
const bulb=$('#bulb-'+m.key);
const isFalseGreen = r.color==='green' && !r.truth;
const isFalseRed = r.color==='red' && r.truth;
bulb.className='bulb '+r.color+(isFalseGreen?' fp':'');
$('#now-'+m.key).textContent=r.now?('→ '+r.now):'';
$('#note-'+m.key).innerHTML=r.note||'';
const truthEl=$('#truth-'+m.key);
if(truthEl){
if(isFalseGreen) truthEl.innerHTML='⚠ FALSE GREEN — not actually working right now';
else if(isFalseRed) truthEl.innerHTML='cautious red — would actually have worked';
else truthEl.innerHTML='';
truthEl.className='truthflag'+(isFalseGreen?' danger':(isFalseRed?' caution':''));
}
$('#log-'+m.key).innerHTML=(m.log||[]).map(l=>`<div>${l}</div>`).join('');
const s=m.stats;
s.ticks++;
if(r.color==='green') s.green++; else if(r.color==='orange') s.orange++; else s.red++;
if(isFalseGreen) s.falseGreen++;
if(isFalseRed) s.falseRed++;
});
const target=parseInt($('#sessionTarget').value,10);
const banner=$('#banner');
if(target>0){
const pct=clamp(tick/target*100,0,100);
$('#progressFill').style.width=pct+'%';
if(tick>=target && !sessionEnded){
banner.textContent=`Realistic session length (${fmtDuration(target)}) reached — that's the real time actually available for a method to prove itself before the app is closed.`;
banner.classList.add('show');
endSession();
}
} else {
$('#progressFill').style.width='0%';
}
$('#clock').textContent=`T+ ${fmtClock(tick)} simulated — ${nodes.length} node(s) — ${nodes.filter(n=>n.transport).length} up`;
}
/* ============================= TRANSPORT CONTROLS ============================= */
function play(){
if(running || sessionEnded) return;
running=true; $('#btnPlay').textContent='❚❚ Pause';
const speed=()=>parseInt($('#speed').value,10);
timer=setInterval(()=>{
for(let i=0;i<speed();i++){ if(sessionEnded) break; tickAll(); }
}, TICK_MS);
}
function pause(){
running=false;
if(!sessionEnded){ $('#btnPlay').textContent='► Resume'; }
clearInterval(timer);
}
function reset(){
pause();
tick=0; sessionEnded=false; clearCounter=1; torCounter=1;
$('#banner').classList.remove('show');
$('#reopenInfo').textContent='';
initNodes();
METHODS.forEach(m=>m.init());
initMethodStats();
renderNodes(); renderMethods();
$('#clock').textContent='T+ 00:00 simulated — 4 nodes active';
$('#progressFill').style.width='0%';
$('#btnPlay').disabled=false; $('#btnPlay').textContent='► Start';
}
function reopenApp(){
pause();
const gapSec=parseInt($('#gapSelect').value,10);
const persist=$('#persistToggle').checked;
const churnProb=clamp(gapSec/(2*365*86400),0,0.6);
let removed=0, totalBefore=nodes.length;
nodes=nodes.filter(n=>{ if(Math.random()<churnProb){ removed++; return false; } return true; });
nodes.forEach(n=>{
Object.keys(n.flags).forEach(f=>{ n.flags[f]=false; });
n.transport=true; n.functional=true; n.broadcastOk=true;
});
const stale=gapSec>=STALE_THRESHOLD_SEC;
let stateNote;
if(!persist){
METHODS.forEach(m=>m.init());
stateNote='method state reset (persistence is off)';
} else if(stale){
METHODS.forEach(m=>m.init());
stateNote='method state reset (gap too long — old history is no longer trustworthy)';
} else {
METHODS.forEach(m=>{ if(m.currentId && !nodes.find(n=>n.id===m.currentId)){ m.currentId=nodes[0]?.id||null; } });
stateNote='method state kept (short gap — history is still considered valid)';
}
initMethodStats();
tick=0; sessionEnded=false;
$('#banner').classList.remove('show');
$('#progressFill').style.width='0%';
renderNodes(); renderMethods();
$('#btnPlay').disabled=false; $('#btnPlay').textContent='► Start';
const gapLabel=$('#gapSelect').selectedOptions[0].textContent;
$('#reopenInfo').textContent=`Reopened after ${gapLabel}: ${removed} of ${totalBefore} node(s) disappeared. ${stateNote}.`;
$('#clock').textContent=`T+ 00:00 simulated — ${nodes.length} node(s) active`;
}
$('#btnPlay').addEventListener('click',()=>running?pause():play());
$('#btnReset').addEventListener('click',reset);
$('#btnReopen').addEventListener('click',reopenApp);
$('#addClear').addEventListener('click',()=>{ if(nodes.length<10){ nodes.push(newNode('clear')); renderNodes(); } });
$('#addTor').addEventListener('click',()=>{ if(nodes.length<10){ nodes.push(newNode('tor')); renderNodes(); } });
/* ============================= INIT ============================= */
initNodes();
renderNodes();
renderMethods();
renderEvents();
renderLegend();
renderReport();
renderImplPicker();
</script>
</body>
</html>