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

Sync execution update on demand #1154

Merged
merged 91 commits into from
Mar 14, 2024
Merged
Show file tree
Hide file tree
Changes from 83 commits
Commits
Show all changes
91 commits
Select commit Hold shift + click to select a range
387e085
Update for Dencun
yrong Sep 21, 2023
846065a
build geth&lodestar from source
yrong Sep 25, 2023
65272d4
Fix makeTrie
yrong Sep 25, 2023
d2f0d66
Merge branch 'main' into ron/dencun
yrong Nov 21, 2023
63b0f07
Update go ethereum to v1.13.5
yrong Nov 21, 2023
faf5d01
Update packages & Speedup e2e setup
yrong Nov 21, 2023
c179311
Update lodestar to v1.12.0
yrong Nov 21, 2023
d728f48
Remove unused
yrong Nov 21, 2023
28f23dd
Remove unrelated changes
yrong Nov 21, 2023
cce7714
Ignore build geth when binary exist
yrong Nov 21, 2023
48cc44f
Cleanup for deprecated ethashproof
yrong Nov 22, 2023
fe1e191
Update with VersionedExecutionPayloadHeader
yrong Nov 22, 2023
d37a736
Fix breaking tests
yrong Nov 22, 2023
1aa5a0a
Merge branch 'main' into ron/dencun
yrong Dec 1, 2023
545e267
Update node package
yrong Dec 1, 2023
1c5b33d
Update git modules
yrong Dec 1, 2023
647f57e
Sync packages with nix
yrong Dec 1, 2023
40daff1
Merge branch 'main' of https://github.com/Snowfork/snowbridge into ro…
yrong Dec 4, 2023
565cd83
Update sdk
yrong Dec 4, 2023
7414746
Update contract binding
yrong Dec 5, 2023
70d017b
More cleanup
yrong Dec 5, 2023
585dc78
For deneb(1)
yrong Dec 5, 2023
ba67bf3
For deneb(2)
yrong Dec 5, 2023
f9f7458
Update sdk
yrong Dec 5, 2023
d542799
For deneb(3)
yrong Dec 5, 2023
904e97a
Update sdk
yrong Dec 5, 2023
99c0304
For deneb(4)
yrong Dec 5, 2023
8a50ced
Enable deneb for local setup
yrong Dec 5, 2023
e5c2381
Fix tests
yrong Dec 5, 2023
29a2afe
Fix BeaconStateDeneb & more tests
yrong Dec 6, 2023
3f6cb38
Merge branch 'main' into ron/dencun
yrong Dec 6, 2023
4aae19a
Generate test fixture for Deneb and more tests accordingly
yrong Dec 7, 2023
79e79dd
Merge branch 'main' into ron/dencun
yrong Dec 7, 2023
ed69a35
Fix parse empty field
yrong Dec 7, 2023
1c1ca20
Setup for switchover test
yrong Dec 7, 2023
8f95e8a
Test workflow specific for deneb
yrong Dec 7, 2023
ba5957e
Ignore change detect building polkadot binary
yrong Dec 11, 2023
9673b21
Encode with error handling
yrong Dec 11, 2023
e767e6e
Fix format
yrong Dec 11, 2023
e5120e8
Merge branch 'main' into ron/dencun
yrong Dec 13, 2023
6a38f79
Update lodestar
yrong Dec 14, 2023
c246f70
Improve scripts setting up nodes for production
yrong Dec 14, 2023
6892678
Merge branch 'main' into ron/dencun
yrong Dec 27, 2023
b76a4dd
Sync execution update on demand
yrong Dec 31, 2023
bdec747
Merge branch 'main' into ron/dencun
yrong Jan 11, 2024
99f5a6d
Fix import
yrong Jan 11, 2024
3580c4d
Reorganize deneb primitives
yrong Jan 11, 2024
d1a5b86
Update go mod
yrong Jan 12, 2024
ad65ebd
Fix format
yrong Jan 12, 2024
53e4fa6
Remove obsolete
yrong Jan 12, 2024
d069f97
Fix import
yrong Jan 12, 2024
da3d338
Merge branch 'main' into ron/dencun
yrong Jan 12, 2024
58a28bd
Merge branch 'main' into ron/dencun
yrong Jan 17, 2024
61dadc9
Fix the deneb ForkVersion
yrong Jan 17, 2024
328d541
Upgrade geth and lodestar
yrong Jan 17, 2024
9d633e2
Merge branch 'ron/dencun' into ron/execution-update-on-demand
yrong Jan 18, 2024
d37ee40
Download geth release to replace the nix default
yrong Jan 18, 2024
d4bc62b
Naming consistently
yrong Jan 18, 2024
0c14e49
Update lodestar with the mock hack
yrong Jan 18, 2024
0ed243a
Fix generate mainnet fixture
yrong Jan 18, 2024
810fa47
Merge branch 'ron/dencun' into ron/execution-update-on-demand
yrong Jan 18, 2024
53c6fb8
Remove fixture unused
yrong Jan 18, 2024
4cdfa96
Backward compatible
yrong Jan 18, 2024
b5ea6b2
Check execution_branch
yrong Jan 18, 2024
6bd6723
Remove build geth
yrong Jan 18, 2024
b892f77
Remove cross check
yrong Jan 18, 2024
a646a4e
sync all lagging periods
yrong Jan 18, 2024
ee71d1a
Clean up
yrong Jan 18, 2024
79247a2
More refactoring
yrong Jan 18, 2024
49800bd
Cleanup scripts
yrong Jan 18, 2024
cdc7165
Update sdk
yrong Jan 18, 2024
072c3f0
Merge branch 'main' into ron/execution-update-on-demand
yrong Jan 19, 2024
c42d0af
Ignore go.work
yrong Jan 19, 2024
5bc2526
Rename function
yrong Jan 19, 2024
f465995
Merge branch 'main' into ron/execution-update-on-demand
yrong Jan 24, 2024
dd866bb
Fix test
yrong Jan 24, 2024
afe2b43
Fix populate checkpoint
yrong Jan 24, 2024
018c565
Fix smoke test
yrong Jan 24, 2024
775e56a
Merge branch 'main' into ron/execution-update-on-demand
yrong Jan 28, 2024
3f0f027
Merge branch 'main' into ron/execution-update-on-demand
yrong Jan 30, 2024
1d67967
Merge branch 'main' into ron/execution-update-on-demand
yrong Feb 6, 2024
7b5e1e3
Update lodestar & polkadot-sdk
yrong Feb 6, 2024
e8557c7
Merge branch 'main' into ron/execution-update-on-demand
yrong Mar 12, 2024
af93289
Check execution already exist before submit
yrong Mar 12, 2024
888ce4d
Update relayer/cmd/generate_beacon_data.go
yrong Mar 12, 2024
5213ba8
Update relayer/relays/beacon/header/header.go
yrong Mar 12, 2024
ddf7e6a
Rename to OptionalExecutionHeader
yrong Mar 12, 2024
cd85cb9
Rename import alias
yrong Mar 12, 2024
03bdb5c
Improve logs
yrong Mar 12, 2024
ef8c27a
Fetch checkpoint on chain from history
yrong Mar 12, 2024
ab191f9
Remove LastExecutionHeaderState & Remove execution header from update
yrong Mar 13, 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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,5 @@ contracts/beefy-state.json

