forked from algorand/go-algorand
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathledger_test.go
1774 lines (1493 loc) · 60 KB
/
ledger_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-2022 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 ledger
import (
"context"
"fmt"
"io/ioutil"
"math/rand"
"os"
"runtime/pprof"
"testing"
"github.com/algorand/go-algorand/data/account"
"github.com/algorand/go-algorand/util/db"
"github.com/stretchr/testify/require"
"github.com/algorand/go-algorand/agreement"
"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/transactions"
"github.com/algorand/go-algorand/data/transactions/logic"
"github.com/algorand/go-algorand/data/transactions/verify"
"github.com/algorand/go-algorand/ledger/ledgercore"
ledgertesting "github.com/algorand/go-algorand/ledger/testing"
"github.com/algorand/go-algorand/logging"
"github.com/algorand/go-algorand/protocol"
"github.com/algorand/go-algorand/test/partitiontest"
"github.com/algorand/go-algorand/util/execpool"
)
func sign(secrets map[basics.Address]*crypto.SignatureSecrets, t transactions.Transaction) transactions.SignedTxn {
var sig crypto.Signature
_, ok := secrets[t.Sender]
if ok {
sig = secrets[t.Sender].Sign(t)
}
return transactions.SignedTxn{
Txn: t,
Sig: sig,
}
}
func (l *Ledger) appendUnvalidated(blk bookkeeping.Block) error {
backlogPool := execpool.MakeBacklog(nil, 0, execpool.LowPriority, nil)
defer backlogPool.Shutdown()
l.verifiedTxnCache = verify.GetMockedCache(false)
vb, err := l.Validate(context.Background(), blk, backlogPool)
if err != nil {
return fmt.Errorf("appendUnvalidated error in Validate: %s", err.Error())
}
return l.AddValidatedBlock(*vb, agreement.Certificate{})
}
func (l *Ledger) appendUnvalidatedTx(t *testing.T, initAccounts map[basics.Address]basics.AccountData, initSecrets map[basics.Address]*crypto.SignatureSecrets, tx transactions.Transaction, ad transactions.ApplyData) error {
stx := sign(initSecrets, tx)
return l.appendUnvalidatedSignedTx(t, initAccounts, stx, ad)
}
func initNextBlockHeader(correctHeader *bookkeeping.BlockHeader, lastBlock bookkeeping.Block, proto config.ConsensusParams) {
if proto.TxnCounter {
correctHeader.TxnCounter = lastBlock.TxnCounter
}
if proto.CompactCertRounds > 0 {
var ccBasic bookkeeping.CompactCertState
if lastBlock.CompactCert[protocol.CompactCertBasic].CompactCertNextRound == 0 {
ccBasic.CompactCertNextRound = (correctHeader.Round + basics.Round(proto.CompactCertVotersLookback)).RoundUpToMultipleOf(basics.Round(proto.CompactCertRounds)) + basics.Round(proto.CompactCertRounds)
} else {
ccBasic.CompactCertNextRound = lastBlock.CompactCert[protocol.CompactCertBasic].CompactCertNextRound
}
correctHeader.CompactCert = map[protocol.CompactCertType]bookkeeping.CompactCertState{
protocol.CompactCertBasic: ccBasic,
}
}
}
func makeNewEmptyBlock(t *testing.T, l *Ledger, GenesisID string, initAccounts map[basics.Address]basics.AccountData) (blk bookkeeping.Block) {
a := require.New(t)
lastBlock, err := l.Block(l.Latest())
a.NoError(err, "could not get last block")
proto := config.Consensus[lastBlock.CurrentProtocol]
poolAddr := testPoolAddr
var totalRewardUnits uint64
if l.Latest() == 0 {
require.NotNil(t, initAccounts)
for _, acctdata := range initAccounts {
if acctdata.Status != basics.NotParticipating {
totalRewardUnits += acctdata.MicroAlgos.RewardUnits(proto)
}
}
} else {
latestRound, totals, err := l.LatestTotals()
require.NoError(t, err)
require.Equal(t, l.Latest(), latestRound)
totalRewardUnits = totals.RewardUnits()
}
poolBal, _, _, err := l.LookupLatest(poolAddr)
a.NoError(err, "could not get incentive pool balance")
blk.BlockHeader = bookkeeping.BlockHeader{
GenesisID: GenesisID,
Round: l.Latest() + 1,
Branch: lastBlock.Hash(),
TimeStamp: 0,
RewardsState: lastBlock.NextRewardsState(l.Latest()+1, proto, poolBal.MicroAlgos, totalRewardUnits, logging.Base()),
UpgradeState: lastBlock.UpgradeState,
// Seed: does not matter,
// UpgradeVote: empty,
}
blk.TxnCommitments, err = blk.PaysetCommit()
require.NoError(t, err)
if proto.SupportGenesisHash {
blk.BlockHeader.GenesisHash = crypto.Hash([]byte(GenesisID))
}
initNextBlockHeader(&blk.BlockHeader, lastBlock, proto)
blk.RewardsPool = testPoolAddr
blk.FeeSink = testSinkAddr
blk.CurrentProtocol = lastBlock.CurrentProtocol
return
}
func (l *Ledger) appendUnvalidatedSignedTx(t *testing.T, initAccounts map[basics.Address]basics.AccountData, stx transactions.SignedTxn, ad transactions.ApplyData) error {
blk := makeNewEmptyBlock(t, l, t.Name(), initAccounts)
proto := config.Consensus[blk.CurrentProtocol]
txib, err := blk.EncodeSignedTxn(stx, ad)
if err != nil {
return fmt.Errorf("could not sign txn: %s", err.Error())
}
if proto.TxnCounter {
blk.TxnCounter = blk.TxnCounter + 1
}
blk.Payset = append(blk.Payset, txib)
blk.TxnCommitments, err = blk.PaysetCommit()
require.NoError(t, err)
return l.appendUnvalidated(blk)
}
func (l *Ledger) addBlockTxns(t *testing.T, accounts map[basics.Address]basics.AccountData, stxns []transactions.SignedTxn, ad transactions.ApplyData) error {
blk := makeNewEmptyBlock(t, l, t.Name(), accounts)
proto := config.Consensus[blk.CurrentProtocol]
for _, stx := range stxns {
txib, err := blk.EncodeSignedTxn(stx, ad)
if err != nil {
return fmt.Errorf("could not sign txn: %s", err.Error())
}
if proto.TxnCounter {
blk.TxnCounter = blk.TxnCounter + 1
}
blk.Payset = append(blk.Payset, txib)
}
var err error
blk.TxnCommitments, err = blk.PaysetCommit()
require.NoError(t, err)
return l.AddBlock(blk, agreement.Certificate{})
}
func TestLedgerBasic(t *testing.T) {
partitiontest.PartitionTest(t)
genesisInitState, _ := ledgertesting.GenerateInitState(t, protocol.ConsensusCurrentVersion, 100)
const inMem = true
cfg := config.GetDefaultLocal()
cfg.Archival = true
log := logging.TestingLog(t)
l, err := OpenLedger(log, t.Name(), inMem, genesisInitState, cfg)
require.NoError(t, err, "could not open ledger")
defer l.Close()
}
func TestLedgerBlockHeaders(t *testing.T) {
partitiontest.PartitionTest(t)
a := require.New(t)
genesisInitState, _ := ledgertesting.GenerateInitState(t, protocol.ConsensusCurrentVersion, 100)
const inMem = true
cfg := config.GetDefaultLocal()
cfg.Archival = true
l, err := OpenLedger(logging.Base(), t.Name(), inMem, genesisInitState, cfg)
a.NoError(err, "could not open ledger")
defer l.Close()
lastBlock, err := l.Block(l.Latest())
a.NoError(err, "could not get last block")
proto := config.Consensus[protocol.ConsensusCurrentVersion]
poolAddr := testPoolAddr
var totalRewardUnits uint64
for _, acctdata := range genesisInitState.Accounts {
totalRewardUnits += acctdata.MicroAlgos.RewardUnits(proto)
}
poolBal, _, _, err := l.LookupLatest(poolAddr)
a.NoError(err, "could not get incentive pool balance")
correctHeader := bookkeeping.BlockHeader{
GenesisID: t.Name(),
Round: l.Latest() + 1,
Branch: lastBlock.Hash(),
TimeStamp: 0,
RewardsState: lastBlock.NextRewardsState(l.Latest()+1, proto, poolBal.MicroAlgos, totalRewardUnits, logging.Base()),
UpgradeState: lastBlock.UpgradeState,
// Seed: does not matter,
// UpgradeVote: empty,
}
emptyBlock := bookkeeping.Block{
BlockHeader: correctHeader,
}
correctHeader.TxnCommitments, err = emptyBlock.PaysetCommit()
require.NoError(t, err)
correctHeader.RewardsPool = testPoolAddr
correctHeader.FeeSink = testSinkAddr
if proto.SupportGenesisHash {
correctHeader.GenesisHash = crypto.Hash([]byte(t.Name()))
}
initNextBlockHeader(&correctHeader, lastBlock, proto)
var badBlock bookkeeping.Block
badBlock = bookkeeping.Block{BlockHeader: correctHeader}
badBlock.BlockHeader.Round++
a.Error(l.appendUnvalidated(badBlock), "added block header with round that was too high")
badBlock = bookkeeping.Block{BlockHeader: correctHeader}
badBlock.BlockHeader.Round--
a.Error(l.appendUnvalidated(badBlock), "added block header with round that was too low")
badBlock = bookkeeping.Block{BlockHeader: correctHeader}
badBlock.BlockHeader.Round = 0
a.Error(l.appendUnvalidated(badBlock), "added block header with round 0")
badBlock = bookkeeping.Block{BlockHeader: correctHeader}
badBlock.BlockHeader.GenesisID = ""
a.Error(l.appendUnvalidated(badBlock), "added block header with empty genesis ID")
badBlock = bookkeeping.Block{BlockHeader: correctHeader}
badBlock.BlockHeader.GenesisID = "incorrect"
a.Error(l.appendUnvalidated(badBlock), "added block header with incorrect genesis ID")
badBlock = bookkeeping.Block{BlockHeader: correctHeader}
badBlock.BlockHeader.UpgradePropose = "invalid"
a.Error(l.appendUnvalidated(badBlock), "added block header with invalid upgrade proposal")
badBlock = bookkeeping.Block{BlockHeader: correctHeader}
badBlock.BlockHeader.UpgradeApprove = true
a.Error(l.appendUnvalidated(badBlock), "added block header with upgrade approve set but no open upgrade")
badBlock = bookkeeping.Block{BlockHeader: correctHeader}
badBlock.BlockHeader.CurrentProtocol = "incorrect"
a.Error(l.appendUnvalidated(badBlock), "added block header with incorrect current protocol")
badBlock = bookkeeping.Block{BlockHeader: correctHeader}
badBlock.BlockHeader.CurrentProtocol = ""
a.Error(l.appendUnvalidated(badBlock), "added block header with empty current protocol")
badBlock = bookkeeping.Block{BlockHeader: correctHeader}
badBlock.BlockHeader.NextProtocol = "incorrect"
a.Error(l.appendUnvalidated(badBlock), "added block header with incorrect next protocol")
badBlock = bookkeeping.Block{BlockHeader: correctHeader}
badBlock.BlockHeader.NextProtocolApprovals++
a.Error(l.appendUnvalidated(badBlock), "added block header with incorrect number of upgrade approvals")
badBlock = bookkeeping.Block{BlockHeader: correctHeader}
badBlock.BlockHeader.NextProtocolVoteBefore++
a.Error(l.appendUnvalidated(badBlock), "added block header with incorrect next protocol vote deadline")
badBlock = bookkeeping.Block{BlockHeader: correctHeader}
badBlock.BlockHeader.NextProtocolSwitchOn++
a.Error(l.appendUnvalidated(badBlock), "added block header with incorrect next protocol switch round")
// TODO test upgrade cases with a valid upgrade in progress
// TODO test timestamp bounds
badBlock = bookkeeping.Block{BlockHeader: correctHeader}
badBlock.BlockHeader.Branch = bookkeeping.BlockHash{}
a.Error(l.appendUnvalidated(badBlock), "added block header with empty previous-block hash")
badBlock = bookkeeping.Block{BlockHeader: correctHeader}
badBlock.BlockHeader.Branch[0]++
a.Error(l.appendUnvalidated(badBlock), "added block header with incorrect previous-block hash")
badBlock = bookkeeping.Block{BlockHeader: correctHeader}
badBlock.BlockHeader.RewardsLevel++
a.Error(l.appendUnvalidated(badBlock), "added block header with incorrect rewards level")
badBlock = bookkeeping.Block{BlockHeader: correctHeader}
badBlock.BlockHeader.RewardsRate++
a.Error(l.appendUnvalidated(badBlock), "added block header with incorrect rewards rate")
badBlock = bookkeeping.Block{BlockHeader: correctHeader}
badBlock.BlockHeader.RewardsResidue++
a.Error(l.appendUnvalidated(badBlock), "added block header with incorrect rewards residue")
// TODO test rewards cases with changing poolAddr money, with changing round, and with changing total reward units
badBlock = bookkeeping.Block{BlockHeader: correctHeader}
badBlock.BlockHeader.TxnCommitments.NativeSha512_256Commitment = crypto.Hash([]byte{0})
a.Error(l.appendUnvalidated(badBlock), "added block header with empty transaction root")
badBlock = bookkeeping.Block{BlockHeader: correctHeader}
badBlock.BlockHeader.TxnCommitments.NativeSha512_256Commitment[0]++
a.Error(l.appendUnvalidated(badBlock), "added block header with invalid transaction root")
correctBlock := bookkeeping.Block{BlockHeader: correctHeader}
a.NoError(l.appendUnvalidated(correctBlock), "could not add block with correct header")
}
func TestLedgerSingleTx(t *testing.T) {
partitiontest.PartitionTest(t)
a := require.New(t)
// V15 is the earliest protocol version in active use.
// The genesis for betanet and testnet is at V15
// The genesis for mainnet is at V17
genesisInitState, initSecrets := ledgertesting.GenerateInitState(t, protocol.ConsensusV15, 100)
const inMem = true
log := logging.TestingLog(t)
cfg := config.GetDefaultLocal()
cfg.Archival = true
l, err := OpenLedger(log, t.Name(), inMem, genesisInitState, cfg)
a.NoError(err, "could not open ledger")
defer l.Close()
proto := config.Consensus[protocol.ConsensusV7]
poolAddr := testPoolAddr
sinkAddr := testSinkAddr
initAccounts := genesisInitState.Accounts
var addrList []basics.Address
for addr := range initAccounts {
if addr != poolAddr && addr != sinkAddr {
addrList = append(addrList, addr)
}
}
correctTxHeader := transactions.Header{
Sender: addrList[0],
Fee: basics.MicroAlgos{Raw: proto.MinTxnFee * 2},
FirstValid: l.Latest() + 1,
LastValid: l.Latest() + 10,
GenesisID: t.Name(),
GenesisHash: genesisInitState.GenesisHash,
}
correctPayFields := transactions.PaymentTxnFields{
Receiver: addrList[1],
Amount: basics.MicroAlgos{Raw: initAccounts[addrList[0]].MicroAlgos.Raw / 10},
}
correctPay := transactions.Transaction{
Type: protocol.PaymentTx,
Header: correctTxHeader,
PaymentTxnFields: correctPayFields,
}
correctCloseFields := transactions.PaymentTxnFields{
CloseRemainderTo: addrList[2],
}
correctClose := transactions.Transaction{
Type: protocol.PaymentTx,
Header: correctTxHeader,
PaymentTxnFields: correctCloseFields,
}
var votePK crypto.OneTimeSignatureVerifier
var selPK crypto.VRFVerifier
votePK[0] = 1
selPK[0] = 2
correctKeyregFields := transactions.KeyregTxnFields{
VotePK: votePK,
SelectionPK: selPK,
VoteKeyDilution: proto.DefaultKeyDilution,
VoteFirst: 0,
VoteLast: 10000,
}
correctKeyreg := transactions.Transaction{
Type: protocol.KeyRegistrationTx,
Header: correctTxHeader,
KeyregTxnFields: correctKeyregFields,
}
correctKeyreg.Sender = addrList[1]
var badTx transactions.Transaction
var ad transactions.ApplyData
// TODO spend into dust, spend to self, close to self, close to receiver, overspend with fee, ...
badTx = correctPay
badTx.GenesisID = "invalid"
a.Error(l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad), "added tx with invalid genesis ID")
badTx = correctPay
badTx.Type = "invalid"
a.Error(l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad), "added tx with invalid tx type")
badTx = correctPay
badTx.KeyregTxnFields = correctKeyregFields
a.Error(l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad), "added pay tx with keyreg fields set")
badTx = correctKeyreg
badTx.PaymentTxnFields = correctPayFields
a.Error(l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad), "added keyreg tx with pay fields set")
badTx = correctKeyreg
badTx.PaymentTxnFields = correctCloseFields
a.Error(l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad), "added keyreg tx with pay (close) fields set")
badTx = correctPay
badTx.FirstValid = badTx.LastValid + 1
a.Error(l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad), "added tx with FirstValid > LastValid")
badTx = correctPay
badTx.LastValid += basics.Round(proto.MaxTxnLife)
a.Error(l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad), "added tx with overly long validity")
badTx = correctPay
badTx.LastValid = l.Latest()
a.Error(l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad), "added expired tx")
badTx = correctPay
badTx.FirstValid = l.Latest() + 2
a.Error(l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad), "added tx which is not valid yet")
badTx = correctPay
badTx.Note = make([]byte, proto.MaxTxnNoteBytes+1)
a.Error(l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad), "added tx with overly large note field")
badTx = correctPay
badTx.Sender = poolAddr
a.Error(l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad), "added tx send from tx pool")
badTx = correctPay
badTx.Sender = basics.Address{}
a.Error(l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad), "added tx send from zero address")
badTx = correctPay
badTx.Fee = basics.MicroAlgos{}
a.Error(l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad), "added tx with zero fee")
badTx = correctPay
badTx.Fee = basics.MicroAlgos{Raw: proto.MinTxnFee - 1}
a.Error(l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad), "added tx with fee below minimum")
badTx = correctKeyreg
fee, overflow := basics.OAddA(initAccounts[badTx.Sender].MicroAlgos, basics.MicroAlgos{Raw: 1})
a.False(overflow)
badTx.Fee = fee
a.Error(l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad), "added keyreg tx with fee above user balance")
// TODO try excessive spending given distribution of some number of rewards
badTx = correctPay
sbadTx := sign(initSecrets, badTx)
sbadTx.Sig = crypto.Signature{}
a.Error(l.appendUnvalidatedSignedTx(t, initAccounts, sbadTx, ad), "added tx with no signature")
badTx = correctPay
sbadTx = sign(initSecrets, badTx)
sbadTx.Sig[5]++
a.Error(l.appendUnvalidatedSignedTx(t, initAccounts, sbadTx, ad), "added tx with corrupt signature")
// TODO set multisig and test
badTx = correctPay
badTx.Sender = sinkAddr
a.Error(l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad), "sink spent to non-sink address")
badTx = correctPay
badTx.Sender = sinkAddr
badTx.CloseRemainderTo = addrList[0]
a.Error(l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad), "sink closed to non-sink address")
badTx = correctPay
badTx.Sender = sinkAddr
badTx.Receiver = poolAddr
badTx.CloseRemainderTo = addrList[0]
a.Error(l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad), "sink closed to non-sink address")
badTx = correctPay
badTx.Sender = sinkAddr
badTx.CloseRemainderTo = poolAddr
a.Error(l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad), "sink closed to pool address")
badTx = correctPay
remainder, overflow := basics.OSubA(initAccounts[badTx.Sender].MicroAlgos, badTx.Amount)
a.False(overflow)
fee, overflow = basics.OAddA(remainder, basics.MicroAlgos{Raw: 1})
a.False(overflow)
badTx.Fee = fee
a.Error(l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad), "overspent with (amount + fee)")
adClose := ad
adClose.ClosingAmount = initAccounts[correctClose.Sender].MicroAlgos
adClose.ClosingAmount, _ = basics.OSubA(adClose.ClosingAmount, correctPay.Amount)
adClose.ClosingAmount, _ = basics.OSubA(adClose.ClosingAmount, correctPay.Fee)
adClose.ClosingAmount, _ = basics.OSubA(adClose.ClosingAmount, correctClose.Amount)
adClose.ClosingAmount, _ = basics.OSubA(adClose.ClosingAmount, correctClose.Fee)
a.NoError(l.appendUnvalidatedTx(t, initAccounts, initSecrets, correctPay, ad), "could not add payment transaction")
a.NoError(l.appendUnvalidatedTx(t, initAccounts, initSecrets, correctClose, adClose), "could not add close transaction")
a.NoError(l.appendUnvalidatedTx(t, initAccounts, initSecrets, correctKeyreg, ad), "could not add key registration")
correctPay.Sender = sinkAddr
correctPay.Receiver = poolAddr
a.NoError(l.appendUnvalidatedTx(t, initAccounts, initSecrets, correctPay, ad), "could not spend from sink to pool")
a.Error(l.appendUnvalidatedTx(t, initAccounts, initSecrets, correctKeyreg, ad), "added duplicate tx")
}
func TestLedgerSingleTxV24(t *testing.T) {
partitiontest.PartitionTest(t)
a := require.New(t)
protoName := protocol.ConsensusV24
genesisInitState, initSecrets := ledgertesting.GenerateInitState(t, protoName, 100)
const inMem = true
log := logging.TestingLog(t)
cfg := config.GetDefaultLocal()
cfg.Archival = true
l, err := OpenLedger(log, t.Name(), inMem, genesisInitState, cfg)
a.NoError(err, "could not open ledger")
defer l.Close()
proto := config.Consensus[protoName]
poolAddr := testPoolAddr
sinkAddr := testSinkAddr
initAccounts := genesisInitState.Accounts
var addrList []basics.Address
for addr := range initAccounts {
if addr != poolAddr && addr != sinkAddr {
addrList = append(addrList, addr)
}
}
correctTxHeader := transactions.Header{
Sender: addrList[0],
Fee: basics.MicroAlgos{Raw: proto.MinTxnFee * 2},
FirstValid: l.Latest() + 1,
LastValid: l.Latest() + 10,
GenesisID: t.Name(),
GenesisHash: genesisInitState.GenesisHash,
}
assetParam := basics.AssetParams{
Total: 100,
UnitName: "unit",
Manager: addrList[0],
}
correctAssetConfigFields := transactions.AssetConfigTxnFields{
AssetParams: assetParam,
}
correctAssetConfig := transactions.Transaction{
Type: protocol.AssetConfigTx,
Header: correctTxHeader,
AssetConfigTxnFields: correctAssetConfigFields,
}
correctAssetTransferFields := transactions.AssetTransferTxnFields{
AssetAmount: 10,
AssetReceiver: addrList[1],
}
correctAssetTransfer := transactions.Transaction{
Type: protocol.AssetTransferTx,
Header: correctTxHeader,
AssetTransferTxnFields: correctAssetTransferFields,
}
approvalProgram := []byte("\x02\x20\x01\x01\x22") // int 1
clearStateProgram := []byte("\x02") // empty
correctAppCreateFields := transactions.ApplicationCallTxnFields{
ApprovalProgram: approvalProgram,
ClearStateProgram: clearStateProgram,
}
correctAppCreate := transactions.Transaction{
Type: protocol.ApplicationCallTx,
Header: correctTxHeader,
ApplicationCallTxnFields: correctAppCreateFields,
}
correctAppCallFields := transactions.ApplicationCallTxnFields{
OnCompletion: 0,
}
correctAppCall := transactions.Transaction{
Type: protocol.ApplicationCallTx,
Header: correctTxHeader,
ApplicationCallTxnFields: correctAppCallFields,
}
var badTx transactions.Transaction
var ad transactions.ApplyData
var assetIdx basics.AssetIndex
var appIdx basics.AppIndex
a.NoError(l.appendUnvalidatedTx(t, initAccounts, initSecrets, correctAssetConfig, ad))
assetIdx = 1 // the first txn
badTx = correctAssetConfig
badTx.ConfigAsset = 2
err = l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad)
a.Error(err)
a.Contains(err.Error(), "asset 2 does not exist or has been deleted")
badTx = correctAssetConfig
badTx.ConfigAsset = assetIdx
badTx.AssetFrozen = true
err = l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad)
a.Error(err)
a.Contains(err.Error(), "type acfg has non-zero fields for type afrz")
badTx = correctAssetConfig
badTx.ConfigAsset = assetIdx
badTx.Sender = addrList[1]
badTx.AssetParams.Freeze = addrList[0]
err = l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad)
a.Error(err)
a.Contains(err.Error(), "this transaction should be issued by the manager")
badTx = correctAssetConfig
badTx.AssetParams.UnitName = "very long unit name that exceeds the limit"
err = l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad)
a.Error(err)
a.Contains(err.Error(), "transaction asset unit name too big: 42 > 8")
badTx = correctAssetTransfer
badTx.XferAsset = assetIdx
badTx.AssetAmount = 101
err = l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad)
a.Error(err)
a.Contains(err.Error(), "underflow on subtracting 101 from sender amount 100")
badTx = correctAssetTransfer
badTx.XferAsset = assetIdx
err = l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad)
a.Error(err)
a.Contains(err.Error(), fmt.Sprintf("asset %d missing from", assetIdx))
a.NoError(l.appendUnvalidatedTx(t, initAccounts, initSecrets, correctAppCreate, ad))
appIdx = 2 // the second successful txn
badTx = correctAppCreate
program := make([]byte, len(approvalProgram))
copy(program, approvalProgram)
program[0] = '\x01'
badTx.ApprovalProgram = program
err = l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad)
a.Error(err)
a.Contains(err.Error(), "program version must be >= 2")
badTx = correctAppCreate
badTx.ApplicationID = appIdx
err = l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad)
a.Error(err)
a.Contains(err.Error(), "programs may only be specified during application creation or update")
badTx = correctAppCall
badTx.ApplicationID = 0
err = l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad)
a.Error(err)
a.Contains(err.Error(), "ApprovalProgram: invalid program (empty)")
badTx.ApprovalProgram = []byte{242}
err = l.appendUnvalidatedTx(t, initAccounts, initSecrets, badTx, ad)
a.Error(err)
a.Contains(err.Error(), "ApprovalProgram: invalid version")
correctAppCall.ApplicationID = appIdx
a.NoError(l.appendUnvalidatedTx(t, initAccounts, initSecrets, correctAppCall, ad))
}
func addEmptyValidatedBlock(t *testing.T, l *Ledger, initAccounts map[basics.Address]basics.AccountData) {
a := require.New(t)
backlogPool := execpool.MakeBacklog(nil, 0, execpool.LowPriority, nil)
defer backlogPool.Shutdown()
blk := makeNewEmptyBlock(t, l, t.Name(), initAccounts)
vb, err := l.Validate(context.Background(), blk, backlogPool)
a.NoError(err)
err = l.AddValidatedBlock(*vb, agreement.Certificate{})
a.NoError(err)
}
// TestLedgerAppCrossRoundWrites ensures app state writes survive between rounds
func TestLedgerAppCrossRoundWrites(t *testing.T) {
partitiontest.PartitionTest(t)
a := require.New(t)
protoName := protocol.ConsensusV24
genesisInitState, initSecrets := ledgertesting.GenerateInitState(t, protoName, 100)
const inMem = true
log := logging.TestingLog(t)
cfg := config.GetDefaultLocal()
cfg.Archival = true
l, err := OpenLedger(log, t.Name(), inMem, genesisInitState, cfg)
a.NoError(err, "could not open ledger")
defer l.Close()
proto := config.Consensus[protoName]
poolAddr := testPoolAddr
sinkAddr := testSinkAddr
initAccounts := genesisInitState.Accounts
var addrList []basics.Address
for addr := range initAccounts {
if addr != poolAddr && addr != sinkAddr {
addrList = append(addrList, addr)
}
}
creator := addrList[0]
user := addrList[1]
correctTxHeader := transactions.Header{
Sender: creator,
Fee: basics.MicroAlgos{Raw: proto.MinTxnFee * 2},
FirstValid: l.Latest() + 1,
LastValid: l.Latest() + 10,
GenesisID: t.Name(),
GenesisHash: genesisInitState.GenesisHash,
}
counter := `#pragma version 2
// a simple global and local calls counter app
byte "counter"
dup
app_global_get
int 1
+
app_global_put // update the counter
int 0
int 0
app_opted_in
bnz opted_in
int 1
return
opted_in:
int 0 // account idx for app_local_put
byte "counter"
int 0
byte "counter"
app_local_get
int 1 // increment
+
app_local_put
int 1
`
ops, err := logic.AssembleString(counter)
a.NoError(err)
approvalProgram := ops.Program
clearStateProgram := []byte("\x02") // empty
appcreateFields := transactions.ApplicationCallTxnFields{
ApprovalProgram: approvalProgram,
ClearStateProgram: clearStateProgram,
GlobalStateSchema: basics.StateSchema{NumUint: 1},
LocalStateSchema: basics.StateSchema{NumUint: 1},
}
appcreate := transactions.Transaction{
Type: protocol.ApplicationCallTx,
Header: correctTxHeader,
ApplicationCallTxnFields: appcreateFields,
}
ad := transactions.ApplyData{EvalDelta: transactions.EvalDelta{GlobalDelta: basics.StateDelta{
"counter": basics.ValueDelta{Action: basics.SetUintAction, Uint: 1},
}}}
a.NoError(l.appendUnvalidatedTx(t, initAccounts, initSecrets, appcreate, ad))
var appIdx basics.AppIndex = 1
rnd := l.Latest()
acctRes, err := l.LookupApplication(rnd, creator, appIdx)
a.NoError(err)
a.Equal(basics.TealValue{Type: basics.TealUintType, Uint: 1}, acctRes.AppParams.GlobalState["counter"])
addEmptyValidatedBlock(t, l, initAccounts)
addEmptyValidatedBlock(t, l, initAccounts)
appcallFields := transactions.ApplicationCallTxnFields{
OnCompletion: transactions.OptInOC,
}
correctTxHeader.Sender = user
appcall := transactions.Transaction{
Type: protocol.ApplicationCallTx,
Header: correctTxHeader,
ApplicationCallTxnFields: appcallFields,
}
appcall.ApplicationID = appIdx
ad = transactions.ApplyData{EvalDelta: transactions.EvalDelta{
GlobalDelta: basics.StateDelta{
"counter": basics.ValueDelta{Action: basics.SetUintAction, Uint: 2},
},
LocalDeltas: map[uint64]basics.StateDelta{
0: {
"counter": basics.ValueDelta{Action: basics.SetUintAction, Uint: 1},
},
},
}}
a.NoError(l.appendUnvalidatedTx(t, initAccounts, initSecrets, appcall, ad))
rnd = l.Latest()
acctworRes, err := l.LookupApplication(rnd, creator, appIdx)
a.NoError(err)
a.Equal(basics.TealValue{Type: basics.TealUintType, Uint: 2}, acctworRes.AppParams.GlobalState["counter"])
addEmptyValidatedBlock(t, l, initAccounts)
acctworRes, err = l.LookupApplication(l.Latest()-1, creator, appIdx)
a.NoError(err)
a.Equal(basics.TealValue{Type: basics.TealUintType, Uint: 2}, acctworRes.AppParams.GlobalState["counter"])
acctRes, err = l.LookupApplication(rnd, user, appIdx)
a.NoError(err)
a.Equal(basics.TealValue{Type: basics.TealUintType, Uint: 1}, acctRes.AppLocalState.KeyValue["counter"])
}
// TestLedgerAppMultiTxnWrites ensures app state writes in multiple txn are applied
func TestLedgerAppMultiTxnWrites(t *testing.T) {
partitiontest.PartitionTest(t)
a := require.New(t)
protoName := protocol.ConsensusV24
genesisInitState, initSecrets := ledgertesting.GenerateInitState(t, protoName, 100)
const inMem = true
log := logging.TestingLog(t)
cfg := config.GetDefaultLocal()
cfg.Archival = true
l, err := OpenLedger(log, t.Name(), inMem, genesisInitState, cfg)
a.NoError(err, "could not open ledger")
defer l.Close()
proto := config.Consensus[protoName]
poolAddr := testPoolAddr
sinkAddr := testSinkAddr
initAccounts := genesisInitState.Accounts
var addrList []basics.Address
for addr := range initAccounts {
if addr != poolAddr && addr != sinkAddr {
addrList = append(addrList, addr)
}
}
creator := addrList[0]
user := addrList[1]
genesisID := t.Name()
correctTxHeader := transactions.Header{
Sender: creator,
Fee: basics.MicroAlgos{Raw: proto.MinTxnFee * 2},
FirstValid: l.Latest() + 1,
LastValid: l.Latest() + 10,
GenesisID: genesisID,
GenesisHash: genesisInitState.GenesisHash,
}
value := byte(10)
sum := `#pragma version 2
// add a value from args to a key
byte "key" // [key]
dup // [key, key]
app_global_get // [key, val]
txna ApplicationArgs 0 // [key, val, arg]
btoi // [key, val, arg]
+ // [key, val+arg]
app_global_put // []
int 1 // [1]
`
ops, err := logic.AssembleString(sum)
a.NoError(err)
approvalProgram := ops.Program
clearStateProgram := []byte("\x02") // empty
appcreateFields := transactions.ApplicationCallTxnFields{
ApprovalProgram: approvalProgram,
ClearStateProgram: clearStateProgram,
GlobalStateSchema: basics.StateSchema{NumUint: 1},
ApplicationArgs: [][]byte{{value}},
}
correctTxHeader.Sender = creator
appcreate := transactions.Transaction{
Type: protocol.ApplicationCallTx,
Header: correctTxHeader,
ApplicationCallTxnFields: appcreateFields,
}
ad := transactions.ApplyData{EvalDelta: transactions.EvalDelta{GlobalDelta: basics.StateDelta{
"key": basics.ValueDelta{Action: basics.SetUintAction, Uint: uint64(value)},
}}}
a.NoError(l.appendUnvalidatedTx(t, initAccounts, initSecrets, appcreate, ad))
var appIdx basics.AppIndex = 1
rnd := l.Latest()
acctRes, err := l.LookupApplication(rnd, creator, appIdx)
a.NoError(err)
a.Equal(basics.TealValue{Type: basics.TealUintType, Uint: uint64(value)}, acctRes.AppParams.GlobalState["key"])
// make two app call txns and put into the same block, with and without groupping
var tests = []struct {
groupped bool
base byte
val1 byte
val2 byte
}{
{true, byte(value), byte(11), byte(17)},
{false, byte(value + 11 + 17), byte(13), byte(19)},
}
for _, test := range tests {
t.Run(fmt.Sprintf("groupped %v", test.groupped), func(t *testing.T) {
a := require.New(t)
base := test.base
value1 := test.val1
appcallFields1 := transactions.ApplicationCallTxnFields{
ApplicationID: appIdx,
OnCompletion: transactions.NoOpOC,
ApplicationArgs: [][]byte{{value1}},
}
correctTxHeader.Sender = creator
appcall1 := transactions.Transaction{
Type: protocol.ApplicationCallTx,
Header: correctTxHeader,
ApplicationCallTxnFields: appcallFields1,
}
ad1 := transactions.ApplyData{EvalDelta: transactions.EvalDelta{GlobalDelta: basics.StateDelta{
"key": basics.ValueDelta{Action: basics.SetUintAction, Uint: uint64(base + value1)},
}}}
value2 := test.val2
appcallFields2 := transactions.ApplicationCallTxnFields{
ApplicationID: appIdx,
OnCompletion: transactions.NoOpOC,
ApplicationArgs: [][]byte{{value2}},
}
correctTxHeader.Sender = user
appcall2 := transactions.Transaction{
Type: protocol.ApplicationCallTx,
Header: correctTxHeader,
ApplicationCallTxnFields: appcallFields2,
}
ad2 := transactions.ApplyData{EvalDelta: transactions.EvalDelta{GlobalDelta: basics.StateDelta{
"key": basics.ValueDelta{Action: basics.SetUintAction, Uint: uint64(base + value1 + value2)},
}}}
a.NotEqual(appcall1.Sender, appcall2.Sender)
if test.groupped {
var group transactions.TxGroup
group.TxGroupHashes = []crypto.Digest{crypto.HashObj(appcall1), crypto.HashObj(appcall2)}
appcall1.Group = crypto.HashObj(group)
appcall2.Group = crypto.HashObj(group)
}
stx1 := sign(initSecrets, appcall1)
stx2 := sign(initSecrets, appcall2)
blk := makeNewEmptyBlock(t, l, genesisID, initAccounts)
txib1, err := blk.EncodeSignedTxn(stx1, ad1)
a.NoError(err)
txib2, err := blk.EncodeSignedTxn(stx2, ad2)
a.NoError(err)
blk.TxnCounter = blk.TxnCounter + 2
blk.Payset = append(blk.Payset, txib1, txib2)
blk.TxnCommitments, err = blk.PaysetCommit()
a.NoError(err)