Skip to content

Commit

Permalink
minor functions relocation across files
Browse files Browse the repository at this point in the history
  • Loading branch information
abi87 committed Dec 11, 2024
1 parent 6b1e3c9 commit 7f4c6a2
Show file tree
Hide file tree
Showing 3 changed files with 178 additions and 146 deletions.
149 changes: 3 additions & 146 deletions beacon/blockchain/process.go → beacon/blockchain/finalize_block.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,132 +22,16 @@ package blockchain

import (
"context"
"encoding/json"
"time"

"github.com/berachain/beacon-kit/consensus/cometbft/service/encoding"
"github.com/berachain/beacon-kit/consensus/types"
"github.com/berachain/beacon-kit/errors"
"github.com/berachain/beacon-kit/primitives/math"
"github.com/berachain/beacon-kit/primitives/transition"
cmtabci "github.com/cometbft/cometbft/abci/types"
sdk "github.com/cosmos/cosmos-sdk/types"
)

const (
// BeaconBlockTxIndex represents the index of the beacon block transaction.
// It is the first transaction in the tx list.
BeaconBlockTxIndex uint = iota
// BlobSidecarsTxIndex represents the index of the blob sidecar transaction.
// It follows the beacon block transaction in the tx list.
BlobSidecarsTxIndex
)

// ProcessGenesisData processes the genesis state and initializes the beacon
// state.
func (s *Service[
_, _, _, _, _, _, _, _, _, _, _, _, GenesisT, _, _, _,
]) ProcessGenesisData(
ctx context.Context,
bytes []byte,
) (transition.ValidatorUpdates, error) {
genesisData := *new(GenesisT)
if err := json.Unmarshal(bytes, &genesisData); err != nil {
s.logger.Error("Failed to unmarshal genesis data", "error", err)
return nil, err
}
return s.stateProcessor.InitializePreminedBeaconStateFromEth1(
s.storageBackend.StateFromContext(ctx),
genesisData.GetDeposits(),
genesisData.GetExecutionPayloadHeader(),
genesisData.GetForkVersion(),
)
}

func (s *Service[
_, _, ConsensusBlockT, BeaconBlockT, _, BeaconBlockHeaderT, _, _, _,
_, _, _, GenesisT, ConsensusSidecarsT, BlobSidecarsT, _,
]) ProcessProposal(
ctx sdk.Context,
req *cmtabci.ProcessProposalRequest,
) (*cmtabci.ProcessProposalResponse, error) {
// Decode the beacon block.
blk, err := encoding.
UnmarshalBeaconBlockFromABCIRequest[BeaconBlockT](
req,
BeaconBlockTxIndex,
s.chainSpec.ActiveForkVersionForSlot(math.U64(req.Height)),
)
if err != nil {
return createProcessProposalResponse(errors.WrapNonFatal(err))
}
var consensusBlk *types.ConsensusBlock[BeaconBlockT]
consensusBlk = consensusBlk.New(
blk,
req.GetProposerAddress(),
req.GetTime(),
)

// Decode the blob sidecars.
sidecars, err := encoding.
UnmarshalBlobSidecarsFromABCIRequest[BlobSidecarsT](
req,
BlobSidecarsTxIndex,
)
if err != nil {
return createProcessProposalResponse(errors.WrapNonFatal(err))
}

var consensusSidecars *types.ConsensusSidecars[
BlobSidecarsT,
BeaconBlockHeaderT,
]
consensusSidecars = consensusSidecars.New(
sidecars,
blk.GetHeader(),
)

if !sidecars.IsNil() && sidecars.Len() > 0 {
s.logger.Info("Received incoming blob sidecars")

// TODO: Clean this up once we remove generics.
c := convertConsensusSidecars[
ConsensusSidecarsT,
BlobSidecarsT,
BeaconBlockHeaderT,
](consensusSidecars)

// Verify the blobs and ensure they match the local state.
err = s.blobProcessor.VerifySidecars(c)
if err != nil {
s.logger.Error(
"rejecting incoming blob sidecars",
"reason", err,
)
return createProcessProposalResponse(errors.WrapNonFatal(err))
}

s.logger.Info(
"Blob sidecars verification succeeded - accepting incoming blob sidecars",
"num_blobs",
sidecars.Len(),
)
}

err = s.VerifyIncomingBlock(
ctx,
consensusBlk.GetBeaconBlock(),
consensusBlk.GetConsensusTime(),
consensusBlk.GetProposerAddress(),
)
if err != nil {
s.logger.Error("failed to verify incoming block", "error", err)
return createProcessProposalResponse(errors.WrapNonFatal(err))
}

return createProcessProposalResponse(nil)
}

