aboutsummaryrefslogtreecommitdiffstats
path: root/swarm/pss/pss_test.go
blob: 6ba04cb5d18ac2fd31f8210169831e75c66575bc (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
// Copyright 2018 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package pss

import (
    "bytes"
    "context"
    "crypto/ecdsa"
    "encoding/binary"
    "encoding/hex"
    "encoding/json"
    "flag"
    "fmt"
    "io/ioutil"
    "math/rand"
    "os"
    "strconv"
    "strings"
    "sync"
    "testing"
    "time"

    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/common/hexutil"
    "github.com/ethereum/go-ethereum/crypto"
    "github.com/ethereum/go-ethereum/log"
    "github.com/ethereum/go-ethereum/metrics"
    "github.com/ethereum/go-ethereum/metrics/influxdb"
    "github.com/ethereum/go-ethereum/node"
    "github.com/ethereum/go-ethereum/p2p"
    "github.com/ethereum/go-ethereum/p2p/discover"
    "github.com/ethereum/go-ethereum/p2p/protocols"
    "github.com/ethereum/go-ethereum/p2p/simulations"
    "github.com/ethereum/go-ethereum/p2p/simulations/adapters"
    "github.com/ethereum/go-ethereum/rpc"
    "github.com/ethereum/go-ethereum/swarm/network"
    "github.com/ethereum/go-ethereum/swarm/state"
    whisper "github.com/ethereum/go-ethereum/whisper/whisperv5"
)

var (
    initOnce       = sync.Once{}
    debugdebugflag = flag.Bool("vv", false, "veryverbose")
    debugflag      = flag.Bool("v", false, "verbose")
    longrunning    = flag.Bool("longrunning", false, "do run long-running tests")
    w              *whisper.Whisper
    wapi           *whisper.PublicWhisperAPI
    psslogmain     log.Logger
    pssprotocols   map[string]*protoCtrl
    useHandshake   bool
)

func init() {
    flag.Parse()
    rand.Seed(time.Now().Unix())

    adapters.RegisterServices(newServices(false))
    initTest()
}

func initTest() {
    initOnce.Do(
        func() {
            loglevel := log.LvlInfo
            if *debugflag {
                loglevel = log.LvlDebug
            } else if *debugdebugflag {
                loglevel = log.LvlTrace
            }

            psslogmain = log.New("psslog", "*")
            hs := log.StreamHandler(os.Stderr, log.TerminalFormat(true))
            hf := log.LvlFilterHandler(loglevel, hs)
            h := log.CallerFileHandler(hf)
            log.Root().SetHandler(h)

            w = whisper.New(&whisper.DefaultConfig)
            wapi = whisper.NewPublicWhisperAPI(w)

            pssprotocols = make(map[string]*protoCtrl)
        },
    )
}

// test that topic conversion functions give predictable results
func TestTopic(t *testing.T) {

    api := &API{}

    topicstr := strings.Join([]string{PingProtocol.Name, strconv.Itoa(int(PingProtocol.Version))}, ":")

    // bytestotopic is the authoritative topic conversion source
    topicobj := BytesToTopic([]byte(topicstr))

    // string to topic and bytes to topic must match
    topicapiobj, _ := api.StringToTopic(topicstr)
    if topicobj != topicapiobj {
        t.Fatalf("bytes and string topic conversion mismatch; %s != %s", topicobj, topicapiobj)
    }

    // string representation of topichex
    topichex := topicobj.String()

    // protocoltopic wrapper on pingtopic should be same as topicstring
    // check that it matches
    pingtopichex := PingTopic.String()
    if topichex != pingtopichex {
        t.Fatalf("protocol topic conversion mismatch; %s != %s", topichex, pingtopichex)
    }

    // json marshal of topic
    topicjsonout, err := topicobj.MarshalJSON()
    if err != nil {
        t.Fatal(err)
    }
    if string(topicjsonout)[1:len(topicjsonout)-1] != topichex {
        t.Fatalf("topic json marshal mismatch; %s != \"%s\"", topicjsonout, topichex)
    }

    // json unmarshal of topic
    var topicjsonin Topic
    topicjsonin.UnmarshalJSON(topicjsonout)
    if topicjsonin != topicobj {
        t.Fatalf("topic json unmarshal mismatch: %x != %x", topicjsonin, topicobj)
    }
}

// test bit packing of message control flags
func TestMsgParams(t *testing.T) {
    var ctrl byte
    ctrl |= pssControlRaw
    p := newMsgParamsFromBytes([]byte{ctrl})
    m := newPssMsg(p)
    if !m.isRaw() || m.isSym() {
        t.Fatal("expected raw=true and sym=false")
    }
    ctrl |= pssControlSym
    p = newMsgParamsFromBytes([]byte{ctrl})
    m = newPssMsg(p)
    if !m.isRaw() || !m.isSym() {
        t.Fatal("expected raw=true and sym=true")
    }
    ctrl &= 0xff &^ pssControlRaw
    p = newMsgParamsFromBytes([]byte{ctrl})
    m = newPssMsg(p)
    if m.isRaw() || !m.isSym() {
        t.Fatal("expected raw=false and sym=true")
    }
}

// test if we can insert into cache, match items with cache and cache expiry
func TestCache(t *testing.T) {
    var err error
    to, _ := hex.DecodeString("08090a0b0c0d0e0f1011121314150001020304050607161718191a1b1c1d1e1f")
    ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    defer cancel()
    keys, err := wapi.NewKeyPair(ctx)
    privkey, err := w.GetPrivateKey(keys)
    if err != nil {
        t.Fatal(err)
    }
    ps := newTestPss(privkey, nil, nil)
    pp := NewPssParams().WithPrivateKey(privkey)
    data := []byte("foo")
    datatwo := []byte("bar")
    datathree := []byte("baz")
    wparams := &whisper.MessageParams{
        TTL:      defaultWhisperTTL,
        Src:      privkey,
        Dst:      &privkey.PublicKey,
        Topic:    whisper.TopicType(PingTopic),
        WorkTime: defaultWhisperWorkTime,
        PoW:      defaultWhisperPoW,
        Payload:  data,
    }
    woutmsg, err := whisper.NewSentMessage(wparams)
    env, err := woutmsg.Wrap(wparams)
    msg := &PssMsg{
        Payload: env,
        To:      to,
    }
    wparams.Payload = datatwo
    woutmsg, err = whisper.NewSentMessage(wparams)
    envtwo, err := woutmsg.Wrap(wparams)
    msgtwo := &PssMsg{
        Payload: envtwo,
        To:      to,
    }
    wparams.Payload = datathree
    woutmsg, err = whisper.NewSentMessage(wparams)
    envthree, err := woutmsg.Wrap(wparams)
    msgthree := &PssMsg{
        Payload: envthree,
        To:      to,
    }

    digest := ps.digest(msg)
    if err != nil {
        t.Fatalf("could not store cache msgone: %v", err)
    }
    digesttwo := ps.digest(msgtwo)
    if err != nil {
        t.Fatalf("could not store cache msgtwo: %v", err)
    }
    digestthree := ps.digest(msgthree)
    if err != nil {
        t.Fatalf("could not store cache msgthree: %v", err)
    }

    if digest == digesttwo {
        t.Fatalf("different msgs return same hash: %d", digesttwo)
    }

    // check the cache
    err = ps.addFwdCache(msg)
    if err != nil {
        t.Fatalf("write to pss expire cache failed: %v", err)
    }

    if !ps.checkFwdCache(msg) {
        t.Fatalf("message %v should have EXPIRE record in cache but checkCache returned false", msg)
    }

    if ps.checkFwdCache(msgtwo) {
        t.Fatalf("message %v should NOT have EXPIRE record in cache but checkCache returned true", msgtwo)
    }

    time.Sleep(pp.CacheTTL + 1*time.Second)
    err = ps.addFwdCache(msgthree)
    if err != nil {
        t.Fatalf("write to pss expire cache failed: %v", err)
    }

    if ps.checkFwdCache(msg) {
        t.Fatalf("message %v should have expired from cache but checkCache returned true", msg)
    }

    if _, ok := ps.fwdCache[digestthree]; !ok {
        t.Fatalf("unexpired message should be in the cache: %v", digestthree)
    }

    if _, ok := ps.fwdCache[digesttwo]; ok {
        t.Fatalf("expired message should have been cleared from the cache: %v", digesttwo)
    }
}

// matching of address hints; whether a message could be or is for the node
func TestAddressMatch(t *testing.T) {

    localaddr := network.RandomAddr().Over()
    copy(localaddr[:8], []byte("deadbeef"))
    remoteaddr := []byte("feedbeef")
    kadparams := network.NewKadParams()
    kad := network.NewKademlia(localaddr, kadparams)
    ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    defer cancel()
    keys, err := wapi.NewKeyPair(ctx)
    if err != nil {
        t.Fatalf("Could not generate private key: %v", err)
    }
    privkey, err := w.GetPrivateKey(keys)
    pssp := NewPssParams().WithPrivateKey(privkey)
    ps, err := NewPss(kad, pssp)
    if err != nil {
        t.Fatal(err.Error())
    }

    pssmsg := &PssMsg{
        To:      remoteaddr,
        Payload: &whisper.Envelope{},
    }

    // differ from first byte
    if ps.isSelfRecipient(pssmsg) {
        t.Fatalf("isSelfRecipient true but %x != %x", remoteaddr, localaddr)
    }
    if ps.isSelfPossibleRecipient(pssmsg) {
        t.Fatalf("isSelfPossibleRecipient true but %x != %x", remoteaddr[:8], localaddr[:8])
    }

    // 8 first bytes same
    copy(remoteaddr[:4], localaddr[:4])
    if ps.isSelfRecipient(pssmsg) {
        t.Fatalf("isSelfRecipient true but %x != %x", remoteaddr, localaddr)
    }
    if !ps.isSelfPossibleRecipient(pssmsg) {
        t.Fatalf("isSelfPossibleRecipient false but %x == %x", remoteaddr[:8], localaddr[:8])
    }

    // all bytes same
    pssmsg.To = localaddr
    if !ps.isSelfRecipient(pssmsg) {
        t.Fatalf("isSelfRecipient false but %x == %x", remoteaddr, localaddr)
    }
    if !ps.isSelfPossibleRecipient(pssmsg) {
        t.Fatalf("isSelfPossibleRecipient false but %x == %x", remoteaddr[:8], localaddr[:8])
    }
}

//
func TestHandlerConditions(t *testing.T) {

    t.Skip("Disabled due to probable faulty logic for outbox expectations")
    // setup
    privkey, err := crypto.GenerateKey()
    if err != nil {
        t.Fatal(err.Error())
    }

    addr := make([]byte, 32)
    addr[0] = 0x01
    ps := newTestPss(privkey, network.NewKademlia(addr, network.NewKadParams()), NewPssParams())

    // message should pass
    msg := &PssMsg{
        To:     addr,
        Expire: uint32(time.Now().Add(time.Second * 60).Unix()),
        Payload: &whisper.Envelope{
            Topic: [4]byte{},
            Data:  []byte{0x66, 0x6f, 0x6f},
        },
    }
    if err := ps.handlePssMsg(context.TODO(), msg); err != nil {
        t.Fatal(err.Error())
    }
    tmr := time.NewTimer(time.Millisecond * 100)
    var outmsg *PssMsg
    select {
    case outmsg = <-ps.outbox:
    case <-tmr.C:
    default:
    }
    if outmsg != nil {
        t.Fatalf("expected outbox empty after full address on msg, but had message %s", msg)
    }

    // message should pass and queue due to partial length
    msg.To = addr[0:1]
    msg.Payload.Data = []byte{0x78, 0x79, 0x80, 0x80, 0x79}
    if err := ps.handlePssMsg(context.TODO(), msg); err != nil {
        t.Fatal(err.Error())
    }
    tmr.Reset(time.Millisecond * 100)
    outmsg = nil
    select {
    case outmsg = <-ps.outbox:
    case <-tmr.C:
    }
    if outmsg == nil {
        t.Fatal("expected message in outbox on encrypt fail, but empty")
    }
    outmsg = nil
    select {
    case outmsg = <-ps.outbox:
    default:
    }
    if outmsg != nil {
        t.Fatalf("expected only one queued message but also had message %v", msg)
    }

    // full address mismatch should put message in queue
    msg.To[0] = 0xff
    if err := ps.handlePssMsg(context.TODO(), msg); err != nil {
        t.Fatal(err.Error())
    }
    tmr.Reset(time.Millisecond * 10)
    outmsg = nil
    select {
    case outmsg = <-ps.outbox:
    case <-tmr.C:
    }
    if outmsg == nil {
        t.Fatal("expected message in outbox on address mismatch, but empty")
    }
    outmsg = nil
    select {
    case outmsg = <-ps.outbox:
    default:
    }
    if outmsg != nil {
        t.Fatalf("expected only one queued message but also had message %v", msg)
    }

    // expired message should be dropped
    msg.Expire = uint32(time.Now().Add(-time.Second).Unix())
    if err := ps.handlePssMsg(context.TODO(), msg); err != nil {
        t.Fatal(err.Error())
    }
    tmr.Reset(time.Millisecond * 10)
    outmsg = nil
    select {
    case outmsg = <-ps.outbox:
    case <-tmr.C:
    default:
    }
    if outmsg != nil {
        t.Fatalf("expected empty queue but have message %v", msg)
    }

    // invalid message should return error
    fckedupmsg := &struct {
        pssMsg *PssMsg
    }{
        pssMsg: &PssMsg{},
    }
    if err := ps.handlePssMsg(context.TODO(), fckedupmsg); err == nil {
        t.Fatalf("expected error from processMsg but error nil")
    }

    // outbox full should return error
    msg.Expire = uint32(time.Now().Add(time.Second * 60).Unix())
    for i := 0; i < defaultOutboxCapacity; i++ {
        ps.outbox <- msg
    }
    msg.Payload.Data = []byte{0x62, 0x61, 0x72}
    err = ps.handlePssMsg(context.TODO(), msg)
    if err == nil {
        t.Fatal("expected error when mailbox full, but was nil")
    }
}

// set and generate pubkeys and symkeys
func TestKeys(t *testing.T) {
    // make our key and init pss with it
    ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    defer cancel()
    ourkeys, err := wapi.NewKeyPair(ctx)
    if err != nil {
        t.Fatalf("create 'our' key fail")
    }
    ctx, cancel2 := context.WithTimeout(context.Background(), time.Second)
    defer cancel2()
    theirkeys, err := wapi.NewKeyPair(ctx)
    if err != nil {
        t.Fatalf("create 'their' key fail")
    }
    ourprivkey, err := w.GetPrivateKey(ourkeys)
    if err != nil {
        t.Fatalf("failed to retrieve 'our' private key")
    }
    theirprivkey, err := w.GetPrivateKey(theirkeys)
    if err != nil {
        t.Fatalf("failed to retrieve 'their' private key")
    }
    ps := newTestPss(ourprivkey, nil, nil)

    // set up peer with mock address, mapped to mocked publicaddress and with mocked symkey
    addr := make(PssAddress, 32)
    copy(addr, network.RandomAddr().Over())
    outkey := network.RandomAddr().Over()
    topicobj := BytesToTopic([]byte("foo:42"))
    ps.SetPeerPublicKey(&theirprivkey.PublicKey, topicobj, &addr)
    outkeyid, err := ps.SetSymmetricKey(outkey, topicobj, &addr, false)
    if err != nil {
        t.Fatalf("failed to set 'our' outgoing symmetric key")
    }

    // make a symmetric key that we will send to peer for encrypting messages to us
    inkeyid, err := ps.GenerateSymmetricKey(topicobj, &addr, true)
    if err != nil {
        t.Fatalf("failed to set 'our' incoming symmetric key")
    }

    // get the key back from whisper, check that it's still the same
    outkeyback, err := ps.w.GetSymKey(outkeyid)
    if err != nil {
        t.Fatalf(err.Error())
    }
    inkey, err := ps.w.GetSymKey(inkeyid)
    if err != nil {
        t.Fatalf(err.Error())
    }
    if !bytes.Equal(outkeyback, outkey) {
        t.Fatalf("passed outgoing symkey doesnt equal stored: %x / %x", outkey, outkeyback)
    }

    t.Logf("symout: %v", outkeyback)
    t.Logf("symin: %v", inkey)

    // check that the key is stored in the peerpool
    psp := ps.symKeyPool[inkeyid][topicobj]
    if psp.address != &addr {
        t.Fatalf("inkey address does not match; %p != %p", psp.address, &addr)
    }
}

func TestGetPublickeyEntries(t *testing.T) {

    privkey, err := crypto.GenerateKey()
    if err != nil {
        t.Fatal(err)
    }
    ps := newTestPss(privkey, nil, nil)

    peeraddr := network.RandomAddr().Over()
    topicaddr := make(map[Topic]PssAddress)
    topicaddr[Topic{0x13}] = peeraddr
    topicaddr[Topic{0x2a}] = peeraddr[:16]
    topicaddr[Topic{0x02, 0x9a}] = []byte{}

    remoteprivkey, err := crypto.GenerateKey()
    if err != nil {
        t.Fatal(err)
    }
    remotepubkeybytes := crypto.FromECDSAPub(&remoteprivkey.PublicKey)
    remotepubkeyhex := common.ToHex(remotepubkeybytes)

    pssapi := NewAPI(ps)

    for to, a := range topicaddr {
        err = pssapi.SetPeerPublicKey(remotepubkeybytes, to, a)
        if err != nil {
            t.Fatal(err)
        }
    }

    intopic, err := pssapi.GetPeerTopics(remotepubkeyhex)
    if err != nil {
        t.Fatal(err)
    }

OUTER:
    for _, tnew := range intopic {
        for torig, addr := range topicaddr {
            if bytes.Equal(torig[:], tnew[:]) {
                inaddr, err := pssapi.GetPeerAddress(remotepubkeyhex, torig)
                if err != nil {
                    t.Fatal(err)
                }
                if !bytes.Equal(addr, inaddr) {
                    t.Fatalf("Address mismatch for topic %x; got %x, expected %x", torig, inaddr, addr)
                }
                delete(topicaddr, torig)
                continue OUTER
            }
        }
        t.Fatalf("received topic %x did not match any existing topics", tnew)
    }

    if len(topicaddr) != 0 {
        t.Fatalf("%d topics were not matched", len(topicaddr))
    }
}

// forwarding should skip peers that do not have matching pss capabilities
func TestMismatch(t *testing.T) {

    // create privkey for forwarder node
    privkey, err := crypto.GenerateKey()
    if err != nil {
        t.Fatal(err)
    }

    // initialize kad
    baseaddr := network.RandomAddr()
    kad := network.NewKademlia((baseaddr).Over(), network.NewKadParams())
    rw := &p2p.MsgPipeRW{}

    // one peer has a mismatching version of pss
    wrongpssaddr := network.RandomAddr()
    wrongpsscap := p2p.Cap{
        Name:    pssProtocolName,
        Version: 0,
    }
    nid, _ := discover.HexID("0x01")
    wrongpsspeer := network.NewPeer(&network.BzzPeer{
        Peer:    protocols.NewPeer(p2p.NewPeer(nid, common.ToHex(wrongpssaddr.Over()), []p2p.Cap{wrongpsscap}), rw, nil),
        BzzAddr: &network.BzzAddr{OAddr: wrongpssaddr.Over(), UAddr: nil},
    }, kad)

    // one peer doesn't even have pss (boo!)
    nopssaddr := network.RandomAddr()
    nopsscap := p2p.Cap{
        Name:    "nopss",
        Version: 1,
    }
    nid, _ = discover.HexID("0x02")
    nopsspeer := network.NewPeer(&network.BzzPeer{
        Peer:    protocols.NewPeer(p2p.NewPeer(nid, common.ToHex(nopssaddr.Over()), []p2p.Cap{nopsscap}), rw, nil),
        BzzAddr: &network.BzzAddr{OAddr: nopssaddr.Over(), UAddr: nil},
    }, kad)

    // add peers to kademlia and activate them
    // it's safe so don't check errors
    kad.Register(wrongpsspeer.BzzAddr)
    kad.On(wrongpsspeer)
    kad.Register(nopsspeer.BzzAddr)
    kad.On(nopsspeer)

    // create pss
    pssmsg := &PssMsg{
        To:      []byte{},
        Expire:  uint32(time.Now().Add(time.Second).Unix()),
        Payload: &whisper.Envelope{},
    }
    ps := newTestPss(privkey, kad, nil)

    // run the forward
    // it is enough that it completes; trying to send to incapable peers would create segfault
    ps.forward(pssmsg)

}

func TestSendRaw(t *testing.T) {
    t.Run("32", testSendRaw)
    t.Run("8", testSendRaw)
    t.Run("0", testSendRaw)
}

func testSendRaw(t *testing.T) {

    var addrsize int64
    var err error

    paramstring := strings.Split(t.Name(), "/")

    addrsize, _ = strconv.ParseInt(paramstring[1], 10, 0)
    log.Info("raw send test", "addrsize", addrsize)

    clients, err := setupNetwork(2, true)
    if err != nil {
        t.Fatal(err)
    }

    topic := "0xdeadbeef"

    var loaddrhex string
    err = clients[0].Call(&loaddrhex, "pss_baseAddr")
    if err != nil {
        t.Fatalf("rpc get node 1 baseaddr fail: %v", err)
    }
    loaddrhex = loaddrhex[:2+(addrsize*2)]
    var roaddrhex string
    err = clients[1].Call(&roaddrhex, "pss_baseAddr")
    if err != nil {
        t.Fatalf("rpc get node 2 baseaddr fail: %v", err)
    }
    roaddrhex = roaddrhex[:2+(addrsize*2)]

    time.Sleep(time.Millisecond * 500)

    // at this point we've verified that symkeys are saved and match on each peer
    // now try sending symmetrically encrypted message, both directions
    lmsgC := make(chan APIMsg)
    lctx, lcancel := context.WithTimeout(context.Background(), time.Second*10)
    defer lcancel()
    lsub, err := clients[0].Subscribe(lctx, "pss", lmsgC, "receive", topic)
    log.Trace("lsub", "id", lsub)
    defer lsub.Unsubscribe()
    rmsgC := make(chan APIMsg)
    rctx, rcancel := context.WithTimeout(context.Background(), time.Second*10)
    defer rcancel()
    rsub, err := clients[1].Subscribe(rctx, "pss", rmsgC, "receive", topic)
    log.Trace("rsub", "id", rsub)
    defer rsub.Unsubscribe()

    // send and verify delivery
    lmsg := []byte("plugh")
    err = clients[1].Call(nil, "pss_sendRaw", loaddrhex, topic, lmsg)
    if err != nil {
        t.Fatal(err)
    }
    select {
    case recvmsg := <-lmsgC:
        if !bytes.Equal(recvmsg.Msg, lmsg) {
            t.Fatalf("node 1 received payload mismatch: expected %v, got %v", lmsg, recvmsg)
        }
    case cerr := <-lctx.Done():
        t.Fatalf("test message (left) timed out: %v", cerr)
    }
    rmsg := []byte("xyzzy")
    err = clients[0].Call(nil, "pss_sendRaw", roaddrhex, topic, rmsg)
    if err != nil {
        t.Fatal(err)
    }
    select {
    case recvmsg := <-rmsgC:
        if !bytes.Equal(recvmsg.Msg, rmsg) {
            t.Fatalf("node 2 received payload mismatch: expected %x, got %v", rmsg, recvmsg.Msg)
        }
    case cerr := <-rctx.Done():
        t.Fatalf("test message (right) timed out: %v", cerr)
    }
}

// send symmetrically encrypted message between two directly connected peers
func TestSendSym(t *testing.T) {
    t.Run("32", testSendSym)
    t.Run("8", testSendSym)
    t.Run("0", testSendSym)
}

func testSendSym(t *testing.T) {

    // address hint size
    var addrsize int64
    var err error
    paramstring := strings.Split(t.Name(), "/")
    addrsize, _ = strconv.ParseInt(paramstring[1], 10, 0)
    log.Info("sym send test", "addrsize", addrsize)

    clients, err := setupNetwork(2, false)
    if err != nil {
        t.Fatal(err)
    }

    var topic string
    err = clients[0].Call(&topic, "pss_stringToTopic", "foo:42")
    if err != nil {
        t.Fatal(err)
    }

    var loaddrhex string
    err = clients[0].Call(&loaddrhex, "pss_baseAddr")
    if err != nil {
        t.Fatalf("rpc get node 1 baseaddr fail: %v", err)
    }
    loaddrhex = loaddrhex[:2+(addrsize*2)]
    var roaddrhex string
    err = clients[1].Call(&roaddrhex, "pss_baseAddr")
    if err != nil {
        t.Fatalf("rpc get node 2 baseaddr fail: %v", err)
    }
    roaddrhex = roaddrhex[:2+(addrsize*2)]

    // retrieve public key from pss instance
    // set this public key reciprocally
    var lpubkeyhex string
    err = clients[0].Call(&lpubkeyhex, "pss_getPublicKey")
    if err != nil {
        t.Fatalf("rpc get node 1 pubkey fail: %v", err)
    }
    var rpubkeyhex string
    err = clients[1].Call(&rpubkeyhex, "pss_getPublicKey")
    if err != nil {
        t.Fatalf("rpc get node 2 pubkey fail: %v", err)
    }

    time.Sleep(time.Millisecond * 500)

    // at this point we've verified that symkeys are saved and match on each peer
    // now try sending symmetrically encrypted message, both directions
    lmsgC := make(chan APIMsg)
    lctx, lcancel := context.WithTimeout(context.Background(), time.Second*10)
    defer lcancel()
    lsub, err := clients[0].Subscribe(lctx, "pss", lmsgC, "receive", topic)
    log.Trace("lsub", "id", lsub)
    defer lsub.Unsubscribe()
    rmsgC := make(chan APIMsg)
    rctx, rcancel := context.WithTimeout(context.Background(), time.Second*10)
    defer rcancel()
    rsub, err := clients[1].Subscribe(rctx, "pss", rmsgC, "receive", topic)
    log.Trace("rsub", "id", rsub)
    defer rsub.Unsubscribe()

    lrecvkey := network.RandomAddr().Over()
    rrecvkey := network.RandomAddr().Over()

    var lkeyids [2]string
    var rkeyids [2]string

    // manually set reciprocal symkeys
    err = clients[0].Call(&lkeyids, "psstest_setSymKeys", rpubkeyhex, lrecvkey, rrecvkey, defaultSymKeySendLimit, topic, roaddrhex)
    if err != nil {
        t.Fatal(err)
    }
    err = clients[1].Call(&rkeyids, "psstest_setSymKeys", lpubkeyhex, rrecvkey, lrecvkey, defaultSymKeySendLimit, topic, loaddrhex)
    if err != nil {
        t.Fatal(err)
    }

    // send and verify delivery
    lmsg := []byte("plugh")
    err = clients[1].Call(nil, "pss_sendSym", rkeyids[1], topic, hexutil.Encode(lmsg))
    if err != nil {
        t.Fatal(err)
    }
    select {
    case recvmsg := <-lmsgC:
        if !bytes.Equal(recvmsg.Msg, lmsg) {
            t.Fatalf("node 1 received payload mismatch: expected %v, got %v", lmsg, recvmsg)
        }
    case cerr := <-lctx.Done():
        t.Fatalf("test message timed out: %v", cerr)
    }
    rmsg := []byte("xyzzy")
    err = clients[0].Call(nil, "pss_sendSym", lkeyids[1], topic, hexutil.Encode(rmsg))
    if err != nil {
        t.Fatal(err)
    }
    select {
    case recvmsg := <-rmsgC:
        if !bytes.Equal(recvmsg.Msg, rmsg) {
            t.Fatalf("node 2 received payload mismatch: expected %x, got %v", rmsg, recvmsg.Msg)
        }
    case cerr := <-rctx.Done():
        t.Fatalf("test message timed out: %v", cerr)
    }
}

// send asymmetrically encrypted message between two directly connected peers
func TestSendAsym(t *testing.T) {
    t.Run("32", testSendAsym)
    t.Run("8", testSendAsym)
    t.Run("0", testSendAsym)
}

func testSendAsym(t *testing.T) {

    // address hint size
    var addrsize int64
    var err error
    paramstring := strings.Split(t.Name(), "/")
    addrsize, _ = strconv.ParseInt(paramstring[1], 10, 0)
    log.Info("asym send test", "addrsize", addrsize)

    clients, err := setupNetwork(2, false)
    if err != nil {
        t.Fatal(err)
    }

    var topic string
    err = clients[0].Call(&topic, "pss_stringToTopic", "foo:42")
    if err != nil {
        t.Fatal(err)
    }

    time.Sleep(time.Millisecond * 250)

    var loaddrhex string
    err = clients[0].Call(&loaddrhex, "pss_baseAddr")
    if err != nil {
        t.Fatalf("rpc get node 1 baseaddr fail: %v", err)
    }
    loaddrhex = loaddrhex[:2+(addrsize*2)]
    var roaddrhex string
    err = clients[1].Call(&roaddrhex, "pss_baseAddr")
    if err != nil {
        t.Fatalf("rpc get node 2 baseaddr fail: %v", err)
    }
    roaddrhex = roaddrhex[:2+(addrsize*2)]

    // retrieve public key from pss instance
    // set this public key reciprocally
    var lpubkey string
    err = clients[0].Call(&lpubkey, "pss_getPublicKey")
    if err != nil {
        t.Fatalf("rpc get node 1 pubkey fail: %v", err)
    }
    var rpubkey string
    err = clients[1].Call(&rpubkey, "pss_getPublicKey")
    if err != nil {
        t.Fatalf("rpc get node 2 pubkey fail: %v", err)
    }

    time.Sleep(time.Millisecond * 500) // replace with hive healthy code

    lmsgC := make(chan APIMsg)
    lctx, lcancel := context.WithTimeout(context.Background(), time.Second*10)
    defer lcancel()
    lsub, err := clients[0].Subscribe(lctx, "pss", lmsgC, "receive", topic)
    log.Trace("lsub", "id", lsub)
    defer lsub.Unsubscribe()
    rmsgC := make(chan APIMsg)
    rctx, rcancel := context.WithTimeout(context.Background(), time.Second*10)
    defer rcancel()
    rsub, err := clients[1].Subscribe(rctx, "pss", rmsgC, "receive", topic)
    log.Trace("rsub", "id", rsub)
    defer rsub.Unsubscribe()

    // store reciprocal public keys
    err = clients[0].Call(nil, "pss_setPeerPublicKey", rpubkey, topic, roaddrhex)
    if err != nil {
        t.Fatal(err)
    }
    err = clients[1].Call(nil, "pss_setPeerPublicKey", lpubkey, topic, loaddrhex)
    if err != nil {
        t.Fatal(err)
    }

    // send and verify delivery
    rmsg := []byte("xyzzy")
    err = clients[0].Call(nil, "pss_sendAsym", rpubkey, topic, hexutil.Encode(rmsg))
    if err != nil {
        t.Fatal(err)
    }
    select {
    case recvmsg := <-rmsgC:
        if !bytes.Equal(recvmsg.Msg, rmsg) {
            t.Fatalf("node 2 received payload mismatch: expected %v, got %v", rmsg, recvmsg.Msg)
        }
    case cerr := <-rctx.Done():
        t.Fatalf("test message timed out: %v", cerr)
    }
    lmsg := []byte("plugh")
    err = clients[1].Call(nil, "pss_sendAsym", lpubkey, topic, hexutil.Encode(lmsg))
    if err != nil {
        t.Fatal(err)
    }
    select {
    case recvmsg := <-lmsgC:
        if !bytes.Equal(recvmsg.Msg, lmsg) {
            t.Fatalf("node 1 received payload mismatch: expected %v, got %v", lmsg, recvmsg.Msg)
        }
    case cerr := <-lctx.Done():
        t.Fatalf("test message timed out: %v", cerr)
    }
}

type Job struct {
    Msg      []byte
    SendNode discover.NodeID
    RecvNode discover.NodeID
}

func worker(id int, jobs <-chan Job, rpcs map[discover.NodeID]*rpc.Client, pubkeys map[discover.NodeID]string, topic string) {
    for j := range jobs {
        rpcs[j.SendNode].Call(nil, "pss_sendAsym", pubkeys[j.RecvNode], topic, hexutil.Encode(j.Msg))
    }
}

func TestNetwork(t *testing.T) {
    t.Run("16/1000/4/sim", testNetwork)
}

// params in run name:
// nodes/msgs/addrbytes/adaptertype
// if adaptertype is exec uses execadapter, simadapter otherwise
func TestNetwork2000(t *testing.T) {
    //enableMetrics()

    if !*longrunning {
        t.Skip("run with --longrunning flag to run extensive network tests")
    }
    t.Run("3/2000/4/sim", testNetwork)
    t.Run("4/2000/4/sim", testNetwork)
    t.Run("8/2000/4/sim", testNetwork)
    t.Run("16/2000/4/sim", testNetwork)
}

func TestNetwork5000(t *testing.T) {
    //enableMetrics()

    if !*longrunning {
        t.Skip("run with --longrunning flag to run extensive network tests")
    }
    t.Run("3/5000/4/sim", testNetwork)
    t.Run("4/5000/4/sim", testNetwork)
    t.Run("8/5000/4/sim", testNetwork)
    t.Run("16/5000/4/sim", testNetwork)
}

func TestNetwork10000(t *testing.T) {
    //enableMetrics()

    if !*longrunning {
        t.Skip("run with --longrunning flag to run extensive network tests")
    }
    t.Run("3/10000/4/sim", testNetwork)
    t.Run("4/10000/4/sim", testNetwork)
    t.Run("8/10000/4/sim", testNetwork)
}

func testNetwork(t *testing.T) {
    type msgnotifyC struct {
        id     discover.NodeID
        msgIdx int
    }

    paramstring := strings.Split(t.Name(), "/")
    nodecount, _ := strconv.ParseInt(paramstring[1], 10, 0)
    msgcount, _ := strconv.ParseInt(paramstring[2], 10, 0)
    addrsize, _ := strconv.ParseInt(paramstring[3], 10, 0)
    adapter := paramstring[4]

    log.Info("network test", "nodecount", nodecount, "msgcount", msgcount, "addrhintsize", addrsize)

    nodes := make([]discover.NodeID, nodecount)
    bzzaddrs := make(map[discover.NodeID]string, nodecount)
    rpcs := make(map[discover.NodeID]*rpc.Client, nodecount)
    pubkeys := make(map[discover.NodeID]string, nodecount)

    sentmsgs := make([][]byte, msgcount)
    recvmsgs := make([]bool, msgcount)
    nodemsgcount := make(map[discover.NodeID]int, nodecount)

    trigger := make(chan discover.NodeID)

    var a adapters.NodeAdapter
    if adapter == "exec" {
        dirname, err := ioutil.TempDir(".", "")
        if err != nil {
            t.Fatal(err)
        }
        a = adapters.NewExecAdapter(dirname)
    } else if adapter == "tcp" {
        a = adapters.NewTCPAdapter(newServices(false))
    } else if adapter == "sim" {
        a = adapters.NewSimAdapter(newServices(false))
    }
    net := simulations.NewNetwork(a, &simulations.NetworkConfig{
        ID: "0",
    })
    defer net.Shutdown()

    f, err := os.Open(fmt.Sprintf("testdata/snapshot_%d.json", nodecount))
    if err != nil {
        t.Fatal(err)
    }
    jsonbyte, err := ioutil.ReadAll(f)
    if err != nil {
        t.Fatal(err)
    }
    var snap simulations.Snapshot
    err = json.Unmarshal(jsonbyte, &snap)
    if err != nil {
        t.Fatal(err)
    }
    err = net.Load(&snap)
    if err != nil {
        //TODO: Fix p2p simulation framework to not crash when loading 32-nodes
        //t.Fatal(err)
    }

    time.Sleep(1 * time.Second)

    triggerChecks := func(trigger chan discover.NodeID, id discover.NodeID, rpcclient *rpc.Client, topic string) error {
        msgC := make(chan APIMsg)
        ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
        defer cancel()
        sub, err := rpcclient.Subscribe(ctx, "pss", msgC, "receive", topic)
        if err != nil {
            t.Fatal(err)
        }
        go func() {
            defer sub.Unsubscribe()
            for {
                select {
                case recvmsg := <-msgC:
                    idx, _ := binary.Uvarint(recvmsg.Msg)
                    if !recvmsgs[idx] {
                        log.Debug("msg recv", "idx", idx, "id", id)
                        recvmsgs[idx] = true
                        trigger <- id
                    }
                case <-sub.Err():
                    return
                }
            }
        }()
        return nil
    }

    var topic string
    for i, nod := range net.GetNodes() {
        nodes[i] = nod.ID()
        rpcs[nodes[i]], err = nod.Client()
        if err != nil {
            t.Fatal(err)
        }
        if topic == "" {
            err = rpcs[nodes[i]].Call(&topic, "pss_stringToTopic", "foo:42")
            if err != nil {
                t.Fatal(err)
            }
        }
        var pubkey string
        err = rpcs[nodes[i]].Call(&pubkey, "pss_getPublicKey")
        if err != nil {
            t.Fatal(err)
        }
        pubkeys[nod.ID()] = pubkey
        var addrhex string
        err = rpcs[nodes[i]].Call(&addrhex, "pss_baseAddr")
        if err != nil {
            t.Fatal(err)
        }
        bzzaddrs[nodes[i]] = addrhex
        err = triggerChecks(trigger, nodes[i], rpcs[nodes[i]], topic)
        if err != nil {
            t.Fatal(err)
        }
    }

    time.Sleep(1 * time.Second)

    // setup workers
    jobs := make(chan Job, 10)
    for w := 1; w <= 10; w++ {
        go worker(w, jobs, rpcs, pubkeys, topic)
    }

    time.Sleep(1 * time.Second)

    for i := 0; i < int(msgcount); i++ {
        sendnodeidx := rand.Intn(int(nodecount))
        recvnodeidx := rand.Intn(int(nodecount - 1))
        if recvnodeidx >= sendnodeidx {
            recvnodeidx++
        }
        nodemsgcount[nodes[recvnodeidx]]++
        sentmsgs[i] = make([]byte, 8)
        c := binary.PutUvarint(sentmsgs[i], uint64(i))
        if c == 0 {
            t.Fatal("0 byte message")
        }
        if err != nil {
            t.Fatal(err)
        }
        err = rpcs[nodes[sendnodeidx]].Call(nil, "pss_setPeerPublicKey", pubkeys[nodes[recvnodeidx]], topic, bzzaddrs[nodes[recvnodeidx]])
        if err != nil {
            t.Fatal(err)
        }

        jobs <- Job{
            Msg:      sentmsgs[i],
            SendNode: nodes[sendnodeidx],
            RecvNode: nodes[recvnodeidx],
        }
    }

    finalmsgcount := 0
    ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
    defer cancel()
outer:
    for i := 0; i < int(msgcount); i++ {
        select {
        case id := <-trigger:
            nodemsgcount[id]--
            finalmsgcount++
        case <-ctx.Done():
            log.Warn("timeout")
            break outer
        }
    }

    for i, msg := range recvmsgs {
        if !msg {
            log.Debug("missing message", "idx", i)
        }
    }
    t.Logf("%d of %d messages received", finalmsgcount, msgcount)

    if finalmsgcount != int(msgcount) {
        t.Fatalf("%d messages were not received", int(msgcount)-finalmsgcount)
    }

}

// check that in a network of a -> b -> c -> a
// a doesn't receive a sent message twice
func TestDeduplication(t *testing.T) {
    var err error

    clients, err := setupNetwork(3, false)
    if err != nil {
        t.Fatal(err)
    }

    var addrsize = 32
    var loaddrhex string
    err = clients[0].Call(&loaddrhex, "pss_baseAddr")
    if err != nil {
        t.Fatalf("rpc get node 1 baseaddr fail: %v", err)
    }
    loaddrhex = loaddrhex[:2+(addrsize*2)]
    var roaddrhex string
    err = clients[1].Call(&roaddrhex, "pss_baseAddr")
    if err != nil {
        t.Fatalf("rpc get node 2 baseaddr fail: %v", err)
    }
    roaddrhex = roaddrhex[:2+(addrsize*2)]
    var xoaddrhex string
    err = clients[2].Call(&xoaddrhex, "pss_baseAddr")
    if err != nil {
        t.Fatalf("rpc get node 3 baseaddr fail: %v", err)
    }
    xoaddrhex = xoaddrhex[:2+(addrsize*2)]

    log.Info("peer", "l", loaddrhex, "r", roaddrhex, "x", xoaddrhex)

    var topic string
    err = clients[0].Call(&topic, "pss_stringToTopic", "foo:42")
    if err != nil {
        t.Fatal(err)
    }

    time.Sleep(time.Millisecond * 250)

    // retrieve public key from pss instance
    // set this public key reciprocally
    var rpubkey string
    err = clients[1].Call(&rpubkey, "pss_getPublicKey")
    if err != nil {
        t.Fatalf("rpc get receivenode pubkey fail: %v", err)
    }

    time.Sleep(time.Millisecond * 500) // replace with hive healthy code

    rmsgC := make(chan APIMsg)
    rctx, cancel := context.WithTimeout(context.Background(), time.Second*1)
    defer cancel()
    rsub, err := clients[1].Subscribe(rctx, "pss", rmsgC, "receive", topic)
    log.Trace("rsub", "id", rsub)
    defer rsub.Unsubscribe()

    // store public key for recipient
    // zero-length address means forward to all
    // we have just two peers, they will be in proxbin, and will both receive
    err = clients[0].Call(nil, "pss_setPeerPublicKey", rpubkey, topic, "0x")
    if err != nil {
        t.Fatal(err)
    }

    // send and verify delivery
    rmsg := []byte("xyzzy")
    err = clients[0].Call(nil, "pss_sendAsym", rpubkey, topic, hexutil.Encode(rmsg))
    if err != nil {
        t.Fatal(err)
    }

    var receivedok bool
OUTER:
    for {
        select {
        case <-rmsgC:
            if receivedok {
                t.Fatalf("duplicate message received")
            }
            receivedok = true
        case <-rctx.Done():
            break OUTER
        }
    }
    if !receivedok {
        t.Fatalf("message did not arrive")
    }
}

// symmetric send performance with varying message sizes
func BenchmarkSymkeySend(b *testing.B) {
    b.Run(fmt.Sprintf("%d", 256), benchmarkSymKeySend)
    b.Run(fmt.Sprintf("%d", 1024), benchmarkSymKeySend)
    b.Run(fmt.Sprintf("%d", 1024*1024), benchmarkSymKeySend)
    b.Run(fmt.Sprintf("%d", 1024*1024*10), benchmarkSymKeySend)
    b.Run(fmt.Sprintf("%d", 1024*1024*100), benchmarkSymKeySend)
}

func benchmarkSymKeySend(b *testing.B) {
    msgsizestring := strings.Split(b.Name(), "/")
    if len(msgsizestring) != 2 {
        b.Fatalf("benchmark called without msgsize param")
    }
    msgsize, err := strconv.ParseInt(msgsizestring[1], 10, 0)
    if err != nil {
        b.Fatalf("benchmark called with invalid msgsize param '%s': %v", msgsizestring[1], err)
    }
    ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    defer cancel()
    keys, err := wapi.NewKeyPair(ctx)
    privkey, err := w.GetPrivateKey(keys)
    ps := newTestPss(privkey, nil, nil)
    msg := make([]byte, msgsize)
    rand.Read(msg)
    topic := BytesToTopic([]byte("foo"))
    to := make(PssAddress, 32)
    copy(to[:], network.RandomAddr().Over())
    symkeyid, err := ps.GenerateSymmetricKey(topic, &to, true)
    if err != nil {
        b.Fatalf("could not generate symkey: %v", err)
    }
    symkey, err := ps.w.GetSymKey(symkeyid)
    if err != nil {
        b.Fatalf("could not retrieve symkey: %v", err)
    }
    ps.SetSymmetricKey(symkey, topic, &to, false)

    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        ps.SendSym(symkeyid, topic, msg)
    }
}

