forked from prysmaticlabs/eth1-mock-rpc
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
471 lines (441 loc) · 13.3 KB
/
main.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
package main
import (
"bufio"
"context"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"path"
"reflect"
"strconv"
"strings"
"sync"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/rpc"
"github.com/pkg/profile"
"github.com/prysmaticlabs/eth1-mock-rpc/eth1"
"github.com/sirupsen/logrus"
prefixed "github.com/x-cray/logrus-prefixed-formatter"
"golang.org/x/net/websocket"
)
const (
maxRequestContentLength = 1024 * 512
defaultErrorCode = -32000
eth1BlockTime = time.Second * 10
startingBlockNumber = 2000
)
var (
wsPort = flag.String("ws-port", "7778", "Port on which to serve websocket listeners")
httpPort = flag.String("http-port", "7777", "Port on which to serve http listeners")
numGenesisDeposits = flag.Int("genesis-deposits", 0, "Number of deposits to read from the keystore to trigger the genesis event")
blockTime = flag.Int("block-time", 14, "Average time between blocks in seconds, default: 14s (Goerli testnet)")
verbosity = flag.String("verbosity", "info", "Logging verbosity (debug, info=default, warn, error, fatal, panic)")
pprof = flag.Bool("pprof", false, "Enable pprof")
unencryptedKeysDir = flag.String("unencrypted-keys-dir", "", "Path to directory of json files containing unencrypted validator private keys")
log = logrus.WithField("prefix", "main")
)
type server struct {
depositsLock sync.Mutex
numDepositsReadyToSend int
deposits []*eth1.DepositData
eth1BlocksByNumber map[uint64]*types.Header
eth1BlockNumbersByHash map[common.Hash]uint64
eth1Logs []types.Log
eth1BlockNum uint64
depositsToSend int
eth1HeadFeed *event.Feed
genesisTime uint64
}
type websocketHandler struct {
blockNum uint64
close chan bool
readOperation chan []*jsonrpcMessage // Channel for read messages from the codec.
readErr chan error
}
func main() {
flag.Parse()
formatter := new(prefixed.TextFormatter)
formatter.TimestampFormat = "2006-01-02 15:04:05"
formatter.FullTimestamp = true
logrus.SetFormatter(formatter)
level, err := logrus.ParseLevel(*verbosity)
if err != nil {
log.Fatal(err)
}
logrus.SetLevel(level)
if *numGenesisDeposits == 0 {
log.Fatal("Please enter a valid number of --genesis-deposits to read from the keystore")
}
// If an unencrypted keys directory is not specified, we throw an error
providedUnencryptedKeys := *unencryptedKeysDir != ""
if !providedUnencryptedKeys {
log.Fatal("Please enter a path to a directory of unencrypted private key JSON files for launching the mock server")
}
fileInfo, err := ioutil.ReadDir(*unencryptedKeysDir)
if err != nil {
log.Fatal(err)
}
validatorKeys := make([][]byte, 0)
withdrawalKeys := make([][]byte, 0)
for _, file := range fileInfo {
r, err := os.Open(path.Join(*unencryptedKeysDir, file.Name()))
if err != nil {
log.Fatal(err)
}
vkey, wkey, err := parseUnencryptedKeysFile(r)
if err != nil {
log.Fatal(err)
}
validatorKeys = append(validatorKeys, vkey...)
withdrawalKeys = append(withdrawalKeys, wkey...)
}
allDeposits, err := createDepositDataFromKeys(validatorKeys, withdrawalKeys)
if err != nil {
log.Fatal(err)
}
if *numGenesisDeposits > len(allDeposits) {
log.Fatalf(
"Number of --genesis-deposits %d > number of deposits found in keystore directory %d",
*numGenesisDeposits,
allDeposits,
)
}
httpListener, err := net.Listen("tcp", fmt.Sprintf("localhost:%s", *httpPort))
if err != nil {
log.Fatal(err)
}
wsListener, err := net.Listen("tcp", fmt.Sprintf("localhost:%s", *wsPort))
if err != nil {
log.Fatal(err)
}
// We also compute a history of eth1 blocks to be used to respond to RPC requests for
// blocks by number, getting our mock server to closely resemble a real chain.
currentBlockNumber := uint64(startingBlockNumber)
blocksByNumber := eth1.ConstructBlocksByNumber(currentBlockNumber, eth1BlockTime)
blockNumbersByHash := make(map[common.Hash]uint64)
for k, v := range blocksByNumber {
h := v.Hash()
blockNumbersByHash[h] = k
}
// We precalculate a list of deposit logs from the entire in-memory deposits list.
logs, err := eth1.DepositEventLogs(allDeposits)
if err != nil {
log.Fatal(err)
}
for i := 0; i < *numGenesisDeposits; i++ {
logs[i].BlockHash = blocksByNumber[currentBlockNumber].Hash()
logs[i].BlockNumber = currentBlockNumber
}
srv := &server{
numDepositsReadyToSend: *numGenesisDeposits,
deposits: allDeposits,
eth1Logs: logs,
eth1BlockNum: currentBlockNumber,
eth1BlockNumbersByHash: blockNumbersByHash,
eth1BlocksByNumber: blocksByNumber,
eth1HeadFeed: new(event.Feed),
genesisTime: uint64(time.Now().Add(10 * time.Second).Unix()),
}
if *pprof {
defer profile.Start().Stop()
}
log.Println("Starting HTTP listener on port :7777")
go http.Serve(httpListener, srv)
log.Println("Starting WebSocket listener on port :7778")
wsSrv := &http.Server{Handler: srv.ServeWebsocket()}
go wsSrv.Serve(wsListener)
go srv.listenForDepositTrigger()
go srv.advanceEth1Chain(*blockTime)
select {}
}
func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
body := io.LimitReader(r.Body, maxRequestContentLength)
conn := &httpServerConn{Reader: body, Writer: w, r: r}
codec := NewJSONCodec(conn)
defer codec.Close()
msgs, batch, err := codec.Read()
if err != nil {
log.WithError(err).Error("Could not read data from request")
w.WriteHeader(http.StatusInternalServerError)
return
}
requestItem := msgs[0]
if !requestItem.isCall() {
log.WithField("messageType", requestItem.Method).Error("Can only serve RPC call types via HTTP")
w.WriteHeader(http.StatusInternalServerError)
return
}
stringRep := requestItem.String()
switch requestItem.Method {
case "eth_getBlockByNumber":
blocks := make([]*types.Header, 0)
for i := 0; i < len(msgs); i++ {
typs := []reflect.Type{
reflect.TypeOf("s"),
reflect.TypeOf(true),
}
args, err := parsePositionalArguments(requestItem.Params, typs)
if err != nil {
log.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
var block *types.Header
var ok bool
if args[0].String() == "latest" {
block, ok = s.eth1BlocksByNumber[s.eth1BlockNum]
if !ok {
log.Errorf("Block with 'latest' does not exist at blocknumber %d", s.eth1BlockNum)
w.WriteHeader(http.StatusInternalServerError)
return
}
} else {
num, err := hexutil.DecodeBig(args[0].String())
if err != nil {
log.Error(err)
w.WriteHeader(http.StatusInternalServerError)
}
if num.Uint64() < startingBlockNumber {
num = num.SetInt64(startingBlockNumber)
}
block, ok = s.eth1BlocksByNumber[num.Uint64()]
if !ok {
log.Errorf("Block %d does not exist", num.Uint64())
w.WriteHeader(http.StatusInternalServerError)
return
}
}
blocks = append(blocks, block)
}
if len(blocks) == 1 && !batch {
response := requestItem.response(blocks[0])
if err := codec.Write(ctx, response); err != nil {
log.Error(err)
w.WriteHeader(http.StatusInternalServerError)
}
return
}
responses := make([]*jsonrpcMessage, 0)
for i, b := range blocks {
res := msgs[i].response(b)
responses = append(responses, res)
}
if err := codec.Write(ctx, responses); err != nil {
log.Error(err)
w.WriteHeader(http.StatusInternalServerError)
}
case "eth_getBlockByHash":
typs := []reflect.Type{
reflect.TypeOf("s"),
reflect.TypeOf(true),
}
args, err := parsePositionalArguments(requestItem.Params, typs)
if err != nil {
log.Error(err)
w.WriteHeader(http.StatusInternalServerError)
}
h := args[0].String()
// Strip out the 0x prefix.
blockHashBytes, err := hex.DecodeString(h[2:])
if err != nil {
log.Error(err)
w.WriteHeader(http.StatusInternalServerError)
}
var blockHash [32]byte
copy(blockHash[:], blockHashBytes)
numByHash := s.eth1BlockNumbersByHash[blockHash]
if numByHash < startingBlockNumber {
numByHash = startingBlockNumber
}
block := s.eth1BlocksByNumber[numByHash]
response := requestItem.response(block)
if err := codec.Write(ctx, response); err != nil {
log.Error(err)
w.WriteHeader(http.StatusInternalServerError)
}
case "eth_getLogs":
response := requestItem.response(s.eth1Logs[:s.numDepositsReadyToSend])
if err := codec.Write(ctx, response); err != nil {
log.Error(err)
w.WriteHeader(http.StatusInternalServerError)
}
case "eth_call":
if strings.Contains(stringRep, eth1.DepositMethodID()) {
count := eth1.DepositCount(s.deposits[:s.numDepositsReadyToSend])
depCount, err := eth1.PackDepositCount(count[:])
if err != nil {
log.WithError(err).Error("Could not respond to HTTP request")
w.WriteHeader(http.StatusInternalServerError)
}
response := requestItem.response(fmt.Sprintf("%#x", depCount))
if err := codec.Write(ctx, response); err != nil {
log.Error(err)
w.WriteHeader(http.StatusInternalServerError)
}
return
}
if strings.Contains(stringRep, eth1.DepositLogsID()) {
root, err := eth1.DepositRoot(s.deposits[:s.numDepositsReadyToSend])
if err != nil {
log.WithError(err).Error("Could not respond to HTTP request")
w.WriteHeader(http.StatusInternalServerError)
return
}
response := requestItem.response(fmt.Sprintf("%#x", root))
if err := codec.Write(ctx, response); err != nil {
log.Error(err)
w.WriteHeader(http.StatusInternalServerError)
}
return
}
s.defaultResponse(w)
default:
s.defaultResponse(w)
}
}
func (s *server) defaultResponse(w http.ResponseWriter) {
log.Error("Could not respond to HTTP request")
w.WriteHeader(http.StatusBadRequest)
}
func (s *server) ServeWebsocket() http.Handler {
return websocket.Server{
Handler: func(conn *websocket.Conn) {
codec := newWebsocketCodec(conn)
wsHandler := &websocketHandler{
blockNum: 0,
close: make(chan bool),
readOperation: make(chan []*jsonrpcMessage),
readErr: make(chan error),
}
defer codec.Close()
// Listen to read events from the codec and dispatch events or errors accordingly.
go wsHandler.websocketReadLoop(codec)
go wsHandler.dispatchWebsocketEventLoop(codec, s.eth1HeadFeed)
<-codec.Closed()
},
}
}
func (w *websocketHandler) dispatchWebsocketEventLoop(codec ServerCodec, headFeed *event.Feed) {
var latestSubID rpc.ID
headChan := make(chan *types.Header, 1)
sub := headFeed.Subscribe(headChan)
defer sub.Unsubscribe()
for {
select {
case <-w.close:
return
case err := <-w.readErr:
log.WithError(err).Error("Could not read data from request")
return
case head := <-headChan:
data, _ := json.Marshal(head)
params, _ := json.Marshal(&subscriptionResult{ID: string(latestSubID), Result: data})
ctx := context.Background()
item := &jsonrpcMessage{
Version: "2.0",
Method: "eth_subscription",
Params: params,
}
if err := codec.Write(ctx, item); err != nil {
log.Error(err)
continue
}
case msgs := <-w.readOperation:
sub := &rpc.Subscription{ID: rpc.NewID()}
item := &jsonrpcMessage{
Version: msgs[0].Version,
ID: msgs[0].ID,
}
latestSubID = sub.ID
newItem := item.response(sub)
if err := codec.Write(context.Background(), newItem); err != nil {
log.Error(err)
continue
}
}
}
}
func (w *websocketHandler) websocketReadLoop(codec ServerCodec) {
for {
select {
case <-w.close:
return
default:
msgs, _, err := codec.Read()
if _, ok := err.(*json.SyntaxError); ok {
if err := codec.Write(context.Background(), errorMessage(err)); err != nil {
log.Error(err)
continue
}
}
if err != nil {
w.readErr <- err
return
}
w.readOperation <- msgs
}
}
}
func (s *server) listenForDepositTrigger() {
reader := bufio.NewReader(os.Stdin)
for {
maxAllowed := len(s.deposits) - s.numDepositsReadyToSend
log.Printf(
"Enter the number of new eth2 deposits to trigger (max allowed %d): ",
maxAllowed,
)
fmt.Print(">> ")
line, _, err := reader.ReadLine()
if err != nil {
log.Error(err)
continue
}
num, err := strconv.Atoi(string(line))
if err != nil {
log.Error(err)
}
if num > maxAllowed {
log.Errorf(
"You have already sent %d/%d available deposits in keystore, cannot submit more",
len(s.deposits),
s.numDepositsReadyToSend,
)
continue
}
s.depositsToSend = num
for s.depositsToSend != 0 {
time.Sleep(1 * time.Second)
// wait till it's sent again
}
}
}
func (s *server) advanceEth1Chain(blockTime int) {
tick := time.NewTicker(time.Second * time.Duration(blockTime))
for {
select {
case <-tick.C:
s.eth1BlockNum++
head := eth1.BlockHeader(s.eth1BlockNum)
s.eth1BlocksByNumber[s.eth1BlockNum] = head
s.eth1BlockNumbersByHash[head.Hash()] = s.eth1BlockNum
for i := s.numDepositsReadyToSend; i < (s.numDepositsReadyToSend + s.depositsToSend); i++ {
s.eth1Logs[i].BlockHash = s.eth1BlocksByNumber[s.eth1BlockNum].Hash()
s.eth1Logs[i].BlockNumber = s.eth1BlockNum
}
s.numDepositsReadyToSend += s.depositsToSend
s.depositsToSend = 0
s.eth1HeadFeed.Send(head)
}
}
}