How exactly blockchain node switches to another ch

2019-08-24 21:56发布

AFAIK after block validation node runs all transactions in the block, changing the state (list of UTXOs)

Let's imagine that at some point node realizes that it was on the wrong chain and there is longer chain available, which forked some blocks before.

How does it make the switch? I imagine that it should run all transactions in reverse till the fork happened to restore the state and than replay all transactions in the blocks from the longer chain?

Thanks!

标签: blockchain
2条回答
爷、活的狠高调
2楼-- · 2019-08-24 22:27

I don't know why you have the picture that anything has to be "rolled back". Yes, it's rolling back, but no calculations with transactions have to be done at all. Here's why:

When node A has N+5 blocks and node B has N+2 block, then all node B has to do is drop these additional two blocks and take the 5 new blocks from A.

That's all! Yes, it effectively is rolling back, but nothing has to be run in reverse, because dropping blocks is effectively equivalent to reversing transactions.

Remember that transactions are directed, so they happen only in one direction in time. Meaning: For valid blocks, every non-coinbase transaction in block number N has to have some history in every previous blocks, so block number N is dependent on that history, but the opposite is not true. Previous blocks don't depend on block number N, so dropping N won't invalidate them.

查看更多
做个烂人
3楼-- · 2019-08-24 22:31

Each node receives individual transactions as well as individual blocks from the network. It also keeps the most updated blockchain locally. For every new transaction it receives, the node validates it, and if valid, propagates to its peers. For every block the node receives, it validates it. The validation includes several steps, among which: 1. checking that the block points to the most recent block in the blockchain (it's preceding block) 2. all transactions included in the block are valid.

A fork is a temporary situation, possible when there are 2 valid blocks (or more) which arrive to a node pretty much at the same time, so the node doesn't know which is the right one. It keeps the first one added to it's local blockchain as the main chain, and keeps the second one as a fork chain (also locally), until a next node arrives, and is added to one of the two. When it happens - the longer chain is chosen to be the main blockchain (at that node!), and the second is kept as a side chain. All such side chains are kept in the node's memory for some time, until it can be sure they are not relevant anymore (since they are shorter than the main blockchain by several blocks), and then removed.

查看更多
登录 后发表回答