// asymmetric send performance with varying message sizes
func BenchmarkAsymkeySend(b *testing.B) {
    b.Run(fmt.Sprintf("%d", 256), benchmarkAsymKeySend)
    b.Run(fmt.Sprintf("%d", 1024), benchmarkAsymKeySend)
    b.Run(fmt.Sprintf("%d", 1024*1024), benchmarkAsymKeySend)
    b.Run(fmt.Sprintf("%d", 1024*1024*10), benchmarkAsymKeySend)
    b.Run(fmt.Sprintf("%d", 1024*1024*100), benchmarkAsymKeySend)
}

func benchmarkAsymKeySend(b *testing.B) {
    msgsizestring := strings.Split(b.Name(), "/")
    if len(msgsizestring) != 2 {
        b.Fatalf("benchmark called without msgsize param")
    }
    msgsize, err := strconv.ParseInt(msgsizestring[1], 10, 0)
    if err != nil {
        b.Fatalf("benchmark called with invalid msgsize param '%s': %v", msgsizestring[1], err)
    }
    ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    defer cancel()
    keys, err := wapi.NewKeyPair(ctx)
    privkey, err := w.GetPrivateKey(keys)
    ps := newTestPss(privkey, nil, nil)
    msg := make([]byte, msgsize)
    rand.Read(msg)
    topic := BytesToTopic([]byte("foo"))
    to := make(PssAddress, 32)
    copy(to[:], network.RandomAddr().Over())
    ps.SetPeerPublicKey(&privkey.PublicKey, topic, &to)
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        ps.SendAsym(common.ToHex(crypto.FromECDSAPub(&privkey.PublicKey)), topic, msg)
    }
}
func BenchmarkSymkeyBruteforceChangeaddr(b *testing.B) {
    for i := 100; i < 100000; i = i * 10 {
        for j := 32; j < 10000; j = j * 8 {
            b.Run(fmt.Sprintf("%d/%d", i, j), benchmarkSymkeyBruteforceChangeaddr)
        }
        //b.Run(fmt.Sprintf("%d", i), benchmarkSymkeyBruteforceChangeaddr)
    }
}

