Repository navigation
Expand file tree
/
Copy pathcheckpoint_test.go
More file actions
870 lines (736 loc) · 28.1 KB
/
Copy pathcheckpoint_test.go
File metadata and controls
870 lines (736 loc) · 28.1 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
package nara
import (
"crypto/ed25519"
"encoding/base64"
"testing"
"time"
"github.com/eljojo/nara/identity"
"github.com/eljojo/nara/types"
)
// Helper to generate a keypair for testing
func generateTestKeypair() identity.NaraKeypair {
pub, priv, _ := ed25519.GenerateKey(nil)
return identity.NaraKeypair{PrivateKey: priv, PublicKey: pub}
}
// Helper to convert public key to base64 string for verification maps
func pubKeyToBase64(pub ed25519.PublicKey) string {
return base64.StdEncoding.EncodeToString(pub)
}
// Test creating a basic checkpoint event
func TestCheckpoint_Create(t *testing.T) {
subject := types.NaraName("lisa")
asOfTime := time.Now().Unix()
firstSeen := int64(1624066568)
restarts := int64(47)
totalUptime := int64(23456789)
event := NewTestCheckpointEvent(subject, asOfTime, firstSeen, restarts, totalUptime)
if event.Service != ServiceCheckpoint {
t.Errorf("Expected service=%s, got %s", ServiceCheckpoint, event.Service)
}
if event.Checkpoint == nil {
t.Fatal("Expected checkpoint payload, got nil")
}
if event.Checkpoint.Subject != subject {
t.Errorf("Expected subject=%s, got %s", subject, event.Checkpoint.Subject)
}
if event.Checkpoint.AsOfTime != asOfTime {
t.Errorf("Expected as_of_time=%d, got %d", asOfTime, event.Checkpoint.AsOfTime)
}
if event.Checkpoint.Observation.StartTime != firstSeen {
t.Errorf("Expected first_seen=%d, got %d", firstSeen, event.Checkpoint.Observation.StartTime)
}
if event.Checkpoint.Observation.Restarts != restarts {
t.Errorf("Expected restarts=%d, got %d", restarts, event.Checkpoint.Observation.Restarts)
}
if event.Checkpoint.Observation.TotalUptime != totalUptime {
t.Errorf("Expected total_uptime=%d, got %d", totalUptime, event.Checkpoint.Observation.TotalUptime)
}
// Note: Checkpoint events are always critical importance (no need to check)
}
// Test that checkpoint events are valid
func TestCheckpoint_Validation(t *testing.T) {
// Valid checkpoint
valid := &CheckpointEventPayload{
Subject: "lisa",
AsOfTime: time.Now().Unix(),
Observation: NaraObservation{
StartTime: 1624066568,
Restarts: 47,
TotalUptime: 23456789,
},
}
if !valid.IsValid() {
t.Error("Expected valid checkpoint to pass validation")
}
// Invalid: missing subject
invalid1 := &CheckpointEventPayload{
AsOfTime: time.Now().Unix(),
Observation: NaraObservation{
StartTime: 1624066568,
Restarts: 47,
},
}
if invalid1.IsValid() {
t.Error("Expected checkpoint without subject to fail validation")
}
// Invalid: missing AsOfTime
invalid2 := &CheckpointEventPayload{
Subject: "lisa",
Observation: NaraObservation{
StartTime: 1624066568,
Restarts: 47,
},
}
if invalid2.IsValid() {
t.Error("Expected checkpoint without as_of_time to fail validation")
}
// Invalid: negative restarts
invalid3 := &CheckpointEventPayload{
Subject: "lisa",
AsOfTime: time.Now().Unix(),
Observation: NaraObservation{
Restarts: -1,
},
}
if invalid3.IsValid() {
t.Error("Expected checkpoint with negative restarts to fail validation")
}
}
// Test adding checkpoint to ledger
func TestCheckpoint_AddToLedger(t *testing.T) {
ledger := NewSyncLedger(1000)
subject := types.NaraName("lisa")
event := NewTestCheckpointEvent(subject, time.Now().Unix(), 1624066568, 47, 23456789)
added := ledger.AddEvent(event)
if !added {
t.Error("Expected checkpoint event to be added to ledger")
}
// Should be able to retrieve it
checkpoint := ledger.GetCheckpoint(subject)
if checkpoint == nil {
t.Fatal("Expected to retrieve checkpoint, got nil")
}
if checkpoint.Observation.Restarts != 47 {
t.Errorf("Expected restarts=47, got %d", checkpoint.Observation.Restarts)
}
}
// Test that only one checkpoint per subject is kept (latest wins)
func TestCheckpoint_OnlyOnePerSubject(t *testing.T) {
ledger := NewSyncLedger(1000)
subject := types.NaraName("lisa")
// Add first checkpoint
asOfTime1 := int64(1000)
event1 := NewTestCheckpointEvent(subject, asOfTime1, 1624066568, 47, 23456789)
ledger.AddEvent(event1)
// Add second checkpoint with later AsOfTime
asOfTime2 := int64(2000)
event2 := NewTestCheckpointEvent(subject, asOfTime2, 1624066568, 50, 24000000)
ledger.AddEvent(event2)
// Should get the latest checkpoint (the one with later asOfTime)
checkpoint := ledger.GetCheckpoint(subject)
if checkpoint == nil {
t.Fatal("Expected to retrieve checkpoint, got nil")
}
if checkpoint.Observation.Restarts != 50 {
t.Errorf("Expected latest checkpoint restarts=50, got %d", checkpoint.Observation.Restarts)
}
// NewTestCheckpointEvent preserves relative ordering by adding offset
expectedAsOfTime := CheckpointCutoffTime + 1000 + asOfTime2
if checkpoint.AsOfTime != expectedAsOfTime {
t.Errorf("Expected latest checkpoint as_of_time=%d, got %d", expectedAsOfTime, checkpoint.AsOfTime)
}
}
// Test that checkpoints are never pruned (critical importance)
func TestCheckpoint_NeverPruned(t *testing.T) {
// Small ledger to trigger pruning
ledger := NewSyncLedger(50)
subject := types.NaraName("lisa")
// Add checkpoint
checkpointEvent := NewTestCheckpointEvent(subject, time.Now().Unix(), 1624066568, 47, 23456789)
ledger.AddEvent(checkpointEvent)
// Flood with other events to trigger pruning
for i := 0; i < 100; i++ {
event := NewPingSyncEvent("observer", "target", float64(i))
ledger.AddEvent(event)
}
// Checkpoint should still exist
checkpoint := ledger.GetCheckpoint(subject)
if checkpoint == nil {
t.Fatal("Checkpoint was pruned but should never be pruned")
}
if checkpoint.Observation.Restarts != 47 {
t.Errorf("Expected checkpoint restarts=47, got %d", checkpoint.Observation.Restarts)
}
}
// Test checkpoint with single voter (basic case)
func TestCheckpoint_SingleVoter(t *testing.T) {
subject := types.NaraName("lisa")
voterID := types.NaraID("homer-id-123")
keypair := generateTestKeypair()
event := NewTestCheckpointEvent(subject, time.Now().Unix(), 1624066568, 47, 23456789)
event.AddCheckpointVoter(voterID, keypair)
if len(event.Checkpoint.VoterIDs) != 1 {
t.Errorf("Expected 1 voter, got %d", len(event.Checkpoint.VoterIDs))
}
if event.Checkpoint.VoterIDs[0] != voterID {
t.Errorf("Expected voterID=%s, got %s", voterID, event.Checkpoint.VoterIDs[0])
}
if len(event.Checkpoint.Signatures) != 1 {
t.Errorf("Expected 1 signature, got %d", len(event.Checkpoint.Signatures))
}
}
// Test checkpoint with multiple voters
func TestCheckpoint_MultipleVoters(t *testing.T) {
subject := types.NaraName("lisa")
voterIDs := []types.NaraID{types.NaraID("homer-id"), types.NaraID("marge-id"), types.NaraID("bart-id")}
keypairs := make([]identity.NaraKeypair, 3)
for i := range keypairs {
keypairs[i] = generateTestKeypair()
}
event := NewTestCheckpointEvent(subject, time.Now().Unix(), 1624066568, 47, 23456789)
for i, voterID := range voterIDs {
event.AddCheckpointVoter(voterID, keypairs[i])
}
if len(event.Checkpoint.VoterIDs) != 3 {
t.Errorf("Expected 3 voters, got %d", len(event.Checkpoint.VoterIDs))
}
if len(event.Checkpoint.Signatures) != 3 {
t.Errorf("Expected 3 signatures, got %d", len(event.Checkpoint.Signatures))
}
}
// Test checkpoint signature verification
func TestCheckpoint_VerifySignatures(t *testing.T) {
subject := types.NaraName("lisa")
voterIDs := []types.NaraID{types.NaraID("homer-id"), types.NaraID("marge-id"), types.NaraID("bart-id")}
keypairs := make([]identity.NaraKeypair, 3)
publicKeys := make(map[types.NaraID]string)
for i, voterID := range voterIDs {
keypairs[i] = generateTestKeypair()
publicKeys[voterID] = pubKeyToBase64(keypairs[i].PublicKey)
}
event := NewTestCheckpointEvent(subject, time.Now().Unix(), 1624066568, 47, 23456789)
for i, voterID := range voterIDs {
event.AddCheckpointVoter(voterID, keypairs[i])
}
// Verify with correct public keys
validCount := event.VerifyCheckpointSignatures(publicKeys)
if validCount != 3 {
t.Errorf("Expected 3 valid signatures, got %d", validCount)
}
}
// Test checkpoint signature verification with wrong keys
func TestCheckpoint_VerifySignatures_WrongKeys(t *testing.T) {
subject := types.NaraName("lisa")
voterID := types.NaraID("homer-id")
keypair := generateTestKeypair()
wrongKeypair := generateTestKeypair()
event := NewTestCheckpointEvent(subject, time.Now().Unix(), 1624066568, 47, 23456789)
event.AddCheckpointVoter(voterID, keypair)
// Verify with wrong public key
publicKeys := map[types.NaraID]string{
voterID: pubKeyToBase64(wrongKeypair.PublicKey), // Wrong key!
}
validCount := event.VerifyCheckpointSignatures(publicKeys)
if validCount != 0 {
t.Errorf("Expected 0 valid signatures with wrong key, got %d", validCount)
}
}
// Test deriving restart count from checkpoint + new events
func TestCheckpoint_DeriveRestartCount(t *testing.T) {
ledger := NewSyncLedger(1000)
subject := types.NaraName("lisa")
checkpointTime := time.Now().Unix() // Use current time (after cutoff, won't be adjusted)
// Add checkpoint: lisa had 47 restarts as of now
checkpointEvent := NewTestCheckpointEvent(subject, checkpointTime, 1624066568, 47, 23456789)
ledger.AddEvent(checkpointEvent)
// Add 3 new restart events after the checkpoint
for i := 0; i < 3; i++ {
startTime := checkpointTime + int64(i+1)*100 // Unique start times after checkpoint
event := NewRestartObservationEvent("observer", subject, startTime, int64(48+i))
ledger.AddEvent(event)
}
// Total should be 47 (checkpoint) + 3 (new) = 50
total := ledger.DeriveRestartCount(types.NaraName(subject))
if total != 50 {
t.Errorf("Expected total restarts=50 (47+3), got %d", total)
}
}
// Test deriving restart count without checkpoint (just count events)
func TestCheckpoint_DeriveRestartCount_NoCheckpoint(t *testing.T) {
ledger := NewSyncLedger(1000)
subject := types.NaraName("lisa")
// Add 5 restart events with unique start times (no checkpoint)
for i := 0; i < 5; i++ {
startTime := int64(1000 + i*100) // Unique start times
event := NewRestartObservationEvent("observer", subject, startTime, int64(i+1))
ledger.AddEvent(event)
}
// Total should just be 5 (count of unique start times)
total := ledger.DeriveRestartCount(types.NaraName(subject))
if total != 5 {
t.Errorf("Expected total restarts=5, got %d", total)
}
}
// Test deriving restart count with backfill fallback (no checkpoint)
func TestCheckpoint_DeriveRestartCount_BackfillFallback(t *testing.T) {
ledger := NewSyncLedger(1000)
subject := types.NaraName("lisa")
// Add backfill event (old system)
backfillEvent := NewBackfillObservationEvent(types.NaraName("observer"), types.NaraName(subject), 1624066568, 47, 1704067200)
ledger.AddEvent(backfillEvent)
// Add 2 new restart events with different start times
event1 := NewRestartObservationEvent("observer", subject, 1704067300, 48)
ledger.AddEvent(event1)
event2 := NewRestartObservationEvent("observer", subject, 1704067400, 49)
ledger.AddEvent(event2)
// Total should be 47 (backfill baseline) + 2 (new unique start times) = 49
total := ledger.DeriveRestartCount(types.NaraName(subject))
if total != 49 {
t.Errorf("Expected total restarts=49 (47+2), got %d", total)
}
}
// Test checkpoint takes precedence over backfill
func TestCheckpoint_PrecedenceOverBackfill(t *testing.T) {
ledger := NewSyncLedger(1000)
subject := types.NaraName("lisa")
checkpointTime := time.Now().Unix() // Use current time (after cutoff, won't be adjusted)
// Add backfill event with old data
backfillEvent := NewBackfillObservationEvent(types.NaraName("observer"), types.NaraName(subject), 1624066568, 40, 1704067200)
ledger.AddEvent(backfillEvent)
// Add checkpoint with newer data (should take precedence)
checkpointEvent := NewTestCheckpointEvent(subject, checkpointTime, 1624066568, 47, 23456789)
ledger.AddEvent(checkpointEvent)
// Add 1 new restart event
newEvent := NewRestartObservationEvent("observer", subject, checkpointTime+100, 48)
ledger.AddEvent(newEvent)
// Total should be 47 (checkpoint) + 1 (new) = 48, NOT 40 (backfill) + something
total := ledger.DeriveRestartCount(types.NaraName(subject))
if total != 48 {
t.Errorf("Expected total restarts=48 (checkpoint 47 + 1 new), got %d", total)
}
}
// Test counting unique start times (deduplication)
func TestCheckpoint_UniqueStartTimes(t *testing.T) {
ledger := NewSyncLedger(1000)
subject := types.NaraName("lisa")
startTime := int64(1704067200)
// Multiple observers report the same restart (same start time)
observers := []types.NaraName{"homer", "marge", "bart"}
for _, obs := range observers {
event := NewRestartObservationEvent(obs, subject, startTime, 1)
ledger.AddEvent(event)
}
// Should count as 1 restart (same start time)
total := ledger.DeriveRestartCount(types.NaraName(subject))
if total != 1 {
t.Errorf("Expected total restarts=1 (same start_time), got %d", total)
}
}
// Test deriving total uptime from checkpoint + status events
func TestCheckpoint_DeriveTotalUptime(t *testing.T) {
ledger := NewSyncLedger(1000)
subject := types.NaraName("lisa")
checkpointTime := time.Now().Unix() // Use current time (after cutoff, won't be adjusted)
// Add checkpoint: lisa had 1000 seconds of uptime as of now
checkpointEvent := NewTestCheckpointEvent(subject, checkpointTime, 1624066568, 10, 1000)
ledger.AddEvent(checkpointEvent)
// Add status change events after checkpoint
// ONLINE at checkpoint+100, OFFLINE at checkpoint+600 = 500 seconds
onlineEvent := NewStatusChangeObservationEvent("observer", subject, "ONLINE")
onlineEvent.Timestamp = (checkpointTime + 100) * 1e9 // Convert to nanoseconds
ledger.AddEvent(onlineEvent)
offlineEvent := NewStatusChangeObservationEvent("observer", subject, "OFFLINE")
offlineEvent.Timestamp = (checkpointTime + 600) * 1e9
ledger.AddEvent(offlineEvent)
// Total uptime should be 1000 (checkpoint) + 500 (new period) = 1500
total := ledger.DeriveTotalUptime(types.NaraName(subject))
if total != 1500 {
t.Errorf("Expected total uptime=1500 (1000+500), got %d", total)
}
}
// Test deriving total uptime from backfill (no checkpoint)
// For backfill events, we assume the nara has been online since StartTime
func TestCheckpoint_DeriveTotalUptime_Backfill(t *testing.T) {
ledger := NewSyncLedger(1000)
subject := types.NaraName("lisa")
// Backfill: lisa has been around since startTime
startTime := time.Now().Unix() - 7200 // 2 hours ago
backfillEvent := NewBackfillObservationEvent(types.NaraName("observer"), types.NaraName(subject), startTime, 10, time.Now().Unix())
ledger.AddEvent(backfillEvent)
// With no status-change events, uptime should be time since startTime
total := ledger.DeriveTotalUptime(types.NaraName(subject))
expectedUptime := time.Now().Unix() - startTime
// Allow 2 second tolerance for timing
if total < expectedUptime-2 || total > expectedUptime+2 {
t.Errorf("Expected uptime ~%d (since startTime), got %d", expectedUptime, total)
}
}
// Test deriving total uptime from backfill with status-change events
func TestCheckpoint_DeriveTotalUptime_BackfillWithOffline(t *testing.T) {
ledger := NewSyncLedger(1000)
subject := types.NaraName("lisa")
// Backfill: lisa has been around since time 1000
backfillEvent := NewBackfillObservationEvent(types.NaraName("observer"), types.NaraName(subject), 1000, 10, 2000)
ledger.AddEvent(backfillEvent)
// Status events: OFFLINE at 1500, back ONLINE at 1700, OFFLINE at 1900
// Timeline: online 1000-1500 (500s), offline 1500-1700 (200s), online 1700-1900 (200s)
// Total uptime: 500 + 200 = 700s
offline1 := NewStatusChangeObservationEvent("observer", subject, "OFFLINE")
offline1.Timestamp = 1500 * 1e9
ledger.AddEvent(offline1)
online1 := NewStatusChangeObservationEvent("observer", subject, "ONLINE")
online1.Timestamp = 1700 * 1e9
ledger.AddEvent(online1)
offline2 := NewStatusChangeObservationEvent("observer", subject, "OFFLINE")
offline2.Timestamp = 1900 * 1e9
ledger.AddEvent(offline2)
total := ledger.DeriveTotalUptime(types.NaraName(subject))
expectedUptime := int64(500 + 200) // 700
if total != expectedUptime {
t.Errorf("Expected uptime=%d (500+200 from backfill timeline), got %d", expectedUptime, total)
}
}
// Test that restart events are NOT pruned when no checkpoint exists
// This ensures we don't lose historical restart data before it's checkpointed
func TestCheckpoint_RestartEventsPreservedWithoutCheckpoint(t *testing.T) {
ledger := NewSyncLedger(1000)
subject := types.NaraName("lisa")
observer := types.NaraName("homer")
// Add 25 restart events (more than MaxObservationsPerPair = 20)
for i := 0; i < 25; i++ {
startTime := int64(1704067200 + i*100) // Unique start times
event := NewRestartObservationEvent(observer, subject, startTime, int64(i+1))
ledger.AddEvent(event)
}
// All 25 should still be there since no checkpoint exists
restartCount := ledger.DeriveRestartCount(types.NaraName(subject))
if restartCount != 25 {
t.Errorf("Expected 25 restarts to be preserved (no checkpoint), got %d", restartCount)
}
// Count actual restart events
count := 0
for _, e := range ledger.Events {
if e.Service == ServiceObservation && e.Observation != nil &&
e.Observation.Subject == subject && e.Observation.Type == "restart" {
count++
}
}
if count < 25 {
t.Errorf("Expected at least 25 restart events preserved, got %d", count)
}
}
// Test that restart events CAN be pruned AFTER a checkpoint exists
func TestCheckpoint_RestartEventsPrunedAfterCheckpoint(t *testing.T) {
ledger := NewSyncLedger(1000)
subject := types.NaraName("lisa")
observer := types.NaraName("homer")
checkpointTime := int64(1704067200)
// First add a checkpoint
checkpoint := NewTestCheckpointEvent(subject, checkpointTime, 1624066568, 10, 1000)
keypair := generateTestKeypair()
checkpoint.AddCheckpointVoter("voter1-id", keypair)
checkpoint.AddCheckpointVoter("voter2-id", generateTestKeypair())
ledger.AddEvent(checkpoint)
// Now add 25 restart events after the checkpoint
for i := 0; i < 25; i++ {
startTime := checkpointTime + int64(i+1)*100 // After checkpoint
event := NewRestartObservationEvent(observer, subject, startTime, int64(11+i))
ledger.AddEvent(event)
}
// With checkpoint existing, compaction should prune to 20
count := 0
for _, e := range ledger.Events {
if e.Service == ServiceObservation && e.Observation != nil &&
e.Observation.Observer == observer && e.Observation.Subject == subject {
count++
}
}
if count > MaxObservationsPerPair {
t.Errorf("Expected at most %d observation events after compaction, got %d", MaxObservationsPerPair, count)
}
// But derived restart count should still be correct: 10 (checkpoint) + remaining unique StartTimes
restartCount := ledger.DeriveRestartCount(types.NaraName(subject))
// We should have checkpoint(10) + some number of new restarts
if restartCount < 10 {
t.Errorf("Expected at least checkpoint restarts (10), got %d", restartCount)
}
}
// Test that round 2 checkpoint signatures can be verified
// This tests the bug where verifyCheckpointSignatures hardcodes round=1
func TestCheckpoint_Round2SignatureVerification(t *testing.T) {
// Create test naras with keypairs
proposerKeypair := generateTestKeypair()
voter1Keypair := generateTestKeypair()
voter2Keypair := generateTestKeypair()
proposerID := types.NaraID("proposer-id")
voter1ID := types.NaraID("voter1-id")
voter2ID := types.NaraID("voter2-id")
subject := types.NaraName("proposer")
asOfTime := time.Now().Unix()
restarts := int64(100)
totalUptime := int64(50000)
firstSeen := int64(1624066568)
round := 2 // Round 2!
// Create signatures using attestation format
// Proposer creates self-attestation
proposerAttestation := Attestation{
Version: 1,
Subject: subject,
SubjectID: proposerID,
Observation: NaraObservation{
Restarts: restarts,
TotalUptime: totalUptime,
StartTime: firstSeen,
},
Attester: subject,
AttesterID: proposerID,
AsOfTime: asOfTime,
}
proposerSig := identity.SignContent(&proposerAttestation, proposerKeypair)
// Voters create third-party attestations
voter1Attestation := Attestation{
Version: 1,
Subject: subject,
SubjectID: proposerID,
Observation: NaraObservation{
Restarts: restarts,
TotalUptime: totalUptime,
StartTime: firstSeen,
},
Attester: types.NaraName("voter1"),
AttesterID: voter1ID,
AsOfTime: asOfTime,
}
voter1Sig := identity.SignContent(&voter1Attestation, voter1Keypair)
voter2Attestation := Attestation{
Version: 1,
Subject: subject,
SubjectID: proposerID,
Observation: NaraObservation{
Restarts: restarts,
TotalUptime: totalUptime,
StartTime: firstSeen,
},
Attester: types.NaraName("voter2"),
AttesterID: voter2ID,
AsOfTime: asOfTime,
}
voter2Sig := identity.SignContent(&voter2Attestation, voter2Keypair)
// Create checkpoint with round 2 signatures
checkpoint := &CheckpointEventPayload{
Subject: subject,
SubjectID: proposerID,
AsOfTime: asOfTime,
Observation: NaraObservation{
Restarts: restarts,
TotalUptime: totalUptime,
StartTime: firstSeen,
},
VoterIDs: []types.NaraID{proposerID, voter1ID, voter2ID},
Signatures: []string{proposerSig, voter1Sig, voter2Sig},
Round: round, // Must match what was signed
}
// Create a CheckpointService with a mock network that returns public keys
ledger := NewSyncLedger(1000)
local := testLocalNara(t, "verifier")
network := local.Network
// Add naras to neighbourhood and register their keys
proposerPubKey := pubKeyToBase64(proposerKeypair.PublicKey)
voter1PubKey := pubKeyToBase64(voter1Keypair.PublicKey)
voter2PubKey := pubKeyToBase64(voter2Keypair.PublicKey)
network.Neighbourhood["proposer"] = &Nara{
Name: "proposer",
Status: NaraStatus{
ID: proposerID,
PublicKey: proposerPubKey,
},
}
network.Neighbourhood["voter1"] = &Nara{
Name: "voter1",
Status: NaraStatus{
ID: voter1ID,
PublicKey: voter1PubKey,
},
}
network.Neighbourhood["voter2"] = &Nara{
Name: "voter2",
Status: NaraStatus{
ID: voter2ID,
PublicKey: voter2PubKey,
},
}
network.RegisterKey(proposerID, proposerPubKey)
network.RegisterKey(voter1ID, voter1PubKey)
network.RegisterKey(voter2ID, voter2PubKey)
service := NewCheckpointService(network, ledger, local)
// Verify signatures - should succeed with attestation format
result := service.verifyCheckpointSignatures(checkpoint)
// All 3 signatures should be valid, verification should pass
if !result.Valid || result.ValidCount != 3 {
t.Errorf("Expected 3 valid signatures, got %d", result.ValidCount)
}
}
// Test that partial signature verification works (some naras unknown)
func TestCheckpoint_PartialSignatureVerification(t *testing.T) {
// Create test naras with keypairs
proposerKeypair := generateTestKeypair()
voter1Keypair := generateTestKeypair()
voter2Keypair := generateTestKeypair()
proposerID := types.NaraID("proposer-id")
voter1ID := types.NaraID("voter1-id")
voter2ID := types.NaraID("voter2-id")
subject := types.NaraName("proposer")
asOfTime := time.Now().Unix()
restarts := int64(100)
totalUptime := int64(50000)
firstSeen := int64(1624066568)
round := 1
// Create signatures using attestation format
proposerAttestation := Attestation{
Version: 1,
Subject: subject,
SubjectID: proposerID,
Observation: NaraObservation{
Restarts: restarts,
TotalUptime: totalUptime,
StartTime: firstSeen,
},
Attester: subject,
AttesterID: proposerID,
AsOfTime: asOfTime,
}
proposerSig := identity.SignContent(&proposerAttestation, proposerKeypair)
voter1Attestation := Attestation{
Version: 1,
Subject: subject,
SubjectID: proposerID,
Observation: NaraObservation{
Restarts: restarts,
TotalUptime: totalUptime,
StartTime: firstSeen,
},
Attester: "voter1",
AttesterID: voter1ID,
AsOfTime: asOfTime,
}
voter1Sig := identity.SignContent(&voter1Attestation, voter1Keypair)
voter2Attestation := Attestation{
Version: 1,
Subject: subject,
SubjectID: proposerID,
Observation: NaraObservation{
Restarts: restarts,
TotalUptime: totalUptime,
StartTime: firstSeen,
},
Attester: types.NaraName("voter2"),
AttesterID: voter2ID,
AsOfTime: asOfTime,
}
voter2Sig := identity.SignContent(&voter2Attestation, voter2Keypair)
// Create checkpoint with all 3 signatures
checkpoint := &CheckpointEventPayload{
Subject: subject,
SubjectID: proposerID,
AsOfTime: asOfTime,
Observation: NaraObservation{
Restarts: restarts,
TotalUptime: totalUptime,
StartTime: firstSeen,
},
VoterIDs: []types.NaraID{proposerID, voter1ID, voter2ID},
Signatures: []string{proposerSig, voter1Sig, voter2Sig},
Round: round,
}
// Create a CheckpointService with a network that only knows voter1
ledger := NewSyncLedger(1000)
local := testLocalNara(t, "verifier")
network := local.Network
// Only add voter1 - proposer and voter2 are "unknown"
voter1PubKey := pubKeyToBase64(voter1Keypair.PublicKey)
network.Neighbourhood["voter1"] = &Nara{
Name: "voter1",
Status: NaraStatus{
ID: voter1ID,
PublicKey: voter1PubKey,
},
}
network.RegisterKey(voter1ID, voter1PubKey)
service := NewCheckpointService(network, ledger, local)
// Only voter1 is known, so only 1 signature is verifiable
// Since we need 2+ valid signatures, verification should fail
result := service.verifyCheckpointSignatures(checkpoint)
if result.Valid {
t.Error("Expected verification to fail with only 1 known voter")
}
if result.ValidCount != 1 {
t.Errorf("Expected 1 valid signature (only voter1 known), got %d", result.ValidCount)
}
if result.KnownCount != 1 {
t.Errorf("Expected 1 known voter, got %d", result.KnownCount)
}
}
// Test that status-change events are pruned first (before restart events)
func TestCheckpoint_StatusChangeEventsPrunedFirst(t *testing.T) {
ledger := NewSyncLedger(1000)
subject := types.NaraName("lisa")
observer := types.NaraName("homer")
// Add 15 restart events
for i := 0; i < 15; i++ {
startTime := int64(1704067200 + i*100)
event := NewRestartObservationEvent(observer, subject, startTime, int64(i+1))
ledger.AddEvent(event)
}
// Add 10 status-change events (total 25, over limit of 20)
for i := 0; i < 10; i++ {
event := NewStatusChangeObservationEvent(observer, subject, "ONLINE")
event.Timestamp = int64(1704067200+i*50) * 1e9
ledger.AddEvent(event)
}
// All 15 restart events should be preserved
restartCount := 0
statusCount := 0
for _, e := range ledger.Events {
if e.Service == ServiceObservation && e.Observation != nil &&
e.Observation.Observer == observer && e.Observation.Subject == subject {
if e.Observation.Type == "restart" {
restartCount++
} else if e.Observation.Type == "status-change" {
statusCount++
}
}
}
if restartCount != 15 {
t.Errorf("Expected all 15 restart events preserved, got %d", restartCount)
}
// Status-change events should have been pruned to make room
if statusCount > 5 {
t.Errorf("Expected status-change events to be pruned (got %d), restarts should be preserved", statusCount)
}
}
// Test backfill created even when restart observations exist
// This reproduces the bug where backfill was skipped if ANY observation events existed
func TestCheckpoint_BackfillCreatedWithExistingRestarts(t *testing.T) {
ledger := NewSyncLedger(1000)
subject := types.NaraName("nelly")
// Add ONE recent restart observation (like a short-memory nara would have)
recentStartTime := time.Now().Unix() - 100
restartEvent := NewRestartObservationEvent("observer", subject, recentStartTime, 1026)
ledger.AddEvent(restartEvent)
// Now add a backfill event with the FULL restart history
// This simulates what should happen during backfillObservations()
backfillEvent := NewBackfillObservationEvent(types.NaraName("observer"), types.NaraName(subject), 1639996062, 1025, time.Now().Unix())
added := ledger.AddEvent(backfillEvent)
if !added {
t.Error("Backfill event should be added even when restart observations exist")
}
// Now derive restart count - should use backfill baseline (1025) + new restart (1)
totalRestarts := ledger.DeriveRestartCount(types.NaraName(subject))
// We expect: backfill baseline (1025) + 1 new restart event with different StartTime = 1026
// BUT the restart event has StartTime=recentStartTime which is different from backfills StartTime=1639996062
// So it should count as a NEW restart
expected := int64(1026) // 1025 from backfill + 1 new
if totalRestarts != expected {
t.Errorf("Expected totalRestarts=%d (1025 backfill + 1 new), got %d", expected, totalRestarts)
}
}