github.com/amazechain/amc@v0.1.3/internal/sync/initial-sync/blocks_queue_utils.go (about)

     1  package initialsync
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"github.com/amazechain/amc/utils"
     7  	"github.com/holiman/uint256"
     8  )
     9  
    10  // resetWithBlocks removes all state machines, then re-adds enough machines to contain all provided
    11  // blocks (machines are set into stateDataParsed state, so that their content is immediately
    12  // consumable). It is assumed that blocks come in an ascending order.
    13  func (q *blocksQueue) resetFromFork(fork *forkData) error {
    14  	if fork == nil {
    15  		return errors.New("nil fork data")
    16  	}
    17  	if len(fork.blocks) == 0 {
    18  		return errors.New("no blocks to reset from")
    19  	}
    20  	firstBlock := fork.blocks[0]
    21  	if firstBlock == nil {
    22  		return errors.New("invalid first block in fork data")
    23  	}
    24  
    25  	blocksPerRequest := q.blocksFetcher.blocksPerPeriod
    26  	if err := q.smm.removeAllStateMachines(); err != nil {
    27  		return err
    28  	}
    29  	firstBlockNr := utils.ConvertH256ToUint256Int(firstBlock.Header.Number)
    30  	fsm := q.smm.addStateMachine(firstBlockNr)
    31  	fsm.pid = fork.peer
    32  	fsm.blocks = fork.blocks
    33  	fsm.state = stateDataParsed
    34  
    35  	// The rest of machines are in skipped state.
    36  	startBlockNr := new(uint256.Int).AddUint64(firstBlockNr, uint64(len(fork.blocks)))
    37  	for i := startBlockNr.Clone(); i.Cmp(new(uint256.Int).AddUint64(startBlockNr, blocksPerRequest*(lookaheadSteps-1))) == -1; i.AddUint64(i, blocksPerRequest) {
    38  
    39  		fsm := q.smm.addStateMachine(i)
    40  		fsm.state = stateSkipped
    41  	}
    42  	return nil
    43  }
    44  
    45  // resetFromBlockNr removes all state machines, and re-adds them starting with a given BlockNr.
    46  func (q *blocksQueue) resetFromBlockNr(ctx context.Context, startBlockNr *uint256.Int) error {
    47  	// Shift start position of all the machines except for the last one.
    48  	blocksPerRequest := q.blocksFetcher.blocksPerPeriod
    49  	if err := q.smm.removeAllStateMachines(); err != nil {
    50  		return err
    51  	}
    52  	for i := startBlockNr.Clone(); i.Cmp(new(uint256.Int).AddUint64(startBlockNr, blocksPerRequest*(lookaheadSteps-1))) == -1; i.AddUint64(i, blocksPerRequest) {
    53  		q.smm.addStateMachine(i)
    54  	}
    55  
    56  	return nil
    57  }