Skip to content

Commit

Permalink
chore: refactory insert of headers to avoid bool parameter
Browse files Browse the repository at this point in the history
  • Loading branch information
RafilxTenfen committed Aug 5, 2024
1 parent bd9263d commit c3de831
Show file tree
Hide file tree
Showing 8 changed files with 73 additions and 68 deletions.
2 changes: 1 addition & 1 deletion app/upgrades/signetlaunch/upgrades.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func insertBtcHeaders(
headersBytes[i] = *h.Header
}

if err := k.InsertHeadersNoEventsAndRollback(ctx, headersBytes); err != nil {
if err := k.InsertHeaders(ctx, headersBytes); err != nil {
return err
}

Expand Down
2 changes: 1 addition & 1 deletion testutil/datagen/btc_header_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ func GenRandBtcChainInsertingInKeeper(
genesisHeaderInfo,
uint32(chainLength),
)
err := k.InsertHeaders(ctx, randomChain.ChainToBytes())
err := k.InsertHeadersWithHookAndEvents(ctx, randomChain.ChainToBytes())
require.NoError(t, err)
tip := k.GetTipInfo(ctx)
randomChainTipInfo := randomChain.GetTipInfo()
Expand Down
105 changes: 55 additions & 50 deletions x/btclightclient/keeper/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,73 +75,78 @@ func (k *Keeper) SetHooks(bh types.BTCLightClientHooks) *Keeper {
return k
}

func (k Keeper) insertHeaders(
ctx context.Context,
headers []*wire.BlockHeader,
) error {
func (k Keeper) insertHandler() func(ctx context.Context, s headersState, result *types.InsertResult) error {
return func(ctx context.Context, s headersState, result *types.InsertResult) error {
// if we receive rollback, should return error
if result.RollbackInfo != nil {
return fmt.Errorf("rollback should not happend %+v", result.RollbackInfo)
}

headerState := k.headersState(ctx)
for _, header := range result.HeadersToInsert {
h := header
s.insertHeader(h)
}
return nil
}
}

result, err := k.bl.InsertHeaders(
headerState,
headers,
)
func (k Keeper) triggerEventAndHandleHooksHandler() func(ctx context.Context, s headersState, result *types.InsertResult) error {
return func(ctx context.Context, s headersState, result *types.InsertResult) error {
// if we have rollback, first delete all headers up to the rollback point
if result.RollbackInfo != nil {
// roll back to the height
s.rollBackHeadersUpTo(result.RollbackInfo.HeaderToRollbackTo.Height)
// trigger rollback event
k.triggerRollBack(ctx, result.RollbackInfo.HeaderToRollbackTo)
}

if err != nil {
return err
for _, header := range result.HeadersToInsert {
h := header
s.insertHeader(h)
k.triggerHeaderInserted(ctx, h)
k.triggerRollForward(ctx, h)
}
return nil
}
}

// if we have rollback, first delete all headers up to the rollback point
if result.RollbackInfo != nil {
// roll back to the height
headerState.rollBackHeadersUpTo(result.RollbackInfo.HeaderToRollbackTo.Height)
// trigger rollback event
k.triggerRollBack(ctx, result.RollbackInfo.HeaderToRollbackTo)
}
func (k Keeper) insertHeadersWithHookAndEvents(
ctx context.Context,
headers []*wire.BlockHeader) error {
return k.insertHeadersInternal(
ctx,
headers,
k.triggerEventAndHandleHooksHandler(),
)
}

k.insertHeadersFromInsertResult(ctx, result, true)
return nil
func (k Keeper) insertHeaders(
ctx context.Context,
headers []*wire.BlockHeader) error {
return k.insertHeadersInternal(
ctx,
headers,
k.insertHandler(),
)
}

func (k Keeper) insertHeadersNoEventsAndRollback(
func (k Keeper) insertHeadersInternal(
ctx context.Context,
headers []*wire.BlockHeader,
handleInsertResult func(ctx context.Context, s headersState, result *types.InsertResult) error,
) error {
headerState := k.headersState(ctx)

result, err := k.bl.InsertHeaders(
headerState,
headers,
)

if err != nil {
return err
}

// if we receive rollback, should return error
if result.RollbackInfo != nil {
return fmt.Errorf("rollback should not happend %+v", result.RollbackInfo)
}

k.insertHeadersFromInsertResult(ctx, result, false)
return nil
}

func (k Keeper) insertHeadersFromInsertResult(
ctx context.Context,
result *types.InsertResult,
triggerEventsAndHooks bool,
) {
headerState := k.headersState(ctx)

for _, header := range result.HeadersToInsert {
h := header
headerState.insertHeader(h)
if !triggerEventsAndHooks {
continue
}
k.triggerHeaderInserted(ctx, h)
k.triggerRollForward(ctx, h)
}
return handleInsertResult(ctx, headerState, result)
}

// InsertHeaderInfos inserts multiple headers info at the store.
Expand All @@ -152,22 +157,22 @@ func (k Keeper) InsertHeaderInfos(ctx context.Context, infos []*types.BTCHeaderI
}
}

func (k Keeper) InsertHeaders(ctx context.Context, headers []bbn.BTCHeaderBytes) error {
func (k Keeper) InsertHeadersWithHookAndEvents(ctx context.Context, headers []bbn.BTCHeaderBytes) error {
if len(headers) == 0 {
return types.ErrEmptyMessage
}

blockHeaders := btcHeadersBytesToBlockHeader(headers)
return k.insertHeaders(ctx, blockHeaders)
return k.insertHeadersWithHookAndEvents(ctx, blockHeaders)
}

func (k Keeper) InsertHeadersNoEventsAndRollback(ctx context.Context, headers []bbn.BTCHeaderBytes) error {
func (k Keeper) InsertHeaders(ctx context.Context, headers []bbn.BTCHeaderBytes) error {
if len(headers) == 0 {
return types.ErrEmptyMessage
}

blockHeaders := btcHeadersBytesToBlockHeader(headers)
return k.insertHeadersNoEventsAndRollback(ctx, blockHeaders)
return k.insertHeaders(ctx, blockHeaders)
}

func btcHeadersBytesToBlockHeader(headers []bbn.BTCHeaderBytes) []*wire.BlockHeader {
Expand Down
22 changes: 11 additions & 11 deletions x/btclightclient/keeper/keeper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ func FuzzKeeperInsertValidChainExtension(f *testing.F) {
extendedChainWork := oldTip.Work.Add(*chainExtensionWork)
extendedChainHeight := uint64(uint32(oldTip.Height) + newChainLength)

err := blcKeeper.InsertHeaders(ctx, keepertest.NewBTCHeaderBytesList(chainToInsert))
err := blcKeeper.InsertHeadersWithHookAndEvents(ctx, keepertest.NewBTCHeaderBytesList(chainToInsert))
require.NoError(t, err)

// updated tip
Expand Down Expand Up @@ -247,7 +247,7 @@ func FuzzKeeperInsertValidBetterChain(f *testing.F) {

require.True(t, len(removedBranch) > 0)

err := blcKeeper.InsertHeaders(ctx, keepertest.NewBTCHeaderBytesList(chainToInsert))
err := blcKeeper.InsertHeadersWithHookAndEvents(ctx, keepertest.NewBTCHeaderBytesList(chainToInsert))
require.NoError(t, err)

// updated tip
Expand Down Expand Up @@ -332,16 +332,16 @@ func FuzzKeeperInsertInvalidChain(f *testing.F) {
require.NotNil(t, currentTip)

// Inserting nil headers should result with error
errNil := blcKeeper.InsertHeaders(ctx, nil)
errNil := blcKeeper.InsertHeadersWithHookAndEvents(ctx, nil)
require.Error(t, errNil)

// Inserting empty headers should result with error
errEmpty := blcKeeper.InsertHeaders(ctx, []bbn.BTCHeaderBytes{})
errEmpty := blcKeeper.InsertHeadersWithHookAndEvents(ctx, []bbn.BTCHeaderBytes{})
require.Error(t, errEmpty)

// Inserting header without existing parent should result with error
chain := datagen.NewBTCHeaderChainWithLength(r, 0, 0, 10)
errNoParent := blcKeeper.InsertHeaders(ctx, chain.ChainToBytes()[1:])
errNoParent := blcKeeper.InsertHeadersWithHookAndEvents(ctx, chain.ChainToBytes()[1:])
require.Error(t, errNoParent)
require.True(t, errors.Is(errNoParent, types.ErrHeaderParentDoesNotExist))

Expand All @@ -358,7 +358,7 @@ func FuzzKeeperInsertInvalidChain(f *testing.F) {

// bump the nonce, it should fail validation and tip should not change
chainToInsert[3].Nonce = chainToInsert[3].Nonce + 1
errInvalidHeader := blcKeeper.InsertHeaders(ctx, keepertest.NewBTCHeaderBytesList(chainToInsert))
errInvalidHeader := blcKeeper.InsertHeadersWithHookAndEvents(ctx, keepertest.NewBTCHeaderBytesList(chainToInsert))
require.Error(t, errInvalidHeader)
newTip := blcKeeper.GetTipInfo(ctx)
// tip did not change
Expand All @@ -374,7 +374,7 @@ func FuzzKeeperInsertInvalidChain(f *testing.F) {
nil,
1,
)
errWorseChain := blcKeeper.InsertHeaders(ctx, keepertest.NewBTCHeaderBytesList(worseChain))
errWorseChain := blcKeeper.InsertHeadersWithHookAndEvents(ctx, keepertest.NewBTCHeaderBytesList(worseChain))
require.Error(t, errWorseChain)
require.True(t, errors.Is(errWorseChain, types.ErrChainWithNotEnoughWork))
})
Expand Down Expand Up @@ -409,13 +409,13 @@ func FuzzKeeperValdateHeaderAtDifficultyAdjustmentBoundaries(f *testing.F) {

// this will always fail as last header is at adjustment boundary, but we created
// it without adjustment
err := blcKeeper.InsertHeaders(ctx, randomChain.ChainToBytes())
err := blcKeeper.InsertHeadersWithHookAndEvents(ctx, randomChain.ChainToBytes())
require.Error(t, err)

randomChainWithoutLastHeader := randomChain.Headers[:len(randomChain.Headers)-1]
chain := keepertest.NewBTCHeaderBytesList(randomChainWithoutLastHeader)
// now all headers are valid, and we are below adjustment boundary
err = blcKeeper.InsertHeaders(ctx, chain)
err = blcKeeper.InsertHeadersWithHookAndEvents(ctx, chain)
require.NoError(t, err)

currentTip := blcKeeper.GetTipInfo(ctx)
Expand All @@ -429,7 +429,7 @@ func FuzzKeeperValdateHeaderAtDifficultyAdjustmentBoundaries(f *testing.F) {
nil,
)
// try to insert header at adjustment boundary without adjustment should fail
err = blcKeeper.InsertHeaders(ctx, []bbn.BTCHeaderBytes{bbn.NewBTCHeaderBytesFromBlockHeader(invalidAdjustedHeader)})
err = blcKeeper.InsertHeadersWithHookAndEvents(ctx, []bbn.BTCHeaderBytes{bbn.NewBTCHeaderBytesFromBlockHeader(invalidAdjustedHeader)})
require.Error(t, err)

// Inserting valid adjusted header should succeed
Expand All @@ -446,7 +446,7 @@ func FuzzKeeperValdateHeaderAtDifficultyAdjustmentBoundaries(f *testing.F) {
)
validAdjustedHeaderBytes := bbn.NewBTCHeaderBytesFromBlockHeader(validAdjustedHeader)

err = blcKeeper.InsertHeaders(ctx, []bbn.BTCHeaderBytes{bbn.NewBTCHeaderBytesFromBlockHeader(validAdjustedHeader)})
err = blcKeeper.InsertHeadersWithHookAndEvents(ctx, []bbn.BTCHeaderBytes{bbn.NewBTCHeaderBytesFromBlockHeader(validAdjustedHeader)})
require.NoError(t, err)

newTip := blcKeeper.GetTipInfo(ctx)
Expand Down
2 changes: 1 addition & 1 deletion x/btclightclient/keeper/msg_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ func (m msgServer) InsertHeaders(ctx context.Context, msg *types.MsgInsertHeader
return nil, types.ErrUnauthorizedReporter.Wrapf("reporter %s is not authorized to insert headers", reporterAddress)
}

err := m.k.InsertHeaders(sdkCtx, msg.Headers)
err := m.k.InsertHeadersWithHookAndEvents(sdkCtx, msg.Headers)

if err != nil {
return nil, err
Expand Down
4 changes: 2 additions & 2 deletions x/monitor/keeper/grpc_query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func FuzzQueryEndedEpochBtcHeight(f *testing.F) {
10,
)
headerBytes := datagen.HeaderToHeaderBytes(chain)
err := lck.InsertHeaders(ctx, headerBytes)
err := lck.InsertHeadersWithHookAndEvents(ctx, headerBytes)
require.NoError(t, err)

// go to BeginBlock of block 11, and thus entering epoch 2
Expand Down Expand Up @@ -98,7 +98,7 @@ func FuzzQueryReportedCheckpointBtcHeight(f *testing.F) {
10,
)
headerBytes := datagen.HeaderToHeaderBytes(chain)
err := lck.InsertHeaders(ctx, headerBytes)
err := lck.InsertHeadersWithHookAndEvents(ctx, headerBytes)
require.NoError(t, err)

// Add checkpoint
Expand Down
2 changes: 1 addition & 1 deletion x/zoneconcierge/keeper/ibc_packet_btc_timestamp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func genRandomChain(
initHeader,
uint32(chainLength),
)
err := k.InsertHeaders(ctx, randomChain.ChainToBytes())
err := k.InsertHeadersWithHookAndEvents(ctx, randomChain.ChainToBytes())
require.NoError(t, err)
tip := k.GetTipInfo(ctx)
randomChainTipInfo := randomChain.GetTipInfo()
Expand Down
2 changes: 1 addition & 1 deletion x/zoneconcierge/types/btc_timestamp.go
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ func (ts *BTCTimestamp) Verify(
headerBytes := bbn.NewBTCHeaderBytesFromBlockHeader(headerInfo.Header.ToBlockHeader())
headersBytes = append(headersBytes, headerBytes)
}
if err := btclcKeeper.InsertHeaders(ctx, headersBytes); err != nil {
if err := btclcKeeper.InsertHeadersWithHookAndEvents(ctx, headersBytes); err != nil {
return err
}

Expand Down

0 comments on commit c3de831

Please sign in to comment.