-
Notifications
You must be signed in to change notification settings - Fork 5
/
main_test.go
1219 lines (977 loc) · 35.1 KB
/
main_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
package main_test
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/gordian-engine/gcosmos/internal/copy/gtest"
"github.com/gordian-engine/gcosmos/internal/gci"
"github.com/stretchr/testify/require"
)
// Configuration for gordian consensus storage.
// If useMemstore=false and useSQLiteInMem=false,
// then on-disk storage is used with temporary database files.
// If only useSQLiteInMem is true,
// then all instances use the in-memory tmsqlite database.
// If only useMemstore is true, the tmmemstore stores are used.
// If both are true, the tests panic (see the following init function).
const (
useMemStore = false
useSQLiteInMem = false
)
func init() {
if useMemStore && useSQLiteInMem {
panic(fmt.Errorf(
"The useMemStore and useSQLiteInMem must both be false, or only one must be true (got useMemStore=%t and useSQLiteInMem=%t)",
useMemStore, useSQLiteInMem,
))
}
}
func TestRootCmd(t *testing.T) {
t.Parallel()
e := NewRootCmd(t, gtest.NewLogger(t))
e.Run("init", "defaultmoniker").NoError(t)
t.Skip("this is failing due an upstream SDK issue")
var err error
require.NotPanics(t, func() {
res := e.Run("--help")
t.Log(res.Stdout.String())
t.Log("------")
t.Log(res.Stderr.String())
err = res.Err
})
require.NoError(t, err)
}
func TestRootCmd_startWithGordian_singleValidator(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
c := ConfigureChain(t, ctx, ChainConfig{
ID: t.Name(),
NVals: 1,
StakeStrategy: ConstantStakeStrategy(1_000_000_000),
})
httpAddr := c.Start(t, ctx, 1).HTTP[0]
if !gci.RunCometInsteadOfGordian {
u := "http://" + httpAddr + "/blocks/watermark"
// TODO: we might need to delay until we get a non-error HTTP response.
deadline := time.Now().Add(10 * time.Second)
var maxHeight uint
for time.Now().Before(deadline) {
resp, err := http.Get(u)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
var m map[string]uint
require.NoError(t, json.NewDecoder(resp.Body).Decode(&m))
resp.Body.Close()
maxHeight = m["VotingHeight"]
if maxHeight < 3 {
time.Sleep(100 * time.Millisecond)
continue
}
// We got at least to height 3, so quit the loop.
break
}
require.GreaterOrEqual(t, maxHeight, uint(3))
}
}
func TestRootCmd_startWithGordian_multipleValidators(t *testing.T) {
if testing.Short() {
t.Skip("skipping slow test in short mode")
}
const totalVals = 4
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
chainID := t.Name()
c := ConfigureChain(t, ctx, ChainConfig{
ID: chainID,
NVals: totalVals,
// Due to an outstanding and undocumented SDK bug,
// we require at least 11 validators.
// But, we don't want to run 11 validators.
// So put the majority of the stake in the first four validators,
// and the rest get the bare minimum.
StakeStrategy: func(idx int) string {
const minAmount = "1000000"
// Give every validator a slightly different amount,
// so that a tracked single vote's power can be distinguished.
return minAmount + fmt.Sprintf("%02d000000stake", idx)
},
})
ca := c.Start(t, ctx, totalVals)
httpAddrs := ca.HTTP
// Each validator must report a height beyond the first few blocks.
for i := range totalVals {
if gci.RunCometInsteadOfGordian {
// Nothing to check in this mode.
break
}
// Gratuitous deadline to get the voting height,
// because the first proposed block is likely to time out
// due to libp2p settle time.
u := "http://" + httpAddrs[i] + "/blocks/watermark"
deadline := time.Now().Add(30 * time.Second)
var maxHeight uint
for time.Now().Before(deadline) {
resp, err := http.Get(u)
require.NoErrorf(t, err, "failed to get the watermark for validator %d/%d", i+1, totalVals)
require.Equal(t, http.StatusOK, resp.StatusCode)
var m map[string]uint
require.NoError(t, json.NewDecoder(resp.Body).Decode(&m))
resp.Body.Close()
maxHeight = m["VotingHeight"]
if maxHeight < 4 {
time.Sleep(100 * time.Millisecond)
continue
}
// We got at least to height 4, so quit the loop.
break
}
require.GreaterOrEqualf(t, maxHeight, uint(4), "checking max block height on validator at index %d", i)
}
t.Run("adding a new validator catches up", func(t *testing.T) {
if gci.RunCometInsteadOfGordian {
t.Skip("skipping due to not testing Gordian")
}
localCtx, cancel := context.WithCancel(ctx)
defer cancel()
lateHTTPAddrFile := AddLateNode(t, localCtx, chainID, c.CanonicalGenesisPath, ca.P2PSeedPath)
var httpAddr string
deadline := time.Now().Add(10 * time.Second)
for time.Now().Before(deadline) {
b, err := os.ReadFile(lateHTTPAddrFile)
if err != nil {
time.Sleep(100 * time.Millisecond)
continue
}
s, ok := strings.CutSuffix(string(b), "\n")
if !ok {
time.Sleep(100 * time.Millisecond)
continue
}
httpAddr = s
break
}
if httpAddr == "" {
t.Fatal("did not read http address from file before deadline")
}
u := "http://" + httpAddr + "/blocks/watermark"
// TODO: we might need to delay until we get a non-error HTTP response.
deadline = time.Now().Add(10 * time.Second)
var maxHeight uint
for time.Now().Before(deadline) {
resp, err := http.Get(u)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
var m map[string]uint
require.NoError(t, json.NewDecoder(resp.Body).Decode(&m))
resp.Body.Close()
maxHeight = m["VotingHeight"]
if maxHeight < 4 {
time.Sleep(100 * time.Millisecond)
continue
}
// We got at least to height 4, so quit the loop.
break
}
require.GreaterOrEqual(t, maxHeight, uint(4), "late-started server did not reach minimum height")
})
}
func Test_single_restart(t *testing.T) {
if testing.Short() {
t.Skip("skipping in short mode")
}
if gci.RunCometInsteadOfGordian {
// I mean, we could run it with Comet, but that doesn't seem worth the effort at this point.
t.Skip("can only run restart test with Gordian")
}
if useMemStore || useSQLiteInMem {
t.Skipf(
"can only test restart with on-disk storage (have useMemStore=%t, useSQLiteInMem=%t)",
useMemStore, useSQLiteInMem,
)
}
t.Parallel()
ctx1, cancel := context.WithCancel(context.Background())
defer cancel()
c := ConfigureChain(t, ctx1, ChainConfig{
ID: t.Name(),
NVals: 1,
StakeStrategy: ConstantStakeStrategy(1_000_000_000),
// TODO: once this is passing with height watermarks,
// set NFixedAccounts and confirm application state too.
})
httpAddr := c.Start(t, ctx1, 1).HTTP[0]
if !gci.RunCometInsteadOfGordian {
baseURL := "http://" + httpAddr
// Make sure we are beyond the initial height.
deadline := time.Now().Add(10 * time.Second)
var maxHeight uint
for time.Now().Before(deadline) {
resp, err := http.Get(baseURL + "/blocks/watermark")
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
var m map[string]uint
require.NoError(t, json.NewDecoder(resp.Body).Decode(&m))
resp.Body.Close()
maxHeight = m["VotingHeight"]
if maxHeight < 3 {
time.Sleep(100 * time.Millisecond)
continue
}
// We are past initial height, so break out of the loop.
break
}
require.GreaterOrEqual(t, maxHeight, uint(3))
expHeight := maxHeight
// Now cancel the context.
// We expect the HTTP server to quit within a moment.
cancel()
deadline = time.Now().Add(3 * time.Second)
gotError := false
for time.Now().Before(deadline) {
_, err := http.Get(baseURL + "/blocks/watermark")
netErr := new(net.OpError)
if errors.As(err, &netErr) {
gotError = true
break
}
time.Sleep(100 * time.Millisecond)
}
require.True(t, gotError, "did not get network error in time")
t.Log("HTTP server was shut down, sleeping a moment before restarting")
time.Sleep(2 * time.Second)
// New context and new started instance.
ctx2, cancel := context.WithCancel(context.Background())
defer cancel()
baseURL = "http://" + c.Start(t, ctx2, 1).HTTP[0]
// c.Start blocks until the HTTP server is available,
// so we should be able to access it immediately.
maxHeight = 0
resp, err := http.Get(baseURL + "/blocks/watermark")
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
var m map[string]uint
require.NoError(t, json.NewDecoder(resp.Body).Decode(&m))
resp.Body.Close()
maxHeight = m["VotingHeight"]
require.GreaterOrEqual(t, maxHeight, expHeight)
// Now wait for the height to increase by two more.
expHeight += 2
deadline = time.Now().Add(15 * time.Second)
for time.Now().Before(deadline) {
resp, err := http.Get(baseURL + "/blocks/watermark")
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
var m map[string]uint
require.NoError(t, json.NewDecoder(resp.Body).Decode(&m))
resp.Body.Close()
maxHeight = m["VotingHeight"]
if maxHeight >= expHeight {
break
}
}
require.GreaterOrEqual(t, maxHeight, expHeight)
}
}
func TestTx_single_basicSend(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
c := ConfigureChain(t, ctx, ChainConfig{
ID: t.Name(),
NVals: 1,
StakeStrategy: ConstantStakeStrategy(1_000_000_000),
NFixedAccounts: 2,
FixedAccountInitialBalance: 10_000,
})
httpAddr := c.Start(t, ctx, 1).HTTP[0]
if !gci.RunCometInsteadOfGordian {
baseURL := "http://" + httpAddr
// Make sure we are beyond the initial height.
deadline := time.Now().Add(10 * time.Second)
var maxHeight uint
for time.Now().Before(deadline) {
resp, err := http.Get(baseURL + "/blocks/watermark")
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
var m map[string]uint
require.NoError(t, json.NewDecoder(resp.Body).Decode(&m))
resp.Body.Close()
maxHeight = m["VotingHeight"]
if maxHeight < 3 {
time.Sleep(100 * time.Millisecond)
continue
}
// We are past initial height, so break out of the loop.
break
}
require.GreaterOrEqual(t, maxHeight, uint(3))
// Ensure we still match the fixed account initial balance.
resp, err := http.Get(baseURL + "/debug/accounts/" + c.FixedAddresses[0] + "/balance")
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
var initBalance balance
require.NoError(t, json.NewDecoder(resp.Body).Decode(&initBalance))
resp.Body.Close()
require.Equal(t, "10000", initBalance.Balance.Amount)
// Now that we are past the initial height,
// make a transaction that we can submit.
const sendAmount = "100stake"
// First generate the transaction.
res := c.RootCmds[0].Run(
"tx", "bank", "send", c.FixedAddresses[0], c.FixedAddresses[1], sendAmount,
"--chain-id", t.Name(),
"--generate-only",
)
res.NoError(t)
dir := t.TempDir()
msgPath := filepath.Join(dir, "send.msg")
require.NoError(t, os.WriteFile(msgPath, res.Stdout.Bytes(), 0o600))
// TODO: is there a better way to dynamically get this?
const accountNumber = 1
// Sign the transaction offline so that we can send it.
res = c.RootCmds[0].Run(
"tx", "sign", msgPath,
"--offline",
"--chain-id", t.Name(),
fmt.Sprintf("--account-number=%d", accountNumber),
"--from", c.FixedAddresses[0],
"--sequence=0", // We know this is the first transaction for the sender.
)
res.NoError(t)
t.Logf("SIGN OUTPUT: %s", res.Stdout.String())
t.Logf("SIGN ERROR : %s", res.Stderr.String())
resp, err = http.Post(baseURL+"/debug/submit_tx", "application/json", &res.Stdout)
require.NoError(t, err)
// Just log out what it responds, for now.
// We can't do much with the response until we actually start handling the transaction.
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
t.Logf("response body: %s", b)
require.Equal(t, http.StatusOK, resp.StatusCode)
// TODO: make some height assertions here instead of just sleeping.
time.Sleep(8 * time.Second)
// Request first account balance again.
resp, err = http.Get(baseURL + "/debug/accounts/" + c.FixedAddresses[0] + "/balance")
require.NoError(t, err)
var newBalance balance
require.NoError(t, json.NewDecoder(resp.Body).Decode(&newBalance))
resp.Body.Close()
require.Equal(t, "9900", newBalance.Balance.Amount) // Was at 10k, subtracted 100.
// And second account should have increased by 100.
resp, err = http.Get(baseURL + "/debug/accounts/" + c.FixedAddresses[1] + "/balance")
require.NoError(t, err)
require.NoError(t, json.NewDecoder(resp.Body).Decode(&newBalance))
resp.Body.Close()
require.Equal(t, "10100", newBalance.Balance.Amount) // Was at 10k, added 100.
}
}
func TestTx_single_delegate(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
const fixedAccountInitialBalance = 75_000_000
c := ConfigureChain(t, ctx, ChainConfig{
ID: t.Name(),
NVals: 1,
StakeStrategy: ConstantStakeStrategy(1_000_000_000),
NFixedAccounts: 1,
FixedAccountInitialBalance: fixedAccountInitialBalance,
})
httpAddr := c.Start(t, ctx, 1).HTTP[0]
if !gci.RunCometInsteadOfGordian {
baseURL := "http://" + httpAddr
// Make sure we are beyond the initial height.
deadline := time.Now().Add(10 * time.Second)
var maxHeight uint
for time.Now().Before(deadline) {
resp, err := http.Get(baseURL + "/blocks/watermark")
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
var m map[string]uint
require.NoError(t, json.NewDecoder(resp.Body).Decode(&m))
resp.Body.Close()
maxHeight = m["VotingHeight"]
if maxHeight < 3 {
time.Sleep(100 * time.Millisecond)
continue
}
// We are past initial height, so break out of the loop.
break
}
require.GreaterOrEqual(t, maxHeight, uint(3))
// Get the validator set.
resp, err := http.Get(baseURL + "/validators")
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
var output struct {
FinalizationHeight uint64
Validators []struct {
// Don't care about the pubkey now,
// since there is only one validator.
Power uint64
}
}
require.NoError(t, json.NewDecoder(resp.Body).Decode(&output))
require.Len(t, output.Validators, 1)
// We need the starting power, because it should increase once we delegate.
startingPow := output.Validators[0].Power
delegateAmount := fmt.Sprintf("%dstake", fixedAccountInitialBalance)
// First generate the transaction.
res := c.RootCmds[0].Run(
// val0 is the name of the first validator key,
// which should be available on the first root command.
"tx", "--chain-id", t.Name(), "staking", "delegate", "val0", delegateAmount, "--from", c.FixedAddresses[0],
"--generate-only",
)
res.NoError(t)
dir := t.TempDir()
msgPath := filepath.Join(dir, "delegate.msg")
require.NoError(t, os.WriteFile(msgPath, res.Stdout.Bytes(), 0o600))
// TODO: is there a better way to dynamically get this?
const accountNumber = 1
// Sign the transaction offline so that we can send it.
res = c.RootCmds[0].Run(
"tx", "sign", msgPath,
"--offline",
"--chain-id", t.Name(),
fmt.Sprintf("--account-number=%d", accountNumber),
"--from", c.FixedAddresses[0],
"--sequence=0", // We know this is the first transaction for the sender.
)
res.NoError(t)
t.Logf("SIGN OUTPUT: %s", res.Stdout.String())
t.Logf("SIGN ERROR : %s", res.Stderr.String())
resp, err = http.Post(baseURL+"/debug/submit_tx", "application/json", &res.Stdout)
require.NoError(t, err)
// Just log out what it responds, for now.
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
t.Logf("response body: %s", b)
require.Equal(t, http.StatusOK, resp.StatusCode)
// TODO: make some height assertions here instead of just sleeping.
time.Sleep(8 * time.Second)
// First account should have a balance of zero,
// now that everything has been delegated.
resp, err = http.Get(baseURL + "/debug/accounts/" + c.FixedAddresses[0] + "/balance")
require.NoError(t, err)
var newBalance balance
require.NoError(t, json.NewDecoder(resp.Body).Decode(&newBalance))
resp.Body.Close()
require.Equal(t, "0", newBalance.Balance.Amount) // Entire balance was delegated.
resp, err = http.Get(baseURL + "/validators")
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
clear(output.Validators)
require.NoError(t, json.NewDecoder(resp.Body).Decode(&output))
require.Len(t, output.Validators, 1)
endingPow := output.Validators[0].Power
require.Greater(t, endingPow, startingPow)
t.Logf("After delegation, power increased from %d to %d", startingPow, endingPow)
}
}
func TestTx_single_addAndRemoveNewValidator(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
const fixedAccountInitialBalance = 2_000_000_000
c := ConfigureChain(t, ctx, ChainConfig{
ID: t.Name(),
NVals: 1,
// Arbitrarily larger stake for first validator,
// so we can continue consensus without the second validator really contributing
// while remaining offline.
StakeStrategy: ConstantStakeStrategy(12 * fixedAccountInitialBalance),
NFixedAccounts: 1,
FixedAccountInitialBalance: fixedAccountInitialBalance,
})
httpAddr := c.Start(t, ctx, 1).HTTP[0]
if !gci.RunCometInsteadOfGordian {
chainID := t.Name()
baseURL := "http://" + httpAddr
// Make sure we are beyond the initial height.
deadline := time.Now().Add(10 * time.Second)
var maxHeight uint
for time.Now().Before(deadline) {
resp, err := http.Get(baseURL + "/blocks/watermark")
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
var m map[string]uint
require.NoError(t, json.NewDecoder(resp.Body).Decode(&m))
resp.Body.Close()
maxHeight = m["VotingHeight"]
if maxHeight < 3 {
time.Sleep(100 * time.Millisecond)
continue
}
// We are past initial height, so break out of the loop.
break
}
require.GreaterOrEqual(t, maxHeight, uint(3))
// Now the fixed address wants to become a validator.
// Use its mnemonic to create a new environment.
newValRootCmd := NewRootCmd(t, gtest.NewLogger(t).With("owner", "newVal"))
newValRootCmd.RunWithInput(
strings.NewReader(FixedMnemonics[0]),
"init", "newVal", "--recover",
).NoError(t)
// And we need to add the actual key,
// which also involves storing the mnemonic on disk.
scratchDir := t.TempDir()
mPath := filepath.Join(scratchDir, "fixed_mnemonic.txt")
require.NoError(t, os.WriteFile(mPath, []byte(FixedMnemonics[0]), 0o600))
res := newValRootCmd.Run(
"keys", "add", "newVal",
"--recover", "--source", mPath,
)
res.NoError(t)
// First we have to generate the JSON for creating a validator.
// We'll have to use a map to serialize this,
// as the struct type in x/staking is not exported.
delegateAmount := fmt.Sprintf("%dstake", fixedAccountInitialBalance/2)
createJson := map[string]any{
"amount": delegateAmount,
"moniker": "newVal",
"min-self-delegation": "1000", // Unsure how this will play out in undelegating.
// Values here copied from output of create-validator --help.
// Shouldn't really matter for this test.
"commission-rate": "0.1",
"commission-max-rate": "0.2",
"commission-max-change-rate": "0.01",
}
// And we have to add the pubkey field,
// which we have to retrieve from keys show.
res = newValRootCmd.Run("gordian", "val-pub-key")
res.NoError(t)
var pubKeyObj map[string]string
require.NoError(t, json.Unmarshal([]byte(res.Stdout.Bytes()), &pubKeyObj))
createJson["pubkey"] = pubKeyObj
jCreate, err := json.Marshal(createJson)
require.NoError(t, err)
// staking create-validator reads the JSON from disk.
createPath := filepath.Join(scratchDir, "create.json")
require.NoError(t, os.WriteFile(createPath, jCreate, 0o600))
res = newValRootCmd.Run(
"tx", "staking",
"create-validator", createPath,
"--from", "newVal",
"--chain-id", chainID,
"--generate-only",
)
res.NoError(t)
stakePath := filepath.Join(scratchDir, "stake.msg")
require.NoError(t, os.WriteFile(stakePath, res.Stdout.Bytes(), 0o600))
// TODO: is there a better way to dynamically get this?
const accountNumber = 1
// Sign the transaction offline so that we can send it.
res = newValRootCmd.Run(
"tx", "sign", stakePath,
"--offline",
"--chain-id", chainID,
fmt.Sprintf("--account-number=%d", accountNumber),
"--from", "newVal",
"--sequence=0", // We know this is the first transaction for the account.
)
res.NoError(t)
resp, err := http.Post(baseURL+"/debug/submit_tx", "application/json", &res.Stdout)
require.NoError(t, err)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
t.Logf("Response body from submitting tx: %s", b)
resp.Body.Close()
require.Equal(t, http.StatusOK, resp.StatusCode)
// Wait for create-validator transaction to flush.
deadline = time.Now().Add(time.Minute)
pendingTxFlushed := false
for time.Now().Before(deadline) {
resp, err := http.Get(baseURL + "/debug/pending_txs")
require.NoError(t, err)
if resp.StatusCode == http.StatusInternalServerError {
// There is an issue with printing pending transactions containing a create validator message.
// Avoid printing body when it's still erroring.
time.Sleep(2 * time.Second)
continue
}
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
resp.Body.Close()
if have := string(b); have == "[]" || have == "[]\n" {
pendingTxFlushed = true
break
}
t.Logf("pending tx body: %s", string(b))
time.Sleep(time.Second)
}
require.True(t, pendingTxFlushed, "pending tx not flushed within a minute")
// Now, we should soon see two validators.
deadline = time.Now().Add(time.Minute)
sawTwoVals := false
for time.Now().Before(deadline) {
resp, err := http.Get(baseURL + "/validators")
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
var valOutput struct {
Validators []struct {
// Don't care about any validator fields.
// Just need two entries.
}
}
require.NoError(t, json.NewDecoder(resp.Body).Decode(&valOutput))
resp.Body.Close()
if len(valOutput.Validators) == 1 {
time.Sleep(time.Second)
continue
}
require.Len(t, valOutput.Validators, 2)
sawTwoVals = true
break
}
require.True(t, sawTwoVals, "did not see two validators listed within a minute of submitting create-validator tx")
t.Run("undelegating from the new validator", func(t *testing.T) {
// If we just restake everything away from the new validator --
// which we should be allowed to do immediately --
// then the new validator should be below the threshold,
// and should be removed from the list.
res := newValRootCmd.Run(
"keys", "show", "newVal",
"--bech", "val",
"--address",
)
res.NoError(t)
newValOperAddr := strings.TrimSpace(res.Stdout.String())
res = c.RootCmds[0].Run(
"keys", "show", "val0",
"--bech", "val",
"--address",
)
res.NoError(t)
origValOperAddr := strings.TrimSpace(res.Stdout.String())
res = newValRootCmd.Run(
"tx", "staking", "redelegate",
newValOperAddr, origValOperAddr, // From new, to original.
delegateAmount, // The same amount we fully delegated to the new validator.
"--from", "newVal",
"--generate-only",
"--chain-id", chainID,
)
res.NoError(t)
t.Logf("redelegate stdout: %s", res.Stdout.String())
t.Logf("redelegate stderr: %s", res.Stderr.String())
// Now write the redelegate message to disk and sign it.
redelegatePath := filepath.Join(scratchDir, "redelegate.msg")
require.NoError(t, os.WriteFile(redelegatePath, res.Stdout.Bytes(), 0o600))
res = newValRootCmd.Run(
"tx", "sign", redelegatePath,
"--offline",
"--chain-id", chainID,
fmt.Sprintf("--account-number=%d", accountNumber),
"--from", "newVal",
"--sequence=1", // Already sent one transaction, next sequence is 1.
)
res.NoError(t)
// Submit the transaction.
resp, err := http.Post(baseURL+"/debug/submit_tx", "application/json", &res.Stdout)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
t.Logf("Response body from submitting tx: %s", b)
resp.Body.Close()
// Wait for create-validator transaction to flush.
deadline = time.Now().Add(time.Minute)
pendingTxFlushed := false
for time.Now().Before(deadline) {
resp, err := http.Get(baseURL + "/debug/pending_txs")
require.NoError(t, err)
// We don't have the serializing issue with the redelegate message,
// like we did with create-validator.
require.Equal(t, http.StatusOK, resp.StatusCode)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
resp.Body.Close()
if have := string(b); have == "[]" || have == "[]\n" {
pendingTxFlushed = true
break
}
t.Logf("pending tx body: %s", string(b))
time.Sleep(time.Second)
}
require.True(t, pendingTxFlushed, "pending tx not flushed within a minute")
// Now, we should soon see just the one validator again.
deadline = time.Now().Add(time.Minute)
sawOneVal := false
for time.Now().Before(deadline) {
resp, err := http.Get(baseURL + "/validators")
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
var valOutput struct {
Validators []struct {
// Don't care about any validator fields.
// Just need two entries.
}
}
require.NoError(t, json.NewDecoder(resp.Body).Decode(&valOutput))
resp.Body.Close()
if len(valOutput.Validators) != 1 {
time.Sleep(time.Second)
continue
}
sawOneVal = true
break
}
require.True(t, sawOneVal, "should have been back down to one validator")
})
}
}
func TestTx_multiple_simpleSend(t *testing.T) {
if testing.Short() {
t.Skip("skipping slow test in short mode")
}
const totalVals = 4
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
chainID := t.Name()
c := ConfigureChain(t, ctx, ChainConfig{
ID: chainID,
NVals: totalVals,
StakeStrategy: func(idx int) string {
const minAmount = "1000000"
// Give every validator a slightly different amount,
// so that a tracked single vote's power can be distinguished.
return minAmount + fmt.Sprintf("%02d000000stake", idx)
},
NFixedAccounts: 2,
FixedAccountInitialBalance: 10_000,
})
ca := c.Start(t, ctx, totalVals)
httpAddrs := ca.HTTP
// Each validator must report a height beyond the first few blocks.
for i := range totalVals {
if gci.RunCometInsteadOfGordian {
// Nothing to check in this mode.
break
}
u := "http://" + httpAddrs[i] + "/blocks/watermark"
// TODO: we might need to delay until we get a non-error HTTP response.
// Another deadline to confirm the voting height.
// This is a lot longer than the deadline to check HTTP addresses
// because the very first proposed block at 1/0 is expected to time out.
deadline := time.Now().Add(30 * time.Second)
var maxHeight uint
for time.Now().Before(deadline) {
resp, err := http.Get(u)
require.NoErrorf(t, err, "failed to get the watermark for validator %d/%d", i+1, totalVals)
require.Equal(t, http.StatusOK, resp.StatusCode)
var m map[string]uint
require.NoError(t, json.NewDecoder(resp.Body).Decode(&m))
resp.Body.Close()
maxHeight = m["VotingHeight"]
if maxHeight < 3 {
time.Sleep(100 * time.Millisecond)
continue
}
// We got at least to height 3, so quit the loop.
break
}
require.GreaterOrEqualf(t, maxHeight, uint(3), "checking max block height on validator at index %d", i)
}
// Now that the validators are all a couple blocks past initial height,
// it's time to submit a transaction.
// TODO: the consensus strategy should be updated to skip the low power validators;
// they are going to delay everything since they aren't running.
const sendAmount = "100stake"
// First generate the transaction.
res := c.RootCmds[0].Run(
"tx", "bank", "send", c.FixedAddresses[0], c.FixedAddresses[1], sendAmount,
"--chain-id", t.Name(),
"--generate-only",