Skip to main content

Detecting ReOrgs

ReOrgs in Tezos

Any decentralized system has to deal with network issues. A blockchain has to factor in malicious or faulty nodes as well.

Consensus algorithms are, thus, a core characteristic of different blockchains. When a block is added to the blockchain, there is still a possibility that the network will converge on a different content for this block later. After each block is created, this chance will rapidly go down with each subsequent block, but in some of the consensus algorithms (namely, Nakamoto-style consensus algorithms), it will never become exactly zero.

Tezos is now using Tenderbake, which is a great improvement over previous ones in terms of block finality. With Tenderbake, we can expect fewer ReOrgs to happen, and when they do, it should rewrite fewer blocks.

How to detect ReOrgs when using TezGraph

As a user of TezGraph, you might want to be able to detect ReOrgs because data you queried from recent blocks or results of subscription might need to be re-evaluated in case of a ReOrg.

A general solution to detect ReOrgs is to use one of the blockchains' fundamental features: Each block has a hash of the previous block in its header.

So we can subscribe to new blocks, keep a list of recent blocks with their level and hash, and if a block arrives with the same level that we have seen earlier, or if a block's predecessor hash does not match the one we have in the list, we know that a ReOrg has happened.

Let's say you use the following query:

query {
blocks(first: 10) {
edges {
node {
hash
level
}
}
}
}

If the latest block is 2244335, you can then subscribe to blockAdded:

subscription {
blockAdded(replayFromBlockLevel: 2244335) {
header {
predecessor
level
}
hash
}
}

Block levels and hashes from the query and subscription can be added to a list or lookup table. Then if a new block from the subscription has the same level as one of the existing blocks in the list, or its predecessor does not match the one you have in the list, you know a ReOrg has happened.

Reacting to ReOrgs depends on your business logic, but generally, you need to make a new query and go back in your list as long as the hashes do not match. Then you can issue a query to refresh your data for the changed blocks.