Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[API] Snapshot delete operation flag added #2064

Merged
merged 3 commits into from
Dec 25, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
53 changes: 28 additions & 25 deletions blockchain/blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ func NewBlockChain(db database.DBManager, cacheConfig *CacheConfig, chainConfig
if diskRoot != (common.Hash{}) {
logger.Warn("Head state missing, repairing", "number", head.Number(), "hash", head.Hash(), "snaproot", diskRoot)

snapDisk, err := bc.setHeadBeyondRoot(head.NumberU64(), diskRoot, true)
snapDisk, err := bc.setHeadBeyondRoot(head.NumberU64(), diskRoot, true, false)
if err != nil {
return nil, err
}
Expand All @@ -314,7 +314,7 @@ func NewBlockChain(db database.DBManager, cacheConfig *CacheConfig, chainConfig
// Dangling block without a state associated, init from scratch
logger.Warn("Head state missing, repairing chain",
"number", head.NumberU64(), "hash", head.Hash().String())
if _, err := bc.setHeadBeyondRoot(head.NumberU64(), common.Hash{}, true); err != nil {
if _, err := bc.setHeadBeyondRoot(head.NumberU64(), common.Hash{}, true, false); err != nil {
return nil, err
}
}
Expand All @@ -327,7 +327,7 @@ func NewBlockChain(db database.DBManager, cacheConfig *CacheConfig, chainConfig
// make sure the headerByNumber (if present) is in our current canonical chain
if headerByNumber != nil && headerByNumber.Hash() == header.Hash() {
logger.Error("Found bad hash, rewinding chain", "number", header.Number, "hash", header.ParentHash)
bc.SetHead(header.Number.Uint64() - 1)
bc.SetHead(header.Number.Uint64()-1, false)
logger.Error("Chain rewind was successful, resuming normal operation")
}
}
Expand Down Expand Up @@ -424,7 +424,7 @@ func (bc *BlockChain) SetCanonicalBlock(blockNum uint64) {
// Dangling block without a state associated, init from scratch
logger.Warn("Head state missing, repairing chain",
"number", head.NumberU64(), "hash", head.Hash().String())
if _, err := bc.setHeadBeyondRoot(head.NumberU64(), common.Hash{}, true); err != nil {
if _, err := bc.setHeadBeyondRoot(head.NumberU64(), common.Hash{}, true, false); err != nil {
logger.Error("Repairing chain is failed", "number", head.NumberU64(), "hash", head.Hash().String(), "err", err)
return
}
Expand Down Expand Up @@ -513,7 +513,7 @@ func (bc *BlockChain) loadLastState() error {
// SetHead rewinds the local chain to a new head with the extra condition
// that the rewind must pass the specified state root. The method will try to
// delete minimal data from disk whilst retaining chain consistency.
func (bc *BlockChain) SetHead(head uint64) error {
func (bc *BlockChain) SetHead(head uint64, deleteSnapshot bool) error {
// With the live pruning enabled, an attempt to SetHead into a state-pruned block number
// may result in an infinite loop, trying to find the existing block (probably the genesis block).
// If the target `head` is below the surviving block numbers, SetHead early exits with an error.
Expand All @@ -523,7 +523,7 @@ func (bc *BlockChain) SetHead(head uint64) error {
lastPruned, head)
}
}
_, err := bc.setHeadBeyondRoot(head, common.Hash{}, false)
_, err := bc.setHeadBeyondRoot(head, common.Hash{}, false, deleteSnapshot)
return err
}

Expand All @@ -535,7 +535,7 @@ func (bc *BlockChain) SetHead(head uint64) error {
// retaining chain consistency.
//
// The method returns the block number where the requested root cap was found.
func (bc *BlockChain) setHeadBeyondRoot(head uint64, root common.Hash, repair bool) (uint64, error) {
func (bc *BlockChain) setHeadBeyondRoot(head uint64, root common.Hash, repair, deleteSnpashot bool) (uint64, error) {
bc.mu.Lock()
defer bc.mu.Unlock()

Expand Down Expand Up @@ -645,25 +645,28 @@ func (bc *BlockChain) setHeadBeyondRoot(head uint64, root common.Hash, repair bo
}
}

// Delete istanbul snapshot database further two epochs
var (
curBlkNum = bc.CurrentBlock().Number().Uint64()
epoch = bc.Config().Istanbul.Epoch
votingEpoch = curBlkNum - (curBlkNum % epoch)
)
if votingEpoch == 0 {
votingEpoch = 1
}
// Delete the snapshot state beyond the block number of the previous epoch on the right
for i := curBlkNum; i >= votingEpoch; i-- {
if params.IsCheckpointInterval(i) {
// delete from sethead number to previous two epoch block nums
// to handle a block that contains non-empty vote data to make sure
// the `HandleGovernanceVote()` cannot be skipped
bc.db.DeleteIstanbulSnapshot(bc.GetBlockByNumber(i).Hash())
if deleteSnpashot {
ian0371 marked this conversation as resolved.
Show resolved Hide resolved
// Delete istanbul snapshot database further two epochs
// Invoked only if the sethead was originated from explicit API call
var (
curBlkNum = bc.CurrentBlock().Number().Uint64()
epoch = bc.Config().Istanbul.Epoch
votingEpoch = curBlkNum - (curBlkNum % epoch)
)
if votingEpoch == 0 {
votingEpoch = 1
}
// Delete the snapshot state beyond the block number of the previous epoch on the right
for i := curBlkNum; i >= votingEpoch; i-- {
if params.IsCheckpointInterval(i) {
// delete from sethead number to previous two epoch block nums
// to handle a block that contains non-empty vote data to make sure
// the `HandleGovernanceVote()` cannot be skipped
bc.db.DeleteIstanbulSnapshot(bc.GetBlockByNumber(i).Hash())
}
}
logger.Trace("[SetHead] Snapshot database deleted", "from", originLatestBlkNum, "to", votingEpoch)
}
logger.Trace("[SetHead] Snapshot database deleted", "from", originLatestBlkNum, "to", votingEpoch)

// Clear out any stale content from the caches
bc.futureBlocks.Purge()
Expand Down Expand Up @@ -784,7 +787,7 @@ func (bc *BlockChain) Reset() error {
// specified genesis state.
func (bc *BlockChain) ResetWithGenesisBlock(genesis *types.Block) error {
// Dump the entire block chain and purge the caches
if err := bc.SetHead(0); err != nil {
if err := bc.SetHead(0, false); err != nil {
return err
}
bc.mu.Lock()
Expand Down
8 changes: 4 additions & 4 deletions blockchain/blockchain_sethead_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ func testSetHead(t *testing.T, tt *rewindTest) {
}

// Set the head of the chain back to the requested number
chain.SetHead(tt.setheadBlock)
chain.SetHead(tt.setheadBlock, true)

// Iterate over all the remaining blocks and ensure there are no gaps
verifyNoGaps(t, chain, true, canonblocks)
Expand Down Expand Up @@ -301,11 +301,11 @@ func testSetHeadEarlyExit(t *testing.T, tt *rewindTest) {
}

db.WriteLastPrunedBlockNumber(tt.setheadBlock + 1)
assert.Error(t, chain.SetHead(tt.setheadBlock))
assert.Error(t, chain.SetHead(tt.setheadBlock, true))

db.WriteLastPrunedBlockNumber(tt.setheadBlock)
assert.Error(t, chain.SetHead(tt.setheadBlock))
assert.Error(t, chain.SetHead(tt.setheadBlock, true))

db.WriteLastPrunedBlockNumber(tt.setheadBlock - 1)
assert.Nil(t, chain.SetHead(tt.setheadBlock))
assert.Nil(t, chain.SetHead(tt.setheadBlock, true))
}
2 changes: 1 addition & 1 deletion node/cn/api_backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ func (b *CNAPIBackend) CurrentBlock() *types.Block {
}

func doSetHead(bc work.BlockChain, cn consensus.Engine, gov governance.Engine, targetBlkNum uint64) error {
if err := bc.SetHead(targetBlkNum); err != nil {
if err := bc.SetHead(targetBlkNum, true); err != nil {
return err
}
// Initialize snapshot cache, staking info cache, and governance cache
Expand Down
2 changes: 1 addition & 1 deletion node/cn/api_backend_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ func TestCNAPIBackend_SetHead(t *testing.T) {
api.cn.governance = testGov()

number := uint64(123)
mockBlockChain.EXPECT().SetHead(number).Times(1)
mockBlockChain.EXPECT().SetHead(number, true).Times(1)

api.SetHead(number)
block := newBlock(int(number))
Expand Down
2 changes: 1 addition & 1 deletion node/cn/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ func New(ctx *node.ServiceContext, config *Config) (*CN, error) {
// Rewind the chain in case of an incompatible config upgrade.
if compat, ok := genesisErr.(*params.ConfigCompatError); ok {
logger.Error("Rewinding chain to upgrade configuration", "err", compat)
cn.blockchain.SetHead(compat.RewindTo)
cn.blockchain.SetHead(compat.RewindTo, false)
chainDB.WriteChainConfig(genesisHash, cn.chainConfig)
}
cn.bloomIndexer.Start(cn.blockchain)
Expand Down
8 changes: 4 additions & 4 deletions work/mocks/blockchain_mock.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion work/work.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ type BlockChain interface {
StateCache() state.Database

SubscribeChainEvent(ch chan<- blockchain.ChainEvent) event.Subscription
SetHead(head uint64) error
SetHead(head uint64, delteSnapshot bool) error
Stop()

SubscribeRemovedLogsEvent(ch chan<- blockchain.RemovedLogsEvent) event.Subscription
Expand Down