-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathsphinx_test.go
More file actions
1545 lines (1288 loc) · 46.9 KB
/
sphinx_test.go
File metadata and controls
1545 lines (1288 loc) · 46.9 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
package sphinx
import (
"bytes"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"reflect"
"testing"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/davecgh/go-spew/spew"
"github.com/stretchr/testify/require"
)
// BOLT 4 Test Vectors
var (
// bolt4PubKeys are the public keys of the hops used in the route.
bolt4PubKeys = []string{
"02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619",
"0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c",
"027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007",
"032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991",
"02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145",
}
// bolt4SessionKey is the session private key.
bolt4SessionKey = bytes.Repeat([]byte{'A'}, 32)
// bolt4AssocData is the associated data added to the packet.
bolt4AssocData = bytes.Repeat([]byte{'B'}, 32)
// bolt4FinalPacketHex encodes the expected sphinx packet as a result of
// creating a new packet with the above parameters.
bolt4FinalPacketHex = "0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a71e87f9aab8f6378c6ff744c1f34b393ad28d065b535c1a8668d85d3b34a1b3befd10f7d61ab590531cf08000178a333a347f8b4072e216400406bdf3bf038659793a1f9e7abc789266cc861cabd95818c0fc8efbdfdc14e3f7c2bc7eb8d6a79ef75ce721caad69320c3a469a202f3e468c67eaf7a7cda226d0fd32f7b48084dca885d014698cf05d742557763d9cb743faeae65dcc79dddaecf27fe5942be5380d15e9a1ec866abe044a9ad635778ba61fc0776dc832b39451bd5d35072d2269cf9b040a2a2fba158a0d8085926dc2e44f0c88bf487da56e13ef2d5e676a8589881b4869ed4c7f0218ff8c6c7dd7221d189c65b3b9aaa71a01484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565a9f99728426ce2380a9580e2a9442481ceae7679906c30b1a0e21a10f26150e0645ab6edfdab1ce8f8bea7b1dee511c5fd38ac0e702c1c15bb86b52bca1b71e15b96982d262a442024c33ceb7dd8f949063c2e5e613e873250e2f8708bd4e1924abd45f65c2fa5617bfb10ee9e4a42d6b5811acc8029c16274f937dac9e8817c7e579fdb767ffe277f26d413ced06b620ede8362081da21cf67c2ca9d6f15fe5bc05f82f5bb93f8916bad3d63338ca824f3bbc11b57ce94a5fa1bc239533679903d6fec92a8c792fd86e2960188c14f21e399cfd72a50c620e10aefc6249360b463df9a89bf6836f4f26359207b765578e5ed76ae9f31b1cc48324be576e3d8e44d217445dba466f9b6293fdf05448584eb64f61e02903f834518622b7d4732471c6e0e22e22d1f45e31f0509eab39cdea5980a492a1da2aaac55a98a01216cd4bfe7abaa682af0fbff2dfed030ba28f1285df750e4d3477190dd193f8643b61d8ac1c427d590badb1f61a05d480908fbdc7c6f0502dd0c4abb51d725e92f95da2a8facb79881a844e2026911adcc659d1fb20a2fce63787c8bb0d9f6789c4b231c76da81c3f0718eb7156565a081d2be6b4170c0e0bcebddd459f53db2590c974bca0d705c055dee8c629bf854a5d58edc85228499ec6dde80cce4c8910b81b1e9e8b0f43bd39c8d69c3a80672729b7dc952dd9448688b6bd06afc2d2819cda80b66c57b52ccf7ac1a86601410d18d0c732f69de792e0894a9541684ef174de766fd4ce55efea8f53812867be6a391ac865802dbc26d93959df327ec2667c7256aa5a1d3c45a69a6158f285d6c97c3b8eedb09527848500517995a9eae4cd911df531544c77f5a9a2f22313e3eb72ca7a07dba243476bc926992e0d1e58b4a2fc8c7b01e0cad726237933ea319bad7537d39f3ed635d1e6c1d29e97b3d2160a09e30ee2b65ac5bce00996a73c008bcf351cecb97b6833b6d121dcf4644260b2946ea204732ac9954b228f0beaa15071930fd9583dfc466d12b5f0eeeba6dcf23d5ce8ae62ee5796359d97a4a15955c778d868d0ef9991d9f2833b5bb66119c5f8b396fd108baed7906cbb3cc376d13551caed97fece6f42a4c908ee279f1127fda1dd3ee77d8de0a6f3c135fa3f1cffe38591b6738dc97b55f0acc52be9753ce53e64d7e497bb00ca6123758df3b68fad99e35c04389f7514a8e36039f541598a417275e77869989782325a15b5342ac5011ff07af698584b476b35d941a4981eac590a07a092bb50342da5d3341f901aa07964a8d02b623c7b106dd0ae50bfa007a22d46c8772fa55558176602946cb1d11ea5460db7586fb89c6d3bcd3ab6dd20df4a4db63d2e7d52380800ad812b8640887e027e946df96488b47fbc4a4fadaa8beda4abe446fafea5403fae2ef"
testLegacyRouteNumHops = 20
)
// Static errors used in tests.
var (
// ErrInsufficientHops is returned when there are not enough hops to
// create a route.
ErrInsufficientHops = errors.New("at least 1 hop is required to " +
"create an onion message route")
)
// Session keys used in onion message tests.
var (
sessionKeyA = bytes.Repeat([]byte{'A'}, 32)
sessionKeyB = bytes.Repeat([]byte{'B'}, 32)
sessionKeyC = bytes.Repeat([]byte{'C'}, 32)
)
// encodeTLVRecord encodes a TLV record with the given type and value.
func encodeTLVRecord(recordType uint64, value []byte) []byte {
var buf bytes.Buffer
// Encode type as varint
writeVarInt(&buf, recordType)
// Encode length as varint
writeVarInt(&buf, uint64(len(value)))
// Write value
buf.Write(value)
return buf.Bytes()
}
// writeVarInt writes a variable-length integer to the buffer.
func writeVarInt(buf *bytes.Buffer, n uint64) {
switch {
case n < 0xfd:
buf.WriteByte(byte(n))
case n <= 0xffff:
buf.WriteByte(0xfd)
buf.WriteByte(byte(n))
buf.WriteByte(byte(n >> 8))
case n <= 0xffffffff:
buf.WriteByte(0xfe)
buf.WriteByte(byte(n))
buf.WriteByte(byte(n >> 8))
buf.WriteByte(byte(n >> 16))
buf.WriteByte(byte(n >> 24))
default:
buf.WriteByte(0xff)
buf.WriteByte(byte(n))
buf.WriteByte(byte(n >> 8))
buf.WriteByte(byte(n >> 16))
buf.WriteByte(byte(n >> 24))
buf.WriteByte(byte(n >> 32))
buf.WriteByte(byte(n >> 40))
buf.WriteByte(byte(n >> 48))
buf.WriteByte(byte(n >> 56))
}
}
func newTestRoute(numHops int) ([]*Router, *PaymentPath, *[]HopData, *OnionPacket, error) {
nodes := make([]*Router, numHops)
// Create numHops random sphinx nodes.
for i := 0; i < len(nodes); i++ {
privKey, _ := btcec.NewPrivateKey()
nodes[i] = NewRouter(
&PrivKeyECDH{PrivKey: privKey}, NewMemoryReplayLog(),
)
}
// Gather all the pub keys in the path.
var (
route PaymentPath
)
for i := 0; i < len(nodes); i++ {
hopData := HopData{
ForwardAmount: uint64(i),
OutgoingCltv: uint32(i),
}
copy(hopData.NextAddress[:], bytes.Repeat([]byte{byte(i)}, 8))
hopPayload, err := NewLegacyHopPayload(&hopData)
if err != nil {
return nil, nil, nil, nil, fmt.Errorf("unable to "+
"create new hop payload: %v", err)
}
route[i] = OnionHop{
NodePub: *nodes[i].onionKey.PubKey(),
HopPayload: hopPayload,
}
}
// Generate a forwarding message to route to the final node via the
// generated intermediate nodes above. Destination should be Hash160,
// adding padding so parsing still works.
sessionKey, _ := btcec.PrivKeyFromBytes(bytes.Repeat([]byte{'A'}, 32))
fwdMsg, err := NewOnionPacket(
&route, sessionKey, nil, DeterministicPacketFiller,
)
if err != nil {
return nil, nil, nil, nil, fmt.Errorf("unable to create "+
"forwarding message: %#v", err)
}
var hopsData []HopData
for i := 0; i < len(nodes); i++ {
hopData, err := route[i].HopPayload.HopData()
if err != nil {
return nil, nil, nil, nil, fmt.Errorf("unable to "+
"gen hop data: %v", err)
}
hopsData = append(hopsData, *hopData)
}
return nodes, &route, &hopsData, fwdMsg, nil
}
// newOnionMessageRoute creates a new onion message route with the specified
// number of hops. It concatenates two blinded paths right in the middle of the
// route, hence it needs at least 2 hops.
func newOnionMessageRoute(numHops int, lastHopMessage []byte) (*OnionPacket,
*PaymentPath, []*Router, *BlindedPath, error) {
if numHops < 1 {
return nil, nil, nil, nil, ErrInsufficientHops
}
// Create routers for each hop.
nodes := make([]*Router, numHops)
for i := range nodes {
privKey, _ := btcec.NewPrivateKey()
nodes[i] = NewRouter(
&PrivKeyECDH{PrivKey: privKey}, NewMemoryReplayLog(),
)
}
// Split the nodes into two parts for creating two blinded paths. If
// numHops equals one, this will create an empty first path.
mid := numHops / 2
firstPathNodes := nodes[:mid]
secondPathNodes := nodes[mid:]
// Create the sessions keys for the two blinded paths.
firstSessionKey, _ := btcec.PrivKeyFromBytes(sessionKeyA)
secondSessionKey, _ := btcec.PrivKeyFromBytes(sessionKeyB)
// Create the first blinded path, adding a next_path_key_override TLV
// at the last node.
blindedPath, err := createBlindedPath(
firstPathNodes, secondPathNodes, firstSessionKey,
secondSessionKey,
)
if err != nil {
return nil, nil, nil, nil, err
}
// Create the route from the blinded path, always adding the
// hop.CipherText as a TLV field type 4.
var route PaymentPath
for i, hop := range blindedPath.BlindedHops {
var b bytes.Buffer
if i == len(blindedPath.BlindedHops)-1 {
// Encode TLV record for type 4 (cipher text)
b.Write(encodeTLVRecord(4, hop.CipherText))
// Encode TLV record for type 65 (hello message)
b.Write(encodeTLVRecord(65, lastHopMessage))
} else {
// Encode TLV record for type 4 (cipher text)
b.Write(encodeTLVRecord(4, hop.CipherText))
}
route[i] = OnionHop{
NodePub: *hop.BlindedNodePub,
HopPayload: HopPayload{
Type: PayloadTLV,
Payload: b.Bytes(),
},
}
}
// According to BOLT04 we SHOULD set onion_message_packet len to 1366 or
// 32834. This means a payload size of 1300 (MaxRoutingPayloadSize) or
// 32768 (MaxOnionMessagePayloadSize) bytes. By checking the total
// payload size of the route we can determine which one to use.
payloadSize := MaxRoutingPayloadSize
if route.TotalPayloadSize() > MaxRoutingPayloadSize {
payloadSize = MaxOnionMessagePayloadSize
}
// Generate the onion packet.
sessionKey, _ := btcec.PrivKeyFromBytes(sessionKeyC)
onionPacket, err := NewOnionPacket(
&route, sessionKey, nil, DeterministicPacketFiller,
WithMaxPayloadSize(payloadSize),
)
if err != nil {
return nil, nil, nil, nil, err
}
return onionPacket, &route, nodes, blindedPath, nil
}
func createBlindedPath(firstPathNodes []*Router, secondPathNodes []*Router,
firstSessionKey *btcec.PrivateKey,
secondSessionKey *btcec.PrivateKey) (*BlindedPath, error) {
firstPathInfos := make([]*HopInfo, len(firstPathNodes))
for i, node := range firstPathNodes {
nextNodeID := node.onionKey.PubKey().SerializeCompressed()
var b bytes.Buffer
if i == len(firstPathNodes)-1 {
secondsSessPub := secondSessionKey.PubKey()
pathKeyOverride := secondsSessPub.SerializeCompressed()
// Encode TLV record for type 4 (next node ID)
b.Write(encodeTLVRecord(4, nextNodeID))
// Encode TLV record for type 8 (path key override)
b.Write(encodeTLVRecord(8, pathKeyOverride))
} else {
// Encode TLV record for type 4 (next node ID)
b.Write(encodeTLVRecord(4, nextNodeID))
}
firstPathInfos[i] = &HopInfo{
NodePub: node.onionKey.PubKey(),
PlainText: b.Bytes(),
}
}
// The first blinded path may be empty if the sender has a direct
// channel with the introduction point.
var firstBlindedPath *BlindedPathInfo
if len(firstPathNodes) > 0 {
var err error
firstBlindedPath, err = BuildBlindedPath(
firstSessionKey, firstPathInfos,
)
if err != nil {
return nil, err
}
}
// Create the second blinded path, omitting the next_node_id TLV for the
// last node.
secondPathInfos := make([]*HopInfo, len(secondPathNodes))
for i, node := range secondPathNodes {
nextNodeID := node.onionKey.PubKey().SerializeCompressed()
var b bytes.Buffer
if i == len(secondPathNodes)-1 {
pathID := make([]byte, 20)
_, err := rand.Read(pathID)
if err != nil {
return nil, err
}
// Encode TLV record for type 6 (path ID)
b.Write(encodeTLVRecord(6, pathID))
} else {
// Encode TLV record for type 4 (next node ID)
b.Write(encodeTLVRecord(4, nextNodeID))
}
secondPathInfos[i] = &HopInfo{
NodePub: node.onionKey.PubKey(),
PlainText: b.Bytes(),
}
}
secondBlindedPath, err := BuildBlindedPath(
secondSessionKey, secondPathInfos,
)
if err != nil {
return nil, err
}
var blindedPath *BlindedPath
if len(firstPathNodes) == 0 {
// If the sender has a direct channel to the introduction point
// of the blinded path the receiver gave us, then the sender
// doesn't need to create its own blinded path. We can just use
// the receiver's blinded path as is.
blindedPath = secondBlindedPath.Path
} else {
// Otherwise, we use the introduction point of the blinded path
// created by the sender and concatenate the hops of both paths.
introductionPoint := firstBlindedPath.Path.IntroductionPoint
blindingPoint := firstBlindedPath.Path.BlindingPoint
blindedPath = &BlindedPath{
IntroductionPoint: introductionPoint,
BlindingPoint: blindingPoint,
BlindedHops: append(
firstBlindedPath.Path.BlindedHops,
secondBlindedPath.Path.BlindedHops...,
),
}
}
return blindedPath, nil
}
func TestBolt4Packet(t *testing.T) {
var (
route PaymentPath
)
for i, pubKeyHex := range bolt4PubKeys {
pubKeyBytes, err := hex.DecodeString(pubKeyHex)
if err != nil {
t.Fatalf("unable to decode BOLT 4 hex pubkey #%d: %v", i, err)
}
pubKey, err := btcec.ParsePubKey(pubKeyBytes)
if err != nil {
t.Fatalf("unable to parse BOLT 4 pubkey #%d: %v", i, err)
}
hopData := HopData{
ForwardAmount: uint64(i),
OutgoingCltv: uint32(i),
}
copy(hopData.NextAddress[:], bytes.Repeat([]byte{byte(i)}, 8))
hopPayload, err := NewLegacyHopPayload(&hopData)
if err != nil {
t.Fatalf("unable to make hop payload: %v", err)
}
route[i] = OnionHop{
NodePub: *pubKey,
HopPayload: hopPayload,
}
}
finalPacket, err := hex.DecodeString(bolt4FinalPacketHex)
if err != nil {
t.Fatalf("unable to decode BOLT 4 final onion packet from hex: "+
"%v", err)
}
sessionKey, _ := btcec.PrivKeyFromBytes(bolt4SessionKey)
pkt, err := NewOnionPacket(
&route, sessionKey, bolt4AssocData, DeterministicPacketFiller,
)
if err != nil {
t.Fatalf("unable to construct onion packet: %v", err)
}
var b bytes.Buffer
if err := pkt.Encode(&b); err != nil {
t.Fatalf("unable to decode onion packet: %v", err)
}
if !bytes.Equal(b.Bytes(), finalPacket) {
t.Fatalf("final packet does not match expected BOLT 4 packet, "+
"want: %s, got %s", hex.EncodeToString(finalPacket),
hex.EncodeToString(b.Bytes()))
}
}
// TestTLVPayloadMessagePacket tests the creation and encoding of an
// onion_message_packet that uses a TLV payload for each hop in the route. This
// test uses the test vectors defined in the BOLT 4 specification. The test
// reads a JSON file containing a predefined route, session key, and the
// expected final onion_message_packet. It then constructs the route hop-by-hop,
// manually creating the TLV payload for each, before creating a new onion
// packet with NewOnionPacket. The test concludes by asserting that the newly
// encoded packet is identical to the one specified in the test vector.
func TestTLVPayloadMessagePacket(t *testing.T) {
t.Parallel()
// First, we'll read out the raw JSON file at the target location.
jsonBytes, err := os.ReadFile(testOnionMessageFileName)
require.NoError(t, err)
// Once we have the raw file, we'll unpack it into our
// onionMessageJsonTestCase struct defined in path_test.go.
testCase := &onionMessageJsonTestCase{}
require.NoError(t, json.Unmarshal(jsonBytes, testCase))
// Next, we'll populate a new OnionHop using the information included
// in this test case.
var route PaymentPath
for i, hop := range testCase.Route.Hops {
blindedPKbytes, err := hex.DecodeString(hop.BlindedNodeID)
require.NoError(t, err)
blindedPubKey, err := btcec.ParsePubKey(blindedPKbytes)
require.NoError(t, err)
encryptedRecipientData, err := hex.DecodeString(
hop.EncryptedRecipientData,
)
require.NoError(t, err)
// Manually encode our onion payload
var b bytes.Buffer
if i == len(testCase.Route.Hops)-1 {
helloBytes := []byte("hello")
// Encode TLV record for type 1 (hello message)
b.Write(encodeTLVRecord(1, helloBytes))
}
// Encode TLV record for type 4 (encrypted recipient data)
b.Write(encodeTLVRecord(4, encryptedRecipientData))
route[i] = OnionHop{
NodePub: *blindedPubKey,
HopPayload: HopPayload{
// Onion messages always use TLV payloads.
Type: PayloadTLV,
Payload: b.Bytes(),
},
}
}
finalPacket, err := hex.DecodeString(
testCase.OnionMessage.OnionMessagePacket,
)
require.NoError(t, err)
sessionKeyBytes, err := hex.DecodeString(testCase.Generate.SessionKey)
require.NoError(t, err)
// With all the required data assembled, we'll craft a new packet.
sessionKey, _ := btcec.PrivKeyFromBytes(sessionKeyBytes)
pkt, err := NewOnionPacket(
&route, sessionKey, nil, DeterministicPacketFiller,
)
require.NoError(t, err)
var b bytes.Buffer
require.NoError(t, pkt.Encode(&b))
// Finally, we expect that our packet matches the packet included in
// the spec's test vectors.
require.Equalf(t, finalPacket, b.Bytes(), "final packet does not "+
"match expected BOLT 4 packet, want: %s, got %s",
hex.EncodeToString(finalPacket), hex.EncodeToString(b.Bytes()))
}
// TestProcessOnionMessageZeroLengthPayload tests that we can properly process
// an onion message that has a zero-length payload.
func TestProcessOnionMessageZeroLengthPayload(t *testing.T) {
t.Parallel()
// First, create a router that will be the destination of the onion
// message.
privKey, err := btcec.NewPrivateKey()
require.NoError(t, err)
router := NewRouter(&PrivKeyECDH{privKey}, NewMemoryReplayLog())
err = router.Start()
require.NoError(t, err)
defer router.Stop()
// Next, create a session key for the onion packet.
sessionKey, err := btcec.NewPrivateKey()
require.NoError(t, err)
// We'll create a simple one-hop path.
path := &PaymentPath{
{
NodePub: *privKey.PubKey(),
},
}
// The hop payload will be an empty TLV payload.
payload, err := NewTLVHopPayload(nil)
require.NoError(t, err)
require.Empty(t, payload.Payload)
path[0].HopPayload = payload
// Now, create the onion packet.
onionPacket, err := NewOnionPacket(
path, sessionKey, nil, DeterministicPacketFiller,
)
require.NoError(t, err)
// We'll now process the packet, making sure to indicate that this is
// an onion message.
processedPacket, err := router.ProcessOnionPacket(
onionPacket, nil, 0, WithTLVPayloadOnly(),
)
require.NoError(t, err)
// The packet should be decoded as an exit node.
require.EqualValues(t, ExitNode, processedPacket.Action)
// The payload should be of type TLV.
require.Equal(t, PayloadTLV, processedPacket.Payload.Type)
// And the payload should be empty.
require.Empty(t, processedPacket.Payload.Payload)
}
func TestSphinxCorrectness(t *testing.T) {
nodes, _, hopDatas, fwdMsg, err := newTestRoute(testLegacyRouteNumHops)
if err != nil {
t.Fatalf("unable to create random onion packet: %v", err)
}
// Now simulate the message propagating through the mix net eventually
// reaching the final destination.
for i := 0; i < len(nodes); i++ {
// Start each node's ReplayLog and defer shutdown
nodes[i].log.Start()
defer nodes[i].log.Stop()
hop := nodes[i]
t.Logf("Processing at hop: %v \n", i)
onionPacket, err := hop.ProcessOnionPacket(
fwdMsg, nil, uint32(i)+1,
)
if err != nil {
t.Fatalf("Node %v was unable to process the "+
"forwarding message: %v", i, err)
}
// The hop data for this hop should *exactly* match what was
// initially used to construct the packet.
expectedHopData := (*hopDatas)[i]
if !reflect.DeepEqual(*onionPacket.ForwardingInstructions, expectedHopData) {
t.Fatalf("hop data doesn't match: expected %v, got %v",
spew.Sdump(expectedHopData),
spew.Sdump(onionPacket.ForwardingInstructions))
}
// If this is the last hop on the path, the node should
// recognize that it's the exit node.
if i == len(nodes)-1 {
if onionPacket.Action != ExitNode {
t.Fatalf("Processing error, node %v is the last hop in "+
"the path, yet it doesn't recognize so", i)
}
} else {
// If this isn't the last node in the path, then the
// returned action should indicate that there are more
// hops to go.
if onionPacket.Action != MoreHops {
t.Fatalf("Processing error, node %v is not the final"+
" hop, yet thinks it is.", i)
}
// The next hop should have been parsed as node[i+1].
parsedNextHop := onionPacket.ForwardingInstructions.NextAddress[:]
expected := bytes.Repeat([]byte{byte(i)}, AddressSize)
require.Equal(t, expected, parsedNextHop)
fwdMsg = onionPacket.NextPacket
}
}
}
func TestSphinxSingleHop(t *testing.T) {
// We'd like to test the proper behavior of the correctness of onion
// packet processing for "single-hop" payments which bare a full onion
// packet.
nodes, _, _, fwdMsg, err := newTestRoute(1)
if err != nil {
t.Fatalf("unable to create test route: %v", err)
}
// Start the ReplayLog and defer shutdown
nodes[0].log.Start()
defer nodes[0].log.Stop()
// Simulating a direct single-hop payment, send the sphinx packet to
// the destination node, making it process the packet fully.
processedPacket, err := nodes[0].ProcessOnionPacket(fwdMsg, nil, 1)
if err != nil {
t.Fatalf("unable to process sphinx packet: %v", err)
}
// The destination node should detect that the packet is destined for
// itself.
if processedPacket.Action != ExitNode {
t.Fatalf("processed action is incorrect, is %v should be %v",
processedPacket.Action, ExitNode)
}
}
func TestSphinxNodeReplay(t *testing.T) {
t.Parallel()
// We'd like to ensure that the sphinx node itself rejects all replayed
// packets which share the same shared secret.
nodes, _, _, fwdMsg, err := newTestRoute(testLegacyRouteNumHops)
if err != nil {
t.Fatalf("unable to create test route: %v", err)
}
// Start the ReplayLog and defer shutdown
nodes[0].log.Start()
defer nodes[0].log.Stop()
// Allow the node to process the initial packet, this should proceed
// without any failures.
_, err = nodes[0].ProcessOnionPacket(fwdMsg, nil, 1)
if err != nil {
t.Fatalf("unable to process sphinx packet: %v", err)
}
// Now, force the node to process the packet a second time, this should
// fail with a detected replay error.
_, err = nodes[0].ProcessOnionPacket(fwdMsg, nil, 1)
if err != ErrReplayedPacket {
t.Fatalf("sphinx packet replay should be rejected, instead "+
"error is %v", err)
}
}
func TestSphinxNodeReplaySameBatch(t *testing.T) {
t.Parallel()
// We'd like to ensure that the sphinx node itself rejects all replayed
// packets which share the same shared secret.
nodes, _, _, fwdMsg, err := newTestRoute(testLegacyRouteNumHops)
if err != nil {
t.Fatalf("unable to create test route: %v", err)
}
// Start the ReplayLog and defer shutdown
nodes[0].log.Start()
defer nodes[0].log.Stop()
tx := nodes[0].BeginTxn([]byte("0"), 2)
// Allow the node to process the initial packet, this should proceed
// without any failures.
if err := tx.ProcessOnionPacket(0, fwdMsg, nil, 1); err != nil {
t.Fatalf("unable to process sphinx packet: %v", err)
}
// Now, force the node to process the packet a second time, this call
// should not fail, even though the batch has internally recorded this
// as a duplicate.
err = tx.ProcessOnionPacket(1, fwdMsg, nil, 1)
if err != nil {
t.Fatalf("adding duplicate sphinx packet to batch should not "+
"result in an error, instead got: %v", err)
}
// Commit the batch to disk, then we will inspect the replay set to
// ensure the duplicate entry was properly included.
_, replaySet, err := tx.Commit()
if err != nil {
t.Fatalf("unable to commit batch of sphinx packets: %v", err)
}
if replaySet.Contains(0) {
t.Fatalf("index 0 was not expected to be in replay set")
}
if !replaySet.Contains(1) {
t.Fatalf("expected replay set to contain duplicate packet " +
"at index 1")
}
}
func TestSphinxNodeReplayLaterBatch(t *testing.T) {
t.Parallel()
// We'd like to ensure that the sphinx node itself rejects all replayed
// packets which share the same shared secret.
nodes, _, _, fwdMsg, err := newTestRoute(testLegacyRouteNumHops)
if err != nil {
t.Fatalf("unable to create test route: %v", err)
}
// Start the ReplayLog and defer shutdown
nodes[0].log.Start()
defer nodes[0].log.Stop()
tx := nodes[0].BeginTxn([]byte("0"), 1)
// Allow the node to process the initial packet, this should proceed
// without any failures.
err = tx.ProcessOnionPacket(uint16(0), fwdMsg, nil, 1)
if err != nil {
t.Fatalf("unable to process sphinx packet: %v", err)
}
_, _, err = tx.Commit()
if err != nil {
t.Fatalf("unable to commit sphinx batch: %v", err)
}
tx2 := nodes[0].BeginTxn([]byte("1"), 1)
// Now, force the node to process the packet a second time, this should
// fail with a detected replay error.
err = tx2.ProcessOnionPacket(uint16(0), fwdMsg, nil, 1)
if err != nil {
t.Fatalf("sphinx packet replay should not have been rejected, "+
"instead error is %v", err)
}
_, replays, err := tx2.Commit()
if err != nil {
t.Fatalf("unable to commit second sphinx batch: %v", err)
}
if !replays.Contains(0) {
t.Fatalf("expected replay set to contain index: %v", 0)
}
}
func TestSphinxNodeReplayBatchIdempotency(t *testing.T) {
// We'd like to ensure that the sphinx node itself rejects all replayed
// packets which share the same shared secret.
nodes, _, _, fwdMsg, err := newTestRoute(testLegacyRouteNumHops)
if err != nil {
t.Fatalf("unable to create test route: %v", err)
}
// Start the ReplayLog and defer shutdown
nodes[0].log.Start()
defer nodes[0].log.Stop()
tx := nodes[0].BeginTxn([]byte("0"), 1)
// Allow the node to process the initial packet, this should proceed
// without any failures.
err = tx.ProcessOnionPacket(uint16(0), fwdMsg, nil, 1)
if err != nil {
t.Fatalf("unable to process sphinx packet: %v", err)
}
packets, replays, err := tx.Commit()
if err != nil {
t.Fatalf("unable to commit sphinx batch: %v", err)
}
tx2 := nodes[0].BeginTxn([]byte("0"), 1)
// Now, force the node to process the packet a second time, this should
// not fail with a detected replay error.
err = tx2.ProcessOnionPacket(uint16(0), fwdMsg, nil, 1)
if err != nil {
t.Fatalf("sphinx packet replay should not have been rejected, "+
"instead error is %v", err)
}
packets2, replays2, err := tx2.Commit()
if err != nil {
t.Fatalf("unable to commit second sphinx batch: %v", err)
}
if replays.Size() != replays2.Size() {
t.Fatalf("expected replay set to be %v, instead got %v",
replays, replays2)
}
if !reflect.DeepEqual(packets, packets2) {
t.Fatalf("expected packets to be %v, instead go %v",
packets, packets2)
}
}
func TestSphinxAssocData(t *testing.T) {
// We want to make sure that the associated data is considered in the
// HMAC creation
nodes, _, _, fwdMsg, err := newTestRoute(5)
if err != nil {
t.Fatalf("unable to create random onion packet: %v", err)
}
// Start the ReplayLog and defer shutdown
nodes[0].log.Start()
defer nodes[0].log.Stop()
_, err = nodes[0].ProcessOnionPacket(fwdMsg, []byte("somethingelse"), 1)
if err == nil {
t.Fatalf("we should fail when associated data changes")
}
}
func TestSphinxEncodeDecode(t *testing.T) {
// Create some test data with a randomly populated, yet valid onion
// forwarding message.
_, _, _, fwdMsg, err := newTestRoute(5)
if err != nil {
t.Fatalf("unable to create random onion packet: %v", err)
}
// Encode the created onion packet into an empty buffer. This should
// succeeed without any errors.
var b bytes.Buffer
if err := fwdMsg.Encode(&b); err != nil {
t.Fatalf("unable to encode message: %v", err)
}
// Now decode the bytes encoded above. Again, this should succeeed
// without any errors.
newFwdMsg := &OnionPacket{}
if err := newFwdMsg.Decode(&b); err != nil {
t.Fatalf("unable to decode message: %v", err)
}
// The two forwarding messages should now be identical.
if !reflect.DeepEqual(fwdMsg, newFwdMsg) {
t.Fatalf("forwarding messages don't match, %v vs %v",
spew.Sdump(fwdMsg), spew.Sdump(newFwdMsg))
}
}
func newEOBRoute(numHops uint32,
eobMapping map[int]HopPayload) (*OnionPacket, []*Router, error) {
nodes := make([]*Router, numHops)
if uint32(len(eobMapping)) != numHops {
return nil, nil, fmt.Errorf("must provide payload " +
"mapping for all hops")
}
// First, we'll assemble a set of routers that will consume all the
// hops we create in this path.
for i := 0; i < len(nodes); i++ {
privKey, err := btcec.NewPrivateKey()
if err != nil {
return nil, nil, fmt.Errorf("Unable to generate "+
"random key for sphinx node: %v", err)
}
nodes[i] = NewRouter(
&PrivKeyECDH{PrivKey: privKey}, NewMemoryReplayLog(),
)
}
// Next we'll gather all the pubkeys in the path, checking our eob
// mapping to see which hops need an extra payload.
var (
route PaymentPath
)
for i := 0; i < len(nodes); i++ {
route[i] = OnionHop{
NodePub: *nodes[i].onionKey.PubKey(),
HopPayload: eobMapping[i],
}
}
// Generate a forwarding message to route to the final node via the
// generated intermediate nodes above. Destination should be Hash160,
// adding padding so parsing still works.
sessionKey, _ := btcec.PrivKeyFromBytes(bytes.Repeat([]byte{'A'}, 32))
fwdMsg, err := NewOnionPacket(
&route, sessionKey, nil, DeterministicPacketFiller,
)
if err != nil {
return nil, nil, err
}
return fwdMsg, nodes, nil
}
func mustNewLegacyHopPayload(hopData *HopData) HopPayload {
payload, err := NewLegacyHopPayload(hopData)
if err != nil {
panic(err)
}
return payload
}
// TestPaymentPathTotalPayloadSizeExceeds1300 tests that a PaymentPath can have
// a TotalPayloadSize greater than 1300 bytes.
func TestPaymentPathTotalPayloadSizeExceeds1300(t *testing.T) {
t.Parallel()
// Scenario A: Create a new single-hop onion message routeA with a
// payload that exceeds 1300 bytes.
onionPacketA, routeA, nodesA, blindedPathA, err := newOnionMessageRoute(
1, bytes.Repeat([]byte("b"), 1500),
)
require.NoError(t, err, "newOnionMessageRoute should not return an "+
"error")
totalSize := routeA.TotalPayloadSize()
require.Greater(t, totalSize, 1300, "TotalPayloadSize should be "+
"greater than 1300")
require.Len(t, onionPacketA.RoutingInfo, MaxOnionMessagePayloadSize,
"RoutingInfo length should be equal to "+
"MaxOnionMessagePayloadSize")
routerA := nodesA[0]
require.NoError(t, routerA.Start())
defer routerA.Stop()
_, err = routerA.ProcessOnionPacket(
onionPacketA, nil, 10,
WithBlindingPoint(blindedPathA.BlindingPoint),
)
require.NoError(t, err, "DecodeHopPayload should not return an "+
"error")
// Scenario B: Create a new multi-hop onion message route that exceeds
// 1300 bytes through the number of hops.
onionPacketB, routeB, nodesB, blindedPathB, err := newOnionMessageRoute(
15, []byte("hello"),
)
require.NoError(t, err, "newOnionMessageRoute should not return an "+
"error")
totalSizeB := routeB.TotalPayloadSize()
require.Greater(t, totalSizeB, 1300, "TotalPayloadSize should be "+
"greater than 1300")
require.Len(t, onionPacketB.RoutingInfo, MaxOnionMessagePayloadSize,
"RoutingInfo length should be equal to "+
"MaxOnionMessagePayloadSize")
routerB := nodesB[0]
require.NoError(t, routerB.Start())
defer routerB.Stop()
_, err = routerB.ProcessOnionPacket(
onionPacketB, nil, 10,
WithBlindingPoint(blindedPathB.BlindingPoint),
)
require.NoError(t, err, "DecodeHopPayload should not return an "+
"error")
}
// TestSingleHopOnionMessage test that we can create and encode a single-hop
// onion message packet.
func TestSingleHopOnionMessage(t *testing.T) {
t.Parallel()
packet, route, nodes, _, err := newOnionMessageRoute(1, []byte("hello"))
require.NoError(t, err, "newOnionMessageRoute should not return an "+
"error")
require.Equal(t, 1, route.TrueRouteLength())
// Start the ReplayLog and defer shutdown
err = nodes[0].log.Start()
require.NoError(t, err, "unable to start ReplayLog")
defer func() {
require.NoError(t, nodes[0].log.Stop())
}()
// In a single-hop onion message the blinding point is the session key
// used by the receiver to create its blinded path. The sender didn't