// decrypt performance using symkey cache, worst case
// (decrypt key always last in cache)
func benchmarkSymkeyBruteforceChangeaddr(b *testing.B) {
    keycountstring := strings.Split(b.Name(), "/")
    cachesize := int64(0)
    var ps *Pss
    if len(keycountstring) < 2 {
        b.Fatalf("benchmark called without count param")
    }
    keycount, err := strconv.ParseInt(keycountstring[1], 10, 0)
    if err != nil {
        b.Fatalf("benchmark called with invalid count param '%s': %v", keycountstring[1], err)
    }
    if len(keycountstring) == 3 {
        cachesize, err = strconv.ParseInt(keycountstring[2], 10, 0)
        if err != nil {
            b.Fatalf("benchmark called with invalid cachesize '%s': %v", keycountstring[2], err)
        }
    }
    pssmsgs := make([]*PssMsg, 0, keycount)
    var keyid string
    ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    defer cancel()
    keys, err := wapi.NewKeyPair(ctx)
    privkey, err := w.GetPrivateKey(keys)
    if cachesize > 0 {
        ps = newTestPss(privkey, nil, &PssParams{SymKeyCacheCapacity: int(cachesize)})
    } else {
        ps = newTestPss(privkey, nil, nil)
    }
    topic := BytesToTopic([]byte("foo"))
    for i := 0; i < int(keycount); i++ {
        to := make(PssAddress, 32)
        copy(to[:], network.RandomAddr().Over())
        keyid, err = ps.GenerateSymmetricKey(topic, &to, true)
        if err != nil {
            b.Fatalf("cant generate symkey #%d: %v", i, err)
        }
        symkey, err := ps.w.GetSymKey(keyid)
        if err != nil {
            b.Fatalf("could not retrieve symkey %s: %v", keyid, err)
        }
        wparams := &whisper.MessageParams{
            TTL:      defaultWhisperTTL,
            KeySym:   symkey,
            Topic:    whisper.TopicType(topic),
            WorkTime: defaultWhisperWorkTime,
            PoW:      defaultWhisperPoW,
            Payload:  []byte("xyzzy"),
            Padding:  []byte("1234567890abcdef"),
        }
        woutmsg, err := whisper.NewSentMessage(wparams)
        if err != nil {
            b.Fatalf("could not create whisper message: %v", err)
        }
        env, err := woutmsg.Wrap(wparams)
        if err != nil {
            b.Fatalf("could not generate whisper envelope: %v", err)
        }
        ps.Register(&topic, func(msg []byte, p *p2p.Peer, asymmetric bool, keyid string) error {
            return nil
        })
        pssmsgs = append(pssmsgs, &PssMsg{
            To:      to,
            Payload: env,
        })
    }
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        if err := ps.process(pssmsgs[len(pssmsgs)-(i%len(pssmsgs))-1]); err != nil {
            b.Fatalf("pss processing failed: %v", err)
        }
    }
}

