Repository navigation
fix(blockvalidation,subtreevalidation): reject forks below a passed checkpoint and keep older-era side blocks out of block assembly #2069
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
Open
icellan
wants to merge
6
commits into
bsv-blockchain:main
Choose a base branch
from
icellan:claude-issue-4940
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
edf46bb
fix(blockvalidation,subtreevalidation): reject forks below a passed c…
icellan 1355a98
docs(changelog): note the checkpoint fork rule and tip-only block ass…
icellan 1b29e02
fix(subtreevalidation): feed block assembly by script era, not by tip…
icellan dfe6305
Merge remote-tracking branch 'origin/main' into claude-pr-2069
icellan eadef14
fix(blockvalidation,subtreevalidation): take the block assembly era f…
icellan d81af66
fix(blockvalidation): re-check the checkpoint fork rule only before t…
icellan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,142 @@ | ||
| package blockvalidation | ||
|
|
||
| import ( | ||
| "context" | ||
| "sync/atomic" | ||
| "testing" | ||
|
|
||
| subtreepkg "github.com/bsv-blockchain/go-subtree" | ||
| "github.com/bsv-blockchain/teranode/errors" | ||
| "github.com/bsv-blockchain/teranode/model" | ||
| "github.com/bsv-blockchain/teranode/pkg/fileformat" | ||
| "github.com/bsv-blockchain/teranode/services/subtreevalidation" | ||
| "github.com/bsv-blockchain/teranode/ulogger" | ||
| "github.com/bsv-blockchain/teranode/util/test" | ||
| "github.com/stretchr/testify/mock" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| // TestValidateBlock_RejectsForkBelowCheckpoint pins bitcoin-sv's bad-fork-prior-to-checkpoint | ||
| // on the direct (non-catchup) path. A side block below a checkpoint the tip has passed is | ||
| // validated at its own height, so below Genesis or Chronicle it gets the older script rules and | ||
| // its txs can reach block assembly (issue 4940). | ||
| func TestValidateBlock_RejectsForkBelowCheckpoint(t *testing.T) { | ||
| initPrometheusMetrics() | ||
|
|
||
| ctx := context.Background() | ||
|
|
||
| utxoStore, subtreeValidationClient, _, txStore, subtreeStore, cleanup := setup(t) | ||
| defer cleanup() | ||
|
|
||
| countingClient := &countingSubtreeValidationClient{Interface: subtreeValidationClient} | ||
|
|
||
| tSettings := test.CreateBaseTestSettings(t) | ||
| tSettings.BlockValidation.OptimisticMining = false | ||
|
|
||
| // Checkpoint at 1000, block at height 1. | ||
| block, mockBlockchain, _ := belowCheckpointPoWFixture(t, tSettings) | ||
|
|
||
| // The fixture's header deliberately fails its own target; make it pass so the block | ||
| // reaches the checkpoint rules. | ||
| nBits, err := model.NewNBitFromString("207fffff") | ||
| require.NoError(t, err) | ||
| block.Header.Bits = *nBits | ||
| for ok, _, _ := block.Header.HasMetTargetDifficulty(); !ok; ok, _, _ = block.Header.HasMetTargetDifficulty() { | ||
| block.Header.Nonce++ | ||
| } | ||
|
|
||
| // The tip has passed the checkpoint. | ||
| for _, call := range mockBlockchain.ExpectedCalls { | ||
| if call.Method == "GetBestBlockHeader" { | ||
| call.ReturnArguments[1] = &model.BlockHeaderMeta{Height: 1500} | ||
| } | ||
| } | ||
| mockBlockchain.On("GetBlockExists", mock.Anything, block.Header.Hash()).Return(false, nil).Maybe() | ||
| mockBlockchain.On("AddBlock", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil).Maybe() | ||
|
|
||
| bv := NewBlockValidation(ctx, ulogger.TestLogger{}, tSettings, mockBlockchain, subtreeStore, txStore, utxoStore, nil, countingClient) | ||
|
|
||
| err = bv.ValidateBlock(ctx, block, "test") | ||
| require.Error(t, err) | ||
| require.True(t, errors.Is(err, errors.ErrBlockInvalid), "a fork below the checkpoint must surface as BlockInvalid, got: %v", err) | ||
| require.Contains(t, err.Error(), "bad-fork-prior-to-checkpoint") | ||
|
|
||
| require.Equal(t, int32(0), countingClient.checkBlockSubtreesCalls.Load(), | ||
| "a fork below the checkpoint must be rejected before its transactions are validated") | ||
| mockBlockchain.AssertNotCalled(t, "AddBlock", mock.Anything, mock.Anything, mock.Anything, mock.Anything) | ||
| } | ||
|
|
||
| // TestValidateBlock_RejectsForkBelowCheckpointPassedDuringValidation pins the re-check | ||
| // before the block is stored: the tip is below the checkpoint when validation starts and | ||
| // passes it while the block's subtrees are checked, so the block must not be stored. | ||
| func TestValidateBlock_RejectsForkBelowCheckpointPassedDuringValidation(t *testing.T) { | ||
| initPrometheusMetrics() | ||
|
|
||
| ctx := context.Background() | ||
|
|
||
| utxoStore, subtreeValidationClient, _, txStore, subtreeStore, cleanup := setup(t) | ||
| defer cleanup() | ||
|
|
||
| passingClient := &passingSubtreeValidationClient{Interface: subtreeValidationClient} | ||
|
|
||
| tSettings := test.CreateBaseTestSettings(t) | ||
| tSettings.BlockValidation.OptimisticMining = false | ||
|
|
||
| // Checkpoint at 1000, block at height 1. | ||
| block, mockBlockchain, subtree := belowCheckpointPoWFixture(t, tSettings) | ||
|
|
||
| subtreeBytes, err := subtree.Serialize() | ||
| require.NoError(t, err) | ||
| require.NoError(t, subtreeStore.Set(ctx, subtree.RootHash()[:], fileformat.FileTypeSubtree, subtreeBytes)) | ||
|
|
||
| subtreeMetaBytes, err := subtreepkg.NewSubtreeMeta(subtree).Serialize() | ||
| require.NoError(t, err) | ||
| require.NoError(t, subtreeStore.Set(ctx, subtree.RootHash()[:], fileformat.FileTypeSubtreeMeta, subtreeMetaBytes)) | ||
|
|
||
| replicated := subtree.Duplicate() | ||
| replicated.ReplaceRootNode(block.CoinbaseTx.TxIDChainHash(), 0, uint64(block.CoinbaseTx.Size())) //nolint:gosec | ||
| block.Header.HashMerkleRoot = replicated.RootHash() | ||
|
|
||
| nBits, err := model.NewNBitFromString("207fffff") | ||
| require.NoError(t, err) | ||
| block.Header.Bits = *nBits | ||
| for ok, _, _ := block.Header.HasMetTargetDifficulty(); !ok; ok, _, _ = block.Header.HasMetTargetDifficulty() { | ||
| block.Header.Nonce++ | ||
| } | ||
|
|
||
| // The first tip lookup is below the checkpoint, every later one has passed it. | ||
| for _, call := range mockBlockchain.ExpectedCalls { | ||
| if call.Method == "GetBestBlockHeader" { | ||
| call.ReturnArguments[1] = &model.BlockHeaderMeta{Height: 900} | ||
| call.Once() | ||
| } | ||
| } | ||
| mockBlockchain.On("GetBestBlockHeader", mock.Anything).Return(block.Header, &model.BlockHeaderMeta{Height: 1500}, nil) | ||
| mockBlockchain.On("GetNextWorkRequired", mock.Anything, mock.Anything, mock.Anything).Return(nBits, nil).Maybe() | ||
| mockBlockchain.On("GetBlockHeaderIDs", mock.Anything, mock.Anything, mock.Anything).Return([]uint32{0}, nil).Maybe() | ||
| mockBlockchain.On("SetBlockSubtreesSet", mock.Anything, mock.Anything).Return(nil).Maybe() | ||
| mockBlockchain.On("GetBlockHeadersFromHeight", mock.Anything, mock.Anything, mock.Anything). | ||
| Return(nil, nil, errors.NewNotFoundError("no main-chain header")).Maybe() | ||
| mockBlockchain.On("GetBlockExists", mock.Anything, block.Header.Hash()).Return(false, nil).Maybe() | ||
| mockBlockchain.On("AddBlock", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil).Maybe() | ||
|
|
||
| bv := NewBlockValidation(ctx, ulogger.TestLogger{}, tSettings, mockBlockchain, subtreeStore, txStore, utxoStore, nil, passingClient) | ||
|
|
||
| err = bv.ValidateBlock(ctx, block, "test") | ||
| require.Error(t, err) | ||
| require.True(t, errors.Is(err, errors.ErrBlockInvalid), "a fork below the checkpoint must surface as BlockInvalid, got: %v", err) | ||
| require.Contains(t, err.Error(), "bad-fork-prior-to-checkpoint") | ||
| require.Equal(t, int32(1), passingClient.checkBlockSubtreesCalls.Load(), "the block must reach subtree validation before the tip passes the checkpoint") | ||
| mockBlockchain.AssertNotCalled(t, "AddBlock", mock.Anything, mock.Anything, mock.Anything, mock.Anything) | ||
| } | ||
|
|
||
| // passingSubtreeValidationClient reports every block's subtrees valid and counts the calls. | ||
| type passingSubtreeValidationClient struct { | ||
| subtreevalidation.Interface | ||
| checkBlockSubtreesCalls atomic.Int32 | ||
| } | ||
|
|
||
| func (c *passingSubtreeValidationClient) CheckBlockSubtrees(context.Context, *model.Block, string, string) error { | ||
| c.checkBlockSubtreesCalls.Add(1) | ||
| return nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.