Skip to content

Commit

Permalink
client: block: apply strict-boolean-expressions
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrocheleau committed Jul 10, 2022
1 parent 6cff52a commit 3348602
Show file tree
Hide file tree
Showing 50 changed files with 326 additions and 255 deletions.
47 changes: 25 additions & 22 deletions packages/client/bin/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { existsSync } from 'fs'
import { ensureDirSync, readFileSync, removeSync } from 'fs-extra'
import { Blockchain } from '@ethereumjs/blockchain'
import { Chain, Common, Hardfork, ConsensusAlgorithm } from '@ethereumjs/common'
import { Address, toBuffer } from '@ethereumjs/util'
import { Address, isFalsy, isTruthy, toBuffer } from '@ethereumjs/util'
import {
parseMultiaddrs,
parseGenesisState,
Expand All @@ -19,7 +19,7 @@ import { EthereumClient } from '../lib/client'
import { Config, DataDirectory, SyncMode } from '../lib/config'
import { Logger, getLogger } from '../lib/logging'
import { startRPCServers, helprpc } from './startRpc'
import type { FullEthereumService } from '../lib/service'
import { FullEthereumService } from '../lib/service'
import { GenesisState } from '@ethereumjs/blockchain/dist/genesisStates'
import { Level } from 'level'
import { AbstractLevel } from 'abstract-level'
Expand Down Expand Up @@ -327,17 +327,17 @@ async function executeBlocks(client: EthereumClient) {
)
process.exit()
}
const { execution } = client.services.find((s) => s.name === 'eth') as FullEthereumService
if (!execution) throw new Error('executeBlocks requires execution')
await execution.executeBlocks(first, last, txHashes)
const service = client.services.find((s) => s.name === 'eth')
if (!(service instanceof FullEthereumService)) throw new Error('executeBlocks requires execution')
await service.execution.executeBlocks(first, last, txHashes)
}

