-
Notifications
You must be signed in to change notification settings - Fork 226
/
dht.go
1498 lines (1266 loc) · 38.8 KB
/
dht.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package fullrt
import (
"bytes"
"context"
"errors"
"fmt"
"math/rand"
"sync"
"sync/atomic"
"time"
"github.com/multiformats/go-base32"
"github.com/multiformats/go-multiaddr"
"github.com/multiformats/go-multihash"
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/network"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/libp2p/go-libp2p-core/peerstore"
"github.com/libp2p/go-libp2p-core/protocol"
"github.com/libp2p/go-libp2p-core/routing"
swarm "github.com/libp2p/go-libp2p-swarm"
"github.com/gogo/protobuf/proto"
"github.com/ipfs/go-cid"
ds "github.com/ipfs/go-datastore"
dssync "github.com/ipfs/go-datastore/sync"
u "github.com/ipfs/go-ipfs-util"
logging "github.com/ipfs/go-log"
kaddht "github.com/libp2p/go-libp2p-kad-dht"
"github.com/libp2p/go-libp2p-kad-dht/crawler"
"github.com/libp2p/go-libp2p-kad-dht/internal"
internalConfig "github.com/libp2p/go-libp2p-kad-dht/internal/config"
"github.com/libp2p/go-libp2p-kad-dht/internal/net"
dht_pb "github.com/libp2p/go-libp2p-kad-dht/pb"
"github.com/libp2p/go-libp2p-kad-dht/providers"
kb "github.com/libp2p/go-libp2p-kbucket"
record "github.com/libp2p/go-libp2p-record"
recpb "github.com/libp2p/go-libp2p-record/pb"
"github.com/libp2p/go-libp2p-xor/kademlia"
kadkey "github.com/libp2p/go-libp2p-xor/key"
"github.com/libp2p/go-libp2p-xor/trie"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
)
var Tracer = otel.Tracer("")
var logger = logging.Logger("fullrtdht")
const rtRefreshLimitsMsg = `Accelerated DHT client was unable to fully refresh its routing table due to Resource Manager limits, which may degrade content routing. Consider increasing resource limits. See debug logs for the "dht-crawler" subsystem for details.`
// FullRT is an experimental DHT client that is under development. Expect breaking changes to occur in this client
// until it stabilizes.
type FullRT struct {
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
enableValues, enableProviders bool
Validator record.Validator
ProviderManager *providers.ProviderManager
datastore ds.Datastore
h host.Host
crawlerInterval time.Duration
lastCrawlTime time.Time
crawler *crawler.Crawler
protoMessenger *dht_pb.ProtocolMessenger
messageSender dht_pb.MessageSender
filterFromTable kaddht.QueryFilterFunc
rtLk sync.RWMutex
rt *trie.Trie
kMapLk sync.RWMutex
keyToPeerMap map[string]peer.ID
peerAddrsLk sync.RWMutex
peerAddrs map[peer.ID][]multiaddr.Multiaddr
bootstrapPeers []*peer.AddrInfo
bucketSize int
triggerRefresh chan struct{}
waitFrac float64
timeoutPerOp time.Duration
bulkSendParallelism int
}
// NewFullRT creates a DHT client that tracks the full network. It takes a protocol prefix for the given network,
// For example, the protocol /ipfs/kad/1.0.0 has the prefix /ipfs.
//
// FullRT is an experimental DHT client that is under development. Expect breaking changes to occur in this client
// until it stabilizes.
//
// Not all of the standard DHT options are supported in this DHT.
func NewFullRT(h host.Host, protocolPrefix protocol.ID, options ...Option) (*FullRT, error) {
var fullrtcfg config
if err := fullrtcfg.apply(options...); err != nil {
return nil, err
}
dhtcfg := &internalConfig.Config{
Datastore: dssync.MutexWrap(ds.NewMapDatastore()),
Validator: record.NamespacedValidator{},
ValidatorChanged: false,
EnableProviders: true,
EnableValues: true,
ProtocolPrefix: protocolPrefix,
}
if err := dhtcfg.Apply(fullrtcfg.dhtOpts...); err != nil {
return nil, err
}
if err := dhtcfg.ApplyFallbacks(h); err != nil {
return nil, err
}
if err := dhtcfg.Validate(); err != nil {
return nil, err
}
ms := net.NewMessageSenderImpl(h, []protocol.ID{dhtcfg.ProtocolPrefix + "/kad/1.0.0"})
protoMessenger, err := dht_pb.NewProtocolMessenger(ms)
if err != nil {
return nil, err
}
c, err := crawler.New(h, crawler.WithParallelism(200))
if err != nil {
return nil, err
}
ctx, cancel := context.WithCancel(context.Background())
pm, err := providers.NewProviderManager(ctx, h.ID(), h.Peerstore(), dhtcfg.Datastore)
if err != nil {
cancel()
return nil, err
}
var bsPeers []*peer.AddrInfo
for _, ai := range dhtcfg.BootstrapPeers() {
tmpai := ai
bsPeers = append(bsPeers, &tmpai)
}
rt := &FullRT{
ctx: ctx,
cancel: cancel,
enableValues: dhtcfg.EnableValues,
enableProviders: dhtcfg.EnableProviders,
Validator: dhtcfg.Validator,
ProviderManager: pm,
datastore: dhtcfg.Datastore,
h: h,
crawler: c,
messageSender: ms,
protoMessenger: protoMessenger,
filterFromTable: kaddht.PublicQueryFilter,
rt: trie.New(),
keyToPeerMap: make(map[string]peer.ID),
bucketSize: dhtcfg.BucketSize,
peerAddrs: make(map[peer.ID][]multiaddr.Multiaddr),
bootstrapPeers: bsPeers,
triggerRefresh: make(chan struct{}),
waitFrac: 0.3,
timeoutPerOp: 5 * time.Second,
crawlerInterval: time.Minute * 60,
bulkSendParallelism: 20,
}
rt.wg.Add(1)
go rt.runCrawler(ctx)
return rt, nil
}
type crawlVal struct {
addrs []multiaddr.Multiaddr
key kadkey.Key
}
func (dht *FullRT) TriggerRefresh(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
case dht.triggerRefresh <- struct{}{}:
return nil
case <-dht.ctx.Done():
return fmt.Errorf("dht is closed")
}
}
func (dht *FullRT) Stat() map[string]peer.ID {
newMap := make(map[string]peer.ID)
dht.kMapLk.RLock()
for k, v := range dht.keyToPeerMap {
newMap[k] = v
}
dht.kMapLk.RUnlock()
return newMap
}
func (dht *FullRT) Ready() bool {
dht.rtLk.RLock()
lastCrawlTime := dht.lastCrawlTime
dht.rtLk.RUnlock()
if time.Since(lastCrawlTime) > dht.crawlerInterval {
return false
}
// TODO: This function needs to be better defined. Perhaps based on going through the peer map and seeing when the
// last time we were connected to any of them was.
dht.peerAddrsLk.RLock()
rtSize := len(dht.keyToPeerMap)
dht.peerAddrsLk.RUnlock()
return rtSize > len(dht.bootstrapPeers)+1
}
func (dht *FullRT) Host() host.Host {
return dht.h
}
func (dht *FullRT) runCrawler(ctx context.Context) {
defer dht.wg.Done()
t := time.NewTicker(dht.crawlerInterval)
m := make(map[peer.ID]*crawlVal)
mxLk := sync.Mutex{}
initialTrigger := make(chan struct{}, 1)
initialTrigger <- struct{}{}
for {
select {
case <-t.C:
case <-initialTrigger:
case <-dht.triggerRefresh:
case <-ctx.Done():
return
}
var addrs []*peer.AddrInfo
dht.peerAddrsLk.Lock()
for k := range m {
addrs = append(addrs, &peer.AddrInfo{ID: k}) // Addrs: v.addrs
}
addrs = append(addrs, dht.bootstrapPeers...)
dht.peerAddrsLk.Unlock()
for k := range m {
delete(m, k)
}
start := time.Now()
limitErrOnce := sync.Once{}
dht.crawler.Run(ctx, addrs,
func(p peer.ID, rtPeers []*peer.AddrInfo) {
conns := dht.h.Network().ConnsToPeer(p)
var addrs []multiaddr.Multiaddr
for _, conn := range conns {
addr := conn.RemoteMultiaddr()
addrs = append(addrs, addr)
}
if len(addrs) == 0 {
logger.Debugf("no connections to %v after successful query. keeping addresses from the peerstore", p)
addrs = dht.h.Peerstore().Addrs(p)
}
keep := kaddht.PublicRoutingTableFilter(dht, p)
if !keep {
return
}
mxLk.Lock()
defer mxLk.Unlock()
m[p] = &crawlVal{
addrs: addrs,
}
},
func(p peer.ID, err error) {
dialErr, ok := err.(*swarm.DialError)
if ok {
for _, transportErr := range dialErr.DialErrors {
if errors.Is(transportErr.Cause, network.ErrResourceLimitExceeded) {
limitErrOnce.Do(func() { logger.Errorf(rtRefreshLimitsMsg) })
}
}
}
// note that DialError implements Unwrap() which returns the Cause, so this covers that case
if errors.Is(err, network.ErrResourceLimitExceeded) {
limitErrOnce.Do(func() { logger.Errorf(rtRefreshLimitsMsg) })
}
})
dur := time.Since(start)
logger.Infof("crawl took %v", dur)
peerAddrs := make(map[peer.ID][]multiaddr.Multiaddr)
kPeerMap := make(map[string]peer.ID)
newRt := trie.New()
for k, v := range m {
v.key = kadkey.KbucketIDToKey(kb.ConvertPeerID(k))
peerAddrs[k] = v.addrs
kPeerMap[string(v.key)] = k
newRt.Add(v.key)
}
dht.peerAddrsLk.Lock()
dht.peerAddrs = peerAddrs
dht.peerAddrsLk.Unlock()
dht.kMapLk.Lock()
dht.keyToPeerMap = kPeerMap
dht.kMapLk.Unlock()
dht.rtLk.Lock()
dht.rt = newRt
dht.lastCrawlTime = time.Now()
dht.rtLk.Unlock()
}
}
func (dht *FullRT) Close() error {
dht.cancel()
err := dht.ProviderManager.Process().Close()
dht.wg.Wait()
return err
}
func (dht *FullRT) Bootstrap(ctx context.Context) error {
return nil
}
// CheckPeers return (success, total)
func (dht *FullRT) CheckPeers(ctx context.Context, peers ...peer.ID) (int, int) {
var peerAddrs chan interface{}
var total int
if len(peers) == 0 {
dht.peerAddrsLk.RLock()
total = len(dht.peerAddrs)
peerAddrs = make(chan interface{}, total)
for k, v := range dht.peerAddrs {
peerAddrs <- peer.AddrInfo{
ID: k,
Addrs: v,
}
}
close(peerAddrs)
dht.peerAddrsLk.RUnlock()
} else {
total = len(peers)
peerAddrs = make(chan interface{}, total)
dht.peerAddrsLk.RLock()
for _, p := range peers {
peerAddrs <- peer.AddrInfo{
ID: p,
Addrs: dht.peerAddrs[p],
}
}
close(peerAddrs)
dht.peerAddrsLk.RUnlock()
}
var success uint64
workers(100, func(i interface{}) {
a := i.(peer.AddrInfo)
dialctx, dialcancel := context.WithTimeout(ctx, time.Second*3)
if err := dht.h.Connect(dialctx, a); err == nil {
atomic.AddUint64(&success, 1)
}
dialcancel()
}, peerAddrs)
return int(success), total
}
func workers(numWorkers int, fn func(interface{}), inputs <-chan interface{}) {
jobs := make(chan interface{})
defer close(jobs)
for i := 0; i < numWorkers; i++ {
go func() {
for j := range jobs {
fn(j)
}
}()
}
for i := range inputs {
jobs <- i
}
}
func (dht *FullRT) GetClosestPeers(ctx context.Context, key string) ([]peer.ID, error) {
ctx, span := Tracer.Start(ctx, "GetClosestPeers")
_ = ctx // not used, but we want to assign it _just_ in case we use it.
defer span.End()
kbID := kb.ConvertKey(key)
kadKey := kadkey.KbucketIDToKey(kbID)
dht.rtLk.RLock()
closestKeys := kademlia.ClosestN(kadKey, dht.rt, dht.bucketSize)
dht.rtLk.RUnlock()
peers := make([]peer.ID, 0, len(closestKeys))
for _, k := range closestKeys {
dht.kMapLk.RLock()
p, ok := dht.keyToPeerMap[string(k)]
if !ok {
logger.Errorf("key not found in map")
}
dht.kMapLk.RUnlock()
dht.peerAddrsLk.RLock()
peerAddrs := dht.peerAddrs[p]
dht.peerAddrsLk.RUnlock()
dht.h.Peerstore().AddAddrs(p, peerAddrs, peerstore.TempAddrTTL)
peers = append(peers, p)
}
return peers, nil
}
// PutValue adds value corresponding to given Key.
// This is the top level "Store" operation of the DHT
func (dht *FullRT) PutValue(ctx context.Context, key string, value []byte, opts ...routing.Option) (err error) {
if !dht.enableValues {
return routing.ErrNotSupported
}
logger.Debugw("putting value", "key", internal.LoggableRecordKeyString(key))
// don't even allow local users to put bad values.
if err := dht.Validator.Validate(key, value); err != nil {
return err
}
old, err := dht.getLocal(ctx, key)
if err != nil {
// Means something is wrong with the datastore.
return err
}
// Check if we have an old value that's not the same as the new one.
if old != nil && !bytes.Equal(old.GetValue(), value) {
// Check to see if the new one is better.
i, err := dht.Validator.Select(key, [][]byte{value, old.GetValue()})
if err != nil {
return err
}
if i != 0 {
return fmt.Errorf("can't replace a newer value with an older value")
}
}
rec := record.MakePutRecord(key, value)
rec.TimeReceived = u.FormatRFC3339(time.Now())
err = dht.putLocal(ctx, key, rec)
if err != nil {
return err
}
peers, err := dht.GetClosestPeers(ctx, key)
if err != nil {
return err
}
successes := dht.execOnMany(ctx, func(ctx context.Context, p peer.ID) error {
routing.PublishQueryEvent(ctx, &routing.QueryEvent{
Type: routing.Value,
ID: p,
})
err := dht.protoMessenger.PutValue(ctx, p, rec)
return err
}, peers, true)
if successes == 0 {
return fmt.Errorf("failed to complete put")
}
return nil
}
// RecvdVal stores a value and the peer from which we got the value.
type RecvdVal struct {
Val []byte
From peer.ID
}
// GetValue searches for the value corresponding to given Key.
func (dht *FullRT) GetValue(ctx context.Context, key string, opts ...routing.Option) (_ []byte, err error) {
if !dht.enableValues {
return nil, routing.ErrNotSupported
}
// apply defaultQuorum if relevant
var cfg routing.Options
if err := cfg.Apply(opts...); err != nil {
return nil, err
}
opts = append(opts, kaddht.Quorum(internalConfig.GetQuorum(&cfg)))
responses, err := dht.SearchValue(ctx, key, opts...)
if err != nil {
return nil, err
}
var best []byte
for r := range responses {
best = r
}
if ctx.Err() != nil {
return best, ctx.Err()
}
if best == nil {
return nil, routing.ErrNotFound
}
logger.Debugf("GetValue %v %x", internal.LoggableRecordKeyString(key), best)
return best, nil
}
// SearchValue searches for the value corresponding to given Key and streams the results.
func (dht *FullRT) SearchValue(ctx context.Context, key string, opts ...routing.Option) (<-chan []byte, error) {
if !dht.enableValues {
return nil, routing.ErrNotSupported
}
var cfg routing.Options
if err := cfg.Apply(opts...); err != nil {
return nil, err
}
responsesNeeded := 0
if !cfg.Offline {
responsesNeeded = internalConfig.GetQuorum(&cfg)
}
stopCh := make(chan struct{})
valCh, lookupRes := dht.getValues(ctx, key, stopCh)
out := make(chan []byte)
go func() {
defer close(out)
best, peersWithBest, aborted := dht.searchValueQuorum(ctx, key, valCh, stopCh, out, responsesNeeded)
if best == nil || aborted {
return
}
updatePeers := make([]peer.ID, 0, dht.bucketSize)
select {
case l := <-lookupRes:
if l == nil {
return
}
for _, p := range l.peers {
if _, ok := peersWithBest[p]; !ok {
updatePeers = append(updatePeers, p)
}
}
case <-ctx.Done():
return
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
dht.updatePeerValues(ctx, key, best, updatePeers)
cancel()
}()
return out, nil
}
func (dht *FullRT) searchValueQuorum(ctx context.Context, key string, valCh <-chan RecvdVal, stopCh chan struct{},
out chan<- []byte, nvals int) ([]byte, map[peer.ID]struct{}, bool) {
numResponses := 0
return dht.processValues(ctx, key, valCh,
func(ctx context.Context, v RecvdVal, better bool) bool {
numResponses++
if better {
select {
case out <- v.Val:
case <-ctx.Done():
return false
}
}
if nvals > 0 && numResponses > nvals {
close(stopCh)
return true
}
return false
})
}
func (dht *FullRT) processValues(ctx context.Context, key string, vals <-chan RecvdVal,
newVal func(ctx context.Context, v RecvdVal, better bool) bool) (best []byte, peersWithBest map[peer.ID]struct{}, aborted bool) {
loop:
for {
if aborted {
return
}
select {
case v, ok := <-vals:
if !ok {
break loop
}
// Select best value
if best != nil {
if bytes.Equal(best, v.Val) {
peersWithBest[v.From] = struct{}{}
aborted = newVal(ctx, v, false)
continue
}
sel, err := dht.Validator.Select(key, [][]byte{best, v.Val})
if err != nil {
logger.Warnw("failed to select best value", "key", internal.LoggableRecordKeyString(key), "error", err)
continue
}
if sel != 1 {
aborted = newVal(ctx, v, false)
continue
}
}
peersWithBest = make(map[peer.ID]struct{})
peersWithBest[v.From] = struct{}{}
best = v.Val
aborted = newVal(ctx, v, true)
case <-ctx.Done():
return
}
}
return
}
func (dht *FullRT) updatePeerValues(ctx context.Context, key string, val []byte, peers []peer.ID) {
fixupRec := record.MakePutRecord(key, val)
for _, p := range peers {
go func(p peer.ID) {
//TODO: Is this possible?
if p == dht.h.ID() {
err := dht.putLocal(ctx, key, fixupRec)
if err != nil {
logger.Error("Error correcting local dht entry:", err)
}
return
}
ctx, cancel := context.WithTimeout(ctx, time.Second*5)
defer cancel()
err := dht.protoMessenger.PutValue(ctx, p, fixupRec)
if err != nil {
logger.Debug("Error correcting DHT entry: ", err)
}
}(p)
}
}
type lookupWithFollowupResult struct {
peers []peer.ID // the top K not unreachable peers at the end of the query
}
func (dht *FullRT) getValues(ctx context.Context, key string, stopQuery chan struct{}) (<-chan RecvdVal, <-chan *lookupWithFollowupResult) {
valCh := make(chan RecvdVal, 1)
lookupResCh := make(chan *lookupWithFollowupResult, 1)
logger.Debugw("finding value", "key", internal.LoggableRecordKeyString(key))
if rec, err := dht.getLocal(ctx, key); rec != nil && err == nil {
select {
case valCh <- RecvdVal{
Val: rec.GetValue(),
From: dht.h.ID(),
}:
case <-ctx.Done():
}
}
peers, err := dht.GetClosestPeers(ctx, key)
if err != nil {
lookupResCh <- &lookupWithFollowupResult{}
close(valCh)
close(lookupResCh)
return valCh, lookupResCh
}
go func() {
defer close(valCh)
defer close(lookupResCh)
queryFn := func(ctx context.Context, p peer.ID) error {
// For DHT query command
routing.PublishQueryEvent(ctx, &routing.QueryEvent{
Type: routing.SendingQuery,
ID: p,
})
rec, peers, err := dht.protoMessenger.GetValue(ctx, p, key)
if err != nil {
return err
}
// For DHT query command
routing.PublishQueryEvent(ctx, &routing.QueryEvent{
Type: routing.PeerResponse,
ID: p,
Responses: peers,
})
if rec == nil {
return nil
}
val := rec.GetValue()
if val == nil {
logger.Debug("received a nil record value")
return nil
}
if err := dht.Validator.Validate(key, val); err != nil {
// make sure record is valid
logger.Debugw("received invalid record (discarded)", "error", err)
return nil
}
// the record is present and valid, send it out for processing
select {
case valCh <- RecvdVal{
Val: val,
From: p,
}:
case <-ctx.Done():
return ctx.Err()
}
return nil
}
dht.execOnMany(ctx, queryFn, peers, false)
lookupResCh <- &lookupWithFollowupResult{peers: peers}
}()
return valCh, lookupResCh
}
// Provider abstraction for indirect stores.
// Some DHTs store values directly, while an indirect store stores pointers to
// locations of the value, similarly to Coral and Mainline DHT.
// Provide makes this node announce that it can provide a value for the given key
func (dht *FullRT) Provide(ctx context.Context, key cid.Cid, brdcst bool) (err error) {
ctx, span := Tracer.Start(ctx, "Provide")
defer span.End()
if !dht.enableProviders {
return routing.ErrNotSupported
} else if !key.Defined() {
return fmt.Errorf("invalid cid: undefined")
}
keyMH := key.Hash()
logger.Debugw("providing", "cid", key, "mh", internal.LoggableProviderRecordBytes(keyMH))
// add self locally
dht.ProviderManager.AddProvider(ctx, keyMH, peer.AddrInfo{ID: dht.h.ID()})
if !brdcst {
return nil
}
closerCtx := ctx
if deadline, ok := ctx.Deadline(); ok {
now := time.Now()
timeout := deadline.Sub(now)
if timeout < 0 {
// timed out
return context.DeadlineExceeded
} else if timeout < 10*time.Second {
// Reserve 10% for the final put.
deadline = deadline.Add(-timeout / 10)
} else {
// Otherwise, reserve a second (we'll already be
// connected so this should be fast).
deadline = deadline.Add(-time.Second)
}
var cancel context.CancelFunc
closerCtx, cancel = context.WithDeadline(ctx, deadline)
defer cancel()
}
var exceededDeadline bool
peers, err := dht.GetClosestPeers(closerCtx, string(keyMH))
switch err {
case context.DeadlineExceeded:
// If the _inner_ deadline has been exceeded but the _outer_
// context is still fine, provide the value to the closest peers
// we managed to find, even if they're not the _actual_ closest peers.
if ctx.Err() != nil {
return ctx.Err()
}
exceededDeadline = true
case nil:
default:
return err
}
successes := dht.execOnMany(ctx, func(ctx context.Context, p peer.ID) error {
err := dht.protoMessenger.PutProvider(ctx, p, keyMH, dht.h)
return err
}, peers, true)
if exceededDeadline {
return context.DeadlineExceeded
}
if successes == 0 {
return fmt.Errorf("failed to complete provide")
}
return ctx.Err()
}
// execOnMany executes the given function on each of the peers, although it may only wait for a certain chunk of peers
// to respond before considering the results "good enough" and returning.
//
// If sloppyExit is true then this function will return without waiting for all of its internal goroutines to close.
// If sloppyExit is true then the passed in function MUST be able to safely complete an arbitrary amount of time after
// execOnMany has returned (e.g. do not write to resources that might get closed or set to nil and therefore result in
// a panic instead of just returning an error).
func (dht *FullRT) execOnMany(ctx context.Context, fn func(context.Context, peer.ID) error, peers []peer.ID, sloppyExit bool) int {
ctx, span := Tracer.Start(ctx, "execOnMany")
defer span.End()
if len(peers) == 0 {
return 0
}
// having a buffer that can take all of the elements is basically a hack to allow for sloppy exits that clean up
// the goroutines after the function is done rather than before
errCh := make(chan error, len(peers))
numSuccessfulToWaitFor := int(float64(len(peers)) * dht.waitFrac)
putctx, cancel := context.WithTimeout(ctx, dht.timeoutPerOp)
defer cancel()
for _, p := range peers {
go func(p peer.ID) {
errCh <- fn(putctx, p)
}(p)
}
var numDone, numSuccess, successSinceLastTick int
var ticker *time.Ticker
var tickChan <-chan time.Time
for numDone < len(peers) {
select {
case err := <-errCh:
numDone++
if err == nil {
numSuccess++
if numSuccess >= numSuccessfulToWaitFor && ticker == nil {
// Once there are enough successes, wait a little longer
ticker = time.NewTicker(time.Millisecond * 500)
defer ticker.Stop()
tickChan = ticker.C
successSinceLastTick = numSuccess
}
// This is equivalent to numSuccess * 2 + numFailures >= len(peers) and is a heuristic that seems to be
// performing reasonably.
// TODO: Make this metric more configurable
// TODO: Have better heuristics in this function whether determined from observing static network
// properties or dynamically calculating them
if numSuccess+numDone >= len(peers) {
cancel()
if sloppyExit {
return numSuccess
}
}
}
case <-tickChan:
if numSuccess > successSinceLastTick {
// If there were additional successes, then wait another tick
successSinceLastTick = numSuccess
} else {
cancel()
if sloppyExit {
return numSuccess
}
}
}
}
return numSuccess
}
func (dht *FullRT) ProvideMany(ctx context.Context, keys []multihash.Multihash) error {
ctx, span := Tracer.Start(ctx, "ProvideMany")
defer span.End()
if !dht.enableProviders {
return routing.ErrNotSupported
}
// Compute addresses once for all provides
pi := peer.AddrInfo{
ID: dht.h.ID(),
Addrs: dht.h.Addrs(),
}
pbPeers := dht_pb.RawPeerInfosToPBPeers([]peer.AddrInfo{pi})
// TODO: We may want to limit the type of addresses in our provider records
// For example, in a WAN-only DHT prohibit sharing non-WAN addresses (e.g. 192.168.0.100)
if len(pi.Addrs) < 1 {
return fmt.Errorf("no known addresses for self, cannot put provider")
}
fn := func(ctx context.Context, p, k peer.ID) error {
pmes := dht_pb.NewMessage(dht_pb.Message_ADD_PROVIDER, multihash.Multihash(k), 0)
pmes.ProviderPeers = pbPeers
return dht.messageSender.SendMessage(ctx, p, pmes)
}
keysAsPeerIDs := make([]peer.ID, 0, len(keys))
for _, k := range keys {
keysAsPeerIDs = append(keysAsPeerIDs, peer.ID(k))
}
return dht.bulkMessageSend(ctx, keysAsPeerIDs, fn, true)
}
func (dht *FullRT) PutMany(ctx context.Context, keys []string, values [][]byte) error {
if !dht.enableValues {
return routing.ErrNotSupported
}
if len(keys) != len(values) {
return fmt.Errorf("number of keys does not match the number of values")
}
keysAsPeerIDs := make([]peer.ID, 0, len(keys))
keyRecMap := make(map[string][]byte)
for i, k := range keys {
keysAsPeerIDs = append(keysAsPeerIDs, peer.ID(k))
keyRecMap[k] = values[i]
}
if len(keys) != len(keyRecMap) {
return fmt.Errorf("does not support duplicate keys")
}
fn := func(ctx context.Context, p, k peer.ID) error {
keyStr := string(k)
return dht.protoMessenger.PutValue(ctx, p, record.MakePutRecord(keyStr, keyRecMap[keyStr]))
}
return dht.bulkMessageSend(ctx, keysAsPeerIDs, fn, false)
}
func (dht *FullRT) bulkMessageSend(ctx context.Context, keys []peer.ID, fn func(ctx context.Context, target, k peer.ID) error, isProvRec bool) error {
ctx, span := Tracer.Start(ctx, "bulkMessageSend", trace.WithAttributes(attribute.Int("numKeys", len(keys))))
defer span.End()
if len(keys) == 0 {
return nil
}
type report struct {
successes int
failures int
lastSuccess time.Time
mx sync.RWMutex
}
keySuccesses := make(map[peer.ID]*report, len(keys))
var numSkipped int64
for _, k := range keys {
keySuccesses[k] = &report{}
}
logger.Infof("bulk send: number of keys %d, unique %d", len(keys), len(keySuccesses))