forked from ethereum/hive
/
ethclient.go
1070 lines (906 loc) · 40.4 KB
/
ethclient.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
import (
"bytes"
"context"
"encoding/json"
"io/ioutil"
"math/big"
"os"
"testing"
"time"
"math/rand"
"strings"
ethereum "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/params"
)
var (
// hash of the genesis block
genesisHash = common.HexToHash("0xf74e0678a551515d1746ccf6e3bbdce19775b0b47608c49dd25ac92302b0a376")
contractCode = `
pragma solidity ^0.4.6;
contract Test {
event E0();
event E1(uint);
event E2(uint indexed);
event E3(address);
event E4(address indexed);
event E5(uint, address) anonymous;
uint public ui;
mapping(address => uint) map;
function Test(uint ui_) {
ui = ui_;
map[msg.sender] = ui_;
}
function events(uint ui_, address addr_) {
E0();
E1(ui_);
E2(ui_);
E3(addr_);
E4(addr_);
E5(ui_, addr_);
}
function constFunc(uint a, uint b, uint c) constant returns(uint, uint, uint) {
return (a, b, c);
}
function getFromMap(address addr) constant returns(uint) {
return map[addr];
}
function addToMap(address addr, uint value) {
map[addr] = value;
}
}
`
// test contract deploy code, will deploy the contract with 1234 as argument
deployCode = common.Hex2Bytes("6060604052346100005760405160208061048c833981016040528080519060200190919050505b8060008190555080600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b505b610409806100836000396000f30060606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063a223e05d1461006a578063abd1a0cf1461008d578063abfced1d146100d4578063e05c914a14610110578063e6768b451461014c575b610000565b346100005761007761019d565b6040518082815260200191505060405180910390f35b34610000576100be600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506101a3565b6040518082815260200191505060405180910390f35b346100005761010e600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919080359060200190919050506101ed565b005b346100005761014a600480803590602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610236565b005b346100005761017960048080359060200190919080359060200190919080359060200190919050506103c4565b60405180848152602001838152602001828152602001935050505060405180910390f35b60005481565b6000600160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490505b919050565b80600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b5050565b7f6031a8d62d7c95988fa262657cd92107d90ed96e08d8f867d32f26edfe85502260405180905060405180910390a17f47e2689743f14e97f7dcfa5eec10ba1dff02f83b3d1d4b9c07b206cbbda66450826040518082815260200191505060405180910390a1817fa48a6b249a5084126c3da369fbc9b16827ead8cb5cdc094b717d3f1dcd995e2960405180905060405180910390a27f7890603b316f3509577afd111710f9ebeefa15e12f72347d9dffd0d65ae3bade81604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a18073ffffffffffffffffffffffffffffffffffffffff167f7efef9ea3f60ddc038e50cccec621f86a0195894dc0520482abf8b5c6b659e4160405180905060405180910390a28181604051808381526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019250505060405180910390a05b5050565b6000600060008585859250925092505b935093509390505600a165627a7a72305820aaf842d0d0c35c45622c5263cbb54813d2974d3999c8c38551d7c613ea2bc117002900000000000000000000000000000000000000000000000000000000000004d2")
// test contract code as deployed
runtimeCode = common.Hex2Bytes("60606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063a223e05d1461006a578063abd1a0cf1461008d578063abfced1d146100d4578063e05c914a14610110578063e6768b451461014c575b610000565b346100005761007761019d565b6040518082815260200191505060405180910390f35b34610000576100be600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506101a3565b6040518082815260200191505060405180910390f35b346100005761010e600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919080359060200190919050506101ed565b005b346100005761014a600480803590602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610236565b005b346100005761017960048080359060200190919080359060200190919080359060200190919050506103c4565b60405180848152602001838152602001828152602001935050505060405180910390f35b60005481565b6000600160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490505b919050565b80600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b5050565b7f6031a8d62d7c95988fa262657cd92107d90ed96e08d8f867d32f26edfe85502260405180905060405180910390a17f47e2689743f14e97f7dcfa5eec10ba1dff02f83b3d1d4b9c07b206cbbda66450826040518082815260200191505060405180910390a1817fa48a6b249a5084126c3da369fbc9b16827ead8cb5cdc094b717d3f1dcd995e2960405180905060405180910390a27f7890603b316f3509577afd111710f9ebeefa15e12f72347d9dffd0d65ae3bade81604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a18073ffffffffffffffffffffffffffffffffffffffff167f7efef9ea3f60ddc038e50cccec621f86a0195894dc0520482abf8b5c6b659e4160405180905060405180910390a28181604051808381526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019250505060405180910390a05b5050565b6000600060008585859250925092505b935093509390505600a165627a7a72305820aaf842d0d0c35c45622c5263cbb54813d2974d3999c8c38551d7c613ea2bc1170029")
// contractSrc is predeploy on the following address in the genesis block.
predeployedContractAddr = common.HexToAddress("0000000000000000000000000000000000000314")
// contractSrc is pre-deployed with the following address in the genesis block.
predeployedContractWithAddress = common.HexToAddress("391694e7e0b0cce554cb130d723a9d27458f9298")
// holds the pre-deployed contract ABI
predeployedContractABI = `[{"constant":true,"inputs":[],"name":"ui","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"addr","type":"address"}],"name":"getFromMap","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"addr","type":"address"},{"name":"value","type":"uint256"}],"name":"addToMap","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"ui_","type":"uint256"},{"name":"addr_","type":"address"}],"name":"events","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"a","type":"uint256"},{"name":"b","type":"uint256"},{"name":"c","type":"uint256"}],"name":"constFunc","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[{"name":"ui_","type":"uint256"}],"payable":false,"type":"constructor"},{"anonymous":false,"inputs":[],"name":"E0","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"","type":"uint256"}],"name":"E1","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"","type":"uint256"}],"name":"E2","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"","type":"address"}],"name":"E3","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"","type":"address"}],"name":"E4","type":"event"},{"anonymous":true,"inputs":[{"indexed":false,"name":"","type":"uint256"},{"indexed":false,"name":"","type":"address"}],"name":"E5","type":"event"}]`
)
// CodeAtTest tests the code for the pre-deployed contract.
func CodeAtTest(t *testing.T, client *TestClient) {
t.Parallel()
ctx, _ := context.WithTimeout(context.Background(), rpcTimeout)
code, err := client.CodeAt(ctx, predeployedContractAddr, common.Big0)
if err != nil {
t.Fatalf("Could not fetch code for predeployed contract: %v", err)
}
if bytes.Compare(runtimeCode, code) != 0 {
t.Fatalf("Unexpected code, want %x, got %x", runtimeCode, code)
}
}
// estimateGasTest fetches the estimated gas usage for a call to the events method.
func estimateGasTest(t *testing.T, client *TestClient) {
t.Parallel()
var (
contractABI, _ = abi.JSON(strings.NewReader(predeployedContractABI))
account = createAndFundAccount(t, new(big.Int).Mul(common.Big1, common.Ether), client)
intArg = big.NewInt(rand.Int63())
addrArg = account.Address
)
payload, err := contractABI.Pack("events", intArg, addrArg)
if err != nil {
t.Fatalf("Unable to prepare tx payload: %v", err)
}
ctx, _ := context.WithTimeout(context.Background(), rpcTimeout)
msg := ethereum.CallMsg{
From: account.Address,
To: &predeployedContractAddr,
Data: payload,
}
estimated, err := client.EstimateGas(ctx, msg)
if err != nil {
t.Fatalf("Could not estimate gas: %v", err)
}
// send the actual tx and test gas usage
rawTx := types.NewTransaction(0, *msg.To, msg.Value, new(big.Int).Add(estimated, big.NewInt(100000)), new(big.Int).Mul(common.Big32, common.Shannon), msg.Data)
tx, err := SignTransaction(rawTx, account)
if err != nil {
t.Fatalf("Could not sign transaction: %v", err)
}
ctx, _ = context.WithTimeout(context.Background(), rpcTimeout)
if err := client.SendTransaction(ctx, tx); err != nil {
t.Fatalf("Could not send tx: %v", err)
}
receipt, err := waitForTxConfirmations(client, tx.Hash(), 1)
if err != nil {
t.Fatalf("Could not wait for confirmations: %v", err)
}
// test lower bound
if estimated.Cmp(receipt.GasUsed) < 0 {
t.Fatalf("Estimated gas too low, want %d >= %d", estimated, receipt.GasUsed)
}
// test upper bound
if new(big.Int).Add(receipt.GasUsed, big.NewInt(5000)).Cmp(estimated) <= 0 {
t.Fatalf("Estimated gas too high, estimated: %d, used: %d", estimated, receipt.GasUsed)
}
}
// balanceAndNonceAtTest creates a new account and transfers funds to it.
// It then tests if the balance and nonce of the sender and receiver
// address are updated correct.
func balanceAndNonceAtTest(t *testing.T, client *TestClient) {
t.Parallel()
var (
sourceAccount = createAndFundAccount(t, new(big.Int).Mul(common.Big1, common.Ether), client)
sourceNonce = uint64(0)
sourceAddress = sourceAccount.Address
targetAccount = createAndFundAccount(t, nil, client)
targetAddr = targetAccount.Address
)
// Get current balance
ctx, _ := context.WithTimeout(context.Background(), rpcTimeout)
sourceAddressBalanceBefore, err := client.BalanceAt(ctx, sourceAddress, nil)
if err != nil {
t.Fatalf("Unable to retrieve balance: %v", err)
}
expected := new(big.Int).Mul(common.Big1, common.Ether)
if sourceAddressBalanceBefore.Cmp(expected) != 0 {
t.Errorf("Expected balance %d, got %d", expected, sourceAddressBalanceBefore)
}
ctx, _ = context.WithTimeout(context.Background(), rpcTimeout)
nonceBefore, err := client.NonceAt(ctx, sourceAddress, nil)
if err != nil {
t.Fatalf("Unable to determine nonce: %v", err)
}
if nonceBefore != sourceNonce {
t.Fatalf("Invalid nonce, want %d, got %d", sourceNonce, nonceBefore)
}
// send 1234 wei to target account and verify balances and nonces are updated
amount := new(big.Int).Mul(big.NewInt(1234), common.Wei)
gasPrice := new(big.Int).Mul(big.NewInt(34), common.Shannon)
gasLimit := big.NewInt(50000)
rawTx := types.NewTransaction(sourceNonce, targetAddr, amount, gasLimit, gasPrice, nil)
valueTx, err := SignTransaction(rawTx, sourceAccount)
if err != nil {
t.Fatalf("Unable to sign value tx: %v", err)
}
sourceNonce++
t.Logf("BalanceAt: send %d wei from 0x%x to 0x%x in 0x%x", valueTx.Value(), sourceAddress, targetAddr, valueTx.Hash())
ctx, _ = context.WithTimeout(context.Background(), rpcTimeout)
if err := client.SendTransaction(ctx, valueTx); err != nil {
t.Fatalf("Unable to send transaction: %v", err)
}
var receipt *types.Receipt
for {
ctx, _ := context.WithTimeout(context.Background(), rpcTimeout)
receipt, err = client.TransactionReceipt(ctx, valueTx.Hash())
if receipt != nil {
break
}
if err != ethereum.NotFound {
t.Fatalf("Could not fetch receipt for 0x%x: %v", valueTx.Hash(), err)
}
time.Sleep(time.Second)
}
// ensure balances have been updated
ctx, _ = context.WithTimeout(context.Background(), rpcTimeout)
accountBalanceAfter, err := client.BalanceAt(ctx, sourceAddress, nil)
if err != nil {
t.Fatalf("Unable to retrieve balance: %v", err)
}
balanceTargetAccountAfter, err := client.BalanceAt(ctx, targetAddr, nil)
if err != nil {
t.Fatalf("Unable to retrieve balance: %v", err)
}
// expected balance is previous balance - tx amount - tx fee (gasUsed * gasPrice)
exp := new(big.Int).Set(sourceAddressBalanceBefore)
exp.Sub(exp, amount)
exp.Sub(exp, new(big.Int).Mul(receipt.GasUsed, valueTx.GasPrice()))
if exp.Cmp(accountBalanceAfter) != 0 {
t.Errorf("Expected sender account to have a balance of %d, got %d", exp, accountBalanceAfter)
}
if balanceTargetAccountAfter.Cmp(amount) != 0 {
t.Errorf("Expected new account to have a balance of %d, got %d", valueTx.Value(), balanceTargetAccountAfter)
}
// ensure nonce is incremented by 1
ctx, _ = context.WithTimeout(context.Background(), rpcTimeout)
nonceAfter, err := client.NonceAt(ctx, sourceAddress, nil)
if err != nil {
t.Fatalf("Unable to determine nonce: %v", err)
}
expectedNonce := nonceBefore + 1
if expectedNonce != nonceAfter {
t.Fatalf("Invalid nonce, want %d, got %d", expectedNonce, nonceAfter)
}
}
// compareAgainstGenesisBlock is a helper function that compares the
// given header against the known genesis block and errors for mismatches.
func compareAgainstGenesisBlock(t *testing.T, head0 *types.Header) {
// only known block is the genesis block that was imported from /genesis.json
genesisFile, err := os.Open("/genesis.json")
if err != nil {
t.Fatalf("failed to read genesis file: %v", err)
}
contents, err := ioutil.ReadAll(genesisFile)
if err != nil {
t.Fatalf("Unable to read genesis file: %v", err)
}
var genesis struct {
ChainConfig *params.ChainConfig `json:"config"`
Nonce string
Timestamp string
ParentHash string
ExtraData string
GasLimit string
Difficulty string
Mixhash string
Coinbase string
Alloc map[string]struct {
Code string
Storage map[string]string
Balance string
}
}
if err := json.Unmarshal(contents, &genesis); err != nil {
t.Fatalf("Unable to parse genesis.json file: %v", err)
}
// check nonce
gNonce, _ := new(big.Int).SetString(genesis.Nonce, 0)
bNonce := new(big.Int).SetBytes(head0.Nonce[:])
if gNonce.Uint64() != bNonce.Uint64() {
t.Errorf("Unexpected nonce, want %d, got %d", gNonce, bNonce)
}
// check timestamp
gTime, _ := new(big.Int).SetString(genesis.Timestamp, 0)
bTime := head0.Time
if gTime.Cmp(bTime) != 0 {
t.Errorf("Unexpected timestamp, want %d, got %s", gTime, bTime)
}
// check extradata
gExtraData := common.FromHex(genesis.ExtraData)
bExtraData := head0.Extra
if bytes.Compare(gExtraData, bExtraData) != 0 {
t.Errorf("Unexpected extradata, want %x, got %x", gExtraData, bExtraData)
}
// check gas limit
gGasLimt, _ := new(big.Int).SetString(genesis.GasLimit, 0)
bGasLimit := head0.GasLimit
if gGasLimt.Cmp(bGasLimit) != 0 {
t.Errorf("Unexpected gas limit, want %d, got %d", gGasLimt, bGasLimit)
}
// check difficulty
gDifficulty, _ := new(big.Int).SetString(genesis.Difficulty, 0)
bDifficulty := head0.Difficulty
if gDifficulty.Cmp(bDifficulty) != 0 {
t.Errorf("Unexpected difficulty, want %d, got %d", gDifficulty, bDifficulty)
}
// check mix hash
gMixHash := common.HexToHash(genesis.Mixhash)
bMixHash := head0.MixDigest
if gMixHash != bMixHash {
t.Errorf("Unexpected mix hash, want %x, got %x", gMixHash, bMixHash)
}
// check coinbase/etherbase
gCoinbase := common.HexToAddress(genesis.Coinbase)
bCoinbase := head0.Coinbase
if gCoinbase != bCoinbase {
t.Errorf("Unexpected coinbase, want %x, got %x", gCoinbase, bCoinbase)
}
// Allocs are tested dynamically when contracts are deployed
}
// headerByHashTest fetched the known genesis header and compares
// it against the genesis file to determine if block fields are
// returned correct.
func headerByHashTest(t *testing.T, client *TestClient) {
t.Parallel()
ctx, _ := context.WithTimeout(context.Background(), rpcTimeout)
headerByHash, err := client.HeaderByHash(ctx, genesisHash)
if err != nil {
t.Fatalf("Unable to fetch block %x: %v", genesisHash, err)
}
compareAgainstGenesisBlock(t, headerByHash)
}
// headerByNumberTest fetched the known genesis header and compares
// it against the genesis file to determine if block fields are
// returned correct.
func headerByNumberTest(t *testing.T, client *TestClient) {
t.Parallel()
ctx, _ := context.WithTimeout(context.Background(), rpcTimeout)
headerByNum, err := client.HeaderByNumber(ctx, common.Big0)
if err != nil {
t.Fatalf("Unable to fetch genesis block: %v", err)
}
compareAgainstGenesisBlock(t, headerByNum)
}
// blockByHashTest fetched the known genesis block and compares it against
// the genesis file to determine if block fields are returned correct.
func blockByHashTest(t *testing.T, client *TestClient) {
t.Parallel()
ctx, _ := context.WithTimeout(context.Background(), rpcTimeout)
blockByHash, err := client.BlockByHash(ctx, genesisHash)
if err != nil {
t.Fatalf("Unable to fetch block %x: %v", genesisHash, err)
}
compareAgainstGenesisBlock(t, blockByHash.Header())
}
// blockByNumberTest retrieves block 0 since that is the only block
// that is known through the genesis.json file and tests if block
// fields matches the fields defined in the genesis file.
func blockByNumberTest(t *testing.T, client *TestClient) {
t.Parallel()
ctx, _ := context.WithTimeout(context.Background(), rpcTimeout)
blockByNum, err := client.BlockByNumber(ctx, common.Big0)
if err != nil {
t.Fatalf("Unable to fetch genesis block: %v", err)
}
compareAgainstGenesisBlock(t, blockByNum.Header())
}
// canonicalChainTest loops over 10 blocks and does some basic validations
// to ensure the chain form a valid canonical chain and resources like uncles,
// transactions and receipts can be fetched and provide a consistent view.
func canonicalChainTest(t *testing.T, client *TestClient) {
t.Parallel()
// wait a bit so there is actually a chain with enough height
for {
ctx, _ := context.WithTimeout(context.Background(), rpcTimeout)
latestBlock, err := client.BlockByNumber(ctx, nil)
if err != nil {
t.Fatalf("Unable to fetch latest block")
}
if latestBlock.NumberU64() >= 20 {
break
}
time.Sleep(time.Second)
}
var childBlock *types.Block
for i := 10; i >= 0; i-- {
ctx, _ := context.WithTimeout(context.Background(), rpcTimeout)
block, err := client.BlockByNumber(ctx, big.NewInt(int64(i)))
if err != nil {
t.Fatalf("Unable to fetch block #%d", i)
}
if childBlock != nil {
if childBlock.ParentHash() != block.Hash() {
t.Errorf("Canonical chain broken on %d-%d / %x-%x", block.NumberU64(), childBlock.NumberU64(), block.Hash(), childBlock.Hash())
}
}
// try to fetch all txs and receipts and do some basic validation on them
// to check if the fetched chain is consistent.
for _, tx := range block.Transactions() {
ctx, _ = context.WithTimeout(context.Background(), rpcTimeout)
fetchedTx, _, err := client.TransactionByHash(ctx, tx.Hash())
if err != nil {
t.Fatalf("Unable to fetch transaction %x from block %x: %v", tx.Hash(), block.Hash(), err)
}
if fetchedTx == nil {
t.Fatalf("Transaction %x could not be found but was included in block %x", tx.Hash(), block.Hash())
}
ctx, _ = context.WithTimeout(context.Background(), rpcTimeout)
receipt, err := client.TransactionReceipt(ctx, fetchedTx.Hash())
if err != nil {
t.Fatalf("Unable to fetch receipt for %x from block %x: %v", fetchedTx.Hash(), block.Hash(), err)
}
if receipt == nil {
t.Fatalf("Receipt for %x could not be found but was included in block %x", fetchedTx.Hash(), block.Hash())
}
if receipt.TxHash != fetchedTx.Hash() {
t.Fatalf("Receipt has an invalid tx, expected %x, got %x", fetchedTx.Hash(), receipt.TxHash)
}
}
// make sure all uncles can be fetched
for _, uncle := range block.Uncles() {
ctx, _ = context.WithTimeout(context.Background(), rpcTimeout)
uBlock, err := client.HeaderByHash(ctx, uncle.Hash())
if err != nil {
t.Fatalf("Unable to fetch uncle block: %v", err)
}
if uBlock == nil {
t.Logf("Could not fetch uncle block %x", uncle.Hash())
}
}
childBlock = block
}
}
// deployContractTest deploys `contractSrc` and tests if the code and state
// on the contract address contain the expected values (as set in the ctor).
func deployContractTest(t *testing.T, client *TestClient) {
t.Parallel()
var (
account = createAndFundAccount(t, new(big.Int).Mul(common.Big1, common.Ether), client)
address = account.Address
nonce = uint64(0)
expectedContractAddress = crypto.CreateAddress(address, nonce)
gasPrice = new(big.Int).Mul(big.NewInt(30), common.Shannon)
gasLimit = big.NewInt(1200000)
)
rawTx := types.NewContractCreation(nonce, common.Big0, gasLimit, gasPrice, deployCode)
deployTx, err := SignTransaction(rawTx, account)
if err != nil {
t.Fatalf("Unable to sign deploy tx: %v", err)
}
// deploy contract
ctx, _ := context.WithTimeout(context.Background(), rpcTimeout)
if err := client.SendTransaction(ctx, deployTx); err != nil {
t.Fatalf("Unable to send transaction: %v", err)
}
t.Logf("Deploy transaction: 0x%x", deployTx.Hash())
// fetch transaction receipt for contract address
var contractAddress common.Address
receipt, err := waitForTxConfirmations(client, deployTx.Hash(), 5)
if err != nil {
t.Fatalf("Unable to retrieve receipt: %v", err)
}
// ensure receipt has the expected address
if expectedContractAddress != receipt.ContractAddress {
t.Fatalf("Contract deploy on different address, expected %x, got %x", expectedContractAddress, contractAddress)
}
// test deployed code matches runtime code
ctx, _ = context.WithTimeout(context.Background(), rpcTimeout)
code, err := client.CodeAt(ctx, receipt.ContractAddress, nil)
if err != nil {
t.Fatalf("Unable to fetch contract code: %v", err)
}
if bytes.Compare(runtimeCode, code) != 0 {
t.Errorf("Deployed code doesn't match, expected %x, got %x", runtimeCode, code)
}
// test contract state, pos 0 must be 1234
ctx, _ = context.WithTimeout(context.Background(), rpcTimeout)
value, err := client.StorageAt(ctx, receipt.ContractAddress, common.Hash{}, nil)
if err == nil {
v := new(big.Int).SetBytes(value)
if v.Uint64() != 1234 {
t.Errorf("Unexpected value on %x:0x01, expected 1234, got %d", receipt.ContractAddress, v)
}
} else {
t.Errorf("Unable to retrieve storage pos 0x01 on address %x: %v", contractAddress, err)
}
// test contract state, map on pos 1 with key myAccount must be 1234
storageKey := make([]byte, 64)
copy(storageKey[12:32], address.Bytes())
storageKey[63] = 1
storageKey = crypto.Keccak256(storageKey)
ctx, _ = context.WithTimeout(context.Background(), rpcTimeout)
value, err = client.StorageAt(ctx, receipt.ContractAddress, common.BytesToHash(storageKey), nil)
if err == nil {
v := new(big.Int).SetBytes(value)
if v.Uint64() != 1234 {
t.Errorf("Unexpected value in map, expected 1234, got %d", v)
}
} else {
t.Fatalf("Unable to retrieve value in map: %v", err)
}
}
// deployContractOutOfGasTest tries to deploy `contractSrc` with insufficient
// gas. It checks the receipts reflects the "out of gas" event and node code/
// state isn't created in the contract address.
func deployContractOutOfGasTest(t *testing.T, client *TestClient) {
t.Parallel()
var (
account = createAndFundAccount(t, new(big.Int).Mul(common.Big1, common.Ether), client)
address = account.Address
nonce = uint64(0)
contractAddress = crypto.CreateAddress(address, nonce)
gasPrice = new(big.Int).Mul(big.NewInt(30), common.Shannon)
gasLimit = big.NewInt(240000) // insufficient gas
)
t.Logf("Calculated contract address: %x", contractAddress)
rawTx := types.NewContractCreation(nonce, common.Big0, gasLimit, gasPrice, deployCode)
deployTx, err := SignTransaction(rawTx, account)
if err != nil {
t.Fatalf("Unable to sign deploy tx: %v", err)
}
t.Logf("Out of gas tx: %x", deployTx.Hash())
// deploy contract
ctx, _ := context.WithTimeout(context.Background(), rpcTimeout)
if err := client.SendTransaction(ctx, deployTx); err != nil {
t.Fatalf("Unable to send transaction: %v", err)
}
// fetch transaction receipt
receipt, err := waitForTxConfirmations(client, deployTx.Hash(), 5)
if err != nil {
t.Fatalf("Unable to fetch tx receipt: %v", err)
}
// test if receipt contractAddress is empty
if receipt.ContractAddress != (common.Address{}) {
t.Errorf("Receipt contract address should be empty, got %x", receipt.ContractAddress)
}
// test if there is nothing deploy on the calculated contract address
ctx, _ = context.WithTimeout(context.Background(), rpcTimeout)
code, err := client.CodeAt(ctx, contractAddress, nil)
if err != nil {
t.Fatalf("Unable to fetch code: %v", err)
}
if len(code) != 0 {
t.Errorf("Expected no code deployed but got %x", code)
}
}
// receiptTest tests whether the created receipt is correct by calling the `events` method
// on the pre-deployed contract.
func receiptTest(t *testing.T, client *TestClient) {
t.Parallel()
var (
contractABI, _ = abi.JSON(strings.NewReader(predeployedContractABI))
account = createAndFundAccount(t, new(big.Int).Mul(common.Big1, common.Ether), client)
nonce = uint64(0)
intArg = big.NewInt(rand.Int63())
addrArg = account.Address
)
payload, err := contractABI.Pack("events", intArg, addrArg)
if err != nil {
t.Fatalf("Unable to prepare tx payload: %v", err)
}
gasPrice := new(big.Int).Mul(big.NewInt(30), common.Shannon)
rawTx := types.NewTransaction(nonce, predeployedContractAddr, common.Big0, big.NewInt(500000), gasPrice, payload)
tx, err := SignTransaction(rawTx, account)
if err != nil {
t.Fatalf("Unable to sign deploy tx: %v", err)
}
ctx, _ := context.WithTimeout(context.Background(), rpcTimeout)
if err := client.SendTransaction(ctx, tx); err != nil {
t.Fatalf("Unable to send transaction: %v", err)
}
// wait for transaction
receipt, err := waitForTxConfirmations(client, tx.Hash(), 0)
if err != nil {
t.Fatalf("Unable to retrieve tx receipt: %v", err)
}
// validate receipt fields
if receipt.TxHash != tx.Hash() {
t.Errorf("Receipt contains invalid tx hash, want %x, got %x", tx.Hash(), receipt.TxHash)
}
if receipt.ContractAddress != (common.Address{}) {
t.Errorf("Receipt contains invalid contract address, want empty address got %x", receipt.ContractAddress)
}
if receipt.CumulativeGasUsed.Cmp(common.Big0) <= 0 {
t.Errorf("Receipt contains invalid comulativeGasUsed, got %d", receipt.CumulativeGasUsed)
}
if receipt.GasUsed.Cmp(common.Big0) <= 0 {
t.Errorf("Receipt contains invalid GasUsed, got %d", receipt.GasUsed)
}
bloom := types.CreateBloom(types.Receipts{receipt})
if receipt.Bloom != bloom {
t.Errorf("Receipt contains invalid bloom, want %x, got %x", bloom, receipt.Bloom)
}
var (
intArgBytes = common.LeftPadBytes(intArg.Bytes(), 32)
addrArgBytes = common.LeftPadBytes(addrArg.Bytes(), 32)
)
if len(receipt.Logs) != 6 {
t.Fatalf("Want 6 logs, got %d", len(receipt.Logs))
}
validateLog(t, tx, *receipt.Logs[0], predeployedContractAddr, receipt.Logs[0].Index+0, contractABI.Events["E0"], nil)
validateLog(t, tx, *receipt.Logs[1], predeployedContractAddr, receipt.Logs[0].Index+1, contractABI.Events["E1"], intArgBytes)
validateLog(t, tx, *receipt.Logs[2], predeployedContractAddr, receipt.Logs[0].Index+2, contractABI.Events["E2"], intArgBytes)
validateLog(t, tx, *receipt.Logs[3], predeployedContractAddr, receipt.Logs[0].Index+3, contractABI.Events["E3"], addrArgBytes)
validateLog(t, tx, *receipt.Logs[4], predeployedContractAddr, receipt.Logs[0].Index+4, contractABI.Events["E4"], addrArgBytes)
validateLog(t, tx, *receipt.Logs[5], predeployedContractAddr, receipt.Logs[0].Index+5, contractABI.Events["E5"], intArgBytes, addrArgBytes)
}
// validateLog is a helper method that tests if the given set of logs are valid when the events method on the
// standard contract is called with argData.
func validateLog(t *testing.T, tx *types.Transaction, log types.Log, contractAddress common.Address, index uint, ev abi.Event, argData ...[]byte) {
if log.Address != contractAddress {
t.Errorf("Log[%d] contains invalid address, want 0x%x, got 0x%x [tx=0x%x]", index, contractAddress, log.Address, tx.Hash())
}
if log.TxHash != tx.Hash() {
t.Errorf("Log[%d] contains invalid hash, want 0x%x, got 0x%x [tx=0x%x]", index, tx.Hash(), log.TxHash, tx.Hash())
}
if log.Index != index {
t.Errorf("Log[%d] has invalid index, want %d, got %d [tx=0x%x]", index, index, log.Index, tx.Hash())
}
// assemble expected topics and log data
var (
topics []common.Hash
data []byte
)
if !ev.Anonymous {
topics = append(topics, ev.Id())
}
for i, arg := range ev.Inputs {
if arg.Indexed {
topics = append(topics, common.BytesToHash(argData[i]))
} else {
data = append(data, argData[i]...)
}
}
if len(log.Topics) != len(topics) {
t.Errorf("Log[%d] contains invalid number of topics, want %d, got %d [tx=0x%x]", index, len(topics), len(log.Topics), tx.Hash())
} else {
for i, topic := range topics {
if topics[i] != topic {
t.Errorf("Log[%d] contains invalid topic, want 0x%x, got 0x%x [tx=0x%x]", index, topics[i], topic, tx.Hash())
}
}
}
if !bytes.Equal(log.Data, data) {
t.Errorf("Log[%d] contains invalid data, want 0x%x, got 0x%x [tx=0x%x]", index, data, log.Data, tx.Hash())
}
}
// syncProgressTest only tests if this function is supported by the node.
func syncProgressTest(t *testing.T, client *TestClient) {
t.Parallel()
ctx, _ := context.WithTimeout(context.Background(), rpcTimeout)
_, err := client.SyncProgress(ctx)
if err != nil {
t.Fatalf("Unable to determine sync progress: %v", err)
}
}
// transactionInBlockTest will wait for a new block with transaction
// and retrieves transaction details by block hash and position.
func transactionInBlockTest(t *testing.T, client *TestClient) {
t.Parallel()
var (
key = createAndFundAccount(t, new(big.Int).Mul(common.Big1, common.Ether), client)
nonce = uint64(0)
gasPrice = new(big.Int).Mul(big.NewInt(20), common.Shannon)
blockNumber = new(big.Int)
)
for {
blockNumber.Add(blockNumber, common.Big1)
ctx, _ := context.WithTimeout(context.Background(), rpcTimeout)
block, err := client.BlockByNumber(ctx, blockNumber)
if err == ethereum.NotFound { // end of chain
rawTx := types.NewTransaction(nonce, predeployedVaultAddr, common.Big1, big.NewInt(100000), gasPrice, nil)
nonce++
tx, err := SignTransaction(rawTx, key)
if err != nil {
t.Fatalf("Unable to sign deploy tx: %v", err)
}
ctx, _ = context.WithTimeout(context.Background(), rpcTimeout)
if err = client.SendTransaction(ctx, tx); err != nil {
t.Fatalf("Unable to send transaction: %v", err)
}
time.Sleep(time.Second)
continue
}
if err != nil {
t.Fatalf("Unable to fetch latest block: %v", err)
}
if len(block.Transactions()) == 0 {
continue
}
for i := 0; i < len(block.Transactions()); i++ {
ctx, _ = context.WithTimeout(context.Background(), rpcTimeout)
_, err = client.TransactionInBlock(ctx, block.Hash(), uint(i))
if err != nil {
t.Fatalf("Unable to fetch transaction by block hash and index: %v", err)
}
}
return
}
}
// transactionInBlockSubscriptionTest will wait for a new block with transaction
// and retrieves transaction details by block hash and position.
func transactionInBlockSubscriptionTest(t *testing.T, client *TestClient) {
t.Parallel()
var (
ctx, _ = context.WithTimeout(context.Background(), rpcTimeout)
heads = make(chan *types.Header)
)
sub, err := client.SubscribeNewHead(ctx, heads)
if err != nil {
t.Fatalf("Unable to subscribe to new heads: %v", err)
}
key := createAndFundAccount(t, new(big.Int).Mul(common.Big1, common.Ether), client)
gasPrice := new(big.Int).Mul(big.NewInt(20), common.Shannon)
for i := 0; i < 5; i++ {
rawTx := types.NewTransaction(uint64(i), predeployedVaultAddr, common.Big1, big.NewInt(100000), gasPrice, nil)
tx, err := SignTransaction(rawTx, key)
if err != nil {
t.Fatalf("Unable to sign deploy tx: %v", err)
}
ctx, _ = context.WithTimeout(context.Background(), rpcTimeout)
if err = client.SendTransaction(ctx, tx); err != nil {
t.Fatalf("Unable to send transaction: %v", err)
}
}
// wait until transaction
defer sub.Unsubscribe()
for {
head := <-heads
ctx, _ = context.WithTimeout(context.Background(), rpcTimeout)
block, err := client.BlockByHash(ctx, head.Hash())
if err != nil {
t.Fatalf("Unable to retrieve block %x: %v", head.Hash(), err)
}
if len(block.Transactions()) == 0 {
continue
}
for i := 0; i < len(block.Transactions()); i++ {
ctx, _ = context.WithTimeout(context.Background(), rpcTimeout)
_, err = client.TransactionInBlock(ctx, head.Hash(), uint(i))
if err != nil {
t.Fatalf("Unable to fetch transaction by block hash and index: %v", err)
}
}
return
}
}
// newHeadSubscriptionTest tests whether
func newHeadSubscriptionTest(t *testing.T, client *TestClient) {
t.Parallel()
var (
ctx, _ = context.WithTimeout(context.Background(), rpcTimeout)
heads = make(chan *types.Header)
)
sub, err := client.SubscribeNewHead(ctx, heads)
if err != nil {
t.Fatalf("Unable to subscribe to new heads: %v", err)
}
defer sub.Unsubscribe()
for i := 0; i < 10; i++ {
select {
case newHead := <-heads:
ctx, _ = context.WithTimeout(context.Background(), rpcTimeout)
header, err := client.HeaderByHash(ctx, newHead.Hash())
if err != nil {
t.Fatalf("Unable to fetch header: %v", err)
}
if header == nil {
t.Fatalf("Unable to fetch header %s", newHead.Hash())
}
case err := <-sub.Err():
t.Fatalf("Received errors: %v", err)
}
}
}
func logSubscriptionTest(t *testing.T, client *TestClient) {
t.Parallel()
var (
ctx, _ = context.WithTimeout(context.Background(), rpcTimeout)
criteria = ethereum.FilterQuery{
Addresses: []common.Address{predeployedContractAddr},
Topics: [][]common.Hash{},
}
logs = make(chan types.Log)
)
sub, err := client.SubscribeFilterLogs(ctx, criteria, logs)
if err != nil {
t.Fatalf("Unable to create log subscription: %v", err)
}
defer sub.Unsubscribe()
var (
contractABI, _ = abi.JSON(strings.NewReader(predeployedContractABI))
account = createAndFundAccount(t, new(big.Int).Mul(common.Big1, common.Ether), client)
address = account.Address
nonce = uint64(0)
arg0 = big.NewInt(rand.Int63())
arg1 = address
)
payload, _ := contractABI.Pack("events", arg0, arg1)
gasPrice := new(big.Int).Mul(big.NewInt(30), common.Shannon)
rawTx := types.NewTransaction(nonce, predeployedContractAddr, common.Big0, big.NewInt(500000), gasPrice, payload)
tx, err := SignTransaction(rawTx, account)
if err != nil {
t.Fatalf("Unable to sign deploy tx: %v", err)
}
ctx, _ = context.WithTimeout(context.Background(), rpcTimeout)
if err = client.SendTransaction(ctx, tx); err != nil {
t.Fatalf("Unable to send transaction: %v", err)
}
t.Logf("Wait for logs generated for transaction: %x", tx.Hash())
var (
expectedLogs = 6
currentLogs = 0
fetchedLogs []types.Log
deadline = time.NewTimer(30 * time.Second)
)
// ensure we receive all logs that are generated by our transaction.
// log fields are in depth verified in another test.
for len(fetchedLogs) < expectedLogs {
select {
case log := <-logs:
// other tests also send transaction to the predeployed
// contract ensure these logs are from "our" transaction.
if log.TxHash != tx.Hash() {
continue
}
fetchedLogs = append(fetchedLogs, log)
case err := <-sub.Err():
t.Fatalf("Log subscription returned error: %v", err)
case <-deadline.C:
t.Fatalf("Only received %d/%d logs", currentLogs, expectedLogs)
}
}
validatePredeployContractLogs(t, tx, fetchedLogs, arg0, arg1)
}
// validatePredeployContractLogs tests wether the given logs are expected when
// the event function was called on the predeployed test contract was called
// with the given args. The event function raises the following events:
// event E0();
// event E1(uint);
// event E2(uint indexed);
// event E3(address);
// event E4(address indexed);
// event E5(uint, address) anonymous;
func validatePredeployContractLogs(t *testing.T, tx *types.Transaction, logs []types.Log, intArg *big.Int, addrArg common.Address) {
if len(logs) != 6 {
t.Fatalf("Unexpected log count, want 6, got %d", len(logs))
}
var (
contractABI, _ = abi.JSON(strings.NewReader(predeployedContractABI))
intArgBytes = common.LeftPadBytes(intArg.Bytes(), 32)
addrArgBytes = common.LeftPadBytes(addrArg.Bytes(), 32)
)
validateLog(t, tx, logs[0], predeployedContractAddr, logs[0].Index+0, contractABI.Events["E0"], nil)
validateLog(t, tx, logs[1], predeployedContractAddr, logs[0].Index+1, contractABI.Events["E1"], intArgBytes)
validateLog(t, tx, logs[2], predeployedContractAddr, logs[0].Index+2, contractABI.Events["E2"], intArgBytes)
validateLog(t, tx, logs[3], predeployedContractAddr, logs[0].Index+3, contractABI.Events["E3"], addrArgBytes)
validateLog(t, tx, logs[4], predeployedContractAddr, logs[0].Index+4, contractABI.Events["E4"], addrArgBytes)
validateLog(t, tx, logs[5], predeployedContractAddr, logs[0].Index+5, contractABI.Events["E5"], intArgBytes, addrArgBytes)
}
func transactionCountTest(t *testing.T, client *TestClient) {
t.Parallel()
var (
key = createAndFundAccount(t, new(big.Int).Mul(common.Big1, common.Ether), client)
gasPrice = new(big.Int).Mul(big.NewInt(20), common.Shannon)
)
for i := 0; i < 60; i++ {
rawTx := types.NewTransaction(uint64(i), predeployedVaultAddr, common.Big1, big.NewInt(100000), gasPrice, nil)
tx, err := SignTransaction(rawTx, key)
if err != nil {
t.Fatalf("Unable to sign deploy tx: %v", err)
}
ctx, _ := context.WithTimeout(context.Background(), rpcTimeout)
if err = client.SendTransaction(ctx, tx); err != nil {
t.Fatalf("Unable to send transaction: %v", err)
}
ctx, _ = context.WithTimeout(context.Background(), rpcTimeout)
block, err := client.BlockByNumber(ctx, nil)
if err != nil {
t.Fatalf("Unable to retrieve latest block: %v", err)
}
if len(block.Transactions()) > 0 {
count, err := client.TransactionCount(ctx, block.Hash())