-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecurity-fixes.patch
More file actions
1454 lines (1370 loc) · 51 KB
/
security-fixes.patch
File metadata and controls
1454 lines (1370 loc) · 51 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
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
diff -ruN '--exclude=.git' aethernet-main/internal/consensus/voting.go aethernet-fixed/internal/consensus/voting.go
--- aethernet-main/internal/consensus/voting.go 2026-02-26 01:15:06.000000000 +0000
+++ aethernet-fixed/internal/consensus/voting.go 2026-02-27 00:22:51.000000000 +0000
@@ -39,6 +39,7 @@
import (
"errors"
"fmt"
+ "math/big"
"sync"
"time"
@@ -47,6 +48,10 @@
"github.com/aethernet/core/internal/identity"
)
+// bigDivisor is the constant 10000 used for weight normalization, pre-allocated
+// as a *big.Int so it is not re-created on every computeWeight call.
+var bigDivisor = big.NewInt(10000)
+
// Sentinel errors for programmatic handling by callers.
var (
// ErrEventNotFound is returned by GetRecord, IsFinalized, FinalOrder, and
@@ -208,10 +213,23 @@
if err != nil {
return 0, fmt.Errorf("consensus: agent %s not in registry: %w", agentID, err)
}
- // Integer-first arithmetic: multiply before dividing to preserve precision.
- // If either ReputationScore or StakedAmount is zero the product is zero,
- // giving weight zero as specified.
- return fp.ReputationScore * fp.StakedAmount / 10000, nil
+ // Overflow-safe arithmetic using math/big: the intermediate product of
+ // ReputationScore × StakedAmount can exceed uint64 for large stakes.
+ // Using big.Int for the multiplication avoids silent wraparound.
+ // If either factor is zero, return zero immediately (short-circuit).
+ if fp.ReputationScore == 0 || fp.StakedAmount == 0 {
+ return 0, nil
+ }
+ product := new(big.Int).Mul(
+ new(big.Int).SetUint64(fp.ReputationScore),
+ new(big.Int).SetUint64(fp.StakedAmount),
+ )
+ result := new(big.Int).Div(product, bigDivisor)
+ // If the result exceeds uint64 range, saturate at MaxUint64.
+ if !result.IsUint64() {
+ return ^uint64(0), nil
+ }
+ return result.Uint64(), nil
}
// RegisterVote records a vote from voterID for the given eventID and immediately
diff -ruN '--exclude=.git' aethernet-main/internal/consensus/voting_test.go aethernet-fixed/internal/consensus/voting_test.go
--- aethernet-main/internal/consensus/voting_test.go 2026-02-26 01:15:06.000000000 +0000
+++ aethernet-fixed/internal/consensus/voting_test.go 2026-02-27 00:26:31.000000000 +0000
@@ -402,3 +402,48 @@
t.Errorf("want %d finalized events, got %d", numGoroutines, got)
}
}
+
+// ---------------------------------------------------------------------------
+// Fix 1: Overflow-safe weight computation
+// ---------------------------------------------------------------------------
+
+func TestComputeWeight_NoOverflow(t *testing.T) {
+ // Use values that would overflow uint64 under naive multiplication:
+ // 10000 * 1_844_674_407_370_955_300 = 1.84e22, exceeding uint64 max (1.84e19).
+ // The math/big implementation must produce the correct result.
+ reg := identity.NewRegistry()
+ const rep = uint64(10000) // max reputation
+ const stake = uint64(1_844_674_407_370_955_300) // near uint64 max / 10000
+ registerAgent(t, reg, "whale", rep, stake)
+ vr := newRound(reg)
+
+ w, err := vr.ComputeWeight("whale")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ // Expected: 10000 * 1_844_674_407_370_955_300 / 10000 = 1_844_674_407_370_955_300
+ if w != stake {
+ t.Errorf("want weight %d, got %d (overflow detected!)", stake, w)
+ }
+}
+
+func TestComputeWeight_LargeValues_NoWrapAround(t *testing.T) {
+ // Values that definitely overflow a uint64 multiplication:
+ // 10000 * MaxUint64 = overflow. Result should saturate, not wrap.
+ reg := identity.NewRegistry()
+ registerAgent(t, reg, "mega", 10000, ^uint64(0))
+ vr := newRound(reg)
+
+ w, err := vr.ComputeWeight("mega")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ // The big.Int result exceeds uint64, so it should saturate at MaxUint64.
+ if w == 0 {
+ t.Fatal("weight wrapped to zero — overflow bug present")
+ }
+ // Since 10000 * MaxUint64 / 10000 = MaxUint64, the result should be MaxUint64.
+ if w != ^uint64(0) {
+ t.Errorf("want MaxUint64 (%d), got %d", ^uint64(0), w)
+ }
+}
diff -ruN '--exclude=.git' aethernet-main/internal/crypto/signing.go aethernet-fixed/internal/crypto/signing.go
--- aethernet-main/internal/crypto/signing.go 2026-02-26 01:15:06.000000000 +0000
+++ aethernet-fixed/internal/crypto/signing.go 2026-02-27 03:04:19.275288010 +0000
@@ -13,18 +13,11 @@
// This struct must mirror the unexported eventCanonical struct in the event package
// exactly — same fields, same JSON tags, same declaration order — so that both
// operations (signing here and ID hashing in event.ComputeID) commit to an
-// identical byte sequence for the same event. The test TestCanonicalBytes_MatchesEventComputeID
-// verifies this invariant by checking sha256(CanonicalBytes(e)) == e.ID.
-//
-// Excluded fields and rationale:
-// - ID: computed from these fields (circular)
-// - Signature: the output of signing (circular; included would prevent signing)
-// - SettlementState: mutable OCS lifecycle metadata that evolves after creation
-// without invalidating the event's causal identity or its signature.
+// identical byte sequence for the same event.
type signable struct {
Type event.EventType `json:"type"`
CausalRefs []event.EventID `json:"causal_refs"`
- Payload interface{} `json:"payload"`
+ Payload json.RawMessage `json:"payload"`
AgentID string `json:"agent_id"`
CausalTimestamp uint64 `json:"causal_timestamp"`
StakeAmount uint64 `json:"stake_amount"`
diff -ruN '--exclude=.git' aethernet-main/internal/dag/dag.go aethernet-fixed/internal/dag/dag.go
--- aethernet-main/internal/dag/dag.go 2026-02-26 01:15:06.000000000 +0000
+++ aethernet-fixed/internal/dag/dag.go 2026-02-27 03:05:35.168260569 +0000
@@ -52,6 +52,7 @@
"sort"
"sync"
+ "github.com/aethernet/core/internal/crypto"
"github.com/aethernet/core/internal/event"
)
@@ -62,15 +63,19 @@
ErrEventNotFound = errors.New("event not found")
// ErrDuplicateEvent is returned when an event whose ID is already stored is added
- // again. Because EventIDs are content-addressed, a duplicate ID means the event
- // content is identical; the Add call is treated as a no-op from a state perspective,
- // but the error signals to the caller that no insertion occurred.
+ // again.
ErrDuplicateEvent = errors.New("duplicate event")
// ErrMissingCausalRef is returned when an event's CausalRefs include an EventID
- // not yet present in the DAG. The event cannot be inserted until all of its
- // causal dependencies are known to the DAG.
+ // not yet present in the DAG.
ErrMissingCausalRef = errors.New("causal reference not in DAG")
+
+ // ErrInvalidSignature is returned when an event's cryptographic signature does
+ // not verify against its canonical content and public key.
+ ErrInvalidSignature = errors.New("dag: invalid event signature")
+
+ // ErrMissingSignature is returned when a non-genesis event has no signature.
+ ErrMissingSignature = errors.New("dag: event has no signature")
)
// DAG is a concurrent, append-only causal directed acyclic graph of AetherNet events.
@@ -127,9 +132,20 @@
return fmt.Errorf("dag: %w: %s", ErrDuplicateEvent, e.ID)
}
+ // Signature enforcement: non-genesis events must be signed and verifiable.
+ // Genesis events (empty CausalRefs) are allowed unsigned as they bootstrap
+ // the DAG and typically pre-date key distribution.
+ isGenesis := len(e.CausalRefs) == 0
+ if !isGenesis {
+ if len(e.Signature) == 0 {
+ return fmt.Errorf("%w: %s", ErrMissingSignature, e.ID)
+ }
+ if !crypto.VerifyEvent(e) {
+ return fmt.Errorf("%w: %s", ErrInvalidSignature, e.ID)
+ }
+ }
+
// Validate all causal references before mutating any state.
- // This makes Add atomic: either all refs exist and the event is inserted,
- // or the first missing ref causes a rejection and the DAG is unchanged.
for _, ref := range e.CausalRefs {
if _, ok := d.events[ref]; !ok {
return fmt.Errorf("dag: %w: %s (referenced by %s)", ErrMissingCausalRef, ref, e.ID)
diff -ruN '--exclude=.git' aethernet-main/internal/dag/dag_test.go aethernet-fixed/internal/dag/dag_test.go
--- aethernet-main/internal/dag/dag_test.go 2026-02-26 01:15:06.000000000 +0000
+++ aethernet-fixed/internal/dag/dag_test.go 2026-02-27 03:09:34.670173971 +0000
@@ -7,6 +7,7 @@
"sync"
"testing"
+ "github.com/aethernet/core/internal/crypto"
"github.com/aethernet/core/internal/dag"
"github.com/aethernet/core/internal/event"
)
@@ -16,6 +17,7 @@
// ---------------------------------------------------------------------------
// makeGenesis creates a genesis event (no causal references) for the given agent.
+// Genesis events are unsigned; the DAG allows this for bootstrap.
func makeGenesis(t *testing.T, agentID string) *event.Event {
t.Helper()
e, err := event.New(
@@ -32,10 +34,17 @@
return e
}
-// makeChild creates an event that references all provided parents.
+// makeChild creates a signed event that references all provided parents.
// priorTimestamps is built automatically from the parents' CausalTimestamps.
+// A fresh keypair is generated for signing since non-genesis events must be signed.
func makeChild(t *testing.T, agentID string, parents ...*event.Event) *event.Event {
t.Helper()
+ kp, err := crypto.GenerateKeyPair()
+ if err != nil {
+ t.Fatalf("makeChild: GenerateKeyPair: %v", err)
+ }
+ aid := string(kp.AgentID())
+
refs := make([]event.EventID, len(parents))
prior := make(map[event.EventID]uint64, len(parents))
for i, p := range parents {
@@ -45,14 +54,17 @@
e, err := event.New(
event.EventTypeTransfer,
refs,
- event.TransferPayload{FromAgent: agentID, ToAgent: "sink", Amount: 1, Currency: "AET"},
- agentID,
+ event.TransferPayload{FromAgent: aid, ToAgent: "sink", Amount: 1, Currency: "AET"},
+ aid,
prior,
0,
)
if err != nil {
t.Fatalf("makeChild(%q): %v", agentID, err)
}
+ if err := crypto.SignEvent(e, kp); err != nil {
+ t.Fatalf("makeChild(%q) sign: %v", agentID, err)
+ }
return e
}
@@ -1061,3 +1073,93 @@
t.Errorf("position 4: got agent=%s, want E", sorted[4].AgentID)
}
}
+
+// ---------------------------------------------------------------------------
+// Fix 4A: Signature verification in DAG.Add
+// ---------------------------------------------------------------------------
+
+func TestAdd_UnsignedNonGenesis_Rejected(t *testing.T) {
+ // A non-genesis event with no signature must be rejected.
+ d := dag.New()
+ genesis := makeGenesis(t, "root")
+ mustAdd(t, d, genesis)
+
+ // Create a child event WITHOUT signing it.
+ refs := []event.EventID{genesis.ID}
+ prior := map[event.EventID]uint64{genesis.ID: genesis.CausalTimestamp}
+ child, err := event.New(
+ event.EventTypeTransfer,
+ refs,
+ event.TransferPayload{FromAgent: "attacker", ToAgent: "sink", Amount: 1, Currency: "AET"},
+ "attacker",
+ prior,
+ 0,
+ )
+ if err != nil {
+ t.Fatalf("event.New: %v", err)
+ }
+
+ err = d.Add(child)
+ if err == nil {
+ t.Fatal("Add should reject unsigned non-genesis event, got nil")
+ }
+ if !errors.Is(err, dag.ErrMissingSignature) {
+ t.Errorf("want ErrMissingSignature, got: %v", err)
+ }
+}
+
+func TestAdd_InvalidSignature_Rejected(t *testing.T) {
+ // An event with a garbage signature must be rejected.
+ d := dag.New()
+ genesis := makeGenesis(t, "root")
+ mustAdd(t, d, genesis)
+
+ kp, _ := crypto.GenerateKeyPair()
+ aid := string(kp.AgentID())
+ refs := []event.EventID{genesis.ID}
+ prior := map[event.EventID]uint64{genesis.ID: genesis.CausalTimestamp}
+ child, err := event.New(
+ event.EventTypeTransfer,
+ refs,
+ event.TransferPayload{FromAgent: aid, ToAgent: "sink", Amount: 1, Currency: "AET"},
+ aid,
+ prior,
+ 0,
+ )
+ if err != nil {
+ t.Fatalf("event.New: %v", err)
+ }
+ // Set garbage signature instead of a valid one.
+ child.Signature = make([]byte, 64)
+
+ err = d.Add(child)
+ if err == nil {
+ t.Fatal("Add should reject invalid signature, got nil")
+ }
+ if !errors.Is(err, dag.ErrInvalidSignature) {
+ t.Errorf("want ErrInvalidSignature, got: %v", err)
+ }
+}
+
+func TestAdd_ValidSignature_Accepted(t *testing.T) {
+ // A properly signed non-genesis event must be accepted.
+ d := dag.New()
+ genesis := makeGenesis(t, "root")
+ mustAdd(t, d, genesis)
+
+ child := makeChild(t, "child", genesis)
+ err := d.Add(child)
+ if err != nil {
+ t.Fatalf("Add should accept validly signed event, got: %v", err)
+ }
+}
+
+func TestAdd_GenesisUnsigned_Accepted(t *testing.T) {
+ // Genesis events (no CausalRefs) are allowed unsigned for bootstrap.
+ d := dag.New()
+ g := makeGenesis(t, "bootstrap")
+ err := d.Add(g)
+ if err != nil {
+ t.Fatalf("Add should accept unsigned genesis event, got: %v", err)
+ }
+}
diff -ruN '--exclude=.git' aethernet-main/internal/event/event.go aethernet-fixed/internal/event/event.go
--- aethernet-main/internal/event/event.go 2026-02-26 01:15:06.000000000 +0000
+++ aethernet-fixed/internal/event/event.go 2026-02-27 03:04:06.897292485 +0000
@@ -109,14 +109,18 @@
// and built upon that event. An empty slice marks a genesis (root) event.
CausalRefs []EventID `json:"causal_refs"`
- // Payload holds type-specific structured data. The concrete type depends on
- // the Type field:
+ // Payload holds type-specific structured data as pre-marshaled JSON bytes.
+ // The concrete type depends on the Type field — use GetPayload[T] to decode:
// EventTypeTransfer → TransferPayload
// EventTypeGeneration → GenerationPayload
// EventTypeAttestation → AttestationPayload
// EventTypeVerification → VerificationPayload
// EventTypeDelegation → DelegationPayload
- Payload interface{} `json:"payload"`
+ //
+ // Storing as json.RawMessage ensures deterministic canonical bytes across
+ // network serialization/deserialization boundaries, which is critical for
+ // signature verification after round-trips.
+ Payload json.RawMessage `json:"payload"`
// AgentID is the capability fingerprint of the originating agent.
// AetherNet identity is track-record-based rather than purely key-based:
@@ -160,12 +164,12 @@
// - Signature: circular — signing happens after hashing
// - SettlementState: mutable post-creation metadata, not part of causal identity
type eventCanonical struct {
- Type EventType `json:"type"`
- CausalRefs []EventID `json:"causal_refs"`
- Payload interface{} `json:"payload"`
- AgentID string `json:"agent_id"`
- CausalTimestamp uint64 `json:"causal_timestamp"`
- StakeAmount uint64 `json:"stake_amount"`
+ Type EventType `json:"type"`
+ CausalRefs []EventID `json:"causal_refs"`
+ Payload json.RawMessage `json:"payload"`
+ AgentID string `json:"agent_id"`
+ CausalTimestamp uint64 `json:"causal_timestamp"`
+ StakeAmount uint64 `json:"stake_amount"`
}
// ComputeID derives the content-addressed EventID from an event's canonical fields.
@@ -226,8 +230,6 @@
}
// Normalize nil to empty slice for consistent JSON serialization and hashing.
- // A nil CausalRefs and an empty CausalRefs are semantically identical (both
- // mean "genesis event"), but JSON encodes them differently: null vs [].
if causalRefs == nil {
causalRefs = []EventID{}
}
@@ -235,10 +237,31 @@
priorTimestamps = map[EventID]uint64{}
}
+ // Marshal the payload to json.RawMessage at creation time so that the
+ // canonical bytes are deterministic regardless of how the event is later
+ // serialized/deserialized across the network. This is the fix for the
+ // JSON non-determinism bug where interface{} payloads produced different
+ // canonical bytes after a network round-trip.
+ var rawPayload json.RawMessage
+ if payload != nil {
+ // If already json.RawMessage, use directly.
+ if rm, ok := payload.(json.RawMessage); ok {
+ rawPayload = rm
+ } else {
+ data, err := json.Marshal(payload)
+ if err != nil {
+ return nil, fmt.Errorf("event: failed to marshal payload: %w", err)
+ }
+ rawPayload = data
+ }
+ } else {
+ rawPayload = json.RawMessage("null")
+ }
+
e := &Event{
Type: eventType,
CausalRefs: causalRefs,
- Payload: payload,
+ Payload: rawPayload,
AgentID: agentID,
CausalTimestamp: ComputeCausalTimestamp(causalRefs, priorTimestamps),
StakeAmount: stakeAmount,
@@ -280,6 +303,25 @@
return fmt.Errorf("event: cannot transition settlement state from %q to %q", e.SettlementState, target)
}
+// GetPayload deserializes the event's json.RawMessage Payload into the concrete
+// type T. This is the standard way to extract typed payload data from an event
+// after the Payload field was changed from interface{} to json.RawMessage for
+// deterministic canonical bytes.
+//
+// Usage:
+//
+// tp, err := event.GetPayload[event.TransferPayload](e)
+func GetPayload[T any](e *Event) (T, error) {
+ var result T
+ if e.Payload == nil {
+ return result, fmt.Errorf("event: payload is nil")
+ }
+ if err := json.Unmarshal(e.Payload, &result); err != nil {
+ return result, fmt.Errorf("event: failed to decode payload as %T: %w", result, err)
+ }
+ return result, nil
+}
+
// ---------------------------------------------------------------------------
// Payload types
// ---------------------------------------------------------------------------
diff -ruN '--exclude=.git' aethernet-main/internal/event/event_test.go aethernet-fixed/internal/event/event_test.go
--- aethernet-main/internal/event/event_test.go 2026-02-26 01:15:06.000000000 +0000
+++ aethernet-fixed/internal/event/event_test.go 2026-02-27 03:09:55.571166413 +0000
@@ -1,6 +1,7 @@
package event_test
import (
+ "encoding/json"
"strings"
"testing"
"time"
@@ -64,7 +65,8 @@
t.Error("Signature should be empty until explicitly signed")
}
- p, ok := e.Payload.(event.TransferPayload)
+ p, err := event.GetPayload[event.TransferPayload](e)
+ ok := err == nil
if !ok {
t.Fatalf("Payload type assertion to TransferPayload failed")
}
@@ -104,7 +106,8 @@
t.Errorf("Type = %q, want Generation", e.Type)
}
- p, ok := e.Payload.(event.GenerationPayload)
+ p, err := event.GetPayload[event.GenerationPayload](e)
+ ok := err == nil
if !ok {
t.Fatalf("Payload type assertion to GenerationPayload failed")
}
@@ -148,7 +151,8 @@
t.Errorf("Type = %q, want Attestation", e.Type)
}
- p, ok := e.Payload.(event.AttestationPayload)
+ p, err := event.GetPayload[event.AttestationPayload](e)
+ ok := err == nil
if !ok {
t.Fatalf("Payload type assertion to AttestationPayload failed")
}
@@ -195,7 +199,8 @@
t.Errorf("Type = %q, want Verification", e.Type)
}
- p, ok := e.Payload.(event.VerificationPayload)
+ p, err := event.GetPayload[event.VerificationPayload](e)
+ ok := err == nil
if !ok {
t.Fatalf("Payload type assertion to VerificationPayload failed")
}
@@ -231,7 +236,7 @@
e := mustNew(t, event.EventTypeVerification, []event.EventID{target.ID}, payload, "honest-validator", nil, 8000)
- p := e.Payload.(event.VerificationPayload)
+ p, _ := event.GetPayload[event.VerificationPayload](e)
if p.Verdict {
t.Error("VerificationPayload.Verdict = true, want false for negative verdict")
}
@@ -258,7 +263,8 @@
t.Errorf("Type = %q, want Delegation", e.Type)
}
- p, ok := e.Payload.(event.DelegationPayload)
+ p, err := event.GetPayload[event.DelegationPayload](e)
+ ok := err == nil
if !ok {
t.Fatalf("Payload type assertion to DelegationPayload failed")
}
@@ -719,3 +725,78 @@
t.Errorf("merge CausalTimestamp = %d, want 3 (max(2,2)+1)", merge.CausalTimestamp)
}
}
+
+// ---------------------------------------------------------------------------
+// Fix 4B: json.RawMessage Payload deterministic round-trip
+// ---------------------------------------------------------------------------
+
+func TestPayload_RoundTrip_Deterministic(t *testing.T) {
+ // Marshal an event to JSON, unmarshal it back, and verify the ID is
+ // still correct. This was broken when Payload was interface{}: after
+ // a JSON round-trip, the interface{} lost its concrete type and produced
+ // different canonical bytes.
+ payload := event.TransferPayload{
+ FromAgent: "alice",
+ ToAgent: "bob",
+ Amount: 42,
+ Currency: "AET",
+ }
+ e := mustNew(t, event.EventTypeTransfer, nil, payload, "alice", nil, 100)
+ originalID := e.ID
+
+ data, err := json.Marshal(e)
+ if err != nil {
+ t.Fatalf("Marshal: %v", err)
+ }
+
+ var roundTripped event.Event
+ if err := json.Unmarshal(data, &roundTripped); err != nil {
+ t.Fatalf("Unmarshal: %v", err)
+ }
+
+ recomputedID, err := event.ComputeID(&roundTripped)
+ if err != nil {
+ t.Fatalf("ComputeID after round-trip: %v", err)
+ }
+ if recomputedID != originalID {
+ t.Errorf("ID changed after JSON round-trip:\n original: %s\n recomputed: %s",
+ originalID, recomputedID)
+ }
+}
+
+func TestGetPayload_Transfer(t *testing.T) {
+ payload := event.TransferPayload{
+ FromAgent: "alice",
+ ToAgent: "bob",
+ Amount: 42,
+ Currency: "AET",
+ }
+ e := mustNew(t, event.EventTypeTransfer, nil, payload, "alice", nil, 0)
+
+ got, err := event.GetPayload[event.TransferPayload](e)
+ if err != nil {
+ t.Fatalf("GetPayload: %v", err)
+ }
+ if got.FromAgent != "alice" || got.ToAgent != "bob" || got.Amount != 42 {
+ t.Errorf("GetPayload returned %+v, want FromAgent=alice, ToAgent=bob, Amount=42", got)
+ }
+}
+
+func TestGetPayload_Generation(t *testing.T) {
+ payload := event.GenerationPayload{
+ GeneratingAgent: "gpu-agent",
+ BeneficiaryAgent: "client",
+ ClaimedValue: 1000,
+ EvidenceHash: "sha256:abc",
+ TaskDescription: "inference",
+ }
+ e := mustNew(t, event.EventTypeGeneration, nil, payload, "gpu-agent", nil, 0)
+
+ got, err := event.GetPayload[event.GenerationPayload](e)
+ if err != nil {
+ t.Fatalf("GetPayload: %v", err)
+ }
+ if got.GeneratingAgent != "gpu-agent" || got.ClaimedValue != 1000 {
+ t.Errorf("GetPayload returned %+v", got)
+ }
+}
diff -ruN '--exclude=.git' aethernet-main/internal/ledger/generation.go aethernet-fixed/internal/ledger/generation.go
--- aethernet-main/internal/ledger/generation.go 2026-02-26 01:15:06.000000000 +0000
+++ aethernet-fixed/internal/ledger/generation.go 2026-02-27 03:10:08.043161904 +0000
@@ -94,17 +94,9 @@
return fmt.Errorf("%w: got %q", ErrNotGeneration, e.Type)
}
- var p event.GenerationPayload
- switch v := e.Payload.(type) {
- case event.GenerationPayload:
- p = v
- case *event.GenerationPayload:
- if v == nil {
- return fmt.Errorf("ledger: Generation event %s has nil payload", e.ID)
- }
- p = *v
- default:
- return fmt.Errorf("ledger: Generation event %s payload has unexpected type %T", e.ID, e.Payload)
+ p, err := event.GetPayload[event.GenerationPayload](e)
+ if err != nil {
+ return fmt.Errorf("ledger: Generation event %s: %w", e.ID, err)
}
l.mu.Lock()
diff -ruN '--exclude=.git' aethernet-main/internal/ledger/ledger_test.go aethernet-fixed/internal/ledger/ledger_test.go
--- aethernet-main/internal/ledger/ledger_test.go 2026-02-26 01:15:06.000000000 +0000
+++ aethernet-fixed/internal/ledger/ledger_test.go 2026-02-27 00:26:54.000000000 +0000
@@ -88,6 +88,11 @@
func TestTransferLedger_RecordAndHistory(t *testing.T) {
tl := ledger.NewTransferLedger()
+ // Fund alice so the balance check passes.
+ if err := tl.FundAgent("alice", 10_000); err != nil {
+ t.Fatalf("FundAgent: %v", err)
+ }
+
e := newTransferEvent(t, "alice", "bob", 1_000, nil, nil)
if err := tl.Record(e); err != nil {
t.Fatalf("Record() error: %v", err)
@@ -139,6 +144,11 @@
func TestTransferLedger_Balance_SettledIncoming(t *testing.T) {
tl := ledger.NewTransferLedger()
+ // Fund alice so she can send to bob.
+ if err := tl.FundAgent("alice", 100_000); err != nil {
+ t.Fatalf("FundAgent: %v", err)
+ }
+
e := newTransferEvent(t, "alice", "bob", 5_000, nil, nil)
if err := tl.Record(e); err != nil {
t.Fatalf("Record() error: %v", err)
@@ -169,6 +179,11 @@
func TestTransferLedger_Balance_ReservesOptimisticOutgoing(t *testing.T) {
tl := ledger.NewTransferLedger()
+ // Fund carol so she can send to alice.
+ if err := tl.FundAgent("carol", 100_000); err != nil {
+ t.Fatalf("FundAgent: %v", err)
+ }
+
// carol → alice: 3000, settled immediately.
inbound := newTransferEvent(t, "carol", "alice", 3_000, nil, nil)
if err := tl.Record(inbound); err != nil {
@@ -198,6 +213,10 @@
func TestTransferLedger_PendingOutgoing_OptimisticOnly(t *testing.T) {
tl := ledger.NewTransferLedger()
+ if err := tl.FundAgent("alice", 100_000); err != nil {
+ t.Fatalf("FundAgent: %v", err)
+ }
+
// e1: alice → bob 1000, stays Optimistic.
e1 := newTransferEvent(t, "alice", "bob", 1_000, nil, nil)
if err := tl.Record(e1); err != nil {
@@ -227,6 +246,10 @@
func TestTransferLedger_DuplicateRecord_Error(t *testing.T) {
tl := ledger.NewTransferLedger()
+ if err := tl.FundAgent("alice", 100_000); err != nil {
+ t.Fatalf("FundAgent: %v", err)
+ }
+
e := newTransferEvent(t, "alice", "bob", 500, nil, nil)
if err := tl.Record(e); err != nil {
t.Fatalf("first Record() error: %v", err)
@@ -250,6 +273,10 @@
func TestTransferLedger_Settle_AdvancesState(t *testing.T) {
tl := ledger.NewTransferLedger()
+ if err := tl.FundAgent("alice", 100_000); err != nil {
+ t.Fatalf("FundAgent: %v", err)
+ }
+
e := newTransferEvent(t, "alice", "bob", 100, nil, nil)
if err := tl.Record(e); err != nil {
t.Fatalf("Record() error: %v", err)
@@ -278,6 +305,10 @@
func TestTransferLedger_Settle_InvalidTransition_Error(t *testing.T) {
tl := ledger.NewTransferLedger()
+ if err := tl.FundAgent("alice", 100_000); err != nil {
+ t.Fatalf("FundAgent: %v", err)
+ }
+
e := newTransferEvent(t, "alice", "bob", 100, nil, nil)
if err := tl.Record(e); err != nil {
t.Fatalf("Record() error: %v", err)
@@ -312,6 +343,10 @@
const agent = "pager"
const n = 5
+ if err := tl.FundAgent(crypto.AgentID(agent), 100_000); err != nil {
+ t.Fatalf("FundAgent: %v", err)
+ }
+
// Build a causal chain so each of the 5 events gets a distinct Lamport
// timestamp (1–5), making the sort order fully deterministic.
var prev *event.Event
@@ -392,6 +427,10 @@
tl := ledger.NewTransferLedger()
const agent = "orderer"
+ if err := tl.FundAgent(crypto.AgentID(agent), 100_000); err != nil {
+ t.Fatalf("FundAgent: %v", err)
+ }
+
// Three-event causal chain: ts=1, ts=2, ts=3.
e1 := newTransferEvent(t, agent, "dst-1", 100, nil, nil)
if err := tl.Record(e1); err != nil {
@@ -876,6 +915,14 @@
tl := ledger.NewTransferLedger()
const goroutines = 50
+ // Fund each concurrent sender so the balance check passes.
+ for i := 0; i < goroutines; i++ {
+ from := crypto.AgentID(fmt.Sprintf("concurrent-sender-%d", i))
+ if err := tl.FundAgent(from, 100_000); err != nil {
+ t.Fatalf("FundAgent %s: %v", from, err)
+ }
+ }
+
var wg sync.WaitGroup
wg.Add(goroutines)
for i := 0; i < goroutines; i++ {
@@ -949,3 +996,55 @@
t.Errorf("GenerationHistory(concurrent-gen-0) len = %d, want 1", len(history))
}
}
+
+// ---------------------------------------------------------------------------
+// Fix 3: Balance validation and FundAgent
+// ---------------------------------------------------------------------------
+
+func TestTransferLedger_Record_ZeroBalance_Rejected(t *testing.T) {
+ tl := ledger.NewTransferLedger()
+
+ // alice has no balance — the transfer must be rejected.
+ e := newTransferEvent(t, "alice", "bob", 1_000, nil, nil)
+ err := tl.Record(e)
+ if err == nil {
+ t.Fatal("Record should reject transfer from zero-balance sender")
+ }
+ if !errors.Is(err, ledger.ErrInsufficientBalance) {
+ t.Errorf("want ErrInsufficientBalance, got %v", err)
+ }
+}
+
+func TestTransferLedger_Record_Overdraft_Rejected(t *testing.T) {
+ tl := ledger.NewTransferLedger()
+
+ if err := tl.FundAgent("alice", 500); err != nil {
+ t.Fatalf("FundAgent: %v", err)
+ }
+
+ // alice has 500 but tries to send 1000.
+ e := newTransferEvent(t, "alice", "bob", 1_000, nil, nil)
+ err := tl.Record(e)
+ if err == nil {
+ t.Fatal("Record should reject overdraft transfer")
+ }
+ if !errors.Is(err, ledger.ErrInsufficientBalance) {
+ t.Errorf("want ErrInsufficientBalance, got %v", err)
+ }
+}
+
+func TestTransferLedger_FundAgent_CreatesSettledEntry(t *testing.T) {
+ tl := ledger.NewTransferLedger()
+
+ if err := tl.FundAgent("bob", 5_000); err != nil {
+ t.Fatalf("FundAgent: %v", err)
+ }
+
+ bal, err := tl.Balance(crypto.AgentID("bob"))
+ if err != nil {
+ t.Fatalf("Balance: %v", err)
+ }
+ if bal != 5_000 {
+ t.Errorf("Balance = %d, want 5000 after FundAgent", bal)
+ }
+}
diff -ruN '--exclude=.git' aethernet-main/internal/ledger/transfer.go aethernet-fixed/internal/ledger/transfer.go
--- aethernet-main/internal/ledger/transfer.go 2026-02-26 01:15:06.000000000 +0000
+++ aethernet-fixed/internal/ledger/transfer.go 2026-02-27 03:10:16.910158698 +0000
@@ -37,6 +37,10 @@
// ErrInvalidTransition is returned when Settle requests a settlement state
// progression that violates the OCS lifecycle rules.
ErrInvalidTransition = errors.New("ledger: invalid settlement state transition")
+
+ // ErrInsufficientBalance is returned when a transfer's FromAgent does not
+ // have enough spendable balance to cover the transfer amount.
+ ErrInsufficientBalance = errors.New("ledger: insufficient balance")
)
// TransferEntry is a single record in the Transfer Ledger. It captures the
@@ -100,19 +104,9 @@
return fmt.Errorf("%w: got %q", ErrNotTransfer, e.Type)
}
- // Accept both value and pointer forms of TransferPayload so callers are not
- // constrained by how they constructed the event.
- var p event.TransferPayload
- switch v := e.Payload.(type) {
- case event.TransferPayload:
- p = v
- case *event.TransferPayload:
- if v == nil {
- return fmt.Errorf("ledger: Transfer event %s has nil payload", e.ID)
- }
- p = *v
- default:
- return fmt.Errorf("ledger: Transfer event %s payload has unexpected type %T", e.ID, e.Payload)
+ p, err := event.GetPayload[event.TransferPayload](e)
+ if err != nil {
+ return fmt.Errorf("ledger: Transfer event %s: %w", e.ID, err)
}
l.mu.Lock()
@@ -122,6 +116,17 @@
return fmt.Errorf("%w: %s", ErrDuplicateEntry, e.ID)
}
+ // Balance validation: the sender must have enough spendable balance to
+ // cover this transfer. Skip the check for the "system" agent which is
+ // the source of genesis credits (FundAgent).
+ if string(p.FromAgent) != "system" && p.Amount > 0 {
+ available := l.balanceLocked(crypto.AgentID(p.FromAgent))
+ if available < p.Amount {
+ return fmt.Errorf("%w: agent %s balance %d < transfer amount %d",
+ ErrInsufficientBalance, p.FromAgent, available, p.Amount)
+ }
+ }
+
l.entries[e.ID] = &TransferEntry{
EventID: e.ID,
FromAgent: crypto.AgentID(p.FromAgent),
@@ -190,7 +195,13 @@
func (l *TransferLedger) Balance(agentID crypto.AgentID) (uint64, error) {
l.mu.RLock()
defer l.mu.RUnlock()
+ return l.balanceLocked(agentID), nil
+}
+// balanceLocked computes the spendable balance while the caller already holds
+// at least a read lock on l.mu. Extracted so Record can call it under the write
+// lock without double-locking.
+func (l *TransferLedger) balanceLocked(agentID crypto.AgentID) uint64 {
var inSettled, outReserved uint64
for _, e := range l.entries {
if e.ToAgent == agentID && e.Settlement == event.SettlementSettled {
@@ -203,9 +214,51 @@
}
if outReserved >= inSettled {
- return 0, nil
+ return 0
+ }
+ return inSettled - outReserved
+}
+
+// BalanceCheck returns an error if agentID does not have enough spendable
+// balance to cover amount. It is a convenience wrapper used by the OCS engine
+// before recording a transfer.
+func (l *TransferLedger) BalanceCheck(agentID crypto.AgentID, amount uint64) error {
+ l.mu.RLock()
+ defer l.mu.RUnlock()
+ if l.balanceLocked(agentID) < amount {
+ return fmt.Errorf("%w: agent %s has insufficient funds for %d", ErrInsufficientBalance, agentID, amount)
+ }
+ return nil
+}
+
+// FundAgent creates a genesis credit entry that grants initial funds to an agent.
+// This is the only path through which new balance enters the Transfer Ledger
+// outside of normal settled transfers. Used for initial staking and test setup.
+// The entry is created in Settled state so it is immediately spendable.
+func (l *TransferLedger) FundAgent(agentID crypto.AgentID, amount uint64) error {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+
+ // Create a synthetic settled entry with a deterministic ID based on the
+ // agent and amount, using a "genesis:" prefix to avoid collisions with
+ // content-addressed event IDs.
+ eid := event.EventID(fmt.Sprintf("genesis:%s:%d:%d", agentID, amount, len(l.entries)))
+ if _, exists := l.entries[eid]; exists {
+ return fmt.Errorf("%w: %s", ErrDuplicateEntry, eid)
+ }
+
+ l.entries[eid] = &TransferEntry{
+ EventID: eid,
+ FromAgent: "system",
+ ToAgent: agentID,
+ Amount: amount,
+ Currency: "AET",
+ Memo: "genesis credit",
+ Timestamp: 0,
+ Settlement: event.SettlementSettled,
+ RecordedAt: time.Now(),
}
- return inSettled - outReserved, nil
+ return nil
}
// PendingOutgoing returns the total outgoing amount across all Optimistic
diff -ruN '--exclude=.git' aethernet-main/internal/network/node.go aethernet-fixed/internal/network/node.go
--- aethernet-main/internal/network/node.go 2026-02-26 01:15:06.000000000 +0000
+++ aethernet-fixed/internal/network/node.go 2026-02-27 03:08:39.214194022 +0000
@@ -2,6 +2,7 @@
import (
"context"
+ "crypto/rand"
"encoding/json"
"errors"
"fmt"
@@ -39,6 +40,11 @@
// Version is the protocol version string, included in every handshake.
Version string
+
+ // KeyPair is this node's Ed25519 keypair, used for challenge-response
+ // authentication during the handshake. Both sides sign the other's challenge
+ // with their private key to prove identity.
+ KeyPair *crypto.KeyPair
}
// DefaultNodeConfig returns a NodeConfig with production-ready defaults.
@@ -142,9 +148,8 @@
n.wg.Wait()
}
-// Connect dials the node at address, performs the two-way handshake, registers
-// the peer, and starts its read/write goroutines. Returns the connected Peer on
-// success, or an error if the dial, handshake, or peer-limit check fails.
+// Connect dials the node at address, performs the two-way challenge-response
+// handshake, registers the peer, and starts its read/write goroutines.
func (n *Node) Connect(address string) (*Peer, error) {
conn, err := net.Dial("tcp", address)
if err != nil {
@@ -153,12 +158,25 @@
peer := NewPeer("", address, conn)
- // Connecting side sends its handshake first.
+ // Generate a challenge for the remote side to sign.
+ myChallenge := make([]byte, 32)
+ if _, err := rand.Read(myChallenge); err != nil {
+ conn.Close()
+ return nil, fmt.Errorf("network: generate challenge: %w", err)
+ }
+
+ // Connecting side sends its handshake first (with challenge, no response yet).
tips := n.dag.Tips()
+ var pubKey []byte
+ if n.config.KeyPair != nil {
+ pubKey = n.config.KeyPair.PublicKey
+ }
hsPayload, err := json.Marshal(HandshakePayload{
- AgentID: n.config.AgentID,
- Version: n.config.Version,
- TipCount: len(tips),
+ AgentID: n.config.AgentID,
+ Version: n.config.Version,
+ TipCount: len(tips),
+ Challenge: myChallenge,
+ PublicKey: pubKey,
})
if err != nil {
conn.Close()
@@ -169,7 +187,7 @@
return nil, fmt.Errorf("network: send handshake: %w", err)
}
- // Then read the acceptor's handshake response.
+ // Read the acceptor's handshake response (contains their challenge + response to ours).
var reply Message
if err := peer.dec.Decode(&reply); err != nil {
conn.Close()
@@ -185,6 +203,33 @@
return nil, fmt.Errorf("network: decode handshake response: %w", err)
}
+ // Verify the acceptor's response to our challenge.