func BenchmarkSymkeyBruteforceSameaddr(b *testing.B) {
    for i := 100; i < 100000; i = i * 10 {
        for j := 32; j < 10000; j = j * 8 {
            b.Run(fmt.Sprintf("%d/%d", i, j), benchmarkSymkeyBruteforceSameaddr)
        }
    }
}

// decrypt performance using symkey cache, best case
// (decrypt key always first in cache)
func benchmarkSymkeyBruteforceSameaddr(b *testing.B) {
    var keyid string
    var ps *Pss
    cachesize := int64(0)
    keycountstring := strings.Split(b.Name(), "/")
    if len(keycountstring) < 2 {
        b.Fatalf("benchmark called without count param")
    }
    keycount, err := strconv.ParseInt(keycountstring[1], 10, 0)
    if err != nil {
        b.Fatalf("benchmark called with invalid count param '%s': %v", keycountstring[1], err)
    }
    if len(keycountstring) == 3 {
        cachesize, err = strconv.ParseInt(keycountstring[2], 10, 0)
        if err != nil {
            b.Fatalf("benchmark called with invalid cachesize '%s': %v", keycountstring[2], err)
        }
    }
    addr := make([]PssAddress, keycount)
    ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    defer cancel()
    keys, err := wapi.NewKeyPair(ctx)
    privkey, err := w.GetPrivateKey(keys)
    if cachesize > 0 {
        ps = newTestPss(privkey, nil, &PssParams{SymKeyCacheCapacity: int(cachesize)})
    } else {
        ps = newTestPss(privkey, nil, nil)
    }
    topic := BytesToTopic([]byte("foo"))
    for i := 0; i < int(keycount); i++ {
        copy(addr[i], network.RandomAddr().Over())
        keyid, err = ps.GenerateSymmetricKey(topic, &addr[i], true)
        if err != nil {
            b.Fatalf("cant generate symkey #%d: %v", i, err)
        }

    }
    symkey, err := ps.w.GetSymKey(keyid)
    if err != nil {
        b.Fatalf("could not retrieve symkey %s: %v", keyid, err)
    }
    wparams := &whisper.MessageParams{
        TTL:      defaultWhisperTTL,
        KeySym:   symkey,
        Topic:    whisper.TopicType(topic),
        WorkTime: defaultWhisperWorkTime,
        PoW:      defaultWhisperPoW,
        Payload:  []byte("xyzzy"),
        Padding:  []byte("1234567890abcdef"),
    }
    woutmsg, err := whisper.NewSentMessage(wparams)
    if err != nil {
        b.Fatalf("could not create whisper message: %v", err)
    }
    env, err := woutmsg.Wrap(wparams)
    if err != nil {
        b.Fatalf("could not generate whisper envelope: %v", err)
    }
    ps.Register(&topic, func(msg []byte, p *p2p.Peer, asymmetric bool, keyid string) error {
        return nil
    })
    pssmsg := &PssMsg{
        To:      addr[len(addr)-1][:],
        Payload: env,
    }
    for i := 0; i < b.N; i++ {
        if err := ps.process(pssmsg); err != nil {
            b.Fatalf("pss processing failed: %v", err)
        }
    }
}

