-
Notifications
You must be signed in to change notification settings - Fork 10
/
main.go
1455 lines (1298 loc) · 56.9 KB
/
main.go
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
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"encoding/csv"
"encoding/json"
"fmt"
"io/ioutil"
"math/rand"
"os"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/iotaledger/multivers-simulation/adversary"
"github.com/iotaledger/multivers-simulation/simulation"
"github.com/iotaledger/multivers-simulation/singlenodeattacks"
"github.com/iotaledger/hive.go/events"
"github.com/iotaledger/hive.go/types"
"github.com/iotaledger/hive.go/typeutils"
"github.com/iotaledger/multivers-simulation/config"
"github.com/iotaledger/multivers-simulation/logger"
"github.com/iotaledger/multivers-simulation/multiverse"
"github.com/iotaledger/multivers-simulation/network"
)
var (
log = logger.New("Simulation")
// csv
awHeader = []string{"Message ID", "Issuance Time (unix)", "Confirmation Time (ns)", "Weight", "# of Confirmed Messages",
"# of Issued Messages", "ns since start"}
wwHeader = []string{"Witness Weight", "Time (ns)"}
dsHeader = []string{"UndefinedColor", "Blue", "Red", "Green", "ns since start", "ns since issuance"}
mmHeader = []string{"Number of Requested Messages", "ns since start"}
tpHeader = []string{"UndefinedColor (Tip Pool Size)", "Blue (Tip Pool Size)", "Red (Tip Pool Size)", "Green (Tip Pool Size)",
"UndefinedColor (Processed)", "Blue (Processed)", "Red (Processed)", "Green (Processed)", "# of Issued Messages", "ns since start"}
ccHeader = []string{"Blue (Confirmed)", "Red (Confirmed)", "Green (Confirmed)",
"Blue (Adversary Confirmed)", "Red (Adversary Confirmed)", "Green (Adversary Confirmed)",
"Blue (Confirmed Accumulated Weight)", "Red (Confirmed Accumulated Weight)", "Green (Confirmed Accumulated Weight)",
"Blue (Confirmed Adversary Weight)", "Red (Confirmed Adversary Weight)", "Green (Confirmed Adversary Weight)",
"Blue (Like)", "Red (Like)", "Green (Like)",
"Blue (Like Accumulated Weight)", "Red (Like Accumulated Weight)", "Green (Like Accumulated Weight)",
"Blue (Adversary Like Accumulated Weight)", "Red (Adversary Like Accumulated Weight)", "Green (Adversary Like Accumulated Weight)",
"Unconfirmed Blue", "Unconfirmed Red", "Unconfirmed Green",
"Unconfirmed Blue Accumulated Weight", "Unconfirmed Red Accumulated Weight", "Unconfirmed Green Accumulated Weight",
"Flips (Winning color changed)", "Honest nodes Flips", "ns since start", "ns since issuance"}
adHeader = []string{"AdversaryGroupID", "Strategy", "AdversaryCount", "q", "ns since issuance"}
ndHeader = []string{"Node ID", "Adversary", "Min Confirmed Accumulated Weight", "Unconfirmation Count"}
csvMutex sync.Mutex
// simulation variables
globalMetricsTicker = time.NewTicker(time.Duration(config.Params.SlowdownFactor*config.Params.ConsensusMonitorTick) * time.Millisecond)
simulationWg = sync.WaitGroup{}
shutdownSignal = make(chan types.Empty)
// global declarations
dsIssuanceTime time.Time
mostLikedColor multiverse.Color
honestOnlyMostLikedColor multiverse.Color
simulationStartTime time.Time
// MetricsMgr *simulation.MetricsManager
// counters
colorCounters = simulation.NewColorCounters()
adversaryCounters = simulation.NewColorCounters()
nodeCounters = []simulation.AtomicCounters[string, int64]{}
atomicCounters = simulation.NewAtomicCounters[string, int64]()
confirmedMessageCounter = make(map[network.PeerID]int64)
storedMessageMap = make(map[multiverse.MessageID]int)
storedMessages = make(map[multiverse.MessageID]*multiverse.Message)
storedMessageMutex sync.RWMutex
disseminatedMessageCounter = make([]int64, config.Params.NodesCount)
undisseminatedMessageCounter = make([]int64, config.Params.NodesCount)
disseminatedMessageMutex sync.RWMutex
disseminatedMessages = make(map[multiverse.MessageID]*multiverse.Message)
disseminatedMessageMetadata = make(map[multiverse.MessageID]*multiverse.MessageMetadata)
confirmedMessageMutex sync.RWMutex
confirmedMessageMap = make(map[multiverse.MessageID]int)
firstConfirmedTimeMap = make(map[multiverse.MessageID]time.Time)
confirmedDelayInNetworkMap = make(map[multiverse.MessageID]time.Duration)
confirmedDelayInNetworkMutex sync.Mutex
fullyConfirmedMessageCounter = make([]int64, config.Params.NodesCount)
fullyConfirmedMessages = make(map[multiverse.MessageID]*multiverse.Message)
fullyConfirmedMessageMetadata = make(map[multiverse.MessageID]*multiverse.MessageMetadata)
partiallyConfirmedMessageCounter = make([]int64, config.Params.NodesCount)
unconfirmedMessageCounter = make([]int64, config.Params.NodesCount)
shutdownGlobalMetrics = make(chan struct{})
localMetrics = make(map[string]map[network.PeerID]float64)
localResultsWriters = make(map[string]*csv.Writer)
localMetricsMutex sync.RWMutex
)
func main() {
log.Info("Starting simulation ... [DONE]")
defer log.Info("Shutting down simulation ... [DONE]")
simulation.ParseFlags()
nodeFactories := map[network.AdversaryType]network.NodeFactory{
network.HonestNode: network.NodeClosure(multiverse.NewNode),
network.ShiftOpinion: network.NodeClosure(adversary.NewShiftingOpinionNode),
network.TheSameOpinion: network.NodeClosure(adversary.NewSameOpinionNode),
network.NoGossip: network.NodeClosure(adversary.NewNoGossipNode),
network.Blowball: network.NodeClosure(singlenodeattacks.NewBlowballNode),
}
// The simulation start time
simulationStartTime = time.Now()
testNetwork := network.New(
network.Nodes(config.Params.NodesCount,
nodeFactories,
network.ZIPFDistribution(config.Params.ZipfParameter),
network.MixedZIPFDistribution(config.Params.ZipfParameter)),
network.Delay(time.Duration(config.Params.SlowdownFactor)*time.Duration(config.Params.MinDelay)*time.Millisecond,
time.Duration(config.Params.SlowdownFactor)*time.Duration(config.Params.MaxDelay)*time.Millisecond),
network.PacketLoss(config.Params.PacketLoss, config.Params.PacketLoss),
network.Topology(network.WattsStrogatz(config.Params.NeighbourCountWS, config.Params.RandomnessWS)),
network.AdversaryPeeringAll(config.Params.AdversaryPeeringAll),
network.AdversarySpeedup(config.Params.AdversarySpeedup),
network.GenesisTime(simulationStartTime),
)
// MetricsMgr = simulation.NewMetricsManager()
// MetricsMgr.Setup(testNetwork)
monitorNetworkState(testNetwork)
// MetricsMgr.StartMetricsCollection()
// The simulation start time
simulationStartTime = time.Now()
// Dump the configuration of this simulation
dumpConfig(path.Join(config.Params.ResultDir, config.Params.ScriptStartTimeStr, "mb.config"))
// Dump the network information
dumpNetworkConfig(testNetwork)
// Start monitoring global metrics
monitorGlobalMetrics(testNetwork)
// start a go routine for each node to start issuing messages
startIssuingMessages(testNetwork)
// start a go routine for each node to start processing messages received from nieghbours and scheduling.
startProcessingMessages(testNetwork)
// To simulate the confirmation time w/o any double spending, the colored msgs are not to be sent
if config.Params.SimulationTarget == "DS" {
SimulateDoubleSpent(testNetwork)
}
select {
case <-shutdownSignal:
shutdownSimulation(testNetwork)
log.Info("Shutting down simulation (consensus reached) ... [DONE]")
case <-time.After(time.Duration(config.Params.SlowdownFactor) * config.Params.SimulationDuration):
fmt.Println(">>>>>>>>>>>>>.Simulation timed out")
shutdownSimulation(testNetwork)
log.Info("Shutting down simulation (simulation timed out) ... [DONE]")
}
}
func startProcessingMessages(n *network.Network) {
for _, peer := range n.Peers {
// The Blowball attacker does not need to process the message
// TODO: Also disable `processMessages` for other attackers which do not require it.
// todo not sure if processing message should be disabled, as node needs to have complete tangle to walk
if !(config.Params.SimulationMode == "Blowball" &&
network.IsAttacker(int(peer.ID))) {
go processMessages(peer)
}
}
}
func processMessages(peer *network.Peer) {
// simulationWg.Add(1)
// defer simulationWg.Done()
pace := time.Duration((float64(time.Second) * float64(config.Params.SlowdownFactor)) / float64(config.Params.SchedulingRate))
ticker := time.NewTicker(pace)
defer ticker.Stop()
validatorPace := time.Duration((float64(time.Second) * float64(config.Params.SlowdownFactor)) / float64(config.Params.ValidatorBPS))
validatorTicker := time.NewTicker(validatorPace)
defer validatorTicker.Stop()
for {
select {
case <-peer.ShutdownProcessing:
log.Warn("Shutting down processing for peer", peer.ID)
return
case networkMessage := <-peer.Socket:
peer.Node.HandleNetworkMessage(networkMessage) // this includes payloads from the node itself so block are created here
case <-ticker.C:
// Trigger the scheduler to pop messages and gossip them
peer.Node.(multiverse.NodeInterface).Tangle().Scheduler.IncrementAccessMana(float64(config.Params.SchedulingRate))
peer.Node.(multiverse.NodeInterface).Tangle().Scheduler.ScheduleMessage()
monitorLocalMetrics(peer)
case <-validatorTicker.C:
if int(peer.ID) <= config.Params.ValidatorCount {
if message, ok := peer.Node.(multiverse.NodeInterface).Tangle().MessageFactory.CreateMessage(true, multiverse.UndefinedColor); ok {
peer.Node.(multiverse.NodeInterface).Tangle().ProcessMessage(message)
}
}
}
}
}
func SimulateAdversarialBehaviour(testNetwork *network.Network) {
switch config.Params.SimulationMode {
case "Accidental":
for i, node := range network.GetAccidentalIssuers(testNetwork) {
color := multiverse.ColorFromInt(i + 1)
go sendMessage(node, color)
log.Infof("Peer %d sent double spend msg: %v", node.ID, color)
}
// todo adversary should be renamed to doublespend
case "Adversary":
time.Sleep(time.Duration(config.Params.DoubleSpendDelay*config.Params.SlowdownFactor) * time.Second)
// Here we simulate the double spending
// MetricsMgr.SetDSIssuanceTime()
for _, group := range testNetwork.AdversaryGroups {
color := multiverse.ColorFromStr(group.InitColor)
for _, nodeID := range group.NodeIDs {
peer := testNetwork.Peer(nodeID)
// honest node does not implement adversary behavior interface
if group.AdversaryType != network.HonestNode {
node := adversary.CastAdversary(peer.Node)
node.AssignColor(color)
}
go sendMessage(peer, color)
log.Infof("Peer %d sent double spend msg: %v", peer.ID, color)
}
}
case "Blowball":
ticker := time.NewTicker(time.Duration(config.Params.SlowdownFactor*config.Params.BlowballDelay) * time.Second)
alreadySentCounter := 0
for {
if alreadySentCounter == config.Params.BlowballMaxSent {
ticker.Stop()
break
}
select {
case <-ticker.C:
for _, group := range testNetwork.AdversaryGroups {
for _, nodeID := range group.NodeIDs {
peer := testNetwork.Peer(nodeID)
go sendMessage(peer, multiverse.UndefinedColor)
alreadySentCounter++
}
}
}
}
}
}
func startIssuingMessages(testNetwork *network.Network) {
fmt.Println("totalWeight ", testNetwork.WeightDistribution.TotalWeight())
if testNetwork.WeightDistribution.TotalWeight() == 0 {
panic("total weight is 0")
}
nodeTotalWeight := float64(testNetwork.WeightDistribution.TotalWeight())
for _, peer := range testNetwork.Peers {
weightOfPeer := float64(testNetwork.WeightDistribution.Weight(peer.ID))
log.Warn("Peer ID Weight: ", peer.ID, weightOfPeer, nodeTotalWeight)
// MetricsMgr.GlobalCounters.Add("relevantValidators", 1)
// peer.AdversarySpeedup=1 for honest nodes and can have different values from adversary nodes
// band := peer.AdversarySpeedup * weightOfPeer * float64(config.Params.IssuingRate) / nodeTotalWeight
band := peer.AdversarySpeedup * float64(testNetwork.BandwidthDistribution.Bandwidth(peer.ID))
// log.Debugf("startIssuingMessages... Peer ID: %d, Bandwidth: %f", peer.ID, band)
// fmt.Println(peer.AdversarySpeedup, weightOfPeer, config.Params.IssuingRate, nodeTotalWeight)
//fmt.Printf("speedup %f band %f\n", peer.AdversarySpeedup, band)
go issueMessages(peer, band)
}
}
func issueMessages(peer *network.Peer, band float64) {
// simulationWg.Add(1)
// defer simulationWg.Done()
pace := time.Duration(float64(time.Second) * float64(config.Params.SlowdownFactor) / band)
if pace == time.Duration(0) {
log.Warn("Peer ID: ", peer.ID, " has 0 pace!")
return
}
ticker := time.NewTicker(pace)
congestionTicker := time.NewTicker(time.Duration(config.Params.SlowdownFactor) * config.Params.SimulationDuration / time.Duration(len(config.Params.CongestionPeriods)))
defer ticker.Stop()
defer congestionTicker.Stop()
band *= config.Params.CongestionPeriods[0]
i := 0
for {
select {
case <-peer.ShutdownIssuing:
log.Warn("Peer ID: ", peer.ID, " has been shutdown!")
return
case <-ticker.C:
if config.Params.IMIF == "poisson" {
pace = time.Duration(float64(time.Second) * float64(config.Params.SlowdownFactor) * rand.ExpFloat64() / band)
if pace > 0 {
ticker.Reset(pace)
}
}
// TODO: for attackers, they don't use the rate setter but will issue as many as blocks to fill up the network traffic
// and they will use higher-frequency ticker to issue more blocks
if peer.Node.(multiverse.NodeInterface).Tangle().Scheduler.RateSetter() {
sendMessage(peer)
}
case <-congestionTicker.C:
if i < len(config.Params.CongestionPeriods)-1 {
band *= config.Params.CongestionPeriods[i+1] / config.Params.CongestionPeriods[i]
i++
}
}
}
}
func sendMessage(peer *network.Peer, optionalColor ...multiverse.Color) {
//MetricsMgr.GlobalCounters.Add("tps", 1)
if len(optionalColor) >= 1 {
peer.Node.(multiverse.NodeInterface).IssuePayload(optionalColor[0])
}
peer.Node.(multiverse.NodeInterface).IssuePayload(multiverse.UndefinedColor)
}
func shutdownSimulation(net *network.Network) {
net.Shutdown()
close(shutdownGlobalMetrics)
dumpAcceptanceLatencyAmongNodes()
dumpFinalData(net)
simulationWg.Wait()
//dumpAllMessageMetaData(net.Peers[0].Node.(multiverse.NodeInterface).Tangle().Storage)
}
func monitorLocalMetrics(peer *network.Peer) {
localMetricsMutex.Lock()
defer localMetricsMutex.Unlock()
if len(localMetrics) != 0 {
localMetrics["Ready Lengths"][peer.ID] = float64(peer.Node.(multiverse.NodeInterface).Tangle().Scheduler.ReadyLen())
localMetrics["Non Ready Lengths"][peer.ID] = float64(peer.Node.(multiverse.NodeInterface).Tangle().Scheduler.NonReadyLen())
localMetrics["Own Mana"][peer.ID] = float64(peer.Node.(multiverse.NodeInterface).Tangle().Scheduler.GetNodeAccessMana(peer.ID))
localMetrics["Tips"][peer.ID] = float64(peer.Node.(multiverse.NodeInterface).Tangle().TipManager.TipSet(0).Size())
localMetrics["Price"][peer.ID] = float64(peer.Node.(multiverse.NodeInterface).Tangle().Scheduler.GetMaxManaBurn())
currentSlotIndex := peer.Node.(multiverse.NodeInterface).Tangle().Storage.SlotIndex(time.Now())
localMetrics["RMC"][peer.ID] = float64(peer.Node.(multiverse.NodeInterface).Tangle().Storage.RMC(currentSlotIndex))
localMetrics["Time since ATT"][peer.ID] = float64(time.Since(peer.Node.(multiverse.NodeInterface).Tangle().Storage.ATT).Seconds())
if peer.ID == 0 {
for i := 0; i < config.Params.NodesCount; i++ {
localMetrics["Mana at Node 0"][network.PeerID(i)] = float64(peer.Node.(multiverse.NodeInterface).Tangle().Scheduler.GetNodeAccessMana(network.PeerID(i)))
localMetrics["Issuer Queue Lengths at Node 0"][network.PeerID(i)] = float64(peer.Node.(multiverse.NodeInterface).Tangle().Scheduler.IssuerQueueLen(network.PeerID(i)))
localMetrics["Deficits at Node 0"][network.PeerID(i)] = float64(peer.Node.(multiverse.NodeInterface).Tangle().Scheduler.Deficit(network.PeerID(i)))
}
}
} else {
localMetrics["Ready Lengths"] = make(map[network.PeerID]float64)
localMetrics["Non Ready Lengths"] = make(map[network.PeerID]float64)
localMetrics["Own Mana"] = make(map[network.PeerID]float64)
localMetrics["Tips"] = make(map[network.PeerID]float64)
localMetrics["Price"] = make(map[network.PeerID]float64)
localMetrics["RMC"] = make(map[network.PeerID]float64)
localMetrics["Mana at Node 0"] = make(map[network.PeerID]float64)
localMetrics["Issuer Queue Lengths at Node 0"] = make(map[network.PeerID]float64)
localMetrics["Deficits at Node 0"] = make(map[network.PeerID]float64)
localMetrics["Time since ATT"] = make(map[network.PeerID]float64)
}
}
func dumpLocalMetrics() {
simulationWg.Add(1)
defer simulationWg.Done()
timeSinceStart := time.Since(simulationStartTime).Nanoseconds()
timeStr := strconv.FormatInt(timeSinceStart, 10)
localMetricsMutex.RLock()
defer localMetricsMutex.RUnlock()
for name := range localMetrics {
if _, exists := localResultsWriters[name]; !exists { // create the file and results writer if it doesn't already exist
lmHeader := make([]string, 0, config.Params.NodesCount+1)
for i := 0; i < config.Params.NodesCount; i++ {
header := []string{fmt.Sprintf("Node %d", i)}
lmHeader = append(lmHeader, header...)
}
header := []string{"ns since start"}
lmHeader = append(lmHeader, header...)
file, err := createFile(path.Join(config.Params.GeneralOutputDir, strings.Join([]string{name, ".csv"}, "")))
if err != nil {
panic(err)
}
localResultsWriters[name] = csv.NewWriter(file)
if err := localResultsWriters[name].Write(lmHeader); err != nil {
panic(err)
}
}
record := make([]string, config.Params.NodesCount+1)
for id := 0; id < config.Params.NodesCount; id++ {
record[id] = strconv.FormatFloat(localMetrics[name][network.PeerID(id)], 'f', 6, 64)
}
record[config.Params.NodesCount] = timeStr
if err := localResultsWriters[name].Write(record); err != nil {
panic(err)
}
localResultsWriters[name].Flush()
}
}
func dumpGlobalMetrics(dissemResultsWriter, undissemResultsWriter, confirmationResultsWriter, partialConfirmationResultsWriter, unconfirmationResultsWriter *csv.Writer) {
simulationWg.Add(1)
defer simulationWg.Done()
timeSinceStart := time.Since(simulationStartTime).Nanoseconds()
timeStr := strconv.FormatInt(timeSinceStart, 10)
log.Debug("Simulation Completion: ", int(100*float64(timeSinceStart)/(float64(config.Params.SlowdownFactor)*float64(config.Params.SimulationDuration))), "%")
disseminatedMessageMutex.RLock()
record := make([]string, config.Params.NodesCount+1)
for id := 0; id < config.Params.NodesCount; id++ {
record[id] = strconv.FormatInt(disseminatedMessageCounter[id], 10)
}
disseminatedMessageMutex.RUnlock()
//log.Debug("Disseminated Messages: ", record)
record[config.Params.NodesCount] = timeStr
if err := dissemResultsWriter.Write(record); err != nil {
panic(err)
}
disseminatedMessageMutex.RLock()
record = make([]string, config.Params.NodesCount+1)
for id := 0; id < config.Params.NodesCount; id++ {
record[id] = strconv.FormatInt(undisseminatedMessageCounter[id], 10)
}
disseminatedMessageMutex.RUnlock()
//log.Debug("Disseminated Messages: ", record)
record[config.Params.NodesCount] = timeStr
if err := undissemResultsWriter.Write(record); err != nil {
panic(err)
}
confirmedMessageMutex.RLock()
record = make([]string, config.Params.NodesCount+1)
for id := 0; id < config.Params.NodesCount; id++ {
record[id] = strconv.FormatInt(fullyConfirmedMessageCounter[id], 10)
}
confirmedMessageMutex.RUnlock()
//log.Debug("Confirmed Messages: ", record)
record[config.Params.NodesCount] = timeStr
if err := confirmationResultsWriter.Write(record); err != nil {
panic(err)
}
confirmedMessageMutex.RLock()
record = make([]string, config.Params.NodesCount+1)
for id := 0; id < config.Params.NodesCount; id++ {
record[id] = strconv.FormatInt(partiallyConfirmedMessageCounter[id], 10)
}
confirmedMessageMutex.RUnlock()
//log.Debug("Partially Confirmed Messages: ", record)
record[config.Params.NodesCount] = timeStr
if err := partialConfirmationResultsWriter.Write(record); err != nil {
panic(err)
}
confirmedMessageMutex.RLock()
record = make([]string, config.Params.NodesCount+1)
for id := 0; id < config.Params.NodesCount; id++ {
record[id] = strconv.FormatInt(unconfirmedMessageCounter[id], 10)
}
confirmedMessageMutex.RUnlock()
//log.Debug("Unconfirmed Messages: ", record)
record[config.Params.NodesCount] = timeStr
if err := unconfirmationResultsWriter.Write(record); err != nil {
panic(err)
}
// Flush the results writer to avoid truncation.
dissemResultsWriter.Flush()
undissemResultsWriter.Flush()
confirmationResultsWriter.Flush()
partialConfirmationResultsWriter.Flush()
unconfirmationResultsWriter.Flush()
}
func monitorGlobalMetrics(net *network.Network) {
// check for global network events such as dissemination and confirmation.
for id := 0; id < config.Params.NodesCount; id++ {
mbPeer := net.Peers[id]
if typeutils.IsInterfaceNil(mbPeer) {
panic(fmt.Sprintf("unknowm peer with id %d", id))
}
mbPeer.Node.(multiverse.NodeInterface).Tangle().Storage.Events.MessageStored.Attach(
events.NewClosure(func(messageID multiverse.MessageID, message *multiverse.Message, messageMetadata *multiverse.MessageMetadata) {
storedMessageMutex.Lock()
if numNodes, exists := storedMessageMap[messageID]; exists {
if numNodes > config.Params.NodesCount {
panic("message stored more than once per node")
}
storedMessageMap[messageID] = numNodes + 1
storedMessages[messageID] = message
} else {
storedMessageMap[messageID] = 1
confirmedMessageMutex.Lock()
unconfirmedMessageCounter[message.Issuer] += 1
confirmedMessageMutex.Unlock()
disseminatedMessageMutex.Lock()
undisseminatedMessageCounter[message.Issuer] += 1
disseminatedMessageMutex.Unlock()
}
// a message is disseminated if it has been stored by all nodes.
if storedMessageMap[messageID] == config.Params.NodesCount {
disseminatedMessageMutex.Lock()
disseminatedMessageCounter[message.Issuer] += 1
undisseminatedMessageCounter[message.Issuer] -= 1
disseminatedMessages[messageID] = message
//log.Debug("Mana Burn value: ", message.ManaBurnValue)
disseminatedMessageMetadata[messageID] = messageMetadata
disseminatedMessageMutex.Unlock()
}
storedMessageMutex.Unlock()
}))
mbPeer.Node.(multiverse.NodeInterface).Tangle().ApprovalManager.Events.MessageConfirmed.Attach(
events.NewClosure(func(message *multiverse.Message, messageMetadata *multiverse.MessageMetadata, weight uint64, messageIDCounter int64) {
confirmedMessageMutex.Lock()
defer confirmedMessageMutex.Unlock()
if numNodes, exists := confirmedMessageMap[message.ID]; exists {
if numNodes > config.Params.NodesCount {
panic("message confirmed more than once per node")
}
confirmedMessageMap[message.ID] = numNodes + 1
} else {
confirmedMessageMap[message.ID] = 1
partiallyConfirmedMessageCounter[message.Issuer] += 1
unconfirmedMessageCounter[message.Issuer] -= 1
}
// a message is disseminated if it has been confirmed by all nodes.
if confirmedMessageMap[message.ID] == config.Params.NodesCount {
partiallyConfirmedMessageCounter[message.Issuer] -= 1
fullyConfirmedMessageCounter[message.Issuer] += 1
fullyConfirmedMessages[message.ID] = message
fullyConfirmedMessageMetadata[message.ID] = messageMetadata
}
// The accepted time difference between the node which first accepted it and the last node which accepted it lastly
confirmedDelayInNetworkMutex.Lock()
defer confirmedDelayInNetworkMutex.Unlock()
if firstAcceptedTime, exists := firstConfirmedTimeMap[message.ID]; exists {
if confirmedMessageMap[message.ID] == config.Params.NodesCount {
confirmedDelayInNetworkMap[message.ID] = messageMetadata.ConfirmationTime().Sub(firstAcceptedTime)
delete(firstConfirmedTimeMap, message.ID)
}
} else {
firstConfirmedTimeMap[message.ID] = messageMetadata.ConfirmationTime()
}
}))
}
// define header with time of dump and each node ID
gmHeader := make([]string, 0, config.Params.NodesCount+1)
for i := 0; i < config.Params.NodesCount; i++ {
header := []string{fmt.Sprintf("Node %d", i)}
gmHeader = append(gmHeader, header...)
}
header := []string{"ns since start"}
gmHeader = append(gmHeader, header...)
// dissemination results
file, err := createFile(path.Join(config.Params.SchedulerOutputDir, "disseminatedMessages.csv"))
if err != nil {
panic(err)
}
dissemResultsWriter := csv.NewWriter(file)
if err := dissemResultsWriter.Write(gmHeader); err != nil {
panic(err)
}
file, err = createFile(path.Join(config.Params.SchedulerOutputDir, "undisseminatedMessages.csv"))
if err != nil {
panic(err)
}
undissemResultsWriter := csv.NewWriter(file)
if err := undissemResultsWriter.Write(gmHeader); err != nil {
panic(err)
}
// confirmination results
file, err = createFile(path.Join(config.Params.SchedulerOutputDir, "fullyConfirmedMessages.csv"))
if err != nil {
panic(err)
}
confirmationResultsWriter := csv.NewWriter(file)
if err := confirmationResultsWriter.Write(gmHeader); err != nil {
panic(err)
}
file, err = createFile(path.Join(config.Params.SchedulerOutputDir, "partiallyConfirmedMessages.csv"))
if err != nil {
panic(err)
}
partialConfirmationResultsWriter := csv.NewWriter(file)
if err := partialConfirmationResultsWriter.Write(gmHeader); err != nil {
panic(err)
}
file, err = createFile(path.Join(config.Params.SchedulerOutputDir, "unconfirmedMessages.csv"))
if err != nil {
panic(err)
}
unconfirmationResultsWriter := csv.NewWriter(file)
if err := unconfirmationResultsWriter.Write(gmHeader); err != nil {
panic(err)
}
go func() {
for {
select {
case <-globalMetricsTicker.C:
dumpLocalMetrics()
dumpGlobalMetrics(dissemResultsWriter,
undissemResultsWriter,
confirmationResultsWriter,
partialConfirmationResultsWriter,
unconfirmationResultsWriter)
case <-shutdownGlobalMetrics:
log.Warn("Shutting down global metrics")
return
}
}
}()
}
func dumpAcceptanceLatencyAmongNodes() {
// accepted time latency in network
file, err := createFile(path.Join(config.Params.GeneralOutputDir, "acceptanceTimeLatencyAmongNodes.csv"))
if err != nil {
panic(err)
}
header := []string{
"blockID",
"Accepted Time Diff",
}
writer := csv.NewWriter(file)
if err := writer.Write(header); err != nil {
panic(err)
}
writer.Flush()
record := make([]string, len(header))
confirmedDelayInNetworkMutex.Lock()
defer confirmedDelayInNetworkMutex.Unlock()
fmt.Println(len(confirmedDelayInNetworkMap))
// Extract blockIDs from confirmedDelayInNetworkMap into a slice of integers
var blockIDs []int
for blkID := range confirmedDelayInNetworkMap {
blockIDs = append(blockIDs, int(blkID))
}
// Sort the blockIDs in ascending order
sort.Ints(blockIDs)
// Iterate over sorted blockIDs and write data to CSV file
for _, blkID := range blockIDs {
timeDiffs := confirmedDelayInNetworkMap[multiverse.MessageID(blkID)]
record[0] = strconv.FormatInt(int64(blkID), 10)
record[1] = strconv.FormatInt(timeDiffs.Nanoseconds(), 10)
if err := writer.Write(record); err != nil {
panic(err)
}
writer.Flush()
}
}
func dumpFinalData(net *network.Network) {
file, err := createFile(path.Join(config.Params.GeneralOutputDir, "Traffic.csv"))
if err != nil {
panic(err)
}
header := []string{
"Slot ID",
"Blocks Count",
}
writer := csv.NewWriter(file)
if err := writer.Write(header); err != nil {
panic(err)
}
writer.Flush()
record := make([]string, len(header))
mbPeer := net.Peers[0]
traffic := mbPeer.Node.(multiverse.NodeInterface).Tangle().Storage.MessagesCountPerSlot()
// Extract slotIDs from traffic map into a slice of integers
var slotIDs []int
for slotID := range traffic {
slotIDs = append(slotIDs, int(slotID))
}
// Sort the slotIDs in ascending order
sort.Ints(slotIDs)
// Iterate over sorted slotIDs and write data to CSV file
for _, slotID := range slotIDs {
blockCount := traffic[multiverse.SlotIndex(slotID)]
record[0] = strconv.FormatInt(int64(slotID), 10)
record[1] = strconv.FormatInt(int64(blockCount), 10)
if err := writer.Write(record); err != nil {
panic(err)
}
writer.Flush()
}
file, err = createFile(path.Join(config.Params.GeneralOutputDir, "BlockInformation.csv"))
if err != nil {
panic(err)
}
// Message ID,Issuance Time (unix),Confirmation Time (ns),Weight,# of Confirmed Messages,# of Issued Messages,ns since start
header = []string{
"Issuer Burn Policy",
"Message ID",
"Issuance Time Since Start (ns)",
"Confirmation Time (ns)",
}
writer = csv.NewWriter(file)
if err := writer.Write(header); err != nil {
panic(err)
}
writer.Flush()
record = make([]string, len(header))
for messageID := range disseminatedMessages {
message := disseminatedMessages[messageID]
messageMetadata := disseminatedMessageMetadata[messageID]
record[0] = strconv.FormatInt(int64(config.Params.BurnPolicies[int(message.Issuer)]), 10)
record[1] = strconv.FormatInt(int64(message.ID), 10)
record[2] = strconv.FormatInt(message.IssuanceTime.Sub(simulationStartTime).Nanoseconds(), 10)
t := int64(messageMetadata.ConfirmationTime().Sub(message.IssuanceTime))
if t < 0 {
t = 0
}
record[3] = strconv.FormatInt(t, 10)
if err := writer.Write(record); err != nil {
panic(err)
}
delete(storedMessages, messageID)
writer.Flush()
}
for messageID := range storedMessages {
message := storedMessages[messageID]
record[0] = strconv.FormatInt(int64(config.Params.BurnPolicies[int(message.Issuer)]), 10)
record[1] = strconv.FormatInt(int64(message.ID), 10)
record[2] = strconv.FormatInt(message.IssuanceTime.Sub(simulationStartTime).Nanoseconds(), 10)
record[3] = strconv.FormatInt(0, 10)
if err := writer.Write(record); err != nil {
panic(err)
}
writer.Flush()
}
file, err = createFile(path.Join(config.Params.SchedulerOutputDir, "DisseminationLatency.csv"))
if err != nil {
panic(err)
}
header = []string{
"Issuer ID",
"Dissemination Time",
"Dissemination Latency",
}
writer = csv.NewWriter(file)
if err := writer.Write(header); err != nil {
panic(err)
}
writer.Flush()
record = make([]string, len(header))
for messageID := range disseminatedMessages {
message := disseminatedMessages[messageID]
messageMetadata := disseminatedMessageMetadata[messageID]
record[0] = strconv.FormatInt(int64(message.Issuer), 10)
record[1] = strconv.FormatInt(int64(messageMetadata.ArrivalTime().Sub(simulationStartTime).Nanoseconds()), 10)
record[2] = strconv.FormatInt(int64(messageMetadata.ArrivalTime().Sub(message.IssuanceTime).Nanoseconds()), 10)
if err := writer.Write(record); err != nil {
panic(err)
}
writer.Flush()
}
file, err = createFile(path.Join(config.Params.GeneralOutputDir, "ConfirmationLatency.csv"))
if err != nil {
panic(err)
}
header = []string{
"Issuer ID",
"Confirmation Time",
"Confirmation Latency",
}
writer = csv.NewWriter(file)
if err := writer.Write(header); err != nil {
panic(err)
}
writer.Flush()
for messageID := range fullyConfirmedMessages {
message := fullyConfirmedMessages[messageID]
messageMetadata := fullyConfirmedMessageMetadata[messageID]
record[0] = strconv.FormatInt(int64(message.Issuer), 10)
record[1] = strconv.FormatInt(int64(messageMetadata.ConfirmationTime().Sub(simulationStartTime).Nanoseconds()), 10)
record[2] = strconv.FormatInt(int64(messageMetadata.ConfirmationTime().Sub(message.IssuanceTime).Nanoseconds()), 10)
if err := writer.Write(record); err != nil {
panic(err)
}
writer.Flush()
}
file, err = createFile(path.Join(config.Params.GeneralOutputDir, "localMetrics.csv"))
if err != nil {
panic(err)
}
writer = csv.NewWriter(file)
for name := range localMetrics {
if err := writer.Write([]string{name}); err != nil {
panic(err)
}
}
writer.Flush()
}
func dumpFinalRecorder() {
fileName := fmt.Sprint("nd-", config.Params.ScriptStartTimeStr, ".csv")
file, err := createFile(path.Join(config.Params.GeneralOutputDir, fileName))
if err != nil {
panic(err)
}
writer := csv.NewWriter(file)
if err := writer.Write(ndHeader); err != nil {
panic(err)
}
for i := 0; i < config.Params.NodesCount; i++ {
record := []string{
strconv.FormatInt(int64(i), 10),
strconv.FormatBool(network.IsAdversary(int(i))),
strconv.FormatInt(int64(nodeCounters[i].Get("minConfirmedAccumulatedWeight")), 10),
strconv.FormatInt(int64(nodeCounters[i].Get("unconfirmationCount")), 10),
}
writeLine(writer, record)
// Flush the writers, or the data will be truncated for high node count
writer.Flush()
}
}
// todo add to metrics manager on shutdown if needed
func flushWriters(writers []*csv.Writer) {
for _, writer := range writers {
writer.Flush()
err := writer.Error()
if err != nil {
log.Error(err)
}
}
}
func dumpConfig(filePath string) {
bytes, err := json.MarshalIndent(config.Params, "", " ")
if err != nil {
log.Error(err)
}
if err := ioutil.WriteFile(filePath, bytes, 0644); err != nil {
log.Error(err)
}
}
func dumpNetworkConfig(net *network.Network) {
file, err := createFile(path.Join(config.Params.SchedulerOutputDir, "networkConfig.csv"))
if err != nil {
panic(err)
}
ncHeader := []string{"Peer ID", "Neighbor ID", "Network Delay (ns)", "Packet Loss (%)"}
ncWriter := csv.NewWriter(file)
if err := ncWriter.Write(ncHeader); err != nil {
panic(err)
}
file, err = createFile(path.Join(config.Params.SchedulerOutputDir, "weights.csv"))
if err != nil {
panic(err)
}
wHeader := []string{"Peer ID", "Weight"}
wWriter := csv.NewWriter(file)
if err := wWriter.Write(wHeader); err != nil {
panic(err)
}
for _, peer := range net.Peers {
for neighbor, connection := range peer.Neighbors {
record := []string{
strconv.FormatInt(int64(peer.ID), 10),
strconv.FormatInt(int64(neighbor), 10),
strconv.FormatInt(connection.NetworkDelay().Nanoseconds(), 10),
strconv.FormatInt(int64(connection.PacketLoss()*100), 10),
}
writeLine(ncWriter, record)
}
writeLine(wWriter, []string{
strconv.FormatInt(int64(peer.ID), 10),
strconv.FormatInt(int64(net.WeightDistribution.Weight(peer.ID)), 10),
})
// Flush the writers, or the data will be truncated for high node count
flushWriters([]*csv.Writer{ncWriter, wWriter})
}
}
func monitorNetworkState(testNetwork *network.Network) (resultsWriters []*csv.Writer) {
adversaryNodesCount := len(network.AdversaryNodeIDToGroupIDMap)
// honestNodesCount := config.Params.NodesCount - adversaryNodesCount
allColors := []multiverse.Color{multiverse.UndefinedColor, multiverse.Red, multiverse.Green, multiverse.Blue}
colorCounters.CreateCounter("opinions", allColors, []int64{int64(config.Params.NodesCount), 0, 0, 0})
colorCounters.CreateCounter("confirmedNodes", allColors, []int64{0, 0, 0, 0})
colorCounters.CreateCounter("opinionsWeights", allColors, []int64{0, 0, 0, 0})
colorCounters.CreateCounter("likeAccumulatedWeight", allColors, []int64{0, 0, 0, 0})
colorCounters.CreateCounter("processedMessages", allColors, []int64{0, 0, 0, 0})
colorCounters.CreateCounter("requestedMissingMessages", allColors, []int64{0, 0, 0, 0})
colorCounters.CreateCounter("tipPoolSizes", allColors, []int64{0, 0, 0, 0})
for _, peer := range testNetwork.Peers {
peerID := peer.ID
tipCounterName := fmt.Sprint("tipPoolSizes-", peerID)
processedCounterName := fmt.Sprint("processedMessages-", peerID)
colorCounters.CreateCounter(tipCounterName, allColors, []int64{0, 0, 0, 0})
colorCounters.CreateCounter(processedCounterName, allColors, []int64{0, 0, 0, 0})
}
colorCounters.CreateCounter("colorUnconfirmed", allColors[1:], []int64{0, 0, 0})
colorCounters.CreateCounter("confirmedAccumulatedWeight", allColors[1:], []int64{0, 0, 0})
colorCounters.CreateCounter("unconfirmedAccumulatedWeight", allColors[1:], []int64{0, 0, 0})
adversaryCounters.CreateCounter("likeAccumulatedWeight", allColors[1:], []int64{0, 0, 0})
adversaryCounters.CreateCounter("opinions", allColors, []int64{int64(adversaryNodesCount), 0, 0, 0})
adversaryCounters.CreateCounter("confirmedNodes", allColors, []int64{0, 0, 0, 0})
adversaryCounters.CreateCounter("confirmedAccumulatedWeight", allColors, []int64{0, 0, 0, 0})
// Initialize the minConfirmedWeight to be the max value (i.e., the total weight)
for i := 0; i < config.Params.NodesCount; i++ {
nodeCounters = append(nodeCounters, *simulation.NewAtomicCounters[string, int64]())
nodeCounters[i].CreateCounter("minConfirmedAccumulatedWeight", int64(config.Params.NodesTotalWeight))
nodeCounters[i].CreateCounter("unconfirmationCount", 0)
}
atomicCounters.CreateCounter("flips", 0)
atomicCounters.CreateCounter("honestFlips", 0)
atomicCounters.CreateCounter("tps", 0)
atomicCounters.CreateCounter("relevantValidators", 0)
atomicCounters.CreateCounter("issuedMessages", 0)
for _, peer := range testNetwork.Peers {
peerID := peer.ID
issuedCounterName := fmt.Sprint("issuedMessages-", peerID)
atomicCounters.CreateCounter(issuedCounterName, 0)
}
mostLikedColor = multiverse.UndefinedColor
honestOnlyMostLikedColor = multiverse.UndefinedColor
// Dump the network information
dumpNetworkConfig(testNetwork)
// Dump the info about adversary nodes
adResultsWriter := createWriter(fmt.Sprintf("ad-%s.csv", config.Params.ScriptStartTimeStr), adHeader, &resultsWriters)
dumpResultsAD(adResultsWriter, testNetwork)
// Dump the double spending result
// dsResultsWriter := createWriter(fmt.Sprintf("ds-%s.csv", config.Params.ScriptStartTimeStr), dsHeader, &resultsWriters)
// Dump the tip pool and processed message (throughput) results
// tpResultsWriter := createWriter(fmt.Sprintf("tp-%s.csv", config.Params.ScriptStartTimeStr), tpHeader, &resultsWriters)
// Dump the requested missing message result
// mmResultsWriter := createWriter(fmt.Sprintf("mm-%s.csv", config.Params.ScriptStartTimeStr), mmHeader, &resultsWriters)
tpAllHeader := make([]string, 0, config.Params.NodesCount+1)
for i := 0; i < config.Params.NodesCount; i++ {
header := []string{fmt.Sprintf("Node %d", i)}
tpAllHeader = append(tpAllHeader, header...)
}
header := []string{fmt.Sprintf("ns since start")}
tpAllHeader = append(tpAllHeader, header...)
// Dump the tip pool and processed message (throughput) results
// tpAllResultsWriter := createWriter(fmt.Sprintf("all-tp-%s.csv", config.Params.ScriptStartTimeStr), tpAllHeader, &resultsWriters)
// Dump the info about how many nodes have confirmed and liked a certain color