forked from ethereum/hive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
udp.go
1106 lines (917 loc) · 29.9 KB
/
udp.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package devp2p
import (
"bytes"
"container/list"
"crypto/ecdsa"
"errors"
"fmt"
"net"
"time"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/p2p/nat"
"github.com/ethereum/go-ethereum/p2p/netutil"
"github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/hive/simulators/common"
)
// Errors
var (
ErrPacketTooSmall = errors.New("too small")
ErrBadHash = errors.New("bad hash")
ErrExpired = errors.New("expired")
ErrUnsolicitedReply = errors.New("unsolicited reply")
ErrUnknownNode = errors.New("unknown node")
ErrTimeout = errors.New("RPC timeout")
ErrClockWarp = errors.New("reply deadline too far in the future")
ErrClosed = errors.New("socket closed")
ErrResponseReceived = errors.New("response received")
ErrPacketMismatch = errors.New("packet mismatch")
ErrCorruptDHT = errors.New("corrupt neighbours data")
UnexpectedPacket = false
)
// Timeouts
const (
respTimeout = 500 * time.Millisecond
expiration = 20 * time.Second
bondExpiration = 24 * time.Hour
ntpFailureThreshold = 32 // Continuous timeouts after which to check NTP
ntpWarningCooldown = 10 * time.Minute // Minimum amount of time to pass before repeating NTP warning
driftThreshold = 10 * time.Second // Allowed clock drift before warning user
)
// RPC packet types
const (
pingPacket = iota + 1 // zero is 'reserved'
pongPacket
findnodePacket
neighborsPacket
garbagePacket1
garbagePacket2
garbagePacket3
garbagePacket4
garbagePacket5
garbagePacket6
garbagePacket7
garbagePacket8
)
// RPC request structures
type (
ping struct {
Version uint
From, To rpcEndpoint
Expiration uint64
// Ignore additional fields (for forward compatibility).
Rest []rlp.RawValue `rlp:"tail"`
}
pingExtra struct {
Version uint
From, To rpcEndpoint
Expiration uint64
JunkData1 uint
JunkData2 []byte
// Ignore additional fields (for forward compatibility).
Rest []rlp.RawValue `rlp:"tail"`
}
// pong is the reply to ping.
pong struct {
// This field should mirror the UDP envelope address
// of the ping packet, which provides a way to discover the
// the external address (after NAT).
To rpcEndpoint
ReplyTok []byte // This contains the hash of the ping packet.
Expiration uint64 // Absolute timestamp at which the packet becomes invalid.
// Ignore additional fields (for forward compatibility).
Rest []rlp.RawValue `rlp:"tail"`
}
// findnode is a query for nodes close to the given target.
findnode struct {
Target encPubkey
Expiration uint64
// Ignore additional fields (for forward compatibility).
Rest []rlp.RawValue `rlp:"tail"`
}
// reply to findnode
neighbors struct {
Nodes []rpcNode
Expiration uint64
// Ignore additional fields (for forward compatibility).
Rest []rlp.RawValue `rlp:"tail"`
}
incomingPacket struct {
packet interface{}
recoveredID encPubkey
}
rpcNode struct {
IP net.IP // len 4 for IPv4 or 16 for IPv6
UDP uint16 // for discovery protocol
TCP uint16 // for RLPx protocol
ID encPubkey
}
rpcEndpoint struct {
IP net.IP // len 4 for IPv4 or 16 for IPv6
UDP uint16 // for discovery protocol
TCP uint16 // for RLPx protocol
}
)
func makeEndpoint(addr *net.UDPAddr, tcpPort uint16) rpcEndpoint {
ip := addr.IP.To4()
if ip == nil {
ip = addr.IP.To16()
}
return rpcEndpoint{IP: ip, UDP: uint16(addr.Port), TCP: tcpPort}
}
func (t *V4Udp) nodeFromRPC(sender *net.UDPAddr, rn rpcNode) (*node, error) {
if rn.UDP <= 1024 {
return nil, errors.New("low port")
}
if err := netutil.CheckRelayIP(sender.IP, rn.IP); err != nil {
return nil, err
}
if t.netrestrict != nil && !t.netrestrict.Contains(rn.IP) {
return nil, errors.New("not contained in netrestrict whitelist")
}
key, err := decodePubkey(rn.ID)
if err != nil {
return nil, err
}
n := wrapNode(enode.NewV4(key, rn.IP, int(rn.TCP), int(rn.UDP)))
err = n.ValidateComplete()
return n, err
}
func nodeToRPC(n *node) rpcNode {
var key ecdsa.PublicKey
var ekey encPubkey
if err := n.Load((*enode.Secp256k1)(&key)); err == nil {
ekey = EncodePubkey(&key)
}
return rpcNode{ID: ekey, IP: n.IP(), UDP: uint16(n.UDP()), TCP: uint16(n.TCP())}
}
type packet interface {
handle(t *V4Udp, from *net.UDPAddr, fromKey encPubkey, mac []byte) error
name() string
}
type conn interface {
ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error)
WriteToUDP(b []byte, addr *net.UDPAddr) (n int, err error)
Close() error
LocalAddr() net.Addr
}
//V4Udp is the v4UDP test class
type V4Udp struct {
conn conn
netrestrict *netutil.Netlist
priv *ecdsa.PrivateKey
ourEndpoint rpcEndpoint
addpending chan *pending
gotreply chan reply
closing chan struct{}
nat nat.Interface
l common.Logger
}
// pending represents a pending reply.
//
// some implementations of the protocol wish to send more than one
// reply packet to findnode. in general, any neighbors packet cannot
// be matched up with a specific findnode packet.
//
// our implementation handles this by storing a callback function for
// each pending reply. incoming packets from a node are dispatched
// to all the callback functions for that node.
type pending struct {
// these fields must match in the reply.
from enode.ID
// time when the request must complete
deadline time.Time
//callback is called when a packet is received. if it returns nil,
//the callback is removed from the pending reply queue (handled successfully and expected by test case).
//if it returns a mismatch error, (ignored by callback, further 'pendings' may be in the test case)
//if it returns any other error, that error is considered the outcome of the
//'pending' operation
//callback func(resp interface{}) (done error)
callback func(resp reply) (done error)
// errc receives nil when the callback indicates completion or an
// error if no further reply is received within the timeout.
errc chan<- error
}
type reply struct {
from enode.ID
ptype byte
data interface{}
// loop indicates whether there was
// a matching request by sending on this channel.
matched chan<- bool
}
// ReadPacket is sent to the unhandled channel when it could not be processed
type ReadPacket struct {
Data []byte
Addr *net.UDPAddr
}
// Config holds Table-related settings.
type Config struct {
// These settings are required and configure the UDP listener:
PrivateKey *ecdsa.PrivateKey
// These settings are optional:
AnnounceAddr *net.UDPAddr // local address announced in the DHT
NodeDBPath string // if set, the node database is stored at this filesystem location
NetRestrict *netutil.Netlist // network whitelist
Bootnodes []*enode.Node // list of bootstrap nodes
Unhandled chan<- ReadPacket // unhandled packets are sent on this channel
}
// ListenUDP returns a new table that listens for UDP packets on laddr.
func ListenUDP(c conn, cfg Config, l common.Logger) (*V4Udp, error) {
v4Udp, err := newUDP(c, cfg, l)
if err != nil {
return nil, err
}
log.Info("UDP listener up", "self")
return v4Udp, nil
}
func newUDP(c conn, cfg Config, l common.Logger) (*V4Udp, error) {
realaddr := c.LocalAddr().(*net.UDPAddr)
if cfg.AnnounceAddr != nil {
realaddr = cfg.AnnounceAddr
}
udp := &V4Udp{
conn: c,
priv: cfg.PrivateKey,
netrestrict: cfg.NetRestrict,
closing: make(chan struct{}),
gotreply: make(chan reply),
addpending: make(chan *pending),
l: l,
}
udp.ourEndpoint = makeEndpoint(realaddr, uint16(realaddr.Port))
go udp.loop()
go udp.readLoop(cfg.Unhandled)
return udp, nil
}
func (t *V4Udp) close() {
close(t.closing)
t.conn.Close()
//t.db.Close()
}
//Ping sends a ping message to the given node and waits for a reply.
func (t *V4Udp) Ping(toid enode.ID, toaddr *net.UDPAddr, validateEnodeID bool, recoveryCallback func(e *ecdsa.PublicKey)) error {
to := makeEndpoint(toaddr, 0)
req := &ping{
Version: 4,
From: t.ourEndpoint,
To: to, // TODO: maybe use known TCP port from DB
Expiration: uint64(time.Now().Add(expiration).Unix()),
}
packet, hash, err := encodePacket(t.priv, pingPacket, req)
if err != nil {
return err
}
t.l.Log("Establishing criteria: Will succeed only if a valid pong is received.")
callback := func(p reply) error {
if p.ptype == pongPacket {
inPacket := p.data.(incomingPacket)
if !bytes.Equal(inPacket.packet.(*pong).ReplyTok, hash) {
return ErrUnsolicitedReply
}
if validateEnodeID && toid != inPacket.recoveredID.id() {
return ErrUnknownNode
}
if recoveryCallback != nil {
key, err := decodePubkey(inPacket.recoveredID)
if err != nil {
recoveryCallback(key)
}
}
return nil
}
return ErrPacketMismatch
}
return <-t.sendPacket(toid, toaddr, req, packet, callback)
}
//PingWrongFrom pings with incorrect from field
func (t *V4Udp) PingWrongFrom(toid enode.ID, toaddr *net.UDPAddr, validateEnodeID bool, recoveryCallback func(e *ecdsa.PublicKey)) error {
to := makeEndpoint(toaddr, 0)
from := makeEndpoint(&net.UDPAddr{IP: []byte{0, 1, 2, 3}, Port: 1}, 0) //this is a garbage endpoint
req := &ping{
Version: 4,
From: from,
To: to, // TODO: maybe use known TCP port from DB
Expiration: uint64(time.Now().Add(expiration).Unix()),
}
packet, hash, err := encodePacket(t.priv, pingPacket, req)
if err != nil {
return err
}
//expect the usual ping stuff - a bad 'from' should be ignored
t.l.Log("Establishing criteria: Will succeed only if a valid pong is received.")
callback := func(p reply) error {
if p.ptype == pongPacket {
inPacket := p.data.(incomingPacket)
if !bytes.Equal(inPacket.packet.(*pong).ReplyTok, hash) {
return ErrUnsolicitedReply
}
if validateEnodeID && toid != inPacket.recoveredID.id() {
return ErrUnknownNode
}
if recoveryCallback != nil {
key, err := decodePubkey(inPacket.recoveredID)
if err != nil {
recoveryCallback(key)
}
}
return nil
}
return ErrPacketMismatch
}
return <-t.sendPacket(toid, toaddr, req, packet, callback)
}
//PingWrongTo pings with incorrect to
func (t *V4Udp) PingWrongTo(toid enode.ID, toaddr *net.UDPAddr, validateEnodeID bool, recoveryCallback func(e *ecdsa.PublicKey)) error {
to := makeEndpoint(&net.UDPAddr{IP: []byte{0, 1, 2, 3}, Port: 1}, 0)
req := &ping{
Version: 4,
From: t.ourEndpoint,
To: to, // TODO: maybe use known TCP port from DB
Expiration: uint64(time.Now().Add(expiration).Unix()),
}
packet, _, err := encodePacket(t.priv, pingPacket, req)
if err != nil {
return err
}
t.l.Log("Establishing criteria: Will succeed if a pong packet is received.")
callback := func(p reply) error {
if p.ptype == pongPacket {
return nil
}
return ErrPacketMismatch
}
return <-t.sendPacket(toid, toaddr, req, packet, callback)
}
//PingExtraData ping with a 'future format' packet containing extra fields
func (t *V4Udp) PingExtraData(toid enode.ID, toaddr *net.UDPAddr, validateEnodeID bool, recoveryCallback func(e *ecdsa.PublicKey)) error {
to := makeEndpoint(toaddr, 0)
req := &pingExtra{
Version: 4,
From: t.ourEndpoint,
To: to,
JunkData1: 42,
JunkData2: []byte{9, 8, 7, 6, 5, 4, 3, 2, 1},
Expiration: uint64(time.Now().Add(expiration).Unix()),
}
packet, hash, err := encodePacket(t.priv, pingPacket, req)
if err != nil {
return err
}
//expect the usual ping responses
t.l.Log("Establishing criteria: Will succeed if a valid pong packet is received.")
callback := func(p reply) error {
if p.ptype == pongPacket {
inPacket := p.data.(incomingPacket)
if !bytes.Equal(inPacket.packet.(*pong).ReplyTok, hash) {
return ErrUnsolicitedReply
}
if validateEnodeID && toid != inPacket.recoveredID.id() {
return ErrUnknownNode
}
if recoveryCallback != nil {
key, err := decodePubkey(inPacket.recoveredID)
if err != nil {
recoveryCallback(key)
}
}
return nil
}
return ErrPacketMismatch
}
return <-t.sendPacket(toid, toaddr, &ping{}, packet, callback) //the dummy ping is just to get the name
}
//PingExtraDataWrongFrom ping with a 'future format' packet containing extra fields and make sure it works even with the wrong 'from' field
func (t *V4Udp) PingExtraDataWrongFrom(toid enode.ID, toaddr *net.UDPAddr, validateEnodeID bool, recoveryCallback func(e *ecdsa.PublicKey)) error {
to := makeEndpoint(toaddr, 0)
from := makeEndpoint(&net.UDPAddr{IP: []byte{0, 1, 2, 3}, Port: 1}, 0) //this is a garbage endpoint
req := &pingExtra{
Version: 4,
From: from,
To: to,
JunkData1: 42,
JunkData2: []byte{9, 8, 7, 6, 5, 4, 3, 2, 1},
Expiration: uint64(time.Now().Add(expiration).Unix()),
}
packet, hash, err := encodePacket(t.priv, pingPacket, req)
if err != nil {
return err
}
//expect the usual ping reponses
t.l.Log("Establishing criteria: Will succeed if a valid pong packet is received.")
callback := func(p reply) error {
if p.ptype == pongPacket {
inPacket := p.data.(incomingPacket)
if !bytes.Equal(inPacket.packet.(*pong).ReplyTok, hash) {
return ErrUnsolicitedReply
}
if validateEnodeID && toid != inPacket.recoveredID.id() {
return ErrUnknownNode
}
if recoveryCallback != nil {
key, err := decodePubkey(inPacket.recoveredID)
if err != nil {
recoveryCallback(key)
}
}
return nil
}
return ErrPacketMismatch
}
return <-t.sendPacket(toid, toaddr, &ping{}, packet, callback) //the dummy ping is just to get the name
}
// PingTargetWrongPacketType send a packet (a ping packet, though it could be something else) with an unknown packet type to the client and
// see how the target behaves. If the target responds to the ping, then fail.
func (t *V4Udp) PingTargetWrongPacketType(toid enode.ID, toaddr *net.UDPAddr, validateEnodeID bool, recoveryCallback func(e *ecdsa.PublicKey)) error {
to := makeEndpoint(toaddr, 0)
req := &ping{
Version: 4,
From: t.ourEndpoint,
To: to, // TODO: maybe use known TCP port from DB
Expiration: uint64(time.Now().Add(expiration).Unix()),
}
packet, _, err := encodePacket(t.priv, garbagePacket8, req)
if err != nil {
return err
}
//expect anything but a ping or pong
t.l.Log("Establishing criteria: Fail immediately if a ping or pong is received. Succeed if nothing occurs within timeout.")
callback := func(p reply) error {
if p.ptype == pongPacket {
return ErrUnsolicitedReply
}
if p.ptype == pingPacket {
return ErrUnsolicitedReply
}
return ErrPacketMismatch
}
return <-t.sendPacket(toid, toaddr, req, packet, callback)
}
// FindnodeWithoutBond tries to find a node without a previous bond
func (t *V4Udp) FindnodeWithoutBond(toid enode.ID, toaddr *net.UDPAddr, target encPubkey) error {
req := &findnode{
Target: target,
Expiration: uint64(time.Now().Add(expiration).Unix()),
}
packet, _, err := encodePacket(t.priv, findnodePacket, req)
if err != nil {
return err
}
//expect nothing
t.l.Log("Establishing criteria: Fail if any packet received. Succeed if nothing received within timeouts.")
callback := func(p reply) error {
return ErrUnsolicitedReply
}
return <-t.sendPacket(toid, toaddr, req, packet, callback)
}
//PingBondedWithMangledFromField ping a bonded node with bad from fields
func (t *V4Udp) PingBondedWithMangledFromField(toid enode.ID, toaddr *net.UDPAddr, validateEnodeID bool, recoveryCallback func(e *ecdsa.PublicKey)) error {
//try to bond with the target using normal ping data
err := t.Ping(toid, toaddr, false, nil)
if err != nil {
return err
}
//hang around for a bit (we don't know if the target was already bonded or not)
time.Sleep(2 * time.Second)
to := makeEndpoint(toaddr, 0)
from := makeEndpoint(&net.UDPAddr{IP: []byte{0, 1, 2, 3}, Port: 1}, 0) //this is a garbage endpoint
req := &ping{
Version: 4,
From: from,
To: to, // TODO: maybe use known TCP port from DB
Expiration: uint64(time.Now().Add(expiration).Unix()),
}
packet, hash, err := encodePacket(t.priv, pingPacket, req)
if err != nil {
return err
}
//expect the usual ping stuff - a bad 'from' should be ignored
t.l.Log("Establishing criteria: Succeed if valid pong received.")
callback := func(p reply) error {
if p.ptype == pongPacket {
inPacket := p.data.(incomingPacket)
if !bytes.Equal(inPacket.packet.(*pong).ReplyTok, hash) {
return ErrUnsolicitedReply
}
if validateEnodeID && toid != inPacket.recoveredID.id() {
return ErrUnknownNode
}
if recoveryCallback != nil {
key, err := decodePubkey(inPacket.recoveredID)
if err != nil {
recoveryCallback(key)
}
}
return nil
}
return ErrPacketMismatch
}
return <-t.sendPacket(toid, toaddr, req, packet, callback)
}
//BondedSourceFindNeighbours basic find neighbours tests
func (t *V4Udp) BondedSourceFindNeighbours(toid enode.ID, toaddr *net.UDPAddr, target encPubkey) error {
//try to bond with the target
err := t.Ping(toid, toaddr, false, nil)
if err != nil {
return err
}
//hang around for a bit (we don't know if the target was already bonded or not)
time.Sleep(2 * time.Second)
//send an unsolicited neighbours packet
req := neighbors{Expiration: uint64(time.Now().Add(expiration).Unix())}
var fakeKey *ecdsa.PrivateKey
if fakeKey, err = crypto.GenerateKey(); err != nil {
return err
}
fakePub := fakeKey.PublicKey
encFakeKey := EncodePubkey(&fakePub)
fakeNeighbour := rpcNode{ID: encFakeKey, IP: net.IP{1, 2, 3, 4}, UDP: 123, TCP: 123}
req.Nodes = []rpcNode{fakeNeighbour}
t.send(toaddr, neighborsPacket, &req)
//now call find neighbours
findReq := &findnode{
Target: target,
Expiration: uint64(time.Now().Add(expiration).Unix()),
}
packet, _, err := encodePacket(t.priv, findnodePacket, findReq)
if err != nil {
return err
}
//expect good neighbours response with no junk
t.l.Log("Establishing criteria: Succeed if a neighbours packet is received that is not polluted.")
callback := func(p reply) error {
if p.ptype == neighborsPacket {
//got a response.
//we assume the target is not connected to a public or populated bootnode
//so we assume the target does not have any other neighbours in the DHT
inPacket := p.data.(incomingPacket)
for _, neighbour := range inPacket.packet.(*neighbors).Nodes {
if neighbour.ID == encFakeKey {
return ErrCorruptDHT
}
}
return nil
}
return ErrUnsolicitedReply
}
return <-t.sendPacket(toid, toaddr, findReq, packet, callback)
}
//PingPastExpiration check past expirations are handled correctly
func (t *V4Udp) PingPastExpiration(toid enode.ID, toaddr *net.UDPAddr, validateEnodeID bool, recoveryCallback func(e *ecdsa.PublicKey)) error {
to := makeEndpoint(toaddr, 0)
req := &ping{
Version: 4,
From: t.ourEndpoint,
To: to, // TODO: maybe use known TCP port from DB
Expiration: uint64(time.Now().Add(-expiration).Unix()),
}
packet, _, err := encodePacket(t.priv, pingPacket, req)
if err != nil {
return err
}
//expect no pong
t.l.Log("Establishing criteria: Fail if a pong is received. Succeed if nothing received within timeout.")
callback := func(p reply) error {
if p.ptype == pongPacket {
return ErrUnsolicitedReply
}
return ErrPacketMismatch
}
return <-t.sendPacket(toid, toaddr, req, packet, callback)
}
//BondedSourceFindNeighboursPastExpiration -
func (t *V4Udp) BondedSourceFindNeighboursPastExpiration(toid enode.ID, toaddr *net.UDPAddr, target encPubkey) error {
//try to bond with the target
err := t.Ping(toid, toaddr, false, nil)
if err != nil {
return err
}
//hang around for a bit (we don't know if the target was already bonded or not)
time.Sleep(2 * time.Second)
//now call find neighbours
findReq := &findnode{
Target: target,
Expiration: uint64(time.Now().Add(-expiration).Unix()),
}
packet, _, err := encodePacket(t.priv, findnodePacket, findReq)
if err != nil {
return err
}
//expect good neighbours response with no junk
t.l.Log("Establishing criteria: Fail if a neighbours packet is received. Succeed if nothing received within timeouts.")
callback := func(p reply) error {
if p.ptype == neighborsPacket {
return ErrUnsolicitedReply
}
return ErrPacketMismatch
}
return <-t.sendPacket(toid, toaddr, findReq, packet, callback)
}
func (t *V4Udp) sendPacket(toid enode.ID, toaddr *net.UDPAddr, req packet, packet []byte, callback func(reply) error) <-chan error {
t.l.Logf("Sending packet %s to enode %s with target endpoint %v", req.name(), toid, toaddr)
errc := t.pending(toid, callback)
t.write(toaddr, req.name(), packet)
return errc
}
// pending adds a reply callback to the pending reply queue.
// see the documentation of type pending for a detailed explanation.
func (t *V4Udp) pending(id enode.ID, callback func(reply) error) <-chan error {
ch := make(chan error, 1)
p := &pending{from: id, callback: callback, errc: ch}
select {
case t.addpending <- p:
// loop will handle it
case <-t.closing:
ch <- ErrClosed
}
return ch
}
func (t *V4Udp) handleReply(from enode.ID, ptype byte, req incomingPacket) bool {
matched := make(chan bool, 1)
select {
case t.gotreply <- reply{from, ptype, req, matched}:
// loop will handle it
return <-matched
case <-t.closing:
return false
}
}
// loop runs in its own goroutine. it keeps track of
// the refresh timer and the pending reply queue.
func (t *V4Udp) loop() {
var (
plist = list.New()
timeout = time.NewTimer(0)
nextTimeout *pending // head of plist when timeout was last reset
contTimeouts = 0 // number of continuous timeouts to do NTP checks
// ntpWarnTime = time.Unix(0, 0)
)
<-timeout.C // ignore first timeout
defer timeout.Stop()
resetTimeout := func() {
if plist.Front() == nil || nextTimeout == plist.Front().Value {
return
}
// Start the timer so it fires when the next pending reply has expired.
now := time.Now()
for el := plist.Front(); el != nil; el = el.Next() {
nextTimeout = el.Value.(*pending)
if dist := nextTimeout.deadline.Sub(now); dist < 2*respTimeout {
timeout.Reset(dist)
return
}
// Remove pending replies whose deadline is too far in the
// future. These can occur if the system clock jumped
// backwards after the deadline was assigned.
nextTimeout.errc <- ErrClockWarp
plist.Remove(el)
}
nextTimeout = nil
timeout.Stop()
}
for {
resetTimeout()
select {
case <-t.closing:
for el := plist.Front(); el != nil; el = el.Next() {
el.Value.(*pending).errc <- ErrClosed
}
return
case p := <-t.addpending:
p.deadline = time.Now().Add(respTimeout)
plist.PushBack(p)
case r := <-t.gotreply:
var matched bool
for el := plist.Front(); el != nil; el = el.Next() {
p := el.Value.(*pending)
if p.from == r.from {
// Remove the matcher if its callback indicates
// that all replies have been received. This is
// required for packet types that expect multiple
// reply packets.
cbres := p.callback(r)
if cbres != ErrPacketMismatch {
matched = true
if cbres == nil {
plist.Remove(el)
p.errc <- nil
} else {
plist.Remove(el)
p.errc <- cbres
}
}
// Reset the continuous timeout counter (time drift detection)
contTimeouts = 0
}
}
r.matched <- matched
case now := <-timeout.C:
nextTimeout = nil
// Notify and remove callbacks whose deadline is in the past.
for el := plist.Front(); el != nil; el = el.Next() {
p := el.Value.(*pending)
if now.After(p.deadline) || now.Equal(p.deadline) {
t.l.Log("Timing out pending packet.")
p.errc <- ErrTimeout
plist.Remove(el)
contTimeouts++
}
}
}
}
}
const (
macSize = 256 / 8
sigSize = 520 / 8
headSize = macSize + sigSize // space of packet frame data
)
var (
headSpace = make([]byte, headSize)
// Neighbors replies are sent across multiple packets to
// stay below the 1280 byte limit. We compute the maximum number
// of entries by stuffing a packet until it grows too large.
maxNeighbors int
)
func init() {
p := neighbors{Expiration: ^uint64(0)}
maxSizeNode := rpcNode{IP: make(net.IP, 16), UDP: ^uint16(0), TCP: ^uint16(0)}
for n := 0; ; n++ {
p.Nodes = append(p.Nodes, maxSizeNode)
size, _, err := rlp.EncodeToReader(p)
if err != nil {
// If this ever happens, it will be caught by the unit tests.
panic("cannot encode: " + err.Error())
}
if headSize+size+1 >= 1280 {
maxNeighbors = n
break
}
}
}
func (t *V4Udp) send(toaddr *net.UDPAddr, ptype byte, req packet) ([]byte, error) {
packet, hash, err := encodePacket(t.priv, ptype, req)
if err != nil {
return hash, err
}
return hash, t.write(toaddr, req.name(), packet)
}
func (t *V4Udp) write(toaddr *net.UDPAddr, what string, packet []byte) error {
_, err := t.conn.WriteToUDP(packet, toaddr)
log.Trace(">> "+what, "addr", toaddr, "err", err)
return err
}
func encodePacket(priv *ecdsa.PrivateKey, ptype byte, req interface{}) (packet, hash []byte, err error) {
b := new(bytes.Buffer)
b.Write(headSpace)
b.WriteByte(ptype)
if err := rlp.Encode(b, req); err != nil {
log.Error("Can't encode discv4 packet", "err", err)
return nil, nil, err
}
packet = b.Bytes()
sig, err := crypto.Sign(crypto.Keccak256(packet[headSize:]), priv)
if err != nil {
log.Error("Can't sign discv4 packet", "err", err)
return nil, nil, err
}
copy(packet[macSize:], sig)
// add the hash to the front. Note: this doesn't protect the
// packet in any way. Our public key will be part of this hash in
// The future.
hash = crypto.Keccak256(packet[macSize:])
copy(packet, hash)
return packet, hash, nil
}
// readLoop runs in its own goroutine. it handles incoming UDP packets.
func (t *V4Udp) readLoop(unhandled chan<- ReadPacket) {
defer t.conn.Close()
if unhandled != nil {
defer close(unhandled)
}
// Discovery packets are defined to be no larger than 1280 bytes.
// Packets larger than this size will be cut at the end and treated
// as invalid because their hash won't match.
buf := make([]byte, 1280)
for {
nbytes, from, err := t.conn.ReadFromUDP(buf)
if netutil.IsTemporaryError(err) {
// Ignore temporary read errors.
log.Debug("Temporary UDP read error", "err", err)
continue
} else if err != nil {
// Shut down the loop for permament errors.
log.Debug("UDP read error", "err", err)
return
}
if t.handlePacket(from, buf[:nbytes]) != nil && unhandled != nil {
select {
case unhandled <- ReadPacket{buf[:nbytes], from}:
default:
}
}
}
}