Skip to content

Commit

Permalink
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 babd512 commit 1c6be76
Show file tree
Hide file tree
Showing 8 changed files with 48 additions and 50 deletions.
10 changes: 5 additions & 5 deletions packages/block/src/block.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Trie } from '@ethereumjs/trie'
import { keccak256 } from 'ethereum-cryptography/keccak'
import { arrToBufArr, bufArrToArr, KECCAK256_RLP, bufferToHex } from '@ethereumjs/util'
import { arrToBufArr, bufArrToArr, KECCAK256_RLP, bufferToHex, isTruthy } from '@ethereumjs/util'
import { RLP } from 'rlp'
import { Common, ConsensusType } from '@ethereumjs/common'
import {
Expand Down Expand Up @@ -98,7 +98,7 @@ export class Block {

// parse transactions
const transactions = []
for (const txData of txsData || []) {
for (const txData of isTruthy(txsData) ? txsData : []) {
transactions.push(
TransactionFactory.fromBlockBodyData(txData, {
...opts,
Expand All @@ -118,10 +118,10 @@ export class Block {
// Disable this option here (all other options carried over), since this overwrites the provided Difficulty to an incorrect value
calcDifficultyFromHeader: undefined,
}
if (uncleOpts.hardforkByTD) {
if (isTruthy(uncleOpts.hardforkByTD)) {
delete uncleOpts.hardforkByBlockNumber
}
for (const uncleHeaderData of uhsData || []) {
for (const uncleHeaderData of isTruthy(uhsData) ? uhsData : []) {
uncleHeaders.push(BlockHeader.fromValuesArray(uncleHeaderData, uncleOpts))
}

Expand Down Expand Up @@ -241,7 +241,7 @@ export class Block {
const errors: string[] = []
this.transactions.forEach((tx, i) => {
const errs = <string[]>tx.validate(true)
if (this._common.isActivatedEIP(1559)) {
if (this._common.isActivatedEIP(1559) === true) {
if (tx.supports(Capability.EIP1559FeeMarket)) {
tx = tx as FeeMarketEIP1559Transaction
if (tx.maxFeePerGas < this.header.baseFeePerGas!) {
Expand Down
8 changes: 4 additions & 4 deletions packages/block/src/from-rpc.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { TransactionFactory, TypedTransaction, TxData } from '@ethereumjs/tx'
import { toBuffer, setLengthLeft } from '@ethereumjs/util'
import { toBuffer, setLengthLeft, isTruthy } from '@ethereumjs/util'
import { Block, BlockOptions } from './index'
import { numberToHex } from './helpers'

Expand All @@ -16,7 +16,7 @@ function normalizeTxParams(_txParams: any) {
txParams.value = numberToHex(txParams.value)

// strict byte length checking
txParams.to = txParams.to ? setLengthLeft(toBuffer(txParams.to), 20) : null
txParams.to = isTruthy(txParams.to) ? setLengthLeft(toBuffer(txParams.to), 20) : null

// v as raw signature value {0,1}
// v is the recovery bit and can be either {0,1} or {27,28}.
Expand All @@ -32,13 +32,13 @@ function normalizeTxParams(_txParams: any) {
*
* @param blockParams - Ethereum JSON RPC of block (eth_getBlockByNumber)
* @param uncles - Optional list of Ethereum JSON RPC of uncles (eth_getUncleByBlockHashAndIndex)
* @param chainOptions - An object describing the blockchain
* @param options - An object describing the blockchain
*/
export function blockFromRpc(blockParams: any, uncles: any[] = [], options?: BlockOptions) {
const header = blockHeaderFromRpc(blockParams, options)

const transactions: TypedTransaction[] = []
if (blockParams.transactions) {
if (isTruthy(blockParams.transactions)) {
const opts = { common: header._common }
for (const _txParams of blockParams.transactions) {
const txParams = normalizeTxParams(_txParams)
Expand Down
5 changes: 3 additions & 2 deletions packages/block/src/header-from-rpc.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { BlockHeader } from './header'
import { BlockOptions } from './types'
import { numberToHex } from './helpers'
import { isTruthy } from '@ethereumjs/util'

/**
* Creates a new block header object from Ethereum JSON RPC.
*
* @param blockParams - Ethereum JSON RPC of block (eth_getBlockByNumber)
* @param chainOptions - An object describing the blockchain
* @param options - An object describing the blockchain
*/
export function blockHeaderFromRpc(blockParams: any, options?: BlockOptions) {
const {
Expand Down Expand Up @@ -36,7 +37,7 @@ export function blockHeaderFromRpc(blockParams: any, options?: BlockOptions) {
coinbase: miner,
stateRoot,
transactionsTrie: transactionsRoot,
receiptTrie: receiptRoot || receiptsRoot,
receiptTrie: isTruthy(receiptRoot) ? receiptRoot : receiptsRoot,
logsBloom,
difficulty: numberToHex(difficulty),
number,
Expand Down
47 changes: 21 additions & 26 deletions packages/block/src/header.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import {
toType,
TypeOutput,
zeros,
isTruthy,
isFalsy,
} from '@ethereumjs/util'
import { RLP } from 'rlp'
import { BlockHeaderBuffer, BlockOptions, HeaderData, JsonHeader } from './types'
Expand Down Expand Up @@ -65,7 +67,7 @@ export class BlockHeader {
* EIP-4399: After merge to PoS, `mixHash` supplanted as `prevRandao`
*/
get prevRandao() {
if (!this._common.isActivatedEIP(4399)) {
if (this._common.isActivatedEIP(4399) === false) {
const msg = this._errorMsg(
'The prevRandao parameter can only be accessed when EIP-4399 is activated'
)
Expand All @@ -87,17 +89,17 @@ export class BlockHeader {
/**
* Static constructor to create a block header from a RLP-serialized header
*
* @param headerData
* @param serializedHeaderData
* @param opts
*/
public static fromRLPSerializedHeader(serialized: Buffer, opts: BlockOptions = {}) {
const values = arrToBufArr(RLP.decode(Uint8Array.from(serialized))) as Buffer[]
public static fromRLPSerializedHeader(serializedHeaderData: Buffer, opts: BlockOptions = {}) {
const values = arrToBufArr(RLP.decode(Uint8Array.from(serializedHeaderData)))

if (!Array.isArray(values)) {
throw new Error('Invalid serialized header input. Must be array')
}

return BlockHeader.fromValuesArray(values, opts)
return BlockHeader.fromValuesArray(values as Buffer[], opts)
}

/**
Expand Down Expand Up @@ -198,7 +200,7 @@ export class BlockHeader {

const parentHash = toType(headerData.parentHash, TypeOutput.Buffer) ?? defaults.parentHash
const uncleHash = toType(headerData.uncleHash, TypeOutput.Buffer) ?? defaults.uncleHash
const coinbase = headerData.coinbase
const coinbase = isTruthy(headerData.coinbase)
? new Address(toType(headerData.coinbase, TypeOutput.Buffer))
: defaults.coinbase
const stateRoot = toType(headerData.stateRoot, TypeOutput.Buffer) ?? defaults.stateRoot
Expand All @@ -222,11 +224,9 @@ export class BlockHeader {
this._common.setHardforkByBlockNumber(number, options.hardforkByTD)
}

if (this._common.isActivatedEIP(1559)) {
if (this._common.isActivatedEIP(1559) === true) {
if (baseFeePerGas === undefined) {
const londonHfBlock = this._common.hardforkBlock(Hardfork.London)
const isInitialEIP1559Block = number === londonHfBlock
if (isInitialEIP1559Block) {
if (number === this._common.hardforkBlock(Hardfork.London)) {
baseFeePerGas = this._common.param('gasConfig', 'initialBaseFee')
} else {
// Minimum possible value for baseFeePerGas is 7,
Expand Down Expand Up @@ -344,14 +344,13 @@ export class BlockHeader {
}

// Validation for EIP-1559 blocks
if (this._common.isActivatedEIP(1559)) {
if (this._common.isActivatedEIP(1559) === true) {
if (typeof this.baseFeePerGas !== 'bigint') {
const msg = this._errorMsg('EIP1559 block has no base fee field')
throw new Error(msg)
}
const londonHfBlock = this._common.hardforkBlock(Hardfork.London)
const isInitialEIP1559Block = londonHfBlock && this.number === londonHfBlock
if (isInitialEIP1559Block) {
if (isTruthy(londonHfBlock) && this.number === londonHfBlock) {
const initialBaseFee = this._common.param('gasConfig', 'initialBaseFee')
if (this.baseFeePerGas! !== initialBaseFee) {
const msg = this._errorMsg('Initial EIP1559 block does not have initial base fee')
Expand Down Expand Up @@ -455,7 +454,7 @@ export class BlockHeader {
// EIP-1559: assume double the parent gas limit on fork block
// to adopt to the new gas target centered logic
const londonHardforkBlock = this._common.hardforkBlock(Hardfork.London)
if (londonHardforkBlock && this.number === londonHardforkBlock) {
if (isTruthy(londonHardforkBlock) && this.number === londonHardforkBlock) {
const elasticity = this._common.param('gasConfig', 'elasticityMultiplier')
parentGasLimit = parentGasLimit * elasticity
}
Expand Down Expand Up @@ -489,7 +488,7 @@ export class BlockHeader {
* Calculates the base fee for a potential next block
*/
public calcNextBaseFee(): bigint {
if (!this._common.isActivatedEIP(1559)) {
if (this._common.isActivatedEIP(1559) === false) {
const msg = this._errorMsg(
'calcNextBaseFee() can only be called with EIP1559 being activated'
)
Expand Down Expand Up @@ -551,7 +550,7 @@ export class BlockHeader {
this.nonce,
]

if (this._common.isActivatedEIP(1559)) {
if (this._common.isActivatedEIP(1559) === true) {
rawItems.push(bigIntToUnpaddedBuffer(this.baseFeePerGas!))
}

Expand Down Expand Up @@ -615,7 +614,7 @@ export class BlockHeader {
// We use a ! here as TS cannot follow this hardfork-dependent logic, but it always gets assigned
let dif!: bigint

if (this._common.hardforkGteHardfork(hardfork, Hardfork.Byzantium)) {
if (this._common.hardforkGteHardfork(hardfork, Hardfork.Byzantium) === true) {
// max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99) (EIP100)
const uncleAddend = parentBlockHeader.uncleHash.equals(KECCAK256_RLP_ARRAY) ? 1 : 2
let a = BigInt(uncleAddend) - (blockTs - parentTs) / BigInt(9)
Expand All @@ -627,13 +626,13 @@ export class BlockHeader {
dif = parentDif + offset * a
}

if (this._common.hardforkGteHardfork(hardfork, Hardfork.Byzantium)) {
if (this._common.hardforkGteHardfork(hardfork, Hardfork.Byzantium) === true) {
// Get delay as parameter from common
num = num - this._common.param('pow', 'difficultyBombDelay')
if (num < BigInt(0)) {
num = BigInt(0)
}
} else if (this._common.hardforkGteHardfork(hardfork, Hardfork.Homestead)) {
} else if (this._common.hardforkGteHardfork(hardfork, Hardfork.Homestead) === true) {
// 1 - (block_timestamp - parent_timestamp) // 10
let a = BigInt(1) - (blockTs - parentTs) / BigInt(10)
const cutoff = BigInt(-99)
Expand Down Expand Up @@ -810,7 +809,7 @@ export class BlockHeader {
mixHash: '0x' + this.mixHash.toString('hex'),
nonce: '0x' + this.nonce.toString('hex'),
}
if (this._common.isActivatedEIP(1559)) {
if (this._common.isActivatedEIP(1559) === true) {
jsonDict.baseFeePerGas = bigIntToHex(this.baseFeePerGas!)
}
return jsonDict
Expand All @@ -821,15 +820,11 @@ export class BlockHeader {
* activation block (see: https://blog.slock.it/hard-fork-specification-24b889e70703)
*/
private _validateDAOExtraData() {
if (!this._common.hardforkIsActiveOnBlock(Hardfork.Dao, this.number)) {
if (this._common.hardforkIsActiveOnBlock(Hardfork.Dao, this.number) === false) {
return
}
const DAOActivationBlock = this._common.hardforkBlock(Hardfork.Dao)
if (
!DAOActivationBlock ||
DAOActivationBlock === BigInt(0) ||
this.number < DAOActivationBlock
) {
if (isFalsy(DAOActivationBlock) || this.number < DAOActivationBlock) {
return
}
const DAO_ExtraData = Buffer.from('64616f2d686172642d666f726b', 'hex')
Expand Down
4 changes: 2 additions & 2 deletions packages/block/src/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { isHexString } from '@ethereumjs/util'
import { isFalsy, isHexString } from '@ethereumjs/util'

/**
* Returns a 0x-prefixed hex number string from a hex string or string integer.
* @param {string} input string to check, convert, and return
*/
export const numberToHex = function (input?: string) {
if (!input) return undefined
if (isFalsy(input)) return undefined
if (!isHexString(input)) {
const regex = new RegExp(/^\d+$/) // test to make sure input contains only digits
if (!regex.test(input)) {
Expand Down
4 changes: 2 additions & 2 deletions packages/block/test/block.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ tape('[Block]: block functions', function (t) {
await block.validateData()
st.fail('should throw')
} catch (error: any) {
st.ok(error.message.includes('invalid transaction trie'))
st.ok((error.message as string).includes('invalid transaction trie'))
}
})

Expand Down Expand Up @@ -225,7 +225,7 @@ tape('[Block]: block functions', function (t) {
await block.validateData()
st.fail('should throw')
} catch (error: any) {
st.ok(error.message.includes('invalid uncle hash'))
st.ok((error.message as string).includes('invalid uncle hash'))
}
})

Expand Down
14 changes: 7 additions & 7 deletions packages/block/test/header.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ tape('[Block]: Header functions', function (t) {
BlockHeader.fromHeaderData({ ...data, extraData }, opts)
st.fail(testCase)
} catch (error: any) {
st.ok(error.message.includes('invalid amount of extra data'), testCase)
st.ok((error.message as string).includes('invalid amount of extra data'), testCase)
}

// PoA
Expand Down Expand Up @@ -218,7 +218,7 @@ tape('[Block]: Header functions', function (t) {
t.fail(testCase)
} catch (error: any) {
t.ok(
error.message.includes(
(error.message as string).includes(
'extraData must be 97 bytes on non-epoch transition blocks, received 32 bytes'
),
testCase
Expand All @@ -239,7 +239,7 @@ tape('[Block]: Header functions', function (t) {
st.fail(testCase)
} catch (error: any) {
st.ok(
error.message.includes(
(error.message as string).includes(
'invalid signer list length in extraData, received signer length of 41 (not divisible by 20)'
),
testCase
Expand Down Expand Up @@ -272,7 +272,7 @@ tape('[Block]: Header functions', function (t) {
await header.validate(blockchain)
st.fail(testCase)
} catch (error: any) {
st.ok(error.message.includes('invalid timestamp diff (lower than period)'), testCase)
st.ok((error.message as string).includes('invalid timestamp diff (lower than period)'), testCase)
}
testCase = 'should not throw on timestamp diff equal to period'
Expand All @@ -293,7 +293,7 @@ tape('[Block]: Header functions', function (t) {
await header.validate(blockchain)
st.fail('should throw')
} catch (error: any) {
if (error.message.includes('coinbase must be filled with zeros on epoch transition blocks')) {
if ((error.message as string).includes('coinbase must be filled with zeros on epoch transition blocks')) {
st.pass('error thrown')
} else {
st.fail('should throw with appropriate error')
Expand All @@ -309,7 +309,7 @@ tape('[Block]: Header functions', function (t) {
await header.validate(blockchain)
st.fail('should throw')
} catch (error: any) {
if (error.message.includes('mixHash must be filled with zeros')) {
if ((error.message as string).includes('mixHash must be filled with zeros')) {
st.pass('error thrown')
} else {
st.fail('should throw with appropriate error')
Expand All @@ -324,7 +324,7 @@ tape('[Block]: Header functions', function (t) {
header.validateCliqueDifficulty(blockchain)
st.fail(testCase)
} catch (error: any) {
if (error.message.includes('difficulty for clique block must be INTURN (2) or NOTURN (1)')) {
if ((error.message as string).includes('difficulty for clique block must be INTURN (2) or NOTURN (1)')) {
st.pass('error thrown on invalid clique difficulty')
} else {
st.fail('should throw with appropriate error')
Expand Down
6 changes: 4 additions & 2 deletions packages/block/test/util.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Chain, Common, Hardfork } from '@ethereumjs/common'
import { keccak256 } from 'ethereum-cryptography/keccak'
import { bufArrToArr } from '@ethereumjs/util'
import { bufArrToArr, isTruthy } from '@ethereumjs/util'
import { RLP } from 'rlp'
import { Block, BlockHeader } from '../src'

Expand Down Expand Up @@ -30,7 +30,9 @@ function createBlock(

const londonHfBlock = common.hardforkBlock(Hardfork.London)
const baseFeePerGas =
londonHfBlock && number > londonHfBlock ? parentBlock.header.calcNextBaseFee() : undefined
isTruthy(londonHfBlock) && number > londonHfBlock
? parentBlock.header.calcNextBaseFee()
: undefined

return Block.fromBlockData(
{
Expand Down

0 comments on commit 1c6be76

Please sign in to comment.