forked from Tribler/dispersy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.py
3566 lines (2897 loc) · 164 KB
/
script.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
# Python 2.5 features
from __future__ import with_statement
"""
Run some python code, usually to test one or more features.
@author: Boudewijn Schoon
@organization: Technical University Delft
@contact: [email protected]
"""
from collections import defaultdict
from hashlib import sha1
from random import shuffle
from time import time
import gc
import inspect
import socket
from .candidate import BootstrapCandidate
from .crypto import ec_generate_key, ec_to_public_bin, ec_to_private_bin
from .debug import Node
from .debugcommunity import DebugCommunity, DebugNode
from .dispersy import Dispersy
from .dispersydatabase import DispersyDatabase
from .dprint import dprint
from .member import Member
from .message import BatchConfiguration, Message, DelayMessageByProof, DropMessage
from .resolution import PublicResolution, LinearResolution
from .revision import update_revision_information
from .tool.lencoder import log, make_valid_key
# update version information directly from SVN
update_revision_information("$HeadURL$", "$Revision$")
def assert_(value, *args):
if not value:
raise AssertionError(*args)
def assert_message_stored(community, member, global_time, undone="done"):
assert isinstance(undone, str)
assert undone in ("done", "undone")
try:
actual_undone, = community.dispersy.database.execute(u"SELECT undone FROM sync WHERE community = ? AND member = ? AND global_time = ?", (community.database_id, member.database_id, global_time)).next()
except StopIteration:
assert_(False, "Message must be stored in the database (", community.database_id, ", ", member.database_id, ", ", global_time, ")")
assert_(isinstance(actual_undone, int), type(actual_undone))
assert_(0 <= actual_undone, actual_undone)
assert_((undone == "done" and actual_undone == 0) or undone == "undone" and 0 < actual_undone, [undone, actual_undone])
class ScriptBase(object):
def __init__(self, **kargs):
self._kargs = kargs
self._testcases = []
self._dispersy = Dispersy.get_instance()
self._dispersy_database = DispersyDatabase.get_instance()
# self._dispersy.callback.register(self.run)
if self.enable_wait_for_wan_address:
self.add_testcase(self.wait_for_wan_address)
self.run()
def add_testcase(self, func, args=()):
assert callable(func)
assert isinstance(args, tuple)
self._testcases.append((func, args))
def next_testcase(self, result=None):
if isinstance(result, Exception):
dprint("exception! shutdown", box=True, level="error")
self._dispersy.callback.stop(wait=False, exception=result)
elif self._testcases:
call, args = self._testcases.pop(0)
dprint("start ", call, line=True, force=True)
if args:
dprint("arguments ", args, force=True)
if call.__doc__:
dprint(call.__doc__, box=True, force=True)
self._dispersy.callback.register(call, args, callback=self.next_testcase)
else:
dprint("shutdown", box=True)
self._dispersy.callback.stop(wait=False)
def caller(self, run, args=()):
assert callable(run)
assert isinstance(args, tuple)
dprint("depricated: use add_testcase instead", level="warning")
return self.add_testcase(run, args)
def run(self):
raise NotImplementedError("Must implement a generator or use self.add_testcase(...)")
@property
def enable_wait_for_wan_address(self):
return True
def wait_for_wan_address(self):
ec = ec_generate_key(u"low")
my_member = Member(ec_to_public_bin(ec), ec_to_private_bin(ec))
community = DebugCommunity.create_community(my_member)
while self._dispersy.wan_address[0] == "0.0.0.0":
yield 0.1
community.unload_community()
class ScenarioScriptBase(ScriptBase):
#TODO: all bartercast references should be converted to some universal style
def __init__(self, logfile, **kargs):
ScriptBase.__init__(self, **kargs)
self._timestep = float(kargs.get('timestep', 1.0))
self._stepcount = 0
self._logfile = logfile
self._my_name = None
self._my_address = None
self._nr_peers = self.__get_nr_peers()
if 'starting_timestamp' in kargs:
self._starting_timestamp = int(kargs['starting_timestamp'])
log(self._logfile, "Using %d as starting timestamp, will wait for %d seconds"%(self._starting_timestamp, self._starting_timestamp - int(time())))
else:
self._starting_timestamp = int(time())
log(self._logfile, "No starting_timestamp specified, using currentime")
@property
def enable_wait_for_wan_address(self):
return False
def get_peer_ip_port(self, peer_id):
assert isinstance(peer_id, int), type(peer_id)
line_nr = 1
for line in open('data/peers'):
if line_nr == peer_id:
ip, port = line.split()
return ip, int(port)
line_nr += 1
def __get_nr_peers(self):
line_nr = 0
for line in open('data/peers'):
line_nr +=1
return line_nr
def set_online(self):
""" Restore on_socket_endpoint and _send functions of
dispersy back to normal.
This simulates a node coming online, since it's able to send
and receive messages.
"""
log(self._logfile, "Going online")
self._dispersy.on_incoming_packets = self.original_on_incoming_packets
self._dispersy.endpoint.send = self.original_send
def set_offline(self):
""" Replace on_socket_endpoint and _sends functions of
dispersy with dummies
This simulates a node going offline, since it's not able to
send or receive any messages
"""
def dummy_on_socket(*params):
return
def dummy_send(*params):
return False
log(self._logfile, "Going offline")
self._dispersy.on_socket_endpoint = dummy_on_socket
self._dispersy.endpoint.send = dummy_send
def get_commands_from_fp(self, fp, step):
""" Return a list of commands from file handle for step
Read lines from fp and return all the lines starting at
timestamp equal to step. If we read the end of the file,
without commands to return, then I return -1.
"""
commands = []
if fp:
while True:
cursor_position = fp.tell()
line = fp.readline().strip()
if not line:
if commands: return commands
else: return -1
cmdstep, command = line.split(' ', 1)
cmdstep = int(cmdstep)
if cmdstep < step:
continue
elif cmdstep == step:
commands.append(command)
else:
# restore cursor position and break
fp.seek(cursor_position)
break
return commands
def sleep(self):
""" Calculate the time to sleep.
"""
#when should we start the next step?
expected_time = self._starting_timestamp + (self._timestep * (self._stepcount + 1))
diff = expected_time - time()
delay = max(0.0, diff)
return delay
def log_desync(self, desync):
log(self._logfile, "sleep", desync=desync, stepcount=self._stepcount)
def join_community(self, my_member):
raise NotImplementedError()
def execute_scenario_cmds(self, commands):
raise NotImplementedError()
def run(self):
self.add_testcase(self._run)
def _run(self):
if __debug__: log(self._logfile, "start-scenario-script")
#
# Read our configuration from the peer.conf file
# name, ip, port, public and private key
#
with open('data/peer.conf') as fp:
self._my_name, ip, port, _ = fp.readline().split()
self._my_address = (ip, int(port))
log(self._logfile, "Read config done", my_name = self._my_name, my_address = self._my_address)
# create my member
ec = ec_generate_key(u"low")
my_member = Member(ec_to_public_bin(ec), ec_to_private_bin(ec))
dprint("-my member- ", my_member.database_id, " ", id(my_member), " ", my_member.mid.encode("HEX"), force=1)
self.original_on_incoming_packets = self._dispersy.on_incoming_packets
self.original_send = self._dispersy.endpoint.send
# join the community with the newly created member
self._community = self.join_community(my_member)
dprint("Joined community ", self._community._my_member)
log("dispersy.log", "joined-community", time = time(), timestep = self._timestep, sync_response_limit = self._community.dispersy_sync_response_limit, starting_timestamp = self._starting_timestamp)
self._stepcount = 0
# wait until we reach the starting time
self._dispersy.callback.register(self.do_steps, delay=self.sleep())
self._dispersy.callback.register(self.do_log)
# I finished the scenario execution. I should stay online
# until killed. Note that I can still sync and exchange
# messages with other peers.
while True:
# wait to be killed
yield 100.0
def do_steps(self):
self._dispersy._statistics.reset()
scenario_fp = open('data/bartercast.log')
try:
availability_fp = open('data/availability.log')
except:
availability_fp = None
self._stepcount += 1
# start the scenario
while True:
# get commands
scenario_cmds = self.get_commands_from_fp(scenario_fp, self._stepcount)
availability_cmds = self.get_commands_from_fp(availability_fp, self._stepcount)
# if there is a start in the avaibility_cmds then go
# online
if availability_cmds != -1 and 'start' in availability_cmds:
self.set_online()
# if there are barter_cmds then execute them
if scenario_cmds != -1:
self.execute_scenario_cmds(scenario_cmds)
# if there is a stop in the availability_cmds then go offline
if availability_cmds != -1 and 'stop' in availability_cmds:
self.set_offline()
sleep = self.sleep()
if sleep < 0.5:
self.log_desync(1.0 - sleep)
yield sleep
self._stepcount += 1
def do_log(self):
def print_on_change(name, prev_dict, cur_dict):
new_values = {}
changed_values = {}
if cur_dict:
for key, value in cur_dict.iteritems():
if not isinstance(key, (basestring, int, long)):
key = str(key)
key = make_valid_key(key)
new_values[key] = value
if prev_dict.get(key, None) != value:
changed_values[key] = value
if changed_values:
log("dispersy.log", name, **changed_values)
return new_values
return prev_dict
prev_statistics = {}
prev_total_received = {}
prev_total_dropped = {}
prev_total_delayed = {}
prev_total_outgoing = {}
prev_total_fail = {}
prev_endpoint_recv = {}
prev_endpoint_send = {}
prev_created_messages = {}
prev_bootstrap_candidates = {}
while True:
#print statistics
self._dispersy.statistics.update()
bl_reuse = sum(c.sync_bloom_reuse for c in self._dispersy.statistics.communities)
candidates = [(c.classification, len(c.candidates) if c.candidates else 0) for c in self._dispersy.statistics.communities]
statistics_dict= {'received_count': self._dispersy.statistics.received_count, 'total_up': self._dispersy.statistics.total_up, 'total_down': self._dispersy.statistics.total_down, 'drop_count': self._dispersy.statistics.drop_count, 'total_send': self._dispersy.statistics.total_send, 'cur_sendqueue': self._dispersy.statistics.cur_sendqueue, 'delay_count': self._dispersy.statistics.delay_count, 'delay_success': self._dispersy.statistics.delay_success, 'delay_timeout': self._dispersy.statistics.delay_timeout, 'walk_attempt': self._dispersy.statistics.walk_attempt, 'walk_success': self._dispersy.statistics.walk_success, 'walk_reset': self._dispersy.statistics.walk_reset, 'conn_type': self._dispersy.statistics.connection_type, 'bl_reuse': bl_reuse, 'candidates': candidates}
prev_statistics = print_on_change("statistics", prev_statistics, statistics_dict)
prev_total_received = print_on_change("statistics-successful-messages", prev_total_received ,self._dispersy.statistics.success)
prev_total_dropped = print_on_change("statistics-dropped-messages", prev_total_dropped ,self._dispersy.statistics.drop)
prev_total_delayed = print_on_change("statistics-delayed-messages", prev_total_delayed ,self._dispersy.statistics.delay)
prev_total_outgoing = print_on_change("statistics-outgoing-messages", prev_total_outgoing ,self._dispersy.statistics.outgoing)
prev_total_fail = print_on_change("statistics-walk-fail", prev_total_fail ,self._dispersy.statistics.walk_fail)
prev_endpoint_recv = print_on_change("statistics-endpoint-recv", prev_endpoint_recv ,self._dispersy.statistics.endpoint_recv)
prev_endpoint_send = print_on_change("statistics-endpoint-send", prev_endpoint_send ,self._dispersy.statistics.endpoint_send)
prev_created_messages = print_on_change("statistics-created-messages", prev_created_messages ,self._dispersy.statistics.created)
prev_bootstrap_candidates = print_on_change("statistics-bootstrap-candidates", prev_bootstrap_candidates ,self._dispersy.statistics.bootstrap_candidates)
# def callback_cmp(a, b):
# return cmp(self._dispersy.callback._statistics[a][0], self._dispersy.callback._statistics[b][0])
# keys = self._dispersy.callback._statistics.keys()
# keys.sort(reverse = True)
#
# total_run = {}
# for key in keys[:10]:
# total_run[make_valid_key(key)] = self._dispersy.callback._statistics[key]
# if len(total_run) > 0:
# log("dispersy.log", "statistics-callback-run", **total_run)
# stats = Conversion.debug_stats
# total = stats["encode-message"]
# nice_total = {'encoded':stats["-encode-count"], 'total':"%.2fs"%total}
# for key, value in sorted(stats.iteritems()):
# if key.startswith("encode") and not key == "encode-message" and total:
# nice_total[make_valid_key(key)] = "%7.2fs ~%5.1f%%" % (value, 100.0 * value / total)
# log("dispersy.log", "statistics-encode", **nice_total)
#
# total = stats["decode-message"]
# nice_total = {'decoded':stats["-decode-count"], 'total':"%.2fs"%total}
# for key, value in sorted(stats.iteritems()):
# if key.startswith("decode") and not key == "decode-message" and total:
# nice_total[make_valid_key(key)] = "%7.2fs ~%5.1f%%" % (value, 100.0 * value / total)
# log("dispersy.log", "statistics-decode", **nice_total)
yield 1.0
class DispersyClassificationScript(ScriptBase):
def run(self):
ec = ec_generate_key(u"low")
self._my_member = Member(ec_to_public_bin(ec), ec_to_private_bin(ec))
self.add_testcase(self.load_no_communities)
self.add_testcase(self.load_one_communities)
self.add_testcase(self.load_two_communities)
self.add_testcase(self.unloading_community)
self.add_testcase(self.enable_autoload)
self.add_testcase(self.enable_disable_autoload)
self.add_testcase(self.reclassify_unloaded_community)
self.add_testcase(self.reclassify_loaded_community)
def reclassify_unloaded_community(self):
"""
Load a community, reclassify it, load all communities of that classification to check.
"""
class ClassTestA(DebugCommunity):
pass
class ClassTestB(DebugCommunity):
pass
# no communities should exist
assert_([ClassTestA.load_community(master) for master in ClassTestA.get_master_members()] == [], "Did you remove the database before running this testcase?")
assert_([ClassTestB.load_community(master) for master in ClassTestB.get_master_members()] == [], "Did you remove the database before running this testcase?")
# create master member
ec = ec_generate_key(u"high")
master = Member(ec_to_public_bin(ec), ec_to_private_bin(ec))
# create community
self._dispersy_database.execute(u"INSERT INTO community (master, member, classification) VALUES (?, ?, ?)",
(master.database_id, self._my_member.database_id, ClassTestA.get_classification()))
# reclassify
community = self._dispersy.reclassify_community(master, ClassTestB)
assert_(isinstance(community, ClassTestB))
assert_(community.cid == master.mid)
try:
classification, = self._dispersy_database.execute(u"SELECT classification FROM community WHERE master = ?", (master.database_id,)).next()
except StopIteration:
assert_(False)
assert_(classification == ClassTestB.get_classification())
# cleanup
community.unload_community()
def reclassify_loaded_community(self):
"""
Load a community, reclassify it, load all communities of that classification to check.
"""
class ClassTestC(DebugCommunity):
pass
class ClassTestD(DebugCommunity):
pass
# no communities should exist
assert_([ClassTestC.load_community(master) for master in ClassTestC.get_master_members()] == [], "Did you remove the database before running this testcase?")
assert_([ClassTestD.load_community(master) for master in ClassTestD.get_master_members()] == [], "Did you remove the database before running this testcase?")
# create community
community_c = ClassTestC.create_community(self._my_member)
assert_(len(list(self._dispersy_database.execute(u"SELECT * FROM community WHERE classification = ?", (ClassTestC.get_classification(),)))) == 1)
# reclassify
community_d = self._dispersy.reclassify_community(community_c, ClassTestD)
assert_(isinstance(community_d, ClassTestD))
assert_(community_c.cid == community_d.cid)
try:
classification, = self._dispersy_database.execute(u"SELECT classification FROM community WHERE master = ?", (community_c.master_member.database_id,)).next()
except StopIteration:
assert_(False)
assert_(classification == ClassTestD.get_classification())
# cleanup
community_d.unload_community()
def load_no_communities(self):
"""
Try to load communities of a certain classification while there are no such communities.
"""
class ClassificationLoadNoCommunities(DebugCommunity):
pass
assert_([ClassificationLoadNoCommunities.load_community(master) for master in ClassificationLoadNoCommunities.get_master_members()] == [], "Did you remove the database before running this testcase?")
def load_one_communities(self):
"""
Try to load communities of a certain classification while there is exactly one such
community available.
"""
class ClassificationLoadOneCommunities(DebugCommunity):
pass
# no communities should exist
assert_([ClassificationLoadOneCommunities.load_community(master) for master in ClassificationLoadOneCommunities.get_master_members()] == [], "Did you remove the database before running this testcase?")
# create master member
ec = ec_generate_key(u"high")
master = Member(ec_to_public_bin(ec), ec_to_private_bin(ec))
# create one community
self._dispersy_database.execute(u"INSERT INTO community (master, member, classification) VALUES (?, ?, ?)",
(master.database_id, self._my_member.database_id, ClassificationLoadOneCommunities.get_classification()))
# load one community
communities = [ClassificationLoadOneCommunities.load_community(master) for master in ClassificationLoadOneCommunities.get_master_members()]
assert_(len(communities) == 1)
assert_(isinstance(communities[0], ClassificationLoadOneCommunities))
# cleanup
communities[0].unload_community()
def load_two_communities(self):
"""
Try to load communities of a certain classification while there is exactly two such
community available.
"""
class LoadTwoCommunities(DebugCommunity):
pass
# no communities should exist
assert_([LoadTwoCommunities.load_community(master) for master in LoadTwoCommunities.get_master_members()] == [])
masters = []
# create two communities
community = LoadTwoCommunities.create_community(self._my_member)
masters.append(community.master_member.public_key)
community.unload_community()
community = LoadTwoCommunities.create_community(self._my_member)
masters.append(community.master_member.public_key)
community.unload_community()
# load two communities
assert_(sorted(masters) == sorted(master.public_key for master in LoadTwoCommunities.get_master_members()))
communities = [LoadTwoCommunities.load_community(master) for master in LoadTwoCommunities.get_master_members()]
assert_(sorted(masters) == sorted(community.master_member.public_key for community in communities))
assert_(len(communities) == 2, len(communities))
assert_(isinstance(communities[0], LoadTwoCommunities))
assert_(isinstance(communities[1], LoadTwoCommunities))
# cleanup
communities[0].unload_community()
communities[1].unload_community()
def unloading_community(self):
"""
Test that calling community.unload_community() eventually results in a call to
community.__del__().
"""
class ClassificationUnloadingCommunity(DebugCommunity):
pass
def check(verbose=False):
# using a function to ensure all local variables are removed (scoping)
i = 0
j = 0
for x in gc.get_objects():
if isinstance(x, ClassificationUnloadingCommunity):
i += 1
for obj in gc.get_referrers(x):
j += 1
if verbose:
dprint(type(obj))
try:
lines, lineno = inspect.getsourcelines(obj)
dprint([line.rstrip() for line in lines], lines=1)
except TypeError:
dprint("TypeError")
pass
dprint(j, " referrers")
return i
community = ClassificationUnloadingCommunity.create_community(self._my_member)
master = community.master_member
cid = community.cid
del community
assert_(isinstance(self._dispersy.get_community(cid), ClassificationUnloadingCommunity))
assert_(check() == 1)
# unload the community
self._dispersy.get_community(cid).unload_community()
try:
self._dispersy.get_community(cid, auto_load=False)
assert_(False)
except KeyError:
pass
# must be garbage collected
wait = 10
for i in range(wait):
gc.collect()
dprint("waiting... ", wait - i)
if check() == 0:
break
else:
yield 1.0
assert_(check(True) == 0)
# load the community for cleanup
community = ClassificationUnloadingCommunity.load_community(master)
assert_(check() == 1)
# cleanup
community.create_dispersy_destroy_community(u"hard-kill")
self._dispersy.get_community(community.cid).unload_community()
def enable_autoload(self):
"""
- Create community
- Enable auto-load (should be enabled by default)
- Define auto load
- Unload community
- Send community message
- Verify that the community got auto-loaded
- Undefine auto load
"""
# create community
community = DebugCommunity.create_community(self._my_member)
cid = community.cid
message = community.get_meta_message(u"full-sync-text")
# create node
node = DebugNode()
node.init_socket()
node.set_community(community)
node.init_my_member(candidate=False)
yield 0.555
dprint("verify auto-load is enabled (default)")
assert_(community.dispersy_auto_load == True)
yield 0.555
dprint("define auto load")
self._dispersy.define_auto_load(DebugCommunity)
yield 0.555
dprint("create wake-up message")
global_time = 10
wakeup = node.encode_message(node.create_full_sync_text_message("Should auto-load", global_time))
dprint("unload community")
community.unload_community()
community = None
node.set_community(None)
try:
self._dispersy.get_community(cid, auto_load=False)
assert_(False)
except KeyError:
pass
yield 0.555
dprint("send community message")
node.give_packet(wakeup)
yield 0.555
dprint("verify that the community got auto-loaded")
try:
community = self._dispersy.get_community(cid)
except KeyError:
assert_(False)
# verify that the message was received
times = [x for x, in self._dispersy_database.execute(u"SELECT global_time FROM sync WHERE community = ? AND member = ? AND meta_message = ?", (community.database_id, node.my_member.database_id, message.database_id))]
assert_(global_time in times)
yield 0.555
dprint("undefine auto load")
self._dispersy.undefine_auto_load(DebugCommunity)
yield 0.555
dprint("cleanup")
community.create_dispersy_destroy_community(u"hard-kill")
self._dispersy.get_community(community.cid).unload_community()
def enable_disable_autoload(self):
"""
- Create community
- Enable auto-load (should be enabled by default)
- Define auto load
- Unload community
- Send community message
- Verify that the community got auto-loaded
- Disable auto-load
- Send community message
- Verify that the community did NOT get auto-loaded
- Undefine auto load
"""
# create community
community = DebugCommunity.create_community(self._my_member)
cid = community.cid
community_database_id = community.database_id
master_member = community.master_member
message = community.get_meta_message(u"full-sync-text")
# create node
node = DebugNode()
node.init_socket()
node.set_community(community)
node.init_my_member(candidate=False)
dprint("verify auto-load is enabled (default)")
assert_(community.dispersy_auto_load == True)
dprint("define auto load")
self._dispersy.define_auto_load(DebugCommunity)
dprint("create wake-up message")
global_time = 10
wakeup = node.encode_message(node.create_full_sync_text_message("Should auto-load", global_time))
dprint("unload community")
community.unload_community()
community = None
node.set_community(None)
try:
self._dispersy.get_community(cid, auto_load=False)
assert_(False)
except KeyError:
pass
dprint("send community message")
node.give_packet(wakeup)
dprint("verify that the community got auto-loaded")
try:
community = self._dispersy.get_community(cid)
except KeyError:
assert_(False)
# verify that the message was received
times = [x for x, in self._dispersy_database.execute(u"SELECT global_time FROM sync WHERE community = ? AND member = ? AND meta_message = ?", (community.database_id, node.my_member.database_id, message.database_id))]
assert_(global_time in times)
dprint("disable auto-load")
community.dispersy_auto_load = False
assert_(community.dispersy_auto_load == False)
dprint("create wake-up message")
node.set_community(community)
global_time = 11
wakeup = node.encode_message(node.create_full_sync_text_message("Should auto-load", global_time))
dprint("unload community")
community.unload_community()
community = None
node.set_community(None)
try:
self._dispersy.get_community(cid, auto_load=False)
assert_(False)
except KeyError:
pass
dprint("send community message")
node.give_packet(wakeup)
dprint("verify that the community did not get auto-loaded")
try:
self._dispersy.get_community(cid, auto_load=False)
assert_(False)
except KeyError:
pass
# verify that the message was NOT received
times = [x for x, in self._dispersy_database.execute(u"SELECT global_time FROM sync WHERE community = ? AND member = ? AND meta_message = ?", (community_database_id, node.my_member.database_id, message.database_id))]
assert_(not global_time in times)
dprint("undefine auto load")
self._dispersy.undefine_auto_load(DebugCommunity)
dprint("cleanup")
community = DebugCommunity.load_community(master_member)
community.create_dispersy_destroy_community(u"hard-kill")
self._dispersy.get_community(community.cid).unload_community()
class DispersyTimelineScript(ScriptBase):
def run(self):
ec = ec_generate_key(u"low")
self._my_member = Member(ec_to_public_bin(ec), ec_to_private_bin(ec))
self.add_testcase(self.succeed_check)
self.add_testcase(self.fail_check)
self.add_testcase(self.loading_community)
self.add_testcase(self.delay_by_proof)
self.add_testcase(self.missing_proof)
self.add_testcase(self.missing_authorize_proof)
def succeed_check(self):
"""
Create a community and perform check if a hard-kill message is accepted.
Whenever a community is created the owner message is authorized to use the
dispersy-destroy-community message. Hence, this message should be accepted by the
timeline.check().
"""
# create a community.
community = DebugCommunity.create_community(self._my_member)
# the master member must have given my_member all permissions for dispersy-destroy-community
yield 0.555
dprint("master_member: ", community.master_member.database_id, ", ", community.master_member.mid.encode("HEX"))
dprint(" my_member: ", community.my_member.database_id, ", ", community.my_member.mid.encode("HEX"))
# check if we are still allowed to send the message
message = community.create_dispersy_destroy_community(u"hard-kill", store=False, update=False, forward=False)
assert_(message.authentication.member == self._my_member)
result = list(message.check_callback([message]))
assert_(result == [message], "check_... methods should return a generator with the accepted messages")
# cleanup
community.create_dispersy_destroy_community(u"hard-kill")
self._dispersy.get_community(community.cid).unload_community()
def fail_check(self):
"""
Create a community and perform check if a hard-kill message is NOT accepted.
Whenever a community is created the owner message is authorized to use the
dispersy-destroy-community message. We will first revoke the authorization (to use this
message) and ensure that the message is no longer accepted by the timeline.check().
"""
# create a community.
community = DebugCommunity.create_community(self._my_member)
# the master member must have given my_member all permissions for dispersy-destroy-community
yield 0.555
dprint("master_member: ", community.master_member.database_id, ", ", community.master_member.mid.encode("HEX"))
dprint(" my_member: ", community.my_member.database_id, ", ", community.my_member.mid.encode("HEX"))
# remove the right to hard-kill
community.create_dispersy_revoke([(community.my_member, community.get_meta_message(u"dispersy-destroy-community"), u"permit")], sign_with_master=True, store=False, forward=False)
# check if we are still allowed to send the message
message = community.create_dispersy_destroy_community(u"hard-kill", store=False, update=False, forward=False)
assert_(message.authentication.member == self._my_member)
result = list(message.check_callback([message]))
assert_(len(result) == 1, "check_... methods should return a generator with the accepted messages")
assert_(isinstance(result[0], DelayMessageByProof), "check_... methods should return a generator with the accepted messages")
# cleanup
community.create_dispersy_destroy_community(u"hard-kill", sign_with_master=True)
self._dispersy.get_community(community.cid).unload_community()
def loading_community(self):
"""
When a community is loaded it must load all available dispersy-authorize and dispersy-revoke
message from the database.
"""
class LoadingCommunityTestCommunity(DebugCommunity):
pass
# create a community. the master member must have given my_member all permissions for
# dispersy-destroy-community
community = LoadingCommunityTestCommunity.create_community(self._my_member)
cid = community.cid
dprint("master_member: ", community.master_member.database_id, ", ", community.master_member.mid.encode("HEX"))
dprint(" my_member: ", community.my_member.database_id, ", ", community.my_member.mid.encode("HEX"))
dprint("unload community")
community.unload_community()
community = None
yield 0.555
# load the same community and see if the same permissions are loaded
communities = [LoadingCommunityTestCommunity.load_community(master) for master in LoadingCommunityTestCommunity.get_master_members()]
assert_(len(communities) == 1)
assert_(communities[0].cid == cid)
community = communities[0]
# check if we are still allowed to send the message
message = community.create_dispersy_destroy_community(u"hard-kill", store=False, update=False, forward=False)
assert_(community._timeline.check(message))
# cleanup
community.create_dispersy_destroy_community(u"hard-kill")
self._dispersy.get_community(community.cid).unload_community()
def delay_by_proof(self):
"""
When SELF receives a message that it has no permission for, it will send a
dispersy-missing-proof message to try to obtain the dispersy-authorize.
"""
community = DebugCommunity.create_community(self._my_member)
# create node and ensure that SELF knows the node address
node1 = DebugNode()
node1.init_socket()
node1.set_community(community)
node1.init_my_member()
yield 0.555
# create node and ensure that SELF knows the node address
node2 = DebugNode()
node2.init_socket()
node2.set_community(community)
node2.init_my_member()
yield 0.555
# permit NODE1
dprint("SELF creates dispersy-authorize for NODE1")
community.create_dispersy_authorize([(node1.my_member, community.get_meta_message(u"protected-full-sync-text"), u"permit"),
(node1.my_member, community.get_meta_message(u"protected-full-sync-text"), u"authorize")])
# NODE2 created message @20
dprint("NODE2 creates protected-full-sync-text, should be delayed for missing proof")
global_time = 20
message = node2.create_protected_full_sync_text_message("Protected message", global_time)
node2.give_message(message)
yield 0.555
# may NOT have been stored in the database
try:
packet, = self._dispersy_database.execute(u"SELECT packet FROM sync WHERE community = ? AND member = ? AND global_time = ?",
(community.database_id, node2.my_member.database_id, global_time)).next()
except StopIteration:
pass
else:
assert_(False, "should not have stored, did not have permission")
# SELF sends dispersy-missing-proof to NODE2
dprint("NODE2 receives dispersy-missing-proof")
_, message = node2.receive_message(message_names=[u"dispersy-missing-proof"])
assert_(message.payload.member.public_key == node2.my_member.public_key)
assert_(message.payload.global_time == global_time)
dprint("=====")
dprint("node1: ", node1.my_member.database_id)
dprint("node2: ", node2.my_member.database_id)
# NODE1 provides proof
dprint("NODE1 creates and provides missing proof")
sequence_number = 1
proof_global_time = 10
node2.give_message(node1.create_dispersy_authorize([(node2.my_member, community.get_meta_message(u"protected-full-sync-text"), u"permit")], sequence_number, proof_global_time))
yield 0.555
dprint("=====")
# must have been stored in the database
dprint("SELF must have processed both the proof and the protected-full-sync-text message")
try:
packet, = self._dispersy_database.execute(u"SELECT packet FROM sync WHERE community = ? AND member = ? AND global_time = ?",
(community.database_id, node2.my_member.database_id, global_time)).next()
except StopIteration:
assert_(False, "should have been stored")
# cleanup
community.create_dispersy_destroy_community(u"hard-kill")
self._dispersy.get_community(community.cid).unload_community()
def missing_proof(self):
"""
When SELF receives a dispersy-missing-proof message she needs to find and send the proof.
"""
community = DebugCommunity.create_community(self._my_member)
# create node and ensure that SELF knows the node address
node = DebugNode()
node.init_socket()
node.set_community(community)
node.init_my_member()
yield 0.555
# SELF creates a protected message
message = community.create_protected_full_sync_text("Protected message")
# flush incoming socket buffer
node.drop_packets()
# NODE pretends to receive the protected message and requests the proof
node.give_message(node.create_dispersy_missing_proof_message(message.authentication.member, message.distribution.global_time))
yield 0.555
# SELF sends dispersy-authorize to NODE
_, authorize = node.receive_message(message_names=[u"dispersy-authorize"])
permission_triplet = (community.my_member, community.get_meta_message(u"protected-full-sync-text"), u"permit")
assert_(permission_triplet in authorize.payload.permission_triplets)
# cleanup
community.create_dispersy_destroy_community(u"hard-kill")
self._dispersy.get_community(community.cid).unload_community()
def missing_authorize_proof(self):
"""
MASTER
\\ authorize(MASTER, OWNER)
\\
OWNER
\\ authorize(OWNER, NODE1)
\\
NODE1
When SELF receives a dispersy-missing-proof message from NODE2 for authorize(OWNER, NODE1)
the dispersy-authorize message for authorize(MASTER, OWNER) must be returned.
"""
community = DebugCommunity.create_community(self._my_member)
# create node and ensure that SELF knows the node address
node1 = DebugNode()
node1.init_socket()
node1.set_community(community)
node1.init_my_member()
yield 0.555
# create node and ensure that SELF knows the node address
node2 = DebugNode()
node2.init_socket()
node2.set_community(community)
node2.init_my_member()
yield 0.555