Skip to content

Commit

Permalink
go/consensus/cometbft/beacon: Fix GetEpochBlock implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
kostko committed Mar 20, 2024
1 parent d6fb720 commit 65294dd
Showing 1 changed file with 19 additions and 16 deletions.
35 changes: 19 additions & 16 deletions go/consensus/cometbft/beacon/beacon.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,32 +114,35 @@ func (sc *serviceClient) GetEpochBlock(ctx context.Context, epoch beaconAPI.Epoc
}

// Find historic epoch.
//
// TODO: This is really really inefficient, and should be optimized,
// maybe a cache of the last few epochs, or a binary search.
height := consensus.HeightLatest
startHeight, err := sc.backend.GetLastRetainedVersion(ctx)
if err != nil {
return -1, fmt.Errorf("failed to query last retained version: %w", err)
}
endHeight := currentBlk
for {
q, err := sc.querier.QueryAt(ctx, height)
if startHeight == endHeight {
return -1, fmt.Errorf("failed to find historic epoch")
}

midHeight := (endHeight - startHeight) / 2
q, err := sc.querier.QueryAt(ctx, midHeight)
if err != nil {
return -1, fmt.Errorf("failed to query epoch: %w", err)
}

var pastEpoch beaconAPI.EpochTime
pastEpoch, height, err = q.Epoch(ctx)
pastEpoch, _, err = q.Epoch(ctx)
if err != nil {
return -1, fmt.Errorf("failed to query epoch: %w", err)
}

if epoch == pastEpoch {
return height, nil
}

height--

// The initial height can be > 1, but presumably this does not
// matter, since we validate that epoch > sc.baseEpoch.
if pastEpoch == 0 || height <= 1 {
return -1, fmt.Errorf("failed to find historic epoch (minimum: %d requested: %d)", pastEpoch, epoch)
switch {
case epoch == pastEpoch:
return midHeight, nil
case epoch < pastEpoch:
endHeight = midHeight
case epoch > pastEpoch:
startHeight = midHeight
}
}
}
Expand Down

0 comments on commit 65294dd

Please sign in to comment.