-
Notifications
You must be signed in to change notification settings - Fork 827
Client: (WIP) rework CLI startup logic using RpcConfig (#3983) #4013
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ether-wan
wants to merge
5
commits into
ethereumjs:master
Choose a base branch
from
ether-wan:client-cli-refactor
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+320
−180
Open
Changes from 3 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
2e689b8
Client: (WIP) rework CLI startup logic using RpcConfig (#3983)
ether-wan ffa06a8
Merge branch 'master' into client-cli-refactor
am1r021 995587c
Merge branch 'master' into client-cli-refactor
am1r021 e0d3c66
Merge remote-tracking branch 'origin/master' into pr/ether-wan/4013
acolytec3 ceaa824
clean up nits
acolytec3 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,23 +1,14 @@ | ||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs' | ||
import { | ||
EthereumJSErrorWithoutCode, | ||
bytesToUnprefixedHex, | ||
hexToBytes, | ||
randomBytes, | ||
} from '@ethereumjs/util' | ||
|
||
import { RPCManager, saveReceiptsMethods } from '../src/rpc/index.ts' | ||
import { RPCManager } 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' | ||
import type { RpcConfig } from '../src/rpc/config.ts' | ||
|
||
export type RPCArgs = { | ||
rpc: boolean | ||
|
@@ -39,191 +30,93 @@ export type RPCArgs = { | |
rpcCors: 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) { | ||
export function startRPCServers(client: EthereumClient, rpcConfigs: RpcConfig[]): Server[] { | ||
const { config } = client | ||
const servers: Server[] = [] | ||
const { | ||
rpc, | ||
rpcAddr, | ||
rpcPort, | ||
ws, | ||
wsPort, | ||
wsAddr, | ||
rpcEngine, | ||
rpcEngineAddr, | ||
rpcEnginePort, | ||
wsEngineAddr, | ||
wsEnginePort, | ||
jwtSecret: jwtSecretPath, | ||
rpcEngineAuth, | ||
rpcCors, | ||
rpcDebug, | ||
rpcDebugVerbose, | ||
} = 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, | ||
const serverGroups: Map<string, { rpcConfig: RpcConfig; server: any }> = new Map() | ||
|
||
for (const rpcConfig of rpcConfigs) { | ||
// unique key for each server: eth-rpc (http & ws), engine-rpc (http & ws) | ||
// used to create a single rpc server for each transport type | ||
const key = `${rpcConfig.type}-${rpcConfig.methodConfig}` | ||
|
||
let serverEntry = serverGroups.get(key) | ||
|
||
if (!serverEntry) { | ||
const { server, namespaces, methods } = createRPCServer(manager, { | ||
methodConfig: rpcConfig.methodConfig, | ||
rpcDebug: rpcConfig.debug, | ||
rpcDebugVerbose: rpcConfig.debugVerbose, | ||
logger: config.logger, | ||
}) | ||
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( | ||
|
||
servers.push(server) | ||
serverGroups.set(key, { rpcConfig, server }) | ||
serverEntry = { rpcConfig, server } | ||
|
||
config.logger?.info( | ||
`Created RPCServer for type=${rpcConfig.type} methodConfig=${rpcConfig.methodConfig} namespaces=${namespaces} methods=${Object.keys( | ||
methods, | ||
).join(',')}`, | ||
) | ||
} | ||
if (ws) { | ||
const opts: any = { | ||
rpcCors, | ||
|
||
const { server } = serverEntry | ||
// middleware for engine auth | ||
const middleware = | ||
rpcConfig.engineAuth && rpcConfig.jwtSecret | ||
? { | ||
jwtSecret: rpcConfig.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 | ||
|
||
if (rpcConfig.transport === 'http') { | ||
const httpServer = createRPCServerListener({ | ||
RPCCors: rpcConfig.cors, | ||
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 | ||
} | ||
withEngineMiddleware: middleware, | ||
}) | ||
httpServer.listen(rpcConfig.port, rpcConfig.address) | ||
|
||
const rpcWsServer = createWsRPCServerListener(opts) | ||
if (rpcWsServer) rpcWsServer.listen(wsPort) | ||
logger?.info( | ||
`Started JSON RPC Server address=ws://${wsAddr}:${wsPort} namespaces=${namespaces}${ | ||
withEngineMethods ? ` rpcEngineAuth=${rpcEngineAuth}` : '' | ||
config.logger?.info( | ||
`Started JSON RPC Server address=http://${rpcConfig.address}:${rpcConfig.port} type=${rpcConfig.type} ${ | ||
rpcConfig.engineAuth ? 'engineAuth=true' : '' | ||
}`, | ||
) | ||
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, | ||
}) | ||
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, | ||
if (rpcConfig.transport === 'ws') { | ||
const wsOpts: any = { | ||
RPCCors: rpcConfig.cors, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is it possible to add typing for this instead of casting to |
||
server, | ||
withEngineMiddleware: rpcEngineAuth ? { jwtSecret } : undefined, | ||
withEngineMiddleware: middleware, | ||
} | ||
|
||
if (rpcEngineAddr === wsEngineAddr && rpcEnginePort === wsEnginePort) { | ||
// We want to load the websocket upgrade request to the same server | ||
opts.httpServer = rpcHttpServer | ||
// Attach to existing HTTP server for upgrades if same port/address | ||
const httpKey = `${rpcConfig.type}-${rpcConfig.methodConfig}` | ||
if (rpcConfig.address === rpcConfig.address && serverGroups.has(httpKey)) { | ||
wsOpts.httpServer = serverGroups.get(httpKey)?.server | ||
} | ||
|
||
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(',')}`, | ||
) | ||
const wsServer = createWsRPCServerListener(wsOpts) | ||
if (wsServer) { | ||
wsServer.listen(rpcConfig.port) | ||
config.logger?.info( | ||
`Started JSON RPC WS Server address=ws://${rpcConfig.address}:${rpcConfig.port} namespaces=${rpcConfig.type} ${ | ||
rpcConfig.engineAuth ? 'engineAuth=true' : '' | ||
}`, | ||
) | ||
} | ||
} | ||
} | ||
|
||
|
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
generateRpcConfigs
->generateRpcConfig
(so: without thes
)to align with
generateClientConfig
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
(also further down the line there are a few
Configs
, can you please also rename consistently? Thanks! (we are a bit picky on naming things 🙂 ))