forked from umbracle/ethgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
409 lines (348 loc) · 8.6 KB
/
server.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
package testutil
import (
"bytes"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"math/big"
"math/rand"
"net"
"net/http"
"os"
"strconv"
"testing"
"time"
"github.com/ory/dockertest"
"github.com/umbracle/go-web3"
"github.com/umbracle/go-web3/compiler"
"golang.org/x/crypto/sha3"
)
const (
DefaultGasPrice = 1879048192 // 0x70000000
DefaultGasLimit = 5242880 // 0x500000
)
var (
DummyAddr = web3.HexToAddress("0x015f68893a39b3ba0681584387670ff8b00f4db2")
)
func getOpenPort() string {
rand.Seed(time.Now().UnixNano())
min, max := 12000, 15000
for {
port := strconv.Itoa(rand.Intn(max-min) + min)
server, err := net.Listen("tcp", ":"+port)
if err == nil {
server.Close()
return port
}
}
}
// MultiAddr creates new servers to test different addresses
func MultiAddr(t *testing.T, cb ServerConfigCallback, c func(s *TestServer, addr string)) {
s := NewTestServer(t, cb)
// http addr
c(s, s.HTTPAddr())
// ws addr
c(s, s.WSAddr())
// ip addr
// c(s, s.IPCPath())
s.Close()
}
// TestServerConfig is the configuration of the server
type TestServerConfig struct {
Period int
}
// ServerConfigCallback is the callback to modify the config
type ServerConfigCallback func(c *TestServerConfig)
// TestServer is a Geth test server
type TestServer struct {
pool *dockertest.Pool
resource *dockertest.Resource
config *TestServerConfig
tmpDir string
accounts []web3.Address
client *ethClient
t *testing.T
}
// NewTestServer creates a new Geth test server
func NewTestServer(t *testing.T, cb ServerConfigCallback) *TestServer {
tmpDir, err := ioutil.TempDir("/tmp", "geth-")
if err != nil {
t.Fatalf("err: %s", err)
}
config := &TestServerConfig{}
if cb != nil {
cb(config)
}
args := []string{"--dev"}
// periodic mining
if config.Period != 0 {
args = append(args, "--dev.period", strconv.Itoa(config.Period))
}
// add data dir
args = append(args, "--datadir", "/eth1data")
// add ipcpath
args = append(args, "--ipcpath", "/eth1data/geth.ipc")
// enable rpc
args = append(args, "--http", "--http.addr", "0.0.0.0", "--http.api", "eth,net,web3,debug")
// enable ws
args = append(args, "--ws", "--ws.addr", "0.0.0.0")
opts := &dockertest.RunOptions{
Repository: "ethereum/client-go",
Tag: "v1.9.25",
Cmd: args,
Mounts: []string{
tmpDir + ":/eth1data",
},
}
pool, err := dockertest.NewPool("")
if err != nil {
t.Fatalf("Could not connect to docker: %s", err)
}
resource, err := pool.RunWithOptions(opts)
if err != nil {
t.Fatalf("Could not start go-ethereum: %s", err)
}
server := &TestServer{
t: t,
pool: pool,
tmpDir: tmpDir,
resource: resource,
config: config,
}
if err := pool.Retry(func() error {
return testHTTPEndpoint(server.HTTPAddr())
}); err != nil {
server.Close()
}
server.client = ðClient{server.HTTPAddr()}
if err := server.client.call("eth_accounts", &server.accounts); err != nil {
t.Fatal(err)
}
return server
}
// Account returns a specific account
func (t *TestServer) Account(i int) web3.Address {
return t.accounts[i]
}
// IPCPath returns the ipc endpoint
func (t *TestServer) IPCPath() string {
return t.tmpDir + "/geth.ipc"
}
// WSAddr returns the websocket endpoint
func (t *TestServer) WSAddr() string {
return fmt.Sprintf("ws://%s:8546", t.resource.Container.NetworkSettings.IPAddress)
}
// HTTPAddr returns the http endpoint
func (t *TestServer) HTTPAddr() string {
return fmt.Sprintf("http://%s:8545", t.resource.Container.NetworkSettings.IPAddress)
}
// ProcessBlock processes a new block
func (t *TestServer) ProcessBlockWithReceipt() (*web3.Receipt, error) {
receipt, err := t.SendTxn(&web3.Transaction{
From: t.accounts[0],
To: &DummyAddr,
Value: big.NewInt(10),
})
return receipt, err
}
func (t *TestServer) ProcessBlock() error {
_, err := t.ProcessBlockWithReceipt()
return err
}
var emptyAddr web3.Address
func isEmptyAddr(w web3.Address) bool {
return bytes.Equal(w[:], emptyAddr[:])
}
// Call sends a contract call
func (t *TestServer) Call(msg *web3.CallMsg) (string, error) {
if isEmptyAddr(msg.From) {
msg.From = t.Account(0)
}
var resp string
if err := t.client.call("eth_call", &resp, msg, "latest"); err != nil {
return "", err
}
return resp, nil
}
func (t *TestServer) Transfer(address web3.Address, value *big.Int) *web3.Receipt {
receipt, err := t.SendTxn(&web3.Transaction{
From: t.accounts[0],
To: &address,
Value: value,
})
if err != nil {
t.t.Fatal(err)
}
return receipt
}
// TxnTo sends a transaction to a given method without any arguments
func (t *TestServer) TxnTo(address web3.Address, method string) *web3.Receipt {
sig := MethodSig(method)
receipt, err := t.SendTxn(&web3.Transaction{
To: &address,
Input: sig,
})
if err != nil {
t.t.Fatal(err)
}
return receipt
}
// SendTxn sends a transaction
func (t *TestServer) SendTxn(txn *web3.Transaction) (*web3.Receipt, error) {
if isEmptyAddr(txn.From) {
txn.From = t.Account(0)
}
if txn.GasPrice == 0 {
txn.GasPrice = DefaultGasPrice
}
if txn.Gas == 0 {
txn.Gas = DefaultGasLimit
}
var hash web3.Hash
if err := t.client.call("eth_sendTransaction", &hash, txn); err != nil {
return nil, err
}
return t.WaitForReceipt(hash)
}
// WaitForReceipt waits for the receipt
func (t *TestServer) WaitForReceipt(hash web3.Hash) (*web3.Receipt, error) {
var receipt *web3.Receipt
var count uint64
for {
err := t.client.call("eth_getTransactionReceipt", &receipt, hash)
if err != nil {
if err.Error() != "not found" {
return nil, err
}
}
if receipt != nil {
break
}
if count > 100 {
return nil, fmt.Errorf("timeout")
}
time.Sleep(50 * time.Millisecond)
count++
}
return receipt, nil
}
// DeployContract deploys a contract with account 0 and returns the address
func (t *TestServer) DeployContract(c *Contract) (*compiler.Artifact, web3.Address) {
// solcContract := compile(c.Print())
solcContract, err := c.Compile()
if err != nil {
panic(err)
}
buf, err := hex.DecodeString(solcContract.Bin)
if err != nil {
panic(err)
}
receipt, err := t.SendTxn(&web3.Transaction{
Input: buf,
})
if err != nil {
panic(err)
}
return solcContract, receipt.ContractAddress
}
func (t *TestServer) testHTTPEndpoint() bool {
resp, err := http.Post(t.HTTPAddr(), "application/json", nil)
if err != nil {
return false
}
defer resp.Body.Close()
return true
}
func (t *TestServer) exit(err error) {
t.Close()
t.t.Fatal(err)
}
// Close closes the server
func (t *TestServer) Close() {
if err := t.pool.Purge(t.resource); err != nil {
t.t.Fatalf("Could not purge geth: %s", err)
}
}
// Simple jsonrpc client to avoid cycle dependencies
type jsonRPCRequest struct {
ID int `json:"id"`
Method string `json:"method"`
Params json.RawMessage `json:"params"`
}
type jsonRPCResponse struct {
ID int `json:"id"`
Result json.RawMessage `json:"result"`
Error *jsonRPCErrorObject `json:"error,omitempty"`
}
type jsonRPCErrorObject struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
}
type ethClient struct {
url string
}
var errNotFound = fmt.Errorf("not found")
func (e *ethClient) call(method string, out interface{}, params ...interface{}) error {
if e.url == "" {
e.url = "http://127.0.0.1:8545"
}
var err error
jsonReq := &jsonRPCRequest{
Method: method,
}
if len(params) > 0 {
jsonReq.Params, err = json.Marshal(params)
if err != nil {
return err
}
}
raw, err := json.Marshal(jsonReq)
if err != nil {
return err
}
resp, err := http.Post(e.url, "application/json", bytes.NewBuffer(raw))
if err != nil {
return err
}
defer resp.Body.Close()
var jsonResp jsonRPCResponse
d := json.NewDecoder(resp.Body)
if err := d.Decode(&jsonResp); err != nil {
return err
}
if jsonResp.Error != nil {
return fmt.Errorf(jsonResp.Error.Message)
}
if bytes.Equal(jsonResp.Result, []byte("null")) {
return errNotFound
}
if err := json.Unmarshal(jsonResp.Result, out); err != nil {
return err
}
return nil
}
// MethodSig returns the signature of a non-parametrized function
func MethodSig(name string) []byte {
h := sha3.NewLegacyKeccak256()
h.Write([]byte(name + "()"))
b := h.Sum(nil)
return b[:4]
}
// TestInfuraEndpoint returns the testing infura endpoint to make testing requests
func TestInfuraEndpoint(t *testing.T) string {
url := os.Getenv("INFURA_URL")
if url == "" {
t.Skip("Infura url not set")
}
return url
}
func testHTTPEndpoint(endpoint string) error {
resp, err := http.Post(endpoint, "application/json", nil)
if err != nil {
return err
}
defer resp.Body.Close()
return nil
}