Skip to content

Commit

Permalink
Re-add difficulty check for PoS, re-activate removed test
Browse files Browse the repository at this point in the history
  • Loading branch information
holgerd77 committed Jul 17, 2024
1 parent 31e5727 commit ef06f31
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
12 changes: 11 additions & 1 deletion packages/blockchain/src/consensus/casper.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { ConsensusAlgorithm } from '@ethereumjs/common'
import { BIGINT_0 } from '@ethereumjs/util'

import type { Consensus } from '../types.js'
import type { BlockHeader } from '@ethereumjs/block'

/**
* This class encapsulates Casper-related consensus functionality when used with the Blockchain class.
Expand All @@ -18,6 +20,14 @@ export class CasperConsensus implements Consensus {

public async validateConsensus(): Promise<void> {}

public async validateDifficulty(): Promise<void> {}
public async validateDifficulty(header: BlockHeader): Promise<void> {
// TODO: This is not really part of consensus validation and it should be analyzed
// if it is possible to replace by a more generic hardfork check between block and
// blockchain along adding new blocks or headers
if (header.difficulty !== BIGINT_0) {
const msg = 'invalid difficulty. PoS blocks must have difficulty 0'
throw new Error(`${msg} ${header.errorStr()}`)
}
}
public async newBlock(): Promise<void> {}
}
25 changes: 24 additions & 1 deletion packages/blockchain/test/pos.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createBlockFromBlockData } from '@ethereumjs/block'
import { Common, Hardfork } from '@ethereumjs/common'
import { Chain, Common, Hardfork } from '@ethereumjs/common'
import { bytesToHex } from '@ethereumjs/util'
import { assert, describe, it } from 'vitest'

Expand Down Expand Up @@ -88,6 +88,29 @@ describe('Proof of Stake - inserting blocks into blockchain', () => {
BigInt(1313601),
'should have calculated the correct post-Merge total difficulty'
)

const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.London })
const powBlock = createBlockFromBlockData(
{
header: {
number: 16,
difficulty: BigInt(1),
parentHash: latestHeader.hash(),
timestamp: latestHeader.timestamp + BigInt(1),
gasLimit: BigInt(10000),
},
},
{ common }
)
try {
await blockchain.putBlock(powBlock)
assert.fail('should throw when inserting PoW block')
} catch (err: any) {
assert.ok(
err.message.includes('invalid difficulty'),
'should throw with invalid difficulty message'
)
}
})
}
})

0 comments on commit ef06f31

Please sign in to comment.