From 7d5d4ee42070e5e55a03585a6aa91aa5d8c93426 Mon Sep 17 00:00:00 2001 From: ScottyPoi Date: Tue, 24 Sep 2024 13:28:28 -0600 Subject: [PATCH 01/21] Edit eslint typescript rules --- config/eslint.cjs | 3 ++- config/tsconfig.json | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/config/eslint.cjs b/config/eslint.cjs index d2f97618a8..4ee5b1ef17 100644 --- a/config/eslint.cjs +++ b/config/eslint.cjs @@ -56,7 +56,8 @@ module.exports = { 'error', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }, ], - '@typescript-eslint/no-redeclare': ['error'], + '@typescript-eslint/no-redeclare': '0', + '@typescript-eslint/no-ex-assign': '0', '@typescript-eslint/no-unnecessary-condition': 'off', '@typescript-eslint/prefer-nullish-coalescing': 'error', '@typescript-eslint/restrict-plus-operands': 'off', diff --git a/config/tsconfig.json b/config/tsconfig.json index 5f6f0ee8f8..c15ecd7148 100644 --- a/config/tsconfig.json +++ b/config/tsconfig.json @@ -14,6 +14,7 @@ "strict": true, "target": "es2020", "lib": ["ES2020", "DOM"], - "skipLibCheck": true + "skipLibCheck": true, + "useUnknownInCatchVariables": false } } From 3bd3d675903b495b8cb18a60a6c579d1d874e2d2 Mon Sep 17 00:00:00 2001 From: ScottyPoi Date: Tue, 24 Sep 2024 13:29:04 -0600 Subject: [PATCH 02/21] block: remove unused e variable --- packages/block/src/block/block.ts | 4 ++-- packages/block/src/header/header.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/block/src/block/block.ts b/packages/block/src/block/block.ts index b6613a2791..6ae073c0f1 100644 --- a/packages/block/src/block/block.ts +++ b/packages/block/src/block/block.ts @@ -607,13 +607,13 @@ export class Block { let hash = '' try { hash = bytesToHex(this.hash()) - } catch (e: any) { + } catch { hash = 'error' } let hf = '' try { hf = this.common.hardfork() - } catch (e: any) { + } catch { hf = 'error' } let errorStr = `block number=${this.header.number} hash=${hash} ` diff --git a/packages/block/src/header/header.ts b/packages/block/src/header/header.ts index 9f24919f56..41760d5593 100644 --- a/packages/block/src/header/header.ts +++ b/packages/block/src/header/header.ts @@ -806,13 +806,13 @@ export class BlockHeader { let hash = '' try { hash = bytesToHex(this.hash()) - } catch (e: any) { + } catch { hash = 'error' } let hf = '' try { hf = this.common.hardfork() - } catch (e: any) { + } catch { hf = 'error' } let errorStr = `block header number=${this.number} hash=${hash} ` From feb647b6644d3602cde69628941125f5c329d02f Mon Sep 17 00:00:00 2001 From: ScottyPoi Date: Tue, 24 Sep 2024 13:30:26 -0600 Subject: [PATCH 03/21] block/test: replace (e: any) pattern with Error type check --- packages/block/test/block.spec.ts | 30 +++++++-- packages/block/test/eip1559block.spec.ts | 40 ++++++++--- packages/block/test/from-rpc.spec.ts | 5 +- packages/block/test/header.spec.ts | 85 +++++++++++++++++++----- packages/block/test/mergeBlock.spec.ts | 35 ++++++++-- 5 files changed, 156 insertions(+), 39 deletions(-) diff --git a/packages/block/test/block.spec.ts b/packages/block/test/block.spec.ts index 6ad2c932a3..044c6c4c85 100644 --- a/packages/block/test/block.spec.ts +++ b/packages/block/test/block.spec.ts @@ -154,7 +154,10 @@ describe('[Block]: block functions', () => { try { createBlockFromRLP(blockRlp, { common }) assert.ok(true, 'should pass') - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } assert.fail('should not throw') } }) @@ -165,7 +168,10 @@ describe('[Block]: block functions', () => { try { createBlockFromRPC(testdataFromRPCGoerliData, [], { common }) assert.ok(true, 'does not throw') - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } assert.fail('error thrown') } }) @@ -184,7 +190,10 @@ describe('[Block]: block functions', () => { try { await block.validateData() assert.fail('should throw') - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } assert.ok((error.message as string).includes('invalid transaction trie')) } }) @@ -205,7 +214,10 @@ describe('[Block]: block functions', () => { try { await block.validateData() assert.fail('should throw') - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } assert.ok((error.message as string).includes('unsigned')) } }) @@ -237,7 +249,10 @@ describe('[Block]: block functions', () => { try { await block.validateData() assert.fail('should throw') - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } assert.ok((error.message as string).includes('invalid uncle hash')) } }) @@ -260,7 +275,10 @@ describe('[Block]: block functions', () => { try { await fn assert.fail('should throw') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok((e.message as string).includes(errorMsg)) } } diff --git a/packages/block/test/eip1559block.spec.ts b/packages/block/test/eip1559block.spec.ts index 8cc3757df8..835655c226 100644 --- a/packages/block/test/eip1559block.spec.ts +++ b/packages/block/test/eip1559block.spec.ts @@ -72,7 +72,10 @@ describe('EIP1559 tests', () => { }, ) assert.fail('should throw when baseFeePerGas is not set to initial base fee') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } const expectedError = 'Initial EIP1559 block does not have initial base fee' assert.ok( e.message.includes(expectedError), @@ -96,7 +99,10 @@ describe('EIP1559 tests', () => { ) ;(header as any).baseFeePerGas = undefined await (header as any)._genericFormatValidation() - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } const expectedError = 'EIP1559 block has no base fee field' assert.ok( e.message.includes(expectedError), @@ -141,7 +147,10 @@ describe('EIP1559 tests', () => { }, ) assert.fail('should throw') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok(e.message.includes('base fee'), 'should throw on wrong initial base fee') } }) @@ -199,7 +208,10 @@ describe('EIP1559 tests', () => { }, ) assert.fail('should throw') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok(e.message.includes('too much gas used'), 'should throw when elasticity is exceeded') } }) @@ -325,7 +337,10 @@ describe('EIP1559 tests', () => { try { header.validateGasLimit(genesis.header) assert.fail('should throw') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.message.includes('gas limit increased too much'), 'should throw if gas limit is increased too much (HF transition block)', @@ -349,7 +364,10 @@ describe('EIP1559 tests', () => { try { header.validateGasLimit(block1.header) assert.fail('should throw') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.message.includes('gas limit increased too much'), 'should throw if gas limit is increased too much (post-HF transition block)', @@ -375,7 +393,10 @@ describe('EIP1559 tests', () => { try { header.validateGasLimit(genesis.header) assert.fail('should throw') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.message.includes('gas limit decreased too much'), 'should throw if gas limit is decreased too much (HF transition block)', @@ -399,7 +420,10 @@ describe('EIP1559 tests', () => { try { header.validateGasLimit(block1.header) assert.fail('should throw') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.message.includes('gas limit decreased too much'), 'should throw if gas limit is decreased too much (post-HF transition block)', diff --git a/packages/block/test/from-rpc.spec.ts b/packages/block/test/from-rpc.spec.ts index b50b5a207c..56fec1fc67 100644 --- a/packages/block/test/from-rpc.spec.ts +++ b/packages/block/test/from-rpc.spec.ts @@ -223,7 +223,10 @@ describe('[fromJSONRPCProvider]', () => { try { await createBlockFromJSONRPCProvider(provider, bytesToHex(randomBytes(32)), {}) assert.fail('should throw') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok( err.message.includes('No block data returned from provider'), 'returned correct error message', diff --git a/packages/block/test/header.spec.ts b/packages/block/test/header.spec.ts index 0037e49c9c..d1254b9197 100644 --- a/packages/block/test/header.spec.ts +++ b/packages/block/test/header.spec.ts @@ -123,7 +123,10 @@ describe('[Block]: Header functions', () => { it('Initialization -> fromRLPSerializedHeader() -> error cases', () => { try { createBlockHeaderFromRLP(RLP.encode('a')) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } const expectedError = 'Invalid serialized header input. Must be array' assert.ok(e.message.includes(expectedError), 'should throw with header as rlp encoded string') } @@ -170,14 +173,20 @@ describe('[Block]: Header functions', () => { headerArray[15] = zeros(4) // bad data try { createBlockHeaderFromBytesArray(headerArray) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } const expectedError = 'invalid header. More values than expected were received' assert.ok(e.message.includes(expectedError), 'should throw on more values than expected') } try { createBlockHeaderFromBytesArray(headerArray.slice(0, 5)) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } const expectedError = 'invalid header. Less values than expected were received' assert.ok(e.message.includes(expectedError), 'should throw on less values than expected') } @@ -208,7 +217,10 @@ describe('[Block]: Header functions', () => { try { createBlockHeader({ ...data, extraData }, opts) assert.ok(true, testCase) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } assert.fail(testCase) } @@ -219,7 +231,10 @@ describe('[Block]: Header functions', () => { try { createBlockHeader({ ...data, extraData }, opts) assert.ok(testCase) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } assert.fail(testCase) } @@ -230,7 +245,10 @@ describe('[Block]: Header functions', () => { try { createBlockHeader({ ...data, extraData }, opts) assert.fail(testCase) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } assert.ok((error.message as string).includes('invalid amount of extra data'), testCase) } @@ -250,7 +268,10 @@ describe('[Block]: Header functions', () => { try { createBlockHeader({ ...data, extraData }, opts) assert.ok(true, testCase) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } assert.fail(testCase) } @@ -260,7 +281,10 @@ describe('[Block]: Header functions', () => { try { createBlockHeader({ ...data, extraData }, opts) assert.fail(testCase) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } assert.ok( (error.message as string).includes( 'extraData must be 97 bytes on non-epoch transition blocks, received 32 bytes', @@ -281,7 +305,10 @@ describe('[Block]: Header functions', () => { try { createBlockHeader({ ...data, number: epoch, extraData }, opts) assert.fail(testCase) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } assert.ok( (error.message as string).includes( 'invalid signer list length in extraData, received signer length of 41 (not divisible by 20)', @@ -301,7 +328,10 @@ describe('[Block]: Header functions', () => { true, 'should instantiate header with invalid extraData when skipConsensusFormatValidation === true', ) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } assert.fail('should not throw') } }) @@ -358,7 +388,10 @@ describe('[Block]: Header functions', () => { try { await header.validate(blockchain) assert.fail(testCase) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error); + } assert.ok((error.message as string).includes('invalid timestamp diff (lower than period)'), testCase) } @@ -368,7 +401,10 @@ describe('[Block]: Header functions', () => { try { await header.validate(blockchain) assert.ok(true, testCase) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error); + } assert.fail(testCase) } @@ -379,7 +415,10 @@ describe('[Block]: Header functions', () => { try { await header.validate(blockchain) assert.fail('should throw') - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error); + } if ((error.message as string).includes('coinbase must be filled with zeros on epoch transition blocks')) { assert.ok(true, 'error thrown') } else { @@ -395,7 +434,10 @@ describe('[Block]: Header functions', () => { try { await header.validate(blockchain) assert.fail('should throw') - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error); + } if ((error.message as string).includes('mixHash must be filled with zeros')) { assert.ok(true, 'error thrown') } else { @@ -410,7 +452,10 @@ describe('[Block]: Header functions', () => { try { header.validateCliqueDifficulty(blockchain) assert.fail(testCase) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error); + } if ((error.message as string).includes('difficulty for clique block must be INTURN (2) or NOTURN (1)')) { assert.ok(true, 'error thrown on invalid clique difficulty') } else { @@ -431,7 +476,10 @@ describe('[Block]: Header functions', () => { try { const res = header.validateCliqueDifficulty(poaBlockchain) assert.equal(res, true, testCase) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error); + } assert.fail(testCase) } @@ -442,7 +490,10 @@ describe('[Block]: Header functions', () => { try { const res = header.validateCliqueDifficulty(poaBlockchain) assert.equal(res, false, testCase) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error); + } assert.fail(testCase) } }) diff --git a/packages/block/test/mergeBlock.spec.ts b/packages/block/test/mergeBlock.spec.ts index ccc7a6f8bd..e93417188c 100644 --- a/packages/block/test/mergeBlock.spec.ts +++ b/packages/block/test/mergeBlock.spec.ts @@ -53,7 +53,10 @@ describe('[Header]: Casper PoS / The Merge Functionality', () => { } createBlockHeader(headerData, { common }) assert.fail('should throw') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok(true, 'should throw on wrong uncleHash') } @@ -64,7 +67,10 @@ describe('[Header]: Casper PoS / The Merge Functionality', () => { } createBlockHeader(headerData, { common }) assert.fail('should throw') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok(true, 'should throw on wrong difficulty') } @@ -75,7 +81,10 @@ describe('[Header]: Casper PoS / The Merge Functionality', () => { } createBlockHeader(headerData, { common }) assert.fail('should throw') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok(true, 'should throw on invalid extraData length') } @@ -85,7 +94,10 @@ describe('[Header]: Casper PoS / The Merge Functionality', () => { } createBlockHeader(headerData, { common }) assert.fail('should throw') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok(true, 'should throw on invalid mixHash length') } @@ -96,7 +108,10 @@ describe('[Header]: Casper PoS / The Merge Functionality', () => { } createBlockHeader(headerData, { common }) assert.fail('should throw') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok(true, 'should throw on wrong nonce') } }) @@ -107,7 +122,10 @@ describe('[Header]: Casper PoS / The Merge Functionality', () => { common, }) assert.fail('should have thrown') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok(true, 'should throw') } }) @@ -126,7 +144,10 @@ describe('[Header]: Casper PoS / The Merge Functionality', () => { try { block.header.prevRandao assert.fail('should have thrown') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok(true, 'prevRandao should throw if EIP-4399 is not activated') } }) From 7e99bb6965b5d3f1b74478159b0d4b78a2afdac7 Mon Sep 17 00:00:00 2001 From: ScottyPoi Date: Tue, 24 Sep 2024 13:33:09 -0600 Subject: [PATCH 04/21] blockchain: replace (e: any) pattern with Error type check --- packages/blockchain/src/blockchain.ts | 20 ++++++-- .../blockchain/test/blockValidation.spec.ts | 35 ++++++++++--- packages/blockchain/test/clique.spec.ts | 30 ++++++++--- .../blockchain/test/customConsensus.spec.ts | 20 ++++++-- packages/blockchain/test/index.spec.ts | 50 +++++++++++++++---- packages/blockchain/test/iterator.spec.ts | 5 +- packages/blockchain/test/util.ts | 5 +- 7 files changed, 132 insertions(+), 33 deletions(-) diff --git a/packages/blockchain/src/blockchain.ts b/packages/blockchain/src/blockchain.ts index 2cb5c8b231..095d3ecb69 100644 --- a/packages/blockchain/src/blockchain.ts +++ b/packages/blockchain/src/blockchain.ts @@ -755,7 +755,10 @@ export class Blockchain implements BlockchainInterface { let block try { block = await this.getBlock(blockId) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } if (err.message.includes('not found in DB') === true) { return } else throw err @@ -796,7 +799,10 @@ export class Blockchain implements BlockchainInterface { let number try { number = await this.dbManager.hashToNumber(hashes[mid]) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } if (err.message.includes('not found in DB') === true) { number = undefined } else throw err @@ -917,7 +923,10 @@ export class Blockchain implements BlockchainInterface { try { const childHeader = await this.getCanonicalHeader(blockNumber + BIGINT_1) await this._delChild(childHeader.hash(), childHeader.number, headHash, ops) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } if (err.message.includes('not found in canonical chain') !== true) { throw err } @@ -997,7 +1006,10 @@ export class Blockchain implements BlockchainInterface { } // Successful execution of onBlock, move the head pointer blocksRanCounter++ - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } if ((error.message as string).includes('not found in DB')) { break } else { diff --git a/packages/blockchain/test/blockValidation.spec.ts b/packages/blockchain/test/blockValidation.spec.ts index 0a9a57732e..24407362ee 100644 --- a/packages/blockchain/test/blockValidation.spec.ts +++ b/packages/blockchain/test/blockValidation.spec.ts @@ -32,7 +32,10 @@ describe('[Blockchain]: Block validation tests', () => { try { await blockchain.putBlock(block3) assert.fail('cannot reach this') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.message.includes('uncle is already included'), 'block throws if uncle is already included', @@ -59,7 +62,10 @@ describe('[Blockchain]: Block validation tests', () => { await blockchain.putBlock(block3) assert.fail('cannot reach this') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok( err.message.includes('not found in DB'), 'block throws if uncle parent hash is not part of the canonical chain', @@ -92,7 +98,10 @@ describe('[Blockchain]: Block validation tests', () => { try { await blockchain.putBlock(blockWithUnclesTooOld) assert.fail('cannot reach this') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.message.includes('uncle block has a parent that is too old'), 'block throws uncle is too old', @@ -114,7 +123,10 @@ describe('[Blockchain]: Block validation tests', () => { try { await blockchain.putBlock(block1) assert.fail('cannot reach this') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.message.includes('uncle block has a parent that is too old or too young'), 'block throws uncle is too young', @@ -150,7 +162,10 @@ describe('[Blockchain]: Block validation tests', () => { try { await blockchain.putBlock(block2) assert.fail('cannot reach this') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.message.includes('invalid difficulty block header number=1 '), 'block throws when uncle header is invalid', @@ -173,7 +188,10 @@ describe('[Blockchain]: Block validation tests', () => { await blockchain.putBlock(block2) assert.fail('cannot reach this') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.message.includes('The uncle is a canonical block'), 'block throws if an uncle is a canonical block', @@ -257,7 +275,10 @@ describe('[Blockchain]: Block validation tests', () => { ) const block2 = createBlock({ header }, { common }) await blockchain.putBlock(block2) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } const expectedError = 'Invalid block: base fee not correct' assert.ok( (e.message as string).includes(expectedError), diff --git a/packages/blockchain/test/clique.spec.ts b/packages/blockchain/test/clique.spec.ts index 08effb50b7..298bb84def 100644 --- a/packages/blockchain/test/clique.spec.ts +++ b/packages/blockchain/test/clique.spec.ts @@ -235,7 +235,10 @@ describe('Clique: Initialization', () => { try { await blockchain.putBlock(block) assert.fail('should fail') - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } assert.ok( error.message.includes('checkpoint signer not found in active signers list'), 'correct error', @@ -266,7 +269,10 @@ describe('Clique: Initialization', () => { try { await blockchain.putBlock(block) assert.fail('should fail') - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } assert.ok( error.message.includes('difficulty for clique block must be INTURN (2) or NOTURN (1)'), 'correct error', @@ -292,7 +298,10 @@ describe('Clique: Initialization', () => { try { await blockchain.putBlock(block) assert.fail('should fail') - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } assert.ok(error.message.includes('invalid clique difficulty'), 'correct error') } }) @@ -664,7 +673,10 @@ describe('Clique: Initialization', () => { try { await addNextBlock(blockchain, blocks, B) assert.fail('should throw error') - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } assert.ok( error.message.includes('invalid PoA block signature (clique)'), 'correct error thrown', @@ -678,7 +690,10 @@ describe('Clique: Initialization', () => { try { await addNextBlock(blockchain, blocks, A) assert.fail('should throw error') - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } assert.ok(error.message.includes('recently signed'), 'correct error thrown') } }) @@ -707,7 +722,10 @@ describe('Clique: Initialization', () => { try { await addNextBlock(blockchain, blocks, A, undefined, undefined, common) assert.fail('should throw error') - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } assert.ok(error.message.includes('recently signed'), 'correct error thrown') } }) diff --git a/packages/blockchain/test/customConsensus.spec.ts b/packages/blockchain/test/customConsensus.spec.ts index 7a55658637..d807585940 100644 --- a/packages/blockchain/test/customConsensus.spec.ts +++ b/packages/blockchain/test/customConsensus.spec.ts @@ -107,7 +107,10 @@ describe('Custom consensus validation rules', () => { try { await blockchain.putBlock(blockWithBadDifficulty) assert.fail('should throw') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok( err.message.includes('invalid difficulty'), 'failed to put block with invalid difficulty', @@ -130,7 +133,10 @@ describe('Custom consensus validation rules', () => { try { await blockchain.putBlock(blockWithBadExtraData) assert.fail('should throw') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok( err.message === 'header contains invalid extradata - must match first 6 elements of fibonacci sequence', @@ -148,7 +154,10 @@ describe('consensus transition checks', () => { try { await blockchain.checkAndTransitionHardForkByNumber(5n) assert.ok('checkAndTransitionHardForkByNumber does not throw with custom consensus') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.fail( `checkAndTransitionHardForkByNumber should not throw with custom consensus, error=${err.message}`, ) @@ -161,7 +170,10 @@ describe('consensus transition checks', () => { assert.fail( 'checkAndTransitionHardForkByNumber should throw when using standard consensus (ethash, clique, casper) but consensus algorithm defined in common is different', ) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes('Consensus object for ethash must be passed')) } }) diff --git a/packages/blockchain/test/index.spec.ts b/packages/blockchain/test/index.spec.ts index 1e7fd0acbc..5b4d8ab1f3 100644 --- a/packages/blockchain/test/index.spec.ts +++ b/packages/blockchain/test/index.spec.ts @@ -107,7 +107,10 @@ describe('blockchain test', () => { validateConsensus: false, genesisBlock, }) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } assert.ok(error, 'returned with error') } }) @@ -221,7 +224,10 @@ describe('blockchain test', () => { try { await blockchain.getBlock(5) assert.fail('should throw an exception') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.message.includes('not found in DB'), `should throw for non-existing block-by-number request`, @@ -231,7 +237,10 @@ describe('blockchain test', () => { try { await blockchain.getBlock(hexToBytes('0x1234')) assert.fail('should throw an exception') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.message.includes('not found in DB'), `should throw for non-existing block-by-hash request`, @@ -260,14 +269,20 @@ describe('blockchain test', () => { try { await blockchain.getBlock(22) assert.fail('canonical references should have been deleted') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes('not found in DB'), 'canonical references correctly deleted') } try { await blockchain.getCanonicalHeader(BigInt(22)) assert.fail('canonical references should have been deleted') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.equal( err.message, 'header with number 22 not found in canonical chain', @@ -538,7 +553,10 @@ describe('blockchain test', () => { try { await blockchain.getBlock(BigInt(2)) assert.fail('block should not be constructed') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.equal( e.message, 'uncle hash should be equal to hash of empty array', @@ -572,7 +590,10 @@ describe('blockchain test', () => { try { await blockchain.putBlock(invalidBlock) assert.fail('should not validate an invalid block') - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } assert.ok(error, 'should not validate an invalid block') } }) @@ -752,7 +773,10 @@ describe('blockchain test', () => { let error try { await blockchain.putBlock(blocks[i]) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } error = err } if (i === 2) { @@ -850,7 +874,10 @@ describe('initialization tests', () => { try { await blockchain.putBlock(otherGenesisBlock) assert.fail('putting a genesis block did not throw') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.equal( e.message, 'Cannot put a different genesis block than current blockchain genesis: create a new Blockchain', @@ -862,7 +889,10 @@ describe('initialization tests', () => { try { await createBlockchain({ genesisBlock: otherGenesisBlock, db }) assert.fail('creating blockchain with different genesis block than in db did not throw') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.equal( e.message, 'The genesis block in the DB has a different hash than the provided genesis block.', diff --git a/packages/blockchain/test/iterator.spec.ts b/packages/blockchain/test/iterator.spec.ts index 3edd1712ed..4ab540dec7 100644 --- a/packages/blockchain/test/iterator.spec.ts +++ b/packages/blockchain/test/iterator.spec.ts @@ -158,7 +158,10 @@ describe('blockchain test', () => { await blockchain.iterator('error', () => { throw new Error('iterator func error') }) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } assert.ok(error) assert.equal(error.message, 'iterator func error', 'should return correct error') } diff --git a/packages/blockchain/test/util.ts b/packages/blockchain/test/util.ts index abb88488c5..8c4ab9ab17 100644 --- a/packages/blockchain/test/util.ts +++ b/packages/blockchain/test/util.ts @@ -58,7 +58,10 @@ export const generateBlockchain = async (numberOfBlocks: number, genesis?: Block }) try { await blockchain.putBlocks(blocks.slice(1)) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } return { error } } From 3923362f3b55c4527c865620f230a80f1bdd02ff Mon Sep 17 00:00:00 2001 From: ScottyPoi Date: Tue, 24 Sep 2024 13:36:54 -0600 Subject: [PATCH 05/21] client: replace (e: any) pattern with Error type check --- .../archive/libp2p/net/peer/libp2ppeer.ts | 5 +++- packages/client/bin/cli.ts | 30 +++++++++++++++---- packages/client/src/config.ts | 5 +++- packages/client/src/execution/level.ts | 5 +++- packages/client/src/execution/vmexecution.ts | 5 +++- packages/client/src/miner/pendingBlock.ts | 5 +++- packages/client/src/net/peer/rlpxpeer.ts | 5 +++- .../client/src/net/protocol/boundprotocol.ts | 10 +++++-- .../client/src/net/protocol/rlpxsender.ts | 10 +++++-- packages/client/src/net/server/rlpxserver.ts | 10 +++++-- packages/client/src/rpc/helpers.ts | 5 +++- packages/client/src/rpc/index.ts | 5 +++- packages/client/src/rpc/modules/debug.ts | 5 +++- .../client/src/rpc/modules/engine/engine.ts | 15 ++++++++-- .../src/rpc/modules/engine/util/generic.ts | 7 +++-- packages/client/src/rpc/modules/eth.ts | 25 ++++++++++++---- packages/client/src/service/service.ts | 5 +++- packages/client/src/service/skeleton.ts | 10 +++++-- packages/client/src/service/txpool.ts | 10 +++++-- packages/client/src/sync/beaconsync.ts | 5 +++- .../client/src/sync/fetcher/blockfetcher.ts | 5 +++- packages/client/src/sync/fetcher/fetcher.ts | 5 +++- .../client/src/sync/fetcher/headerfetcher.ts | 5 +++- .../src/sync/fetcher/reverseblockfetcher.ts | 5 +++- .../client/src/sync/fetcher/storagefetcher.ts | 5 +++- packages/client/src/sync/snapsync.ts | 5 +++- packages/client/src/sync/sync.ts | 10 +++++-- packages/client/src/util/metaDBManager.ts | 5 +++- packages/client/src/util/parse.ts | 5 +++- packages/client/test/cli/cli.spec.ts | 10 +++++-- .../test/integration/beaconsync.spec.ts | 5 +++- packages/client/test/logging.spec.ts | 5 +++- .../test/net/protocol/boundprotocol.spec.ts | 10 +++++-- .../client/test/net/protocol/protocol.spec.ts | 5 +++- packages/client/test/rpc/rpc.spec.ts | 25 ++++++++++++---- packages/client/test/rpc/websocket.spec.ts | 10 +++++-- packages/client/test/sim/beaconsync.spec.ts | 5 +++- packages/client/test/sim/txGenerator.ts | 5 +++- .../test/sync/fetcher/blockfetcher.spec.ts | 5 +++- .../test/sync/fetcher/headerfetcher.spec.ts | 5 +++- .../sync/fetcher/reverseblockfetcher.spec.ts | 5 +++- .../test/sync/fetcher/trienodefetcher.spec.ts | 5 +++- packages/client/test/sync/fullsync.spec.ts | 5 +++- packages/client/test/sync/lightsync.spec.ts | 5 +++- packages/client/test/sync/skeleton.spec.ts | 20 ++++++++++--- packages/client/test/sync/txpool.spec.ts | 10 +++++-- 46 files changed, 297 insertions(+), 75 deletions(-) diff --git a/packages/client/archive/libp2p/net/peer/libp2ppeer.ts b/packages/client/archive/libp2p/net/peer/libp2ppeer.ts index 8f89e78781..188d2f87d1 100644 --- a/packages/client/archive/libp2p/net/peer/libp2ppeer.ts +++ b/packages/client/archive/libp2p/net/peer/libp2ppeer.ts @@ -104,7 +104,10 @@ export class Libp2pPeer extends Peer { try { const { stream } = await node.dialProtocol(peer as any, protocol) await this.bindProtocol(p, new Libp2pSender(stream)) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } const peerInfo = isPeerId(peer) ? `id=${peer.toB58String()}` : `multiaddr=${peer}` this.config.logger.debug( `Peer doesn't support protocol=${protocol} ${peerInfo} ${err.stack}`, diff --git a/packages/client/bin/cli.ts b/packages/client/bin/cli.ts index 0fc6c1bcab..af84384ee9 100755 --- a/packages/client/bin/cli.ts +++ b/packages/client/bin/cli.ts @@ -554,7 +554,10 @@ async function executeBlocks(client: EthereumClient) { if ((blockRange[0][1] as string[]).length > 0 && blockRange.length === 2) { throw new Error('wrong input') } - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } client.config.logger.error( 'Wrong input format for block execution, allowed format types: 5, 5-10, 5[0xba4b5fd92a26badad3cad22eb6f7c7e745053739b5f5d1e8a3afb00f8fb2a280,[TX_HASH_2],...], 5[*] (all txs in verbose mode)', ) @@ -580,7 +583,10 @@ async function startBlock(client: EthereumClient) { try { await client.chain.resetCanonicalHead(startBlock) logger.info(`Chain height reset to ${client.chain.headers.height}`) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } logger.error(`Error setting back chain in startBlock: ${err}`) process.exit() } @@ -616,7 +622,10 @@ async function startExecutionFrom(client: EthereumClient) { logger.info( `vmHead set to ${client.chain.headers.height} for starting stateless execution at hardfork=${startExecutionHardfork}`, ) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } logger.error(`Error setting vmHead for starting stateless execution: ${err}`) process.exit() } @@ -691,7 +700,10 @@ async function startClient( block.header.number }`, ) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } config.logger.info( `Encountered error while while preloading chain data error=${err.message}`, ) @@ -857,7 +869,10 @@ async function inputAccounts() { const derivedAddress = createAddressFromPrivateKey(privKey) accounts.push([derivedAddress, privKey]) } - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } console.error(`Encountered error unlocking account:\n${e.message}`) process.exit() } @@ -1019,7 +1034,10 @@ async function run() { common = createCustomCommon(customChainParams, Mainnet, { customCrypto: cryptoFunctions, }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } console.error(err) console.error(`invalid chain parameters: ${err.message}`) process.exit() diff --git a/packages/client/src/config.ts b/packages/client/src/config.ts index 389e615e07..d0d2b9e2e6 100644 --- a/packages/client/src/config.ts +++ b/packages/client/src/config.ts @@ -684,7 +684,10 @@ export class Config { let key try { key = await db.get(dbKey, encodingOpts) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } if (error.code === 'LEVEL_NOT_FOUND') { // generate and save a new key key = genPrivateKey() diff --git a/packages/client/src/execution/level.ts b/packages/client/src/execution/level.ts index dbebf46699..bbdd004b67 100644 --- a/packages/client/src/execution/level.ts +++ b/packages/client/src/execution/level.ts @@ -67,7 +67,10 @@ export class LevelDB< try { value = await this._leveldb.get(key, encodings) if (value === null) return undefined - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } // https://github.com/Level/abstract-level/blob/915ad1317694d0ce8c580b5ab85d81e1e78a3137/abstract-level.js#L309 // This should be `true` if the error came from LevelDB // so we can check for `NOT true` to identify any non-404 errors diff --git a/packages/client/src/execution/vmexecution.ts b/packages/client/src/execution/vmexecution.ts index 37c063747a..53942f4cba 100644 --- a/packages/client/src/execution/vmexecution.ts +++ b/packages/client/src/execution/vmexecution.ts @@ -738,7 +738,10 @@ export class VMExecution extends Execution { // set as new head block headBlock = block parentState = block.header.stateRoot - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } // only marked the block as invalid if it was an actual execution error // for e.g. absence of executionWitness doesn't make a block invalid if (!`${error.message}`.includes('Invalid executionWitness=null')) { diff --git a/packages/client/src/miner/pendingBlock.ts b/packages/client/src/miner/pendingBlock.ts index 8fdd97c848..3544e67592 100644 --- a/packages/client/src/miner/pendingBlock.ts +++ b/packages/client/src/miner/pendingBlock.ts @@ -347,7 +347,10 @@ export class PendingBlock { skipHardForkValidation: this.skipHardForkValidation, }) addTxResult = AddTxResult.Success - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } if (error.message === 'tx has a higher gas limit than the remaining gas in the block') { if (builder.gasUsed > (builder as any).headerData.gasLimit - BigInt(21000)) { // If block has less than 21000 gas remaining, consider it full diff --git a/packages/client/src/net/peer/rlpxpeer.ts b/packages/client/src/net/peer/rlpxpeer.ts index d2016f20f8..b07745f2b6 100644 --- a/packages/client/src/net/peer/rlpxpeer.ts +++ b/packages/client/src/net/peer/rlpxpeer.ts @@ -125,7 +125,10 @@ export class RlpxPeer extends Peer { try { await this.bindProtocols(rlpxPeer) this.config.events.emit(Event.PEER_CONNECTED, this) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } this.config.events.emit(Event.PEER_ERROR, error, this) } } diff --git a/packages/client/src/net/protocol/boundprotocol.ts b/packages/client/src/net/protocol/boundprotocol.ts index 299d18c5d2..51d40be58d 100644 --- a/packages/client/src/net/protocol/boundprotocol.ts +++ b/packages/client/src/net/protocol/boundprotocol.ts @@ -79,7 +79,10 @@ export class BoundProtocol { this.config.events.emit(Event.PROTOCOL_ERROR, error, this.peer) } } - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } this.config.events.emit(Event.PROTOCOL_ERROR, error, this.peer) } }) @@ -117,7 +120,10 @@ export class BoundProtocol { let error try { data = this.protocol.decode(message, incoming.payload) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } error = new Error(`Could not decode message ${message.name}: ${e}`) } const resolver = this.resolvers.get(incoming.code) diff --git a/packages/client/src/net/protocol/rlpxsender.ts b/packages/client/src/net/protocol/rlpxsender.ts index 9f915bf7a3..9a8ca397d9 100644 --- a/packages/client/src/net/protocol/rlpxsender.ts +++ b/packages/client/src/net/protocol/rlpxsender.ts @@ -34,7 +34,10 @@ export class RlpxSender extends Sender { sendStatus(status: any) { try { this.sender.sendStatus(status) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } this.emit('error', err) } } @@ -48,7 +51,10 @@ export class RlpxSender extends Sender { try { //@ts-ignore "type number is not assignable to type never" this.sender.sendMessage(code, data) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } this.emit('error', err) } } diff --git a/packages/client/src/net/server/rlpxserver.ts b/packages/client/src/net/server/rlpxserver.ts index 1b02ce48c5..cdf0bbd769 100644 --- a/packages/client/src/net/server/rlpxserver.ts +++ b/packages/client/src/net/server/rlpxserver.ts @@ -158,7 +158,10 @@ export class RlpxServer extends Server { for (const promise of promises) { try { await promise - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } this.error(e) } } @@ -277,7 +280,10 @@ export class RlpxServer extends Server { this.peers.set(peer.id, peer) this.config.logger.debug(`Peer connected: ${peer}`) this.config.events.emit(Event.PEER_CONNECTED, peer) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } // Fixes a memory leak where RlpxPeer objects could not be GCed, // likely to the complex two-way bound-protocol logic peer = null diff --git a/packages/client/src/rpc/helpers.ts b/packages/client/src/rpc/helpers.ts index 24cc138b40..b13b49553a 100644 --- a/packages/client/src/rpc/helpers.ts +++ b/packages/client/src/rpc/helpers.ts @@ -18,7 +18,10 @@ export function callWithStackTrace(handler: Function, debug: boolean) { try { const res = await handler(...args) return res - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } const e: RPCError = { code: error.code ?? INTERNAL_ERROR, message: error.message, diff --git a/packages/client/src/rpc/index.ts b/packages/client/src/rpc/index.ts index ced41f3981..67bac8c70e 100644 --- a/packages/client/src/rpc/index.ts +++ b/packages/client/src/rpc/index.ts @@ -46,7 +46,10 @@ export class RPCManager { methods[concatenatedMethodName] = mod[methodName].bind((...params: any[]) => { try { mod(...params) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } throw { code: INTERNAL_ERROR, message: error.message ?? error, diff --git a/packages/client/src/rpc/modules/debug.ts b/packages/client/src/rpc/modules/debug.ts index 0ee2ad639b..0da7152460 100644 --- a/packages/client/src/rpc/modules/debug.ts +++ b/packages/client/src/rpc/modules/debug.ts @@ -349,7 +349,10 @@ export class Debug { try { // Validator already verified that `blockHash` is properly formatted. block = await this.chain.getBlock(hexToBytes(blockHash)) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } throw { code: INTERNAL_ERROR, message: 'Could not get requested block hash.', diff --git a/packages/client/src/rpc/modules/engine/engine.ts b/packages/client/src/rpc/modules/engine/engine.ts index 47d9abe161..837deccb66 100644 --- a/packages/client/src/rpc/modules/engine/engine.ts +++ b/packages/client/src/rpc/modules/engine/engine.ts @@ -447,7 +447,10 @@ export class Engine { if (headBlock.common.isActivatedEIP(4844)) { try { headBlock.validateBlobTransactions(parent.header) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } const validationError = `Invalid 4844 transactions: ${error}` const latestValidHash = await validHash( hexToBytes(parentHash as PrefixedHexString), @@ -470,7 +473,10 @@ export class Engine { if (!executedParentExists) { throw new Error(`Parent block not yet executed number=${parent.header.number}`) } - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } // Stash the block for a potential forced forkchoice update to it later. this.remoteBlocks.set(bytesToUnprefixedHex(headBlock.hash()), headBlock) @@ -1380,7 +1386,10 @@ export class Engine { BigInt(executionPayload.executionPayload.timestamp), ) return executionPayload - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } if (validEngineCodes.includes(error.code)) throw error throw { code: INTERNAL_ERROR, diff --git a/packages/client/src/rpc/modules/engine/util/generic.ts b/packages/client/src/rpc/modules/engine/util/generic.ts index ad231ea6dc..3f014b4eb7 100644 --- a/packages/client/src/rpc/modules/engine/util/generic.ts +++ b/packages/client/src/rpc/modules/engine/util/generic.ts @@ -65,7 +65,10 @@ export const validExecutedChainBlock = async ( // if the block was canonical and executed we would have returned by now return null - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } return null } } @@ -105,7 +108,7 @@ export const validHash = async ( hash = validParent.header.parentHash } } - } catch (_error: any) { + } catch { // ignore error thrown by the loop and return null below } diff --git a/packages/client/src/rpc/modules/eth.ts b/packages/client/src/rpc/modules/eth.ts index d34c4434f8..bf35290161 100644 --- a/packages/client/src/rpc/modules/eth.ts +++ b/packages/client/src/rpc/modules/eth.ts @@ -819,7 +819,10 @@ export class Eth { const tx = block.transactions[txIndex] return toJSONRPCTx(tx, block, txIndex) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } throw { code: INVALID_PARAMS, message: error.message.toString(), @@ -844,7 +847,10 @@ export class Eth { const tx = block.transactions[txIndex] return toJSONRPCTx(tx, block, txIndex) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } throw { code: INVALID_PARAMS, message: error.message.toString(), @@ -1070,7 +1076,10 @@ export class Eth { if (blockHash !== undefined) { try { from = to = await this._chain.getBlock(hexToBytes(blockHash)) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } throw { code: INVALID_PARAMS, message: 'unknown blockHash', @@ -1189,7 +1198,10 @@ export class Eth { } else { tx = createTxFromRLP(txBuf, { common }) } - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } throw { code: PARSE_ERROR, message: `serialized tx data could not be parsed (${e.message})`, @@ -1209,7 +1221,10 @@ export class Eth { try { await txPool.add(tx, true) txPool.sendNewTxHashes([[tx.type], [tx.serialize().byteLength], [tx.hash()]], pool.peers) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } throw { code: INVALID_PARAMS, message: error.message ?? error.toString(), diff --git a/packages/client/src/service/service.ts b/packages/client/src/service/service.ts index 5b9aee525a..3a4c1ec05b 100644 --- a/packages/client/src/service/service.ts +++ b/packages/client/src/service/service.ts @@ -84,7 +84,10 @@ export class Service { if (this.running) { try { await this.handle(message, protocol, peer) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } this.config.logger.debug( `Error handling message (${protocol}:${message.name}): ${error.message}`, ) diff --git a/packages/client/src/service/skeleton.ts b/packages/client/src/service/skeleton.ts index 8401285ea1..52ee4d65dd 100644 --- a/packages/client/src/service/skeleton.ts +++ b/packages/client/src/service/skeleton.ts @@ -1401,7 +1401,10 @@ export class Skeleton extends MetaDBManager { throw Error(`SkeletonBlock rlp lookup failed for ${number} onlyCanonical=${onlyCanonical}`) } return this.skeletonBlockRlpToBlock(skeletonBlockRlp) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } // If skeleton is linked, it probably has deleted the block and put it into the chain if (onlyCanonical && !this.status.linked) return undefined // As a fallback, try to get the block from the canonical chain in case it is available there @@ -1474,7 +1477,10 @@ export class Skeleton extends MetaDBManager { await this.delete(DBKey.SkeletonBlockHashToNumber, block.hash()) await this.delete(DBKey.SkeletonUnfinalizedBlockByHash, block.hash()) return true - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } return false } } diff --git a/packages/client/src/service/txpool.ts b/packages/client/src/service/txpool.ts index ec9dba5412..a7cafb788f 100644 --- a/packages/client/src/service/txpool.ts +++ b/packages/client/src/service/txpool.ts @@ -577,7 +577,10 @@ export class TxPool { newTxHashes[0].push(tx.type) newTxHashes[1].push(tx.serialize().byteLength) newTxHashes[2].push(tx.hash()) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } this.config.logger.debug( `Error adding tx to TxPool: ${error.message} (tx hash: ${bytesToHex(tx.hash())})`, ) @@ -636,7 +639,10 @@ export class TxPool { for (const tx of txs) { try { await this.add(tx) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } this.config.logger.debug( `Error adding tx to TxPool: ${error.message} (tx hash: ${bytesToHex(tx.hash())})`, ) diff --git a/packages/client/src/sync/beaconsync.ts b/packages/client/src/sync/beaconsync.ts index f419b698b1..42eefa17ab 100644 --- a/packages/client/src/sync/beaconsync.ts +++ b/packages/client/src/sync/beaconsync.ts @@ -141,7 +141,10 @@ export class BeaconSynchronizer extends Synchronizer { while (this.running) { try { await this.sync() - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } this.config.logger.error(`Beacon sync error: ${error.message}`) this.config.events.emit(Event.SYNC_ERROR, error) } diff --git a/packages/client/src/sync/fetcher/blockfetcher.ts b/packages/client/src/sync/fetcher/blockfetcher.ts index 7aa6b1091b..d875ef51a8 100644 --- a/packages/client/src/sync/fetcher/blockfetcher.ts +++ b/packages/client/src/sync/fetcher/blockfetcher.ts @@ -147,7 +147,10 @@ export class BlockFetcher extends BlockFetcherBase { } last=${blocks[blocks.length - 1]?.header.number})`, ) this.config.events.emit(Event.SYNC_FETCHED_BLOCKS, blocks.slice(0, num)) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } this.DEBUG && this.debug( `Error storing fetcher results in blockchain (blocks num=${blocks.length} first=${ diff --git a/packages/client/src/sync/fetcher/fetcher.ts b/packages/client/src/sync/fetcher/fetcher.ts index 5229b2efc3..78cba1841a 100644 --- a/packages/client/src/sync/fetcher/fetcher.ts +++ b/packages/client/src/sync/fetcher/fetcher.ts @@ -460,7 +460,10 @@ export abstract class Fetcher extends Readable } this.finished += jobItems.length cb() - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } this.config.logger.warn(`Error storing received block or header result: ${error}`) const { destroyFetcher, banPeer, stepBack } = this.processStoreError( error, diff --git a/packages/client/src/sync/fetcher/headerfetcher.ts b/packages/client/src/sync/fetcher/headerfetcher.ts index 940fbd6492..fa84f9b5af 100644 --- a/packages/client/src/sync/fetcher/headerfetcher.ts +++ b/packages/client/src/sync/fetcher/headerfetcher.ts @@ -96,7 +96,10 @@ export class HeaderFetcher extends BlockFetcherBase { try { return await this.metaDB.get(this.dbKey(type, hash), encodingOpts) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } if (error.code === 'LEVEL_NOT_FOUND') { return null } diff --git a/packages/client/src/util/parse.ts b/packages/client/src/util/parse.ts index a62f8c26d8..bde051d47c 100644 --- a/packages/client/src/util/parse.ts +++ b/packages/client/src/util/parse.ts @@ -66,7 +66,10 @@ export function parseMultiaddrs(input: MultiaddrLike): Multiaddr[] { } throw new Error(`Unable to parse bootnode URL: ${s}`) }) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } throw new Error(`Invalid bootnode URLs: ${e.message}`) } } diff --git a/packages/client/test/cli/cli.spec.ts b/packages/client/test/cli/cli.spec.ts index 8b5e0ad51f..c8a195d64f 100644 --- a/packages/client/test/cli/cli.spec.ts +++ b/packages/client/test/cli/cli.spec.ts @@ -148,7 +148,10 @@ describe('[CLI]', () => { await wait(600) const client = Client.http({ port: 7777 }) await client.request('engine_exchangeCapabilities', [], 2.0) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert( e.message.includes('Unauthorized: Error: Missing auth header'), 'authentication failure shows that auth is defaulting to active', @@ -347,7 +350,10 @@ describe('[CLI]', () => { try { await clientNoConnection.request('web3_clientVersion', [], 2.0) assert.fail('should have thrown on invalid client address') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok(e !== undefined, 'failed to connect to RPC on invalid address') child.kill() resolve(undefined) diff --git a/packages/client/test/integration/beaconsync.spec.ts b/packages/client/test/integration/beaconsync.spec.ts index de3a673a03..f63baeca32 100644 --- a/packages/client/test/integration/beaconsync.spec.ts +++ b/packages/client/test/integration/beaconsync.spec.ts @@ -51,7 +51,10 @@ describe('should not sync with stale peers', async () => { await localServer.discover('remotePeer', '127.0.0.2') await wait(300) assert.fail('should not sync') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok('did not sync') } }) diff --git a/packages/client/test/logging.spec.ts b/packages/client/test/logging.spec.ts index 84438dc59f..e8dfc89a02 100644 --- a/packages/client/test/logging.spec.ts +++ b/packages/client/test/logging.spec.ts @@ -20,7 +20,10 @@ describe('[Logging]', () => { it('should log error stacks properly', () => { try { throw new Error('an error') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } e.level = 'error' assert.ok( /an error\n {4}at/.test((format.transform(e) as any).message), diff --git a/packages/client/test/net/protocol/boundprotocol.spec.ts b/packages/client/test/net/protocol/boundprotocol.spec.ts index ea82ec3d66..afc958ce9b 100644 --- a/packages/client/test/net/protocol/boundprotocol.spec.ts +++ b/packages/client/test/net/protocol/boundprotocol.spec.ts @@ -127,7 +127,10 @@ describe('[BoundProtocol]', () => { td.when(protocol.decode(testResponse, '2')).thenThrow(new Error('error1')) try { await bound.request('TestMessage', 1) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(/error1/.test(err.message), 'got error') } }) @@ -143,7 +146,10 @@ describe('[BoundProtocol]', () => { }) try { await bound.request('TestMessage', {}) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(/timed out/.test(err.message), 'got error') } }) diff --git a/packages/client/test/net/protocol/protocol.spec.ts b/packages/client/test/net/protocol/protocol.spec.ts index 0798f13f89..018d359399 100644 --- a/packages/client/test/net/protocol/protocol.spec.ts +++ b/packages/client/test/net/protocol/protocol.spec.ts @@ -81,7 +81,10 @@ describe('[Protocol]', () => { }, 101) try { await p.handshake(sender) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok(/timed out/.test(e.message), 'got timeout error') } }) diff --git a/packages/client/test/rpc/rpc.spec.ts b/packages/client/test/rpc/rpc.spec.ts index a9de741234..8c19b076e2 100644 --- a/packages/client/test/rpc/rpc.spec.ts +++ b/packages/client/test/rpc/rpc.spec.ts @@ -27,7 +27,10 @@ describe('JSON-RPC call', () => { try { await rpc.request(req, []) assert.fail('should error when request not authenticated by JWT') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.equal(err.code, 401, 'unauthorized request') } }) @@ -44,7 +47,10 @@ describe('JSON-RPC call', () => { try { await rpc.request(req, []) assert.fail('should have thrown an error') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.equal(err.code, 401, 'errored with invalid token') } }) @@ -63,7 +69,10 @@ describe('JSON-RPC call', () => { try { await rpc.request(req, []) assert.fail('should have thrown an error') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.equal(err.code, 401, 'errored with invalid token') assert.equal(err.message, 'Unauthorized: Error: Signature verification failed') } @@ -104,7 +113,10 @@ describe('JSON-RPC call', () => { try { await rpc.request(req, []) assert.fail('should have thrown an error') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.equal(err.code, 401, 'errored with valid but stale token') assert.ok(err.message.includes('Stale jwt'), 'valid but stale token') } @@ -141,7 +153,10 @@ describe('JSON-RPC call', () => { try { await rpc.request('protected_METHOD_DOES_NOT_EXIST', ['0x1', true]) assert.fail('should have thrown') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.equal(err.code, 401, 'errored with unauthorized') assert.ok(err.message.includes('Missing auth header'), 'no auth token provided') } diff --git a/packages/client/test/rpc/websocket.spec.ts b/packages/client/test/rpc/websocket.spec.ts index 6dacd73197..32bf3e4472 100644 --- a/packages/client/test/rpc/websocket.spec.ts +++ b/packages/client/test/rpc/websocket.spec.ts @@ -36,7 +36,10 @@ describe('JSON-RPC call', () => { resolve(undefined) }) }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.fail(err) } }) @@ -70,7 +73,10 @@ describe('JSON-RPC call', () => { resolve(undefined) }) }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.fail(err) } }) diff --git a/packages/client/test/sim/beaconsync.spec.ts b/packages/client/test/sim/beaconsync.spec.ts index 06407ee97a..18ea5611b6 100644 --- a/packages/client/test/sim/beaconsync.spec.ts +++ b/packages/client/test/sim/beaconsync.spec.ts @@ -76,7 +76,10 @@ describe('simple mainnet test run', async () => { try { await waitForELStart(client) assert.ok(true, 'geth<>lodestar started successfully') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.fail(e.message + ': geth<>lodestar failed to start') } }, 60000) diff --git a/packages/client/test/sim/txGenerator.ts b/packages/client/test/sim/txGenerator.ts index cd6698d863..e0c027539c 100644 --- a/packages/client/test/sim/txGenerator.ts +++ b/packages/client/test/sim/txGenerator.ts @@ -158,7 +158,10 @@ async function run(data: any) { await sleep(1000) } } - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } console.log(error) console.log(`Error retrieving blocks from ${error.config.url}: ${error.response.data}`) return false diff --git a/packages/client/test/sync/fetcher/blockfetcher.spec.ts b/packages/client/test/sync/fetcher/blockfetcher.spec.ts index 15c04cd7f1..bd936d1d42 100644 --- a/packages/client/test/sync/fetcher/blockfetcher.spec.ts +++ b/packages/client/test/sync/fetcher/blockfetcher.spec.ts @@ -249,7 +249,10 @@ describe('store()', async () => { try { await fetcher.store([]) assert.fail('fetcher store should have errored') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.equal(err.message, 'could not find parent header', 'store() threw on invalid block') const { destroyFetcher, banPeer } = fetcher.processStoreError(err, { first: BigInt(1), diff --git a/packages/client/test/sync/fetcher/headerfetcher.spec.ts b/packages/client/test/sync/fetcher/headerfetcher.spec.ts index 83eb52baca..a0929ce4d0 100644 --- a/packages/client/test/sync/fetcher/headerfetcher.spec.ts +++ b/packages/client/test/sync/fetcher/headerfetcher.spec.ts @@ -115,7 +115,10 @@ describe('store()', async () => { try { await fetcher.store([0 as any]) assert.fail('should fail') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.equal(err.message, 'err0', 'store() threw on invalid header') } }) diff --git a/packages/client/test/sync/fetcher/reverseblockfetcher.spec.ts b/packages/client/test/sync/fetcher/reverseblockfetcher.spec.ts index 867cf84a47..1d395761a7 100644 --- a/packages/client/test/sync/fetcher/reverseblockfetcher.spec.ts +++ b/packages/client/test/sync/fetcher/reverseblockfetcher.spec.ts @@ -265,7 +265,10 @@ describe('store()', async () => { try { await fetcher.store([]) assert.fail('fetcher store should have errored') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.equal( err.message, `Blocks don't extend canonical subchain`, diff --git a/packages/client/test/sync/fetcher/trienodefetcher.spec.ts b/packages/client/test/sync/fetcher/trienodefetcher.spec.ts index 64303e1d69..dab7d6cb64 100644 --- a/packages/client/test/sync/fetcher/trienodefetcher.spec.ts +++ b/packages/client/test/sync/fetcher/trienodefetcher.spec.ts @@ -184,7 +184,10 @@ describe('[TrieNodeFetcher]', async () => { try { await fetcher.store(undefined as any) assert.ok('should run without error') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.fail(err.message) } }) diff --git a/packages/client/test/sync/fullsync.spec.ts b/packages/client/test/sync/fullsync.spec.ts index 0df617ac9e..2b5c6bb52d 100644 --- a/packages/client/test/sync/fullsync.spec.ts +++ b/packages/client/test/sync/fullsync.spec.ts @@ -167,7 +167,10 @@ describe('[FullSynchronizer]', async () => { BlockFetcher.prototype.fetch = vi.fn().mockRejectedValue(new Error('err0')) try { await sync.sync() - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.equal(err.message, 'err0', 'got error') await sync.stop() await sync.close() diff --git a/packages/client/test/sync/lightsync.spec.ts b/packages/client/test/sync/lightsync.spec.ts index e8d718e1fb..f06678c709 100644 --- a/packages/client/test/sync/lightsync.spec.ts +++ b/packages/client/test/sync/lightsync.spec.ts @@ -99,7 +99,10 @@ describe('[LightSynchronizer]', async () => { td.when(HeaderFetcher.prototype.fetch()).thenReject(new Error('err0')) try { await sync.sync() - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.equal(err.message, 'err0', 'got error') await sync.stop() await sync.close() diff --git a/packages/client/test/sync/skeleton.spec.ts b/packages/client/test/sync/skeleton.spec.ts index e8e7b9eb6e..1f3670754a 100644 --- a/packages/client/test/sync/skeleton.spec.ts +++ b/packages/client/test/sync/skeleton.spec.ts @@ -56,7 +56,10 @@ describe('[Skeleton]/ startup scenarios ', () => { try { await skeleton.reset() assert.fail('should have thrown') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes('skeleton reset'), 'throws when skeleton sync not started') } await skeleton.open() @@ -366,7 +369,10 @@ describe('[Skeleton] / setHead', async () => { } else { assert.ok(true, `test ${testCaseIndex}: successfully passed`) } - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } if ( typeof testCase.err?.message === 'string' && (error.message as string).includes(testCase.err.message) @@ -867,7 +873,10 @@ describe('[Skeleton] / setHead', async () => { ) try { await skeleton.setHead(block5, false) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } if (error !== errReorgDenied) { assert.fail(error) } @@ -882,7 +891,10 @@ describe('[Skeleton] / setHead', async () => { await skeleton.initSync(block4PoS) try { await skeleton.putBlocks([block3PoS]) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } if (error !== errSyncMerged) { assert.fail(error) } diff --git a/packages/client/test/sync/txpool.spec.ts b/packages/client/test/sync/txpool.spec.ts index 57fbd98ed1..88679cd745 100644 --- a/packages/client/test/sync/txpool.spec.ts +++ b/packages/client/test/sync/txpool.spec.ts @@ -142,7 +142,10 @@ const handleTxs = async ( pool.stop() pool.close() return true - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } pool.stop() pool.close() @@ -420,7 +423,10 @@ describe('[TxPool]', async () => { try { await pool.add(txA02_Underpriced) assert.fail('should fail adding underpriced txn to txpool') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.message.includes('replacement gas too low'), 'successfully failed adding underpriced txn', From f3543fc947dfe8d81abdbfa27ad6dfc833ac4fba Mon Sep 17 00:00:00 2001 From: ScottyPoi Date: Tue, 24 Sep 2024 13:38:16 -0600 Subject: [PATCH 06/21] common: replace (e: any) pattern with Error type check --- packages/common/src/utils.ts | 5 ++++- packages/common/test/utils.spec.ts | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/common/src/utils.ts b/packages/common/src/utils.ts index 6fcbc92f44..e47f6a3add 100644 --- a/packages/common/src/utils.ts +++ b/packages/common/src/utils.ts @@ -238,7 +238,10 @@ export function parseGethGenesis(json: any, name?: string) { finalJSON.name = name } return parseGethParams(finalJSON) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } throw new Error(`Error parsing parameters file: ${e.message}`) } } diff --git a/packages/common/test/utils.spec.ts b/packages/common/test/utils.spec.ts index c418aa8e51..737287e06d 100644 --- a/packages/common/test/utils.spec.ts +++ b/packages/common/test/utils.spec.ts @@ -70,7 +70,10 @@ describe('[Utils/Parse]', () => { try { createCommonFromGethGenesis(mergeAtGenesisData, {}) assert.fail('should have thrown') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes('nonzero terminal total difficulty')) } }) From cd53d55347ca0559865c9db42856bac1535c10a3 Mon Sep 17 00:00:00 2001 From: ScottyPoi Date: Tue, 24 Sep 2024 13:39:21 -0600 Subject: [PATCH 07/21] devp2p: replace (e: any) pattern with Error type check --- packages/devp2p/src/dns/dns.ts | 5 ++- packages/devp2p/src/dpt/dpt.ts | 10 ++++-- packages/devp2p/src/dpt/server.ts | 5 ++- packages/devp2p/src/rlpx/peer.ts | 15 ++++++-- packages/devp2p/test/enr.spec.ts | 35 +++++++++++++++---- .../test/integration/eth-simulator.spec.ts | 15 ++++++-- .../test/integration/les-simulator.spec.ts | 10 ++++-- .../test/integration/snap-simulator.spec.ts | 5 ++- packages/devp2p/test/rlpx.spec.ts | 5 ++- 9 files changed, 84 insertions(+), 21 deletions(-) diff --git a/packages/devp2p/src/dns/dns.ts b/packages/devp2p/src/dns/dns.ts index 2b0ad7226a..7e3b60d186 100644 --- a/packages/devp2p/src/dns/dns.ts +++ b/packages/devp2p/src/dns/dns.ts @@ -102,7 +102,10 @@ export class DNS { default: return null } - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } if (this.DEBUG) { debug(`Errored searching DNS tree at subdomain ${subdomain}: ${error}`) } diff --git a/packages/devp2p/src/dpt/dpt.ts b/packages/devp2p/src/dpt/dpt.ts index 8a6b2341c7..48afa69a21 100644 --- a/packages/devp2p/src/dpt/dpt.ts +++ b/packages/devp2p/src/dpt/dpt.ts @@ -139,7 +139,10 @@ export class DPT { if (peer.id !== undefined) { this._confirmedPeers.add(bytesToUnprefixedHex(peer.id)) } - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } this.events.emit('error', error) return } @@ -165,7 +168,10 @@ export class DPT { this.events.emit('peer:new', peer) this._kbucket.add(peer) return peer - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } this._banlist.add(obj, 300000) // 5 min * 60 * 1000 throw err } diff --git a/packages/devp2p/src/dpt/server.ts b/packages/devp2p/src/dpt/server.ts index 3fea7d07a7..1cc43538de 100644 --- a/packages/devp2p/src/dpt/server.ts +++ b/packages/devp2p/src/dpt/server.ts @@ -54,7 +54,10 @@ export class Server { this._socket.on('message', (msg: Uint8Array, rinfo: RemoteInfo) => { try { this._handler(msg, rinfo) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } this.events.emit('error', err) } }) diff --git a/packages/devp2p/src/rlpx/peer.ts b/packages/devp2p/src/rlpx/peer.ts index 276cba03d3..aa788a5dcc 100644 --- a/packages/devp2p/src/rlpx/peer.ts +++ b/packages/devp2p/src/rlpx/peer.ts @@ -598,7 +598,10 @@ export class Peer { if (protocolName === 'Peer') { try { payload = RLP.decode(payload) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } if (msgCode === PREFIXES.DISCONNECT) { if (compressed) { payload = RLP.decode(origPayload) @@ -611,7 +614,10 @@ export class Peer { } } protocolObj.protocol._handleMessage?.(msgCode, payload) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } this.disconnect(DISCONNECT_REASON.SUBPROTOCOL_ERROR) this.DEBUG && this._logger(`Error on peer subprotocol message handling: ${err}`) this.events.emit('error', err) @@ -643,7 +649,10 @@ export class Peer { break } } - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } this.disconnect(DISCONNECT_REASON.SUBPROTOCOL_ERROR) this.DEBUG && this._logger(`Error on peer socket data handling: ${err}`) this.events.emit('error', err) diff --git a/packages/devp2p/test/enr.spec.ts b/packages/devp2p/test/enr.spec.ts index dba85aec43..a5a63e3052 100644 --- a/packages/devp2p/test/enr.spec.ts +++ b/packages/devp2p/test/enr.spec.ts @@ -16,7 +16,10 @@ describe('ENR tests', () => { it('ENR (root): should error if DNS root entry is mis-prefixed', () => { try { ENR.parseAndVerifyRoot(dns.enrRootBadPrefix, dns.publicKey) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.toString().includes("ENR root entry must start with 'enrtree-root:'"), 'has correct error message', @@ -27,7 +30,10 @@ describe('ENR tests', () => { it('ENR (root): should error if DNS root entry signature is invalid', () => { try { ENR.parseAndVerifyRoot(dns.enrRootBadSig, dns.publicKey) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.toString().includes('Unable to verify ENR root signature'), 'has correct error message', @@ -38,7 +44,10 @@ describe('ENR tests', () => { it('ENR (root): should error if DNS root entry is malformed', () => { try { ENR.parseAndVerifyRoot(dns.enrRootMalformed, dns.publicKey) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.toString().includes("Could not parse 'l' value from ENR root entry"), 'has correct error message', @@ -57,7 +66,10 @@ describe('ENR tests', () => { it('ENR (tree): should error if DNS tree entry is mis-prefixed', () => { try { ENR.parseTree(dns.enrTreeBadPrefix) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.toString().includes("ENR tree entry must start with 'enrtree:'"), 'has correct error message', @@ -68,7 +80,10 @@ describe('ENR tests', () => { it('ENR (tree): should error if DNS tree entry is misformatted', () => { try { ENR.parseTree(dns.enrTreeMalformed) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.toString().includes('Could not parse domain from ENR tree entry'), 'has correct error message', @@ -93,7 +108,10 @@ describe('ENR tests', () => { it('ENR (branch): should error if DNS branch entry is mis-prefixed', () => { try { ENR.parseBranch(dns.enrBranchBadPrefix) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.toString().includes("ENR branch entry must start with 'enrtree-branch:'"), 'has correct error message', @@ -120,7 +138,10 @@ describe('ENR tests', () => { it('ENR (enr): should error if record mis-prefixed', () => { try { ENR.parseAndVerifyRecord(dns.enrBadPrefix) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.toString().includes("String encoded ENR must start with 'enr:'"), 'has correct error message', diff --git a/packages/devp2p/test/integration/eth-simulator.spec.ts b/packages/devp2p/test/integration/eth-simulator.spec.ts index 186bea401c..4bc47c4802 100644 --- a/packages/devp2p/test/integration/eth-simulator.spec.ts +++ b/packages/devp2p/test/integration/eth-simulator.spec.ts @@ -107,7 +107,10 @@ describe('ETH simulator tests', () => { opts.onOnceStatus0 = function (rlpxs: any, eth: any) { try { eth.sendMessage(expectedCode, []) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } const msg = `Error: Code ${expectedCode} not allowed with version ${version}` assert.equal(err.toString(), msg, `should emit error: ${msg}`) util.destroyRLPXs(rlpxs) @@ -208,7 +211,10 @@ describe('ETH simulator tests', () => { opts.onOnceStatus0 = function (rlpxs: any, eth: any) { try { eth.sendMessage(0x55, []) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } const msg = 'Error: Unknown code 85' assert.equal(err.toString(), msg, `should emit error: ${msg}`) util.destroyRLPXs(rlpxs) @@ -227,7 +233,10 @@ describe('ETH simulator tests', () => { opts.onOnceStatus0 = function (rlpxs: any, eth: any) { try { eth.sendMessage(devp2p.ETH.MESSAGE_CODES.STATUS, []) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } const msg = 'Error: Please send status message through .sendStatus' assert.equal(err.toString(), msg, `should emit error: ${msg}`) util.destroyRLPXs(rlpxs) diff --git a/packages/devp2p/test/integration/les-simulator.spec.ts b/packages/devp2p/test/integration/les-simulator.spec.ts index 610f85eed5..e53a96f037 100644 --- a/packages/devp2p/test/integration/les-simulator.spec.ts +++ b/packages/devp2p/test/integration/les-simulator.spec.ts @@ -116,7 +116,10 @@ describe('LES simulator tests', () => { opts.onOnceStatus0 = function (rlpxs: any, les: any) { try { les.sendMessage(0x55, [1, []]) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } const msg = 'Error: Unknown code 85' assert.equal(err.toString(), msg, `should emit error: ${msg}`) util.destroyRLPXs(rlpxs) @@ -135,7 +138,10 @@ describe('LES simulator tests', () => { opts.onOnceStatus0 = function (rlpxs: any, les: any) { try { les.sendMessage(devp2p.ETH.MESSAGE_CODES.STATUS, 1, []) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } const msg = 'Error: Please send status message through .sendStatus' assert.equal(err.toString(), msg, `should emit error: ${msg}`) util.destroyRLPXs(rlpxs) diff --git a/packages/devp2p/test/integration/snap-simulator.spec.ts b/packages/devp2p/test/integration/snap-simulator.spec.ts index 5d43bdbce8..6bc1fce9f0 100644 --- a/packages/devp2p/test/integration/snap-simulator.spec.ts +++ b/packages/devp2p/test/integration/snap-simulator.spec.ts @@ -31,7 +31,10 @@ describe('Snap sync simulator tests', () => { opts.sendMessage = function (rlpxs: any, snap: any) { try { snap.sendMessage(0x55, [1, []]) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } const msg = 'Error: Unknown code 85' assert.equal(err.toString(), msg, `should emit error: ${msg}`) util.destroyRLPXs(rlpxs) diff --git a/packages/devp2p/test/rlpx.spec.ts b/packages/devp2p/test/rlpx.spec.ts index 04262069e6..e956ed9309 100644 --- a/packages/devp2p/test/rlpx.spec.ts +++ b/packages/devp2p/test/rlpx.spec.ts @@ -147,7 +147,10 @@ describe('RLPx', () => { try { await rlpx.connect(mockPeer) assert.fail('should throw') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.equal(err.message, 'Already connected') } }) From cf4f8bceedeeb06f0a53cd836c7410ed4517060d Mon Sep 17 00:00:00 2001 From: ScottyPoi Date: Tue, 24 Sep 2024 13:40:51 -0600 Subject: [PATCH 08/21] evm: replace (e: any) pattern with Error type check --- packages/evm/scripts/eofContainerValidator.ts | 5 ++++- packages/evm/src/evm.ts | 10 ++++++++-- packages/evm/src/interpreter.ts | 5 ++++- packages/evm/src/precompiles/01-ecrecover.ts | 5 ++++- packages/evm/src/precompiles/05-modexp.ts | 5 ++++- packages/evm/src/precompiles/06-bn254-add.ts | 5 ++++- packages/evm/src/precompiles/07-bn254-mul.ts | 5 ++++- .../evm/src/precompiles/08-bn254-pairing.ts | 5 ++++- .../precompiles/0a-kzg-point-evaluation.ts | 5 ++++- .../evm/src/precompiles/0b-bls12-g1add.ts | 5 ++++- .../evm/src/precompiles/0c-bls12-g1mul.ts | 5 ++++- .../evm/src/precompiles/0d-bls12-g1msm.ts | 5 ++++- .../evm/src/precompiles/0e-bls12-g2add.ts | 5 ++++- .../evm/src/precompiles/0f-bls12-g2mul.ts | 5 ++++- .../evm/src/precompiles/10-bls12-g2msm.ts | 5 ++++- .../evm/src/precompiles/11-bls12-pairing.ts | 5 ++++- .../src/precompiles/12-bls12-map-fp-to-g1.ts | 5 ++++- .../src/precompiles/13-bls12-map-fp2-to-g2.ts | 5 ++++- packages/evm/test/runCall.spec.ts | 5 ++++- packages/evm/test/runCode.spec.ts | 20 +++++++++++++++---- packages/evm/test/stack.spec.ts | 5 ++++- 21 files changed, 100 insertions(+), 25 deletions(-) diff --git a/packages/evm/scripts/eofContainerValidator.ts b/packages/evm/scripts/eofContainerValidator.ts index 7a15bf0076..af2a558bfc 100644 --- a/packages/evm/scripts/eofContainerValidator.ts +++ b/packages/evm/scripts/eofContainerValidator.ts @@ -28,7 +28,10 @@ function processLine(line) { try { validateEOF(bytes, evm) console.log('OK') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } console.log('err: ' + e.message) } } diff --git a/packages/evm/src/evm.ts b/packages/evm/src/evm.ts index 16ead4bc27..73691fccf4 100644 --- a/packages/evm/src/evm.ts +++ b/packages/evm/src/evm.ts @@ -320,7 +320,10 @@ export class EVM implements EVMInterface { if (!message.delegatecall) { try { await this._addToBalance(toAccount, message) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } errorMessage = e } } @@ -505,7 +508,10 @@ export class EVM implements EVMInterface { let errorMessage try { await this._addToBalance(toAccount, message as MessageWithTo) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } errorMessage = e } diff --git a/packages/evm/src/interpreter.ts b/packages/evm/src/interpreter.ts index 647f6eb6c4..fe47f13ba5 100644 --- a/packages/evm/src/interpreter.ts +++ b/packages/evm/src/interpreter.ts @@ -322,7 +322,10 @@ export class Interpreter { if (overheadTimer !== undefined) { this.performanceLogger.unpauseTimer(overheadTimer) } - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } if (overheadTimer !== undefined) { this.performanceLogger.unpauseTimer(overheadTimer) } diff --git a/packages/evm/src/precompiles/01-ecrecover.ts b/packages/evm/src/precompiles/01-ecrecover.ts index e5ad0ad41c..63ac8c2c72 100644 --- a/packages/evm/src/precompiles/01-ecrecover.ts +++ b/packages/evm/src/precompiles/01-ecrecover.ts @@ -58,7 +58,10 @@ export function precompile01(opts: PrecompileInput): ExecResult { ) } publicKey = ecrecoverFunction(msgHash, bytesToBigInt(v), r, s) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } if (opts._debug !== undefined) { opts._debug(`${pName} failed: PK recovery failed`) } diff --git a/packages/evm/src/precompiles/05-modexp.ts b/packages/evm/src/precompiles/05-modexp.ts index 38b185669d..4d32dd5397 100644 --- a/packages/evm/src/precompiles/05-modexp.ts +++ b/packages/evm/src/precompiles/05-modexp.ts @@ -62,7 +62,10 @@ function getAdjustedExponentLength(data: Uint8Array): bigint { try { const baseLen = bytesToBigInt(data.subarray(0, 32)) expBytesStart = 96 + Number(baseLen) // 96 for base length, then exponent length, and modulus length, then baseLen for the base data, then exponent bytes start - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } expBytesStart = Number.MAX_SAFE_INTEGER - 32 } const expLen = bytesToBigInt(data.subarray(32, 64)) diff --git a/packages/evm/src/precompiles/06-bn254-add.ts b/packages/evm/src/precompiles/06-bn254-add.ts index 23c8163bf1..d8a7d2e4c8 100644 --- a/packages/evm/src/precompiles/06-bn254-add.ts +++ b/packages/evm/src/precompiles/06-bn254-add.ts @@ -24,7 +24,10 @@ export function precompile06(opts: PrecompileInput): ExecResult { let returnData try { returnData = (opts._EVM as EVM)['_bn254'].add(input) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } if (opts._debug !== undefined) { opts._debug(`${pName} failed: ${e.message}`) } diff --git a/packages/evm/src/precompiles/07-bn254-mul.ts b/packages/evm/src/precompiles/07-bn254-mul.ts index 28be204aef..d784eafa57 100644 --- a/packages/evm/src/precompiles/07-bn254-mul.ts +++ b/packages/evm/src/precompiles/07-bn254-mul.ts @@ -24,7 +24,10 @@ export function precompile07(opts: PrecompileInput): ExecResult { let returnData try { returnData = (opts._EVM as EVM)['_bn254'].mul(input) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } if (opts._debug !== undefined) { opts._debug(`${pName} failed: ${e.message}`) } diff --git a/packages/evm/src/precompiles/08-bn254-pairing.ts b/packages/evm/src/precompiles/08-bn254-pairing.ts index 2d1e67ed3a..503393618c 100644 --- a/packages/evm/src/precompiles/08-bn254-pairing.ts +++ b/packages/evm/src/precompiles/08-bn254-pairing.ts @@ -28,7 +28,10 @@ export function precompile08(opts: PrecompileInput): ExecResult { let returnData try { returnData = (opts._EVM as EVM)['_bn254'].pairing(opts.data) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } if (opts._debug !== undefined) { opts._debug(`${pName} failed: ${e.message}`) } diff --git a/packages/evm/src/precompiles/0a-kzg-point-evaluation.ts b/packages/evm/src/precompiles/0a-kzg-point-evaluation.ts index 990fe37b2e..6f0d4b2715 100644 --- a/packages/evm/src/precompiles/0a-kzg-point-evaluation.ts +++ b/packages/evm/src/precompiles/0a-kzg-point-evaluation.ts @@ -63,7 +63,10 @@ export async function precompile0a(opts: PrecompileInput): Promise { if (res === false) { return EvmErrorResult(new EvmError(ERROR.INVALID_PROOF), opts.gasLimit) } - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } if (err.message.includes('C_KZG_BADARGS') === true) { if (opts._debug !== undefined) { opts._debug(`${pName} failed: INVALID_INPUTS`) diff --git a/packages/evm/src/precompiles/0b-bls12-g1add.ts b/packages/evm/src/precompiles/0b-bls12-g1add.ts index 9fd91e3b4b..cd72390840 100644 --- a/packages/evm/src/precompiles/0b-bls12-g1add.ts +++ b/packages/evm/src/precompiles/0b-bls12-g1add.ts @@ -39,7 +39,10 @@ export async function precompile0b(opts: PrecompileInput): Promise { let returnValue try { returnValue = bls.addG1(opts.data) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } if (opts._debug !== undefined) { opts._debug(`${pName} failed: ${e.message}`) } diff --git a/packages/evm/src/precompiles/0c-bls12-g1mul.ts b/packages/evm/src/precompiles/0c-bls12-g1mul.ts index aedb566405..fa97312485 100644 --- a/packages/evm/src/precompiles/0c-bls12-g1mul.ts +++ b/packages/evm/src/precompiles/0c-bls12-g1mul.ts @@ -37,7 +37,10 @@ export async function precompile0c(opts: PrecompileInput): Promise { let returnValue try { returnValue = bls.mulG1(opts.data) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } if (opts._debug !== undefined) { opts._debug(`${pName} failed: ${e.message}`) } diff --git a/packages/evm/src/precompiles/0d-bls12-g1msm.ts b/packages/evm/src/precompiles/0d-bls12-g1msm.ts index ac67b5be48..c84e0c4626 100644 --- a/packages/evm/src/precompiles/0d-bls12-g1msm.ts +++ b/packages/evm/src/precompiles/0d-bls12-g1msm.ts @@ -62,7 +62,10 @@ export async function precompile0d(opts: PrecompileInput): Promise { let returnValue try { returnValue = bls.msmG1(opts.data) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } if (opts._debug !== undefined) { opts._debug(`${pName} failed: ${e.message}`) } diff --git a/packages/evm/src/precompiles/0e-bls12-g2add.ts b/packages/evm/src/precompiles/0e-bls12-g2add.ts index d1bc0e4807..600534676c 100644 --- a/packages/evm/src/precompiles/0e-bls12-g2add.ts +++ b/packages/evm/src/precompiles/0e-bls12-g2add.ts @@ -45,7 +45,10 @@ export async function precompile0e(opts: PrecompileInput): Promise { let returnValue try { returnValue = bls.addG2(opts.data) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } return EvmErrorResult(e, opts.gasLimit) } diff --git a/packages/evm/src/precompiles/0f-bls12-g2mul.ts b/packages/evm/src/precompiles/0f-bls12-g2mul.ts index 3e6e16d6eb..949846d806 100644 --- a/packages/evm/src/precompiles/0f-bls12-g2mul.ts +++ b/packages/evm/src/precompiles/0f-bls12-g2mul.ts @@ -41,7 +41,10 @@ export async function precompile0f(opts: PrecompileInput): Promise { let returnValue try { returnValue = bls.mulG2(opts.data) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } if (opts._debug !== undefined) { opts._debug(`${pName} failed: ${e.message}`) } diff --git a/packages/evm/src/precompiles/10-bls12-g2msm.ts b/packages/evm/src/precompiles/10-bls12-g2msm.ts index b327e3ca6f..7688778dc2 100644 --- a/packages/evm/src/precompiles/10-bls12-g2msm.ts +++ b/packages/evm/src/precompiles/10-bls12-g2msm.ts @@ -53,7 +53,10 @@ export async function precompile10(opts: PrecompileInput): Promise { let returnValue try { returnValue = bls.msmG2(opts.data) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } if (opts._debug !== undefined) { opts._debug(`${pName} failed: ${e.message}`) } diff --git a/packages/evm/src/precompiles/11-bls12-pairing.ts b/packages/evm/src/precompiles/11-bls12-pairing.ts index fa8a03ecc9..70c04d5e5d 100644 --- a/packages/evm/src/precompiles/11-bls12-pairing.ts +++ b/packages/evm/src/precompiles/11-bls12-pairing.ts @@ -59,7 +59,10 @@ export async function precompile11(opts: PrecompileInput): Promise { let returnValue try { returnValue = bls.pairingCheck(opts.data) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } if (opts._debug !== undefined) { opts._debug(`${pName} failed: ${e.message}`) } diff --git a/packages/evm/src/precompiles/12-bls12-map-fp-to-g1.ts b/packages/evm/src/precompiles/12-bls12-map-fp-to-g1.ts index 93381090db..8ef220c8e9 100644 --- a/packages/evm/src/precompiles/12-bls12-map-fp-to-g1.ts +++ b/packages/evm/src/precompiles/12-bls12-map-fp-to-g1.ts @@ -34,7 +34,10 @@ export async function precompile12(opts: PrecompileInput): Promise { let returnValue try { returnValue = bls.mapFPtoG1(opts.data) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } if (opts._debug !== undefined) { opts._debug(`${pName} failed: ${e.message}`) } diff --git a/packages/evm/src/precompiles/13-bls12-map-fp2-to-g2.ts b/packages/evm/src/precompiles/13-bls12-map-fp2-to-g2.ts index ff4a60f3c4..9b7c121025 100644 --- a/packages/evm/src/precompiles/13-bls12-map-fp2-to-g2.ts +++ b/packages/evm/src/precompiles/13-bls12-map-fp2-to-g2.ts @@ -37,7 +37,10 @@ export async function precompile13(opts: PrecompileInput): Promise { let returnValue try { returnValue = bls.mapFP2toG2(opts.data) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } if (opts._debug !== undefined) { opts._debug(`${pName} failed: ${e.message}`) } diff --git a/packages/evm/test/runCall.spec.ts b/packages/evm/test/runCall.spec.ts index 8cf1217959..693fcedac8 100644 --- a/packages/evm/test/runCall.spec.ts +++ b/packages/evm/test/runCall.spec.ts @@ -469,7 +469,10 @@ describe('RunCall tests', () => { try { await evm.runCall(runCallArgs) assert.fail('should not accept a negative call value') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok( err.message.includes('value field cannot be negative'), 'throws on negative call value', diff --git a/packages/evm/test/runCode.spec.ts b/packages/evm/test/runCode.spec.ts index 821626a339..d5bdc25a0d 100644 --- a/packages/evm/test/runCode.spec.ts +++ b/packages/evm/test/runCode.spec.ts @@ -40,7 +40,10 @@ describe('VM.runCode: initial program counter', () => { `should start the execution at the specified pc or 0, testCases[${i}]`, ) } - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } err = e } @@ -68,7 +71,10 @@ describe('VM.runCode: interpreter', () => { let result: any try { result = await evm.runCode!(runCodeArgs) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.fail('should not throw error') } assert.equal(result!.exceptionError!.errorType, 'EvmError') @@ -97,7 +103,10 @@ describe('VM.runCode: interpreter', () => { try { await evm.runCode!(runCodeArgs) assert.fail('should throw error') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok(e.toString().includes('Test'), 'error thrown') } }) @@ -115,7 +124,10 @@ describe('VM.runCode: RunCodeOptions', () => { try { await evm.runCode!(runCodeArgs) assert.fail('should not accept a negative call value') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok( err.message.includes('value field cannot be negative'), 'throws on negative call value', diff --git a/packages/evm/test/stack.spec.ts b/packages/evm/test/stack.spec.ts index ed75419f04..c09fbb3538 100644 --- a/packages/evm/test/stack.spec.ts +++ b/packages/evm/test/stack.spec.ts @@ -134,7 +134,10 @@ describe('Stack', () => { const res = await evm.runCall(runCallArgs) const executionReturnValue = res.execResult.returnValue assert.deepEqual(executionReturnValue, expectedReturnValue) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.fail(e.message) } }) From 75ffbbf6caa445250d28778f5003240ab1bc6b6b Mon Sep 17 00:00:00 2001 From: ScottyPoi Date: Tue, 24 Sep 2024 13:42:07 -0600 Subject: [PATCH 09/21] rlp: replace (e: any) pattern with Error type check --- packages/rlp/test/dataTypes.spec.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/rlp/test/dataTypes.spec.ts b/packages/rlp/test/dataTypes.spec.ts index 20105c0563..0b9cce30b1 100644 --- a/packages/rlp/test/dataTypes.spec.ts +++ b/packages/rlp/test/dataTypes.spec.ts @@ -28,7 +28,10 @@ describe('invalid RLPs', () => { try { RLP.decode(input) assert.fail() - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } if (typeof msg !== 'undefined') { assert.deepEqual(e.message, msg) } else { From a38c6972d175064c3b5d2073d0ab335171dfb8e2 Mon Sep 17 00:00:00 2001 From: ScottyPoi Date: Tue, 24 Sep 2024 13:42:50 -0600 Subject: [PATCH 10/21] statemanager: replace (e: any) pattern with Error type check --- .../statemanager/test/rpcStateManager.spec.ts | 10 ++++++++-- packages/statemanager/test/stateManager.spec.ts | 10 ++++++++-- .../test/stateManager.storage.spec.ts | 15 ++++++++++++--- .../test/statelessVerkleStateManager.spec.ts | 5 ++++- packages/statemanager/test/vmState.spec.ts | 5 ++++- 5 files changed, 36 insertions(+), 9 deletions(-) diff --git a/packages/statemanager/test/rpcStateManager.spec.ts b/packages/statemanager/test/rpcStateManager.spec.ts index 8fbaf674fb..bbb6c2d215 100644 --- a/packages/statemanager/test/rpcStateManager.spec.ts +++ b/packages/statemanager/test/rpcStateManager.spec.ts @@ -208,7 +208,10 @@ describe('RPC State Manager API tests', () => { try { await createBlockFromJSONRPCProvider(provider, 'fakeBlockTag', {} as any) assert.fail('should have thrown') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok( err.message.includes('expected blockTag to be block hash, bigint, hex prefixed string'), 'threw with correct error when invalid blockTag provided', @@ -307,7 +310,10 @@ describe('runBlock test', () => { block.header.gasUsed, 'should compute correct cumulative gas for block', ) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.fail(`should have successfully ran block; got error ${err.message}`) } }) diff --git a/packages/statemanager/test/stateManager.spec.ts b/packages/statemanager/test/stateManager.spec.ts index c0783792e3..909ab37b4f 100644 --- a/packages/statemanager/test/stateManager.spec.ts +++ b/packages/statemanager/test/stateManager.spec.ts @@ -282,7 +282,10 @@ describe('StateManager -> General', () => { try { await addMerkleStateProofData(newPartialStateManager2, [proof2, stProof], true) assert.fail('cannot reach this') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok(e.message.includes('proof does not have the expected trie root')) } @@ -297,7 +300,10 @@ describe('StateManager -> General', () => { try { await fromMerkleStateProof([proof1, zeroAddressProof], true) assert.fail('cannot reach this') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok(e.message.includes('proof does not have the expected trie root')) } diff --git a/packages/statemanager/test/stateManager.storage.spec.ts b/packages/statemanager/test/stateManager.storage.spec.ts index 1c0ded01f1..91a7eb2b06 100644 --- a/packages/statemanager/test/stateManager.storage.spec.ts +++ b/packages/statemanager/test/stateManager.storage.spec.ts @@ -49,7 +49,10 @@ describe('StateManager -> Storage', () => { try { await stateManager.putStorage(address, new Uint8Array(12), hexToBytes('0x1231')) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.equal(e.message, 'Storage key must be 32 bytes long') return } @@ -68,7 +71,10 @@ describe('StateManager -> Storage', () => { try { await stateManager.getStorage(address, new Uint8Array(12)) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.equal(e.message, 'Storage key must be 32 bytes long') return } @@ -90,7 +96,10 @@ describe('StateManager -> Storage', () => { try { await stateManager.putStorage(address, key, value) assert.fail('did not throw') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok(true, 'threw on trying to set storage values larger than 32 bytes') } }) diff --git a/packages/statemanager/test/statelessVerkleStateManager.spec.ts b/packages/statemanager/test/statelessVerkleStateManager.spec.ts index 0acce807a1..9d3122666d 100644 --- a/packages/statemanager/test/statelessVerkleStateManager.spec.ts +++ b/packages/statemanager/test/statelessVerkleStateManager.spec.ts @@ -82,7 +82,10 @@ describe('StatelessVerkleStateManager: Kaustinen Verkle Block', () => { try { await stateManager.getAccount(address) assert.fail('should throw on getting account that is not found in witness') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.equal( e.message.slice(0, 25), 'No witness bundled for ad', diff --git a/packages/statemanager/test/vmState.spec.ts b/packages/statemanager/test/vmState.spec.ts index 64079ff27e..43e5449dd5 100644 --- a/packages/statemanager/test/vmState.spec.ts +++ b/packages/statemanager/test/vmState.spec.ts @@ -131,7 +131,10 @@ describe('Original storage cache', async () => { it("getOriginalContractStorage should validate the key's length", async () => { try { await stateManager.originalStorageCache.get(address, new Uint8Array(12)) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.equal(e.message, 'Storage key must be 32 bytes long') return } From 13ea657e31c8a0704466778aff8f2f6aee31e2a1 Mon Sep 17 00:00:00 2001 From: ScottyPoi Date: Tue, 24 Sep 2024 13:43:48 -0600 Subject: [PATCH 11/21] trie: replace (e: any) pattern with Error type check --- packages/trie/benchmarks/engines/level.ts | 5 ++++- packages/trie/examples/customLevelDB.ts | 5 ++++- packages/trie/recipes/level-legacy.ts | 5 ++++- packages/trie/recipes/level.ts | 7 +++++-- packages/trie/scripts/view.ts | 5 ++++- packages/trie/src/proof/index.ts | 15 ++++++++++++--- packages/trie/src/proof/range.ts | 5 ++++- packages/trie/src/trie.ts | 10 ++++++++-- packages/trie/src/util/walkController.ts | 10 ++++++++-- packages/trie/test/proof.spec.ts | 15 ++++++++++++--- packages/trie/test/trie/trie.spec.ts | 5 ++++- 11 files changed, 69 insertions(+), 18 deletions(-) diff --git a/packages/trie/benchmarks/engines/level.ts b/packages/trie/benchmarks/engines/level.ts index 16f3f814ab..179078181d 100644 --- a/packages/trie/benchmarks/engines/level.ts +++ b/packages/trie/benchmarks/engines/level.ts @@ -67,7 +67,10 @@ export class LevelDB< try { value = await this._leveldb.get(key, encodings) if (value === null) return undefined - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } // https://github.com/Level/abstract-level/blob/915ad1317694d0ce8c580b5ab85d81e1e78a3137/abstract-level.js#L309 // This should be `true` if the error came from LevelDB // so we can check for `NOT true` to identify any non-404 errors diff --git a/packages/trie/examples/customLevelDB.ts b/packages/trie/examples/customLevelDB.ts index dbe92d8de6..5cffa3e110 100644 --- a/packages/trie/examples/customLevelDB.ts +++ b/packages/trie/examples/customLevelDB.ts @@ -69,7 +69,10 @@ export class LevelDB< try { value = await this._leveldb.get(key, encodings) if (value === null) return undefined - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } // https://github.com/Level/abstract-level/blob/915ad1317694d0ce8c580b5ab85d81e1e78a3137/abstract-level.js#L309 // This should be `true` if the error came from LevelDB // so we can check for `NOT true` to identify any non-404 errors diff --git a/packages/trie/recipes/level-legacy.ts b/packages/trie/recipes/level-legacy.ts index 52755e283b..b9713c410b 100644 --- a/packages/trie/recipes/level-legacy.ts +++ b/packages/trie/recipes/level-legacy.ts @@ -16,7 +16,10 @@ export class LevelDB implements DB { let value try { value = await this._leveldb.get(key, ENCODING_OPTS) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } // https://github.com/Level/abstract-level/blob/915ad1317694d0ce8c580b5ab85d81e1e78a3137/abstract-level.js#L309 // This should be `true` if the error came from LevelDB // so we can check for `NOT true` to identify any non-404 errors diff --git a/packages/trie/recipes/level.ts b/packages/trie/recipes/level.ts index 68b78e03f3..e58cd55658 100644 --- a/packages/trie/recipes/level.ts +++ b/packages/trie/recipes/level.ts @@ -17,7 +17,7 @@ export class LevelDB implements DB { string | Uint8Array | Uint8Array, string | Uint8Array, string | Uint8Array - > | null + > | null, ) { this._leveldb = leveldb ?? new MemoryLevel(ENCODING_OPTS) } @@ -26,7 +26,10 @@ export class LevelDB implements DB { let value try { value = await this._leveldb.get(key, ENCODING_OPTS) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } // https://github.com/Level/abstract-level/blob/915ad1317694d0ce8c580b5ab85d81e1e78a3137/abstract-level.js#L309 // This should be `true` if the error came from LevelDB // so we can check for `NOT true` to identify any non-404 errors diff --git a/packages/trie/scripts/view.ts b/packages/trie/scripts/view.ts index 9ce644f428..4411b0c827 100644 --- a/packages/trie/scripts/view.ts +++ b/packages/trie/scripts/view.ts @@ -103,7 +103,10 @@ export const view = async (testName: string, inputs: any[], root: string) => { } try { await trie.put(input[0], input[1]) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } debugT(`trie.put error: ${e.message}`) } trie.checkpoint() diff --git a/packages/trie/src/proof/index.ts b/packages/trie/src/proof/index.ts index c3462c9318..deb495578a 100644 --- a/packages/trie/src/proof/index.ts +++ b/packages/trie/src/proof/index.ts @@ -27,7 +27,10 @@ export async function verifyTrieProof( const proofTrie = await createTrieFromProof(proof, opts) const value = await proofTrie.get(key, true) return value - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } throw new Error('Invalid proof provided') } } @@ -149,7 +152,10 @@ export async function verifyMerkleProof( }) try { await updateTrieFromMerkleProof(proofTrie, proof, true) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } throw new Error('Invalid proof nodes given') } try { @@ -160,7 +166,10 @@ export async function verifyMerkleProof( const value = await proofTrie.get(trie['appliedKey'](key), true) trie['DEBUG'] && trie['debug'](`PROOF VERIFIED`, ['VERIFY_PROOF']) return value - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } if (err.message === 'Missing node in DB') { throw new Error('Invalid proof provided') } else { diff --git a/packages/trie/src/proof/range.ts b/packages/trie/src/proof/range.ts index a3699989fc..2557f8aeb2 100644 --- a/packages/trie/src/proof/range.ts +++ b/packages/trie/src/proof/range.ts @@ -333,7 +333,10 @@ async function verifyMerkleProof( trie: proofTrie, value, } - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } if (err.message === 'Missing node in DB') { throw new Error('Invalid proof provided') } else { diff --git a/packages/trie/src/trie.ts b/packages/trie/src/trie.ts index 4ab3ef7fb9..de584e2186 100644 --- a/packages/trie/src/trie.ts +++ b/packages/trie/src/trie.ts @@ -171,7 +171,10 @@ export class Trie { try { const value = await this.lookupNode(root) return value !== null - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } if (error.message === 'Missing node in DB') { return equalsBytes(root, this.EMPTY_TRIE_ROOT) } else { @@ -411,7 +414,10 @@ export class Trie { ['FIND_PATH'], ) await this.walkTrie(start, onFound) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } if (error.message !== 'Missing node in DB' || throwIfMissing) { throw error } diff --git a/packages/trie/src/util/walkController.ts b/packages/trie/src/util/walkController.ts index 0339f3fafa..5caf35efed 100644 --- a/packages/trie/src/util/walkController.ts +++ b/packages/trie/src/util/walkController.ts @@ -54,7 +54,10 @@ export class WalkController { let node try { node = await this.trie.lookupNode(root) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } return this.reject(error) } this.processNode(root, node, []) @@ -101,7 +104,10 @@ export class WalkController { let childNode try { childNode = await this.trie.lookupNode(nodeRef) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } return this.reject(error) } taskFinishedCallback() // this marks the current task as finished. If there are any tasks left in the queue, this will immediately execute the first task. diff --git a/packages/trie/test/proof.spec.ts b/packages/trie/test/proof.spec.ts index 99455e0569..811766815f 100644 --- a/packages/trie/test/proof.spec.ts +++ b/packages/trie/test/proof.spec.ts @@ -51,7 +51,10 @@ describe('simple merkle proofs generation and verification', () => { try { await verifyTrieProof(utf8ToBytes('key1aa'), proof) assert.fail('expected error: Invalid proof provided') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.equal(e.message, 'Invalid proof provided') } @@ -61,7 +64,10 @@ describe('simple merkle proofs generation and verification', () => { try { await verifyTrieProof(utf8ToBytes('key2bb'), proof) assert.fail('expected error: Invalid proof provided') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.equal(e.message, 'Invalid proof provided') } @@ -76,7 +82,10 @@ describe('simple merkle proofs generation and verification', () => { try { await createTrieFromProof(proof, { root: trie.root() }) assert.fail(`expected error: 'The provided proof does not have the expected trie root'`) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.equal(e.message, 'The provided proof does not have the expected trie root') } }) diff --git a/packages/trie/test/trie/trie.spec.ts b/packages/trie/test/trie/trie.spec.ts index f719b0195f..4963545a61 100644 --- a/packages/trie/test/trie/trie.spec.ts +++ b/packages/trie/test/trie/trie.spec.ts @@ -213,7 +213,10 @@ for (const { constructor, defaults, title } of [ try { await emptyTrie.checkRoot(ROOT_DB_KEY) assert.fail('Should throw') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.notEqual( 'Missing node in DB', e.message, From 9df3660607bd373e1f9afb9e9f4bc101d4419afd Mon Sep 17 00:00:00 2001 From: ScottyPoi Date: Tue, 24 Sep 2024 13:44:34 -0600 Subject: [PATCH 12/21] vm: replace (e: any) pattern with Error type check --- packages/vm/src/runBlock.ts | 5 ++- packages/vm/src/runTx.ts | 5 ++- packages/vm/src/vm.ts | 5 ++- .../EIPs/eip-1283-net-gas-metering.spec.ts | 5 ++- packages/vm/test/api/EIPs/eip-3607.spec.ts | 10 ++++- packages/vm/test/api/EIPs/eip-7002.spec.ts | 5 ++- packages/vm/test/api/buildBlock.spec.ts | 20 ++++++++-- packages/vm/test/api/index.spec.ts | 15 +++++-- .../vm/test/api/istanbul/eip-1344.spec.ts | 5 ++- .../vm/test/api/istanbul/eip-1884.spec.ts | 5 ++- .../vm/test/api/istanbul/eip-2200.spec.ts | 5 ++- packages/vm/test/api/level.ts | 5 ++- packages/vm/test/api/runBlock.spec.ts | 5 ++- packages/vm/test/api/runTx.spec.ts | 40 +++++++++++++++---- packages/vm/test/t8n/t8ntool.ts | 5 ++- .../tester/runners/BlockchainTestsRunner.ts | 25 +++++++++--- .../tester/runners/GeneralStateTestsRunner.ts | 15 +++++-- packages/vm/test/tester/testLoader.ts | 5 ++- 18 files changed, 148 insertions(+), 37 deletions(-) diff --git a/packages/vm/src/runBlock.ts b/packages/vm/src/runBlock.ts index a5d9be682b..e087308ee0 100644 --- a/packages/vm/src/runBlock.ts +++ b/packages/vm/src/runBlock.ts @@ -200,7 +200,10 @@ export async function runBlock(vm: VM, opts: RunBlockOpts): Promise { debug(`tx checkpoint committed`) } return result - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } await vm.evm.journal.revert() if (vm.DEBUG) { debug(`tx checkpoint reverted`) diff --git a/packages/vm/src/vm.ts b/packages/vm/src/vm.ts index 5d010271a4..8eaa1b9033 100644 --- a/packages/vm/src/vm.ts +++ b/packages/vm/src/vm.ts @@ -127,7 +127,10 @@ export class VM { let hf = '' try { hf = this.common.hardfork() - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } hf = 'error' } const errorStr = `vm hf=${hf}` diff --git a/packages/vm/test/api/EIPs/eip-1283-net-gas-metering.spec.ts b/packages/vm/test/api/EIPs/eip-1283-net-gas-metering.spec.ts index 203f8ba3bb..5d999b37ea 100644 --- a/packages/vm/test/api/EIPs/eip-1283-net-gas-metering.spec.ts +++ b/packages/vm/test/api/EIPs/eip-1283-net-gas-metering.spec.ts @@ -58,7 +58,10 @@ describe('Constantinople: EIP-1283', () => { assert.equal(res.execResult.exceptionError, undefined) assert.equal(res.execResult.executionGasUsed, BigInt(testCase.used)) assert.equal(res.execResult.gasRefund, BigInt(testCase.refund)) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.fail(e.message) } } diff --git a/packages/vm/test/api/EIPs/eip-3607.spec.ts b/packages/vm/test/api/EIPs/eip-3607.spec.ts index dc7f71d502..5d8e3ec559 100644 --- a/packages/vm/test/api/EIPs/eip-3607.spec.ts +++ b/packages/vm/test/api/EIPs/eip-3607.spec.ts @@ -18,7 +18,10 @@ describe('EIP-3607 tests', () => { try { await runTx(vm, { tx, skipHardForkValidation: true }) assert.fail('runTx should have thrown') - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } if ((error.message as string).includes('EIP-3607')) { assert.ok(true, 'threw correct error') } else { @@ -35,7 +38,10 @@ describe('EIP-3607 tests', () => { try { await runTx(vm, { tx, skipHardForkValidation: true }) assert.ok('runTx successfully ran') - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } assert.fail('threw an unexpected error') } }) diff --git a/packages/vm/test/api/EIPs/eip-7002.spec.ts b/packages/vm/test/api/EIPs/eip-7002.spec.ts index 7850812765..0d89354f8a 100644 --- a/packages/vm/test/api/EIPs/eip-7002.spec.ts +++ b/packages/vm/test/api/EIPs/eip-7002.spec.ts @@ -182,7 +182,10 @@ describe('EIP-7002 tests', () => { skipBlockValidation: true, generate: true, }) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok(e.message.includes('Attempt to accumulate EIP-7002 requests failed')) } }) diff --git a/packages/vm/test/api/buildBlock.spec.ts b/packages/vm/test/api/buildBlock.spec.ts index 5405a1a860..e032adeb4c 100644 --- a/packages/vm/test/api/buildBlock.spec.ts +++ b/packages/vm/test/api/buildBlock.spec.ts @@ -81,7 +81,10 @@ describe('BlockBuilder', () => { try { await blockBuilder.addTransaction(tx) assert.fail('should throw error') - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } if ( (error.message as string).includes( 'tx has a higher gas limit than the remaining gas in the block', @@ -268,7 +271,10 @@ describe('BlockBuilder', () => { 'reverted', 'block should be in reverted status', ) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } assert.fail('should not throw') } @@ -289,7 +295,10 @@ describe('BlockBuilder', () => { 'reverted', 'block should be in reverted status', ) - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } assert.fail('should not throw') } }) @@ -350,7 +359,10 @@ describe('BlockBuilder', () => { try { await blockBuilder.addTransaction(tx) assert.fail('should throw error') - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } assert.ok( (error.message as string).includes("is less than the block's baseFeePerGas"), 'should fail with appropriate error', diff --git a/packages/vm/test/api/index.spec.ts b/packages/vm/test/api/index.spec.ts index 178cc2841e..272f97afdc 100644 --- a/packages/vm/test/api/index.spec.ts +++ b/packages/vm/test/api/index.spec.ts @@ -57,7 +57,10 @@ describe('VM -> Default EVM / Custom EVM Opts', () => { try { await createVM({ evmOpts: {}, evm: await createEVM() }) assert.fail('should throw') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok('correctly thrown') } }) @@ -124,7 +127,10 @@ describe('VM -> supportedHardforks', () => { try { await createVM({ common }) assert.fail('should have failed for unsupported hardfork') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok(e.message.includes('supportedHardforks')) } // restore supported hardforks @@ -188,7 +194,10 @@ describe('VM -> common (chain, HFs, EIPs)', () => { common = new Common({ chain: Mainnet, hardfork: 'extraCheese' }) vm = await createVM({ common }) assert.fail('should have failed for invalid chain') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok(e.message.includes('not supported')) } }) diff --git a/packages/vm/test/api/istanbul/eip-1344.spec.ts b/packages/vm/test/api/istanbul/eip-1344.spec.ts index 0d24b903ac..25fa514db3 100644 --- a/packages/vm/test/api/istanbul/eip-1344.spec.ts +++ b/packages/vm/test/api/istanbul/eip-1344.spec.ts @@ -32,7 +32,10 @@ describe('Istanbul: EIP-1344', () => { assert.ok(res.exceptionError === undefined) assert.equal(testCase.chainId, bytesToBigInt(res.returnValue)) } - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.fail(e.message) } } diff --git a/packages/vm/test/api/istanbul/eip-1884.spec.ts b/packages/vm/test/api/istanbul/eip-1884.spec.ts index 9ca0582116..64d6db9eef 100644 --- a/packages/vm/test/api/istanbul/eip-1884.spec.ts +++ b/packages/vm/test/api/istanbul/eip-1884.spec.ts @@ -40,7 +40,10 @@ describe('Istanbul: EIP-1884', () => { assert.ok(res.exceptionError === undefined) assert.ok(BigInt(testCase.selfbalance!) === bytesToBigInt(res.returnValue)) } - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.fail(e.message) } } diff --git a/packages/vm/test/api/istanbul/eip-2200.spec.ts b/packages/vm/test/api/istanbul/eip-2200.spec.ts index d3f24a3161..7eaed5b763 100644 --- a/packages/vm/test/api/istanbul/eip-2200.spec.ts +++ b/packages/vm/test/api/istanbul/eip-2200.spec.ts @@ -78,7 +78,10 @@ describe('Istanbul: EIP-2200', () => { } assert.equal(res.execResult.executionGasUsed, BigInt(testCase.used)) assert.equal(res.execResult.gasRefund!, BigInt(testCase.refund)) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.fail(e.message) } } diff --git a/packages/vm/test/api/level.ts b/packages/vm/test/api/level.ts index 39ba1e1a96..1457f3abdf 100644 --- a/packages/vm/test/api/level.ts +++ b/packages/vm/test/api/level.ts @@ -32,7 +32,10 @@ export class LevelDB implements DB { try { value = await this._leveldb.get(key, ENCODING_OPTS) if (value === null) return undefined - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } // https://github.com/Level/abstract-level/blob/915ad1317694d0ce8c580b5ab85d81e1e78a3137/abstract-level.js#L309 // This should be `true` if the error came from LevelDB // so we can check for `NOT true` to identify any non-404 errors diff --git a/packages/vm/test/api/runBlock.spec.ts b/packages/vm/test/api/runBlock.spec.ts index a4df164cb0..d854c2959a 100644 --- a/packages/vm/test/api/runBlock.spec.ts +++ b/packages/vm/test/api/runBlock.spec.ts @@ -273,7 +273,10 @@ describe('runBlock() -> API parameter usage/data errors', async () => { ;(vm.blockchain as any).validateHeader = undefined try { await runBlock(vm, { block }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.equal( err.message, 'cannot validate header: blockchain has no `validateHeader` method', diff --git a/packages/vm/test/api/runTx.spec.ts b/packages/vm/test/api/runTx.spec.ts index 15010aeebc..443cebebf6 100644 --- a/packages/vm/test/api/runTx.spec.ts +++ b/packages/vm/test/api/runTx.spec.ts @@ -273,7 +273,10 @@ describe('runTx() -> API parameter usage/data errors', () => { await runTx(vm, { tx, skipHardForkValidation: true }) // TODO uncomment: // assert.fail('should throw error') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.message.includes('(EIP-2718) not activated'), `should fail for ${TRANSACTION_TYPES[1].name}`, @@ -323,7 +326,10 @@ describe('runTx() -> API parameter usage/data errors', () => { try { await runTx(vm, { tx }) assert.fail('should throw error') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.message.includes('not signed') === true || e.message.includes('Invalid Signature') === true, @@ -339,7 +345,10 @@ describe('runTx() -> API parameter usage/data errors', () => { const tx = getTransaction(vm.common, txType.type, true) try { await runTx(vm, { tx }) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.message.toLowerCase().includes('enough funds'), `should fail for ${txType.name}`, @@ -361,7 +370,10 @@ describe('runTx() -> API parameter usage/data errors', () => { try { await runTx(vm, { tx }) assert.fail('should throw error') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.message.toLowerCase().includes('max cost'), `should fail if max cost exceeds balance`, @@ -388,7 +400,10 @@ describe('runTx() -> API parameter usage/data errors', () => { try { await runTx(vm, { tx: tx2 }) assert.fail('cannot reach this') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok(true, 'successfully threw on insufficient balance for transaction') } }) @@ -405,7 +420,10 @@ describe('runTx() -> API parameter usage/data errors', () => { try { await runTx(vm, { tx }) assert.fail('cannot reach this') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok(true, 'successfully threw on wrong nonces') } }) @@ -420,7 +438,10 @@ describe('runTx() -> API parameter usage/data errors', () => { try { await runTx(vm, { tx, block }) assert.fail('should fail') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.message.includes("is less than the block's baseFeePerGas"), 'should fail with appropriate error', @@ -726,7 +747,10 @@ describe('runTx() -> RunTxOptions', () => { skipBalance, }) assert.fail('should not accept a negative call value') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok( err.message.includes('value field cannot be negative'), 'throws on negative call value', diff --git a/packages/vm/test/t8n/t8ntool.ts b/packages/vm/test/t8n/t8ntool.ts index ce5b44f291..09b1f66cf0 100644 --- a/packages/vm/test/t8n/t8ntool.ts +++ b/packages/vm/test/t8n/t8ntool.ts @@ -107,7 +107,10 @@ export class TransitionTool { // Set `allowNoBlobs` to `true`, since the test might not have the blob // The 4844-tx at this should still be valid, since it has the `blobHashes` field await builder.addTransaction(tx, { allowNoBlobs: true }) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } this.rejected.push({ index, error: e.message, diff --git a/packages/vm/test/tester/runners/BlockchainTestsRunner.ts b/packages/vm/test/tester/runners/BlockchainTestsRunner.ts index 11edabeea2..4dcec449b8 100644 --- a/packages/vm/test/tester/runners/BlockchainTestsRunner.ts +++ b/packages/vm/test/tester/runners/BlockchainTestsRunner.ts @@ -141,7 +141,10 @@ export async function runBlockchainTest(options: any, testData: any, t: tape.Tes const blockRlp = hexToBytes(raw.rlp as PrefixedHexString) const decodedRLP: any = RLP.decode(Uint8Array.from(blockRlp)) currentBlock = bytesToBigInt(decodedRLP[0][8]) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } await handleError(e, expectException) continue } @@ -179,7 +182,10 @@ export async function runBlockchainTest(options: any, testData: any, t: tape.Tes if (shouldFail) { t.fail('tx should fail, but did not fail') } - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } if (!shouldFail) { t.fail(`tx should not fail, but failed: ${e.message}`) } else { @@ -207,13 +213,19 @@ export async function runBlockchainTest(options: any, testData: any, t: tape.Tes try { await runBlock(vm, { block, root: parentState, setHardfork: true }) // set as new head block - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } // remove invalid block await blockchain!.delBlock(block.header.hash()) throw error } }) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } // if the test fails, then block.header is the prev because // vm.runBlock has a check that prevents the actual postState from being // imported if it is not equal to the expected postState. it is useful @@ -234,7 +246,10 @@ export async function runBlockchainTest(options: any, testData: any, t: tape.Tes t.fail(`expected exception but test did not throw an exception: ${expectException}`) return } - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } // caught an error, reduce block number currentBlock-- await handleError(error, expectException) diff --git a/packages/vm/test/tester/runners/GeneralStateTestsRunner.ts b/packages/vm/test/tester/runners/GeneralStateTestsRunner.ts index 310bb35a61..1ae1c25b88 100644 --- a/packages/vm/test/tester/runners/GeneralStateTestsRunner.ts +++ b/packages/vm/test/tester/runners/GeneralStateTestsRunner.ts @@ -105,7 +105,10 @@ async function runTestCase(options: any, testData: any, t: tape.Test) { try { tx = makeTx(testData.transaction, { common }) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } console.log('error: ', e) console.log('testData.transaction: ', testData.transaction) execInfo = 'tx instantiation exception' @@ -153,7 +156,10 @@ async function runTestCase(options: any, testData: any, t: tape.Test) { try { await runTx(vm, { tx, block }) execInfo = 'successful tx run' - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } console.log(e) execInfo = `tx runtime error :${e.message}` } @@ -208,7 +214,10 @@ export async function runStateTest(options: any, testData: any, t: tape.Test) { await runTestCase(options, testCase, t) } } - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } console.log(e) t.fail(`error running test case for fork: ${options.forkConfigTestSuite}`) } diff --git a/packages/vm/test/tester/testLoader.ts b/packages/vm/test/tester/testLoader.ts index a7ad7fb22d..9678b62d93 100644 --- a/packages/vm/test/tester/testLoader.ts +++ b/packages/vm/test/tester/testLoader.ts @@ -89,7 +89,10 @@ export function getTestFromSource(file: string, onFile: Function) { .on('end', function () { try { test = JSON.parse(contents) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } onFile(e) } From e77fae10b6b6101b7566de0a7c16c0f6f775b5f9 Mon Sep 17 00:00:00 2001 From: ScottyPoi Date: Tue, 24 Sep 2024 13:45:09 -0600 Subject: [PATCH 13/21] wallet: replace (e: any) pattern with Error type check --- packages/wallet/test/index.spec.ts | 165 +++++++++++++++++++++++------ 1 file changed, 132 insertions(+), 33 deletions(-) diff --git a/packages/wallet/test/index.spec.ts b/packages/wallet/test/index.spec.ts index b7c918d2bb..3bcbccd75a 100644 --- a/packages/wallet/test/index.spec.ts +++ b/packages/wallet/test/index.spec.ts @@ -116,7 +116,10 @@ describe('Wallet tests', () => { it('.toV3() should fail', async () => { try { await Wallet.fromPublicKey(pubKey).toV3('') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok( err.message.includes('This is a public key only wallet'), 'fails to generate V3 when no private key present', @@ -316,7 +319,10 @@ describe('Wallet tests', () => { try { await fixtureWallet.toV3('testtest', { kdf: 'superkey' }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes('Unsupported kdf'), 'should fail for unsupported kdf') } }, 30000) @@ -326,34 +332,52 @@ describe('Wallet tests', () => { try { await fixtureWallet.toV3(pw, { salt: 'f' }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes(errStr)) } try { await fixtureWallet.toV3(pw, { salt: 'fff' }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes(errStr)) } try { await fixtureWallet.toV3(pw, { salt: 'xfff' }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes(errStr)) } try { await fixtureWallet.toV3(pw, { salt: 'fffx' }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes(errStr)) } try { await fixtureWallet.toV3(pw, { salt: 'fffxff' }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes(errStr)) } try { await fixtureWallet.toV3(pw, { salt: {} as never as undefined }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok( err.message.includes( 'Invalid salt, must be a string (empty or a non-zero even number of hex characters) or Uint8Array', @@ -499,55 +523,85 @@ describe('Wallet tests', () => { try { await fixtureWallet.toV3(pw, { iv: '' }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes(errStrLength)) } try { await fixtureWallet.toV3(pw, { iv: 'ff' }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes(errStrLength)) } try { await fixtureWallet.toV3(pw, { iv: 'ffffffffffffffffffffffffffffffffff' }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes(errStrLength)) } try { await fixtureWallet.toV3(pw, { iv: 'xfffffffffffffffffffffffffffffff' }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes(errStrLength)) } try { await fixtureWallet.toV3(pw, { iv: 'fffffffffffffffffffffffffffffffx' }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes(errStrLength)) } try { await fixtureWallet.toV3(pw, { iv: 'fffffffffffffffxffffffffffffffff' }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes(errStrLength)) } try { await fixtureWallet.toV3(pw, { iv: hexToBytes('0x') }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes(errBuffLength)) } try { await fixtureWallet.toV3(pw, { iv: hexToBytes('0xff') }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes(errBuffLength)) } try { await fixtureWallet.toV3(pw, { iv: hexToBytes('0xffffffffffffffffffffffffffffffffff'), }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes(errBuffLength)) } try { await fixtureWallet.toV3(pw, { iv: {} as never as any }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok( err.message.includes( 'Invalid iv, must be a string (32 hex characters) or Uint8Array (16 bytes)', @@ -562,54 +616,84 @@ describe('Wallet tests', () => { try { await fixtureWallet.toV3(pw, { uuid: '' }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes(errStrLength)) } try { await fixtureWallet.toV3(pw, { uuid: 'ff' }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes(errStrLength)) } try { await fixtureWallet.toV3(pw, { uuid: 'ffffffffffffffffffffffffffffffffff' }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes(errStrLength)) } try { await fixtureWallet.toV3(pw, { uuid: 'xfffffffffffffffffffffffffffffff' }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes(errStrLength)) } try { await fixtureWallet.toV3(pw, { uuid: 'fffffffffffffffffffffffffffffffx' }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes(errStrLength)) } try { await fixtureWallet.toV3(pw, { uuid: 'fffffffffffffffxffffffffffffffff' }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes(errStrLength)) } try { await fixtureWallet.toV3(pw, { uuid: hexToBytes('0x') }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes(errBuffLength)) } try { await fixtureWallet.toV3(pw, { uuid: hexToBytes('0xff') }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes(errBuffLength)) } try { await fixtureWallet.toV3(pw, { uuid: hexToBytes('0xffffffffffffffffffffffffffffffffff'), }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes(errBuffLength)) } try { await fixtureWallet.toV3(pw, { uuid: {} as never as any }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok( err.message.includes( 'Invalid uuid, must be a string (32 hex characters) or Uint8Array (16 bytes)', @@ -727,7 +811,10 @@ describe('Wallet tests', () => { '{"crypto":{"cipher":"aes-128-ctr","cipherparams":{"iv":"6087dab2f9fdbbfaddc31a909735c1e6"},"ciphertext":"5318b4d5bcd28de64ee5559e671353e16f075ecae9f99c7a79a38af5f869aa46","kdf":"pbkdf2","kdfparams":{"c":262144,"dklen":32,"prf":"hmac-sha256","salt":"ae3cd4e7013836a3df6bd7241b12db061dbe2c6785853cce422d148a624ce0bd"},"mac":"517ead924a9d0dc3124507e3393d175ce3ff7c1e96529c6c555ce9e51205e9b2"},"id":"3198bc9c-6672-5ab3-d995-4942343ae5b6","version":3}' try { await Wallet.fromV3(w, 'wrongtestpassword') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes('Key derivation failed - possibly wrong passphrase')) } }, 30000) @@ -744,7 +831,10 @@ describe('Wallet tests', () => { try { await Wallet.fromV3(w, 'testpassword') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } // TODO: Determine if specific error message should be checked (different between NodeJS and browser) assert.ok(err !== undefined, 'threw error for broken input in strict mode') } @@ -753,7 +843,10 @@ describe('Wallet tests', () => { const w = '{"version":2}' try { await Wallet.fromV3(w, 'testpassword') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes('Not a V3 wallet')) } }, 30000) @@ -761,7 +854,10 @@ describe('Wallet tests', () => { const w = '{"crypto":{"kdf":"superkey"},"version":3}' try { await Wallet.fromV3(w, 'testpassword') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes('Unsupported key derivation scheme')) } }, 30000) @@ -769,7 +865,10 @@ describe('Wallet tests', () => { const w = '{"crypto":{"kdf":"pbkdf2","kdfparams":{"prf":"invalid"}},"version":3}' try { await Wallet.fromV3(w, 'testpassword') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes('Unsupported parameters to PBKDF2')) } }, 30000) From 92b33d172ae83194459e5b769546b87ca0d127d1 Mon Sep 17 00:00:00 2001 From: ScottyPoi Date: Tue, 24 Sep 2024 13:45:51 -0600 Subject: [PATCH 14/21] tx: replace (e: any) pattern with Error type check --- packages/tx/src/baseTransaction.ts | 20 +++++++-- packages/tx/src/capabilities/legacy.ts | 5 ++- packages/tx/test/base.spec.ts | 45 ++++++++++++++++----- packages/tx/test/eip4844.spec.ts | 15 +++++-- packages/tx/test/fromRpc.spec.ts | 5 ++- packages/tx/test/inputValue.spec.ts | 5 ++- packages/tx/test/transactionRunner.spec.ts | 5 ++- packages/tx/test/typedTxsAndEIP2930.spec.ts | 20 +++++++-- 8 files changed, 96 insertions(+), 24 deletions(-) diff --git a/packages/tx/src/baseTransaction.ts b/packages/tx/src/baseTransaction.ts index 0f1b469f00..9cf96104f1 100644 --- a/packages/tx/src/baseTransaction.ts +++ b/packages/tx/src/baseTransaction.ts @@ -280,7 +280,10 @@ export abstract class BaseTransaction // Main signature verification is done in `getSenderPublicKey()` const publicKey = this.getSenderPublicKey() return unpadBytes(publicKey).length !== 0 - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } return false } } @@ -451,19 +454,28 @@ export abstract class BaseTransaction let hash = '' try { hash = this.isSigned() ? bytesToHex(this.hash()) : 'not available (unsigned)' - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } hash = 'error' } let isSigned = '' try { isSigned = this.isSigned().toString() - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } hash = 'error' } let hf = '' try { hf = this.common.hardfork() - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } hf = 'error' } diff --git a/packages/tx/src/capabilities/legacy.ts b/packages/tx/src/capabilities/legacy.ts index 34ebd741dc..ee95e39712 100644 --- a/packages/tx/src/capabilities/legacy.ts +++ b/packages/tx/src/capabilities/legacy.ts @@ -96,7 +96,10 @@ export function getSenderPublicKey(tx: LegacyTxInterface): Uint8Array { tx.cache.senderPubKey = sender } return sender - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } const msg = errorMsg(tx, 'Invalid Signature') throw new Error(msg) } diff --git a/packages/tx/test/base.spec.ts b/packages/tx/test/base.spec.ts index a2117f10e5..a30042fbf5 100644 --- a/packages/tx/test/base.spec.ts +++ b/packages/tx/test/base.spec.ts @@ -190,7 +190,10 @@ describe('[BaseTransaction]', () => { try { createLegacyTxFromBytesArray(rlpData) assert.fail('should have thrown when nonce has leading zeroes') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok( err.message.includes('nonce cannot have leading zeroes'), 'should throw with nonce with leading zeroes', @@ -201,7 +204,10 @@ describe('[BaseTransaction]', () => { try { createLegacyTxFromBytesArray(rlpData) assert.fail('should have thrown when v has leading zeroes') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok( err.message.includes('v cannot have leading zeroes'), 'should throw with v with leading zeroes', @@ -212,7 +218,10 @@ describe('[BaseTransaction]', () => { try { createAccessList2930TxFromBytesArray(rlpData) assert.fail('should have thrown when gasLimit has leading zeroes') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok( err.message.includes('gasLimit cannot have leading zeroes'), 'should throw with gasLimit with leading zeroes', @@ -223,7 +232,10 @@ describe('[BaseTransaction]', () => { try { create1559FeeMarketTxFromBytesArray(rlpData) assert.fail('should have thrown when maxPriorityFeePerGas has leading zeroes') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok( err.message.includes('maxPriorityFeePerGas cannot have leading zeroes'), 'should throw with maxPriorityFeePerGas with leading zeroes', @@ -438,7 +450,10 @@ describe('[BaseTransaction]', () => { const tx = createFeeMarket1559Tx(eip1559Txs[0]) try { ;(tx as any)._validateCannotExceedMaxInteger({ a: MAX_INTEGER }, 256, true) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok( err.message.includes('equal or exceed MAX_INTEGER'), 'throws when value equals or exceeds MAX_INTEGER', @@ -446,12 +461,18 @@ describe('[BaseTransaction]', () => { } try { ;(tx as any)._validateCannotExceedMaxInteger({ a: MAX_INTEGER + BigInt(1) }, 256, false) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes('exceed MAX_INTEGER'), 'throws when value exceeds MAX_INTEGER') } try { ;(tx as any)._validateCannotExceedMaxInteger({ a: BigInt(0) }, 100, false) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok( err.message.includes('unimplemented bits value'), 'throws when bits value other than 64 or 256 provided', @@ -459,12 +480,18 @@ describe('[BaseTransaction]', () => { } try { ;(tx as any)._validateCannotExceedMaxInteger({ a: MAX_UINT64 + BigInt(1) }, 64, false) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes('2^64'), 'throws when 64 bit integer exceeds MAX_UINT64') } try { ;(tx as any)._validateCannotExceedMaxInteger({ a: MAX_UINT64 }, 64, true) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok( err.message.includes('2^64'), 'throws when 64 bit integer equals or exceeds MAX_UINT64', diff --git a/packages/tx/test/eip4844.spec.ts b/packages/tx/test/eip4844.spec.ts index cf0e895941..a152c70eb7 100644 --- a/packages/tx/test/eip4844.spec.ts +++ b/packages/tx/test/eip4844.spec.ts @@ -227,7 +227,10 @@ describe('EIP4844 constructor tests - invalid scenarios', () => { } try { createBlob4844Tx({ ...baseTxData, ...shortVersionHash }, { common }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok( err.message.includes('versioned hash is invalid length'), 'throws on invalid versioned hash length', @@ -235,7 +238,10 @@ describe('EIP4844 constructor tests - invalid scenarios', () => { } try { createBlob4844Tx({ ...baseTxData, ...invalidVersionHash }, { common }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok( err.message.includes('does not start with KZG commitment'), 'throws on invalid commitment version', @@ -243,7 +249,10 @@ describe('EIP4844 constructor tests - invalid scenarios', () => { } try { createBlob4844Tx({ ...baseTxData, ...tooManyBlobs }, { common }) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok( err.message.includes('tx can contain at most'), 'throws on too many versioned hashes', diff --git a/packages/tx/test/fromRpc.spec.ts b/packages/tx/test/fromRpc.spec.ts index df6f7b37d9..935980e683 100644 --- a/packages/tx/test/fromRpc.spec.ts +++ b/packages/tx/test/fromRpc.spec.ts @@ -61,7 +61,10 @@ describe('[fromJSONRPCProvider]', () => { try { await createTxFromJSONRPCProvider(provider, bytesToHex(randomBytes(32)), {}) assert.fail('should throw') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok( err.message.includes('No data returned from provider'), 'throws correct error when no tx returned', diff --git a/packages/tx/test/inputValue.spec.ts b/packages/tx/test/inputValue.spec.ts index e281fcf3dd..21e80363f8 100644 --- a/packages/tx/test/inputValue.spec.ts +++ b/packages/tx/test/inputValue.spec.ts @@ -224,7 +224,10 @@ describe('[Invalid Access Lists]', () => { tx = tx.sign(hexToBytes(`0x${'42'.repeat(32)}`)) } assert.fail('did not fail on `fromTxData`') - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok(true, 'failed ok on decoding in `fromTxData`') tx = createTx({ type: txType }) if (signed) { diff --git a/packages/tx/test/transactionRunner.spec.ts b/packages/tx/test/transactionRunner.spec.ts index 7941133744..ebbb16a5f0 100644 --- a/packages/tx/test/transactionRunner.spec.ts +++ b/packages/tx/test/transactionRunner.spec.ts @@ -86,7 +86,10 @@ describe('TransactionTests', async () => { `Transaction should be valid on ${forkName}`, ) } - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } if (shouldBeInvalid) { assert.ok(shouldBeInvalid, `Transaction should be invalid on ${forkName}`) } else { diff --git a/packages/tx/test/typedTxsAndEIP2930.spec.ts b/packages/tx/test/typedTxsAndEIP2930.spec.ts index 968bac39c2..1e73cc7349 100644 --- a/packages/tx/test/typedTxsAndEIP2930.spec.ts +++ b/packages/tx/test/typedTxsAndEIP2930.spec.ts @@ -162,7 +162,10 @@ describe('[AccessList2930Transaction / FeeMarket1559Tx] -> EIP-2930 Compatibilit for (const txType of txTypes) { try { txType.create.rlp(new Uint8Array([99]), {}) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.message.includes('wrong tx type'), `should throw on wrong tx type (${txType.name})`, @@ -173,7 +176,10 @@ describe('[AccessList2930Transaction / FeeMarket1559Tx] -> EIP-2930 Compatibilit // Correct tx type + RLP-encoded 5 const serialized = concatBytes(new Uint8Array([txType.type]), new Uint8Array([5])) txType.create.rlp(serialized, {}) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.message.includes('must be array'), `should throw when RLP payload not an array (${txType.name})`, @@ -184,7 +190,10 @@ describe('[AccessList2930Transaction / FeeMarket1559Tx] -> EIP-2930 Compatibilit // Correct tx type + RLP-encoded empty list const serialized = concatBytes(new Uint8Array([txType.type]), hexToBytes('0xc0')) txType.create.rlp(serialized, {}) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } assert.ok( e.message.includes('values (for unsigned tx)'), `should throw with invalid number of values (${txType.name})`, @@ -449,7 +458,10 @@ describe('[AccessList2930Transaction] -> Class Specific Tests', () => { }, { common }, ) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok( err.message.includes('gasLimit * gasPrice cannot exceed MAX_INTEGER'), 'throws when gasLimit * gasPrice exceeds MAX_INTEGER', From d7807e3e68fca3920bbf3d45b8b54316aee7b7a1 Mon Sep 17 00:00:00 2001 From: ScottyPoi Date: Tue, 24 Sep 2024 13:47:01 -0600 Subject: [PATCH 15/21] util: replace (e: any) pattern with Error type check --- packages/util/src/account.ts | 10 ++++++++-- packages/util/test/account.spec.ts | 10 ++++++++-- packages/util/test/provider.spec.ts | 15 ++++++++++++--- packages/util/test/signature.spec.ts | 5 ++++- 4 files changed, 32 insertions(+), 8 deletions(-) diff --git a/packages/util/src/account.ts b/packages/util/src/account.ts index a62022e959..ada39c49d8 100644 --- a/packages/util/src/account.ts +++ b/packages/util/src/account.ts @@ -418,7 +418,10 @@ export function createPartialAccountFromRLP(serialized: Uint8Array) { export const isValidAddress = function (hexAddress: string): hexAddress is PrefixedHexString { try { assertIsString(hexAddress) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } return false } @@ -624,7 +627,10 @@ export const zeroAddress = function (): string { export const isZeroAddress = function (hexAddress: string): boolean { try { assertIsString(hexAddress) - } catch (e: any) { + } catch (e) { + if (!(e instanceof Error)) { + e = new Error(e) + } return false } diff --git a/packages/util/test/account.spec.ts b/packages/util/test/account.spec.ts index 0e83962a48..2fc5ccd252 100644 --- a/packages/util/test/account.spec.ts +++ b/packages/util/test/account.spec.ts @@ -319,7 +319,10 @@ describe('Utility Functions', () => { '0x3a443d8381a6798a70c6ff9304bdc8cb0163c23211d11628fae52ef9e0dca11a001cf066d56a8156fc201cd5df8a36ef694eecd258903fca7086c1fae7441e1d' as any try { isValidPublic((pubKey) as Uint8Array) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok( err.message.includes('This method only supports Uint8Array'), 'should throw if input is not Uint8Array', @@ -458,7 +461,10 @@ describe('Utility Functions', () => { privateKey = '0xea54bdc52d163f88c93ab0615782cf718a2efb9e51a7989aab1b08067e9c1c5f' as any try { privateToPublic((privateKey) as Uint8Array) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok( err.message.includes('This method only supports Uint8Array'), 'should throw if private key is not Uint8Array', diff --git a/packages/util/test/provider.spec.ts b/packages/util/test/provider.spec.ts index 5a8eb08f84..1f8a072244 100644 --- a/packages/util/test/provider.spec.ts +++ b/packages/util/test/provider.spec.ts @@ -59,7 +59,10 @@ describe('fetchFromProvider', () => { params: ['0xabcd'], }) assert.fail('should throw') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes('fetch'), 'tried to fetch and failed') } }) @@ -79,7 +82,10 @@ describe('fetchFromProvider', () => { params: ['0xabcd'], }) assert.fail('should throw') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes('ERROR'), 'received a formatted RPC error') assert.ok(err.message.includes('eth_getBalance'), 'error is for correct method') } @@ -101,7 +107,10 @@ describe('fetchFromProvider', () => { params: ['0xabcd'], }) assert.fail('should throw') - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes('Could not parse error'), 'received a formatted RPC error') assert.ok(err.message.includes('eth_getBalance'), 'error is for correct method') } diff --git a/packages/util/test/signature.spec.ts b/packages/util/test/signature.spec.ts index 9a6a65b7ff..cef5441f44 100644 --- a/packages/util/test/signature.spec.ts +++ b/packages/util/test/signature.spec.ts @@ -169,7 +169,10 @@ describe('hashPersonalMessage', () => { it('should throw if input is not a Uint8Array', () => { try { hashPersonalMessage(([0, 1, 2, 3, 4]) as Uint8Array) - } catch (err: any) { + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err) + } assert.ok(err.message.includes('This method only supports Uint8Array')) } }) From 9678ae4a6ef15aa076526f6e5b170c654f705f72 Mon Sep 17 00:00:00 2001 From: ScottyPoi Date: Tue, 24 Sep 2024 13:47:08 -0600 Subject: [PATCH 16/21] verkle: replace (e: any) pattern with Error type check --- packages/verkle/src/verkleTree.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/verkle/src/verkleTree.ts b/packages/verkle/src/verkleTree.ts index d6249d4f6f..7649c91ec0 100644 --- a/packages/verkle/src/verkleTree.ts +++ b/packages/verkle/src/verkleTree.ts @@ -142,7 +142,10 @@ export class VerkleTree { try { const value = await this._db.get(root) return value !== null - } catch (error: any) { + } catch (error) { + if (!(error instanceof Error)) { + error = new Error(error) + } if (error.message === 'Missing node in DB') { return equalsBytes(root, this.EMPTY_TREE_ROOT) } else { From 96d13a9df67949027b74affa61a8fe15ccb433d3 Mon Sep 17 00:00:00 2001 From: ScottyPoi Date: Tue, 24 Sep 2024 14:29:55 -0600 Subject: [PATCH 17/21] fix rule format --- config/eslint.cjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/config/eslint.cjs b/config/eslint.cjs index 4ee5b1ef17..0e370ce840 100644 --- a/config/eslint.cjs +++ b/config/eslint.cjs @@ -56,8 +56,8 @@ module.exports = { 'error', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }, ], - '@typescript-eslint/no-redeclare': '0', - '@typescript-eslint/no-ex-assign': '0', + '@typescript-eslint/no-redeclare': 0, + 'no-ex-assign': 0, '@typescript-eslint/no-unnecessary-condition': 'off', '@typescript-eslint/prefer-nullish-coalescing': 'error', '@typescript-eslint/restrict-plus-operands': 'off', From 48f2d90a0d3719b2006d008d8322afcb67c8ea45 Mon Sep 17 00:00:00 2001 From: ScottyPoi Date: Tue, 24 Sep 2024 15:07:02 -0600 Subject: [PATCH 18/21] evm: revert change for custom error object --- packages/evm/src/interpreter.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/packages/evm/src/interpreter.ts b/packages/evm/src/interpreter.ts index fe47f13ba5..9ca5c607d4 100644 --- a/packages/evm/src/interpreter.ts +++ b/packages/evm/src/interpreter.ts @@ -323,9 +323,6 @@ export class Interpreter { this.performanceLogger.unpauseTimer(overheadTimer) } } catch (e) { - if (!(e instanceof Error)) { - e = new Error(e) - } if (overheadTimer !== undefined) { this.performanceLogger.unpauseTimer(overheadTimer) } From 220d1a23caa62eec239ed7d028205b77cc896437 Mon Sep 17 00:00:00 2001 From: ScottyPoi Date: Tue, 24 Sep 2024 16:24:05 -0600 Subject: [PATCH 19/21] remove pattern where unnecessary --- packages/evm/src/evm.ts | 6 ------ packages/evm/src/precompiles/01-ecrecover.ts | 5 +---- packages/evm/src/precompiles/05-modexp.ts | 5 +---- packages/evm/src/precompiles/06-bn254-add.ts | 3 --- packages/evm/src/precompiles/07-bn254-mul.ts | 3 --- .../evm/src/precompiles/08-bn254-pairing.ts | 3 --- .../evm/src/precompiles/0b-bls12-g1add.ts | 3 --- .../evm/src/precompiles/0c-bls12-g1mul.ts | 3 --- .../evm/src/precompiles/0d-bls12-g1msm.ts | 3 --- .../evm/src/precompiles/0e-bls12-g2add.ts | 3 --- .../evm/src/precompiles/0f-bls12-g2mul.ts | 3 --- .../evm/src/precompiles/10-bls12-g2msm.ts | 3 --- .../evm/src/precompiles/11-bls12-pairing.ts | 3 --- .../src/precompiles/12-bls12-map-fp-to-g1.ts | 3 --- .../src/precompiles/13-bls12-map-fp2-to-g2.ts | 3 --- packages/tx/src/baseTransaction.ts | 20 ++++--------------- packages/tx/src/capabilities/legacy.ts | 5 +---- packages/vm/src/runBlock.ts | 3 --- packages/vm/src/runTx.ts | 3 --- packages/vm/src/vm.ts | 5 +---- packages/vm/test/api/level.ts | 3 --- 21 files changed, 8 insertions(+), 83 deletions(-) diff --git a/packages/evm/src/evm.ts b/packages/evm/src/evm.ts index 73691fccf4..4d32c93fa5 100644 --- a/packages/evm/src/evm.ts +++ b/packages/evm/src/evm.ts @@ -321,9 +321,6 @@ export class EVM implements EVMInterface { try { await this._addToBalance(toAccount, message) } catch (e) { - if (!(e instanceof Error)) { - e = new Error(e) - } errorMessage = e } } @@ -509,9 +506,6 @@ export class EVM implements EVMInterface { try { await this._addToBalance(toAccount, message as MessageWithTo) } catch (e) { - if (!(e instanceof Error)) { - e = new Error(e) - } errorMessage = e } diff --git a/packages/evm/src/precompiles/01-ecrecover.ts b/packages/evm/src/precompiles/01-ecrecover.ts index 63ac8c2c72..21cc0fe344 100644 --- a/packages/evm/src/precompiles/01-ecrecover.ts +++ b/packages/evm/src/precompiles/01-ecrecover.ts @@ -58,10 +58,7 @@ export function precompile01(opts: PrecompileInput): ExecResult { ) } publicKey = ecrecoverFunction(msgHash, bytesToBigInt(v), r, s) - } catch (e) { - if (!(e instanceof Error)) { - e = new Error(e) - } + } catch { if (opts._debug !== undefined) { opts._debug(`${pName} failed: PK recovery failed`) } diff --git a/packages/evm/src/precompiles/05-modexp.ts b/packages/evm/src/precompiles/05-modexp.ts index 4d32dd5397..5c2a2079b8 100644 --- a/packages/evm/src/precompiles/05-modexp.ts +++ b/packages/evm/src/precompiles/05-modexp.ts @@ -62,10 +62,7 @@ function getAdjustedExponentLength(data: Uint8Array): bigint { try { const baseLen = bytesToBigInt(data.subarray(0, 32)) expBytesStart = 96 + Number(baseLen) // 96 for base length, then exponent length, and modulus length, then baseLen for the base data, then exponent bytes start - } catch (e) { - if (!(e instanceof Error)) { - e = new Error(e) - } + } catch { expBytesStart = Number.MAX_SAFE_INTEGER - 32 } const expLen = bytesToBigInt(data.subarray(32, 64)) diff --git a/packages/evm/src/precompiles/06-bn254-add.ts b/packages/evm/src/precompiles/06-bn254-add.ts index d8a7d2e4c8..86d577bbab 100644 --- a/packages/evm/src/precompiles/06-bn254-add.ts +++ b/packages/evm/src/precompiles/06-bn254-add.ts @@ -25,9 +25,6 @@ export function precompile06(opts: PrecompileInput): ExecResult { try { returnData = (opts._EVM as EVM)['_bn254'].add(input) } catch (e) { - if (!(e instanceof Error)) { - e = new Error(e) - } if (opts._debug !== undefined) { opts._debug(`${pName} failed: ${e.message}`) } diff --git a/packages/evm/src/precompiles/07-bn254-mul.ts b/packages/evm/src/precompiles/07-bn254-mul.ts index d784eafa57..40e572c01b 100644 --- a/packages/evm/src/precompiles/07-bn254-mul.ts +++ b/packages/evm/src/precompiles/07-bn254-mul.ts @@ -25,9 +25,6 @@ export function precompile07(opts: PrecompileInput): ExecResult { try { returnData = (opts._EVM as EVM)['_bn254'].mul(input) } catch (e) { - if (!(e instanceof Error)) { - e = new Error(e) - } if (opts._debug !== undefined) { opts._debug(`${pName} failed: ${e.message}`) } diff --git a/packages/evm/src/precompiles/08-bn254-pairing.ts b/packages/evm/src/precompiles/08-bn254-pairing.ts index 503393618c..19935dc522 100644 --- a/packages/evm/src/precompiles/08-bn254-pairing.ts +++ b/packages/evm/src/precompiles/08-bn254-pairing.ts @@ -29,9 +29,6 @@ export function precompile08(opts: PrecompileInput): ExecResult { try { returnData = (opts._EVM as EVM)['_bn254'].pairing(opts.data) } catch (e) { - if (!(e instanceof Error)) { - e = new Error(e) - } if (opts._debug !== undefined) { opts._debug(`${pName} failed: ${e.message}`) } diff --git a/packages/evm/src/precompiles/0b-bls12-g1add.ts b/packages/evm/src/precompiles/0b-bls12-g1add.ts index cd72390840..90b17ad826 100644 --- a/packages/evm/src/precompiles/0b-bls12-g1add.ts +++ b/packages/evm/src/precompiles/0b-bls12-g1add.ts @@ -40,9 +40,6 @@ export async function precompile0b(opts: PrecompileInput): Promise { try { returnValue = bls.addG1(opts.data) } catch (e) { - if (!(e instanceof Error)) { - e = new Error(e) - } if (opts._debug !== undefined) { opts._debug(`${pName} failed: ${e.message}`) } diff --git a/packages/evm/src/precompiles/0c-bls12-g1mul.ts b/packages/evm/src/precompiles/0c-bls12-g1mul.ts index fa97312485..3b4ae45530 100644 --- a/packages/evm/src/precompiles/0c-bls12-g1mul.ts +++ b/packages/evm/src/precompiles/0c-bls12-g1mul.ts @@ -38,9 +38,6 @@ export async function precompile0c(opts: PrecompileInput): Promise { try { returnValue = bls.mulG1(opts.data) } catch (e) { - if (!(e instanceof Error)) { - e = new Error(e) - } if (opts._debug !== undefined) { opts._debug(`${pName} failed: ${e.message}`) } diff --git a/packages/evm/src/precompiles/0d-bls12-g1msm.ts b/packages/evm/src/precompiles/0d-bls12-g1msm.ts index c84e0c4626..68c9c7ae10 100644 --- a/packages/evm/src/precompiles/0d-bls12-g1msm.ts +++ b/packages/evm/src/precompiles/0d-bls12-g1msm.ts @@ -63,9 +63,6 @@ export async function precompile0d(opts: PrecompileInput): Promise { try { returnValue = bls.msmG1(opts.data) } catch (e) { - if (!(e instanceof Error)) { - e = new Error(e) - } if (opts._debug !== undefined) { opts._debug(`${pName} failed: ${e.message}`) } diff --git a/packages/evm/src/precompiles/0e-bls12-g2add.ts b/packages/evm/src/precompiles/0e-bls12-g2add.ts index 600534676c..6e150adb00 100644 --- a/packages/evm/src/precompiles/0e-bls12-g2add.ts +++ b/packages/evm/src/precompiles/0e-bls12-g2add.ts @@ -46,9 +46,6 @@ export async function precompile0e(opts: PrecompileInput): Promise { try { returnValue = bls.addG2(opts.data) } catch (e) { - if (!(e instanceof Error)) { - e = new Error(e) - } return EvmErrorResult(e, opts.gasLimit) } diff --git a/packages/evm/src/precompiles/0f-bls12-g2mul.ts b/packages/evm/src/precompiles/0f-bls12-g2mul.ts index 949846d806..d9735b5c20 100644 --- a/packages/evm/src/precompiles/0f-bls12-g2mul.ts +++ b/packages/evm/src/precompiles/0f-bls12-g2mul.ts @@ -42,9 +42,6 @@ export async function precompile0f(opts: PrecompileInput): Promise { try { returnValue = bls.mulG2(opts.data) } catch (e) { - if (!(e instanceof Error)) { - e = new Error(e) - } if (opts._debug !== undefined) { opts._debug(`${pName} failed: ${e.message}`) } diff --git a/packages/evm/src/precompiles/10-bls12-g2msm.ts b/packages/evm/src/precompiles/10-bls12-g2msm.ts index 7688778dc2..0d42c42c4e 100644 --- a/packages/evm/src/precompiles/10-bls12-g2msm.ts +++ b/packages/evm/src/precompiles/10-bls12-g2msm.ts @@ -54,9 +54,6 @@ export async function precompile10(opts: PrecompileInput): Promise { try { returnValue = bls.msmG2(opts.data) } catch (e) { - if (!(e instanceof Error)) { - e = new Error(e) - } if (opts._debug !== undefined) { opts._debug(`${pName} failed: ${e.message}`) } diff --git a/packages/evm/src/precompiles/11-bls12-pairing.ts b/packages/evm/src/precompiles/11-bls12-pairing.ts index 70c04d5e5d..7eaacd7829 100644 --- a/packages/evm/src/precompiles/11-bls12-pairing.ts +++ b/packages/evm/src/precompiles/11-bls12-pairing.ts @@ -60,9 +60,6 @@ export async function precompile11(opts: PrecompileInput): Promise { try { returnValue = bls.pairingCheck(opts.data) } catch (e) { - if (!(e instanceof Error)) { - e = new Error(e) - } if (opts._debug !== undefined) { opts._debug(`${pName} failed: ${e.message}`) } diff --git a/packages/evm/src/precompiles/12-bls12-map-fp-to-g1.ts b/packages/evm/src/precompiles/12-bls12-map-fp-to-g1.ts index 8ef220c8e9..1d5812caa8 100644 --- a/packages/evm/src/precompiles/12-bls12-map-fp-to-g1.ts +++ b/packages/evm/src/precompiles/12-bls12-map-fp-to-g1.ts @@ -35,9 +35,6 @@ export async function precompile12(opts: PrecompileInput): Promise { try { returnValue = bls.mapFPtoG1(opts.data) } catch (e) { - if (!(e instanceof Error)) { - e = new Error(e) - } if (opts._debug !== undefined) { opts._debug(`${pName} failed: ${e.message}`) } diff --git a/packages/evm/src/precompiles/13-bls12-map-fp2-to-g2.ts b/packages/evm/src/precompiles/13-bls12-map-fp2-to-g2.ts index 9b7c121025..243e226384 100644 --- a/packages/evm/src/precompiles/13-bls12-map-fp2-to-g2.ts +++ b/packages/evm/src/precompiles/13-bls12-map-fp2-to-g2.ts @@ -38,9 +38,6 @@ export async function precompile13(opts: PrecompileInput): Promise { try { returnValue = bls.mapFP2toG2(opts.data) } catch (e) { - if (!(e instanceof Error)) { - e = new Error(e) - } if (opts._debug !== undefined) { opts._debug(`${pName} failed: ${e.message}`) } diff --git a/packages/tx/src/baseTransaction.ts b/packages/tx/src/baseTransaction.ts index 9cf96104f1..6fa99b1cf1 100644 --- a/packages/tx/src/baseTransaction.ts +++ b/packages/tx/src/baseTransaction.ts @@ -280,10 +280,7 @@ export abstract class BaseTransaction // Main signature verification is done in `getSenderPublicKey()` const publicKey = this.getSenderPublicKey() return unpadBytes(publicKey).length !== 0 - } catch (e) { - if (!(e instanceof Error)) { - e = new Error(e) - } + } catch { return false } } @@ -454,28 +451,19 @@ export abstract class BaseTransaction let hash = '' try { hash = this.isSigned() ? bytesToHex(this.hash()) : 'not available (unsigned)' - } catch (e) { - if (!(e instanceof Error)) { - e = new Error(e) - } + } catch { hash = 'error' } let isSigned = '' try { isSigned = this.isSigned().toString() - } catch (e) { - if (!(e instanceof Error)) { - e = new Error(e) - } + } catch { hash = 'error' } let hf = '' try { hf = this.common.hardfork() - } catch (e) { - if (!(e instanceof Error)) { - e = new Error(e) - } + } catch { hf = 'error' } diff --git a/packages/tx/src/capabilities/legacy.ts b/packages/tx/src/capabilities/legacy.ts index ee95e39712..13423ef8d6 100644 --- a/packages/tx/src/capabilities/legacy.ts +++ b/packages/tx/src/capabilities/legacy.ts @@ -96,10 +96,7 @@ export function getSenderPublicKey(tx: LegacyTxInterface): Uint8Array { tx.cache.senderPubKey = sender } return sender - } catch (e) { - if (!(e instanceof Error)) { - e = new Error(e) - } + } catch { const msg = errorMsg(tx, 'Invalid Signature') throw new Error(msg) } diff --git a/packages/vm/src/runBlock.ts b/packages/vm/src/runBlock.ts index e087308ee0..ceb1e93c1e 100644 --- a/packages/vm/src/runBlock.ts +++ b/packages/vm/src/runBlock.ts @@ -201,9 +201,6 @@ export async function runBlock(vm: VM, opts: RunBlockOpts): Promise { } return result } catch (e) { - if (!(e instanceof Error)) { - e = new Error(e) - } await vm.evm.journal.revert() if (vm.DEBUG) { debug(`tx checkpoint reverted`) diff --git a/packages/vm/src/vm.ts b/packages/vm/src/vm.ts index 8eaa1b9033..7c6f2634b6 100644 --- a/packages/vm/src/vm.ts +++ b/packages/vm/src/vm.ts @@ -127,10 +127,7 @@ export class VM { let hf = '' try { hf = this.common.hardfork() - } catch (e) { - if (!(e instanceof Error)) { - e = new Error(e) - } + } catch { hf = 'error' } const errorStr = `vm hf=${hf}` diff --git a/packages/vm/test/api/level.ts b/packages/vm/test/api/level.ts index 1457f3abdf..74d395e38f 100644 --- a/packages/vm/test/api/level.ts +++ b/packages/vm/test/api/level.ts @@ -33,9 +33,6 @@ export class LevelDB implements DB { value = await this._leveldb.get(key, ENCODING_OPTS) if (value === null) return undefined } catch (error) { - if (!(error instanceof Error)) { - error = new Error(error) - } // https://github.com/Level/abstract-level/blob/915ad1317694d0ce8c580b5ab85d81e1e78a3137/abstract-level.js#L309 // This should be `true` if the error came from LevelDB // so we can check for `NOT true` to identify any non-404 errors From 2a18d4f705ed184687a270e78705b5c521a3b1ad Mon Sep 17 00:00:00 2001 From: ScottyPoi Date: Tue, 24 Sep 2024 17:07:32 -0600 Subject: [PATCH 20/21] revert change to helper function --- packages/client/src/rpc/helpers.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/packages/client/src/rpc/helpers.ts b/packages/client/src/rpc/helpers.ts index b13b49553a..af885f86f5 100644 --- a/packages/client/src/rpc/helpers.ts +++ b/packages/client/src/rpc/helpers.ts @@ -19,9 +19,6 @@ export function callWithStackTrace(handler: Function, debug: boolean) { const res = await handler(...args) return res } catch (error) { - if (!(error instanceof Error)) { - error = new Error(error) - } const e: RPCError = { code: error.code ?? INTERNAL_ERROR, message: error.message, From f9048e076780a5b3030e8a530f28d4d16e8ee2e4 Mon Sep 17 00:00:00 2001 From: ScottyPoi Date: Tue, 24 Sep 2024 18:00:56 -0600 Subject: [PATCH 21/21] client: revert where unnecessary --- packages/client/bin/cli.ts | 5 +---- packages/client/src/execution/level.ts | 3 --- packages/client/src/miner/pendingBlock.ts | 2 +- packages/client/src/net/peer/rlpxpeer.ts | 3 --- packages/client/src/net/protocol/boundprotocol.ts | 6 ------ packages/client/src/net/protocol/rlpxsender.ts | 6 ------ packages/client/src/rpc/modules/debug.ts | 5 +---- packages/client/src/rpc/modules/engine/engine.ts | 13 ++----------- .../client/src/rpc/modules/engine/util/generic.ts | 5 +---- packages/client/src/rpc/modules/eth.ts | 5 +---- packages/client/src/service/skeleton.ts | 10 ++-------- 11 files changed, 9 insertions(+), 54 deletions(-) diff --git a/packages/client/bin/cli.ts b/packages/client/bin/cli.ts index af84384ee9..c59d3c10e0 100755 --- a/packages/client/bin/cli.ts +++ b/packages/client/bin/cli.ts @@ -554,10 +554,7 @@ async function executeBlocks(client: EthereumClient) { if ((blockRange[0][1] as string[]).length > 0 && blockRange.length === 2) { throw new Error('wrong input') } - } catch (e) { - if (!(e instanceof Error)) { - e = new Error(e) - } + } catch { client.config.logger.error( 'Wrong input format for block execution, allowed format types: 5, 5-10, 5[0xba4b5fd92a26badad3cad22eb6f7c7e745053739b5f5d1e8a3afb00f8fb2a280,[TX_HASH_2],...], 5[*] (all txs in verbose mode)', ) diff --git a/packages/client/src/execution/level.ts b/packages/client/src/execution/level.ts index bbdd004b67..d3d537eaa0 100644 --- a/packages/client/src/execution/level.ts +++ b/packages/client/src/execution/level.ts @@ -68,9 +68,6 @@ export class LevelDB< value = await this._leveldb.get(key, encodings) if (value === null) return undefined } catch (error) { - if (!(error instanceof Error)) { - error = new Error(error) - } // https://github.com/Level/abstract-level/blob/915ad1317694d0ce8c580b5ab85d81e1e78a3137/abstract-level.js#L309 // This should be `true` if the error came from LevelDB // so we can check for `NOT true` to identify any non-404 errors diff --git a/packages/client/src/miner/pendingBlock.ts b/packages/client/src/miner/pendingBlock.ts index 3544e67592..35571e08d3 100644 --- a/packages/client/src/miner/pendingBlock.ts +++ b/packages/client/src/miner/pendingBlock.ts @@ -359,7 +359,7 @@ export class PendingBlock { } else { addTxResult = AddTxResult.SkippedByGasLimit } - } else if ((error as Error).message.includes('blobs missing')) { + } else if (error.message.includes('blobs missing') === true) { // Remove the blob tx which doesn't has blobs bundled this.txPool.removeByHash(bytesToHex(tx.hash()), tx) this.config.logger.error( diff --git a/packages/client/src/net/peer/rlpxpeer.ts b/packages/client/src/net/peer/rlpxpeer.ts index b07745f2b6..911dc14210 100644 --- a/packages/client/src/net/peer/rlpxpeer.ts +++ b/packages/client/src/net/peer/rlpxpeer.ts @@ -126,9 +126,6 @@ export class RlpxPeer extends Peer { await this.bindProtocols(rlpxPeer) this.config.events.emit(Event.PEER_CONNECTED, this) } catch (error) { - if (!(error instanceof Error)) { - error = new Error(error) - } this.config.events.emit(Event.PEER_ERROR, error, this) } } diff --git a/packages/client/src/net/protocol/boundprotocol.ts b/packages/client/src/net/protocol/boundprotocol.ts index 51d40be58d..c4991bbc44 100644 --- a/packages/client/src/net/protocol/boundprotocol.ts +++ b/packages/client/src/net/protocol/boundprotocol.ts @@ -80,9 +80,6 @@ export class BoundProtocol { } } } catch (error) { - if (!(error instanceof Error)) { - error = new Error(error) - } this.config.events.emit(Event.PROTOCOL_ERROR, error, this.peer) } }) @@ -121,9 +118,6 @@ export class BoundProtocol { try { data = this.protocol.decode(message, incoming.payload) } catch (e) { - if (!(e instanceof Error)) { - e = new Error(e) - } error = new Error(`Could not decode message ${message.name}: ${e}`) } const resolver = this.resolvers.get(incoming.code) diff --git a/packages/client/src/net/protocol/rlpxsender.ts b/packages/client/src/net/protocol/rlpxsender.ts index 9a8ca397d9..6755f8dff9 100644 --- a/packages/client/src/net/protocol/rlpxsender.ts +++ b/packages/client/src/net/protocol/rlpxsender.ts @@ -35,9 +35,6 @@ export class RlpxSender extends Sender { try { this.sender.sendStatus(status) } catch (err) { - if (!(err instanceof Error)) { - err = new Error(err) - } this.emit('error', err) } } @@ -52,9 +49,6 @@ export class RlpxSender extends Sender { //@ts-ignore "type number is not assignable to type never" this.sender.sendMessage(code, data) } catch (err) { - if (!(err instanceof Error)) { - err = new Error(err) - } this.emit('error', err) } } diff --git a/packages/client/src/rpc/modules/debug.ts b/packages/client/src/rpc/modules/debug.ts index 0da7152460..cd2e1298a3 100644 --- a/packages/client/src/rpc/modules/debug.ts +++ b/packages/client/src/rpc/modules/debug.ts @@ -349,10 +349,7 @@ export class Debug { try { // Validator already verified that `blockHash` is properly formatted. block = await this.chain.getBlock(hexToBytes(blockHash)) - } catch (err) { - if (!(err instanceof Error)) { - err = new Error(err) - } + } catch { throw { code: INTERNAL_ERROR, message: 'Could not get requested block hash.', diff --git a/packages/client/src/rpc/modules/engine/engine.ts b/packages/client/src/rpc/modules/engine/engine.ts index 837deccb66..f2898fab2d 100644 --- a/packages/client/src/rpc/modules/engine/engine.ts +++ b/packages/client/src/rpc/modules/engine/engine.ts @@ -447,10 +447,7 @@ export class Engine { if (headBlock.common.isActivatedEIP(4844)) { try { headBlock.validateBlobTransactions(parent.header) - } catch (error) { - if (!(error instanceof Error)) { - error = new Error(error) - } + } catch { const validationError = `Invalid 4844 transactions: ${error}` const latestValidHash = await validHash( hexToBytes(parentHash as PrefixedHexString), @@ -473,10 +470,7 @@ export class Engine { if (!executedParentExists) { throw new Error(`Parent block not yet executed number=${parent.header.number}`) } - } catch (error) { - if (!(error instanceof Error)) { - error = new Error(error) - } + } catch { // Stash the block for a potential forced forkchoice update to it later. this.remoteBlocks.set(bytesToUnprefixedHex(headBlock.hash()), headBlock) @@ -1387,9 +1381,6 @@ export class Engine { ) return executionPayload } catch (error) { - if (!(error instanceof Error)) { - error = new Error(error) - } if (validEngineCodes.includes(error.code)) throw error throw { code: INTERNAL_ERROR, diff --git a/packages/client/src/rpc/modules/engine/util/generic.ts b/packages/client/src/rpc/modules/engine/util/generic.ts index 3f014b4eb7..9ef3345b96 100644 --- a/packages/client/src/rpc/modules/engine/util/generic.ts +++ b/packages/client/src/rpc/modules/engine/util/generic.ts @@ -65,10 +65,7 @@ export const validExecutedChainBlock = async ( // if the block was canonical and executed we would have returned by now return null - } catch (error) { - if (!(error instanceof Error)) { - error = new Error(error) - } + } catch { return null } } diff --git a/packages/client/src/rpc/modules/eth.ts b/packages/client/src/rpc/modules/eth.ts index bf35290161..41fbf16fec 100644 --- a/packages/client/src/rpc/modules/eth.ts +++ b/packages/client/src/rpc/modules/eth.ts @@ -1076,10 +1076,7 @@ export class Eth { if (blockHash !== undefined) { try { from = to = await this._chain.getBlock(hexToBytes(blockHash)) - } catch (error) { - if (!(error instanceof Error)) { - error = new Error(error) - } + } catch { throw { code: INVALID_PARAMS, message: 'unknown blockHash', diff --git a/packages/client/src/service/skeleton.ts b/packages/client/src/service/skeleton.ts index 52ee4d65dd..bde837ade6 100644 --- a/packages/client/src/service/skeleton.ts +++ b/packages/client/src/service/skeleton.ts @@ -1401,10 +1401,7 @@ export class Skeleton extends MetaDBManager { throw Error(`SkeletonBlock rlp lookup failed for ${number} onlyCanonical=${onlyCanonical}`) } return this.skeletonBlockRlpToBlock(skeletonBlockRlp) - } catch (error) { - if (!(error instanceof Error)) { - error = new Error(error) - } + } catch { // If skeleton is linked, it probably has deleted the block and put it into the chain if (onlyCanonical && !this.status.linked) return undefined // As a fallback, try to get the block from the canonical chain in case it is available there @@ -1477,10 +1474,7 @@ export class Skeleton extends MetaDBManager { await this.delete(DBKey.SkeletonBlockHashToNumber, block.hash()) await this.delete(DBKey.SkeletonUnfinalizedBlockByHash, block.hash()) return true - } catch (error) { - if (!(error instanceof Error)) { - error = new Error(error) - } + } catch { return false } }