// setup simulated network with bzz/discovery and pss services.
// connects nodes in a circle
// if allowRaw is set, omission of builtin pss encryption is enabled (see PssParams)
func setupNetwork(numnodes int, allowRaw bool) (clients []*rpc.Client, err error) {
    nodes := make([]*simulations.Node, numnodes)
    clients = make([]*rpc.Client, numnodes)
    if numnodes < 2 {
        return nil, fmt.Errorf("Minimum two nodes in network")
    }
    adapter := adapters.NewSimAdapter(newServices(allowRaw))
    net := simulations.NewNetwork(adapter, &simulations.NetworkConfig{
        ID:             "0",
        DefaultService: "bzz",
    })
    for i := 0; i < numnodes; i++ {
        nodeconf := adapters.RandomNodeConfig()
        nodeconf.Services = []string{"bzz", pssProtocolName}
        nodes[i], err = net.NewNodeWithConfig(nodeconf)
        if err != nil {
            return nil, fmt.Errorf("error creating node 1: %v", err)
        }
        err = net.Start(nodes[i].ID())
        if err != nil {
            return nil, fmt.Errorf("error starting node 1: %v", err)
        }
        if i > 0 {
            err = net.Connect(nodes[i].ID(), nodes[i-1].ID())
            if err != nil {
                return nil, fmt.Errorf("error connecting nodes: %v", err)
            }
        }
        clients[i], err = nodes[i].Client()
        if err != nil {
            return nil, fmt.Errorf("create node 1 rpc client fail: %v", err)
        }
    }
    if numnodes > 2 {
        err = net.Connect(nodes[0].ID(), nodes[len(nodes)-1].ID())
        if err != nil {
            return nil, fmt.Errorf("error connecting first and last nodes")
        }
    }
    return clients, nil
}

