forked from algorand/go-algorand
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtxHandler_test.go
2505 lines (2231 loc) · 86 KB
/
txHandler_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
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2019-2023 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand. If not, see <https://www.gnu.org/licenses/>.
package data
import (
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"math/rand"
"os"
"runtime"
"runtime/pprof"
"strings"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/algorand/go-deadlock"
"github.com/algorand/go-algorand/agreement"
"github.com/algorand/go-algorand/components/mocks"
"github.com/algorand/go-algorand/config"
"github.com/algorand/go-algorand/crypto"
"github.com/algorand/go-algorand/data/basics"
"github.com/algorand/go-algorand/data/bookkeeping"
"github.com/algorand/go-algorand/data/pools"
"github.com/algorand/go-algorand/data/transactions"
"github.com/algorand/go-algorand/data/transactions/verify"
"github.com/algorand/go-algorand/data/txntest"
"github.com/algorand/go-algorand/ledger/ledgercore"
"github.com/algorand/go-algorand/logging"
"github.com/algorand/go-algorand/network"
"github.com/algorand/go-algorand/protocol"
"github.com/algorand/go-algorand/test/partitiontest"
"github.com/algorand/go-algorand/util/execpool"
"github.com/algorand/go-algorand/util/metrics"
)
// txHandler uses config values to determine backlog size. Tests should use a static value
var txBacklogSize = config.GetDefaultLocal().TxBacklogSize
// mock sender is used to implement OnClose, since TXHandlers expect to use Senders and ERL Clients
type mockSender struct{}
func (m mockSender) OnClose(func()) {}
// txHandlerConfig is a subset of tx handler related options from config.Local
type txHandlerConfig struct {
enableFilteringRawMsg bool
enableFilteringCanonical bool
}
func makeTestGenesisAccounts(tb testing.TB, numUsers int) ([]basics.Address, []*crypto.SignatureSecrets, map[basics.Address]basics.AccountData) {
addresses := make([]basics.Address, numUsers)
secrets := make([]*crypto.SignatureSecrets, numUsers)
genesis := make(map[basics.Address]basics.AccountData)
for i := 0; i < numUsers; i++ {
secret := keypair()
addr := basics.Address(secret.SignatureVerifier)
secrets[i] = secret
addresses[i] = addr
genesis[addr] = basics.AccountData{
Status: basics.Online,
MicroAlgos: basics.MicroAlgos{Raw: 10000000000000},
}
}
genesis[poolAddr] = basics.AccountData{
Status: basics.NotParticipating,
MicroAlgos: basics.MicroAlgos{Raw: config.Consensus[protocol.ConsensusCurrentVersion].MinBalance},
}
require.Equal(tb, len(genesis), numUsers+1)
return addresses, secrets, genesis
}
func BenchmarkTxHandlerProcessing(b *testing.B) {
const numUsers = 100
log := logging.TestingLog(b)
log.SetLevel(logging.Warn)
addresses, secrets, genesis := makeTestGenesisAccounts(b, numUsers)
genBal := bookkeeping.MakeGenesisBalances(genesis, sinkAddr, poolAddr)
ledgerName := fmt.Sprintf("%s-mem-%d", b.Name(), b.N)
const inMem = true
cfg := config.GetDefaultLocal()
cfg.Archival = true
cfg.TxBacklogReservedCapacityPerPeer = 1
cfg.IncomingConnectionsLimit = 10
ledger, err := LoadLedger(log, ledgerName, inMem, protocol.ConsensusCurrentVersion, genBal, genesisID, genesisHash, nil, cfg)
require.NoError(b, err)
defer ledger.Close()
l := ledger
cfg.TxPoolSize = 75000
cfg.EnableProcessBlockStats = false
txHandler, err := makeTestTxHandler(l, cfg)
require.NoError(b, err)
defer txHandler.txVerificationPool.Shutdown()
defer close(txHandler.streamVerifierDropped)
makeTxns := func(N int) [][]transactions.SignedTxn {
ret := make([][]transactions.SignedTxn, 0, N)
for u := 0; u < N; u++ {
// generate transactions
tx := transactions.Transaction{
Type: protocol.PaymentTx,
Header: transactions.Header{
Sender: addresses[u%numUsers],
Fee: basics.MicroAlgos{Raw: proto.MinTxnFee * 2},
FirstValid: 0,
LastValid: basics.Round(proto.MaxTxnLife),
Note: make([]byte, 2),
},
PaymentTxnFields: transactions.PaymentTxnFields{
Receiver: addresses[(u+1)%numUsers],
Amount: basics.MicroAlgos{Raw: mockBalancesMinBalance + (rand.Uint64() % 10000)},
},
}
signedTx := tx.Sign(secrets[u%numUsers])
ret = append(ret, []transactions.SignedTxn{signedTx})
}
return ret
}
b.Run("processDecoded", func(b *testing.B) {
signedTransactionGroups := makeTxns(b.N)
b.ResetTimer()
for i := range signedTransactionGroups {
txHandler.processDecoded(signedTransactionGroups[i])
}
})
b.Run("verify.TxnGroup", func(b *testing.B) {
signedTransactionGroups := makeTxns(b.N)
b.ResetTimer()
// make a header including only the fields needed by PrepareGroupContext
hdr := bookkeeping.BlockHeader{}
hdr.FeeSink = basics.Address{}
hdr.RewardsPool = basics.Address{}
hdr.CurrentProtocol = protocol.ConsensusCurrentVersion
vtc := vtCache{}
b.Logf("verifying %d signedTransactionGroups", len(signedTransactionGroups))
b.ResetTimer()
for i := range signedTransactionGroups {
verify.TxnGroup(signedTransactionGroups[i], &hdr, vtc, l)
}
})
}
// vtCache is a noop VerifiedTransactionCache
type vtCache struct{}
func (vtCache) Add(txgroup []transactions.SignedTxn, groupCtx *verify.GroupContext) {}
func (vtCache) AddPayset(txgroup [][]transactions.SignedTxn, groupCtxs []*verify.GroupContext) {
return
}
func (vtCache) GetUnverifiedTransactionGroups(payset [][]transactions.SignedTxn, CurrSpecAddrs transactions.SpecialAddresses, CurrProto protocol.ConsensusVersion) [][]transactions.SignedTxn {
return nil
}
func (vtCache) UpdatePinned(pinnedTxns map[transactions.Txid]transactions.SignedTxn) error {
return nil
}
func (vtCache) Pin(txgroup []transactions.SignedTxn) error { return nil }
func BenchmarkTimeAfter(b *testing.B) {
b.StopTimer()
b.ResetTimer()
deadline := time.Now().Add(5 * time.Second)
after := 0
before := 0
b.StartTimer()
for i := 0; i < b.N; i++ {
if time.Now().After(deadline) {
after++
} else {
before++
}
}
}
func makeRandomTransactions(num int) ([]transactions.SignedTxn, []byte) {
stxns := make([]transactions.SignedTxn, num)
result := make([]byte, 0, num*200)
for i := 0; i < num; i++ {
var sig crypto.Signature
crypto.RandBytes(sig[:])
var addr basics.Address
crypto.RandBytes(addr[:])
stxns[i] = transactions.SignedTxn{
Sig: sig,
AuthAddr: addr,
Txn: transactions.Transaction{
Header: transactions.Header{
Sender: addr,
Fee: basics.MicroAlgos{Raw: crypto.RandUint64()},
Note: sig[:],
},
PaymentTxnFields: transactions.PaymentTxnFields{
Receiver: addr,
Amount: basics.MicroAlgos{Raw: crypto.RandUint64()},
},
},
}
d2 := protocol.Encode(&stxns[i])
result = append(result, d2...)
}
return stxns, result
}
func TestTxHandlerProcessIncomingTxn(t *testing.T) {
partitiontest.PartitionTest(t)
t.Parallel()
const numTxns = 11
handler := makeTestTxHandlerOrphaned(1)
stxns, blob := makeRandomTransactions(numTxns)
action := handler.processIncomingTxn(network.IncomingMessage{Data: blob, Sender: mockSender{}})
require.Equal(t, network.OutgoingMessage{Action: network.Ignore}, action)
require.Equal(t, 1, len(handler.backlogQueue))
msg := <-handler.backlogQueue
require.Equal(t, numTxns, len(msg.unverifiedTxGroup))
for i := 0; i < numTxns; i++ {
require.Equal(t, stxns[i], msg.unverifiedTxGroup[i])
}
}
// BenchmarkTxHandlerProcessIncomingTxn is single-threaded ProcessIncomingTxn benchmark
func BenchmarkTxHandlerProcessIncomingTxn(b *testing.B) {
deadlockDisable := deadlock.Opts.Disable
deadlock.Opts.Disable = true
defer func() {
deadlock.Opts.Disable = deadlockDisable
}()
const numTxnsPerGroup = 16
handler := makeTestTxHandlerOrphaned(txBacklogSize)
// prepare tx groups
blobs := make([][]byte, b.N)
stxns := make([][]transactions.SignedTxn, b.N)
for i := 0; i < b.N; i++ {
stxns[i], blobs[i] = makeRandomTransactions(numTxnsPerGroup)
}
ctx, cancelFun := context.WithCancel(context.Background())
// start consumer
var wg sync.WaitGroup
wg.Add(1)
go func(ctx context.Context, n int) {
defer wg.Done()
outer:
for i := 0; i < n; i++ {
select {
case <-ctx.Done():
break outer
default:
}
msg := <-handler.backlogQueue
require.Equal(b, numTxnsPerGroup, len(msg.unverifiedTxGroup))
}
}(ctx, b.N)
// submit tx groups
b.ResetTimer()
for i := 0; i < b.N; i++ {
action := handler.processIncomingTxn(network.IncomingMessage{Data: blobs[i]})
require.Equal(b, network.OutgoingMessage{Action: network.Ignore}, action)
}
cancelFun()
wg.Wait()
}
func ipow(x, n int) int {
var res int = 1
for n != 0 {
if n&1 != 0 {
res *= x
}
n >>= 1
x *= x
}
return res
}
func TestPow(t *testing.T) {
partitiontest.PartitionTest(t)
t.Parallel()
require.Equal(t, 1, ipow(10, 0))
require.Equal(t, 10, ipow(10, 1))
require.Equal(t, 100, ipow(10, 2))
require.Equal(t, 8, ipow(2, 3))
}
func getNumBacklogDropped() int {
return int(transactionMessagesDroppedFromBacklog.GetUint64Value())
}
func getNumRawMsgDup() int {
return int(transactionMessagesDupRawMsg.GetUint64Value())
}
func getNumCanonicalDup() int {
return int(transactionMessagesDupCanonical.GetUint64Value())
}
type benchFinalize func()
func benchTxHandlerProcessIncomingTxnSubmit(b *testing.B, handler *TxHandler, blobs [][]byte, numThreads int) benchFinalize {
// submit tx groups
var wgp sync.WaitGroup
wgp.Add(numThreads)
hashesPerThread := b.N / numThreads
if hashesPerThread == 0 {
hashesPerThread = 1
}
finalize := func() {}
if b.N == 100001 {
profpath := b.Name() + "_cpuprof.pprof"
profout, err := os.Create(profpath)
if err != nil {
b.Fatal(err)
return finalize
}
b.Logf("%s: cpu profile for b.N=%d", profpath, b.N)
pprof.StartCPUProfile(profout)
finalize = func() {
pprof.StopCPUProfile()
profout.Close()
}
}
for g := 0; g < numThreads; g++ {
start := g * hashesPerThread
end := (g + 1) * (hashesPerThread)
// workaround for trivial runs with b.N = 1
if start >= b.N {
start = 0
}
if end >= b.N {
end = b.N
}
// handle the remaining blobs
if g == numThreads-1 {
end = b.N
}
// b.Logf("%d: %d %d", b.N, start, end)
go func(start int, end int) {
defer wgp.Done()
for i := start; i < end; i++ {
action := handler.processIncomingTxn(network.IncomingMessage{Data: blobs[i]})
require.Equal(b, network.OutgoingMessage{Action: network.Ignore}, action)
}
}(start, end)
}
wgp.Wait()
return finalize
}
func benchTxHandlerProcessIncomingTxnConsume(b *testing.B, handler *TxHandler, numTxnsPerGroup int, avgDelay time.Duration, statsCh chan<- [4]int) benchFinalize {
droppedStart := getNumBacklogDropped()
dupStart := getNumRawMsgDup()
cdupStart := getNumCanonicalDup()
// start consumer
var wg sync.WaitGroup
wg.Add(1)
go func(statsCh chan<- [4]int) {
defer wg.Done()
received := 0
dropped := getNumBacklogDropped() - droppedStart
dups := getNumRawMsgDup() - dupStart
cdups := getNumCanonicalDup() - cdupStart
for dups+dropped+received+cdups < b.N {
select {
case msg := <-handler.backlogQueue:
require.Equal(b, numTxnsPerGroup, len(msg.unverifiedTxGroup))
received++
default:
dropped = getNumBacklogDropped() - droppedStart
dups = getNumRawMsgDup() - dupStart
cdups = getNumCanonicalDup() - cdupStart
}
if avgDelay > 0 {
time.Sleep(avgDelay)
}
}
statsCh <- [4]int{dropped, received, dups, cdups}
}(statsCh)
return func() {
wg.Wait()
}
}
// BenchmarkTxHandlerProcessIncomingTxn16 is the same BenchmarkTxHandlerProcessIncomingTxn with 16 goroutines
func BenchmarkTxHandlerProcessIncomingTxn16(b *testing.B) {
deadlockDisable := deadlock.Opts.Disable
deadlock.Opts.Disable = true
defer func() {
deadlock.Opts.Disable = deadlockDisable
}()
const numSendThreads = 16
const numTxnsPerGroup = 16
handler := makeTestTxHandlerOrphaned(txBacklogSize)
// uncomment to benchmark no-dedup version
// handler.cacheConfig = txHandlerConfig{}
// prepare tx groups
blobs := make([][]byte, b.N)
stxns := make([][]transactions.SignedTxn, b.N)
for i := 0; i < b.N; i++ {
stxns[i], blobs[i] = makeRandomTransactions(numTxnsPerGroup)
}
statsCh := make(chan [4]int, 1)
defer close(statsCh)
finConsume := benchTxHandlerProcessIncomingTxnConsume(b, handler, numTxnsPerGroup, 0, statsCh)
// submit tx groups
b.ResetTimer()
finalizeSubmit := benchTxHandlerProcessIncomingTxnSubmit(b, handler, blobs, numSendThreads)
finalizeSubmit()
finConsume()
}
// BenchmarkTxHandlerProcessIncomingLogicTxn16 is similar to BenchmarkTxHandlerProcessIncomingTxn16
// but with logicsig groups of 4 txns
func BenchmarkTxHandlerProcessIncomingLogicTxn16(b *testing.B) {
deadlockDisable := deadlock.Opts.Disable
deadlock.Opts.Disable = true
defer func() {
deadlock.Opts.Disable = deadlockDisable
}()
const numSendThreads = 16
handler := makeTestTxHandlerOrphaned(txBacklogSize)
// prepare tx groups
blobs := make([][]byte, b.N)
stxns := make([][]transactions.SignedTxn, b.N)
for i := 0; i < b.N; i++ {
txns := txntest.CreateTinyManTxGroup(b, true)
stxns[i], _ = txntest.CreateTinyManSignedTxGroup(b, txns)
var blob []byte
for j := range stxns[i] {
encoded := protocol.Encode(&stxns[i][j])
blob = append(blob, encoded...)
}
blobs[i] = blob
}
numTxnsPerGroup := len(stxns[0])
statsCh := make(chan [4]int, 1)
defer close(statsCh)
finConsume := benchTxHandlerProcessIncomingTxnConsume(b, handler, numTxnsPerGroup, 0, statsCh)
// submit tx groups
b.ResetTimer()
finalizeSubmit := benchTxHandlerProcessIncomingTxnSubmit(b, handler, blobs, numSendThreads)
finalizeSubmit()
finConsume()
}
// BenchmarkTxHandlerIncDeDup checks txn receiving with duplicates
// simulating processing delay
func BenchmarkTxHandlerIncDeDup(b *testing.B) {
deadlockDisable := deadlock.Opts.Disable
deadlock.Opts.Disable = true
defer func() {
deadlock.Opts.Disable = deadlockDisable
}()
// parameters
const numSendThreads = 16
const numTxnsPerGroup = 16
var tests = []struct {
dedup bool
dupFactor int
workerDelay time.Duration
firstLevelOnly bool
}{
{false, 4, 10 * time.Microsecond, false},
{true, 4, 10 * time.Microsecond, false},
{false, 8, 10 * time.Microsecond, false},
{true, 8, 10 * time.Microsecond, false},
{false, 4, 4 * time.Microsecond, false},
{true, 4, 4 * time.Microsecond, false},
{false, 4, 0, false},
{true, 4, 0, false},
{true, 4, 10 * time.Microsecond, true},
}
for _, test := range tests {
var name string
var enabled string = "Y"
if !test.dedup {
enabled = "N"
}
name = fmt.Sprintf("x%d/on=%s/delay=%v", test.dupFactor, enabled, test.workerDelay)
if test.firstLevelOnly {
name = fmt.Sprintf("%s/one-level", name)
}
b.Run(name, func(b *testing.B) {
numPoolWorkers := runtime.NumCPU()
dupFactor := test.dupFactor
avgDelay := test.workerDelay / time.Duration(numPoolWorkers)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var handler *TxHandler
if test.firstLevelOnly {
handler = makeTestTxHandlerOrphanedWithContext(
ctx, txBacklogSize, txBacklogSize,
txHandlerConfig{enableFilteringRawMsg: true, enableFilteringCanonical: false}, 0,
)
} else if !test.dedup {
handler = makeTestTxHandlerOrphanedWithContext(
ctx, txBacklogSize, 0,
txHandlerConfig{}, 0,
)
} else {
handler = makeTestTxHandlerOrphanedWithContext(
ctx, txBacklogSize, txBacklogSize,
txHandlerConfig{enableFilteringRawMsg: true, enableFilteringCanonical: true}, 0,
)
}
// prepare tx groups
blobs := make([][]byte, b.N)
stxns := make([][]transactions.SignedTxn, b.N)
for i := 0; i < b.N; i += dupFactor {
stxns[i], blobs[i] = makeRandomTransactions(numTxnsPerGroup)
if b.N >= dupFactor { // skip trivial runs
for j := 1; j < dupFactor; j++ {
if i+j < b.N {
stxns[i+j], blobs[i+j] = stxns[i], blobs[i]
}
}
}
}
statsCh := make(chan [4]int, 1)
defer close(statsCh)
finConsume := benchTxHandlerProcessIncomingTxnConsume(b, handler, numTxnsPerGroup, avgDelay, statsCh)
// submit tx groups
b.ResetTimer()
finalizeSubmit := benchTxHandlerProcessIncomingTxnSubmit(b, handler, blobs, numSendThreads)
finalizeSubmit()
finConsume()
stats := <-statsCh
unique := b.N / dupFactor
dropped := stats[0]
received := stats[1]
dups := stats[2]
cdups := stats[3]
b.ReportMetric(float64(received)/float64(unique)*100, "ack,%")
b.ReportMetric(float64(dropped)/float64(b.N)*100, "drop,%")
if test.dedup {
b.ReportMetric(float64(dups)/float64(b.N)*100, "trap,%")
}
if b.N > 1 && os.Getenv("DEBUG") != "" {
b.Logf("unique %d, dropped %d, received %d, dups %d", unique, dropped, received, dups)
if cdups > 0 {
b.Logf("canonical dups %d vs %d recv", cdups, received)
}
}
})
}
}
func TestTxHandlerProcessIncomingGroup(t *testing.T) {
partitiontest.PartitionTest(t)
t.Parallel()
type T struct {
inputSize int
numDecoded int
action network.ForwardingPolicy
}
var checks = []T{}
for i := 1; i <= config.MaxTxGroupSize; i++ {
checks = append(checks, T{i, i, network.Ignore})
}
for i := 1; i < 10; i++ {
checks = append(checks, T{config.MaxTxGroupSize + i, 0, network.Disconnect})
}
for _, check := range checks {
t.Run(fmt.Sprintf("%d-%d", check.inputSize, check.numDecoded), func(t *testing.T) {
handler := TxHandler{
backlogQueue: make(chan *txBacklogMsg, 1),
}
stxns, blob := makeRandomTransactions(check.inputSize)
action := handler.processIncomingTxn(network.IncomingMessage{Data: blob})
require.Equal(t, network.OutgoingMessage{Action: check.action}, action)
if check.numDecoded > 0 {
msg := <-handler.backlogQueue
require.Equal(t, check.numDecoded, len(msg.unverifiedTxGroup))
for i := 0; i < check.numDecoded; i++ {
require.Equal(t, stxns[i], msg.unverifiedTxGroup[i])
}
} else {
require.Len(t, handler.backlogQueue, 0)
}
})
}
}
func TestTxHandlerProcessIncomingCensoring(t *testing.T) {
partitiontest.PartitionTest(t)
t.Parallel()
craftNonCanonical := func(t *testing.T, stxn *transactions.SignedTxn, blobStxn []byte) []byte {
// make non-canonical encoding and ensure it is not accepted
stxnNonCanTxn := transactions.SignedTxn{Txn: stxn.Txn}
blobTxn := protocol.Encode(&stxnNonCanTxn)
stxnNonCanAuthAddr := transactions.SignedTxn{AuthAddr: stxn.AuthAddr}
blobAuthAddr := protocol.Encode(&stxnNonCanAuthAddr)
stxnNonCanAuthSig := transactions.SignedTxn{Sig: stxn.Sig}
blobSig := protocol.Encode(&stxnNonCanAuthSig)
if blobStxn == nil {
blobStxn = protocol.Encode(stxn)
}
// double check our skills for transactions.SignedTxn creation by creating a new canonical encoding and comparing to the original
blobValidation := make([]byte, 0, len(blobTxn)+len(blobAuthAddr)+len(blobSig))
blobValidation = append(blobValidation[:], blobAuthAddr...)
blobValidation = append(blobValidation[:], blobSig[1:]...) // cut transactions.SignedTxn's field count
blobValidation = append(blobValidation[:], blobTxn[1:]...) // cut transactions.SignedTxn's field count
blobValidation[0] += 2 // increase field count
require.Equal(t, blobStxn, blobValidation)
// craft non-canonical
blobNonCan := make([]byte, 0, len(blobTxn)+len(blobAuthAddr)+len(blobSig))
blobNonCan = append(blobNonCan[:], blobTxn...)
blobNonCan = append(blobNonCan[:], blobAuthAddr[1:]...) // cut transactions.SignedTxn's field count
blobNonCan = append(blobNonCan[:], blobSig[1:]...) // cut transactions.SignedTxn's field count
blobNonCan[0] += 2 // increase field count
require.Len(t, blobNonCan, len(blobStxn))
require.NotEqual(t, blobStxn, blobNonCan)
return blobNonCan
}
forgeSig := func(t *testing.T, stxn *transactions.SignedTxn, blobStxn []byte) (transactions.SignedTxn, []byte) {
stxnForged := *stxn
crypto.RandBytes(stxnForged.Sig[:])
blobForged := protocol.Encode(&stxnForged)
require.NotEqual(t, blobStxn, blobForged)
return stxnForged, blobForged
}
encodeGroup := func(t *testing.T, g []transactions.SignedTxn, blobRef []byte) []byte {
result := make([]byte, 0, len(blobRef))
for i := 0; i < len(g); i++ {
enc := protocol.Encode(&g[i])
result = append(result, enc...)
}
require.NotEqual(t, blobRef, result)
return result
}
t.Run("single", func(t *testing.T) {
handler := makeTestTxHandlerOrphanedWithContext(context.Background(), txBacklogSize, txBacklogSize, txHandlerConfig{true, true}, 0)
stxns, blob := makeRandomTransactions(1)
stxn := stxns[0]
action := handler.processIncomingTxn(network.IncomingMessage{Data: blob})
require.Equal(t, network.OutgoingMessage{Action: network.Ignore}, action)
msg := <-handler.backlogQueue
require.Equal(t, 1, len(msg.unverifiedTxGroup))
require.Equal(t, stxn, msg.unverifiedTxGroup[0])
// forge signature, ensure accepted
stxnForged, blobForged := forgeSig(t, &stxn, blob)
action = handler.processIncomingTxn(network.IncomingMessage{Data: blobForged})
require.Equal(t, network.OutgoingMessage{Action: network.Ignore}, action)
msg = <-handler.backlogQueue
require.Equal(t, 1, len(msg.unverifiedTxGroup))
require.Equal(t, stxnForged, msg.unverifiedTxGroup[0])
// make non-canonical encoding and ensure it is not accepted
blobNonCan := craftNonCanonical(t, &stxn, blob)
action = handler.processIncomingTxn(network.IncomingMessage{Data: blobNonCan})
require.Equal(t, network.OutgoingMessage{Action: network.Ignore}, action)
require.Len(t, handler.backlogQueue, 0)
})
t.Run("group", func(t *testing.T) {
handler := makeTestTxHandlerOrphanedWithContext(context.Background(), txBacklogSize, txBacklogSize, txHandlerConfig{true, true}, 0)
num := rand.Intn(config.MaxTxGroupSize-1) + 2 // 2..config.MaxTxGroupSize
require.LessOrEqual(t, num, config.MaxTxGroupSize)
stxns, blob := makeRandomTransactions(num)
action := handler.processIncomingTxn(network.IncomingMessage{Data: blob})
require.Equal(t, network.OutgoingMessage{Action: network.Ignore}, action)
msg := <-handler.backlogQueue
require.Equal(t, num, len(msg.unverifiedTxGroup))
for i := 0; i < num; i++ {
require.Equal(t, stxns[i], msg.unverifiedTxGroup[i])
}
// swap two txns
i := rand.Intn(num / 2)
j := rand.Intn(num-num/2) + num/2
require.Less(t, i, j)
swapped := make([]transactions.SignedTxn, num)
copied := copy(swapped, stxns)
require.Equal(t, num, copied)
swapped[i], swapped[j] = swapped[j], swapped[i]
blobSwapped := encodeGroup(t, swapped, blob)
action = handler.processIncomingTxn(network.IncomingMessage{Data: blobSwapped})
require.Equal(t, network.OutgoingMessage{Action: network.Ignore}, action)
require.Len(t, handler.backlogQueue, 1)
msg = <-handler.backlogQueue
require.Equal(t, num, len(msg.unverifiedTxGroup))
for i := 0; i < num; i++ {
require.Equal(t, swapped[i], msg.unverifiedTxGroup[i])
}
// forge signature, ensure accepted
i = rand.Intn(num)
forged := make([]transactions.SignedTxn, num)
copied = copy(forged, stxns)
require.Equal(t, num, copied)
crypto.RandBytes(forged[i].Sig[:])
blobForged := encodeGroup(t, forged, blob)
action = handler.processIncomingTxn(network.IncomingMessage{Data: blobForged})
require.Equal(t, network.OutgoingMessage{Action: network.Ignore}, action)
require.Len(t, handler.backlogQueue, 1)
msg = <-handler.backlogQueue
require.Equal(t, num, len(msg.unverifiedTxGroup))
for i := 0; i < num; i++ {
require.Equal(t, forged[i], msg.unverifiedTxGroup[i])
}
// make non-canonical encoding and ensure it is not accepted
i = rand.Intn(num)
nonCan := make([]transactions.SignedTxn, num)
copied = copy(nonCan, stxns)
require.Equal(t, num, copied)
blobNonCan := make([]byte, 0, len(blob))
for j := 0; j < num; j++ {
enc := protocol.Encode(&nonCan[j])
if j == i {
enc = craftNonCanonical(t, &stxns[j], enc)
}
blobNonCan = append(blobNonCan, enc...)
}
require.Len(t, blobNonCan, len(blob))
require.NotEqual(t, blob, blobNonCan)
action = handler.processIncomingTxn(network.IncomingMessage{Data: blobNonCan})
require.Equal(t, network.OutgoingMessage{Action: network.Ignore}, action)
require.Len(t, handler.backlogQueue, 0)
})
}
// makeTestTxHandlerOrphaned creates a tx handler without any backlog consumer.
// It is caller responsibility to run a consumer thread.
func makeTestTxHandlerOrphaned(backlogSize int) *TxHandler {
return makeTestTxHandlerOrphanedWithContext(context.Background(), txBacklogSize, txBacklogSize, txHandlerConfig{true, false}, 0)
}
func makeTestTxHandlerOrphanedWithContext(ctx context.Context, backlogSize int, cacheSize int, txHandlerConfig txHandlerConfig, refreshInterval time.Duration) *TxHandler {
if backlogSize <= 0 {
backlogSize = txBacklogSize
}
if cacheSize <= 0 {
cacheSize = txBacklogSize
}
handler := &TxHandler{
backlogQueue: make(chan *txBacklogMsg, backlogSize),
}
if txHandlerConfig.enableFilteringRawMsg {
handler.msgCache = makeSaltedCache(cacheSize)
handler.msgCache.Start(ctx, refreshInterval)
}
if txHandlerConfig.enableFilteringCanonical {
handler.txCanonicalCache = makeDigestCache(cacheSize)
}
return handler
}
func makeTestTxHandler(dl *Ledger, cfg config.Local) (*TxHandler, error) {
tp := pools.MakeTransactionPool(dl.Ledger, cfg, logging.Base())
backlogPool := execpool.MakeBacklog(nil, 0, execpool.LowPriority, nil)
opts := TxHandlerOpts{
tp, backlogPool, dl, &mocks.MockNetwork{}, "", crypto.Digest{}, cfg,
}
return MakeTxHandler(opts)
}
func TestTxHandlerProcessIncomingCache(t *testing.T) {
partitiontest.PartitionTest(t)
t.Parallel()
handler := makeTestTxHandlerOrphaned(20)
var action network.OutgoingMessage
var msg *txBacklogMsg
// double enqueue a single txn message, ensure it discarded
stxns1, blob1 := makeRandomTransactions(1)
require.Equal(t, 1, len(stxns1))
action = handler.processIncomingTxn(network.IncomingMessage{Data: blob1})
require.Equal(t, network.OutgoingMessage{Action: network.Ignore}, action)
require.Equal(t, 1, len(handler.backlogQueue))
action = handler.processIncomingTxn(network.IncomingMessage{Data: blob1})
require.Equal(t, network.OutgoingMessage{Action: network.Ignore}, action)
require.Equal(t, 1, len(handler.backlogQueue))
msg = <-handler.backlogQueue
require.Equal(t, 1, len(msg.unverifiedTxGroup))
require.Equal(t, stxns1[0], msg.unverifiedTxGroup[0])
// double enqueue a two txns message
stxns2, blob2 := makeRandomTransactions(2)
require.Equal(t, 2, len(stxns2))
action = handler.processIncomingTxn(network.IncomingMessage{Data: blob2})
require.Equal(t, network.OutgoingMessage{Action: network.Ignore}, action)
require.Equal(t, 1, len(handler.backlogQueue))
action = handler.processIncomingTxn(network.IncomingMessage{Data: blob2})
require.Equal(t, network.OutgoingMessage{Action: network.Ignore}, action)
require.Equal(t, 1, len(handler.backlogQueue))
msg = <-handler.backlogQueue
require.Equal(t, 2, len(msg.unverifiedTxGroup))
require.Equal(t, stxns2[0], msg.unverifiedTxGroup[0])
require.Equal(t, stxns2[1], msg.unverifiedTxGroup[1])
// now combine seen and not seen txns, ensure the group is still enqueued
stxns3, _ := makeRandomTransactions(2)
require.Equal(t, 2, len(stxns3))
stxns3[1] = stxns1[0]
var blob3 []byte
for i := range stxns3 {
encoded := protocol.Encode(&stxns3[i])
blob3 = append(blob3, encoded...)
}
require.Greater(t, len(blob3), 0)
action = handler.processIncomingTxn(network.IncomingMessage{Data: blob3})
require.Equal(t, network.OutgoingMessage{Action: network.Ignore}, action)
require.Equal(t, 1, len(handler.backlogQueue))
msg = <-handler.backlogQueue
require.Equal(t, 2, len(msg.unverifiedTxGroup))
require.Equal(t, stxns3[0], msg.unverifiedTxGroup[0])
require.Equal(t, stxns3[1], msg.unverifiedTxGroup[1])
// check a combo from two different seen groups, ensure the group is still enqueued
stxns4 := make([]transactions.SignedTxn, 2)
stxns4[0] = stxns2[0]
stxns4[1] = stxns3[0]
var blob4 []byte
for i := range stxns4 {
encoded := protocol.Encode(&stxns4[i])
blob4 = append(blob4, encoded...)
}
require.Greater(t, len(blob4), 0)
action = handler.processIncomingTxn(network.IncomingMessage{Data: blob4})
require.Equal(t, network.OutgoingMessage{Action: network.Ignore}, action)
require.Equal(t, 1, len(handler.backlogQueue))
msg = <-handler.backlogQueue
require.Equal(t, 2, len(msg.unverifiedTxGroup))
require.Equal(t, stxns4[0], msg.unverifiedTxGroup[0])
require.Equal(t, stxns4[1], msg.unverifiedTxGroup[1])
}
func TestTxHandlerProcessIncomingCacheRotation(t *testing.T) {
partitiontest.PartitionTest(t)
t.Parallel()
stxns1, blob1 := makeRandomTransactions(1)
require.Equal(t, 1, len(stxns1))
resetCanonical := func(handler *TxHandler) {
handler.txCanonicalCache.swap()
handler.txCanonicalCache.swap()
}
t.Run("scheduled", func(t *testing.T) {
// double enqueue a single txn message, ensure it discarded
ctx, cancelFunc := context.WithCancel(context.Background())
defer cancelFunc()
handler := makeTestTxHandlerOrphanedWithContext(ctx, txBacklogSize, txBacklogSize, txHandlerConfig{true, true}, 10*time.Millisecond)
var action network.OutgoingMessage
var msg *txBacklogMsg
action = handler.processIncomingTxn(network.IncomingMessage{Data: blob1})
require.Equal(t, network.OutgoingMessage{Action: network.Ignore}, action)
require.Equal(t, 1, len(handler.backlogQueue))
resetCanonical(handler)
action = handler.processIncomingTxn(network.IncomingMessage{Data: blob1})
require.Equal(t, network.OutgoingMessage{Action: network.Ignore}, action)
require.Equal(t, 1, len(handler.backlogQueue))
msg = <-handler.backlogQueue
require.Equal(t, 1, len(msg.unverifiedTxGroup))
require.Equal(t, stxns1[0], msg.unverifiedTxGroup[0])
})
t.Run("manual", func(t *testing.T) {
// double enqueue a single txn message, ensure it discarded
ctx, cancelFunc := context.WithCancel(context.Background())
defer cancelFunc()
handler := makeTestTxHandlerOrphanedWithContext(ctx, txBacklogSize, txBacklogSize, txHandlerConfig{true, true}, 10*time.Millisecond)
var action network.OutgoingMessage
var msg *txBacklogMsg
action = handler.processIncomingTxn(network.IncomingMessage{Data: blob1})
require.Equal(t, network.OutgoingMessage{Action: network.Ignore}, action)
require.Equal(t, 1, len(handler.backlogQueue))
resetCanonical(handler)
action = handler.processIncomingTxn(network.IncomingMessage{Data: blob1})
require.Equal(t, network.OutgoingMessage{Action: network.Ignore}, action)
require.Equal(t, 1, len(handler.backlogQueue))
msg = <-handler.backlogQueue
require.Equal(t, 1, len(msg.unverifiedTxGroup))
require.Equal(t, stxns1[0], msg.unverifiedTxGroup[0])
// rotate once, ensure the txn still there
handler.msgCache.Remix()
resetCanonical(handler)
action = handler.processIncomingTxn(network.IncomingMessage{Data: blob1})
require.Equal(t, network.OutgoingMessage{Action: network.Ignore}, action)
require.Equal(t, 0, len(handler.backlogQueue))
// rotate twice, ensure the txn done
handler.msgCache.Remix()
resetCanonical(handler)
action = handler.processIncomingTxn(network.IncomingMessage{Data: blob1})
require.Equal(t, network.OutgoingMessage{Action: network.Ignore}, action)
require.Equal(t, 1, len(handler.backlogQueue))
resetCanonical(handler)
action = handler.processIncomingTxn(network.IncomingMessage{Data: blob1})
require.Equal(t, network.OutgoingMessage{Action: network.Ignore}, action)
require.Equal(t, 1, len(handler.backlogQueue))
msg = <-handler.backlogQueue
require.Equal(t, 1, len(msg.unverifiedTxGroup))
require.Equal(t, stxns1[0], msg.unverifiedTxGroup[0])
})
}
// TestTxHandlerProcessIncomingCacheBacklogDrop checks if dropped messages are also removed from caches
func TestTxHandlerProcessIncomingCacheBacklogDrop(t *testing.T) {
partitiontest.PartitionTest(t)
handler := makeTestTxHandlerOrphanedWithContext(context.Background(), 1, 20, txHandlerConfig{true, true}, 0)
stxns1, blob1 := makeRandomTransactions(1)
require.Equal(t, 1, len(stxns1))
action := handler.processIncomingTxn(network.IncomingMessage{Data: blob1})
require.Equal(t, network.OutgoingMessage{Action: network.Ignore}, action)
require.Equal(t, 1, len(handler.backlogQueue))
require.Equal(t, 1, handler.msgCache.Len())
require.Equal(t, 1, handler.txCanonicalCache.Len())
stxns2, blob2 := makeRandomTransactions(1)
require.Equal(t, 1, len(stxns2))
initialValue := transactionMessagesDroppedFromBacklog.GetUint64Value()