Skip to content

Commit

Permalink
Remove LastExecutionHeaderState & Remove execution header from update
Browse files Browse the repository at this point in the history
  • Loading branch information
yrong committed Mar 13, 2024
1 parent ef8c27a commit ab191f9
Show file tree
Hide file tree
Showing 8 changed files with 53 additions and 168 deletions.
25 changes: 0 additions & 25 deletions relayer/chain/parachain/writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -266,31 +266,6 @@ func (wr *ParachainWriter) GetLastBasicChannelNonceByAddress(address common.Addr
return uint64(nonce), nil
}

func (wr *ParachainWriter) GetLastExecutionHeaderState() (state.ExecutionHeader, error) {
key, err := types.CreateStorageKey(wr.conn.Metadata(), "EthereumBeaconClient", "LatestExecutionState", nil, nil)
if err != nil {
return state.ExecutionHeader{}, fmt.Errorf("create storage key for LatestExecutionHeaderState: %w", err)
}

var storageState struct {
BeaconBlockRoot types.H256
BeaconSlot types.U64
BlockHash types.H256
BlockNumber types.U64
}
_, err = wr.conn.API().RPC.State.GetStorageLatest(key, &storageState)
if err != nil {
return state.ExecutionHeader{}, fmt.Errorf("get storage for LatestExecutionHeaderState (err): %w", err)
}

return state.ExecutionHeader{
BeaconBlockRoot: common.Hash(storageState.BeaconBlockRoot),
BeaconSlot: uint64(storageState.BeaconSlot),
BlockHash: common.Hash(storageState.BlockHash),
BlockNumber: uint64(storageState.BlockNumber),
}, nil
}

