-
Notifications
You must be signed in to change notification settings - Fork 24
feat: adaptive subtreeData skip during catchup when txs exist locally #539
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
freemans13
wants to merge
3
commits into
bsv-blockchain:main
Choose a base branch
from
freemans13:feat/adaptive-subtreedata-skip-during-catchup
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.
+334
−3
Open
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| package utxocheck | ||
|
|
||
| import ( | ||
| "context" | ||
|
|
||
| "github.com/bsv-blockchain/go-bt/v2/chainhash" | ||
| subtreepkg "github.com/bsv-blockchain/go-subtree" | ||
| "github.com/bsv-blockchain/teranode/stores/utxo" | ||
| "github.com/bsv-blockchain/teranode/stores/utxo/fields" | ||
| ) | ||
|
|
||
| // CheckAllTxsExistInUTXO batch-checks whether all transaction hashes exist in the UTXO store. | ||
| // It processes hashes in batches, skipping coinbase placeholders. | ||
| // Returns false immediately when any tx is missing or still in Creating state. | ||
| // Returns true only when ALL non-coinbase txs exist and are fully created. | ||
| // On UTXO store error, returns (false, err) so callers can fall back to subtreeData. | ||
| func CheckAllTxsExistInUTXO(ctx context.Context, utxoStore utxo.Store, txHashes []chainhash.Hash, batchSize int) (bool, error) { | ||
| if len(txHashes) == 0 { | ||
| return true, nil | ||
| } | ||
|
|
||
| if batchSize <= 0 { | ||
| batchSize = 1000 | ||
| } | ||
|
|
||
| for i := 0; i < len(txHashes); i += batchSize { | ||
| end := i + batchSize | ||
| if end > len(txHashes) { | ||
| end = len(txHashes) | ||
| } | ||
|
|
||
| batch := make([]*utxo.UnresolvedMetaData, 0, end-i) | ||
| for j := i; j < end; j++ { | ||
| if txHashes[j].Equal(subtreepkg.CoinbasePlaceholderHashValue) { | ||
| continue | ||
| } | ||
| batch = append(batch, &utxo.UnresolvedMetaData{ | ||
| Hash: txHashes[j], | ||
| Idx: j, | ||
| }) | ||
| } | ||
|
|
||
| if len(batch) == 0 { | ||
| continue | ||
| } | ||
|
|
||
| if err := utxoStore.BatchDecorate(ctx, batch, fields.Creating); err != nil { | ||
| return false, err | ||
| } | ||
|
|
||
| for _, item := range batch { | ||
| if item.Err != nil || item.Data == nil || item.Data.Creating { | ||
| return false, nil | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return true, 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,164 @@ | ||
| package utxocheck | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "testing" | ||
|
|
||
| "github.com/bsv-blockchain/go-bt/v2/chainhash" | ||
| subtreepkg "github.com/bsv-blockchain/go-subtree" | ||
| "github.com/bsv-blockchain/teranode/stores/utxo" | ||
| "github.com/bsv-blockchain/teranode/stores/utxo/meta" | ||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/mock" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestCheckAllTxsExistInUTXO(t *testing.T) { | ||
| ctx := context.Background() | ||
|
|
||
| makeHash := func(i int) chainhash.Hash { | ||
| var h chainhash.Hash | ||
| copy(h[:], fmt.Sprintf("tx%032d", i)) | ||
| return h | ||
| } | ||
|
|
||
| t.Run("empty hashes returns true", func(t *testing.T) { | ||
| mockStore := &utxo.MockUtxostore{} | ||
| result, err := CheckAllTxsExistInUTXO(ctx, mockStore, nil, 1000) | ||
| require.NoError(t, err) | ||
| assert.True(t, result) | ||
| }) | ||
|
|
||
| t.Run("all txs exist returns true", func(t *testing.T) { | ||
| mockStore := &utxo.MockUtxostore{} | ||
| hashes := []chainhash.Hash{makeHash(1), makeHash(2), makeHash(3)} | ||
|
|
||
| mockStore.On("BatchDecorate", mock.Anything, mock.Anything, mock.Anything). | ||
| Run(func(args mock.Arguments) { | ||
| batch := args.Get(1).([]*utxo.UnresolvedMetaData) | ||
| for _, item := range batch { | ||
| item.Data = &meta.Data{Creating: false} | ||
| } | ||
| }). | ||
| Return(nil) | ||
|
|
||
| result, err := CheckAllTxsExistInUTXO(ctx, mockStore, hashes, 1000) | ||
| require.NoError(t, err) | ||
| assert.True(t, result) | ||
| }) | ||
|
|
||
| t.Run("missing tx returns false", func(t *testing.T) { | ||
| mockStore := &utxo.MockUtxostore{} | ||
| hashes := []chainhash.Hash{makeHash(1), makeHash(2), makeHash(3)} | ||
|
|
||
| mockStore.On("BatchDecorate", mock.Anything, mock.Anything, mock.Anything). | ||
| Run(func(args mock.Arguments) { | ||
| batch := args.Get(1).([]*utxo.UnresolvedMetaData) | ||
| batch[0].Data = &meta.Data{Creating: false} | ||
| // batch[1] left nil — missing tx | ||
| }). | ||
| Return(nil) | ||
|
|
||
| result, err := CheckAllTxsExistInUTXO(ctx, mockStore, hashes, 1000) | ||
| require.NoError(t, err) | ||
| assert.False(t, result) | ||
| }) | ||
|
|
||
| t.Run("creating tx returns false", func(t *testing.T) { | ||
| mockStore := &utxo.MockUtxostore{} | ||
| hashes := []chainhash.Hash{makeHash(1)} | ||
|
|
||
| mockStore.On("BatchDecorate", mock.Anything, mock.Anything, mock.Anything). | ||
| Run(func(args mock.Arguments) { | ||
| batch := args.Get(1).([]*utxo.UnresolvedMetaData) | ||
| batch[0].Data = &meta.Data{Creating: true} | ||
| }). | ||
| Return(nil) | ||
|
|
||
| result, err := CheckAllTxsExistInUTXO(ctx, mockStore, hashes, 1000) | ||
| require.NoError(t, err) | ||
| assert.False(t, result) | ||
| }) | ||
|
|
||
| t.Run("BatchDecorate error returns false with error", func(t *testing.T) { | ||
| mockStore := &utxo.MockUtxostore{} | ||
| hashes := []chainhash.Hash{makeHash(1)} | ||
|
|
||
| mockStore.On("BatchDecorate", mock.Anything, mock.Anything, mock.Anything). | ||
| Return(fmt.Errorf("store error")) | ||
|
|
||
| result, err := CheckAllTxsExistInUTXO(ctx, mockStore, hashes, 1000) | ||
| require.Error(t, err) | ||
| assert.False(t, result) | ||
| }) | ||
|
|
||
| t.Run("coinbase placeholder is skipped", func(t *testing.T) { | ||
| mockStore := &utxo.MockUtxostore{} | ||
| hashes := []chainhash.Hash{subtreepkg.CoinbasePlaceholderHashValue, makeHash(1)} | ||
|
|
||
| mockStore.On("BatchDecorate", mock.Anything, mock.Anything, mock.Anything). | ||
| Run(func(args mock.Arguments) { | ||
| batch := args.Get(1).([]*utxo.UnresolvedMetaData) | ||
| require.Len(t, batch, 1, "coinbase should be filtered out") | ||
| batch[0].Data = &meta.Data{Creating: false} | ||
| }). | ||
| Return(nil) | ||
|
|
||
| result, err := CheckAllTxsExistInUTXO(ctx, mockStore, hashes, 1000) | ||
| require.NoError(t, err) | ||
| assert.True(t, result) | ||
| }) | ||
|
|
||
| t.Run("batching works correctly", func(t *testing.T) { | ||
| mockStore := &utxo.MockUtxostore{} | ||
| hashes := make([]chainhash.Hash, 5) | ||
| for i := range hashes { | ||
| hashes[i] = makeHash(i) | ||
| } | ||
|
|
||
| callCount := 0 | ||
| mockStore.On("BatchDecorate", mock.Anything, mock.Anything, mock.Anything). | ||
| Run(func(args mock.Arguments) { | ||
| batch := args.Get(1).([]*utxo.UnresolvedMetaData) | ||
| for _, item := range batch { | ||
| item.Data = &meta.Data{Creating: false} | ||
| } | ||
| callCount++ | ||
| }). | ||
| Return(nil) | ||
|
|
||
| result, err := CheckAllTxsExistInUTXO(ctx, mockStore, hashes, 2) | ||
| require.NoError(t, err) | ||
| assert.True(t, result) | ||
| assert.Equal(t, 3, callCount, "5 items with batch size 2 should create 3 batches") | ||
| }) | ||
|
|
||
| t.Run("item error returns false", func(t *testing.T) { | ||
| mockStore := &utxo.MockUtxostore{} | ||
| hashes := []chainhash.Hash{makeHash(1)} | ||
|
|
||
| mockStore.On("BatchDecorate", mock.Anything, mock.Anything, mock.Anything). | ||
| Run(func(args mock.Arguments) { | ||
| batch := args.Get(1).([]*utxo.UnresolvedMetaData) | ||
| batch[0].Err = fmt.Errorf("not found") | ||
| }). | ||
| Return(nil) | ||
|
|
||
| result, err := CheckAllTxsExistInUTXO(ctx, mockStore, hashes, 1000) | ||
| require.NoError(t, err) | ||
| assert.False(t, result) | ||
| }) | ||
|
|
||
| t.Run("only coinbase hashes returns true without calling store", func(t *testing.T) { | ||
| mockStore := &utxo.MockUtxostore{} | ||
| hashes := []chainhash.Hash{subtreepkg.CoinbasePlaceholderHashValue} | ||
|
|
||
| result, err := CheckAllTxsExistInUTXO(ctx, mockStore, hashes, 1000) | ||
| require.NoError(t, err) | ||
| assert.True(t, result) | ||
| // BatchDecorate should not be called since only coinbase hashes | ||
| mockStore.AssertNotCalled(t, "BatchDecorate") | ||
| }) | ||
|
|
||
| } |
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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The atomic flag pattern here has a race condition. When multiple goroutines check
needsSubtreeData.Load()at line 436 before any have called.Store(true), they all proceed to the UTXO check. If one goroutine finds a missing tx and sets the flag, other goroutines that already passed the check will still download subtreeData even though the flag is now set.Impact: The optimization won't be as effective as intended - some goroutines will unnecessarily download subtreeData even after the flag is set.
Solution: This is an inherent limitation of the optimization pattern and may be acceptable since it still provides bandwidth savings. However, if you want stricter behavior, consider checking the flag again before calling
fetchAndStoreSubtreeDataat lines 458 and 464.Update: ✅ Fixed - The code now includes a re-check of the flag at line 449 after fetching the subtree, which closes the race window. This ensures goroutines that are in-flight will check the flag again before proceeding to download subtreeData.