forked from holochain/holochain-proto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dht_test.go
924 lines (776 loc) · 31.1 KB
/
dht_test.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
package holochain
import (
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"testing"
"time"
. "github.com/holochain/holochain-proto/hash"
b58 "github.com/jbenet/go-base58"
peer "github.com/libp2p/go-libp2p-peer"
. "github.com/smartystreets/goconvey/convey"
"github.com/tidwall/buntdb"
)
func TestNewDHT(t *testing.T) {
d, _, h := PrepareTestChain("test")
defer CleanupTestChain(h, d)
os.Remove(filepath.Join(h.DBPath(), DHTStoreFileName))
Convey("It should initialize the DHT struct and data store", t, func() {
So(FileExists(h.DBPath(), DHTStoreFileName), ShouldBeFalse)
dht := NewDHT(h)
So(FileExists(h.DBPath(), DHTStoreFileName), ShouldBeTrue)
So(dht.h, ShouldEqual, h)
So(dht.config, ShouldEqual, &h.nucleus.dna.DHTConfig)
})
}
func TestSetupDHT(t *testing.T) {
d, _, h := PrepareTestChain("test")
defer CleanupTestChain(h, d)
err := h.dht.SetupDHT()
Convey("it should add the holochain ID to the DHT", t, func() {
So(err, ShouldBeNil)
ID := h.DNAHash()
So(h.dht.exists(ID, StatusLive), ShouldBeNil)
_, et, _, status, err := h.dht.get(h.dnaHash, StatusLive, GetMaskAll)
So(err, ShouldBeNil)
So(status, ShouldEqual, StatusLive)
So(et, ShouldEqual, DNAEntryType)
})
Convey("it should push the agent entry to the DHT at genesis time", t, func() {
data, et, _, status, err := h.dht.get(h.agentHash, StatusLive, GetMaskAll)
So(err, ShouldBeNil)
So(status, ShouldEqual, StatusLive)
So(et, ShouldEqual, AgentEntryType)
var e Entry
e, _, _ = h.chain.GetEntry(h.agentHash)
var b []byte
b, _ = e.Marshal()
So(string(data), ShouldEqual, string(b))
})
Convey("it should push the key to the DHT at genesis time", t, func() {
keyHash, _ := NewHash(h.nodeIDStr)
data, et, _, status, err := h.dht.get(keyHash, StatusLive, GetMaskAll)
So(err, ShouldBeNil)
So(status, ShouldEqual, StatusLive)
So(et, ShouldEqual, KeyEntryType)
pubKey, err := h.agent.EncodePubKey()
So(string(data), ShouldEqual, pubKey)
data, et, _, status, err = h.dht.get(keyHash, StatusDefault, GetMaskDefault)
So(err, ShouldBeNil)
So(status, ShouldEqual, StatusLive)
So(string(data), ShouldEqual, pubKey)
})
}
func TestPutGetModDel(t *testing.T) {
d, _, h := PrepareTestChain("test")
defer CleanupTestChain(h, d)
dht := h.dht
var id = h.nodeID
hash, _ := NewHash("QmY8Mzg9F69e5P9AoQPYat655HEhc1TVGs11tmfNSzkqh2")
var idx int
Convey("It should store and retrieve", t, func() {
err := dht.put(h.node.NewMessage(PUT_REQUEST, PutReq{H: hash}), "someType", hash, id, []byte("some value"), StatusLive)
So(err, ShouldBeNil)
idx, _ = dht.GetIdx()
data, entryType, sources, status, err := dht.get(hash, StatusLive, GetMaskAll)
So(err, ShouldBeNil)
So(string(data), ShouldEqual, "some value")
So(entryType, ShouldEqual, "someType")
So(status, ShouldEqual, StatusLive)
So(sources[0], ShouldEqual, h.nodeIDStr)
badhash, _ := NewHash("QmY8Mzg9F69e5P9AoQPYat655HEhc1TVGs11tmfNSzkqh3")
data, entryType, _, _, err = dht.get(badhash, StatusLive, GetMaskDefault)
So(entryType, ShouldEqual, "")
So(err, ShouldEqual, ErrHashNotFound)
})
Convey("mod should move the hash to the modified status and record replacedBy link", t, func() {
m := h.node.NewMessage(MOD_REQUEST, hash)
newhashStr := "QmY8Mzg9F69e5P9AoQPYat655HEhc1TVGs11tmfNSzkqh4"
newhash, _ := NewHash(newhashStr)
err := dht.mod(m, hash, newhash)
So(err, ShouldBeNil)
data, entryType, _, status, err := dht.get(hash, StatusAny, GetMaskAll)
So(err, ShouldBeNil)
So(string(data), ShouldEqual, "some value")
So(entryType, ShouldEqual, "someType")
So(status, ShouldEqual, StatusModified)
afterIdx, _ := dht.GetIdx()
So(afterIdx-idx, ShouldEqual, 1)
data, entryType, _, status, err = dht.get(hash, StatusLive, GetMaskDefault)
So(err, ShouldEqual, ErrHashNotFound)
data, entryType, _, status, err = dht.get(hash, StatusDefault, GetMaskDefault)
So(err, ShouldEqual, ErrHashModified)
// replaced by link gets returned in the data!!
So(string(data), ShouldEqual, newhashStr)
links, err := dht.getLinks(hash, SysTagReplacedBy, StatusLive)
So(err, ShouldBeNil)
So(len(links), ShouldEqual, 1)
So(links[0].H, ShouldEqual, newhashStr)
})
Convey("del should move the hash to the deleted status", t, func() {
m := h.node.NewMessage(DEL_REQUEST, hash)
err := dht.del(m, hash)
So(err, ShouldBeNil)
data, entryType, _, status, err := dht.get(hash, StatusAny, GetMaskAll)
So(err, ShouldBeNil)
So(string(data), ShouldEqual, "some value")
So(entryType, ShouldEqual, "someType")
So(status, ShouldEqual, StatusDeleted)
afterIdx, _ := dht.GetIdx()
So(afterIdx-idx, ShouldEqual, 2)
data, entryType, _, status, err = dht.get(hash, StatusLive, GetMaskDefault)
So(err, ShouldEqual, ErrHashNotFound)
data, entryType, _, status, err = dht.get(hash, StatusDefault, GetMaskDefault)
So(err, ShouldEqual, ErrHashDeleted)
})
}
func TestLinking(t *testing.T) {
d, _, h := PrepareTestChain("test")
defer CleanupTestChain(h, d)
err := h.dht.SetupDHT()
dht := h.dht
baseStr := "QmZcUPvPhD1Xvk6mwijYF8AfR3mG31S1YsEfHG4khrFPRr"
base, err := NewHash(baseStr)
if err != nil {
panic(err)
}
linkingEntryHashStr := "QmY8Mzg9F69e5P9AoQPYat655HEhc1TVGs11tmfNSzkqh3"
linkingEntryHash, _ := NewHash(linkingEntryHashStr)
linkHash1Str := "QmY8Mzg9F69e5P9AoQPYat655HEhc1TVGs11tmfNSzkqh1"
linkHash1, _ := NewHash(linkHash1Str)
linkHash2Str := "QmY8Mzg9F69e5P9AoQPYat655HEhc1TVGs11tmfNSzkqh2"
//linkHash2, _ := NewHash(linkHash2Str)
Convey("It should fail if hash doesn't exist", t, func() {
err := dht.putLink(nil, baseStr, linkHash1Str, "tag foo")
So(err, ShouldEqual, ErrHashNotFound)
v, err := dht.getLinks(base, "tag foo", StatusLive)
So(v, ShouldBeNil)
So(err, ShouldEqual, ErrHashNotFound)
})
var id peer.ID
err = dht.put(h.node.NewMessage(PUT_REQUEST, PutReq{H: base}), "someType", base, id, []byte("some value"), StatusLive)
if err != nil {
panic(err)
}
// the message doesn't actually matter for this test because it only gets used later in gossiping
fakeMsg := h.node.NewMessage(LINK_REQUEST, LinkReq{Base: linkHash1, Links: linkingEntryHash})
Convey("Low level should add linking events to buntdb", t, func() {
err := dht.link(fakeMsg, baseStr, linkHash1Str, "link test", StatusLive)
So(err, ShouldBeNil)
err = dht.db.View(func(tx *buntdb.Tx) error {
err = tx.Ascend("link", func(key, value string) bool {
So(key, ShouldEqual, fmt.Sprintf(`link:%s:%s:link test`, baseStr, linkHash1Str))
So(value, ShouldEqual, fmt.Sprintf(`[{"Status":%d,"Source":"%s","LinksEntry":"%s"}]`, StatusLive, h.nodeIDStr, linkingEntryHashStr))
return true
})
return nil
})
err = dht.link(fakeMsg, baseStr, linkHash1Str, "link test", StatusDeleted)
So(err, ShouldBeNil)
err = dht.db.View(func(tx *buntdb.Tx) error {
err = tx.Ascend("link", func(key, value string) bool {
So(value, ShouldEqual, fmt.Sprintf(`[{"Status":%d,"Source":"%s","LinksEntry":"%s"},{"Status":%d,"Source":"%s","LinksEntry":"%s"}]`, StatusLive, h.nodeIDStr, linkingEntryHashStr, StatusDeleted, h.nodeIDStr, linkingEntryHashStr))
return true
})
return nil
})
})
Convey("It should store and retrieve links values on a base", t, func() {
data, err := dht.getLinks(base, "tag foo", StatusLive)
So(err, ShouldBeNil)
So(len(data), ShouldEqual, 0)
err = dht.putLink(fakeMsg, baseStr, linkHash1Str, "tag foo")
So(err, ShouldBeNil)
err = dht.putLink(fakeMsg, baseStr, linkHash2Str, "tag foo")
So(err, ShouldBeNil)
err = dht.putLink(fakeMsg, baseStr, linkHash1Str, "tag bar")
So(err, ShouldBeNil)
data, err = dht.getLinks(base, "tag foo", StatusLive)
So(err, ShouldBeNil)
So(len(data), ShouldEqual, 2)
m := data[0]
So(m.H, ShouldEqual, linkHash1Str)
m = data[1]
So(m.H, ShouldEqual, linkHash2Str)
data, err = dht.getLinks(base, "tag bar", StatusLive)
So(err, ShouldBeNil)
So(len(data), ShouldEqual, 1)
So(data[0].H, ShouldEqual, linkHash1Str)
})
Convey("It should store and retrieve a links source", t, func() {
err = dht.putLink(fakeMsg, baseStr, linkHash1Str, "tag source")
So(err, ShouldBeNil)
data, err := dht.getLinks(base, "tag source", StatusLive)
So(err, ShouldBeNil)
So(len(data), ShouldEqual, 1)
data, err = dht.getLinks(base, "tag source", StatusLive)
So(err, ShouldBeNil)
So(len(data), ShouldEqual, 1)
So(data[0].Source, ShouldEqual, h.nodeIDStr)
})
Convey("It should work to put a link a second time", t, func() {
err = dht.putLink(fakeMsg, baseStr, linkHash1Str, "tag foo")
So(err, ShouldBeNil)
})
Convey("It should fail delete links non existent links bases and tags", t, func() {
badHashStr := "QmY8Mzg9F69e5P9AoQPYat655HEhc1TVGs11tmfNSzkqhX"
err := dht.delLink(fakeMsg, badHashStr, linkHash1Str, "tag foo")
So(err, ShouldEqual, ErrHashNotFound)
err = dht.delLink(fakeMsg, baseStr, badHashStr, "tag foo")
So(err, ShouldEqual, ErrLinkNotFound)
err = dht.delLink(fakeMsg, baseStr, linkHash1Str, "tag baz")
So(err, ShouldEqual, ErrLinkNotFound)
})
Convey("It should delete links", t, func() {
err := dht.delLink(fakeMsg, baseStr, linkHash1Str, "tag bar")
So(err, ShouldBeNil)
data, err := dht.getLinks(base, "tag bar", StatusLive)
So(err, ShouldBeNil)
So(len(data), ShouldEqual, 0)
err = dht.delLink(fakeMsg, baseStr, linkHash1Str, "tag foo")
So(err, ShouldBeNil)
data, err = dht.getLinks(base, "tag foo", StatusLive)
So(err, ShouldBeNil)
So(len(data), ShouldEqual, 1)
err = dht.delLink(fakeMsg, baseStr, linkHash2Str, "tag foo")
So(err, ShouldBeNil)
data, err = dht.getLinks(base, "tag foo", StatusLive)
So(err, ShouldBeNil)
So(len(data), ShouldEqual, 0)
})
}
func TestDHTSend(t *testing.T) {
d, _, h := PrepareTestChain("test")
defer CleanupTestChain(h, d)
hash, _ := NewHash("QmY8Mzg9F69e5P9AoQPYat655HEhc1TVGs11tmfNSzkqh2")
Convey("send GET_REQUEST message for non existent hash should get error", t, func() {
msg := h.node.NewMessage(GET_REQUEST, GetReq{H: hash, StatusMask: StatusLive})
_, err := h.dht.send(nil, h.node.HashAddr, msg)
So(err, ShouldEqual, ErrHashNotFound)
})
now := time.Unix(1, 1) // pick a constant time so the test will always work
e := GobEntry{C: "4"}
_, hd, err := h.NewEntry(now, "evenNumbers", &e)
if err != nil {
panic(err)
}
// publish the entry data to the dht
hash = hd.EntryLink
Convey("after a handled PUT_REQUEST data should be stored in DHT", t, func() {
msg := h.node.NewMessage(PUT_REQUEST, PutReq{H: hash})
r, err := h.dht.send(nil, h.node.HashAddr, msg)
So(err, ShouldBeNil)
So(r, ShouldEqual, DHTChangeOK)
hd, _ := h.chain.GetEntryHeader(hash)
So(hd.EntryLink.Equal(&hash), ShouldBeTrue)
})
Convey("send GET_REQUEST message should return content", t, func() {
msg := h.node.NewMessage(GET_REQUEST, GetReq{H: hash, StatusMask: StatusLive})
r, err := h.dht.send(nil, h.node.HashAddr, msg)
So(err, ShouldBeNil)
resp := r.(GetResp)
So(fmt.Sprintf("%v", resp.Entry), ShouldEqual, fmt.Sprintf("%v", e))
})
Convey("send GET_REQUEST message should return content of sys types", t, func() {
msg := h.node.NewMessage(GET_REQUEST, GetReq{H: h.agentHash, StatusMask: StatusLive})
r, err := h.dht.send(nil, h.nodeID, msg)
So(err, ShouldBeNil)
resp := r.(GetResp)
ae, _ := h.agent.AgentEntry(nil)
a, _ := ae.ToJSON()
So(resp.Entry.Content().(string), ShouldEqual, a)
msg = h.node.NewMessage(GET_REQUEST, GetReq{H: HashFromPeerID(h.nodeID), StatusMask: StatusLive})
r, err = h.dht.send(nil, h.nodeID, msg)
So(err, ShouldBeNil)
resp = r.(GetResp)
So(resp.Entry.Content().(string), ShouldEqual, ae.PublicKey)
// for now this is an error because we presume everyone has the DNA.
// once we implement dna changes, this needs to be changed
msg = h.node.NewMessage(GET_REQUEST, GetReq{H: h.dnaHash, StatusMask: StatusLive})
r, err = h.dht.send(nil, h.nodeID, msg)
So(err, ShouldBeError)
})
}
func TestDHTQueryGet(t *testing.T) {
nodesCount := 6
mt := setupMultiNodeTesting(nodesCount)
defer mt.cleanupMultiNodeTesting()
h := mt.nodes[0]
now := time.Unix(1, 1) // pick a constant time so the test will always work
e := GobEntry{C: "4"}
_, hd, err := h.NewEntry(now, "evenNumbers", &e)
if err != nil {
panic(err)
}
/*for i := 0; i < nodesCount; i++ {
fmt.Printf("node%d:%v\n", i, mt.nodes[i].node.HashAddr.Pretty()[2:6])
}*/
// publish the entry data to local DHT node (0)
hash := hd.EntryLink
msg := h.node.NewMessage(PUT_REQUEST, PutReq{H: hash})
_, err = h.dht.send(nil, h.node.HashAddr, msg)
if err != nil {
panic(err)
}
ringConnect(t, mt.ctx, mt.nodes, nodesCount)
// pick a distant node that has to do some of the recursive lookups to get back to node 0.
Convey("Kademlia GET_REQUEST should return content", t, func() {
h2 := mt.nodes[nodesCount-2]
r, err := h2.dht.Query(hash, GET_REQUEST, GetReq{H: hash, StatusMask: StatusLive})
So(err, ShouldBeNil)
resp := r.(GetResp)
So(fmt.Sprintf("%v", resp.Entry), ShouldEqual, fmt.Sprintf("%v", e))
})
}
func TestDHTKadPut(t *testing.T) {
nodesCount := 6
mt := setupMultiNodeTesting(nodesCount)
defer mt.cleanupMultiNodeTesting()
h := mt.nodes[0]
now := time.Unix(1, 1) // pick a constant time so the test will always work
e := GobEntry{C: "4"}
_, hd, err := h.NewEntry(now, "evenNumbers", &e)
if err != nil {
panic(err)
}
hash := hd.EntryLink
/*
for i := 0; i < nodesCount; i++ {
fmt.Printf("node%d:%v\n", i, mt.nodes[i].node.HashAddr.Pretty()[2:6])
}
//node0:NnRV
//node1:UfY4
//node2:YA62
//node3:S4BF
//node4:W4He
//node5:dxxu
starConnect(t, mt.ctx, mt.nodes, nodesCount)
// get closest peers in the routing table
rtp := h.node.routingTable.NearestPeers(hash, AlphaValue)
fmt.Printf("CLOSE:%v\n", rtp)
//[<peer.ID S4BFeT> <peer.ID W4HeEG> <peer.ID UfY4We>]
//i.e 3,4,1
*/
ringConnect(t, mt.ctx, mt.nodes, nodesCount)
Convey("Kademlia PUT_REQUEST should put the hash to its closet node even if we don't know about it yet", t, func() {
rtp := h.node.routingTable.NearestPeers(hash, AlphaValue)
// check that our routing table doesn't contain closest node yet
So(fmt.Sprintf("%v", rtp), ShouldEqual, "[<peer.ID UfY4We> <peer.ID dxxuES>]")
err := h.dht.Change(hash, PUT_REQUEST, PutReq{H: hash})
So(err, ShouldBeNil)
rtp = h.node.routingTable.NearestPeers(hash, AlphaValue)
// routing table should be updated
So(fmt.Sprintf("%v", rtp), ShouldEqual, "[<peer.ID S4BFeT> <peer.ID W4HeEG> <peer.ID UfY4We>]")
// and get from node should get the value
msg := h.node.NewMessage(GET_REQUEST, GetReq{H: hash, StatusMask: StatusLive})
r, err := h.dht.send(nil, mt.nodes[3].nodeID, msg)
So(err, ShouldBeNil)
resp := r.(GetResp)
So(fmt.Sprintf("%v", resp.Entry), ShouldEqual, fmt.Sprintf("%v", e))
})
}
func TestActionReceiver(t *testing.T) {
d, _, h := PrepareTestChain("test")
defer CleanupTestChain(h, d)
Convey("PUT_REQUEST should fail if body isn't a hash", t, func() {
m := h.node.NewMessage(PUT_REQUEST, "foo")
_, err := ActionReceiver(h, m)
So(err.Error(), ShouldEqual, "Unexpected request body type 'string' in put request, expecting holochain.PutReq")
})
Convey("LINK_REQUEST should fail if body not a good linking request", t, func() {
m := h.node.NewMessage(LINK_REQUEST, "foo")
_, err := ActionReceiver(h, m)
So(err.Error(), ShouldEqual, "Unexpected request body type 'string' in link request, expecting holochain.LinkReq")
})
now := time.Unix(1, 1) // pick a constant time so the test will always work
e := GobEntry{C: "124"}
_, hd, _ := h.NewEntry(now, "evenNumbers", &e)
hash := hd.EntryLink
Convey("PUT_REQUEST should queue a valid message", t, func() {
m := h.node.NewMessage(PUT_REQUEST, PutReq{H: hash})
r, err := ActionReceiver(h, m)
So(err, ShouldBeNil)
So(r, ShouldEqual, DHTChangeOK)
})
Convey("GET_REQUEST should return the requested values", t, func() {
m := h.node.NewMessage(GET_REQUEST, GetReq{H: hash, StatusMask: StatusLive})
r, err := ActionReceiver(h, m)
So(err, ShouldBeNil)
resp := r.(GetResp)
So(fmt.Sprintf("%v", resp.Entry), ShouldEqual, fmt.Sprintf("%v", e))
m = h.node.NewMessage(GET_REQUEST, GetReq{H: hash, GetMask: GetMaskEntryType})
r, err = ActionReceiver(h, m)
So(err, ShouldBeNil)
resp = r.(GetResp)
So(resp.Entry.C, ShouldEqual, nil)
So(resp.EntryType, ShouldEqual, "evenNumbers")
m = h.node.NewMessage(GET_REQUEST, GetReq{H: hash, GetMask: GetMaskEntry + GetMaskEntryType})
r, err = ActionReceiver(h, m)
So(err, ShouldBeNil)
resp = r.(GetResp)
So(fmt.Sprintf("%v", resp.Entry), ShouldEqual, fmt.Sprintf("%v", e))
So(resp.EntryType, ShouldEqual, "evenNumbers")
m = h.node.NewMessage(GET_REQUEST, GetReq{H: hash, GetMask: GetMaskSources})
r, err = ActionReceiver(h, m)
So(err, ShouldBeNil)
resp = r.(GetResp)
So(resp.Entry.C, ShouldEqual, nil)
So(fmt.Sprintf("%v", resp.Sources), ShouldEqual, fmt.Sprintf("[%v]", h.nodeIDStr))
So(resp.EntryType, ShouldEqual, "evenNumbers") // you allways get the entry type even if not in getmask at this level (ActionReceiver) because we have to be able to look up the definition to interpret the contents
m = h.node.NewMessage(GET_REQUEST, GetReq{H: hash, GetMask: GetMaskEntry + GetMaskSources})
r, err = ActionReceiver(h, m)
So(err, ShouldBeNil)
resp = r.(GetResp)
So(fmt.Sprintf("%v", resp.Entry), ShouldEqual, fmt.Sprintf("%v", e))
So(fmt.Sprintf("%v", resp.Sources), ShouldEqual, fmt.Sprintf("[%v]", h.nodeIDStr))
So(resp.EntryType, ShouldEqual, "evenNumbers") // you allways get the entry type even if not in getmask at this level (ActionReceiver) because we have to be able to look up the definition to interpret the contents
})
someData := `{"firstName":"Zippy","lastName":"Pinhead"}`
e = GobEntry{C: someData}
_, hd, _ = h.NewEntry(now, "profile", &e)
profileHash := hd.EntryLink
le := GobEntry{C: fmt.Sprintf(`{"Links":[{"Base":"%s","Link":"%s","Tag":"4stars"},{"Base":"%s","Link":"%s","Tag":"3stars"}]}`, hash.String(), profileHash.String(), hash.String(), h.agentHash)}
_, lhd, _ := h.NewEntry(time.Now(), "rating", &le)
Convey("LINK_REQUEST should store links", t, func() {
lr := LinkReq{Base: hash, Links: lhd.EntryLink}
m := h.node.NewMessage(LINK_REQUEST, lr)
r, err := ActionReceiver(h, m)
So(err, ShouldBeNil)
So(r, ShouldEqual, DHTChangeOK)
// check that it got put
meta, err := h.dht.getLinks(hash, "4stars", StatusLive)
So(err, ShouldBeNil)
So(meta[0].H, ShouldEqual, hd.EntryLink.String())
})
e2 := GobEntry{C: "322"}
hash2, _ := e2.Sum(h.hashSpec)
e3 := GobEntry{C: "324"}
hash3, _ := e3.Sum(h.hashSpec)
Convey("LINK_REQUEST of unknown hash should get queued for retry", t, func() {
lr := LinkReq{Base: hash2, Links: hash3}
m := h.node.NewMessage(LINK_REQUEST, lr)
r, err := ActionReceiver(h, m)
So(err, ShouldBeNil)
So(r, ShouldEqual, DHTChangeUnknownHashQueuedForRetry)
So(len(h.dht.retryQueue), ShouldEqual, 1)
<-h.dht.retryQueue // unload the queue
})
Convey("GETLINK_REQUEST should retrieve link values", t, func() {
mq := LinkQuery{Base: hash, T: "4stars"}
m := h.node.NewMessage(GETLINK_REQUEST, mq)
r, err := ActionReceiver(h, m)
So(err, ShouldBeNil)
results := r.(*LinkQueryResp)
So(results.Links[0].H, ShouldEqual, hd.EntryLink.String())
So(results.Links[0].T, ShouldEqual, "")
})
Convey("GETLINK_REQUEST with empty tag should retrieve all linked values", t, func() {
mq := LinkQuery{Base: hash, T: ""}
m := h.node.NewMessage(GETLINK_REQUEST, mq)
r, err := ActionReceiver(h, m)
So(err, ShouldBeNil)
results := r.(*LinkQueryResp)
var l4star, l3star TaggedHash
// could come back in any order...
if results.Links[0].T == "4stars" {
l4star = results.Links[0]
l3star = results.Links[1]
} else {
l4star = results.Links[1]
l3star = results.Links[0]
}
So(l3star.H, ShouldEqual, h.agentHash.String())
So(l3star.T, ShouldEqual, "3stars")
So(l4star.H, ShouldEqual, hd.EntryLink.String())
So(l4star.T, ShouldEqual, "4stars")
})
Convey("GOSSIP_REQUEST should request and advertise data by idx", t, func() {
g := GossipReq{MyIdx: 1, YourIdx: 2}
m := h.node.NewMessage(GOSSIP_REQUEST, g)
r, err := GossipReceiver(h, m)
So(err, ShouldBeNil)
gr := r.(Gossip)
So(len(gr.Puts), ShouldEqual, 4)
})
le2 := GobEntry{C: fmt.Sprintf(`{"Links":[{"Base":"%s","Link":"%s","Tag":"4stars","LinkAction":"%s"}]}`, hash.String(), profileHash.String(), DelAction)}
_, lhd2, _ := h.NewEntry(time.Now(), "rating", &le2)
Convey("LINK_REQUEST with del type should mark a link as deleted", t, func() {
lr := LinkReq{Base: hash, Links: lhd2.EntryLink}
m := h.node.NewMessage(LINK_REQUEST, lr)
r, err := ActionReceiver(h, m)
So(r, ShouldEqual, DHTChangeOK)
results, err := h.dht.getLinks(hash, "4stars", StatusLive)
So(err, ShouldBeNil)
So(len(results), ShouldEqual, 0)
results, err = h.dht.getLinks(hash, "4stars", StatusDeleted)
So(err, ShouldBeNil)
So(len(results), ShouldEqual, 1)
})
Convey("GETLINK_REQUEST with mask option should retrieve deleted link values", t, func() {
mq := LinkQuery{Base: hash, T: "4stars", StatusMask: StatusDeleted}
m := h.node.NewMessage(GETLINK_REQUEST, mq)
r, err := ActionReceiver(h, m)
So(err, ShouldBeNil)
results := r.(*LinkQueryResp)
So(results.Links[0].H, ShouldEqual, hd.EntryLink.String())
})
Convey("MOD_REQUEST of unknown hash should get queued for retry", t, func() {
req := ModReq{H: hash2, N: hash3}
m := h.node.NewMessage(MOD_REQUEST, req)
r, err := ActionReceiver(h, m)
So(err, ShouldBeNil)
So(r, ShouldEqual, DHTChangeUnknownHashQueuedForRetry)
So(len(h.dht.retryQueue), ShouldEqual, 1)
<-h.dht.retryQueue // unload the queue
})
// put a second entry to DHT
h.NewEntry(now, "evenNumbers", &e2)
m2 := h.node.NewMessage(PUT_REQUEST, PutReq{H: hash2})
ActionReceiver(h, m2)
Convey("MOD_REQUEST should set hash to modified", t, func() {
req := ModReq{H: hash, N: hash2}
m := h.node.NewMessage(MOD_REQUEST, req)
r, err := ActionReceiver(h, m)
So(err, ShouldBeNil)
So(r, ShouldEqual, DHTChangeOK)
})
Convey("DELETE_REQUEST should set status of hash to deleted", t, func() {
entry := DelEntry{Hash: hash2, Message: "expired"}
a := NewDelAction("evenNumbers", entry)
_, err := h.doCommit(a, &StatusChange{Action: DelAction, Hash: hash2})
entryHash := a.header.EntryLink
m := h.node.NewMessage(DEL_REQUEST, DelReq{H: hash2, By: entryHash})
r, err := ActionReceiver(h, m)
So(err, ShouldBeNil)
So(r, ShouldEqual, DHTChangeOK)
data, entryType, _, status, _ := h.dht.get(hash2, StatusAny, GetMaskAll)
var e GobEntry
e.Unmarshal(data)
So(e.C, ShouldEqual, "322")
So(entryType, ShouldEqual, "evenNumbers")
So(status, ShouldEqual, StatusDeleted)
})
Convey("DELETE_REQUEST of unknown hash should get queued for retry", t, func() {
req := DelReq{H: hash3, By: hash3}
m := h.node.NewMessage(DEL_REQUEST, req)
r, err := ActionReceiver(h, m)
So(err, ShouldBeNil)
So(r, ShouldEqual, DHTChangeUnknownHashQueuedForRetry)
So(len(h.dht.retryQueue), ShouldEqual, 1)
})
Convey("LISTADD_REQUEST with bad warrant should return error", t, func() {
pid, _ := makePeer("testPeer")
m := h.node.NewMessage(LISTADD_REQUEST,
ListAddReq{
ListType: BlockedList,
Peers: []string{peer.IDB58Encode(pid)},
WarrantType: SelfRevocationType,
Warrant: []byte("bad warrant!"),
})
_, err := ActionReceiver(h, m)
So(err.Error(), ShouldEqual, "List add request rejected on warrant failure: unable to decode warrant (invalid character 'b' looking for beginning of value)")
})
Convey("LISTADD_REQUEST with warrant out of context should return error", t, func() {
pid, oldPrivKey := makePeer("testPeer")
_, newPrivKey := makePeer("peer1")
revocation, _ := NewSelfRevocation(oldPrivKey, newPrivKey, []byte("extra data"))
w, _ := NewSelfRevocationWarrant(revocation)
data, _ := w.Encode()
m := h.node.NewMessage(LISTADD_REQUEST,
ListAddReq{
ListType: BlockedList,
Peers: []string{peer.IDB58Encode(pid)},
WarrantType: SelfRevocationType,
Warrant: data,
})
_, err := ActionReceiver(h, m)
So(err.Error(), ShouldEqual, "List add request rejected on warrant failure: expected old key to be modified on DHT")
})
/*
getting a good warrant without also having already had the addToList happen is hard,
so not quite sure how to test this
Convey("LISTADD_REQUEST with good warrant should add to list", t, func() {
pid, oldPrivKey := makePeer("testPeer")
_, newPrivKey := makePeer("peer1")
revocation, _ := NewSelfRevocation(oldPrivKey, newPrivKey, []byte("extra data"))
w, _ := NewSelfRevocationWarrant(revocation)
data, _ := w.Encode()
m := h.node.NewMessage(LISTADD_REQUEST,
ListAddReq{
ListType: BlockedList,
Peers: []string{peer.IDB58Encode(pid)},
WarrantType: SelfRevocationType,
Warrant: data,
})
r, err := ActionReceiver(h, m)
So(err, ShouldBeNil)
So(r, ShouldEqual, DHTChangeOK)
peerList, err := h.dht.getList(BlockedList)
So(err, ShouldBeNil)
So(len(peerList.Records), ShouldEqual, 1)
So(peerList.Records[0].ID, ShouldEqual, pid)
})
*/
}
func TestDHTDump(t *testing.T) {
d, _, h := PrepareTestChain("test")
defer CleanupTestChain(h, d)
Convey("dht dump of index 1 should show the agent put", t, func() {
msg, _ := h.dht.GetIdxMessage(1)
f, _ := msg.Fingerprint()
msgStr := msg.String()
str, err := h.dht.DumpIdx(1)
So(err, ShouldBeNil)
So(strings.Index(str, fmt.Sprintf("MSG (fingerprint %v)", f)) >= 0, ShouldBeTrue)
So(strings.Index(str, msgStr) >= 0, ShouldBeTrue)
})
Convey("dht dump of index 99 should return err", t, func() {
_, err := h.dht.DumpIdx(99)
So(err.Error(), ShouldEqual, "no such change index")
})
reviewHash := commit(h, "review", "this is my bogus review of the user")
commit(h, "rating", fmt.Sprintf(`{"Links":[{"Base":"%s","Link":"%s","Tag":"4stars"}]}`, h.nodeIDStr, reviewHash.String()))
Convey("dht.String() should produce human readable DHT", t, func() {
dump := h.dht.String()
So(dump, ShouldContainSubstring, "DHT changes: 4")
d, _ := h.dht.DumpIdx(1)
So(dump, ShouldContainSubstring, d)
d, _ = h.dht.DumpIdx(2)
So(dump, ShouldContainSubstring, d)
So(dump, ShouldContainSubstring, "DHT entries:")
So(dump, ShouldContainSubstring, fmt.Sprintf("Hash--%s (status 1)", h.nodeIDStr))
pk, _ := h.agent.PubKey().Bytes()
So(dump, ShouldContainSubstring, fmt.Sprintf("Value: %s", string(b58.Encode(pk))))
So(dump, ShouldContainSubstring, fmt.Sprintf("Sources: %s", h.nodeIDStr))
So(dump, ShouldContainSubstring, fmt.Sprintf("Linked to: %s with tag %s", reviewHash, "4stars"))
})
Convey("dht.JSON() should output DHT formatted as JSON string", t, func() {
dump, err := h.dht.JSON()
So(err, ShouldBeNil)
d, _ := h.dht.DumpIdxJSON(1)
So(NormaliseJSON(dump), ShouldContainSubstring, NormaliseJSON(d))
d, _ = h.dht.DumpIdxJSON(2)
So(NormaliseJSON(dump), ShouldContainSubstring, NormaliseJSON(d))
json := NormaliseJSON(dump)
matched, err := regexp.MatchString(`{"dht_changes":\[.*\],"dht_entries":\[.*\]}`, json)
So(err, ShouldBeNil)
So(matched, ShouldBeTrue)
})
}
func TestDHTRetry(t *testing.T) {
d, _, h := PrepareTestChain("test")
defer CleanupTestChain(h, d)
d1 := `{"firstName":"Zippy","lastName":"Pinhead"}`
e := GobEntry{C: d1}
hash, _ := e.Sum(h.hashSpec)
d2 := `{"firstName":"Zerbina","lastName":"Pinhead"}`
e2 := GobEntry{C: d2}
hash2, _ := e2.Sum(h.hashSpec)
Convey("it should make a change after some retries", t, func() {
req := ModReq{H: hash, N: hash2}
m := h.node.NewMessage(MOD_REQUEST, req)
r, err := ActionReceiver(h, m)
So(err, ShouldBeNil)
So(r, ShouldEqual, DHTChangeUnknownHashQueuedForRetry)
// pause for a few retires
h.node.retrying = h.TaskTicker(time.Millisecond*10, RetryTask)
time.Sleep(time.Millisecond * 25)
// add the entries and get them into the DHT
h.NewEntry(time.Now(), "profile", &e)
h.NewEntry(time.Now(), "profile", &e2)
m = h.node.NewMessage(PUT_REQUEST, PutReq{H: hash})
err = h.dht.put(m, "profile", hash, h.nodeID, []byte(d1), StatusLive)
So(err, ShouldBeNil)
m = h.node.NewMessage(PUT_REQUEST, PutReq{H: hash2})
err = h.dht.put(m, "profile", hash2, h.nodeID, []byte(d2), StatusLive)
So(err, ShouldBeNil)
_, _, _, status, _ := h.dht.get(hash, StatusAny, GetMaskAll)
So(status, ShouldEqual, StatusLive)
// wait for next retry
time.Sleep(time.Millisecond * 40)
_, _, _, status, _ = h.dht.get(hash, StatusAny, GetMaskAll)
So(status, ShouldEqual, StatusModified)
// stop retrying for next test
stop := h.node.retrying
h.node.retrying = nil
stop <- true
})
Convey("retries should be limited", t, func() {
e3 := GobEntry{C: `{"firstName":"Zappy","lastName":"Pinhead"}`}
hash3, _ := e3.Sum(h.hashSpec)
e4 := GobEntry{C: `{"firstName":"Zuppy","lastName":"Pinhead"}`}
hash4, _ := e4.Sum(h.hashSpec)
req := ModReq{H: hash3, N: hash4}
m := h.node.NewMessage(MOD_REQUEST, req)
r, err := ActionReceiver(h, m)
So(err, ShouldBeNil)
So(r, ShouldEqual, DHTChangeUnknownHashQueuedForRetry)
So(len(h.dht.retryQueue), ShouldEqual, 1)
interval := time.Millisecond * 10
h.node.retrying = h.TaskTicker(interval, RetryTask)
time.Sleep(interval * (MaxRetries + 2))
So(len(h.dht.retryQueue), ShouldEqual, 0)
})
}
func TestDHTMultiNode(t *testing.T) {
nodesCount := 10
mt := setupMultiNodeTesting(nodesCount)
defer mt.cleanupMultiNodeTesting()
nodes := mt.nodes
ringConnectMutual(t, mt.ctx, mt.nodes, nodesCount)
var connections int
Convey("each node should be able to get the key of others", t, func() {
for i := 0; i < nodesCount; i++ {
h1 := nodes[i]
for j := 0; j < nodesCount; j++ {
h2 := nodes[j]
options := GetOptions{StatusMask: StatusDefault}
req := GetReq{H: HashFromPeerID(h1.nodeID), StatusMask: options.StatusMask, GetMask: options.GetMask}
response, err := NewGetAction(req, &options).Do(h2)
if err != nil {
fmt.Printf("FAIL : %v couldn't get from %v err: %err\n", h2.nodeID, h1.nodeID, err)
} else {
e := response.(GetResp).Entry
responseStr := fmt.Sprintf("%v", e.Content())
pk, _ := h1.agent.EncodePubKey()
expectedResponseStr := pk
if responseStr == expectedResponseStr {
connections += 1
//fmt.Printf("SUCCESS: %v got from %v\n", h2.nodeID, h1.nodeID)
} else {
//fmt.Printf("Expected:%s\n", expectedResponseStr)
//fmt.Printf("Got :%s\n", responseStr)
}
}
}
}
So(connections, ShouldEqual, nodesCount*nodesCount)
})
hashes := []Hash{}
// add a bunch of data and links to that data on the key
for i := 0; i < nodesCount; i++ {
h := nodes[i]
hash := commit(h, "review", fmt.Sprintf("this statement by node %d (%v)", i, h.nodeID))
commit(h, "rating", fmt.Sprintf(`{"Links":[{"Base":"%s","Link":"%s","Tag":"statement"}]}`, h.nodeIDStr, hash.String()))
hashes = append(hashes, hash)
}
Convey("each node should be able to get statements form the other nodes including self", t, func() {
for i := 0; i < nodesCount; i++ {
h1 := nodes[i]
for j := 0; j < nodesCount; j++ {
h2 := nodes[j]
options := GetLinksOptions{Load: true, StatusMask: StatusLive}
response, err := NewGetLinksAction(
&LinkQuery{
Base: HashFromPeerID(h1.nodeID),
T: "statement",
StatusMask: options.StatusMask,
}, &options).Do(h2)
So(err, ShouldBeNil)
So(fmt.Sprintf("%v", response), ShouldEqual, fmt.Sprintf("&{[{%v this statement by node %d (%v) review %s}]}", hashes[i], i, h1.nodeID, h1.nodeID.Pretty()))
}
}
})
}