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

Release Candidate v2024.0.0 - HIP-32 code (no mainnet HF) + Improvements #4546

Merged
merged 136 commits into from
Mar 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
136 commits
Select commit Hold shift + click to select a range
da863bf
Fixed memory leak and deadcode. (#4539)
Frozen Oct 20, 2023
a65f92d
Fix typo in README test steps (#4541)
UncertainBadg3r Oct 23, 2023
5faeb5f
Call `UpdateConsensusInformation` after bingo. (#4542)
Frozen Oct 23, 2023
d49715e
add new functions to p2p stream client for sharing the full states (#…
GheisMohammadi Oct 24, 2023
57dd5f2
Fixed. (#4543)
Frozen Oct 26, 2023
b1389da
Fixed data race. (#4544)
Frozen Oct 26, 2023
2f23d81
Last mile blocks insert.
Frozen Jun 13, 2023
fad17fe
Added logs.
Frozen Jun 14, 2023
c638184
Added logs.
Frozen Jun 14, 2023
b6987ec
Added logs.
Frozen Jun 14, 2023
525b20a
Start and finish syncing.
Frozen Jun 14, 2023
0e45682
Passed peerID to handlers.
Frozen Jun 25, 2023
a6ddc19
Implemented method for interface.
Frozen Jun 25, 2023
82b3f0c
Updated.
Frozen Jul 23, 2023
41900b0
Rebased onto dev.
Frozen Oct 17, 2023
f0b70d9
Fixed imports.
Frozen Oct 20, 2023
6179450
Fixed imports.
Frozen Oct 23, 2023
96e0386
Fixed imports.
Frozen Oct 23, 2023
64d7392
Clean up.
Frozen Oct 25, 2023
dc326f6
Rebased.
Frozen Oct 26, 2023
f24413e
Merge pull request #4455 from Frozen/block-peers
Frozen Oct 26, 2023
e124173
Cleanup. (#4547)
Frozen Oct 30, 2023
4b8cf56
Leader rotation. Check next leader aliveness. (#4359)
Frozen Oct 31, 2023
3167545
Cleanup (#4548)
Frozen Nov 2, 2023
b187cd7
Deadcode and cleanup. (#4550)
Frozen Nov 8, 2023
1f7d678
Refactored verify block. (#4554)
Frozen Nov 10, 2023
6f7a047
Fixed data race. (#4559)
Frozen Nov 10, 2023
dbe4d43
Timeout for block proposal. (#4553)
Frozen Nov 10, 2023
2089a0c
Fixed import and workaround for failing test. (#4560)
Frozen Nov 13, 2023
8f774ea
Fix typos (#4563)
omahs Nov 15, 2023
582a4cf
Fixed panic with dsync. (#4562)
Frozen Nov 16, 2023
6eda785
fix the issue of adding an existed block in legacy sync (#4565)
GheisMohammadi Nov 17, 2023
78685f9
Removed future blocks from blockchain_impl.go (#4569)
Frozen Nov 22, 2023
1f974af
Removed fast block. (#4571)
Frozen Nov 23, 2023
368fc9e
Removed unused functions and improved locks usage. (#4572)
Frozen Nov 24, 2023
b7b7fbf
Skip epochchain errors. (#4573)
Frozen Nov 24, 2023
fe1d97a
Removed outdated check. (#4574)
Frozen Nov 29, 2023
f993468
fix: max-rate bellow the era min-rate (#4552)
diego1q2w Nov 29, 2023
7be2b02
Revert "fix: max-rate bellow the era min-rate (#4552)" (#4578)
Frozen Dec 2, 2023
b7123fb
fix: eth json transaction (#4581)
diego1q2w Dec 5, 2023
86fca20
Fixed infinity loop sync. (#4575)
Frozen Dec 5, 2023
3b27215
use v2.NewReceipt for eth type receipt
adsorptionenthalpy Dec 6, 2023
29c6249
Fix. (#4583)
Frozen Dec 7, 2023
2001b34
Merge pull request #4582 from harmony-one/feature/HET104-12523
adsorptionenthalpy Dec 7, 2023
ca05f3f
add statesync as a new state to staged sync
GheisMohammadi Jun 25, 2023
9ec0272
add initial state download manager to stream sync
GheisMohammadi Jun 26, 2023
2064cfd
add protocol to stage statesync
GheisMohammadi Jun 26, 2023
702eb5e
add task management logic to state download manager in stream sync
GheisMohammadi Jun 26, 2023
4629fda
fix statesync config
GheisMohammadi Jun 26, 2023
9e1249a
refactor state download manager
GheisMohammadi Jun 28, 2023
841073d
refactor stage state sync
GheisMohammadi Jun 28, 2023
975857f
fix state download manager tasks issue
GheisMohammadi Jun 29, 2023
0da96b9
add receipt download manager
GheisMohammadi Jun 29, 2023
12d930f
fix receipt download manager result queue
GheisMohammadi Jun 29, 2023
6f3aa67
refactor stage receipts and change the stages sorting
GheisMohammadi Jun 29, 2023
e11b6ef
goimports staged stream sync
GheisMohammadi Jun 29, 2023
9103468
add block insertion without execution to blockchain implementation
GheisMohammadi Jul 3, 2023
cfc94bb
fix tests for new block insertion
GheisMohammadi Jul 3, 2023
9954a90
refactor staged stream sync to process fast sync and new block insertion
GheisMohammadi Jul 3, 2023
3522127
refactor stage receipts
GheisMohammadi Jul 3, 2023
591f223
fix block insertion in main.go
GheisMohammadi Jul 3, 2023
7006e15
goimports staged sync files
GheisMohammadi Jul 3, 2023
30de7c2
refactor stages list initialization based on the sync mode
GheisMohammadi Jul 3, 2023
f10dd1e
add SyncMode to configs
GheisMohammadi Jul 3, 2023
498bcc0
fix state download manager failure message
GheisMohammadi Jul 4, 2023
1f26944
split verifyAndInsertBlock function to be able to reuse verification …
GheisMohammadi Jul 5, 2023
7c3807a
refactor stage bodies to extract receip hashes in this stage rather t…
GheisMohammadi Jul 5, 2023
d4c8577
goimports
GheisMohammadi Jul 5, 2023
8f81810
add InsertReceiptChain to blockchain interface
GheisMohammadi Jul 5, 2023
57a77ab
refactor get receipts stage to use insertReceiptsChain
GheisMohammadi Jul 6, 2023
bcf1b77
remove using currentCycle, cleanup stage receipts
GheisMohammadi Jul 6, 2023
6f9a1ec
goimports
GheisMohammadi Jul 6, 2023
12235f5
fix stages forward order for staged stream sync
GheisMohammadi Jul 10, 2023
f6b8951
add SyncMode to flags
GheisMohammadi Jul 13, 2023
cd7ccbe
fix stages and replace with forward stages
GheisMohammadi Aug 16, 2023
772d865
fix block validation in stage bodies
GheisMohammadi Sep 6, 2023
c1d352b
add pivot to chain accessor, add CurrentFastBlock to blockchain_impl,…
GheisMohammadi Sep 26, 2023
8d66bdf
add getBlockByMaxVote to sync helper
GheisMohammadi Sep 27, 2023
917a301
add tests for node data request
GheisMohammadi Oct 3, 2023
7c21eef
fix stream tests
GheisMohammadi Oct 3, 2023
d534fea
add Validator method to blockchain to fix the interface
GheisMohammadi Oct 3, 2023
e96855b
fix shard chain test
GheisMohammadi Oct 3, 2023
ebd689f
remove blockExecution option from insertChain
GheisMohammadi Oct 3, 2023
36d2abd
remove extra blockExecutions
GheisMohammadi Oct 4, 2023
9629d9c
remove blockExecution option from staged stream sync
GheisMohammadi Oct 4, 2023
e4dcda6
refactor staged stream sync, fix the state sync functions
GheisMohammadi Oct 4, 2023
6348128
improve stage handling for create new instance of staged stream sync
GheisMohammadi Oct 4, 2023
c808f2b
fix pivot block issue for write on chain
GheisMohammadi Oct 5, 2023
bdd7f14
improve stream sync current cycle and pivot checks, fix edge case iss…
GheisMohammadi Oct 6, 2023
135c7da
fix WriteHeadBlock, fix GetDownloadDetails index, improve fetching cu…
GheisMohammadi Oct 24, 2023
3fcfad4
fix rebase conflicts
GheisMohammadi Oct 26, 2023
9992825
add state sync
GheisMohammadi Nov 14, 2023
c340c70
fix GetNextBatch to complete sync after there is no more pending stat…
GheisMohammadi Nov 16, 2023
3374100
fix state sync file name spell error
GheisMohammadi Nov 16, 2023
e141f79
add ProofSet and ProofList to staged stream sync
GheisMohammadi Dec 7, 2023
390bdb6
add client new functions to stream sync adapter, update GetAccountRan…
GheisMohammadi Dec 7, 2023
0901e92
add state sync full, complete full state sync stage
GheisMohammadi Dec 7, 2023
02e2fee
Fix: max rate issue (#4580)
diego1q2w Dec 10, 2023
f3ce9f3
return back deleted codes, fix rebase issues, goimports
GheisMohammadi Dec 11, 2023
191c55b
fix full state sync requests cap, add error handling to stage state s…
GheisMohammadi Dec 12, 2023
419aad1
remove state debug logs
GheisMohammadi Dec 12, 2023
c82599b
Merge pull request #4465 from harmony-one/feature/fastsync
adsorptionenthalpy Dec 12, 2023
9a5ba3c
blocksCountAliveness can't be bigger than minimumBlocksForLeaderInRow…
Frozen Dec 20, 2023
556444c
Feature: last signing power. (#4584)
Frozen Dec 20, 2023
d6690ed
Activate external rotation devnet. (#4596)
Frozen Dec 22, 2023
718286f
delay for a few epochs the leader rotations devnet (#4597)
diego1q2w Dec 24, 2023
41066fa
fix conflicts main->dev
adsorptionenthalpy Dec 29, 2023
e68b44f
Complete Fast Sync codes (#4594)
GheisMohammadi Jan 9, 2024
5443bf7
reduce internal voting power to 10% devnet (#4599)
diego1q2w Jan 9, 2024
7df72eb
Merge branch 'dev' into maintodev122023
ONECasey Jan 9, 2024
2927929
Merge pull request #4600 from harmony-one/maintodev122023
sophoah Jan 9, 2024
50a1a75
ignore known blocks for processing state sync (#4602)
GheisMohammadi Jan 9, 2024
f576910
Force verify all sign. (#4601)
Frozen Jan 10, 2024
00734e2
closing stream removes it from stream manager as well, so it doesn't …
GheisMohammadi Jan 11, 2024
1dd67a8
15 nodes per shard for devnet (#4607)
Frozen Jan 11, 2024
a31b4f5
Thread safe Decider. (#4610)
Frozen Jan 16, 2024
cdbc79e
Devnet: activate leader rotation at epoch 4 . (#4611)
Frozen Jan 17, 2024
e15bae1
Fix for panic "insertChain failed to update current block" (#4612)
Frozen Jan 18, 2024
17a2522
Recreate trie after revert. (#4608)
Frozen Jan 18, 2024
51a1ffe
prepare devnet reset (#4615)
diego1q2w Jan 23, 2024
2441a0b
Fix fast sync null snapshot and null response issue (#4613)
GheisMohammadi Jan 25, 2024
8d24b5b
fix wrong root hash for generating snapshot
GheisMohammadi Jan 25, 2024
d1ffd5c
add cache configurations
GheisMohammadi Jan 25, 2024
9b42870
return back sync default settings
GheisMohammadi Jan 25, 2024
f3fc633
Fix for revert. (#4617)
Frozen Jan 25, 2024
fe72c4f
activate devnet external hardfork (#4619)
diego1q2w Jan 26, 2024
0066c2e
push the activation of the external devnet epoch (#4620)
diego1q2w Jan 27, 2024
0082c4d
add system log for creating/loading snapshot
GheisMohammadi Jan 29, 2024
c01cc29
Merge pull request #4618 from harmony-one/fix/snapshot
adsorptionenthalpy Jan 29, 2024
ae4ffeb
fix allowed txs to be able to handle multiple txs for same from addre…
GheisMohammadi Jan 30, 2024
8d5f20f
Removed outdated flag, additional checks and simplified logic. (#4621)
Frozen Jan 30, 2024
ca91cb2
Skip check when the 100% check is achieved. (#4625)
diego1q2w Feb 2, 2024
b53a911
push devnet external and leader rotation epochs (#4634)
diego1q2w Feb 20, 2024
138a460
Update dev to include main hotfixes (#4633)
ONECasey Feb 21, 2024
86c4a21
Merge branch 'main' into dev
ONECasey Feb 21, 2024
49bba17
Fix. (#4635)
Frozen Feb 22, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
This [github document](https://help.github.com/articles/creating-a-pull-request/) provides some guidance on how to create a pull request in github.

## PR requirement
To pursue engineering excellence, we have insisted on the highest stardard on the quality of each PR.
To pursue engineering excellence, we have insisted on the highest standard for the quality of each PR.

* For each PR, please run [golint](https://github.com/golang/lint), [goimports](https://godoc.org/golang.org/x/tools/cmd/goimports), to fix the basic issues/warnings.
* Make sure you understand [How to Write a Git Commit Message](https://chris.beams.io/posts/git-commit/).
Expand All @@ -21,7 +21,7 @@ To pursue engineering excellence, we have insisted on the highest stardard on th
The best practice is to reorder and squash your local commits before the PR submission to create an atomic and self-contained PR.
This [book chapter](https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History) provides detailed explanation and guidance on how to rewrite the local git history.

For exampple, a typical workflow is like the following.
For example, a typical workflow is like the following.
```bash
# assuming you are working on a fix of bug1, and use a local branch called "fixes_of_bug1".

Expand Down
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -179,4 +179,4 @@ debug_external: clean
bash test/debug-external.sh

build_localnet_validator:
bash test/build-localnet-validator.sh
bash test/build-localnet-validator.sh
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ make debug-kill

To keep things consistent, we have a docker image to run all tests. **These are the same tests ran on the pull request checks**.

Note that all testing docker container binds a couple of ports to the host machine for your convince. The ports are:
Note that all test Docker containers bind several ports to the host machine for your convenience. The ports are:
* `9500` - Shard 0 RPC for a validator
* `9501` - Shard 1 RPC for a validator
* `9599` - Shard 0 RPC for an explorer
Expand All @@ -174,7 +174,7 @@ To run this test, do:
make test-rpc
```
This test starts a localnet (within the Docker container), **ensures it reaches a consensus**, and runs a series of tests to ensure correct RPC behavior.
This test also acts as a preliminary integration test (more through tests are done on the testnets).
This test also acts as a preliminary integration test (more thorough tests are done on the testnets).
> The tests ran by this command can be found [here](https://github.com/harmony-one/harmony-test/tree/master/localnet).

If you wish to debug further with the localnet after the tests are done, open a new shell and run:
Expand All @@ -194,7 +194,7 @@ To run this test, do:
make test-rosetta
```
This test starts a localnet (within the Docker container), **ensures it reaches a consensus**, and runs the Construction & Data API checks using the [rosetta-cli](https://github.com/coinbase/rosetta-cli).
This test also acts as a preliminary integration test (more through tests are done on the testnets).
This test also acts as a preliminary integration test (more thorough tests are done on the testnets).
> The config for this test can be found [here](https://github.com/harmony-one/harmony-test/blob/master/localnet/configs/localnet_rosetta_test_s0.json) & [here](https://github.com/harmony-one/harmony-test/blob/master/localnet/configs/localnet_rosetta_test_s1.json)

Similar to the RPC tests, if you wish to debug further with the localnet after the tests are done, open a new shell and run:
Expand Down
17 changes: 15 additions & 2 deletions api/service/legacysync/epoch_syncing.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,9 @@ func syncLoop(bc core.BlockChain, syncConfig *SyncConfig) (timeout int) {

err := ProcessStateSync(syncConfig, heights, bc)
if err != nil {
if errors.Is(err, core.ErrKnownBlock) {
return 10
}
utils.Logger().Error().Err(err).
Msgf("[EPOCHSYNC] ProcessStateSync failed (isBeacon: %t, ShardID: %d, otherEpoch: %d, currentEpoch: %d)",
isBeacon, bc.ShardID(), otherEpoch, curEpoch)
Expand Down Expand Up @@ -199,8 +202,18 @@ func processWithPayload(payload [][]byte, bc core.BlockChain) error {
decoded = append(decoded, block)
}

_, err := bc.InsertChain(decoded, true)
return err
for _, block := range decoded {
_, err := bc.InsertChain([]*types.Block{block}, true)
switch {
case errors.Is(err, core.ErrKnownBlock):
continue
case err != nil:
return err
default:
}
}

return nil
}

// CreateSyncConfig creates SyncConfig for StateSync object.
Expand Down
33 changes: 26 additions & 7 deletions api/service/legacysync/syncing.go
Original file line number Diff line number Diff line change
Expand Up @@ -860,11 +860,12 @@ func (ss *StateSync) getBlockFromLastMileBlocksByParentHash(parentHash common.Ha
}

// UpdateBlockAndStatus ...
func (ss *StateSync) UpdateBlockAndStatus(block *types.Block, bc core.BlockChain, verifyAllSig bool) error {
func (ss *StateSync) UpdateBlockAndStatus(block *types.Block, bc core.BlockChain) error {
if block.NumberU64() != bc.CurrentBlock().NumberU64()+1 {
utils.Logger().Debug().Uint64("curBlockNum", bc.CurrentBlock().NumberU64()).Uint64("receivedBlockNum", block.NumberU64()).Msg("[SYNC] Inappropriate block number, ignore!")
return nil
}
verifyAllSig := true

haveCurrentSig := len(block.GetCurrentCommitSig()) != 0
// Verify block signatures
Expand Down Expand Up @@ -904,7 +905,17 @@ func (ss *StateSync) UpdateBlockAndStatus(block *types.Block, bc core.BlockChain
}

_, err := bc.InsertChain([]*types.Block{block}, false /* verifyHeaders */)
if err != nil {
switch {
case errors.Is(err, core.ErrKnownBlock):
utils.Logger().Info().
Uint64("blockHeight", block.NumberU64()).
Uint64("blockEpoch", block.Epoch().Uint64()).
Str("blockHex", block.Hash().Hex()).
Uint32("ShardID", block.ShardID()).
Err(err).
Msg("[SYNC] UpdateBlockAndStatus: Block exists")
return nil
case err != nil:
utils.Logger().Error().
Err(err).
Msgf(
Expand All @@ -913,6 +924,7 @@ func (ss *StateSync) UpdateBlockAndStatus(block *types.Block, bc core.BlockChain
block.ShardID(),
)
return err
default:
}
utils.Logger().Info().
Uint64("blockHeight", block.NumberU64()).
Expand Down Expand Up @@ -944,8 +956,8 @@ func (ss *StateSync) generateNewState(bc core.BlockChain) error {
break
}
// Enforce sig check for the last block in a batch
enforceSigCheck := !commonIter.HasNext()
err = ss.UpdateBlockAndStatus(block, bc, enforceSigCheck)
_ = !commonIter.HasNext()
err = ss.UpdateBlockAndStatus(block, bc)
if err != nil {
break
}
Expand All @@ -962,7 +974,7 @@ func (ss *StateSync) generateNewState(bc core.BlockChain) error {
if block == nil {
break
}
err = ss.UpdateBlockAndStatus(block, bc, true)
err = ss.UpdateBlockAndStatus(block, bc)
if err != nil {
break
}
Expand All @@ -983,7 +995,7 @@ func (ss *StateSync) generateNewState(bc core.BlockChain) error {
if block == nil {
break
}
err = ss.UpdateBlockAndStatus(block, bc, false)
err = ss.UpdateBlockAndStatus(block, bc)
if err != nil {
break
}
Expand Down Expand Up @@ -1111,6 +1123,9 @@ func (ss *StateSync) SyncLoop(bc core.BlockChain, isBeacon bool, consensus *cons
}
err := ss.ProcessStateSync(startHash[:], size, bc)
if err != nil {
if errors.Is(err, core.ErrKnownBlock) {
continue
}
utils.Logger().Error().Err(err).
Msgf("[SYNC] ProcessStateSync failed (isBeacon: %t, ShardID: %d, otherHeight: %d, currentHeight: %d)",
isBeacon, bc.ShardID(), otherHeight, currentHeight)
Expand Down Expand Up @@ -1148,7 +1163,11 @@ func (ss *StateSync) addConsensusLastMile(bc core.BlockChain, consensus *consens
if block == nil {
break
}
if _, err := bc.InsertChain(types.Blocks{block}, true); err != nil {
_, err := bc.InsertChain(types.Blocks{block}, true)
switch {
case errors.Is(err, core.ErrKnownBlock):
case errors.Is(err, core.ErrNotLastBlockInEpoch):
case err != nil:
return errors.Wrap(err, "failed to InsertChain")
}
}
Expand Down
5 changes: 5 additions & 0 deletions api/service/stagedstreamsync/adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/p2p/stream/common/streammanager"
syncproto "github.com/harmony-one/harmony/p2p/stream/protocols/sync"
"github.com/harmony-one/harmony/p2p/stream/protocols/sync/message"
sttypes "github.com/harmony-one/harmony/p2p/stream/types"
)

Expand All @@ -20,6 +21,10 @@ type syncProtocol interface {
GetBlocksByHashes(ctx context.Context, hs []common.Hash, opts ...syncproto.Option) ([]*types.Block, sttypes.StreamID, error)
GetReceipts(ctx context.Context, hs []common.Hash, opts ...syncproto.Option) (receipts []types.Receipts, stid sttypes.StreamID, err error)
GetNodeData(ctx context.Context, hs []common.Hash, opts ...syncproto.Option) (data [][]byte, stid sttypes.StreamID, err error)
GetAccountRange(ctx context.Context, root common.Hash, origin common.Hash, limit common.Hash, bytes uint64, opts ...syncproto.Option) (accounts []*message.AccountData, proof [][]byte, stid sttypes.StreamID, err error)
GetStorageRanges(ctx context.Context, root common.Hash, accounts []common.Hash, origin common.Hash, limit common.Hash, bytes uint64, opts ...syncproto.Option) (slots [][]*message.StorageData, proof [][]byte, stid sttypes.StreamID, err error)
GetByteCodes(ctx context.Context, hs []common.Hash, bytes uint64, opts ...syncproto.Option) (codes [][]byte, stid sttypes.StreamID, err error)
GetTrieNodes(ctx context.Context, root common.Hash, paths []*message.TrieNodePathSet, bytes uint64, opts ...syncproto.Option) (nodes [][]byte, stid sttypes.StreamID, err error)

RemoveStream(stID sttypes.StreamID) // If a stream delivers invalid data, remove the stream
StreamFailed(stID sttypes.StreamID, reason string)
Expand Down
5 changes: 4 additions & 1 deletion api/service/stagedstreamsync/beacon_helper.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package stagedstreamsync

import (
"errors"
"time"

"github.com/harmony-one/harmony/core"
"github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/internal/utils"
"github.com/rs/zerolog"
Expand Down Expand Up @@ -126,7 +128,8 @@ func (bh *beaconHelper) insertLastMileBlocks() (inserted int, bn uint64, err err
}
// TODO: Instruct the beacon helper to verify signatures. This may require some forks
// in pub-sub message (add commit sigs in node.block.sync messages)
if _, err = bh.bc.InsertChain(types.Blocks{b}, true); err != nil {
_, err = bh.bc.InsertChain(types.Blocks{b}, true)
if err != nil && !errors.Is(err, core.ErrKnownBlock) {
bn--
return
}
Expand Down
56 changes: 38 additions & 18 deletions api/service/stagedstreamsync/block_manager.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package stagedstreamsync

import (
"fmt"
"sync"

"github.com/ethereum/go-ethereum/common"
sttypes "github.com/harmony-one/harmony/p2p/stream/types"
"github.com/ledgerwatch/erigon-lib/kv"
"github.com/rs/zerolog"
Expand All @@ -11,6 +13,7 @@ import (
type BlockDownloadDetails struct {
loopID int
streamID sttypes.StreamID
rootHash common.Hash
}

// blockDownloadManager is the helper structure for get blocks request management
Expand All @@ -19,11 +22,11 @@ type blockDownloadManager struct {
tx kv.RwTx

targetBN uint64
requesting map[uint64]struct{} // block numbers that have been assigned to workers but not received
processing map[uint64]struct{} // block numbers received requests but not inserted
retries *prioritizedNumbers // requests where error happens
rq *resultQueue // result queue wait to be inserted into blockchain
bdd map[uint64]BlockDownloadDetails // details about how this block was downloaded
requesting map[uint64]struct{} // block numbers that have been assigned to workers but not received
processing map[uint64]struct{} // block numbers received requests but not inserted
retries *prioritizedNumbers // requests where error happens
rq *resultQueue // result queue wait to be inserted into blockchain
bdd map[uint64]*BlockDownloadDetails // details about how this block was downloaded

logger zerolog.Logger
lock sync.Mutex
Expand All @@ -38,26 +41,26 @@ func newBlockDownloadManager(tx kv.RwTx, chain blockChain, targetBN uint64, logg
processing: make(map[uint64]struct{}),
retries: newPrioritizedNumbers(),
rq: newResultQueue(),
bdd: make(map[uint64]BlockDownloadDetails),
bdd: make(map[uint64]*BlockDownloadDetails),
logger: logger,
}
}

// GetNextBatch get the next block numbers batch
func (gbm *blockDownloadManager) GetNextBatch() []uint64 {
func (gbm *blockDownloadManager) GetNextBatch(curHeight uint64) []uint64 {
gbm.lock.Lock()
defer gbm.lock.Unlock()

cap := BlocksPerRequest

bns := gbm.getBatchFromRetries(cap)
bns := gbm.getBatchFromRetries(cap, curHeight)
if len(bns) > 0 {
cap -= len(bns)
gbm.addBatchToRequesting(bns)
}

if gbm.availableForMoreTasks() {
addBNs := gbm.getBatchFromUnprocessed(cap)
addBNs := gbm.getBatchFromUnprocessed(cap, curHeight)
gbm.addBatchToRequesting(addBNs)
bns = append(bns, addBNs...)
}
Expand Down Expand Up @@ -88,7 +91,7 @@ func (gbm *blockDownloadManager) HandleRequestResult(bns []uint64, blockBytes []
gbm.retries.push(bn)
} else {
gbm.processing[bn] = struct{}{}
gbm.bdd[bn] = BlockDownloadDetails{
gbm.bdd[bn] = &BlockDownloadDetails{
loopID: loopID,
streamID: streamID,
}
Expand All @@ -107,7 +110,7 @@ func (gbm *blockDownloadManager) SetDownloadDetails(bns []uint64, loopID int, st
defer gbm.lock.Unlock()

for _, bn := range bns {
gbm.bdd[bn] = BlockDownloadDetails{
gbm.bdd[bn] = &BlockDownloadDetails{
loopID: loopID,
streamID: streamID,
}
Expand All @@ -116,25 +119,43 @@ func (gbm *blockDownloadManager) SetDownloadDetails(bns []uint64, loopID int, st
}

// GetDownloadDetails returns the download details for a block
func (gbm *blockDownloadManager) GetDownloadDetails(blockNumber uint64) (loopID int, streamID sttypes.StreamID) {
func (gbm *blockDownloadManager) GetDownloadDetails(blockNumber uint64) (loopID int, streamID sttypes.StreamID, err error) {
gbm.lock.Lock()
defer gbm.lock.Unlock()

return gbm.bdd[blockNumber].loopID, gbm.bdd[blockNumber].streamID
if dm, exist := gbm.bdd[blockNumber]; exist {
return dm.loopID, dm.streamID, nil
}
return 0, sttypes.StreamID(fmt.Sprint(0)), fmt.Errorf("there is no download details for the block number: %d", blockNumber)
}

// SetRootHash sets the root hash for a specific block
func (gbm *blockDownloadManager) SetRootHash(blockNumber uint64, root common.Hash) {
gbm.lock.Lock()
defer gbm.lock.Unlock()

gbm.bdd[blockNumber].rootHash = root
}

// GetRootHash returns the root hash for a specific block
func (gbm *blockDownloadManager) GetRootHash(blockNumber uint64) common.Hash {
gbm.lock.Lock()
defer gbm.lock.Unlock()

return gbm.bdd[blockNumber].rootHash
}

// getBatchFromRetries get the block number batch to be requested from retries.
func (gbm *blockDownloadManager) getBatchFromRetries(cap int) []uint64 {
func (gbm *blockDownloadManager) getBatchFromRetries(cap int, fromBlockNumber uint64) []uint64 {
var (
requestBNs []uint64
curHeight = gbm.chain.CurrentBlock().NumberU64()
)
for cnt := 0; cnt < cap; cnt++ {
bn := gbm.retries.pop()
if bn == 0 {
break // no more retries
}
if bn <= curHeight {
if bn <= fromBlockNumber {
continue
}
requestBNs = append(requestBNs, bn)
Expand All @@ -143,10 +164,9 @@ func (gbm *blockDownloadManager) getBatchFromRetries(cap int) []uint64 {
}

// getBatchFromUnprocessed returns a batch of block numbers to be requested from unprocessed.
func (gbm *blockDownloadManager) getBatchFromUnprocessed(cap int) []uint64 {
func (gbm *blockDownloadManager) getBatchFromUnprocessed(cap int, curHeight uint64) []uint64 {
var (
requestBNs []uint64
curHeight = gbm.chain.CurrentBlock().NumberU64()
)
bn := curHeight + 1
// TODO: this algorithm can be potentially optimized.
Expand Down
Loading