func newServices(allowRaw bool) adapters.Services {
    stateStore := state.NewInmemoryStore()
    kademlias := make(map[discover.NodeID]*network.Kademlia)
    kademlia := func(id discover.NodeID) *network.Kademlia {
        if k, ok := kademlias[id]; ok {
            return k
        }
        addr := network.NewAddrFromNodeID(id)
        params := network.NewKadParams()
        params.MinProxBinSize = 2
        params.MaxBinSize = 3
        params.MinBinSize = 1
        params.MaxRetries = 1000
        params.RetryExponent = 2
        params.RetryInterval = 1000000
        kademlias[id] = network.NewKademlia(addr.Over(), params)
        return kademlias[id]
    }
    return adapters.Services{
        pssProtocolName: func(ctx *adapters.ServiceContext) (node.Service, error) {
            // execadapter does not exec init()
            initTest()

            ctxlocal, cancel := context.WithTimeout(context.Background(), time.Second)
            defer cancel()
            keys, err := wapi.NewKeyPair(ctxlocal)
            privkey, err := w.GetPrivateKey(keys)
            pssp := NewPssParams().WithPrivateKey(privkey)
            pssp.AllowRaw = allowRaw
            pskad := kademlia(ctx.Config.ID)
            ps, err := NewPss(pskad, pssp)
            if err != nil {
                return nil, err
            }

            ping := &Ping{
                OutC: make(chan bool),
                Pong: true,
            }
            p2pp := NewPingProtocol(ping)
            pp, err := RegisterProtocol(ps, &PingTopic, PingProtocol, p2pp, &ProtocolParams{Asymmetric: true})
            if err != nil {
                return nil, err
            }
            if useHandshake {
                SetHandshakeController(ps, NewHandshakeParams())
            }
            ps.Register(&PingTopic, pp.Handle)
            ps.addAPI(rpc.API{
                Namespace: "psstest",
                Version:   "0.3",
                Service:   NewAPITest(ps),
                Public:    false,
            })
            if err != nil {
                log.Error("Couldnt register pss protocol", "err", err)
                os.Exit(1)
            }
            pssprotocols[ctx.Config.ID.String()] = &protoCtrl{
                C:        ping.OutC,
                protocol: pp,
                run:      p2pp.Run,
            }
            return ps, nil
        },
        "bzz": func(ctx *adapters.ServiceContext) (node.Service, error) {
            addr := network.NewAddrFromNodeID(ctx.Config.ID)
            hp := network.NewHiveParams()
            hp.Discovery = false
            config := &network.BzzConfig{
                OverlayAddr:  addr.Over(),
                UnderlayAddr: addr.Under(),
                HiveParams:   hp,
            }
            return network.NewBzz(config, kademlia(ctx.Config.ID), stateStore, nil, nil), nil
        },
    }
}