go/
gocache/
go.work*
control/target/
3 changes: 2 additions & 1 deletion relayer/chain/ethereum/header.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@ package ethereum

import (
"fmt"
"math/big"

etypes "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/rlp"
"github.com/snowfork/go-substrate-rpc-client/v4/scale"
types "github.com/snowfork/go-substrate-rpc-client/v4/types"
"math/big"
)

type HeaderID struct {
Expand Down
21 changes: 21 additions & 0 deletions relayer/chain/parachain/writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -385,3 +385,24 @@ func (wr *ParachainWriter) getNumberFromParachain(pallet, storage string) (uint6

return uint64(number), nil
}

func (wr *ParachainWriter) GetCompactExecutionHeaderStateByBlockHash(blockHash types.H256) (state.CompactExecutionHeaderState, error) {
var headerState state.CompactExecutionHeaderState
key, err := types.CreateStorageKey(wr.conn.Metadata(), "EthereumBeaconClient", "ExecutionHeaders", blockHash[:], nil)
if err != nil {
return headerState, fmt.Errorf("create storage key for ExecutionHeaders: %w", err)
}

var compactExecutionHeader scale.CompactExecutionHeader
_, err = wr.conn.API().RPC.State.GetStorageLatest(key, &compactExecutionHeader)
if err != nil {
return headerState, fmt.Errorf("get storage for ExecutionHeaders (err): %w", err)
}
headerState = state.CompactExecutionHeaderState{
ParentHash: common.Hash(compactExecutionHeader.ParentHash),
BlockNumber: uint64(compactExecutionHeader.BlockNumber.Int64()),
StateRoot: common.Hash(compactExecutionHeader.StateRoot),
ReceiptsRoot: common.Hash(compactExecutionHeader.ReceiptsRoot),
}
return headerState, nil
}
8 changes: 4 additions & 4 deletions relayer/cmd/generate_beacon_data.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func generateBeaconCheckpointCmd() *cobra.Command {
}

cmd.Flags().String("url", "http://127.0.0.1:9596", "Beacon URL")
cmd.Flags().Bool("export_json", false, "Export Json")
cmd.Flags().Bool("export-json", false, "Export Json")

return cmd
}
Expand Down Expand Up @@ -115,9 +115,9 @@ func generateBeaconCheckpoint(cmd *cobra.Command, _ []string) error {
if err != nil {
return fmt.Errorf("get initial sync: %w", err)
}
exportJson, err := cmd.Flags().GetBool("export_json")
exportJson, err := cmd.Flags().GetBool("export-json")
if err != nil {
return err
return fmt.Errorf("get initial sync: %w", err)
yrong marked this conversation as resolved.
Show resolved Hide resolved
}
if exportJson {
initialSync := checkPointScale.ToJSON()
Expand Down Expand Up @@ -282,7 +282,7 @@ func generateBeaconTestFixture(cmd *cobra.Command, _ []string) error {
BlockRootsTree: finalizedUpdateAfterMessage.BlockRootsTree,
Slot: uint64(finalizedUpdateAfterMessage.Payload.FinalizedHeader.Slot),
}
headerUpdateScale, err := s.GetNextHeaderUpdateBySlotWithCheckpoint(beaconBlockSlot, &checkPoint)
headerUpdateScale, err := s.GetHeaderUpdateBySlotWithCheckpoint(beaconBlockSlot, &checkPoint)
if err != nil {
return fmt.Errorf("get header update: %w", err)
}
Expand Down
147 changes: 40 additions & 107 deletions relayer/relays/beacon/header/header.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@ import (
"fmt"
"time"

"github.com/snowfork/go-substrate-rpc-client/v4/types"
"github.com/ethereum/go-ethereum/common"
"github.com/snowfork/snowbridge/relayer/relays/beacon/config"
"github.com/snowfork/snowbridge/relayer/relays/beacon/header/syncer/scale"

log "github.com/sirupsen/logrus"
"github.com/snowfork/go-substrate-rpc-client/v4/types"
"github.com/snowfork/snowbridge/relayer/chain/parachain"
"github.com/snowfork/snowbridge/relayer/relays/beacon/cache"
"github.com/snowfork/snowbridge/relayer/relays/beacon/header/syncer"
Expand Down Expand Up @@ -186,11 +187,6 @@ func (h *Header) SyncFinalizedHeader(ctx context.Context) error {
}

func (h *Header) SyncHeaders(ctx context.Context) error {
err := h.SyncExecutionHeaders(ctx)
if err != nil {
return err
}

hasChanged, err := h.syncer.HasFinalizedHeaderChanged(h.cache.Finalized.LastSyncedHash)
if err != nil {
return err
Expand All @@ -208,79 +204,12 @@ func (h *Header) SyncHeaders(ctx context.Context) error {
return nil
}

func (h *Header) SyncExecutionHeaders(ctx context.Context) error {
fromSlot := h.cache.LastSyncedExecutionSlot
// SyncExecutionHeaders at least from initial checkpoint
if fromSlot <= h.cache.InitialCheckpointSlot {
fromSlot = h.cache.InitialCheckpointSlot
}
toSlot := h.cache.Finalized.LastSyncedSlot
if fromSlot >= toSlot {
log.WithFields(log.Fields{
"fromSlot": fromSlot,
"toSlot": toSlot,
}).Info("execution headers sync up to date with last finalized header")
return nil
}
log.WithFields(log.Fields{
"fromSlot": fromSlot,
"fromEpoch": h.syncer.ComputeEpochAtSlot(fromSlot),
"toSlot": toSlot,
"toEpoch": h.syncer.ComputeEpochAtSlot(toSlot),
"totalSlots": toSlot - fromSlot,
}).Info("starting to back-fill headers")

var headersToSync []scale.HeaderUpdatePayload

// start syncing at next block after last synced block
currentSlot := fromSlot
headerUpdate, err := h.getNextHeaderUpdateBySlot(currentSlot)
if err != nil {
return fmt.Errorf("get next header update by slot with ancestry proof: %w", err)
}
currentSlot = uint64(headerUpdate.Header.Slot)

for currentSlot <= toSlot {
log.WithFields(log.Fields{
"currentSlot": currentSlot,
}).Info("fetching next header at slot")

var nextHeaderUpdate scale.HeaderUpdatePayload
if currentSlot >= toSlot {
// Just construct an empty update so to break the loop
nextHeaderUpdate = scale.HeaderUpdatePayload{Header: scale.BeaconHeader{Slot: types.U64(toSlot + 1)}}
} else {
// To get the sync witness for the current synced header. This header
// will be used as the next update.
nextHeaderUpdate, err = h.getNextHeaderUpdateBySlot(currentSlot)
if err != nil {
return fmt.Errorf("get next header update by slot with ancestry proof: %w", err)
}
}

headersToSync = append(headersToSync, headerUpdate)
// last slot to be synced, sync headers
if currentSlot >= toSlot {
err = h.batchSyncHeaders(ctx, headersToSync)
if err != nil {
return fmt.Errorf("batch sync headers failed: %w", err)
}
}
headerUpdate = nextHeaderUpdate
currentSlot = uint64(headerUpdate.Header.Slot)
}
// waiting for all batch calls to be executed on chain
err = h.waitingForBatchCallFinished(toSlot)
if err != nil {
return err
}
h.cache.SetLastSyncedExecutionSlot(toSlot)
return nil
}

func (h *Header) syncLaggingSyncCommitteePeriods(ctx context.Context, latestSyncedPeriod, currentSyncPeriod uint64) error {
// sync for the next period
periodsToSync := []uint64{latestSyncedPeriod + 1}
// sync for all missing periods
periodsToSync := []uint64{}
for i := latestSyncedPeriod + 1; i <= currentSyncPeriod; i++ {
periodsToSync = append(periodsToSync, i)
}
claravanstaden marked this conversation as resolved.
Show resolved Hide resolved

// For initialPeriod special handling here to sync it again for nextSyncCommittee which is not included in InitCheckpoint
if h.isInitialSyncPeriod() {
Expand Down Expand Up @@ -353,6 +282,13 @@ func (h *Header) populateClosestCheckpoint(slot uint64) (cache.Proof, error) {
checkpointSlot := checkpoint.Slot
if checkpointSlot == 0 {
checkpointSlot = h.syncer.CalculateNextCheckpointSlot(slot)
lastFinalizedHeaderState, err := h.writer.GetLastFinalizedHeaderState()
if err != nil {
return cache.Proof{}, fmt.Errorf("fetch parachain last finalized header state: %w", err)
}
if checkpointSlot > lastFinalizedHeaderState.BeaconSlot {
checkpointSlot = lastFinalizedHeaderState.BeaconSlot
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a comment here to explain why this check.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

log.WithFields(log.Fields{"calculatedCheckpointSlot": checkpointSlot}).Info("checkpoint slot not available, try with slot in next sync period instead")
}
err := h.populateFinalizedCheckpoint(checkpointSlot)
Expand All @@ -377,8 +313,7 @@ func (h *Header) populateClosestCheckpoint(slot uint64) (cache.Proof, error) {
return checkpoint, nil
}

func (h *Header) getNextHeaderUpdateBySlot(slot uint64) (scale.HeaderUpdatePayload, error) {
slot = slot + 1
func (h *Header) getHeaderUpdateBySlot(slot uint64) (scale.HeaderUpdatePayload, error) {
header, err := h.syncer.FindBeaconHeaderWithBlockIncluded(slot)
if err != nil {
return scale.HeaderUpdatePayload{}, fmt.Errorf("get next beacon header with block included: %w", err)
Expand All @@ -394,14 +329,33 @@ func (h *Header) getNextHeaderUpdateBySlot(slot uint64) (scale.HeaderUpdatePaylo
return h.syncer.GetHeaderUpdate(blockRoot, &checkpoint)
}

func (h *Header) batchSyncHeaders(ctx context.Context, headerUpdates []scale.HeaderUpdatePayload) error {
headerUpdatesInf := make([]interface{}, len(headerUpdates))
for i, v := range headerUpdates {
headerUpdatesInf[i] = v
func (h *Header) SyncExecutionHeader(ctx context.Context, blockRoot common.Hash) error {
header, err := h.syncer.Client.GetHeader(blockRoot)
if err != nil {
return fmt.Errorf("get beacon header by blockRoot: %w", err)
}
err := h.writer.BatchCall(ctx, "EthereumBeaconClient.submit_execution_header", headerUpdatesInf)
headerUpdate, err := h.getHeaderUpdateBySlot(header.Slot)
if err != nil {
return err
return fmt.Errorf("get header update by slot with ancestry proof: %w", err)
}
err = h.writer.WriteToParachainAndWatch(ctx, "EthereumBeaconClient.submit_execution_header", headerUpdate)
if err != nil {
return fmt.Errorf("submit_execution_header: %w", err)
}
var blockHash types.H256
if headerUpdate.ExecutionHeader.Deneb != nil {
blockHash = headerUpdate.ExecutionHeader.Deneb.BlockHash
} else if headerUpdate.ExecutionHeader.Capella != nil {
blockHash = headerUpdate.ExecutionHeader.Capella.BlockHash
} else {
return fmt.Errorf("invalid blockHash in headerUpdate")
}
compactExecutionHeaderState, err := h.writer.GetCompactExecutionHeaderStateByBlockHash(blockHash)
if err != nil {
return fmt.Errorf("get compactExecutionHeaderState by blockHash: %w", err)
}
if compactExecutionHeaderState.BlockNumber == 0 {
return fmt.Errorf("invalid compactExecutionHeaderState")
yrong marked this conversation as resolved.
Show resolved Hide resolved
}
return nil
}
Expand All @@ -411,24 +365,3 @@ func (h *Header) isInitialSyncPeriod() bool {
lastFinalizedPeriod := h.syncer.ComputeSyncPeriodAtSlot(h.cache.Finalized.LastSyncedSlot)
return initialPeriod == lastFinalizedPeriod
}

func (h *Header) waitingForBatchCallFinished(toSlot uint64) error {
batchCallFinished := false
cnt := 0
for cnt <= 12 {
executionHeaderState, err := h.writer.GetLastExecutionHeaderState()
if err != nil {
return fmt.Errorf("fetch last execution hash: %w", err)
}
if executionHeaderState.BeaconSlot == toSlot {
batchCallFinished = true
break
}
time.Sleep(6 * time.Second)
cnt++
}
if !batchCallFinished {
return ErrExecutionHeaderNotImported
}
return nil
}
25 changes: 11 additions & 14 deletions relayer/relays/beacon/header/syncer/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,14 @@ import (
"github.com/snowfork/snowbridge/relayer/relays/util"
)

const (
ConstructRequestErrorMessage = "construct header request"
DoHTTPRequestErrorMessage = "do http request"
HTTPStatusNotOKErrorMessage = "http status not ok"
ReadResponseBodyErrorMessage = "read response body"
UnmarshalBodyErrorMessage = "unmarshal body"
)

var (
ErrNotFound = errors.New("not found")
ErrSyncCommitteeUpdateNotAvailable = errors.New("no sync committee update available")
ConstructRequestErrorMessage = "construct header request"
DoHTTPRequestErrorMessage = "do http request"
HTTPStatusNotOKErrorMessage = "http status not ok"
ReadResponseBodyErrorMessage = "read response body"
UnmarshalBodyErrorMessage = "unmarshal body"
)

type BeaconClient struct {
Expand All @@ -42,30 +39,30 @@ func NewBeaconClient(endpoint string, slotsInEpoch uint64) *BeaconClient {
}

func (b *BeaconClient) GetBootstrap(blockRoot common.Hash) (BootstrapResponse, error) {
var response BootstrapResponse
req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/eth/v1/beacon/light_client/bootstrap/%s", b.endpoint, blockRoot), nil)
if err != nil {
return BootstrapResponse{}, fmt.Errorf("%s: %w", ConstructRequestErrorMessage, err)
return response, fmt.Errorf("%s: %w", ConstructRequestErrorMessage, err)
}

req.Header.Set("accept", "application/json")
res, err := b.httpClient.Do(req)
if err != nil {
return BootstrapResponse{}, fmt.Errorf("%s: %w", DoHTTPRequestErrorMessage, err)
return response, fmt.Errorf("%s: %w", DoHTTPRequestErrorMessage, err)
}

if res.StatusCode != http.StatusOK {
return BootstrapResponse{}, fmt.Errorf("%s: %d", HTTPStatusNotOKErrorMessage, res.StatusCode)
return response, fmt.Errorf("%s: %d", HTTPStatusNotOKErrorMessage, res.StatusCode)
}

bodyBytes, err := io.ReadAll(res.Body)
if err != nil {
return BootstrapResponse{}, fmt.Errorf("%s: %w", ReadResponseBodyErrorMessage, err)
return response, fmt.Errorf("%s: %w", ReadResponseBodyErrorMessage, err)
}

var response BootstrapResponse
err = json.Unmarshal(bodyBytes, &response)
if err != nil {
return BootstrapResponse{}, fmt.Errorf("%s: %w", UnmarshalBodyErrorMessage, err)
return response, fmt.Errorf("%s: %w", UnmarshalBodyErrorMessage, err)
}

return response, nil
Expand Down
Loading