-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathtestutil.go
750 lines (609 loc) · 14.8 KB
/
testutil.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
// +build unit integration
package wavelet
import (
"encoding/binary"
"encoding/hex"
"fmt"
atomic2 "go.uber.org/atomic"
"io/ioutil"
"net"
"os"
"strconv"
"sync/atomic"
"testing"
"time"
"github.com/pkg/errors"
"github.com/perlin-network/noise"
"github.com/perlin-network/noise/cipher"
"github.com/perlin-network/noise/edwards25519"
"github.com/perlin-network/noise/handshake"
"github.com/perlin-network/noise/skademlia"
"github.com/perlin-network/wavelet/store"
"github.com/perlin-network/wavelet/sys"
"google.golang.org/grpc"
)
var (
FaucetWallet = "87a6813c3b4cf534b6ae82db9b1409fa7dbd5c13dba5858970b56084c4a930eb400056ee68a7cc2695222df05ea76875bc27ec6e61e8e62317c336157019c405"
)
type TestNetwork struct {
faucet *TestLedger
nodes map[AccountID]*TestLedger
}
type TestNetworkConfig struct {
AddFaucet bool
}
func defaultTestNetworkConfig() TestNetworkConfig {
return TestNetworkConfig{
AddFaucet: true,
}
}
type TestNetworkOption func(cfg *TestNetworkConfig)
func NewTestNetwork(opts ...TestNetworkOption) (*TestNetwork, error) {
n := &TestNetwork{
nodes: map[AccountID]*TestLedger{},
}
cfg := defaultTestNetworkConfig()
for _, opt := range opts {
opt(&cfg)
}
var err error
if cfg.AddFaucet {
n.faucet, err = n.AddNode(WithWallet(FaucetWallet), WithRemoveExistingDB(true))
if err != nil {
return nil, err
}
}
return n, nil
}
func (n *TestNetwork) Cleanup() {
for _, node := range n.nodes {
node.Cleanup(true)
}
}
func (n *TestNetwork) Faucet() *TestLedger {
return n.faucet
}
func (n *TestNetwork) SetFaucet(node *TestLedger) {
n.faucet = node
}
type TestLedgerOption func(cfg *TestLedgerConfig)
func WithWallet(wallet string) TestLedgerOption {
return func(cfg *TestLedgerConfig) {
cfg.Wallet = wallet
}
}
func WithRemoveExistingDB(remove bool) TestLedgerOption {
return func(cfg *TestLedgerConfig) {
cfg.RemoveExistingDB = remove
}
}
func WithDBPath(path string) TestLedgerOption {
return func(cfg *TestLedgerConfig) {
cfg.DBPath = path
}
}
func (n *TestNetwork) AddNode(opts ...TestLedgerOption) (*TestLedger, error) {
var peers []string
if n.faucet != nil {
peers = append(peers, n.faucet.Addr())
}
cfg := TestLedgerConfig{
Peers: peers,
N: len(n.nodes),
}
for _, opt := range opts {
opt(&cfg)
}
node, err := NewTestLedger(cfg)
if err != nil {
return nil, err
}
node.network = n
n.nodes[node.PublicKey()] = node
return node, nil
}
func (n *TestNetwork) Nodes() []*TestLedger {
nodes := make([]*TestLedger, 0, len(n.nodes))
for _, n := range n.nodes {
nodes = append(nodes, n)
}
return nodes
}
// WaitForRound waits for all the nodes in the network to
// reach the specified block.
func (n *TestNetwork) WaitForBlock(block uint64) error {
if len(n.nodes) == 0 {
return nil
}
results := make(chan error)
for _, node := range n.nodes {
go func() {
if ri := <-node.WaitForBlock(block); ri != block {
results <- fmt.Errorf("for %x block expected to be %d but got %d", node.PublicKey(), block, ri)
} else {
results <- nil
}
}()
}
for range n.nodes {
if err := <-results; err != nil {
return err
}
}
return nil
}
func (n *TestNetwork) WaitForConsensus() error {
results := make(chan error)
for _, l := range n.nodes {
go func(ledger *TestLedger) {
err := <-ledger.WaitForConsensus()
results <- err
}(l)
}
for range n.nodes {
if err := <-results; err != nil {
return err
}
}
return nil
}
func (n *TestNetwork) WaitForSync() error {
syncs := make(chan error)
for _, l := range n.nodes {
go func(ledger *TestLedger) {
syncedErr := <-ledger.WaitForSync()
syncs <- syncedErr
}(l)
}
for range n.nodes {
if syncedErr := <-syncs; syncedErr != nil {
return syncedErr
}
}
return nil
}
func (n *TestNetwork) WaitUntilSync() error {
for _, l := range n.nodes {
if err := l.WaitUntilSync(); err != nil {
return err
}
}
return nil
}
type TestLedger struct {
network *TestNetwork
nonce uint64
ledger *Ledger
client *skademlia.Client
server *grpc.Server
addr string
dbPath string
kv store.KV
kvCleanup func()
stopped chan struct{}
synced atomic2.Bool
}
type TestLedgerConfig struct {
Wallet string
Peers []string
N int
RemoveExistingDB bool
DBPath string
}
func NewTestLedger(cfg TestLedgerConfig) (*TestLedger, error) {
keys, err := loadKeys(cfg.Wallet)
if err != nil {
return nil, err
}
ln, err := net.Listen("tcp", ":0") // nolint:gosec
if err != nil {
return nil, err
}
addr := net.JoinHostPort("127.0.0.1", strconv.Itoa(ln.Addr().(*net.TCPAddr).Port))
client := skademlia.NewClient(addr, keys, skademlia.WithC1(sys.SKademliaC1), skademlia.WithC2(sys.SKademliaC2))
client.SetCredentials(noise.NewCredentials(addr, handshake.NewECDH(), cipher.NewAEAD(), client.Protocol()))
var kvOpts []store.TestKVOption
if !cfg.RemoveExistingDB {
kvOpts = append(kvOpts, store.WithKeepExisting())
}
path := fmt.Sprintf("db_%d", cfg.N)
if cfg.DBPath != "" {
path = cfg.DBPath
}
kv, cleanup, err := store.NewTestKV("level", path, kvOpts...)
if err != nil {
return nil, err
}
ledger, err := NewLedger(kv, client, WithoutGC())
if err != nil {
return nil, err
}
server := client.Listen()
RegisterWaveletServer(server, ledger.Protocol())
stopped := make(chan struct{})
go func() {
defer close(stopped)
if err := server.Serve(ln); err != nil && err != grpc.ErrServerStopped {
fmt.Println(err)
}
}()
for _, addr := range cfg.Peers {
if _, err := client.Dial(addr); err != nil {
return nil, err
}
}
client.Bootstrap()
tl := &TestLedger{
ledger: ledger,
client: client,
server: server,
addr: addr,
dbPath: path,
kv: kv,
kvCleanup: cleanup,
stopped: stopped,
}
tl.ledger.syncManager.OnStateReconciled = append(
tl.ledger.syncManager.OnStateReconciled,
func(outOfSync bool) {
tl.synced.Store(!outOfSync)
},
)
return tl, nil
}
func (l *TestLedger) Leave(wipeDB bool) {
l.Cleanup(wipeDB)
delete(l.network.nodes, l.PublicKey())
}
func (l *TestLedger) Cleanup(wipeDB bool) {
l.server.Stop()
<-l.stopped
l.ledger.Close()
l.kvCleanup()
if wipeDB && len(l.DBPath()) != 0 {
if err := os.RemoveAll(l.DBPath()); err != nil {
panic(err)
}
}
}
func (l *TestLedger) Addr() string {
return l.addr
}
func (l *TestLedger) Ledger() *Ledger {
return l.ledger
}
func (l *TestLedger) Client() *skademlia.Client {
return l.client
}
func (l *TestLedger) KV() store.KV {
return l.kv
}
func (l *TestLedger) Keys() *skademlia.Keypair {
return l.ledger.client.Keys()
}
func (l *TestLedger) PrivateKey() edwards25519.PrivateKey {
keys := l.ledger.client.Keys()
return keys.PrivateKey()
}
func (l *TestLedger) PublicKey() AccountID {
keys := l.ledger.client.Keys()
return keys.PublicKey()
}
func (l *TestLedger) DBPath() string {
return l.dbPath
}
func (l *TestLedger) Balance() uint64 {
snapshot := l.ledger.Snapshot()
balance, _ := ReadAccountBalance(snapshot, l.PublicKey())
return balance
}
func (l *TestLedger) BalanceWithPublicKey(key AccountID) uint64 {
snapshot := l.ledger.Snapshot()
balance, _ := ReadAccountBalance(snapshot, key)
return balance
}
func (l *TestLedger) BalanceOfAccount(node *TestLedger) uint64 {
snapshot := l.ledger.Snapshot()
balance, _ := ReadAccountBalance(snapshot, node.PublicKey())
return balance
}
func (l *TestLedger) GasBalanceOfAddress(address [32]byte) uint64 {
snapshot := l.ledger.Snapshot()
balance, _ := ReadAccountContractGasBalance(snapshot, address)
return balance
}
func (l *TestLedger) Stake() uint64 {
snapshot := l.ledger.Snapshot()
stake, _ := ReadAccountStake(snapshot, l.PublicKey())
return stake
}
func (l *TestLedger) StakeWithPublicKey(key AccountID) uint64 {
snapshot := l.ledger.Snapshot()
balance, _ := ReadAccountStake(snapshot, key)
return balance
}
func (l *TestLedger) StakeOfAccount(node *TestLedger) uint64 {
snapshot := l.ledger.Snapshot()
stake, _ := ReadAccountStake(snapshot, node.PublicKey())
return stake
}
func (l *TestLedger) Reward() uint64 {
snapshot := l.ledger.Snapshot()
reward, _ := ReadAccountReward(snapshot, l.PublicKey())
return reward
}
func (l *TestLedger) RewardWithPublicKey(key AccountID) uint64 {
snapshot := l.ledger.Snapshot()
reward, _ := ReadAccountReward(snapshot, key)
return reward
}
func (l *TestLedger) BlockIndex() uint64 {
return l.ledger.Blocks().Latest().Index
}
func (l *TestLedger) WaitForConsensus() <-chan error {
ch := make(chan error)
go func() {
start := l.ledger.Blocks().Latest()
timeout := time.NewTimer(time.Second * 10)
ticker := time.NewTicker(time.Millisecond * 5)
for {
select {
case <-timeout.C:
ch <- fmt.Errorf("%x has not proceed to next block", l.PublicKey())
return
case <-ticker.C:
current := l.ledger.Blocks().Latest()
if current.Index > start.Index {
ch <- nil
return
}
}
}
}()
return ch
}
func (l *TestLedger) WaitUntilConsensus() error {
return <-l.WaitForConsensus()
}
// WaitUntilBalance should be used to ensure that the ledger's balance
// is of a specific value before continuing.
func (l *TestLedger) WaitUntilBalance(balance uint64) error {
ticker := time.NewTicker(time.Millisecond * 200)
timeout := time.NewTimer(time.Second * 30)
for {
select {
case <-ticker.C:
if l.Balance() == balance {
return nil
}
case <-timeout.C:
return errors.New("timed out waiting for balance")
}
}
}
func (l *TestLedger) WaitUntilStake(stake uint64) error {
ticker := time.NewTicker(time.Millisecond * 200)
timeout := time.NewTimer(time.Second * 30)
for {
select {
case <-ticker.C:
if l.Stake() == stake {
return nil
}
case <-timeout.C:
return errors.New("timed out waiting for stake")
}
}
}
func (l *TestLedger) WaitForBlock(index uint64) <-chan uint64 {
ch := make(chan uint64)
go func() {
timeout := time.NewTimer(time.Second * 10)
ticker := time.NewTicker(time.Millisecond * 10)
for {
select {
case <-timeout.C:
ch <- 0
return
case <-ticker.C:
current := l.ledger.Blocks().Latest()
if current.Index >= index {
ch <- current.Index
return
}
}
}
}()
return ch
}
func (l *TestLedger) WaitUntilBlock(block uint64) error {
timeout := time.NewTimer(time.Second * 300)
for {
select {
case ri := <-l.WaitForBlock(block):
if ri >= block {
return nil
}
case <-timeout.C:
return errors.New("timed out waiting for block")
}
}
}
func (l *TestLedger) WaitForSync() <-chan error {
ch := make(chan error)
go func() {
timeout := time.NewTimer(time.Second * 30)
timer := time.NewTicker(50 * time.Millisecond)
defer timeout.Stop()
defer timer.Stop()
for {
select {
case <-timeout.C:
ch <- fmt.Errorf("%x timed out waiting for sync", l.PublicKey())
return
case <-timer.C:
if l.synced.Load() {
ch <- nil
return
}
}
}
}()
return ch
}
func (l *TestLedger) WaitUntilSync() error {
return <-l.WaitForSync()
}
func (l *TestLedger) newSignedTransaction(tag sys.Tag, payload []byte) Transaction {
nonce := atomic.AddUint64(&l.nonce, 1)
block := l.BlockIndex()
var nonceBuf [8]byte
binary.BigEndian.PutUint64(nonceBuf[:], nonce)
var blockBuf [8]byte
binary.BigEndian.PutUint64(blockBuf[:], block)
keys := l.ledger.client.Keys()
signature := edwards25519.Sign(
keys.PrivateKey(),
append(nonceBuf[:], append(blockBuf[:], append([]byte{byte(tag)}, payload...)...)...),
)
return NewSignedTransaction(
keys.PublicKey(), nonce, block,
tag, payload, signature,
)
}
func (l *TestLedger) Pay(to *TestLedger, amount uint64) (Transaction, error) {
t := Transfer{
Recipient: to.PublicKey(),
Amount: amount,
}
var tx Transaction
payload, err := t.Marshal()
if err != nil {
return tx, err
}
tx = l.newSignedTransaction(sys.TagTransfer, payload)
l.ledger.AddTransaction(tx)
return tx, nil
}
func (l *TestLedger) SpawnContract(contractPath string, gasLimit uint64, params []byte) (Transaction, error) {
code, err := ioutil.ReadFile(contractPath)
if err != nil {
return Transaction{}, err
}
c := Contract{
GasLimit: gasLimit,
Code: code,
Params: params,
}
var tx Transaction
payload, err := c.Marshal()
if err != nil {
return tx, err
}
tx = l.newSignedTransaction(sys.TagContract, payload)
l.ledger.AddTransaction(tx)
return tx, nil
}
func (l *TestLedger) DepositGas(id [32]byte, gasDeposit uint64) (Transaction, error) {
t := Transfer{
Recipient: id,
GasDeposit: gasDeposit,
}
var tx Transaction
payload, err := t.Marshal()
if err != nil {
return tx, err
}
tx = l.newSignedTransaction(sys.TagTransfer, payload)
l.ledger.AddTransaction(tx)
return tx, nil
}
func (l *TestLedger) CallContract(id [32]byte, amount uint64, gasLimit uint64, funcName string, params []byte) (Transaction, error) {
t := Transfer{
Recipient: id,
Amount: amount,
GasLimit: gasLimit,
FuncName: []byte(funcName),
FuncParams: params,
}
var tx Transaction
payload, err := t.Marshal()
if err != nil {
return tx, err
}
tx = l.newSignedTransaction(sys.TagTransfer, payload)
l.ledger.AddTransaction(tx)
return tx, nil
}
func (l *TestLedger) PlaceStake(amount uint64) (Transaction, error) {
s := Stake{
Opcode: sys.PlaceStake,
Amount: amount,
}
var tx Transaction
payload, err := s.Marshal()
if err != nil {
return tx, err
}
tx = l.newSignedTransaction(sys.TagStake, payload)
l.ledger.AddTransaction(tx)
return tx, nil
}
func (l *TestLedger) WithdrawStake(amount uint64) (Transaction, error) {
s := Stake{
Opcode: sys.WithdrawStake,
Amount: amount,
}
var tx Transaction
payload, err := s.Marshal()
if err != nil {
return tx, err
}
tx = l.newSignedTransaction(sys.TagStake, payload)
l.ledger.AddTransaction(tx)
return tx, nil
}
// loadKeys returns a keypair from a wallet string, or generates a new one
// if no wallet is provided.
func loadKeys(wallet string) (*skademlia.Keypair, error) {
// Generate a keypair if wallet is empty
if wallet == "" {
return skademlia.NewKeys(sys.SKademliaC1, sys.SKademliaC2)
}
if len(wallet) != hex.EncodedLen(edwards25519.SizePrivateKey) {
return nil, fmt.Errorf("private key is not of the right length")
}
var privateKey edwards25519.PrivateKey
n, err := hex.Decode(privateKey[:], []byte(wallet))
if err != nil {
return nil, err
}
if n != edwards25519.SizePrivateKey {
return nil, fmt.Errorf("private key is not of the right length")
}
keys, err := skademlia.LoadKeys(privateKey, sys.SKademliaC1, sys.SKademliaC2)
if err != nil {
return nil, err
}
return keys, nil
}
func waitFor(fn func() bool) error {
timeout := time.NewTimer(time.Second * 30)
ticker := time.NewTicker(time.Millisecond * 100)
for {
select {
case <-timeout.C:
return errors.New("timed out waiting")
case <-ticker.C:
if fn() {
return nil
}
}
}
}
func FailTest(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}