-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchord_tasks.py
2803 lines (2231 loc) · 105 KB
/
chord_tasks.py
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 (c) 2014-2015 Sam Maloney.
# License: GPL v2.
import llog
import asyncio
from collections import namedtuple
from concurrent import futures
from datetime import datetime
import logging
import math
import os
import random
from sqlalchemy import func
import bittrie
import chord
import chord_packet as cp
from chordexception import ChordException
from db import Peer, DataBlock, NodeState
import mbase32
import multipart as mp
import mutil
import enc
import node as mnnode
import peer as mnpeer
import rsakey
import sshtype
log = logging.getLogger(__name__)
class Counter(object):
def __init__(self, value=None):
self.value = value
#TODO: The existence of the following (DataResponseWrapper) is the indicator
# that we should really refactor this whole file into a new class that is an
# instance per request.
class DataResponseWrapper(object):
def __init__(self, data_key):
self.data_key = data_key
self.data = None
self.pubkey = None
self.signature = None
self.path_hash = b""
self.version = None
self.targeted = False
self.data_done = None
self.data_present_cnt = 0
self.will_store_cnt = 0
self.storing_nodes = 0
class TunnelMeta(object):
def __init__(self, peer=None, jobs=None):
assert type(peer) is mnpeer.Peer
self.peer = peer
self.queue = None
self.local_cid = None
self.jobs = jobs
self.task_running = False
class VPeer(object):
def __init__(self, peer=None, path=None, tun_meta=None):
# self.peer can be a mnpeer.Peer for immediate Peer, or a db.Peer for
# a non immediate (tunneled) Peer.
assert type(peer) is Peer or type(peer) is mnpeer.Peer
self.peer = peer
self.path = path
self.tun_meta = tun_meta
self.used = False
self.will_store = False
self.data_present = False
EMPTY_PEER_LIST_MESSAGE = cp.ChordPeerList(peers=[])
EMPTY_PEER_LIST_PACKET = EMPTY_PEER_LIST_MESSAGE.encode()
EMPTY_GET_DATA_MESSAGE = cp.ChordGetData()
EMPTY_GET_DATA_PACKET = EMPTY_GET_DATA_MESSAGE.encode()
class ChordTasks(object):
def __init__(self, engine):
self.engine = engine
self.loop = engine.loop
self.last_peer_add_time = None
self.add_peer_memory_cache = {} # {Peer.address, Peer}
@asyncio.coroutine
def send_node_info(self, peer):
log.info("Sending ChordNodeInfo message.")
local_cid, queue =\
yield from peer.protocol.open_channel("mpeer", True)
if not queue:
return
msg = cp.ChordNodeInfo()
msg.sender_address = self.engine.bind_address
msg.version = self.engine.node.morphis_version
peer.protocol.write_channel_data(local_cid, msg.encode())
data = yield from queue.get()
if not data:
return
msg = cp.ChordNodeInfo(data)
log.info("Received ChordNodeInfo message.")
peer.version = msg.version
peer.full_node = True
yield from peer.protocol.close_channel(local_cid)
yield from self.engine._check_update_remote_address(msg, peer)
if log.isEnabledFor(logging.INFO):
log.info("Outbound Node (addr=[{}]) reports as version=[{}]."\
.format(peer.address, peer.version))
self.engine._notify_protocol_ready()
@asyncio.coroutine
def perform_stabilize(self):
found_new_nodes = False
if not self.engine.peers:
log.info("No connected nodes, unable to perform stabilize.")
return
# Fetch closest to ourselves.
closest_nodes, new_nodes = yield from\
self._perform_stabilize(self.engine.node_id, self.engine.peer_trie)
found_new_nodes |= new_nodes
closest_found_distance =\
closest_nodes[0].distance if closest_nodes else None
# Fetch furthest from ourselves.
node_id = bytearray(self.engine.node_id)
for i in range(len(node_id)):
node_id[i] = (~node_id[i]) & 0xFF
furthest_nodes, new_nodes = yield from self._perform_stabilize(node_id)
found_new_nodes |= new_nodes
if not closest_found_distance:
closest_found_distance = chord.NODE_ID_BITS
if furthest_nodes:
for node in furthest_nodes:
if node.distance < closest_found_distance:
closest_found_distance = node.distance
if closest_found_distance is chord.NODE_ID_BITS:
log.info("Don't know how close a bucket to stop at so not"\
" searching inbetween closest and furthest.")
return
# closest_found_distance = 0
# log.warning("Stabilize FindNode id=[{:0512b}]."\
# .format(int.from_bytes(self.engine.node_id, "big")))
# Fetch each bucket starting at furthest, stopping when we get to the
# closest that we found above.
orig_node_id = self.engine.node_id
for bit in range(chord.NODE_ID_BITS-1, -1, -1):
if log.isEnabledFor(logging.INFO):
log.info("Performing FindNode for bucket [{}]."\
.format(bit+1))
node_id = bytearray(orig_node_id)
# Change the most significant bit so that the resulting id is
# inside the bucket for said bit difference.
byte_ = chord.NODE_ID_BYTES - 1 - (bit >> 3)
bit_pos = bit % 8
node_id[byte_] ^= 1 << bit_pos
# Randomize the remaining less significant bits so that we are
# performing a FindNode for a random ID within the bucket.
if bit_pos:
bit_mask = 1 << (bit_pos - 1)
bit_mask ^= bit_mask - 1
node_id[byte_] ^= random.randint(0, 255) & bit_mask
for i in range(byte_ + 1, chord.NODE_ID_BYTES):
node_id[i] ^= random.randint(0, 255)
# log.warning("Stabilize FindNode id=[{:0512b}]."\
# .format(int.from_bytes(node_id, "big")))
assert mutil.calc_log_distance(\
node_id, self.engine.node_id)[0] == (bit + 1),\
"calc={}, bit={}, diff={}."\
.format(\
mutil.calc_log_distance(\
node_id, self.engine.node_id)[0],\
bit + 1,
mutil.hex_string(\
mutil.calc_raw_distance(\
self.engine.node_id, node_id)))
nodes, new_nodes = yield from self._perform_stabilize(node_id)
found_new_nodes |= new_nodes
if not closest_found_distance and not nodes:
break
elif bit+1 == closest_found_distance:
break;
if new_nodes:
log.info("Finished total stabilize, checking connections.")
yield from self.engine.process_connection_count()
@asyncio.coroutine
def _perform_stabilize(self, node_id, input_trie=None):
"returns: conn_nods, new_nodes"\
" conn_nodes: found nodes sorted by closets."\
" new_nodes: if any found were new."
conn_nodes = yield from\
self.send_find_node(node_id, input_trie=input_trie)
if not conn_nodes:
return None, False
for node in conn_nodes:
# Do not trust hearsay node_id; add_peers will recalculate it from
# the public key.
node.node_id = None
new_nodes = yield from self.engine.add_peers(\
conn_nodes, process_check_connections=False)
return conn_nodes, bool(new_nodes)
@asyncio.coroutine
def send_get_data(self, data_key, path=None, scan_only=False,\
retry_factor=1):
assert type(data_key) in (bytes, bytearray)\
and len(data_key) == chord.NODE_ID_BYTES,\
"type(data_key)=[{}], len={}."\
.format(type(data_key), len(data_key))
if path:
if type(path) is str:
path = path.encode()
orig_data_key = data_key
path_hash = enc.generate_ID(path)
data_key = enc.generate_ID(data_key + path_hash)
else:
path_hash = None
data_id = enc.generate_ID(data_key)
data_rw = yield from\
self.send_find_node(data_id, for_data=True, data_key=data_key,\
path_hash=path_hash, scan_only=scan_only,\
retry_factor=retry_factor)
if data_rw.data:
#FIXME: This is not optimal as we start a whole new FindNode for
# this. When rewriting this file incorporate this stage into the
# retrevial process at the end (and have it async just like this).
r = random.randint(1, 5)
if retry_factor > 1:
# Increase chance of uploading a block if it was hard to fetch.
r = min(r, r * (retry_factor/10))
if r >= 5:
if data_rw.version:
if log.isEnabledFor(logging.INFO):
log.info("Healing updateable key block [{}]."\
.format(mbase32.encode(data_key)))
sdmsg = cp.ChordStoreData()
sdmsg.data = data_rw.data
sdmsg.pubkey = data_rw.pubkey
sdmsg.path_hash = data_rw.path_hash
sdmsg.version = data_rw.version
sdmsg.signature = data_rw.signature
asyncio.async(\
self.send_find_node(\
data_id, for_data=True, data_msg=sdmsg),\
loop=self.loop)
if path:
data_key = orig_data_key
asyncio.async(\
self.send_store_updateable_key_key(\
data_rw.pubkey, data_key),\
loop=self.loop)
else:
if log.isEnabledFor(logging.INFO):
log.info("Healing block [{}]."\
.format(mbase32.encode(data_key)))
asyncio.async(\
self.send_store_data(data_rw.data, store_key=False),\
loop=self.loop)
return data_rw
@asyncio.coroutine
def send_get_targeted_data(self, data_key, retry_factor=1):
assert type(data_key) in (bytes, bytearray)\
and len(data_key) == chord.NODE_ID_BYTES,\
"type(data_key)=[{}], len={}."\
.format(type(data_key), len(data_key))
data_id = enc.generate_ID(data_key)
data_rw = yield from\
self.send_find_node(data_id, for_data=True, data_key=data_key,\
targeted=True, retry_factor=retry_factor)
return data_rw
@asyncio.coroutine
def send_find_key(self, data_key_prefix, significant_bits=None,\
target_key=None, retry_factor=2):
assert type(data_key_prefix) in (bytes, bytearray),\
"type(data_key_prefix)=[{}].".format(type(data_key_prefix))
if not significant_bits:
significant_bits = len(data_key_prefix) * 8
if log.isEnabledFor(logging.INFO):
log.info("Performing wildcard (key) search (prefix=[{}],"\
" significant_bits=[{}], target_key=[{}])."\
.format(mbase32.encode(data_key_prefix), significant_bits,\
mbase32.encode(target_key)))
ldiff = chord.NODE_ID_BYTES - len(data_key_prefix)
if ldiff > 0:
data_key_prefix += b'\x00' * ldiff
data_rw = yield from\
self.send_find_node(data_key_prefix,\
significant_bits=significant_bits, for_data=True,\
data_key=None, target_key=target_key,\
retry_factor=retry_factor)
return data_rw
@asyncio.coroutine
def send_store_key(self, data, data_key=None, targeted=False,\
key_callback=None, retry_factor=5):
if log.isEnabledFor(logging.INFO):
data_key_enc = mbase32.encode(data_key) if data_key else None
log.info("Sending ChordStoreKey for data_key=[{}], targeted=[{}]."\
.format(data_key_enc, targeted))
if not data_key:
data_key = enc.generate_ID(data)
if key_callback:
key_callback(data_key)
skmsg = cp.ChordStoreKey()
skmsg.data = data
skmsg.targeted = targeted
storing_nodes =\
yield from self.send_find_node(\
data_key, for_data=True, data_msg=skmsg,\
retry_factor=retry_factor)
return storing_nodes
@asyncio.coroutine
def send_store_updateable_key_key(\
self, pubkey, data_key=None, key_callback=None, retry_factor=5):
assert type(pubkey) in (bytes, bytearray)
r = yield from\
self.send_store_key(\
pubkey, data_key=data_key, key_callback=key_callback,\
retry_factor=retry_factor)
return r
@asyncio.coroutine
def send_store_data(self, data, store_key=False, key_callback=None,\
retry_factor=5):
"Sends a StoreData request, returning the count of nodes that claim"\
" to have stored it."
# data_id is a double hash due to the anti-entrapment feature.
data_key = enc.generate_ID(data)
if key_callback:
key_callback(data_key)
data_id = enc.generate_ID(data_key)
sdmsg = cp.ChordStoreData()
sdmsg.data = data
storing_nodes =\
yield from self.send_find_node(\
data_id, for_data=True, data_msg=sdmsg)
if store_key:
yield from self.send_store_key(data, data_key)
return storing_nodes
@asyncio.coroutine
def send_store_targeted_data(\
self, data, store_key=False, key_callback=None, retry_factor=20):
"Sends a StoreData request for a TargetedBlock, returning the count"\
" of nodes that claim to have stored it."
tb_header = data[:mp.TargetedBlock.BLOCK_OFFSET]
# data_id is a double hash due to the anti-entrapment feature.
data_key = enc.generate_ID(tb_header)
if key_callback:
key_callback(data_key)
data_id = enc.generate_ID(data_key)
sdmsg = cp.ChordStoreData()
sdmsg.data = data
sdmsg.targeted = True
storing_nodes =\
yield from self.send_find_node(\
data_id, for_data=True, data_msg=sdmsg,\
retry_factor=retry_factor)
if store_key:
yield from self.send_store_key(data, data_key, targeted=True,\
retry_factor=retry_factor)
return storing_nodes
@asyncio.coroutine
def send_store_updateable_key(\
self, data, privatekey, path=None, version=None, store_key=None,\
key_callback=None, retry_factor=5):
assert not path or type(path) is bytes, type(path)
assert not version or type(version) is int, type(version)
public_key_bytes = privatekey.asbytes() # asbytes=public key.
data_key = enc.generate_ID(public_key_bytes)
if key_callback:
key_callback(data_key)
if path:
path_hash = enc.generate_ID(path)
data_id = enc.generate_ID(enc.generate_ID(data_key + path_hash))
else:
path_hash = b""
data_id = enc.generate_ID(data_key)
if log.isEnabledFor(logging.DEBUG):
log.debug("data_key=[{}], data_id=[{}]."\
.format(mbase32.encode(data_key), mbase32.encode(data_id)))
hm = bytearray()
hm += sshtype.encodeBinary(path_hash)
hm += sshtype.encodeMpint(version)
hm += sshtype.encodeBinary(enc.generate_ID(data))
signature = privatekey.sign_ssh_data(hm)
sdmsg = cp.ChordStoreData()
sdmsg.data = data
sdmsg.pubkey = public_key_bytes
sdmsg.path_hash = path_hash
sdmsg.version = version
sdmsg.signature = signature
storing_nodes =\
yield from self.send_find_node(\
data_id, for_data=True, data_msg=sdmsg)
if store_key:
yield from self.send_store_updateable_key_key(\
public_key_bytes, data_key)
return storing_nodes
@asyncio.coroutine
def send_find_node(self, node_id, significant_bits=None, input_trie=None,\
for_data=False, data_msg=None, data_key=None, path_hash=None,\
targeted=False, target_key=None, scan_only=False, retry_factor=1):
"Returns found nodes sorted by closets. If for_data is True then"\
" this is really {get/store}_data instead of find_node. If data_msg"\
" is None than it is get_data and the data is returned. Store data"\
" currently returns the count of nodes that claim to have stored the"\
" data."
assert len(node_id) == chord.NODE_ID_BYTES
# data_key needs to be bytes for PyCrypto usage later on.
assert data_key is None or type(data_key) is bytes, type(data_key)
if for_data:
data_mode = cp.DataMode.get if data_msg is None\
else cp.DataMode.store
else:
data_mode = cp.DataMode.none
if not self.engine.peers:
log.info("No connected nodes, unable to send FindNode.")
return self._generate_fail_response(data_mode, data_key)
if not input_trie:
input_trie = bittrie.BitTrie()
# for peer in self.engine.peer_trie:
for peer in self.engine.peers.values():
if not peer.full_node:
continue
key = bittrie.XorKey(node_id, peer.node_id)
input_trie[key] = peer
max_initial_queries = 3
slowpoke_factor = 2
max_concurrent_queries = max_initial_queries * slowpoke_factor
maximum_depth = 512
if log.isEnabledFor(logging.INFO):
log.info("Performing FindNode (node_id=[{}], data_mode={}) to a"\
" max depth of [{}]."\
.format(mbase32.encode(node_id), data_mode, maximum_depth))
result_trie = bittrie.BitTrie()
# Store ourselves to ignore when peers respond with us in their list.
result_trie[bittrie.XorKey(node_id, self.engine.node_id)] = False
tasks = []
used_tunnels = {}
far_peers_by_path = {}
data_msg_type = type(data_msg)
# Build the FindNode message that we are going to send.
fnmsg = cp.ChordFindNode()
fnmsg.node_id = node_id
fnmsg.data_mode = data_mode
if data_msg_type is cp.ChordStoreData:
fnmsg.version = data_msg.version
if significant_bits:
fnmsg.significant_bits = significant_bits
if target_key:
fnmsg.target_key = target_key
# Setup the DataResponseWrapper which is returned from this function
# but also is used to pass around some info to helper functions this
# main send_find_node(..) function calls.
sent_data_request = Counter(0)
data_rw = DataResponseWrapper(data_key)
if data_msg_type is cp.ChordStoreData:
if data_msg.pubkey:
data_rw.pubkey = data_msg.pubkey
if data_msg.path_hash:
data_rw.path_hash = data_msg.path_hash
else:
if path_hash:
data_rw.path_hash = path_hash
if targeted:
data_rw.targeted = True
# Open the tunnels with upto max_initial_queries immediate PeerS.
for peer in input_trie:
key = bittrie.XorKey(node_id, peer.node_id)
vpeer = VPeer(peer)
# Store immediate PeerS in the result_trie.
result_trie[key] = vpeer
if len(tasks) == max_initial_queries:
# We still add all immediate PeerS so that later we can ignore
# them if they are included in lists returned by querying.
continue
if not peer.ready():
continue
tun_meta = TunnelMeta(peer)
used_tunnels[vpeer] = tun_meta
tasks.append(self._send_find_node(\
vpeer, fnmsg, result_trie, tun_meta, data_mode,\
far_peers_by_path, data_rw))
vpeer.used = True
if not tasks:
log.info("Cannot perform FindNode, as we know no closer nodes.")
return self._generate_fail_response(data_mode, data_key)
if log.isEnabledFor(logging.DEBUG):
log.debug("Starting {} root level FindNode tasks."\
.format(len(tasks)))
done_cnt = 0
max_time = 7.0 #TODO: This is probably excessive!
diff = 0
start = datetime.today()
while diff < max_time and done_cnt < max_initial_queries:
try:
done, pending =\
yield from asyncio.wait(\
tasks,\
loop=self.loop,\
timeout=max_time - diff,\
return_when=futures.FIRST_COMPLETED)
except asyncio.CancelledError:
self._close_channels(used_tunnels)
raise
done_cnt += len(done)
tasks = list(pending)
if not pending:
break
diff = (datetime.today() - start).total_seconds()
if not done_cnt:
log.info("Couldn't open any tunnels in time, giving up.")
for task in tasks:
task.cancel()
self._close_channels(used_tunnels)
return self._generate_fail_response(data_mode, data_key)
# Instruct our tunnels to relay the FindNode message out further, also
# processing the responses and using that data to build further tunnels
# and send out the FindNode even deeper. After this loop, we have
# done all the finding we are going to do.
query_cntr = Counter(0)
task_cntr = Counter(0)
depth = Counter(0)
done_all = asyncio.Event(loop=self.loop)
done_one = asyncio.Event(loop=self.loop)
wanted = 1 if data_mode is cp.DataMode.get else max_initial_queries
if retry_factor > 1:
wanted = min(wanted, wanted + 1 * (retry_factor/10))
for depth.value in range(1, maximum_depth):
if data_rw.data_present_cnt >= wanted:
break;
if data_rw.will_store_cnt >= wanted:
break;
direct_peers_lower = 0
current_depth_step_query_cnt = 0
for row in result_trie:
if row is False:
# Row is ourself. Prevent infinite loops.
# Sometimes we are looking closer than ourselves, sometimes
# further (stabilize vs other). We could use this to end
# the loop maybe, do checks. For now, just ignoring it to
# prevent infinite loops.
continue
if row.used:
# We've already sent to this Peer.
continue
if row.path is None:
# This is a immediate (direct connected) Peer.
peer = row.peer
if not peer.ready():
continue
tun_meta = TunnelMeta(peer)
used_tunnels[row] = tun_meta
query_cntr.value += 1
task = asyncio.async(\
self._send_find_node(\
row, fnmsg, result_trie, tun_meta, data_mode,\
far_peers_by_path, data_rw, done_one=done_one,\
done_all=done_all, query_cntr=query_cntr),\
loop=self.loop)
tasks.append(task)
row.used = True
current_depth_step_query_cnt += 1
continue
tun_meta = row.tun_meta
if not tun_meta.queue:
# The tunnel is not open to this Peer anymore.
continue
if log.isEnabledFor(logging.DEBUG):
log.debug("Sending FindNode to path [{}]."\
.format(row.path))
pkt = self._generate_relay_packets(row.path)
tun_meta.peer.protocol.write_channel_data(\
tun_meta.local_cid, pkt)
row.used = True
query_cntr.value += 1
current_depth_step_query_cnt += 1
if tun_meta.jobs is None:
# If this is the first relay for this tunnel, then start a
# _process_find_node_relay task for that tunnel.
tun_meta.jobs = 1
task_cntr.value += 1
task = asyncio.async(\
self._process_find_node_relay(\
node_id, significant_bits, tun_meta, query_cntr,\
done_all, done_one, task_cntr, result_trie,\
data_mode, far_peers_by_path, sent_data_request,\
data_rw, depth),\
loop=self.loop)
tasks.append(task)
else:
tun_meta.jobs += 1
# if query_cntr.value == max_concurrent_queries:
if current_depth_step_query_cnt == max_concurrent_queries:
break
if not current_depth_step_query_cnt:
log.info("FindNode search has ended at closest nodes.")
break
# yield from done_all.wait()
# done_all.clear()
# Wait upto a second for at least one response.
try:
try:
yield from asyncio.wait_for(\
done_one.wait(),\
timeout=1,\
loop=self.loop)
except asyncio.TimeoutError:
pass
done_one.clear()
# Wait a bit more for the rest of the tasks.
try:
yield from asyncio.wait_for(\
done_all.wait(),\
timeout=0.1 * retry_factor,\
loop=self.loop)
except asyncio.TimeoutError:
pass
done_all.clear()
except asyncio.CancelledError:
self._close_channels(used_tunnels)
for task in tasks:
task.cancel()
raise
# assert query_cntr.value == 0
if not task_cntr.value:
log.info("All tasks (tunnels) exited.")
break
# Proceed to the second stage of the request.
# FIXME: Write this whole stuff to merge these two so it can be async.
if data_mode.value and not scan_only:
stores_sent = 0
if data_mode is cp.DataMode.get:
msg_name = "GetData"
data_rw.data_done = asyncio.Event(loop=self.loop)
if significant_bits:
closest_datas = []
#FIXME: Ahh! If we have it why did we do the above! :)
# Move this up to the top and save us a send_find_node!
data_present = yield from\
self._check_has_data(\
node_id, significant_bits, target_key)
if data_present:
closest_datas.append(data_present)
#TODO: This could be optimized to be built as peers sent
# the present message instead of iterating the whole list.
for vpeer in result_trie:
if not vpeer:
continue
if vpeer.data_present:
closest_datas.append(vpeer.data_present)
closest_datas.sort()
if len(closest_datas):
data_rw.data_key = closest_datas[0]
result_trie = []
else:
assert data_mode is cp.DataMode.store
if data_msg_type is cp.ChordStoreData:
msg_name = "StoreData"
else:
assert data_msg_type is cp.ChordStoreKey
msg_name = "StoreKey"
data_msg_pkt = data_msg.encode()
# If in get_data mode, then send a GetData message to each Peer
# that indicated data presence, one at a time, stopping upon first
# success. Right now we will start at closest node, which might
# make it harder to Sybil attack targeted data_ids.
#TODO: Figure out if that is so, because otherwise we might not
# want to grab from the closest for load balancing purposes.
# Certainly future versions should have a more advanced algorithm
# here that bases the decision on latency, tunnel depth, trust,
# Etc.
# If in store_data mode, then send the data to the closest willing
# nodes that we found.
if log.isEnabledFor(logging.INFO):
log.info("Sending {} with {} tunnels still open."\
.format(msg_name, task_cntr.value))
# Just FYI: There might be no tunnels open if we are connected to
# everyone, or only immediate PeerS were closest.
sent_data_request.value = 1 # Let tunnel process tasks know.
# We have to process responses from three different cases:
# 1. Peer reached through a tunnel.
# 2. Immediate Peer that is also an open tunnel. (task running)
# 3. Immediate Peer that is not an open tunnel.
# The last case requires a new processing task as no task is
# already running to handle it. Case 1 & 2 are handled by the
# _process_find_node_relay(..) co-routine tasks. The last case can
# only happen if there was no tunnel opened with that Peer. If the
# tunnel got closed then we don't even use that immediate Peer so
# it being closed won't be a case we have to handle. (We don't
# reopen channels at this point.)
#NOTE: result_trie is [] when significant_bits.
done_one.clear()
for row in result_trie:
if row is False:
# Row is ourself.
if data_mode is cp.DataMode.get:
assert significant_bits is None
data_present =\
yield from self._check_has_data(\
node_id, significant_bits, None)
if not data_present:
continue
log.info("We have the data; fetching.")
enc_data, data_l, version, signature, epubkey,\
pubkeylen =\
yield from self._retrieve_data(node_id)
if enc_data is None:
continue
drmsg = cp.ChordDataResponse()
drmsg.data = enc_data
drmsg.original_size = data_l
if version is not None:
drmsg.version = version
drmsg.signature = signature
if epubkey:
drmsg.epubkey = epubkey
drmsg.pubkeylen = pubkeylen
r = yield from self._process_data_response(\
drmsg, None, None, data_rw)
if not r:
# Data was invalid somehow!
log.warning("Data from ourselves was invalid!")
continue
# Otherwise, break out of the loop as we've fetched the
# data.
break
else:
assert data_mode is cp.DataMode.store
will_store, need_pruning =\
yield from self._check_do_want_data(\
node_id, fnmsg.version)
if not will_store:
continue
log.info("We are choosing to additionally store the"\
" data locally.")
if data_msg_type is cp.ChordStoreData:
r = yield from self._store_data(\
None, node_id, data_msg, need_pruning)
else:
assert data_msg_type is cp.ChordStoreKey
r = yield from\
self._store_key(peer, fnmsg.node_id, data_msg)
if not r:
log.info("We failed to store the data.")
#NOTE: We don't count ourselves in storing_nodes.
# Store it still elsewhere if others want it as well.
continue
if data_mode is cp.DataMode.get:
if not row.data_present:
# This node doesn't have our data.
continue
else:
assert data_mode is cp.DataMode.store
if not row.will_store:
# The node may be close to id, but it says that it
# does not want to store the proposed data for whatever
# reason.
continue
tun_meta = row.tun_meta
if tun_meta and not tun_meta.queue:
# Peer is reached through a tunnel, but the tunnel is
# closed.
continue
if log.isEnabledFor(logging.INFO):
log.info("Sending {} to Peer [{}] and path [{}]."\
.format(msg_name, row.peer.address, row.path))
if data_mode is cp.DataMode.get:
pkt = EMPTY_GET_DATA_PACKET
else:
assert data_mode is cp.DataMode.store
pkt = data_msg_pkt
if tun_meta:
# Then this is a Peer reached through a tunnel.
pkt = self._generate_relay_packets(row.path, pkt)
tun_meta.jobs += 1
else:
# Then this is an immediate Peer.
tun_meta = used_tunnels.get(row)
if tun_meta.task_running:
# Then this immediate Peer is an open tunnel and will
# be handled as described above for case #2.
tun_meta.jobs += 1
elif tun_meta.queue:
# Then this immediate Peer is not an open tunnel and we
# will have to start a task to process its DataStored
# message.
if tun_meta.jobs is None:
tun_meta.jobs = 1
else:
tun_meta.jobs += 1
asyncio.async(\
self._wait_for_data_stored(\
data_mode, row, tun_meta, query_cntr,\
done_one, done_all, data_rw),\
loop=self.loop)
else:
# Then this immediate Peer had its channel closed;
# don't use it.
continue
tun_meta.peer.protocol.write_channel_data(\
tun_meta.local_cid, pkt)
query_cntr.value += 1
done_all.clear()
if data_mode is cp.DataMode.get:
# We only send one at a time, stopping at success.
# yield from done_all.wait()