func newTestPss(privkey *ecdsa.PrivateKey, kad *network.Kademlia, ppextra *PssParams) *Pss {

    var nid discover.NodeID
    copy(nid[:], crypto.FromECDSAPub(&privkey.PublicKey))
    addr := network.NewAddrFromNodeID(nid)

    // set up routing if kademlia is not passed to us
    if kad == nil {
        kp := network.NewKadParams()
        kp.MinProxBinSize = 3
        kad = network.NewKademlia(addr.Over(), kp)
    }

    // create pss
    pp := NewPssParams().WithPrivateKey(privkey)
    if ppextra != nil {
        pp.SymKeyCacheCapacity = ppextra.SymKeyCacheCapacity
    }
    ps, err := NewPss(kad, pp)
    if err != nil {
        return nil
    }
    ps.Start(nil)

    return ps
}

// API calls for test/development use
type APITest struct {
    *Pss
}

func NewAPITest(ps *Pss) *APITest {
    return &APITest{Pss: ps}
}

func (apitest *APITest) SetSymKeys(pubkeyid string, recvsymkey []byte, sendsymkey []byte, limit uint16, topic Topic, to PssAddress) ([2]string, error) {
    recvsymkeyid, err := apitest.SetSymmetricKey(recvsymkey, topic, &to, true)
    if err != nil {
        return [2]string{}, err
    }
    sendsymkeyid, err := apitest.SetSymmetricKey(sendsymkey, topic, &to, false)
    if err != nil {
        return [2]string{}, err
    }
    return [2]string{recvsymkeyid, sendsymkeyid}, nil
}

func (apitest *APITest) Clean() (int, error) {
    return apitest.Pss.cleanKeys(), nil
}

// enableMetrics is starting InfluxDB reporter so that we collect stats when running tests locally
func enableMetrics() {
    metrics.Enabled = true
    go influxdb.InfluxDBWithTags(metrics.DefaultRegistry, 1*time.Second, "http://localhost:8086", "metrics", "admin", "admin", "swarm.", map[string]string{
        "host": "test",
    })
}