Identify if a block has been included in the main chain or was forked
This script uses web3.js to evaluate whether a specific block within a blockchain network has been integrated into the main chain or if it was a result of a reorg.
Prerequisites
Prerequisites
You will need a Chainstack account and an EVM-compatible node to follow this recipe.
Environment setup
Environment setup
Install node.js in case it is not installed.
Create a new directory for your project, then install the web3.js library.
npm install web3
Initialize a provider instance
Initialize a provider instance
Create a new file, index.js
, import the web3.js library, and initialize a new provider instance using your Chainstack node URL.
Paste your Chainstack node URL in the NODE_URL
const.
Create the function with the logic
Create the function with the logic
Add a function that takes a block number as a parameter, retrieves the block data using the eth_getBlockByNumber
method, and compares its hash with the parent hash of the next block.
This function returns true
if the block is forked and false
if it is not.
You can remove the console.log
statements from the function and only use its boolean returns.
Call the function
Call the function
Now you can run the function. Add a const
to specify which block to analyze.
Understand the logic
Understand the logic
A block hash is generated through the application of a cryptographic hash function, which takes the block’s data, including transactions and other information, as well as the hash of the parent block (the previous block), and outputs a unique, fixed-length digest. This hash represents the current block within the blockchain.
The script compares the parent hash of the following block with the hash of the block under inspection. If the two values match, it can be concluded that the block was included in the main chain. Conversely, if the values do not match, it indicates that the block was not used to generate the hash of the next block and has therefore been excluded from the main chain, resulting in a forked block.