func (wr *ParachainWriter) GetLastFinalizedHeaderState() (state.FinalizedHeader, error) {
finalizedState, err := wr.GetFinalizedStateByStorageKey("LatestFinalizedBlockRoot")
if err != nil {
Expand Down
8 changes: 0 additions & 8 deletions relayer/relays/beacon/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,14 +67,6 @@ func (b *BeaconCache) SetLastSyncedFinalizedState(finalizedHeaderRoot common.Has
}
}

func (b *BeaconCache) SetLastSyncedExecutionSlot(slot uint64) {
b.mu.Lock()
defer b.mu.Unlock()
if slot > b.LastSyncedExecutionSlot {
b.LastSyncedExecutionSlot = slot
}
}

func (b *BeaconCache) SetInitialCheckpointSlot(slot uint64) {
b.mu.Lock()
defer b.mu.Unlock()
Expand Down
18 changes: 11 additions & 7 deletions relayer/relays/beacon/header/header.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ var ErrFinalizedHeaderNotImported = errors.New("finalized header not imported")
var ErrSyncCommitteeNotImported = errors.New("sync committee not imported")
var ErrSyncCommitteeLatency = errors.New("sync committee latency found")
var ErrExecutionHeaderNotImported = errors.New("execution header not imported")
var ErrBeaconHeaderNotFinalized = errors.New("beacon header not finalized")

type Header struct {
cache *cache.BeaconCache
Expand All @@ -44,22 +45,15 @@ func (h *Header) Sync(ctx context.Context, eg *errgroup.Group) error {
return fmt.Errorf("fetch parachain last finalized header state: %w", err)
}
latestSyncedPeriod := h.syncer.ComputeSyncPeriodAtSlot(lastFinalizedHeaderState.BeaconSlot)
executionHeaderState, err := h.writer.GetLastExecutionHeaderState()
if err != nil {
return fmt.Errorf("fetch last execution hash: %w", err)
}

log.WithFields(log.Fields{
"last_finalized_hash": lastFinalizedHeaderState.BeaconBlockRoot,
"last_finalized_slot": lastFinalizedHeaderState.BeaconSlot,
"last_finalized_period": latestSyncedPeriod,
"last_execution_hash": executionHeaderState.BeaconBlockRoot,
"last_execution_slot": executionHeaderState.BeaconSlot,
}).Info("set cache: Current state")
h.cache.SetLastSyncedFinalizedState(lastFinalizedHeaderState.BeaconBlockRoot, lastFinalizedHeaderState.BeaconSlot)
h.cache.SetInitialCheckpointSlot(lastFinalizedHeaderState.InitialCheckpointSlot)
h.cache.AddCheckPointSlots([]uint64{lastFinalizedHeaderState.BeaconSlot})
h.cache.SetLastSyncedExecutionSlot(executionHeaderState.BeaconSlot)

log.Info("starting to sync finalized headers")

Expand Down Expand Up @@ -288,6 +282,9 @@ func (h *Header) populateClosestCheckpoint(slot uint64) (cache.Proof, error) {
if err != nil {
return checkpoint, fmt.Errorf("get last finalized header for the checkpoint: %w", err)
}
if slot > lastFinalizedHeaderState.BeaconSlot {
return checkpoint, ErrBeaconHeaderNotFinalized
}
if checkpointSlot < lastFinalizedHeaderState.BeaconSlot {
log.WithFields(log.Fields{"calculatedCheckpointSlot": checkpointSlot, "lastFinalizedSlot": lastFinalizedHeaderState.BeaconSlot}).Info("fetch checkpoint on chain backward from history")
historyState, err := h.writer.FindCheckPointBackward(slot)
Expand Down Expand Up @@ -343,6 +340,13 @@ func (h *Header) SyncExecutionHeader(ctx context.Context, blockRoot common.Hash)
if err != nil {
return fmt.Errorf("get beacon header by blockRoot: %w", err)
}
lastFinalizedHeaderState, err := h.writer.GetLastFinalizedHeaderState()
if err != nil {
return fmt.Errorf("fetch last finalized header state: %w", err)
}
if header.Slot > lastFinalizedHeaderState.BeaconSlot {
return ErrBeaconHeaderNotFinalized
}
headerUpdate, err := h.getHeaderUpdateBySlot(header.Slot)
if err != nil {
return fmt.Errorf("get header update by slot with ancestry proof: %w", err)
Expand Down
46 changes: 25 additions & 21 deletions relayer/relays/beacon/header/syncer/api/api_response.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,17 @@ import (

type SyncCommitteePeriodUpdateResponse struct {
Data struct {
AttestedHeader BeaconHeaderWithExecutionHeaderResponse `json:"attested_header"`
NextSyncCommittee SyncCommitteeResponse `json:"next_sync_committee"`
NextSyncCommitteeBranch []string `json:"next_sync_committee_branch"`
FinalizedHeader BeaconHeaderWithExecutionHeaderResponse `json:"finalized_header"`
FinalityBranch []string `json:"finality_branch"`
SyncAggregate SyncAggregateResponse `json:"sync_aggregate"`
SignatureSlot string `json:"signature_slot"`
AttestedHeader struct {
Beacon HeaderResponse `json:"beacon"`
} `json:"attested_header"`
NextSyncCommittee SyncCommitteeResponse `json:"next_sync_committee"`
NextSyncCommitteeBranch []string `json:"next_sync_committee_branch"`
FinalizedHeader struct {
Beacon HeaderResponse `json:"beacon"`
} `json:"finalized_header"`
FinalityBranch []string `json:"finality_branch"`
SyncAggregate SyncAggregateResponse `json:"sync_aggregate"`
SignatureSlot string `json:"signature_slot"`
} `json:"data"`
}

Expand Down Expand Up @@ -74,9 +78,11 @@ type BeaconBlockResponse struct {

type BootstrapResponse struct {
Data struct {
Header BeaconHeaderWithExecutionHeaderResponse `json:"header"`
CurrentSyncCommittee SyncCommitteeResponse `json:"current_sync_committee"`
CurrentSyncCommitteeBranch []string `json:"current_sync_committee_branch"`
Header struct {
Beacon HeaderResponse `json:"beacon"`
} `json:"header"`
CurrentSyncCommittee SyncCommitteeResponse `json:"current_sync_committee"`
CurrentSyncCommitteeBranch []string `json:"current_sync_committee_branch"`
} `json:"data"`
}

Expand Down Expand Up @@ -253,19 +259,17 @@ type ForkResponse struct {
} `json:"data"`
}

type BeaconHeaderWithExecutionHeaderResponse struct {
Beacon HeaderResponse `json:"beacon"`
Execution beaconjson.FullExecutionPayloadHeaderJson `json:"execution,omitempty"`
ExecutionBranch []string `json:"execution_branch,omitempty"`
}

type LatestFinalisedUpdateResponse struct {
Data struct {
AttestedHeader BeaconHeaderWithExecutionHeaderResponse `json:"attested_header"`
FinalizedHeader BeaconHeaderWithExecutionHeaderResponse `json:"finalized_header"`
FinalityBranch []string `json:"finality_branch"`
SyncAggregate SyncAggregateResponse `json:"sync_aggregate"`
SignatureSlot string `json:"signature_slot"`
AttestedHeader struct {
Beacon HeaderResponse `json:"beacon"`
} `json:"attested_header"`
FinalizedHeader struct {
Beacon HeaderResponse `json:"beacon"`
} `json:"finalized_header"`
FinalityBranch []string `json:"finality_branch"`
SyncAggregate SyncAggregateResponse `json:"sync_aggregate"`
SignatureSlot string `json:"signature_slot"`
} `json:"data"`
}

Expand Down
20 changes: 0 additions & 20 deletions relayer/relays/beacon/header/syncer/scale/beacon_scale.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,26 +41,6 @@ type UpdatePayload struct {
FinalityBranch []types.H256
BlockRootsRoot types.H256
BlockRootsBranch []types.H256
ExecutionHeader OptionalExecutionHeader
ExecutionBranch OptionalExecutionBranch
}

type OptionalExecutionHeader struct {
HasValue bool
Value VersionedExecutionPayloadHeader
}

func (o OptionalExecutionHeader) Encode(encoder scale.Encoder) error {
return encoder.EncodeOption(o.HasValue, o.Value)
}

type OptionalExecutionBranch struct {
HasValue bool
Value []types.H256
}

func (o OptionalExecutionBranch) Encode(encoder scale.Encoder) error {
return encoder.EncodeOption(o.HasValue, o.Value)
}

type OptionNextSyncCommitteeUpdatePayload struct {
Expand Down
11 changes: 0 additions & 11 deletions relayer/relays/beacon/header/syncer/scale/json_conversion.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,6 @@ func (p UpdatePayload) ToJSON() json.Update {
NextSyncCommitteeBranch: util.ScaleBranchToString(p.NextSyncCommitteeUpdate.Value.NextSyncCommitteeBranch),
}
}
var executionHeader json.VersionedExecutionPayloadHeader
if p.ExecutionHeader.HasValue {
executionHeader = p.ExecutionHeader.Value.ToJSON()
}

var executionBranch []string
if p.ExecutionBranch.HasValue {
executionBranch = util.ScaleBranchToString(p.ExecutionBranch.Value)
}

return json.Update{
AttestedHeader: p.AttestedHeader.ToJSON(),
Expand All @@ -43,8 +34,6 @@ func (p UpdatePayload) ToJSON() json.Update {
FinalityBranch: util.ScaleBranchToString(p.FinalityBranch),
BlockRootsRoot: p.BlockRootsRoot.Hex(),
BlockRootsBranch: util.ScaleBranchToString(p.BlockRootsBranch),
ExecutionHeader: &executionHeader,
ExecutionBranch: &executionBranch,
}
}

Expand Down
53 changes: 0 additions & 53 deletions relayer/relays/beacon/header/syncer/syncer.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,11 +128,6 @@ func (s *Syncer) GetSyncCommitteePeriodUpdate(from uint64) (scale.Update, error)
return scale.Update{}, fmt.Errorf("beacon header hash tree root: %w", err)
}

executionPayloadHeader, executionBranch, err := s.getExecutionHeaderFromBeaconHeader(committeeUpdateContainer.Data.FinalizedHeader)
if err != nil {
return scale.Update{}, fmt.Errorf("get execution header from beacon header: %w", err)
}

syncCommitteePeriodUpdate := scale.Update{
Payload: scale.UpdatePayload{
AttestedHeader: attestedHeader,
Expand All @@ -149,14 +144,6 @@ func (s *Syncer) GetSyncCommitteePeriodUpdate(from uint64) (scale.Update, error)
FinalityBranch: util.ProofBranchToScale(committeeUpdate.FinalityBranch),
BlockRootsRoot: blockRootsProof.Leaf,
BlockRootsBranch: blockRootsProof.Proof,
ExecutionHeader: scale.OptionalExecutionHeader{
HasValue: true,
Value: executionPayloadHeader,
},
ExecutionBranch: scale.OptionalExecutionBranch{
HasValue: true,
Value: executionBranch,
},
},
FinalizedHeaderBlockRoot: finalizedHeaderBlockRoot,
BlockRootsTree: blockRootsProof.Tree,
Expand Down Expand Up @@ -261,11 +248,6 @@ func (s *Syncer) GetFinalizedUpdate() (scale.Update, error) {
return scale.Update{}, fmt.Errorf("parse signature slot as int: %w", err)
}

executionPayloadHeader, executionBranch, err := s.getExecutionHeaderFromBeaconHeader(finalizedUpdate.Data.FinalizedHeader)
if err != nil {
return scale.Update{}, fmt.Errorf("get execution header from beacon header: %w", err)
}

updatePayload := scale.UpdatePayload{
AttestedHeader: attestedHeader,
SyncAggregate: syncAggregate,
Expand All @@ -277,14 +259,6 @@ func (s *Syncer) GetFinalizedUpdate() (scale.Update, error) {
FinalityBranch: util.ProofBranchToScale(finalizedUpdate.Data.FinalityBranch),
BlockRootsRoot: blockRootsProof.Leaf,
BlockRootsBranch: blockRootsProof.Proof,
ExecutionHeader: scale.OptionalExecutionHeader{
HasValue: true,
Value: executionPayloadHeader,
},
ExecutionBranch: scale.OptionalExecutionBranch{
HasValue: true,
Value: executionBranch,
},
}

return scale.Update{
Expand Down Expand Up @@ -510,30 +484,3 @@ func (s *Syncer) getExecutionHeaderBranch(block state.BeaconBlock) ([]types.H256

return util.BytesBranchToScale(proof.Hashes), nil
}

func (s *Syncer) getExecutionHeaderFromBeaconHeader(header api.BeaconHeaderWithExecutionHeaderResponse) (scale.VersionedExecutionPayloadHeader, []types.H256, error) {
var versionedExecutionPayloadHeader scale.VersionedExecutionPayloadHeader
var executionBranch []types.H256
slot, err := strconv.ParseUint(header.Beacon.Slot, 10, 64)
if err != nil {
return versionedExecutionPayloadHeader, executionBranch, fmt.Errorf("invalid slot in header: %w", err)
}
if s.DenebForked(slot) {
executionPayloadScale, err := api.DenebJsonExecutionPayloadHeaderToScale(&header.Execution)
if err != nil {
return versionedExecutionPayloadHeader, executionBranch, fmt.Errorf("convert payloadHeader to scale: %w", err)
}
versionedExecutionPayloadHeader = scale.VersionedExecutionPayloadHeader{Deneb: &executionPayloadScale}
} else {
executionPayloadScale, err := api.CapellaJsonExecutionPayloadHeaderToScale(&header.Execution)
if err != nil {
return versionedExecutionPayloadHeader, executionBranch, fmt.Errorf("convert payloadHeader to scale: %w", err)
}
versionedExecutionPayloadHeader = scale.VersionedExecutionPayloadHeader{Capella: &executionPayloadScale}
}
if len(header.ExecutionBranch) == 0 {
return versionedExecutionPayloadHeader, executionBranch, fmt.Errorf("invalid ExecutionBranch in header: %w", err)
}
executionBranch = util.ProofBranchToScale(header.ExecutionBranch)
return versionedExecutionPayloadHeader, executionBranch, nil
}
40 changes: 17 additions & 23 deletions relayer/relays/execution/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,45 +91,37 @@ func (r *Relay) Start(ctx context.Context, eg *errgroup.Group) error {
select {
case <-ctx.Done():
return nil
case <-time.After(12 * time.Second):
case <-time.After(6 * time.Second):
log.WithFields(log.Fields{
"channelId": r.config.Source.ChannelID,
}).Info("Polling Nonces")

executionHeaderState, err := writer.GetLastExecutionHeaderState()
if err != nil {
return err
}

paraNonce, err := r.fetchLatestParachainNonce()
if err != nil {
return err
}

if executionHeaderState.BlockNumber == 0 {
log.WithFields(log.Fields{
"channelId": r.config.Source.ChannelID,
}).Info("Beacon execution state syncing not started, waiting...")
continue
}

ethNonce, err := r.fetchEthereumNonce(ctx, executionHeaderState.BlockNumber)
ethNonce, err := r.fetchEthereumNonce(ctx)
if err != nil {
return err
}

log.WithFields(log.Fields{
"ethBlockNumber": executionHeaderState.BlockNumber,
"channelId": types.H256(r.config.Source.ChannelID).Hex(),
"paraNonce": paraNonce,
"ethNonce": ethNonce,
"channelId": types.H256(r.config.Source.ChannelID).Hex(),
"paraNonce": paraNonce,
"ethNonce": ethNonce,
}).Info("Polled Nonces")

if paraNonce == ethNonce {
continue
}

events, err := r.findEvents(ctx, executionHeaderState.BlockNumber, paraNonce+1)
blockNumber, err := ethconn.Client().BlockNumber(ctx)
if err != nil {
return fmt.Errorf("get last block number: %w", err)
}

events, err := r.findEvents(ctx, blockNumber, paraNonce+1)
if err != nil {
return fmt.Errorf("find events: %w", err)
}
Expand Down Expand Up @@ -163,6 +155,10 @@ func (r *Relay) Start(ctx context.Context, eg *errgroup.Group) error {

// ParentBeaconRoot in https://eips.ethereum.org/EIPS/eip-4788 from Deneb onward
err = beaconHeader.SyncExecutionHeader(ctx, *blockHeader.ParentBeaconRoot)
if err == header.ErrBeaconHeaderNotFinalized {
logger.Warn("beacon header not finalized, just skipped")
continue
}
if err != nil {
return fmt.Errorf("sync beacon header: %w", err)
}
Expand Down Expand Up @@ -208,11 +204,9 @@ func (r *Relay) fetchLatestParachainNonce() (uint64, error) {
return paraNonce, nil
}

func (r *Relay) fetchEthereumNonce(ctx context.Context, blockNumber uint64) (uint64, error) {
func (r *Relay) fetchEthereumNonce(ctx context.Context) (uint64, error) {
opts := bind.CallOpts{
Pending: false,
BlockNumber: new(big.Int).SetUint64(blockNumber),
Context: ctx,
Context: ctx,
}
_, ethOutboundNonce, err := r.gatewayContract.ChannelNoncesOf(&opts, r.config.Source.ChannelID)
if err != nil {
Expand Down

0 comments on commit ab191f9

Please sign in to comment.