/**
* Starts the client on a specified block number.
* Note: this is destructive and removes blocks from the blockchain. Please back up your datadir.
*/
async function startBlock(client: EthereumClient) {
if (!args.startBlock) return
if (isFalsy(typeof args.startBlock)) return
const startBlock = BigInt(args.startBlock)
const { blockchain } = client.chain
const height = (await blockchain.getCanonicalHeadHeader()).number
Expand Down Expand Up @@ -369,7 +369,7 @@ async function startClient(config: Config, customGenesisState?: GenesisState) {
const dbs = initDBs(config)

let blockchain
if (customGenesisState) {
if (isTruthy(customGenesisState)) {
const validateConsensus = config.chainCommon.consensusAlgorithm() === ConsensusAlgorithm.Clique
blockchain = await Blockchain.create({
db: dbs.chainDB,
Expand All @@ -388,13 +388,13 @@ async function startClient(config: Config, customGenesisState?: GenesisState) {
...dbs,
})

if (args.startBlock) {
if (isTruthy(args.startBlock)) {
await startBlock(client)
}

await client.open()

if (args.executeBlocks) {
if (isTruthy(args.executeBlocks)) {
// Special block execution debug mode (does not change any state)
await executeBlocks(client)
} else {
Expand Down Expand Up @@ -547,7 +547,7 @@ function generateAccount(): Account {
* Main entry point to start a client
*/
async function run() {
if (args.helprpc) {
if (isTruthy(args.helprpc)) {
// Output RPC help and exit
return helprpc()
}
Expand All @@ -557,14 +557,14 @@ async function run() {

// Configure accounts for mining and prefunding in a local devnet
const accounts: Account[] = []
if (args.unlock) {
if (isTruthy(args.unlock)) {
accounts.push(...(await inputAccounts()))
}

let customGenesisState: GenesisState | undefined
let common = new Common({ chain, hardfork: Hardfork.Chainstart })

if (args.dev) {
if (isTruthy(args.dev)) {
args.discDns = false
if (accounts.length === 0) {
// If generating new keys delete old chain data to prevent genesis block mismatch
Expand All @@ -578,15 +578,17 @@ async function run() {

// Configure common based on args given
if (
(args.customChainParams || args.customGenesisState || args.gethGenesis) &&
(args.network !== 'mainnet' || args.networkId)
(isTruthy(args.customChainParams) ||
isTruthy(args.customGenesisState) ||
isTruthy(args.gethGenesis)) &&
(args.network !== 'mainnet' || isTruthy(args.networkId))
) {
console.error('cannot specify both custom chain parameters and preset network ID')
process.exit()
}
// Use custom chain parameters file if specified
if (args.customChain) {
if (!args.customGenesisState) {
if (isTruthy(args.customChain)) {
if (isFalsy(args.customGenesisState)) {
console.error('cannot have custom chain parameters without genesis state')
process.exit()
}
Expand All @@ -601,7 +603,7 @@ async function run() {
console.error(`invalid chain parameters: ${err.message}`)
process.exit()
}
} else if (args.gethGenesis) {
} else if (isTruthy(args.gethGenesis)) {
// Use geth genesis parameters file if specified
const genesisFile = JSON.parse(readFileSync(args.gethGenesis, 'utf-8'))
const chainName = path.parse(args.gethGenesis).base.split('.')[0]
Expand All @@ -613,7 +615,7 @@ async function run() {
customGenesisState = await parseGenesisState(genesisFile)
}

if (args.mine && accounts.length === 0) {
if (isTruthy(args.mine) && accounts.length === 0) {
console.error(
'Please provide an account to mine blocks with `--unlock [address]` or use `--dev` to generate'
)
Expand All @@ -625,8 +627,8 @@ async function run() {
ensureDirSync(configDirectory)
const key = await Config.getClientKey(datadir, common)
logger = getLogger(args)
const bootnodes = args.bootnodes ? parseMultiaddrs(args.bootnodes) : undefined
const multiaddrs = args.multiaddrs ? parseMultiaddrs(args.multiaddrs) : undefined
const bootnodes = isTruthy(args.bootnodes) ? parseMultiaddrs(args.bootnodes) : undefined
const multiaddrs = isTruthy(args.multiaddrs) ? parseMultiaddrs(args.multiaddrs) : undefined
const config = new Config({
accounts,
bootnodes,
Expand All @@ -644,7 +646,7 @@ async function run() {
maxPeers: args.maxPeers,
maxPerRequest: args.maxPerRequest,
maxFetcherJobs: args.maxFetcherJobs,
mine: args.mine || args.dev,
mine: isTruthy(args.mine) ? args.mine : args.dev,
minerCoinbase: args.minerCoinbase,
minPeers: args.minPeers,
multiaddrs,
Expand All @@ -658,7 +660,8 @@ async function run() {
config.events.setMaxListeners(50)

const client = await startClient(config, customGenesisState)
const servers = args.rpc || args.rpcEngine ? startRPCServers(client, args) : []
const servers =
isTruthy(args.rpc) || isTruthy(args.rpcEngine) ? startRPCServers(client, args) : []

process.on('SIGINT', async () => {
config.logger.info('Caught interrupt signal. Shutting down...')
Expand Down
8 changes: 4 additions & 4 deletions packages/client/bin/startRpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,11 @@ type RPCArgs = {
*/
function parseJwtSecret(config: Config, jwtFilePath?: string): Buffer {
let jwtSecret
if (jwtFilePath) {
if (typeof jwtFilePath === 'string') {
const jwtSecretContents = readFileSync(jwtFilePath, 'utf-8').trim()
const hexPattern = new RegExp(/^(0x|0X)?(?<jwtSecret>[a-fA-F0-9]+)$/, 'g')
const jwtSecretHex = hexPattern.exec(jwtSecretContents)?.groups?.jwtSecret
if (!jwtSecretHex || jwtSecretHex.length != 64) {
if (typeof jwtSecretHex === 'undefined' || jwtSecretHex.length !== 64) {
throw Error('Need a valid 256 bit hex encoded secret')
}
config.logger.debug(`Read a hex encoded jwt secret from path=${jwtFilePath}`)
Expand Down Expand Up @@ -103,8 +103,8 @@ export function startRPCServers(client: EthereumClient, args: RPCArgs) {
jwtSecret,
unlessFn: (req: any) =>
Array.isArray(req.body)
? !req.body.some((r: any) => r.method.includes('engine_'))
: !req.body.method.includes('engine_'),
? req.body.some((r: any) => r.method.includes('engine_')) === false
: req.body.method.includes('engine_') === false,
}
: undefined,
})
Expand Down
3 changes: 2 additions & 1 deletion packages/client/browser/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ export async function createClient(args: any) {
const datadir = args.datadir ?? Config.DATADIR_DEFAULT
const common = new Common({ chain: args.network ?? Chain.Mainnet })
const key = await Config.getClientKey(datadir, common)
const bootnodes = args.bootnodes ? parseMultiaddrs(args.bootnodes) : undefined
const bootnodes =
typeof args.bootnodes !== 'undefined' ? parseMultiaddrs(args.bootnodes) : undefined
const config = new Config({
common,
key,
Expand Down
4 changes: 2 additions & 2 deletions packages/client/lib/execution/receipt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,12 +111,12 @@ export class ReceiptsManager extends MetaDBManager {
*/
async getReceipts(
blockHash: Buffer,
calcBloom?: Boolean,
calcBloom?: boolean,
includeTxType?: true
): Promise<TxReceiptWithType[]>
async getReceipts(
blockHash: Buffer,
calcBloom?: Boolean,
calcBloom?: boolean,
includeTxType?: false
): Promise<TxReceipt[]>
async getReceipts(
Expand Down
24 changes: 13 additions & 11 deletions packages/client/lib/execution/vmexecution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export class VMExecution extends Execution {
constructor(options: ExecutionOptions) {
super(options)

if (!this.config.vm) {
if (typeof this.config.vm === 'undefined') {
const trie = new Trie({ db: new LevelDB(this.stateDB) })

const stateManager = new DefaultStateManager({
Expand Down Expand Up @@ -92,7 +92,7 @@ export class VMExecution extends Execution {
const result = await this.vm.runBlock(opts)
receipts = result.receipts
}
if (receipts) {
if (typeof receipts !== 'undefined') {
// Save receipts
this.pendingReceipts?.set(block.hash().toString('hex'), receipts)
}
Expand Down Expand Up @@ -147,7 +147,7 @@ export class VMExecution extends Execution {

while (
(numExecuted === undefined || (loop && numExecuted === this.NUM_BLOCKS_PER_ITERATION)) &&
!startHeadBlock.hash().equals(canonicalHead.hash())
startHeadBlock.hash().equals(canonicalHead.hash()) === false
) {
let txCounter = 0
headBlock = undefined
Expand Down Expand Up @@ -242,23 +242,25 @@ export class VMExecution extends Execution {
)
numExecuted = await this.vmPromise

if (errorBlock) {
if (typeof errorBlock !== 'undefined') {
await this.chain.blockchain.setIteratorHead('vm', (errorBlock as Block).header.parentHash)
return 0
}

const endHeadBlock = await this.vm.blockchain.getIteratorHead('vm')
if (numExecuted && numExecuted > 0) {
if (typeof numExecuted === 'number' && numExecuted > 0) {
const firstNumber = startHeadBlock.header.number
const firstHash = short(startHeadBlock.hash())
const lastNumber = endHeadBlock.header.number
const lastHash = short(endHeadBlock.hash())
const baseFeeAdd = this.config.execCommon.gteHardfork(Hardfork.London)
? `baseFee=${endHeadBlock.header.baseFeePerGas} `
: ''
const tdAdd = this.config.execCommon.gteHardfork(Hardfork.Merge)
? ''
: `td=${this.chain.blocks.td} `
const baseFeeAdd =
this.config.execCommon.gteHardfork(Hardfork.London) === true
? `baseFee=${endHeadBlock.header.baseFeePerGas} `
: ''
const tdAdd =
this.config.execCommon.gteHardfork(Hardfork.Merge) === true
? ''
: `td=${this.chain.blocks.td} `
this.config.logger.info(
`Executed blocks count=${numExecuted} first=${firstNumber} hash=${firstHash} ${tdAdd}${baseFeeAdd}hardfork=${this.hardfork} last=${lastNumber} hash=${lastHash} txs=${txCounter}`
)
Expand Down
15 changes: 8 additions & 7 deletions packages/client/lib/logging.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { isFalsy, isTruthy } from '@ethereumjs/util'
import * as chalk from 'chalk'
import { createLogger, format, transports as wTransports, Logger as WinstonLogger } from 'winston'
const DailyRotateFile = require('winston-daily-rotate-file')
Expand Down Expand Up @@ -28,10 +29,10 @@ enum LevelColors {
* Adds stack trace to error message if included
*/
const errorFormat = format((info: any) => {
if (info.message instanceof Error && info.message.stack) {
if (info.message instanceof Error && isTruthy(info.message.stack)) {
return { ...info, message: info.message.stack }
}
if (info instanceof Error && info.stack) {
if (info instanceof Error && isTruthy(info.stack)) {
return { ...info, message: info.stack }
}
return info
Expand All @@ -51,7 +52,7 @@ function logFormat(colors = false) {
return printf((info: any) => {
let level = info.level.toUpperCase()

if (!info.message) info.message = '(empty message)'
if (isFalsy(info.message)) info.message = '(empty message)'

if (colors) {
const colorLevel = LevelColors[info.level as keyof typeof LevelColors]
Expand All @@ -61,8 +62,8 @@ function logFormat(colors = false) {
const regex = /(\w+)=(.+?)(?:\s|$)/g
const replaceFn = (_: any, tag: string, char: string) => `${color(tag)}=${char} `
info.message = info.message.replace(regex, replaceFn)
if (info.attentionCL) info.attentionCL = info.attentionCL.replace(regex, replaceFn)
if (info.attentionHF) info.attentionHF = info.attentionHF.replace(regex, replaceFn)
if (isTruthy(info.attentionCL)) info.attentionCL = info.attentionCL.replace(regex, replaceFn)
if (isTruthy(info.attentionHF)) info.attentionHF = info.attentionHF.replace(regex, replaceFn)
}

if (info.attentionCL !== undefined) attentionCL = info.attentionCL
Expand Down Expand Up @@ -97,7 +98,7 @@ function logFileTransport(args: any) {
level: args.logLevelFile,
format: formatConfig(),
}
if (!args.logRotate) {
if (isFalsy(args.logRotate)) {
return new wTransports.File({
...opts,
filename,
Expand Down Expand Up @@ -125,7 +126,7 @@ export function getLogger(args: { [key: string]: any } = { loglevel: 'info' }) {
format: formatConfig(true),
}),
]
if (args.logFile) {
if (isTruthy(args.logFile)) {
transports.push(logFileTransport(args))
}
const logger = createLogger({
Expand Down
Loading

0 comments on commit 3348602

Please sign in to comment.