forked from web3coach/the-blockchain-bar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode_integration_test.go
789 lines (659 loc) · 23.1 KB
/
node_integration_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
// Copyright 2020 The the-blockchain-bar Authors
// This file is part of the the-blockchain-bar library.
//
// The the-blockchain-bar library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The the-blockchain-bar library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package node
import (
"context"
"encoding/json"
"io"
"io/ioutil"
"os"
"path/filepath"
"testing"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/web3coach/the-blockchain-bar/database"
"github.com/web3coach/the-blockchain-bar/fs"
"github.com/web3coach/the-blockchain-bar/wallet"
)
// The password for testing keystore files:
//
// ./test_andrej--3eb92807f1f91a8d4d85bc908c7f86dcddb1df57
// ./test_babayaga--6fdc0d8d15ae6b4ebf45c52fd2aafbcbb19a65c8
//
// Pre-generated for testing purposes using wallet_test.go.
//
// It's necessary to have pre-existing accounts before a new node
// with fresh new, empty keystore is initialized and booted in order
// to configure the accounts balances in genesis.json
//
// I.e: A quick solution to a chicken-egg problem.
const testKsAndrejAccount = "0x3eb92807f1f91a8d4d85bc908c7f86dcddb1df57"
const testKsBabaYagaAccount = "0x6fdc0d8d15ae6b4ebf45c52fd2aafbcbb19a65c8"
const testKsAndrejFile = "test_andrej--3eb92807f1f91a8d4d85bc908c7f86dcddb1df57"
const testKsBabaYagaFile = "test_babayaga--6fdc0d8d15ae6b4ebf45c52fd2aafbcbb19a65c8"
const testKsAccountsPwd = "security123"
const nodeVersion = "0.0.0-alpha 01abcd Test Run"
func TestNode_Run(t *testing.T) {
datadir, err := getTestDataDirPath()
if err != nil {
t.Fatal(err)
}
err = fs.RemoveDir(datadir)
if err != nil {
t.Fatal(err)
}
n := New(datadir, "127.0.0.1", 8085, database.NewAccount(DefaultMiner), PeerNode{}, nodeVersion, defaultTestMiningDifficulty)
ctx, _ := context.WithTimeout(context.Background(), time.Second*5)
err = n.Run(ctx, true, "")
if err != nil {
t.Fatal(err)
}
}
func TestNode_Mining(t *testing.T) {
dataDir, andrej, babaYaga, err := setupTestNodeDir(1000000, 0)
if err != nil {
t.Error(err)
}
defer fs.RemoveDir(dataDir)
// Required for AddPendingTX() to describe
// from what node the TX came from (local node in this case)
nInfo := NewPeerNode(
"127.0.0.1",
8085,
false,
babaYaga,
true,
nodeVersion,
)
// Construct a new Node instance and configure
// Andrej as a miner
n := New(dataDir, nInfo.IP, nInfo.Port, andrej, nInfo, nodeVersion, defaultTestMiningDifficulty)
// Allow the mining to run for 30 mins, in the worst case
ctx, closeNode := context.WithTimeout(
context.Background(),
time.Minute*30,
)
// Schedule a new TX in 3 seconds from now, in a separate thread
// because the n.Run() few lines below is a blocking call
go func() {
time.Sleep(time.Second * miningIntervalSeconds / 3)
tx := database.NewBaseTx(andrej, babaYaga, 1, 1, "")
signedTx, err := wallet.SignTxWithKeystoreAccount(tx, andrej, testKsAccountsPwd, wallet.GetKeystoreDirPath(dataDir))
if err != nil {
t.Error(err)
return
}
_ = n.AddPendingTX(signedTx, nInfo)
}()
// Schedule a TX with insufficient funds in 4 seconds validating
// the AddPendingTX won't add it to the Mempool
go func() {
time.Sleep(time.Second*(miningIntervalSeconds/3) + 1)
tx := database.NewBaseTx(babaYaga, andrej, 50, 1, "")
signedTx, err := wallet.SignTxWithKeystoreAccount(tx, babaYaga, testKsAccountsPwd, wallet.GetKeystoreDirPath(dataDir))
if err != nil {
t.Error(err)
return
}
err = n.AddPendingTX(signedTx, nInfo)
t.Log(err)
if err == nil {
t.Errorf("TX should not be added to Mempool because BabaYaga doesn't have %d TBB tokens", tx.Value)
return
}
}()
// Schedule a new TX in 12 seconds from now simulating
// that it came in - while the first TX is being mined
go func() {
time.Sleep(time.Second * (miningIntervalSeconds + 2))
tx := database.NewBaseTx(andrej, babaYaga, 2, 2, "")
signedTx, err := wallet.SignTxWithKeystoreAccount(tx, andrej, testKsAccountsPwd, wallet.GetKeystoreDirPath(dataDir))
if err != nil {
t.Error(err)
return
}
err = n.AddPendingTX(signedTx, nInfo)
if err != nil {
t.Error(err)
return
}
}()
go func() {
// Periodically check if we mined the 2 blocks
ticker := time.NewTicker(10 * time.Second)
for {
select {
case <-ticker.C:
if n.state.LatestBlock().Header.Number == 1 {
closeNode()
return
}
}
}
}()
// Run the node, mining and everything in a blocking call (hence the go-routines before)
_ = n.Run(ctx, true, "")
if n.state.LatestBlock().Header.Number != 1 {
t.Fatal("2 pending TX not mined into 2 blocks under 30m")
}
}
// Expect:
// ERROR: wrong TX. Sender '0x3EB9....' is forged
//
// TODO: Improve this with TX Receipt concept in next chapters.
// TODO: Improve this with a 100% clear error check.
func TestNode_ForgedTx(t *testing.T) {
dataDir, andrej, babaYaga, err := setupTestNodeDir(1000000, 0)
if err != nil {
t.Error(err)
}
defer fs.RemoveDir(dataDir)
n := New(dataDir, "127.0.0.1", 8085, andrej, PeerNode{}, nodeVersion, defaultTestMiningDifficulty)
ctx, closeNode := context.WithTimeout(context.Background(), time.Minute*30)
andrejPeerNode := NewPeerNode("127.0.0.1", 8085, false, andrej, true, nodeVersion)
txValue := uint(5)
txNonce := uint(1)
tx := database.NewBaseTx(andrej, babaYaga, txValue, txNonce, "")
validSignedTx, err := wallet.SignTxWithKeystoreAccount(tx, andrej, testKsAccountsPwd, wallet.GetKeystoreDirPath(dataDir))
if err != nil {
t.Error(err)
closeNode()
return
}
go func() {
// Wait for the node to run
time.Sleep(time.Second * 1)
err = n.AddPendingTX(validSignedTx, andrejPeerNode)
if err != nil {
t.Error(err)
closeNode()
return
}
}()
go func() {
ticker := time.NewTicker(time.Second * (miningIntervalSeconds - 3))
wasForgedTxAdded := false
for {
select {
case <-ticker.C:
if !n.state.LatestBlockHash().IsEmpty() {
if wasForgedTxAdded && !n.isMining {
closeNode()
return
}
if !wasForgedTxAdded {
// Attempt to forge the same TX but with modified time
// Because the TX.time changed, the TX.signature will be considered forged
// database.NewTx() changes the TX time
forgedTx := database.NewBaseTx(andrej, babaYaga, txValue, txNonce, "")
// Use the signature from a valid TX
forgedSignedTx := database.NewSignedTx(forgedTx, validSignedTx.Sig)
err = n.AddPendingTX(forgedSignedTx, andrejPeerNode)
t.Log(err)
if err == nil {
t.Errorf("adding a forged TX to the Mempool should not be possible")
closeNode()
return
}
wasForgedTxAdded = true
time.Sleep(time.Second * (miningIntervalSeconds + 3))
}
}
}
}
}()
_ = n.Run(ctx, true, "")
if n.state.LatestBlock().Header.Number != 0 {
t.Fatal("was suppose to mine only one TX. The second TX was forged")
}
if n.state.Balances[babaYaga] != txValue {
t.Fatal("forged tx succeeded")
}
}
// Expect:
// ERROR: wrong TX. Sender '0x3EB9...' next nonce must be '2', not '1'
//
// TODO: Improve this with TX Receipt concept in next chapters.
// TODO: Improve this with a 100% clear error check.
func TestNode_ReplayedTx(t *testing.T) {
dataDir, andrej, babaYaga, err := setupTestNodeDir(1000000, 0)
if err != nil {
t.Error(err)
}
defer fs.RemoveDir(dataDir)
n := New(dataDir, "127.0.0.1", 8085, andrej, PeerNode{}, nodeVersion, defaultTestMiningDifficulty)
ctx, closeNode := context.WithCancel(context.Background())
andrejPeerNode := NewPeerNode("127.0.0.1", 8085, false, andrej, true, nodeVersion)
babaYagaPeerNode := NewPeerNode("127.0.0.1", 8086, false, babaYaga, true, nodeVersion)
txValue := uint(5)
txNonce := uint(1)
tx := database.NewBaseTx(andrej, babaYaga, txValue, txNonce, "")
signedTx, err := wallet.SignTxWithKeystoreAccount(tx, andrej, testKsAccountsPwd, wallet.GetKeystoreDirPath(dataDir))
if err != nil {
t.Error(err)
closeNode()
return
}
go func() {
// Wait for the node to run
time.Sleep(time.Second * 1)
err = n.AddPendingTX(signedTx, andrejPeerNode)
if err != nil {
t.Error(err)
closeNode()
return
}
}()
go func() {
ticker := time.NewTicker(time.Second * (miningIntervalSeconds - 3))
wasReplayedTxAdded := false
for {
select {
case <-ticker.C:
if !n.state.LatestBlockHash().IsEmpty() {
if wasReplayedTxAdded && !n.isMining {
closeNode()
return
}
// The Andrej's original TX got mined.
// Execute the attack by replaying the TX again!
if !wasReplayedTxAdded {
// Simulate the TX was submitted to different node
n.archivedTXs = make(map[string]database.SignedTx)
// Execute the attack
err = n.AddPendingTX(signedTx, babaYagaPeerNode)
t.Log(err)
if err == nil {
t.Errorf("re-adding a TX to the Mempool should not be possible because of Nonce")
closeNode()
return
}
wasReplayedTxAdded = true
time.Sleep(time.Second * (miningIntervalSeconds + 3))
}
}
}
}
}()
_ = n.Run(ctx, true, "")
if n.state.Balances[babaYaga] == txValue*2 {
t.Errorf("replayed attack was successful :( Damn digital signatures!")
return
}
if n.state.Balances[babaYaga] != txValue {
t.Errorf("replayed attack was successful :( Damn digital signatures!")
return
}
if n.state.LatestBlock().Header.Number == 1 {
t.Errorf("the second block was not suppose to be persisted because it contained a malicious TX")
return
}
}
// The test logic summary:
// - BabaYaga runs the node
// - BabaYaga tries to mine 2 TXs
// - The mining gets interrupted because a new block from Andrej gets synced
// - Andrej will get the block reward for this synced block
// - The synced block contains 1 of the TXs BabaYaga tried to mine
// - BabaYaga tries to mine 1 TX left
// - BabaYaga succeeds and gets her block reward
func TestNode_MiningStopsOnNewSyncedBlock(t *testing.T) {
tc := []struct {
name string
ForkTIP1 uint64
}{
{"Legacy", 35}, // Prior ForkTIP1 was activated on number 35
{"ForkTIP1", 0}, // To test new blocks when the ForkTIP1 is active
}
for _, tc := range tc {
t.Run(tc.name, func(t *testing.T) {
babaYaga := database.NewAccount(testKsBabaYagaAccount)
andrej := database.NewAccount(testKsAndrejAccount)
dataDir, err := getTestDataDirPath()
if err != nil {
t.Fatal(err)
}
genesisBalances := make(map[common.Address]uint)
genesisBalances[andrej] = 1000000
genesis := database.Genesis{Balances: genesisBalances, ForkTIP1: tc.ForkTIP1}
genesisJson, err := json.Marshal(genesis)
if err != nil {
t.Fatal(err)
}
err = database.InitDataDirIfNotExists(dataDir, genesisJson)
defer fs.RemoveDir(dataDir)
err = copyKeystoreFilesIntoTestDataDirPath(dataDir)
if err != nil {
t.Fatal(err)
}
// Required for AddPendingTX() to describe
// from what node the TX came from (local node in this case)
nInfo := NewPeerNode(
"127.0.0.1",
8085,
false,
database.NewAccount(""),
true,
nodeVersion,
)
// Start mining with a high mining difficulty, just to be slow on purpose and let a synced block arrive first
n := New(dataDir, nInfo.IP, nInfo.Port, babaYaga, nInfo, nodeVersion, uint(5))
// Allow the test to run for 30 mins, in the worst case
ctx, closeNode := context.WithTimeout(context.Background(), time.Minute*30)
tx1 := database.NewBaseTx(andrej, babaYaga, 1, 1, "")
tx2 := database.NewBaseTx(andrej, babaYaga, 2, 2, "")
if tc.name == "Legacy" {
tx1.Gas = 0
tx1.GasPrice = 0
tx2.Gas = 0
tx2.GasPrice = 0
}
signedTx1, err := wallet.SignTxWithKeystoreAccount(tx1, andrej, testKsAccountsPwd, wallet.GetKeystoreDirPath(dataDir))
if err != nil {
t.Error(err)
return
}
signedTx2, err := wallet.SignTxWithKeystoreAccount(tx2, andrej, testKsAccountsPwd, wallet.GetKeystoreDirPath(dataDir))
if err != nil {
t.Error(err)
return
}
tx2Hash, err := signedTx2.Hash()
if err != nil {
t.Error(err)
return
}
// Pre-mine a valid block without running the `n.Run()`
// with Andrej as a miner who will receive the block reward,
// to simulate the block came on the fly from another peer
validPreMinedPb := NewPendingBlock(database.Hash{}, 0, andrej, []database.SignedTx{signedTx1})
validSyncedBlock, err := Mine(ctx, validPreMinedPb, defaultTestMiningDifficulty)
if err != nil {
t.Fatal(err)
}
// Add 2 new TXs into the BabaYaga's node, triggers mining
go func() {
time.Sleep(time.Second * (miningIntervalSeconds - 2))
err := n.AddPendingTX(signedTx1, nInfo)
if err != nil {
t.Fatal(err)
}
err = n.AddPendingTX(signedTx2, nInfo)
if err != nil {
t.Fatal(err)
}
}()
// Interrupt the previously started mining with a new synced block
// BUT this block contains only 1 TX the previous mining activity tried to mine
// which means the mining will start again for the one pending TX that is left and wasn't in
// the synced block
go func() {
time.Sleep(time.Second * (miningIntervalSeconds + 2))
if !n.isMining {
t.Fatal("should be mining")
}
// Change the mining difficulty back to the testing level from previously purposefully slow, high value
// otherwise the synced block would be invalid.
n.ChangeMiningDifficulty(defaultTestMiningDifficulty)
_, err := n.state.AddBlock(validSyncedBlock)
if err != nil {
t.Fatal(err)
}
// Mock the Andrej's block came from a network
n.newSyncedBlocks <- validSyncedBlock
time.Sleep(time.Second)
if n.isMining {
t.Fatal("synced block should have canceled mining")
}
// Mined TX1 by Andrej should be removed from the Mempool
_, onlyTX2IsPending := n.pendingTXs[tx2Hash.Hex()]
if len(n.pendingTXs) != 1 && !onlyTX2IsPending {
t.Fatal("synced block should have canceled mining of already mined TX")
}
}()
go func() {
// Regularly check whenever both TXs are now mined
ticker := time.NewTicker(time.Second * 10)
for {
select {
case <-ticker.C:
if n.state.LatestBlock().Header.Number == 1 {
closeNode()
return
}
}
}
}()
go func() {
time.Sleep(time.Second * 2)
// Take a snapshot of the DB balances
// before the mining is finished and the 2 blocks
// are created.
startingAndrejBalance := n.state.Balances[andrej]
startingBabaYagaBalance := n.state.Balances[babaYaga]
// Wait until the 30 mins timeout is reached or
// the 2 blocks got already mined and the closeNode() was triggered
<-ctx.Done()
endAndrejBalance := n.state.Balances[andrej]
endBabaYagaBalance := n.state.Balances[babaYaga]
// In TX1 Andrej transferred 1 TBB token to BabaYaga
// In TX2 Andrej transferred 2 TBB tokens to BabaYaga
var expectedEndAndrejBalance uint
var expectedEndBabaYagaBalance uint
// Andrej will occur the cost of SENDING 2 TXs but will collect the reward for mining one block with tx1 in it
// BabaYaga will RECEIVE value from 2 TXs and will also collect the reward for mining one block with tx2 in it
if n.state.IsTIP1Fork() {
expectedEndAndrejBalance = startingAndrejBalance - tx1.Cost(true) - tx2.Cost(true) + database.BlockReward + tx1.GasCost()
expectedEndBabaYagaBalance = startingBabaYagaBalance + tx1.Value + tx2.Value + database.BlockReward + tx2.GasCost()
} else {
expectedEndAndrejBalance = startingAndrejBalance - tx1.Cost(false) - tx2.Cost(false) + database.BlockReward + database.TxFee
expectedEndBabaYagaBalance = startingBabaYagaBalance + tx1.Value + tx2.Value + database.BlockReward + database.TxFee
}
if endAndrejBalance != expectedEndAndrejBalance {
t.Errorf("Andrej expected end balance is %d not %d", expectedEndAndrejBalance, endAndrejBalance)
}
if endBabaYagaBalance != expectedEndBabaYagaBalance {
t.Errorf("BabaYaga expected end balance is %d not %d", expectedEndBabaYagaBalance, endBabaYagaBalance)
}
t.Logf("Starting Andrej balance: %d", startingAndrejBalance)
t.Logf("Starting BabaYaga balance: %d", startingBabaYagaBalance)
t.Logf("Ending Andrej balance: %d", endAndrejBalance)
t.Logf("Ending BabaYaga balance: %d", endBabaYagaBalance)
}()
_ = n.Run(ctx, true, "")
if n.state.LatestBlock().Header.Number != 1 {
t.Fatal("was suppose to mine 2 pending TX into 2 valid blocks under 30m")
}
if len(n.pendingTXs) != 0 {
t.Fatal("no pending TXs should be left to mine")
}
})
}
}
func TestNode_MiningSpamTransactions(t *testing.T) {
tc := []struct {
name string
ForkTIP1 uint64
}{
{"Legacy", 35}, // Prior ForkTIP1 was activated on number 35
{"ForkTIP1", 0}, // To test new blocks when the ForkTIP1 is active
}
for _, tc := range tc {
t.Run(tc.name, func(t *testing.T) {
andrejBalance := uint(1000)
babaYagaBalance := uint(0)
minerBalance := uint(0)
minerKey, err := wallet.NewRandomKey()
if err != nil {
t.Fatal(err)
}
miner := minerKey.Address
dataDir, andrej, babaYaga, err := setupTestNodeDir(andrejBalance, tc.ForkTIP1)
if err != nil {
t.Fatal(err)
}
defer fs.RemoveDir(dataDir)
n := New(dataDir, "127.0.0.1", 8085, miner, PeerNode{}, nodeVersion, defaultTestMiningDifficulty)
ctx, closeNode := context.WithCancel(context.Background())
minerPeerNode := NewPeerNode("127.0.0.1", 8085, false, miner, true, nodeVersion)
txValue := uint(200)
txCount := uint(4)
spamTXs := make([]database.SignedTx, txCount)
go func() {
// Wait for the node to run and initialize its state and other components
time.Sleep(time.Second)
now := uint64(time.Now().Unix())
// Schedule 4 transfers from Andrej -> BabaYaga
for i := uint(1); i <= txCount; i++ {
txNonce := i
tx := database.NewBaseTx(andrej, babaYaga, txValue, txNonce, "")
// Ensure every TX has a unique timestamp and the nonce 0 has oldest timestamp, nonce 1 younger timestamp etc
tx.Time = now - uint64(txCount-i*100)
if tc.name == "Legacy" {
tx.Gas = 0
tx.GasPrice = 0
}
signedTx, err := wallet.SignTxWithKeystoreAccount(tx, andrej, testKsAccountsPwd, wallet.GetKeystoreDirPath(dataDir))
if err != nil {
t.Fatal(err)
}
spamTXs[i-1] = signedTx
}
// Collect pre-signed TXs to an array to make sure all 4 fit into a block within the mining interval,
// otherwise slower machines can start mining after TX 3 or so, making the test fail on e.g: Github Actions.
for _, tx := range spamTXs {
_ = n.AddPendingTX(tx, minerPeerNode)
}
}()
go func() {
// Periodically check if we mined the block
ticker := time.NewTicker(10 * time.Second)
for {
select {
case <-ticker.C:
if !n.state.LatestBlockHash().IsEmpty() {
closeNode()
return
}
}
}
}()
// Run the node, mining and everything in a blocking call (hence the go-routines before)
_ = n.Run(ctx, true, "")
var expectedAndrejBalance uint
var expectedBabaYagaBalance uint
var expectedMinerBalance uint
// in nutshell: sender occurs tx.Cost(), receiver gains tx.Value() and miner collects tx.GasCost()
if n.state.IsTIP1Fork() {
expectedAndrejBalance = andrejBalance
expectedMinerBalance = minerBalance + database.BlockReward
for _, tx := range spamTXs {
expectedAndrejBalance -= tx.Cost(true)
expectedMinerBalance += tx.GasCost()
}
expectedBabaYagaBalance = babaYagaBalance + (txCount * txValue)
} else {
expectedAndrejBalance = andrejBalance - (txCount * txValue) - (txCount * database.TxFee)
expectedBabaYagaBalance = babaYagaBalance + (txCount * txValue)
expectedMinerBalance = minerBalance + database.BlockReward + (txCount * database.TxFee)
}
if n.state.Balances[andrej] != expectedAndrejBalance {
t.Errorf("Andrej balance is incorrect. Expected: %d. Got: %d", expectedAndrejBalance, n.state.Balances[andrej])
}
if n.state.Balances[babaYaga] != expectedBabaYagaBalance {
t.Errorf("BabaYaga balance is incorrect. Expected: %d. Got: %d", expectedBabaYagaBalance, n.state.Balances[babaYaga])
}
if n.state.Balances[miner] != expectedMinerBalance {
t.Errorf("Miner balance is incorrect. Expected: %d. Got: %d", expectedMinerBalance, n.state.Balances[miner])
}
t.Logf("Andrej final balance: %d TBB", n.state.Balances[andrej])
t.Logf("BabaYaga final balance: %d TBB", n.state.Balances[babaYaga])
t.Logf("Miner final balance: %d TBB", n.state.Balances[miner])
})
}
}
// Creates dir like: "/tmp/tbb_test945924586"
func getTestDataDirPath() (string, error) {
return ioutil.TempDir(os.TempDir(), "tbb_test")
}
// Copy the pre-generated, commited keystore files from this folder into the new testDataDirPath()
//
// Afterwards the test datadir path will look like:
// "/tmp/tbb_test945924586/keystore/test_andrej--3eb92807f1f91a8d4d85bc908c7f86dcddb1df57"
// "/tmp/tbb_test945924586/keystore/test_babayaga--6fdc0d8d15ae6b4ebf45c52fd2aafbcbb19a65c8"
func copyKeystoreFilesIntoTestDataDirPath(dataDir string) error {
andrejSrcKs, err := os.Open(testKsAndrejFile)
if err != nil {
return err
}
defer andrejSrcKs.Close()
ksDir := filepath.Join(wallet.GetKeystoreDirPath(dataDir))
err = os.Mkdir(ksDir, 0777)
if err != nil {
return err
}
andrejDstKs, err := os.Create(filepath.Join(ksDir, testKsAndrejFile))
if err != nil {
return err
}
defer andrejDstKs.Close()
_, err = io.Copy(andrejDstKs, andrejSrcKs)
if err != nil {
return err
}
babayagaSrcKs, err := os.Open(testKsBabaYagaFile)
if err != nil {
return err
}
defer babayagaSrcKs.Close()
babayagaDstKs, err := os.Create(filepath.Join(ksDir, testKsBabaYagaFile))
if err != nil {
return err
}
defer babayagaDstKs.Close()
_, err = io.Copy(babayagaDstKs, babayagaSrcKs)
if err != nil {
return err
}
return nil
}
// setupTestNodeDir creates a default testing node directory with 2 keystore accounts
//
// Remember to remove the dir once test finishes: defer fs.RemoveDir(dataDir)
func setupTestNodeDir(andrejBalance uint, forkTip1 uint64) (dataDir string, andrej, babaYaga common.Address, err error) {
babaYaga = database.NewAccount(testKsBabaYagaAccount)
andrej = database.NewAccount(testKsAndrejAccount)
dataDir, err = getTestDataDirPath()
if err != nil {
return "", common.Address{}, common.Address{}, err
}
genesisBalances := make(map[common.Address]uint)
genesisBalances[andrej] = andrejBalance
genesis := database.Genesis{Balances: genesisBalances, ForkTIP1: forkTip1}
genesisJson, err := json.Marshal(genesis)
if err != nil {
return "", common.Address{}, common.Address{}, err
}
err = database.InitDataDirIfNotExists(dataDir, genesisJson)
if err != nil {
return "", common.Address{}, common.Address{}, err
}
err = copyKeystoreFilesIntoTestDataDirPath(dataDir)
if err != nil {
return "", common.Address{}, common.Address{}, err
}
return dataDir, andrej, babaYaga, nil
}