-
Notifications
You must be signed in to change notification settings - Fork 846
Expand file tree
/
Copy pathstartRPC.ts
More file actions
260 lines (240 loc) · 7.95 KB
/
startRPC.ts
File metadata and controls
260 lines (240 loc) · 7.95 KB
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
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'
import {
EthereumJSErrorWithoutCode,
bytesToUnprefixedHex,
hexToBytes,
randomBytes,
} from '@ethereumjs/util'
import { RPCManager, saveReceiptsMethods } from '../src/rpc/index.ts'
import * as modules from '../src/rpc/modules/index.ts'
import {
MethodConfig,
createRPCServer,
createRPCServerListener,
createWsRPCServerListener,
} from '../src/util/index.ts'
import type { Server } from 'jayson/promise/index.js'
import type { EthereumClient } from '../src/client.ts'
import type { Config } from '../src/config.ts'
export type RPCArgs = {
rpc: boolean
rpcAddr: string
rpcPort: number
ws: boolean
wsPort: number
wsAddr: string
rpcEngine: boolean
rpcEngineAddr: string
rpcEnginePort: number
wsEngineAddr: string
wsEnginePort: number
rpcDebug: string
rpcDebugVerbose: string
helpRPC: boolean
jwtSecret?: string
rpcEngineAuth: boolean
rpcCors: string
rpcEthMaxPayload: string
rpcEngineMaxPayload: string
}
/**
* Returns a jwt secret from a provided file path, otherwise saves a randomly generated one to datadir if none already exists
*/
function parseJwtSecret(config: Config, jwtFilePath?: string): Uint8Array {
let jwtSecret: Uint8Array
const defaultJwtPath = `${config.datadir}/jwtsecret`
const usedJwtPath = jwtFilePath ?? defaultJwtPath
// If jwtFilePath is provided, it should exist
if (jwtFilePath !== undefined && !existsSync(jwtFilePath)) {
throw EthereumJSErrorWithoutCode(`No file exists at provided jwt secret path=${jwtFilePath}`)
}
if (jwtFilePath !== undefined || existsSync(defaultJwtPath)) {
const jwtSecretContents = readFileSync(jwtFilePath ?? defaultJwtPath, 'utf-8').trim()
const hexPattern = new RegExp(/^(0x|0X)?(?<jwtSecret>[a-fA-F0-9]+)$/, 'g')
const jwtSecretHex = hexPattern.exec(jwtSecretContents)?.groups?.jwtSecret
if (jwtSecretHex === undefined || jwtSecretHex.length !== 64) {
throw Error('Need a valid 256 bit hex encoded secret')
}
jwtSecret = hexToBytes(`0x${jwtSecretHex}`)
} else {
const folderExists = existsSync(config.datadir)
if (!folderExists) {
mkdirSync(config.datadir, { recursive: true })
}
jwtSecret = randomBytes(32)
writeFileSync(defaultJwtPath, bytesToUnprefixedHex(jwtSecret), {})
config.logger?.info(`New Engine API JWT token created path=${defaultJwtPath}`)
}
config.logger?.info(`Using Engine API with JWT token authentication path=${usedJwtPath}`)
return jwtSecret
}
/**
* Starts and returns enabled RPCServers
*/
export function startRPCServers(client: EthereumClient, args: RPCArgs) {
const { config } = client
const servers: Server[] = []
const {
rpc,
rpcAddr,
rpcPort,
ws,
wsPort,
wsAddr,
rpcEngine,
rpcEngineAddr,
rpcEnginePort,
wsEngineAddr,
wsEnginePort,
jwtSecret: jwtSecretPath,
rpcEngineAuth,
rpcCors,
rpcDebug,
rpcDebugVerbose,
rpcEthMaxPayload,
rpcEngineMaxPayload,
} = args
const manager = new RPCManager(client, config)
const { logger } = config
const jwtSecret =
rpcEngine && rpcEngineAuth ? parseJwtSecret(config, jwtSecretPath) : new Uint8Array(0)
let withEngineMethods = false
if ((rpc || rpcEngine) && !config.saveReceipts) {
logger?.warn(
`Starting client without --saveReceipts might lead to interop issues with a CL especially if the CL intends to propose blocks, omitting methods=${saveReceiptsMethods}`,
)
}
if (rpc || ws) {
let rpcHttpServer
withEngineMethods = rpcEngine && rpcEnginePort === rpcPort && rpcEngineAddr === rpcAddr
const { server, namespaces, methods } = createRPCServer(manager, {
methodConfig: withEngineMethods ? MethodConfig.WithEngine : MethodConfig.WithoutEngine,
rpcDebugVerbose,
rpcDebug,
logger,
})
servers.push(server)
if (rpc) {
rpcHttpServer = createRPCServerListener({
RPCCors: rpcCors,
server,
withEngineMiddleware:
withEngineMethods && rpcEngineAuth
? {
jwtSecret,
unlessFn: (req: any) =>
Array.isArray(req.body)
? req.body.some((r: any) => r.method.includes('engine_')) === false
: req.body.method.includes('engine_') === false,
}
: undefined,
maxPayload: rpcEthMaxPayload,
})
rpcHttpServer.listen(rpcPort, rpcAddr)
logger?.info(
`Started JSON RPC Server address=http://${rpcAddr}:${rpcPort} namespaces=${namespaces}${
withEngineMethods ? ' rpcEngineAuth=' + rpcEngineAuth.toString() : ''
}`,
)
logger?.debug(
`Methods available at address=http://${rpcAddr}:${rpcPort} namespaces=${namespaces} methods=${Object.keys(
methods,
).join(',')}`,
)
}
if (ws) {
const opts: any = {
rpcCors,
server,
withEngineMiddleware: withEngineMethods && rpcEngineAuth ? { jwtSecret } : undefined,
}
if (rpcAddr === wsAddr && rpcPort === wsPort) {
// We want to load the websocket upgrade request to the same server
opts.httpServer = rpcHttpServer
}
const rpcWsServer = createWsRPCServerListener(opts)
if (rpcWsServer) rpcWsServer.listen(wsPort)
logger?.info(
`Started JSON RPC Server address=ws://${wsAddr}:${wsPort} namespaces=${namespaces}${
withEngineMethods ? ` rpcEngineAuth=${rpcEngineAuth}` : ''
}`,
)
logger?.debug(
`Methods available at address=ws://${wsAddr}:${wsPort} namespaces=${namespaces} methods=${Object.keys(
methods,
).join(',')}`,
)
}
}
if (rpcEngine && !(rpc && rpcPort === rpcEnginePort && rpcAddr === rpcEngineAddr)) {
const { server, namespaces, methods } = createRPCServer(manager, {
methodConfig: MethodConfig.EngineOnly,
rpcDebug,
rpcDebugVerbose,
logger,
})
servers.push(server)
const rpcHttpServer = createRPCServerListener({
RPCCors: rpcCors,
server,
withEngineMiddleware: rpcEngineAuth
? {
jwtSecret,
}
: undefined,
maxPayload: rpcEngineMaxPayload,
})
rpcHttpServer.listen(rpcEnginePort, rpcEngineAddr)
logger?.info(
`Started JSON RPC server address=http://${rpcEngineAddr}:${rpcEnginePort} namespaces=${namespaces} rpcEngineAuth=${rpcEngineAuth}`,
)
logger?.debug(
`Methods available at address=http://${rpcEngineAddr}:${rpcEnginePort} namespaces=${namespaces} methods=${Object.keys(
methods,
).join(',')}`,
)
if (ws) {
const opts: any = {
rpcCors,
server,
withEngineMiddleware: rpcEngineAuth ? { jwtSecret } : undefined,
}
if (rpcEngineAddr === wsEngineAddr && rpcEnginePort === wsEnginePort) {
// We want to load the websocket upgrade request to the same server
opts.httpServer = rpcHttpServer
}
const rpcWsServer = createWsRPCServerListener(opts)
if (rpcWsServer) rpcWsServer.listen(wsEnginePort, wsEngineAddr)
logger?.info(
`Started JSON RPC Server address=ws://${wsEngineAddr}:${wsEnginePort} namespaces=${namespaces} rpcEngineAuth=${rpcEngineAuth}`,
)
logger?.debug(
`Methods available at address=ws://${wsEngineAddr}:${wsEnginePort} namespaces=${namespaces} methods=${Object.keys(
methods,
).join(',')}`,
)
}
}
return servers
}
/**
* Output RPC help and exit
*/
export function helpRPC() {
/* eslint-disable no-console */
console.log('-'.repeat(27))
console.log('JSON-RPC: Supported Methods')
console.log('-'.repeat(27))
console.log()
for (const modName of modules.list) {
console.log(`${modName}:`)
const methods = RPCManager.getMethodNames((modules as any)[modName])
for (const methodName of methods) {
console.log(`-> ${modName.toLowerCase()}_${methodName}`)
}
console.log()
}
console.log()
/* eslint-enable no-console */
process.exit()
}