func (s *Service[
_, _, ConsensusBlockT, BeaconBlockT, _, BeaconBlockHeaderT, _, _, _,
_, _, _, GenesisT, ConsensusSidecarsT, BlobSidecarsT, _,
Expand Down Expand Up @@ -186,7 +70,7 @@ func (s *Service[
panic("failed to convert consensusBlk to ConsensusBlockT")
}

valUpdates, finalizeErr = s.processBeaconBlock(ctx, val)
valUpdates, finalizeErr = s.finalizeBeaconBlock(ctx, val)
if finalizeErr != nil {
s.logger.Error("Failed to process verified beacon block",
"error", finalizeErr,
Expand All @@ -204,11 +88,11 @@ func (s *Service[
return valUpdates, nil
}

// processBeaconBlock receives an incoming beacon block, it first validates
// finalizeBeaconBlock receives an incoming beacon block, it first validates
// and then processes the block.
func (s *Service[
_, _, ConsensusBlockT, _, _, _, _, _, _, _, _, _, _, _, _, _,
]) processBeaconBlock(
]) finalizeBeaconBlock(
ctx context.Context,
blk ConsensusBlockT,
) (transition.ValidatorUpdates, error) {
Expand Down Expand Up @@ -301,30 +185,3 @@ func (s *Service[
)
return valUpdates, err
}

// createResponse generates the appropriate ProcessProposalResponse based on the
// error.
func createProcessProposalResponse(
err error,
) (*cmtabci.ProcessProposalResponse, error) {
status := cmtabci.PROCESS_PROPOSAL_STATUS_REJECT
if !errors.IsFatal(err) {
status = cmtabci.PROCESS_PROPOSAL_STATUS_ACCEPT
err = nil
}
return &cmtabci.ProcessProposalResponse{Status: status}, err
}

func convertConsensusSidecars[
ConsensusSidecarsT any,
BlobSidecarsT any,
BeaconBlockHeaderT any,
](
cSidecars *types.ConsensusSidecars[BlobSidecarsT, BeaconBlockHeaderT],
) ConsensusSidecarsT {
val, ok := any(cSidecars).(ConsensusSidecarsT)
if !ok {
panic("failed to convert conesensusSidecars to ConsensusSidecarsT")
}
return val
}
49 changes: 49 additions & 0 deletions beacon/blockchain/init_chain.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// SPDX-License-Identifier: BUSL-1.1
//
// Copyright (C) 2024, Berachain Foundation. All rights reserved.
// Use of this software is governed by the Business Source License included
// in the LICENSE file of this repository and at www.mariadb.com/bsl11.
//
// ANY USE OF THE LICENSED WORK IN VIOLATION OF THIS LICENSE WILL AUTOMATICALLY
// TERMINATE YOUR RIGHTS UNDER THIS LICENSE FOR THE CURRENT AND ALL OTHER
// VERSIONS OF THE LICENSED WORK.
//
// THIS LICENSE DOES NOT GRANT YOU ANY RIGHT IN ANY TRADEMARK OR LOGO OF
// LICENSOR OR ITS AFFILIATES (PROVIDED THAT YOU MAY USE A TRADEMARK OR LOGO OF
// LICENSOR AS EXPRESSLY REQUIRED BY THIS LICENSE).
//
// TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
// AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
// EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
// TITLE.

package blockchain

import (
"context"
"encoding/json"

"github.com/berachain/beacon-kit/primitives/transition"
)

// ProcessGenesisData processes the genesis state and initializes the beacon
// state.
func (s *Service[
_, _, _, _, _, _, _, _, _, _, _, _, GenesisT, _, _, _,
]) ProcessGenesisData(
ctx context.Context,
bytes []byte,
) (transition.ValidatorUpdates, error) {
genesisData := *new(GenesisT)
if err := json.Unmarshal(bytes, &genesisData); err != nil {
s.logger.Error("Failed to unmarshal genesis data", "error", err)
return nil, err
}
return s.stateProcessor.InitializePreminedBeaconStateFromEth1(
s.storageBackend.StateFromContext(ctx),
genesisData.GetDeposits(),
genesisData.GetExecutionPayloadHeader(),
genesisData.GetForkVersion(),
)
}
126 changes: 126 additions & 0 deletions beacon/blockchain/receive.go → beacon/blockchain/process_proposal.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,111 @@ import (
"time"

payloadtime "github.com/berachain/beacon-kit/beacon/payload-time"
"github.com/berachain/beacon-kit/consensus/cometbft/service/encoding"
"github.com/berachain/beacon-kit/consensus/types"
engineerrors "github.com/berachain/beacon-kit/engine-primitives/errors"
"github.com/berachain/beacon-kit/errors"
"github.com/berachain/beacon-kit/primitives/math"
"github.com/berachain/beacon-kit/primitives/transition"
cmtabci "github.com/cometbft/cometbft/abci/types"
sdk "github.com/cosmos/cosmos-sdk/types"
)

const (
// BeaconBlockTxIndex represents the index of the beacon block transaction.
// It is the first transaction in the tx list.
BeaconBlockTxIndex uint = iota
// BlobSidecarsTxIndex represents the index of the blob sidecar transaction.
// It follows the beacon block transaction in the tx list.
BlobSidecarsTxIndex
)

func (s *Service[
_, _, ConsensusBlockT, BeaconBlockT, _, BeaconBlockHeaderT, _, _, _,
_, _, _, GenesisT, ConsensusSidecarsT, BlobSidecarsT, _,
]) ProcessProposal(
ctx sdk.Context,
req *cmtabci.ProcessProposalRequest,
) (*cmtabci.ProcessProposalResponse, error) {
// Decode the beacon block.
blk, err := encoding.
UnmarshalBeaconBlockFromABCIRequest[BeaconBlockT](
req,
BeaconBlockTxIndex,
s.chainSpec.ActiveForkVersionForSlot(math.U64(req.Height)),
)
if err != nil {
return createProcessProposalResponse(errors.WrapNonFatal(err))
}

// Decode the blob sidecars.
sidecars, err := encoding.
UnmarshalBlobSidecarsFromABCIRequest[BlobSidecarsT](
req,
BlobSidecarsTxIndex,
)
if err != nil {
return createProcessProposalResponse(errors.WrapNonFatal(err))
}

// Process the blob sidecars, if any
if !sidecars.IsNil() && sidecars.Len() > 0 {
var consensusSidecars *types.ConsensusSidecars[
BlobSidecarsT,
BeaconBlockHeaderT,
]
consensusSidecars = consensusSidecars.New(
sidecars,
blk.GetHeader(),
)

s.logger.Info("Received incoming blob sidecars")

// TODO: Clean this up once we remove generics.
c := convertConsensusSidecars[
ConsensusSidecarsT,
BlobSidecarsT,
BeaconBlockHeaderT,
](consensusSidecars)

// Verify the blobs and ensure they match the local state.
err = s.blobProcessor.VerifySidecars(c)
if err != nil {
s.logger.Error(
"rejecting incoming blob sidecars",
"reason", err,
)
return createProcessProposalResponse(errors.WrapNonFatal(err))
}

s.logger.Info(
"Blob sidecars verification succeeded - accepting incoming blob sidecars",
"num_blobs",
sidecars.Len(),
)
}

// Process the block
var consensusBlk *types.ConsensusBlock[BeaconBlockT]
consensusBlk = consensusBlk.New(
blk,
req.GetProposerAddress(),
req.GetTime(),
)
err = s.VerifyIncomingBlock(
ctx,
consensusBlk.GetBeaconBlock(),
consensusBlk.GetConsensusTime(),
consensusBlk.GetProposerAddress(),
)
if err != nil {
s.logger.Error("failed to verify incoming block", "error", err)
return createProcessProposalResponse(errors.WrapNonFatal(err))
}

return createProcessProposalResponse(nil)
}

// VerifyIncomingBlock verifies the state root of an incoming block
// and logs the process.
func (s *Service[
Expand Down Expand Up @@ -181,3 +280,30 @@ func (s *Service[
]) shouldBuildOptimisticPayloads() bool {
return s.optimisticPayloadBuilds && s.localBuilder.Enabled()
}

// createResponse generates the appropriate ProcessProposalResponse based on the
// error.
func createProcessProposalResponse(
err error,
) (*cmtabci.ProcessProposalResponse, error) {
status := cmtabci.PROCESS_PROPOSAL_STATUS_REJECT
if !errors.IsFatal(err) {
status = cmtabci.PROCESS_PROPOSAL_STATUS_ACCEPT
err = nil
}
return &cmtabci.ProcessProposalResponse{Status: status}, err
}

func convertConsensusSidecars[
ConsensusSidecarsT any,
BlobSidecarsT any,
BeaconBlockHeaderT any,
](
cSidecars *types.ConsensusSidecars[BlobSidecarsT, BeaconBlockHeaderT],
) ConsensusSidecarsT {
val, ok := any(cSidecars).(ConsensusSidecarsT)
if !ok {
panic("failed to convert conesensusSidecars to ConsensusSidecarsT")
}
return val
}

0 comments on commit 7f4c6a2

Please sign in to comment.