diff --git a/mod/beacon/blockchain/execution_engine.go b/mod/beacon/blockchain/execution_engine.go index e74e366d8d..d937c207e4 100644 --- a/mod/beacon/blockchain/execution_engine.go +++ b/mod/beacon/blockchain/execution_engine.go @@ -71,16 +71,8 @@ func (s *Service[ return } - prevBlockRoot, err := blk.HashTreeRoot() - if err != nil { - s.logger.Error( - "failed to get block root in non-optimistic payload", - "error", err, - ) - return - } - - if _, err = s.lb.RequestPayloadAsync( + prevBlockRoot := blk.HashTreeRoot() + if _, err := s.lb.RequestPayloadAsync( ctx, stCopy, blk.GetSlot()+1, diff --git a/mod/beacon/blockchain/payload.go b/mod/beacon/blockchain/payload.go index 922620f7b6..59917e12ec 100644 --- a/mod/beacon/blockchain/payload.go +++ b/mod/beacon/blockchain/payload.go @@ -24,7 +24,6 @@ import ( "context" "time" - "github.com/berachain/beacon-kit/mod/primitives/pkg/common" "github.com/berachain/beacon-kit/mod/primitives/pkg/math" ) @@ -87,10 +86,8 @@ func (s *Service[ st BeaconStateT, ) error { var ( - prevStateRoot common.Root - prevBlockRoot common.Root - lph ExecutionPayloadHeaderT - slot math.Slot + lph ExecutionPayloadHeaderT + slot math.Slot ) s.logger.Info("Rebuilding payload for rejected block ⏳ ") @@ -109,16 +106,8 @@ func (s *Service[ return err } - prevStateRoot, err = st.HashTreeRoot() - if err != nil { - return err - } - - latestHeader.SetStateRoot(prevStateRoot) - prevBlockRoot, err = latestHeader.HashTreeRoot() - if err != nil { - return err - } + // Set the previous state root on the header. + latestHeader.SetStateRoot(st.HashTreeRoot()) // We need to get the *last* finalized execution payload, thus // the BeaconState that was passed in must be `unmodified`. @@ -140,7 +129,7 @@ func (s *Service[ uint64((lph.GetTimestamp()+1)), ), // We set the parent root to the previous block root. - prevBlockRoot, + latestHeader.HashTreeRoot(), // We set the head of our chain to the previous finalized block. lph.GetBlockHash(), // We can say that the payload from the previous block is *finalized*, @@ -190,15 +179,8 @@ func (s *Service[ "next_slot", slot.Base10(), ) - // We know that this block was properly formed so we can - // calculate the block hash easily. - blkRoot, err := blk.HashTreeRoot() - if err != nil { - return err - } - // We process the slot to update any RANDAO values. - if _, err = s.sp.ProcessSlots( + if _, err := s.sp.ProcessSlots( st, slot, ); err != nil { return err @@ -206,7 +188,7 @@ func (s *Service[ // We then trigger a request for the next payload. payload := blk.GetBody().GetExecutionPayload() - if _, err = s.lb.RequestPayloadAsync( + if _, err := s.lb.RequestPayloadAsync( ctx, st, slot, // TODO: this is hood as fuck. @@ -217,7 +199,7 @@ func (s *Service[ ), // The previous block root is simply the root of the block we just // processed. - blkRoot, + blk.HashTreeRoot(), // We set the head of our chain to the block we just processed. payload.GetBlockHash(), // We can say that the payload from the previous block is *finalized*, diff --git a/mod/beacon/blockchain/types.go b/mod/beacon/blockchain/types.go index a936ede74a..d05f718cac 100644 --- a/mod/beacon/blockchain/types.go +++ b/mod/beacon/blockchain/types.go @@ -172,7 +172,7 @@ type ReadOnlyBeaconState[ // GetSlot retrieves the current slot of the beacon state. GetSlot() (math.Slot, error) // HashTreeRoot returns the hash tree root of the beacon state. - HashTreeRoot() (common.Root, error) + HashTreeRoot() common.Root } // StateProcessor defines the interface for processing various state transitions diff --git a/mod/beacon/validator/block_builder.go b/mod/beacon/validator/block_builder.go index 3f1e2fee99..c2e41e808f 100644 --- a/mod/beacon/validator/block_builder.go +++ b/mod/beacon/validator/block_builder.go @@ -188,7 +188,7 @@ func (s *Service[ return crypto.BLSSignature{}, err } - signingRoot, err := forkData.New( + signingRoot := forkData.New( version.FromUint32[common.Version]( s.chainSpec.ActiveForkVersionForEpoch(epoch), ), genesisValidatorsRoot, @@ -196,10 +196,6 @@ func (s *Service[ s.chainSpec.DomainTypeRandao(), epoch, ) - - if err != nil { - return crypto.BLSSignature{}, err - } return s.signer.Sign(signingRoot[:]) } @@ -383,5 +379,5 @@ func (s *Service[ return common.Root{}, err } - return st.HashTreeRoot() + return st.HashTreeRoot(), nil } diff --git a/mod/beacon/validator/types.go b/mod/beacon/validator/types.go index cfd017306b..cdbbd327f8 100644 --- a/mod/beacon/validator/types.go +++ b/mod/beacon/validator/types.go @@ -103,7 +103,7 @@ type BeaconState[ExecutionPayloadHeaderT any] interface { // GetSlot returns the current slot of the beacon state. GetSlot() (math.Slot, error) // HashTreeRoot returns the hash tree root of the beacon state. - HashTreeRoot() (common.Root, error) + HashTreeRoot() common.Root // ValidatorIndexByPubkey returns the validator index by public key. ValidatorIndexByPubkey(crypto.BLSPubkey) (math.ValidatorIndex, error) // GetEth1DepositIndex returns the latest deposit index from the beacon @@ -185,7 +185,7 @@ type ForkData[T any] interface { ComputeRandaoSigningRoot( common.DomainType, math.Epoch, - ) (common.Root, error) + ) common.Root } // PayloadBuilder represents a service that is responsible for diff --git a/mod/consensus-types/pkg/types/attestation_data.go b/mod/consensus-types/pkg/types/attestation_data.go index 2a330c3289..37b6ec14cc 100644 --- a/mod/consensus-types/pkg/types/attestation_data.go +++ b/mod/consensus-types/pkg/types/attestation_data.go @@ -87,8 +87,8 @@ func (a *AttestationData) DefineSSZ(codec *ssz.Codec) { } // HashTreeRoot computes the SSZ hash tree root of the AttestationData object. -func (a *AttestationData) HashTreeRoot() (common.Root, error) { - return ssz.HashSequential(a), nil +func (a *AttestationData) HashTreeRoot() common.Root { + return ssz.HashSequential(a) } // MarshalSSZ marshals the AttestationData object to SSZ format. diff --git a/mod/consensus-types/pkg/types/attestation_data_test.go b/mod/consensus-types/pkg/types/attestation_data_test.go index 74421075e1..1cee00f49d 100644 --- a/mod/consensus-types/pkg/types/attestation_data_test.go +++ b/mod/consensus-types/pkg/types/attestation_data_test.go @@ -108,8 +108,7 @@ func TestAttestationData_GetTree(t *testing.T) { require.NoError(t, err) require.NotNil(t, tree) - expectedRoot, err := data.HashTreeRoot() - require.NoError(t, err) + expectedRoot := data.HashTreeRoot() // Compare the tree root with the expected root actualRoot := tree.Hash() diff --git a/mod/consensus-types/pkg/types/block.go b/mod/consensus-types/pkg/types/block.go index 4c03a85eb7..7584952020 100644 --- a/mod/consensus-types/pkg/types/block.go +++ b/mod/consensus-types/pkg/types/block.go @@ -135,8 +135,8 @@ func (b *BeaconBlock) UnmarshalSSZ(buf []byte) error { } // HashTreeRoot computes the Merkleization of the BeaconBlock object. -func (b *BeaconBlock) HashTreeRoot() (common.Root, error) { - return ssz.HashConcurrent(b), nil +func (b *BeaconBlock) HashTreeRoot() common.Root { + return ssz.HashConcurrent(b) } /* -------------------------------------------------------------------------- */ @@ -226,16 +226,11 @@ func (b *BeaconBlock) GetBody() *BeaconBlockBody { // GetHeader builds a BeaconBlockHeader from the BeaconBlock. func (b *BeaconBlock) GetHeader() *BeaconBlockHeader { - bodyRoot, err := b.GetBody().HashTreeRoot() - if err != nil { - return nil - } - return &BeaconBlockHeader{ Slot: b.Slot, ProposerIndex: b.ProposerIndex, ParentBlockRoot: b.ParentRoot, StateRoot: b.StateRoot, - BodyRoot: bodyRoot, + BodyRoot: b.GetBody().HashTreeRoot(), } } diff --git a/mod/consensus-types/pkg/types/block_test.go b/mod/consensus-types/pkg/types/block_test.go index 585426c446..1f7b4d0398 100644 --- a/mod/consensus-types/pkg/types/block_test.go +++ b/mod/consensus-types/pkg/types/block_test.go @@ -139,8 +139,7 @@ func TestBeaconBlock_MarshalUnmarshalSSZ(t *testing.T) { func TestBeaconBlock_HashTreeRoot(t *testing.T) { block := generateValidBeaconBlock() - hashRoot, err := block.HashTreeRoot() - require.NoError(t, err) + hashRoot := block.HashTreeRoot() require.NotNil(t, hashRoot) } diff --git a/mod/consensus-types/pkg/types/body.go b/mod/consensus-types/pkg/types/body.go index eacb35acc5..a7a769604b 100644 --- a/mod/consensus-types/pkg/types/body.go +++ b/mod/consensus-types/pkg/types/body.go @@ -147,8 +147,8 @@ func (b *BeaconBlockBody) UnmarshalSSZ(buf []byte) error { } // HashTreeRoot returns the SSZ hash tree root of the BeaconBlockBody. -func (b *BeaconBlockBody) HashTreeRoot() (common.Root, error) { - return ssz.HashConcurrent(b), nil +func (b *BeaconBlockBody) HashTreeRoot() common.Root { + return ssz.HashConcurrent(b) } /* -------------------------------------------------------------------------- */ @@ -291,26 +291,14 @@ func (b *BeaconBlockBody) SetSlashingInfo(_ []*SlashingInfo) { } // GetTopLevelRoots returns the top-level roots of the BeaconBlockBody. -func (b *BeaconBlockBody) GetTopLevelRoots() ([][32]byte, error) { - var ( - err error - layer = make([][32]byte, BodyLengthDeneb) - ) - - layer[0], err = b.GetRandaoReveal().HashTreeRoot() - if err != nil { - return nil, err - } - - layer[1], err = b.Eth1Data.HashTreeRoot() - if err != nil { - return nil, err +func (b *BeaconBlockBody) GetTopLevelRoots() []common.Root { + return []common.Root{ + b.GetRandaoReveal().HashTreeRoot(), + b.Eth1Data.HashTreeRoot(), + b.GetGraffiti().HashTreeRoot(), + Deposits(b.GetDeposits()).HashTreeRoot(), + b.GetExecutionPayload().HashTreeRoot(), } - - layer[2] = b.GetGraffiti() - layer[3] = Deposits(b.GetDeposits()).HashTreeRoot() - layer[4], err = b.GetExecutionPayload().HashTreeRoot() - return layer, err } // Length returns the number of fields in the BeaconBlockBody struct. diff --git a/mod/consensus-types/pkg/types/body_test.go b/mod/consensus-types/pkg/types/body_test.go index cb8d0edf44..9a4634c8d4 100644 --- a/mod/consensus-types/pkg/types/body_test.go +++ b/mod/consensus-types/pkg/types/body_test.go @@ -147,8 +147,7 @@ func TestBeaconBlockBody_MarshalSSZTo(t *testing.T) { func TestBeaconBlockBody_GetTopLevelRoots(t *testing.T) { body := generateBeaconBlockBody() - roots, err := body.GetTopLevelRoots() - require.NoError(t, err) + roots := body.GetTopLevelRoots() require.NotNil(t, roots) } diff --git a/mod/consensus-types/pkg/types/deposit.go b/mod/consensus-types/pkg/types/deposit.go index 49f36e7e45..a205abdf60 100644 --- a/mod/consensus-types/pkg/types/deposit.go +++ b/mod/consensus-types/pkg/types/deposit.go @@ -137,8 +137,8 @@ func (d *Deposit) SizeSSZ() uint32 { } // HashTreeRoot computes the Merkleization of the Deposit object. -func (d *Deposit) HashTreeRoot() (common.Root, error) { - return ssz.HashSequential(d), nil +func (d *Deposit) HashTreeRoot() common.Root { + return ssz.HashSequential(d) } /* -------------------------------------------------------------------------- */ diff --git a/mod/consensus-types/pkg/types/deposit_message.go b/mod/consensus-types/pkg/types/deposit_message.go index d7a4d55946..5dae4c5c77 100644 --- a/mod/consensus-types/pkg/types/deposit_message.go +++ b/mod/consensus-types/pkg/types/deposit_message.go @@ -51,22 +51,13 @@ func CreateAndSignDepositMessage( credentials WithdrawalCredentials, amount math.Gwei, ) (*DepositMessage, crypto.BLSSignature, error) { - domain, err := forkData.ComputeDomain(domainType) - if err != nil { - return nil, crypto.BLSSignature{}, err - } - + domain := forkData.ComputeDomain(domainType) depositMessage := &DepositMessage{ Pubkey: signer.PublicKey(), Credentials: credentials, Amount: amount, } - - signingRoot, err := ComputeSigningRoot(depositMessage, domain) - if err != nil { - return nil, crypto.BLSSignature{}, err - } - + signingRoot := ComputeSigningRoot(depositMessage, domain) signature, err := signer.Sign(signingRoot[:]) if err != nil { return nil, crypto.BLSSignature{}, err @@ -107,8 +98,8 @@ func (dm *DepositMessage) DefineSSZ(codec *ssz.Codec) { } // HashTreeRoot computes the SSZ hash tree root of the DepositMessage object. -func (dm *DepositMessage) HashTreeRoot() (common.Root, error) { - return ssz.HashSequential(dm), nil +func (dm *DepositMessage) HashTreeRoot() common.Root { + return ssz.HashSequential(dm) } // MarshalSSZTo marshals the DepositMessage object to SSZ format into the @@ -139,17 +130,9 @@ func (dm *DepositMessage) VerifyCreateValidator( pubkey crypto.BLSPubkey, message []byte, signature crypto.BLSSignature, ) error, ) error { - domain, err := forkData.ComputeDomain(domainType) - if err != nil { - return err - } - - signingRoot, err := ComputeSigningRoot(dm, domain) - if err != nil { - return err - } - - if err = signatureVerificationFn( + signingRoot := ComputeSigningRoot( + dm, forkData.ComputeDomain(domainType)) + if err := signatureVerificationFn( dm.Pubkey, signingRoot[:], signature, ); err != nil { return errors.Join(err, ErrDepositMessage) diff --git a/mod/consensus-types/pkg/types/deposit_test.go b/mod/consensus-types/pkg/types/deposit_test.go index 0393b7626c..5e9fb5b474 100644 --- a/mod/consensus-types/pkg/types/deposit_test.go +++ b/mod/consensus-types/pkg/types/deposit_test.go @@ -86,9 +86,9 @@ func TestDeposit_MarshalSSZTo(t *testing.T) { func TestDeposit_HashTreeRoot(t *testing.T) { deposit := generateValidDeposit() - - _, err := deposit.HashTreeRoot() - require.NoError(t, err) + require.NotPanics(t, func() { + _ = deposit.HashTreeRoot() + }) } func TestDeposit_SizeSSZ(t *testing.T) { diff --git a/mod/consensus-types/pkg/types/eth1data.go b/mod/consensus-types/pkg/types/eth1data.go index 60ba4742e4..c7a9c08760 100644 --- a/mod/consensus-types/pkg/types/eth1data.go +++ b/mod/consensus-types/pkg/types/eth1data.go @@ -87,8 +87,8 @@ func (e *Eth1Data) DefineSSZ(codec *ssz.Codec) { } // HashTreeRoot computes the SSZ hash tree root of the Eth1Data object. -func (e *Eth1Data) HashTreeRoot() (common.Root, error) { - return ssz.HashSequential(e), nil +func (e *Eth1Data) HashTreeRoot() common.Root { + return ssz.HashSequential(e) } // MarshalSSZ marshals the Eth1Data object to SSZ format. diff --git a/mod/consensus-types/pkg/types/eth1data_test.go b/mod/consensus-types/pkg/types/eth1data_test.go index 5a1ff0b029..0f958558d0 100644 --- a/mod/consensus-types/pkg/types/eth1data_test.go +++ b/mod/consensus-types/pkg/types/eth1data_test.go @@ -78,8 +78,9 @@ func TestEth1Data_HashTreeRoot(t *testing.T) { BlockHash: gethprimitives.ExecutionHash{}, } - _, err := eth1Data.HashTreeRoot() - require.NoError(t, err) + require.NotPanics(t, func() { + _ = eth1Data.HashTreeRoot() + }) } func TestEth1Data_GetTree(t *testing.T) { diff --git a/mod/consensus-types/pkg/types/fork.go b/mod/consensus-types/pkg/types/fork.go index d59f1d41b6..2f0bc087b1 100644 --- a/mod/consensus-types/pkg/types/fork.go +++ b/mod/consensus-types/pkg/types/fork.go @@ -100,8 +100,8 @@ func (f *Fork) UnmarshalSSZ(buf []byte) error { } // HashTreeRoot computes the SSZ hash tree root of the Fork object. -func (f *Fork) HashTreeRoot() (common.Root, error) { - return ssz.HashSequential(f), nil +func (f *Fork) HashTreeRoot() common.Root { + return ssz.HashSequential(f) } /* -------------------------------------------------------------------------- */ diff --git a/mod/consensus-types/pkg/types/fork_data.go b/mod/consensus-types/pkg/types/fork_data.go index 7194d6f88b..cfc102f499 100644 --- a/mod/consensus-types/pkg/types/fork_data.go +++ b/mod/consensus-types/pkg/types/fork_data.go @@ -71,8 +71,8 @@ func (fd *ForkData) DefineSSZ(codec *ssz.Codec) { } // HashTreeRoot computes the SSZ hash tree root of the ForkData object. -func (fd *ForkData) HashTreeRoot() (common.Root, error) { - return ssz.HashSequential(fd), nil +func (fd *ForkData) HashTreeRoot() common.Root { + return ssz.HashSequential(fd) } // MarshalSSZTo marshals the ForkData object to SSZ format into the provided @@ -98,31 +98,22 @@ func (fd *ForkData) UnmarshalSSZ(buf []byte) error { //nolint:lll func (fd *ForkData) ComputeDomain( domainType common.DomainType, -) (common.Domain, error) { - forkDataRoot, err := fd.HashTreeRoot() - if err != nil { - return common.Domain{}, err - } - +) common.Domain { + forkDataRoot := fd.HashTreeRoot() return common.Domain( append( domainType[:], forkDataRoot[:28]...), - ), nil + ) } // ComputeRandaoSigningRoot computes the randao signing root. func (fd *ForkData) ComputeRandaoSigningRoot( domainType common.DomainType, epoch math.Epoch, -) (common.Root, error) { - signingDomain, err := fd.ComputeDomain(domainType) - if err != nil { - return common.Root{}, err - } - +) common.Root { return ComputeSigningRootUInt64( uint64(epoch), - signingDomain, + fd.ComputeDomain(domainType), ) } diff --git a/mod/consensus-types/pkg/types/fork_data_test.go b/mod/consensus-types/pkg/types/fork_data_test.go index 7fb883e1dc..22e94e11f9 100644 --- a/mod/consensus-types/pkg/types/fork_data_test.go +++ b/mod/consensus-types/pkg/types/fork_data_test.go @@ -69,9 +69,9 @@ func TestForkData_HashTreeRoot(t *testing.T) { CurrentVersion: common.Version{}, GenesisValidatorsRoot: common.Root{}, } - _, err := forkData.HashTreeRoot() - - require.NoError(t, err) + require.NotPanics(t, func() { + _ = forkData.HashTreeRoot() + }) } func TestForkData_ComputeDomain(t *testing.T) { @@ -82,8 +82,9 @@ func TestForkData_ComputeDomain(t *testing.T) { domainType := common.DomainType{ 0x01, 0x00, 0x00, 0x00, } - _, err := forkData.ComputeDomain(domainType) - require.NoError(t, err) + require.NotPanics(t, func() { + _ = forkData.ComputeDomain(domainType) + }) } func TestForkData_ComputeRandaoSigningRoot(t *testing.T) { @@ -95,8 +96,9 @@ func TestForkData_ComputeRandaoSigningRoot(t *testing.T) { domainType := common.DomainType{0, 0, 0, 0} epoch := math.Epoch(1) - _, err := fd.ComputeRandaoSigningRoot(domainType, epoch) - require.NoError(t, err) + require.NotPanics(t, func() { + fd.ComputeRandaoSigningRoot(domainType, epoch) + }) } func TestNewForkData(t *testing.T) { diff --git a/mod/consensus-types/pkg/types/fork_test.go b/mod/consensus-types/pkg/types/fork_test.go index 7def95486a..83f5acc89e 100644 --- a/mod/consensus-types/pkg/types/fork_test.go +++ b/mod/consensus-types/pkg/types/fork_test.go @@ -72,8 +72,9 @@ func TestFork_HashTreeRoot(t *testing.T) { Epoch: math.Epoch(1000), } - _, err := fork.HashTreeRoot() - require.NoError(t, err) + require.NotPanics(t, func() { + _ = fork.HashTreeRoot() + }) } func TestFork_GetTree(t *testing.T) { diff --git a/mod/consensus-types/pkg/types/header.go b/mod/consensus-types/pkg/types/header.go index d11849f44a..f1a91e432c 100644 --- a/mod/consensus-types/pkg/types/header.go +++ b/mod/consensus-types/pkg/types/header.go @@ -122,8 +122,8 @@ func (b *BeaconBlockHeader) UnmarshalSSZ(buf []byte) error { } // HashTreeRoot computes the SSZ hash tree root of the BeaconBlockHeader object. -func (b *BeaconBlockHeader) HashTreeRoot() (common.Root, error) { - return ssz.HashSequential(b), nil +func (b *BeaconBlockHeader) HashTreeRoot() common.Root { + return ssz.HashSequential(b) } /* -------------------------------------------------------------------------- */ diff --git a/mod/consensus-types/pkg/types/header_test.go b/mod/consensus-types/pkg/types/header_test.go index dfb21c923e..a37e76e580 100644 --- a/mod/consensus-types/pkg/types/header_test.go +++ b/mod/consensus-types/pkg/types/header_test.go @@ -68,7 +68,7 @@ func TestBeaconBlockHeader_SizeSSZ(t *testing.T) { require.Equal(t, uint32(112), size) } -func TestBeaconBlockHeader_HashTreeRoot(t *testing.T) { +func TestBeaconBlockHeader_HashTreeRoot(_ *testing.T) { header := types.NewBeaconBlockHeader( math.Slot(100), math.ValidatorIndex(200), @@ -77,8 +77,7 @@ func TestBeaconBlockHeader_HashTreeRoot(t *testing.T) { common.Root{}, ) - _, err := header.HashTreeRoot() - require.NoError(t, err) + _ = header.HashTreeRoot() } func TestBeaconBlockHeader_GetTree(t *testing.T) { diff --git a/mod/consensus-types/pkg/types/payload.go b/mod/consensus-types/pkg/types/payload.go index 8f8df163ce..19a9d8cf8c 100644 --- a/mod/consensus-types/pkg/types/payload.go +++ b/mod/consensus-types/pkg/types/payload.go @@ -144,8 +144,8 @@ func (p *ExecutionPayload) UnmarshalSSZ(bz []byte) error { } // HashTreeRoot returns the hash tree root of the ExecutionPayload. -func (p *ExecutionPayload) HashTreeRoot() (common.Root, error) { - return ssz.HashConcurrent(p), nil +func (p *ExecutionPayload) HashTreeRoot() common.Root { + return ssz.HashConcurrent(p) } /* -------------------------------------------------------------------------- */ diff --git a/mod/consensus-types/pkg/types/payload_header.go b/mod/consensus-types/pkg/types/payload_header.go index 23541b2561..291899cf9a 100644 --- a/mod/consensus-types/pkg/types/payload_header.go +++ b/mod/consensus-types/pkg/types/payload_header.go @@ -160,8 +160,8 @@ func (h *ExecutionPayloadHeader) UnmarshalSSZ(bz []byte) error { } // HashTreeRootSSZ returns the hash tree root of the ExecutionPayloadHeader. -func (h *ExecutionPayloadHeader) HashTreeRoot() (common.Root, error) { - return ssz.HashConcurrent(h), nil +func (h *ExecutionPayloadHeader) HashTreeRoot() common.Root { + return ssz.HashConcurrent(h) } /* -------------------------------------------------------------------------- */ diff --git a/mod/consensus-types/pkg/types/payload_header_test.go b/mod/consensus-types/pkg/types/payload_header_test.go index 70caae0aaf..a4b70838c0 100644 --- a/mod/consensus-types/pkg/types/payload_header_test.go +++ b/mod/consensus-types/pkg/types/payload_header_test.go @@ -235,8 +235,9 @@ func TestExecutionPayloadHeader_SizeSSZ(t *testing.T) { func TestExecutionPayloadHeader_HashTreeRoot(t *testing.T) { header := generateExecutionPayloadHeader() - _, err := header.HashTreeRoot() - require.NoError(t, err) + require.NotPanics(t, func() { + header.HashTreeRoot() + }) } func TestExecutionPayloadHeader_GetTree(t *testing.T) { diff --git a/mod/consensus-types/pkg/types/payload_test.go b/mod/consensus-types/pkg/types/payload_test.go index 3b3a79c691..cd8b8ce8e8 100644 --- a/mod/consensus-types/pkg/types/payload_test.go +++ b/mod/consensus-types/pkg/types/payload_test.go @@ -98,8 +98,9 @@ func TestExecutionPayload_SizeSSZ(t *testing.T) { func TestExecutionPayload_HashTreeRoot(t *testing.T) { payload := generateExecutionPayload() - _, err := payload.HashTreeRoot() - require.NoError(t, err) + require.NotPanics(t, func() { + _ = payload.HashTreeRoot() + }) } func TestExecutionPayload_GetTree(t *testing.T) { diff --git a/mod/consensus-types/pkg/types/signing_data.go b/mod/consensus-types/pkg/types/signing_data.go index 69ce510940..5cb37855cf 100644 --- a/mod/consensus-types/pkg/types/signing_data.go +++ b/mod/consensus-types/pkg/types/signing_data.go @@ -56,8 +56,8 @@ func (s *SigningData) DefineSSZ(codec *ssz.Codec) { } // HashTreeRoot computes the SSZ hash tree root of the SigningData object. -func (s *SigningData) HashTreeRoot() (common.Root, error) { - return ssz.HashSequential(s), nil +func (s *SigningData) HashTreeRoot() common.Root { + return ssz.HashSequential(s) } // MarshalSSZTo marshals the SigningData object to SSZ format into the provided @@ -82,15 +82,11 @@ func (s *SigningData) UnmarshalSSZ(buf []byte) error { // //nolint:lll // link. func ComputeSigningRoot( - sszObject interface{ HashTreeRoot() (common.Root, error) }, + sszObject interface{ HashTreeRoot() common.Root }, domain common.Domain, -) (common.Root, error) { - objectRoot, err := sszObject.HashTreeRoot() - if err != nil { - return common.Root{}, err - } +) common.Root { return (&SigningData{ - ObjectRoot: objectRoot, + ObjectRoot: sszObject.HashTreeRoot(), Domain: domain, }).HashTreeRoot() } @@ -100,7 +96,7 @@ func ComputeSigningRootUInt64( value uint64, domain common.Domain, -) (common.Root, error) { +) common.Root { bz := make([]byte, constants.RootLength) binary.LittleEndian.PutUint64(bz, value) return (&SigningData{ diff --git a/mod/consensus-types/pkg/types/slashing_info.go b/mod/consensus-types/pkg/types/slashing_info.go index 068cc9f25b..d57790c335 100644 --- a/mod/consensus-types/pkg/types/slashing_info.go +++ b/mod/consensus-types/pkg/types/slashing_info.go @@ -83,8 +83,8 @@ func (s *SlashingInfo) DefineSSZ(codec *ssz.Codec) { } // HashTreeRoot computes the SSZ hash tree root of the SlashingInfo object. -func (s *SlashingInfo) HashTreeRoot() (common.Root, error) { - return ssz.HashSequential(s), nil +func (s *SlashingInfo) HashTreeRoot() common.Root { + return ssz.HashSequential(s) } // MarshalSSZ marshals the SlashingInfo object to SSZ format. diff --git a/mod/consensus-types/pkg/types/slashing_info_test.go b/mod/consensus-types/pkg/types/slashing_info_test.go index 4a6a115f5a..ba29fbd473 100644 --- a/mod/consensus-types/pkg/types/slashing_info_test.go +++ b/mod/consensus-types/pkg/types/slashing_info_test.go @@ -102,10 +102,7 @@ func TestSlashingInfo_GetTree(t *testing.T) { require.NoError(t, err) require.NotNil(t, tree) - expectedRoot, err := data.HashTreeRoot() - require.NoError(t, err) - - // Compare the tree root with the expected root + expectedRoot := data.HashTreeRoot() actualRoot := tree.Hash() require.Equal(t, string(expectedRoot[:]), string(actualRoot)) } diff --git a/mod/consensus-types/pkg/types/state.go b/mod/consensus-types/pkg/types/state.go index 2a6264a331..d48f36a8cc 100644 --- a/mod/consensus-types/pkg/types/state.go +++ b/mod/consensus-types/pkg/types/state.go @@ -224,8 +224,8 @@ func (st *BeaconState[ // HashTreeRoot computes the Merkleization of the BeaconState. func (st *BeaconState[ _, _, _, _, _, _, _, _, _, _, -]) HashTreeRoot() (common.Root, error) { - return ssz.HashConcurrent(st), nil +]) HashTreeRoot() common.Root { + return ssz.HashConcurrent(st) } /* -------------------------------------------------------------------------- */ diff --git a/mod/consensus-types/pkg/types/state_test.go b/mod/consensus-types/pkg/types/state_test.go index a4bab9d7d1..a5c34606a5 100644 --- a/mod/consensus-types/pkg/types/state_test.go +++ b/mod/consensus-types/pkg/types/state_test.go @@ -179,8 +179,9 @@ func TestBeaconStateMarshalUnmarshalSSZ(t *testing.T) { func TestHashTreeRoot(t *testing.T) { state := generateValidBeaconState() - _, err := state.HashTreeRoot() - require.NoError(t, err) + require.NotPanics(t, func() { + state.HashTreeRoot() + }) } func TestGetTree(t *testing.T) { @@ -225,8 +226,7 @@ func TestBeaconState_HashTreeRoot(t *testing.T) { state := generateValidBeaconState() // Get the HashTreeRoot - root, err := state.HashTreeRoot() - require.NoError(t, err) + root := state.HashTreeRoot() // Get the HashConcurrent concurrentRoot := common.Root(karalabessz.HashSequential(state)) diff --git a/mod/consensus-types/pkg/types/validator.go b/mod/consensus-types/pkg/types/validator.go index 5919b50c1a..21c25287aa 100644 --- a/mod/consensus-types/pkg/types/validator.go +++ b/mod/consensus-types/pkg/types/validator.go @@ -141,8 +141,8 @@ func (v *Validator) DefineSSZ(codec *ssz.Codec) { } // HashTreeRoot computes the SSZ hash tree root of the Validator object. -func (v *Validator) HashTreeRoot() (common.Root, error) { - return ssz.HashSequential(v), nil +func (v *Validator) HashTreeRoot() common.Root { + return ssz.HashSequential(v) } // MarshalSSZ marshals the Validator object to SSZ format. diff --git a/mod/consensus-types/pkg/types/validator_test.go b/mod/consensus-types/pkg/types/validator_test.go index 6cabf8765b..ecf9372113 100644 --- a/mod/consensus-types/pkg/types/validator_test.go +++ b/mod/consensus-types/pkg/types/validator_test.go @@ -745,13 +745,12 @@ func TestValidator_HashTreeRoot(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Test HashTreeRoot - root, err := tt.validator.HashTreeRoot() - require.NoError(t, err) + root := tt.validator.HashTreeRoot() require.NotEqual(t, [32]byte{}, root) // Test HashTreeRootWith hh := ssz.NewHasher() - err = tt.validator.HashTreeRootWith(hh) + err := tt.validator.HashTreeRootWith(hh) require.NoError(t, err) // Test GetTree diff --git a/mod/consensus/pkg/cometbft/helpers.go b/mod/consensus/pkg/cometbft/helpers.go index 77ae7bd49e..b98fc9d87c 100644 --- a/mod/consensus/pkg/cometbft/helpers.go +++ b/mod/consensus/pkg/cometbft/helpers.go @@ -103,10 +103,7 @@ func (c *ConsensusEngine[ var index math.U64 attestations := make([]AttestationDataT, len(votes)) st := c.sb.StateFromContext(ctx) - root, err := st.HashTreeRoot() - if err != nil { - return nil, err - } + root := st.HashTreeRoot() for i, vote := range votes { index, err = st.ValidatorIndexByCometBFTAddress(vote.Validator.Address) if err != nil { diff --git a/mod/consensus/pkg/cometbft/types.go b/mod/consensus/pkg/cometbft/types.go index 30b734510b..e0d65a452d 100644 --- a/mod/consensus/pkg/cometbft/types.go +++ b/mod/consensus/pkg/cometbft/types.go @@ -44,7 +44,7 @@ type BeaconState interface { cometBFTAddress []byte, ) (math.ValidatorIndex, error) // HashTreeRoot returns the hash tree root of the beacon state. - HashTreeRoot() (common.Root, error) + HashTreeRoot() common.Root } // Middleware is the interface for the CometBFT middleware. diff --git a/mod/da/pkg/blob/factory.go b/mod/da/pkg/blob/factory.go index 2a4656eb19..ae9b386cca 100644 --- a/mod/da/pkg/blob/factory.go +++ b/mod/da/pkg/blob/factory.go @@ -25,6 +25,7 @@ import ( "github.com/berachain/beacon-kit/mod/da/pkg/types" engineprimitives "github.com/berachain/beacon-kit/mod/engine-primitives/pkg/engine-primitives" + "github.com/berachain/beacon-kit/mod/primitives/pkg/common" "github.com/berachain/beacon-kit/mod/primitives/pkg/math" "github.com/berachain/beacon-kit/mod/primitives/pkg/merkle" "golang.org/x/sync/errgroup" @@ -108,7 +109,7 @@ func (f *SidecarFactory[BeaconBlockT, BeaconBlockBodyT]) BuildSidecars( func (f *SidecarFactory[BeaconBlockT, BeaconBlockBodyT]) BuildKZGInclusionProof( body BeaconBlockBodyT, index math.U64, -) ([][32]byte, error) { +) ([]common.Root, error) { startTime := time.Now() defer f.metrics.measureBuildKZGInclusionProofDuration(startTime) @@ -133,15 +134,11 @@ func (f *SidecarFactory[BeaconBlockT, BeaconBlockBodyT]) BuildKZGInclusionProof( // BuildBlockBodyProof builds a block body proof. func (f *SidecarFactory[BeaconBlockT, BeaconBlockBodyT]) BuildBlockBodyProof( body BeaconBlockBodyT, -) ([][32]byte, error) { +) ([]common.Root, error) { startTime := time.Now() defer f.metrics.measureBuildBlockBodyProofDuration(startTime) - membersRoots, err := body.GetTopLevelRoots() - if err != nil { - return nil, err - } - - tree, err := merkle.NewTreeWithMaxLeaves[[32]byte]( + membersRoots := body.GetTopLevelRoots() + tree, err := merkle.NewTreeWithMaxLeaves[common.Root]( membersRoots, body.Length()-1, ) @@ -156,17 +153,12 @@ func (f *SidecarFactory[BeaconBlockT, BeaconBlockBodyT]) BuildBlockBodyProof( func (f *SidecarFactory[BeaconBlockT, BeaconBlockBodyT]) BuildCommitmentProof( body BeaconBlockBodyT, index math.U64, -) ([][32]byte, error) { +) ([]common.Root, error) { startTime := time.Now() defer f.metrics.measureBuildCommitmentProofDuration(startTime) - - commitmentsLeaves, err := body.GetBlobKzgCommitments().Leafify() - if err != nil { - return nil, err - } - - bodyTree, err := merkle.NewTreeWithMaxLeaves[[32]byte]( - commitmentsLeaves, f.chainSpec.MaxBlobCommitmentsPerBlock(), + bodyTree, err := merkle.NewTreeWithMaxLeaves[common.Root]( + body.GetBlobKzgCommitments().Leafify(), + f.chainSpec.MaxBlobCommitmentsPerBlock(), ) if err != nil { return nil, err diff --git a/mod/da/pkg/blob/types.go b/mod/da/pkg/blob/types.go index b15527e323..2a08804953 100644 --- a/mod/da/pkg/blob/types.go +++ b/mod/da/pkg/blob/types.go @@ -26,6 +26,7 @@ import ( types "github.com/berachain/beacon-kit/mod/consensus-types/pkg/types" gethprimitives "github.com/berachain/beacon-kit/mod/geth-primitives" + "github.com/berachain/beacon-kit/mod/primitives/pkg/common" "github.com/berachain/beacon-kit/mod/primitives/pkg/eip4844" "github.com/berachain/beacon-kit/mod/primitives/pkg/math" ) @@ -49,7 +50,7 @@ type BeaconBlock[BeaconBlockBodyT any] interface { type BeaconBlockBody interface { GetBlobKzgCommitments() eip4844.KZGCommitments[gethprimitives.ExecutionHash] - GetTopLevelRoots() ([][32]byte, error) + GetTopLevelRoots() []common.Root Length() uint64 } diff --git a/mod/da/pkg/types/sidecar.go b/mod/da/pkg/types/sidecar.go index a3ae9b2982..22132caf72 100644 --- a/mod/da/pkg/types/sidecar.go +++ b/mod/da/pkg/types/sidecar.go @@ -47,7 +47,7 @@ type BlobSidecar struct { BeaconBlockHeader *types.BeaconBlockHeader // InclusionProof is the inclusion proof of the blob in the beacon block // body. - InclusionProof [][32]byte + InclusionProof []common.Root } // BuildBlobSidecar creates a blob sidecar from the given blobs and @@ -58,7 +58,7 @@ func BuildBlobSidecar( blob *eip4844.Blob, commitment eip4844.KZGCommitment, proof eip4844.KZGProof, - inclusionProof [][32]byte, + inclusionProof []common.Root, ) *BlobSidecar { return &BlobSidecar{ Index: index.Unwrap(), @@ -75,23 +75,15 @@ func BuildBlobSidecar( func (b *BlobSidecar) HasValidInclusionProof( kzgOffset uint64, ) bool { - // Calculate the hash tree root of the KZG commitment. - leaf, err := b.KzgCommitment.HashTreeRoot() - if err != nil { - return false - } - - gIndex := kzgOffset + b.Index - // Verify the inclusion proof. return merkle.IsValidMerkleBranch( - leaf, + b.KzgCommitment.HashTreeRoot(), b.InclusionProof, //#nosec:G701 // safe. uint8( len(b.InclusionProof), ), // TODO: use KZG_INCLUSION_PROOF_DEPTH calculation. - gIndex, + kzgOffset+b.Index, b.BeaconBlockHeader.BodyRoot, ) } @@ -135,6 +127,6 @@ func (b *BlobSidecar) MarshalSSZTo(buf []byte) ([]byte, error) { } // HashTreeRoot computes the SSZ hash tree root of the BlobSidecar object. -func (b *BlobSidecar) HashTreeRoot() (common.Root, error) { - return ssz.HashSequential(b), nil +func (b *BlobSidecar) HashTreeRoot() common.Root { + return ssz.HashSequential(b) } diff --git a/mod/da/pkg/types/sidecar_test.go b/mod/da/pkg/types/sidecar_test.go index 31cab51ae1..ce0b9e57d1 100644 --- a/mod/da/pkg/types/sidecar_test.go +++ b/mod/da/pkg/types/sidecar_test.go @@ -45,7 +45,7 @@ func TestSidecarMarshalling(t *testing.T) { &blob, eip4844.KZGCommitment{}, eip4844.KZGProof{}, - [][32]byte{ + []common.Root{ byteslib.ToBytes32([]byte("1")), byteslib.ToBytes32([]byte("2")), byteslib.ToBytes32([]byte("3")), @@ -93,7 +93,7 @@ func TestHasValidInclusionProof(t *testing.T) { &eip4844.Blob{}, eip4844.KZGCommitment{}, eip4844.KZGProof{}, - [][32]byte{ + []common.Root{ byteslib.ToBytes32([]byte("4")), byteslib.ToBytes32([]byte("5")), byteslib.ToBytes32([]byte("6")), @@ -110,7 +110,7 @@ func TestHasValidInclusionProof(t *testing.T) { &eip4844.Blob{}, eip4844.KZGCommitment{}, eip4844.KZGProof{}, - [][32]byte{}, + []common.Root{}, ), kzgOffset: 0, expectedResult: false, @@ -143,7 +143,7 @@ func TestHashTreeRoot(t *testing.T) { &eip4844.Blob{0, 1, 2, 3, 4, 5, 6, 7}, eip4844.KZGCommitment{1, 2, 3}, eip4844.KZGProof{4, 5, 6}, - [][32]byte{ + []common.Root{ byteslib.ToBytes32([]byte("1")), byteslib.ToBytes32([]byte("2")), byteslib.ToBytes32([]byte("3")), @@ -164,15 +164,15 @@ func TestHashTreeRoot(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - result, err := tt.sidecar.HashTreeRoot() - if tt.expectError { - require.Error(t, err, "Expected an error but got none") - } else { - require.NoError(t, err, - "Did not expect an error but got one") - assert.Equal(t, tt.expectedResult, result, - "Hash result should match expected value") - } + require.NotPanics(t, func() { + result := tt.sidecar.HashTreeRoot() + require.Equal( + t, + tt.expectedResult, + result, + "HashTreeRoot result should match expected value", + ) + }, "HashTreeRoot should not panic") }) } } diff --git a/mod/da/pkg/types/sidecars.go b/mod/da/pkg/types/sidecars.go index cade98b0e7..64566f5b28 100644 --- a/mod/da/pkg/types/sidecars.go +++ b/mod/da/pkg/types/sidecars.go @@ -49,18 +49,9 @@ func (bs *BlobSidecars) ValidateBlockRoots() error { // We only need to check if there is more than // a single blob in the sidecar. if sc := bs.Sidecars; len(sc) > 1 { - firstHtr, err := sc[0].BeaconBlockHeader.HashTreeRoot() - if err != nil { - return err - } - - var nextHtr [32]byte + firstHtr := sc[0].BeaconBlockHeader.HashTreeRoot() for i := 1; i < len(sc); i++ { - nextHtr, err = sc[i].BeaconBlockHeader.HashTreeRoot() - if err != nil { - return err - } - if firstHtr != nextHtr { + if firstHtr != sc[i].BeaconBlockHeader.HashTreeRoot() { return ErrSidecarContainsDifferingBlockRoots } } diff --git a/mod/da/pkg/types/sidecars_test.go b/mod/da/pkg/types/sidecars_test.go index 433e87f168..8188a3d95d 100644 --- a/mod/da/pkg/types/sidecars_test.go +++ b/mod/da/pkg/types/sidecars_test.go @@ -26,6 +26,7 @@ import ( ctypes "github.com/berachain/beacon-kit/mod/consensus-types/pkg/types" "github.com/berachain/beacon-kit/mod/da/pkg/types" byteslib "github.com/berachain/beacon-kit/mod/primitives/pkg/bytes" + "github.com/berachain/beacon-kit/mod/primitives/pkg/common" "github.com/berachain/beacon-kit/mod/primitives/pkg/eip4844" "github.com/berachain/beacon-kit/mod/primitives/pkg/math" "github.com/stretchr/testify/require" @@ -39,7 +40,7 @@ func TestEmptySidecarMarshalling(t *testing.T) { &eip4844.Blob{}, eip4844.KZGCommitment{}, [48]byte{}, - [][32]byte{ + []common.Root{ byteslib.ToBytes32([]byte("1")), byteslib.ToBytes32([]byte("2")), byteslib.ToBytes32([]byte("3")), @@ -94,7 +95,7 @@ func TestValidateBlockRoots(t *testing.T) { &eip4844.Blob{}, [48]byte{}, [48]byte{}, - [][32]byte{ + []common.Root{ byteslib.ToBytes32([]byte("1")), byteslib.ToBytes32([]byte("2")), byteslib.ToBytes32([]byte("3")), @@ -127,7 +128,7 @@ func TestValidateBlockRoots(t *testing.T) { &eip4844.Blob{}, eip4844.KZGCommitment{}, eip4844.KZGProof{}, - [][32]byte{ + []common.Root{ byteslib.ToBytes32([]byte("1")), byteslib.ToBytes32([]byte("2")), byteslib.ToBytes32([]byte("3")), diff --git a/mod/engine-primitives/pkg/engine-primitives/withdrawal.go b/mod/engine-primitives/pkg/engine-primitives/withdrawal.go index 9d90e54bc3..f91f5ef499 100644 --- a/mod/engine-primitives/pkg/engine-primitives/withdrawal.go +++ b/mod/engine-primitives/pkg/engine-primitives/withdrawal.go @@ -86,8 +86,8 @@ func (w *Withdrawal) DefineSSZ(c *ssz.Codec) { } // HashTreeRoot. -func (w *Withdrawal) HashTreeRoot() (common.Root, error) { - return ssz.HashSequential(w), nil +func (w *Withdrawal) HashTreeRoot() common.Root { + return ssz.HashSequential(w) } // MarshalSSZ marshals the Withdrawal object to SSZ format. diff --git a/mod/engine-primitives/pkg/engine-primitives/withdrawal_ssz_test.go b/mod/engine-primitives/pkg/engine-primitives/withdrawal_ssz_test.go index 7189f5ccc1..b2f60921a8 100644 --- a/mod/engine-primitives/pkg/engine-primitives/withdrawal_ssz_test.go +++ b/mod/engine-primitives/pkg/engine-primitives/withdrawal_ssz_test.go @@ -46,8 +46,7 @@ func TestWithdrawalSSZ(t *testing.T) { size := withdrawal.SizeSSZ() require.Equal(t, uint32(44), size) - tree, errHashTree := withdrawal.HashTreeRoot() - require.NoError(t, errHashTree) + tree := withdrawal.HashTreeRoot() require.NotNil(t, tree) } diff --git a/mod/node-api/backend/mocks/beacon_block_header.mock.go b/mod/node-api/backend/mocks/beacon_block_header.mock.go index dfc861550d..d563d803d6 100644 --- a/mod/node-api/backend/mocks/beacon_block_header.mock.go +++ b/mod/node-api/backend/mocks/beacon_block_header.mock.go @@ -254,7 +254,7 @@ func (_c *BeaconBlockHeader_GetStateRoot_Call[BeaconBlockHeaderT]) RunAndReturn( } // HashTreeRoot provides a mock function with given fields: -func (_m *BeaconBlockHeader[BeaconBlockHeaderT]) HashTreeRoot() (bytes.B32, error) { +func (_m *BeaconBlockHeader[BeaconBlockHeaderT]) HashTreeRoot() bytes.B32 { ret := _m.Called() if len(ret) == 0 { @@ -262,10 +262,6 @@ func (_m *BeaconBlockHeader[BeaconBlockHeaderT]) HashTreeRoot() (bytes.B32, erro } var r0 bytes.B32 - var r1 error - if rf, ok := ret.Get(0).(func() (bytes.B32, error)); ok { - return rf() - } if rf, ok := ret.Get(0).(func() bytes.B32); ok { r0 = rf() } else { @@ -274,13 +270,7 @@ func (_m *BeaconBlockHeader[BeaconBlockHeaderT]) HashTreeRoot() (bytes.B32, erro } } - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() - } else { - r1 = ret.Error(1) - } - - return r0, r1 + return r0 } // BeaconBlockHeader_HashTreeRoot_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HashTreeRoot' @@ -300,12 +290,12 @@ func (_c *BeaconBlockHeader_HashTreeRoot_Call[BeaconBlockHeaderT]) Run(run func( return _c } -func (_c *BeaconBlockHeader_HashTreeRoot_Call[BeaconBlockHeaderT]) Return(_a0 bytes.B32, _a1 error) *BeaconBlockHeader_HashTreeRoot_Call[BeaconBlockHeaderT] { - _c.Call.Return(_a0, _a1) +func (_c *BeaconBlockHeader_HashTreeRoot_Call[BeaconBlockHeaderT]) Return(_a0 bytes.B32) *BeaconBlockHeader_HashTreeRoot_Call[BeaconBlockHeaderT] { + _c.Call.Return(_a0) return _c } -func (_c *BeaconBlockHeader_HashTreeRoot_Call[BeaconBlockHeaderT]) RunAndReturn(run func() (bytes.B32, error)) *BeaconBlockHeader_HashTreeRoot_Call[BeaconBlockHeaderT] { +func (_c *BeaconBlockHeader_HashTreeRoot_Call[BeaconBlockHeaderT]) RunAndReturn(run func() bytes.B32) *BeaconBlockHeader_HashTreeRoot_Call[BeaconBlockHeaderT] { _c.Call.Return(run) return _c } diff --git a/mod/node-api/backend/mocks/beacon_state.mock.go b/mod/node-api/backend/mocks/beacon_state.mock.go index 08efcb3f13..470417fff4 100644 --- a/mod/node-api/backend/mocks/beacon_state.mock.go +++ b/mod/node-api/backend/mocks/beacon_state.mock.go @@ -1085,7 +1085,7 @@ func (_c *BeaconState_GetValidatorsByEffectiveBalance_Call[BeaconBlockHeaderT, E } // HashTreeRoot provides a mock function with given fields: -func (_m *BeaconState[BeaconBlockHeaderT, Eth1DataT, ExecutionPayloadHeaderT, ForkT, ValidatorT, ValidatorsT, WithdrawalT]) HashTreeRoot() (bytes.B32, error) { +func (_m *BeaconState[BeaconBlockHeaderT, Eth1DataT, ExecutionPayloadHeaderT, ForkT, ValidatorT, ValidatorsT, WithdrawalT]) HashTreeRoot() bytes.B32 { ret := _m.Called() if len(ret) == 0 { @@ -1093,10 +1093,6 @@ func (_m *BeaconState[BeaconBlockHeaderT, Eth1DataT, ExecutionPayloadHeaderT, Fo } var r0 bytes.B32 - var r1 error - if rf, ok := ret.Get(0).(func() (bytes.B32, error)); ok { - return rf() - } if rf, ok := ret.Get(0).(func() bytes.B32); ok { r0 = rf() } else { @@ -1105,13 +1101,7 @@ func (_m *BeaconState[BeaconBlockHeaderT, Eth1DataT, ExecutionPayloadHeaderT, Fo } } - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() - } else { - r1 = ret.Error(1) - } - - return r0, r1 + return r0 } // BeaconState_HashTreeRoot_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HashTreeRoot' @@ -1131,12 +1121,12 @@ func (_c *BeaconState_HashTreeRoot_Call[BeaconBlockHeaderT, Eth1DataT, Execution return _c } -func (_c *BeaconState_HashTreeRoot_Call[BeaconBlockHeaderT, Eth1DataT, ExecutionPayloadHeaderT, ForkT, ValidatorT, ValidatorsT, WithdrawalT]) Return(_a0 bytes.B32, _a1 error) *BeaconState_HashTreeRoot_Call[BeaconBlockHeaderT, Eth1DataT, ExecutionPayloadHeaderT, ForkT, ValidatorT, ValidatorsT, WithdrawalT] { - _c.Call.Return(_a0, _a1) +func (_c *BeaconState_HashTreeRoot_Call[BeaconBlockHeaderT, Eth1DataT, ExecutionPayloadHeaderT, ForkT, ValidatorT, ValidatorsT, WithdrawalT]) Return(_a0 bytes.B32) *BeaconState_HashTreeRoot_Call[BeaconBlockHeaderT, Eth1DataT, ExecutionPayloadHeaderT, ForkT, ValidatorT, ValidatorsT, WithdrawalT] { + _c.Call.Return(_a0) return _c } -func (_c *BeaconState_HashTreeRoot_Call[BeaconBlockHeaderT, Eth1DataT, ExecutionPayloadHeaderT, ForkT, ValidatorT, ValidatorsT, WithdrawalT]) RunAndReturn(run func() (bytes.B32, error)) *BeaconState_HashTreeRoot_Call[BeaconBlockHeaderT, Eth1DataT, ExecutionPayloadHeaderT, ForkT, ValidatorT, ValidatorsT, WithdrawalT] { +func (_c *BeaconState_HashTreeRoot_Call[BeaconBlockHeaderT, Eth1DataT, ExecutionPayloadHeaderT, ForkT, ValidatorT, ValidatorsT, WithdrawalT]) RunAndReturn(run func() bytes.B32) *BeaconState_HashTreeRoot_Call[BeaconBlockHeaderT, Eth1DataT, ExecutionPayloadHeaderT, ForkT, ValidatorT, ValidatorsT, WithdrawalT] { _c.Call.Return(run) return _c } diff --git a/mod/node-api/handlers/proof/merkle/execution.go b/mod/node-api/handlers/proof/merkle/execution.go index 729cd80799..4f06e8f006 100644 --- a/mod/node-api/handlers/proof/merkle/execution.go +++ b/mod/node-api/handlers/proof/merkle/execution.go @@ -109,13 +109,8 @@ func verifyExecutionNumberInBlock( proof []common.Root, leaf common.Root, ) (common.Root, error) { - beaconRoot, err := bbh.HashTreeRoot() - if err != nil { - return common.Root{}, err - } - - var beaconRootVerified bool - if beaconRootVerified, err = merkle.VerifyProof( + beaconRoot := bbh.HashTreeRoot() + if beaconRootVerified, err := merkle.VerifyProof( ExecutionPayloadNumberGIndexDenebBlock, leaf, proof, beaconRoot, ); err != nil { diff --git a/mod/node-api/handlers/proof/merkle/proposer.go b/mod/node-api/handlers/proof/merkle/proposer.go index 9227aa0904..03210b9dae 100644 --- a/mod/node-api/handlers/proof/merkle/proposer.go +++ b/mod/node-api/handlers/proof/merkle/proposer.go @@ -117,13 +117,8 @@ func verifyProposerInBlock( proof []common.Root, leaf common.Root, ) (common.Root, error) { - beaconRoot, err := bbh.HashTreeRoot() - if err != nil { - return common.Root{}, err - } - - var beaconRootVerified bool - if beaconRootVerified, err = merkle.VerifyProof( + beaconRoot := bbh.HashTreeRoot() + if beaconRootVerified, err := merkle.VerifyProof( merkle.GeneralizedIndex(ZeroValidatorPubkeyGIndexDenebBlock+valOffset), leaf, proof, beaconRoot, ); err != nil { diff --git a/mod/primitives/pkg/bytes/b20.go b/mod/primitives/pkg/bytes/b20.go index c5a40df010..d143e0149f 100644 --- a/mod/primitives/pkg/bytes/b20.go +++ b/mod/primitives/pkg/bytes/b20.go @@ -72,19 +72,12 @@ func (h *B20) UnmarshalJSON(input []byte) error { /* SSZMarshaler */ /* -------------------------------------------------------------------------- */ -// SizeSSZ returns the size of its SSZ encoding in bytes. -func (h B20) SizeSSZ() uint32 { - return B20Size -} - // MarshalSSZ implements the SSZ marshaling for B20. func (h B20) MarshalSSZ() ([]byte, error) { return h[:], nil } // HashTreeRoot returns the hash tree root of the B20. -func (h B20) HashTreeRoot() (B32, error) { - var result [32]byte - copy(result[:], h[:]) - return result, nil +func (h B20) HashTreeRoot() B32 { + return ToBytes32(h[:]) } diff --git a/mod/primitives/pkg/bytes/b20_test.go b/mod/primitives/pkg/bytes/b20_test.go index efd2c07beb..ef7aedfd77 100644 --- a/mod/primitives/pkg/bytes/b20_test.go +++ b/mod/primitives/pkg/bytes/b20_test.go @@ -73,30 +73,6 @@ func TestBytes20MarshalText(t *testing.T) { } } -func TestBytes20SizeSSZ(t *testing.T) { - tests := []struct { - name string - input bytes.B20 - want uint32 - }{ - { - name: "size of B20", - input: bytes.B20{ - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, - 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, - }, - want: bytes.B20Size, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := tt.input.SizeSSZ() - require.Equal(t, tt.want, got, "Test case: %s", tt.name) - }) - } -} - func TestBytes20MarshalSSZ(t *testing.T) { tests := []struct { name string @@ -147,8 +123,7 @@ func TestBytes20HashTreeRoot(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := tt.input.HashTreeRoot() - require.NoError(t, err, "Test case: %s", tt.name) + got := tt.input.HashTreeRoot() require.Equal(t, tt.want, got, "Test case: %s", tt.name) }) } diff --git a/mod/primitives/pkg/bytes/b32.go b/mod/primitives/pkg/bytes/b32.go index a8e4f6a12d..b42520b628 100644 --- a/mod/primitives/pkg/bytes/b32.go +++ b/mod/primitives/pkg/bytes/b32.go @@ -37,7 +37,9 @@ type B32 [32]byte // ToBytes32 is a utility function that transforms a byte slice into a fixed // 32-byte array. If the input exceeds 32 bytes, it gets truncated. func ToBytes32(input []byte) B32 { - return B32(ExtendToSize(input, B32Size)) + var b B32 + copy(b[:], input) + return b } /* -------------------------------------------------------------------------- */ @@ -72,17 +74,12 @@ func (h *B32) UnmarshalJSON(input []byte) error { /* SSZMarshaler */ /* -------------------------------------------------------------------------- */ -// SizeSSZ returns the size of its SSZ encoding in bytes. -func (h B32) SizeSSZ() uint32 { - return B32Size -} - // MarshalSSZ implements the SSZ marshaling for B32. func (h B32) MarshalSSZ() ([]byte, error) { return h[:], nil } // HashTreeRoot returns the hash tree root of the B32. -func (h B32) HashTreeRoot() (B32, error) { - return h, nil +func (h B32) HashTreeRoot() B32 { + return h } diff --git a/mod/primitives/pkg/bytes/b32_test.go b/mod/primitives/pkg/bytes/b32_test.go index f15fdc6e99..5409d08868 100644 --- a/mod/primitives/pkg/bytes/b32_test.go +++ b/mod/primitives/pkg/bytes/b32_test.go @@ -27,12 +27,6 @@ import ( "github.com/stretchr/testify/require" ) -func TestB32SizeSSZ(t *testing.T) { - var b bytes.B32 - require.Equal(t, bytes.B32Size, int(b.SizeSSZ()), - "SizeSSZ should return the correct size") -} - func TestB32MarshalSSZ(t *testing.T) { tests := []struct { name string diff --git a/mod/primitives/pkg/bytes/b4.go b/mod/primitives/pkg/bytes/b4.go index a214f43cf2..adca0ea115 100644 --- a/mod/primitives/pkg/bytes/b4.go +++ b/mod/primitives/pkg/bytes/b4.go @@ -18,7 +18,7 @@ // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND // TITLE. // - +//nolint:dupl // it's okay. package bytes import ( @@ -67,3 +67,17 @@ func (h B4) String() string { func (h *B4) UnmarshalJSON(input []byte) error { return unmarshalJSONHelper(h[:], input) } + +/* -------------------------------------------------------------------------- */ +/* SSZMarshaler */ +/* -------------------------------------------------------------------------- */ + +// MarshalSSZ implements the SSZ marshaling for B8. +func (h B4) MarshalSSZ() ([]byte, error) { + return h[:], nil +} + +// HashTreeRoot returns the hash tree root of the B8. +func (h B4) HashTreeRoot() B32 { + return ToBytes32(h[:]) +} diff --git a/mod/primitives/pkg/bytes/b48.go b/mod/primitives/pkg/bytes/b48.go index f96b2b7847..6e8ffd482c 100644 --- a/mod/primitives/pkg/bytes/b48.go +++ b/mod/primitives/pkg/bytes/b48.go @@ -73,21 +73,16 @@ func (h *B48) UnmarshalJSON(input []byte) error { /* SSZMarshaler */ /* -------------------------------------------------------------------------- */ -// SizeSSZ returns the size of its SSZ encoding in bytes. -func (h B48) SizeSSZ() uint32 { - return B48Size -} - // MarshalSSZ implements the SSZ marshaling for B48. func (h B48) MarshalSSZ() ([]byte, error) { return h[:], nil } -func (h B48) HashTreeRoot() (B32, error) { +func (h B48) HashTreeRoot() B32 { //nolint:mnd // for a tree height of 1 we need 2 working chunks. result := make([][32]byte, 2) copy(result[0][:], h[:32]) copy(result[1][:], h[32:48]) gohashtree.HashChunks(result, result) - return result[0], nil + return result[0] } diff --git a/mod/primitives/pkg/bytes/b48_test.go b/mod/primitives/pkg/bytes/b48_test.go index 68b697db9f..979b4b2452 100644 --- a/mod/primitives/pkg/bytes/b48_test.go +++ b/mod/primitives/pkg/bytes/b48_test.go @@ -43,19 +43,12 @@ func TestB48_HashTreeRoot(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - result, err := tt.input.HashTreeRoot() - require.NoError(t, err) + result := tt.input.HashTreeRoot() require.Equal(t, tt.want, result) }) } } -func TestB48SizeSSZ(t *testing.T) { - var b bytes.B48 - require.Equal(t, bytes.B48Size, int(b.SizeSSZ()), - "SizeSSZ should return the correct size") -} - func TestB48MarshalSSZ(t *testing.T) { tests := []struct { name string diff --git a/mod/primitives/pkg/bytes/b8.go b/mod/primitives/pkg/bytes/b8.go index 85d9193571..88722897c5 100644 --- a/mod/primitives/pkg/bytes/b8.go +++ b/mod/primitives/pkg/bytes/b8.go @@ -18,7 +18,7 @@ // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND // TITLE. // - +//nolint:dupl // it's okay. package bytes import ( @@ -72,19 +72,12 @@ func (h *B8) UnmarshalJSON(input []byte) error { /* SSZMarshaler */ /* -------------------------------------------------------------------------- */ -// SizeSSZ returns the size of its SSZ encoding in bytes. -func (h B8) SizeSSZ() uint32 { - return B8Size -} - // MarshalSSZ implements the SSZ marshaling for B8. func (h B8) MarshalSSZ() ([]byte, error) { return h[:], nil } // HashTreeRoot returns the hash tree root of the B8. -func (h B8) HashTreeRoot() (B32, error) { - var result [32]byte - copy(result[:], h[:]) - return result, nil +func (h B8) HashTreeRoot() B32 { + return ToBytes32(h[:]) } diff --git a/mod/primitives/pkg/bytes/b8_test.go b/mod/primitives/pkg/bytes/b8_test.go index fa3607c5d5..8fac38bd68 100644 --- a/mod/primitives/pkg/bytes/b8_test.go +++ b/mod/primitives/pkg/bytes/b8_test.go @@ -27,27 +27,6 @@ import ( "github.com/stretchr/testify/require" ) -func TestBytes8SizeSSZ(t *testing.T) { - tests := []struct { - name string - input bytes.B8 - want uint32 - }{ - { - name: "size of B8", - input: bytes.B8{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, - want: bytes.B8Size, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := tt.input.SizeSSZ() - require.Equal(t, tt.want, got, "Test case: %s", tt.name) - }) - } -} - func TestBytes8MarshalSSZ(t *testing.T) { tests := []struct { name string @@ -85,8 +64,7 @@ func TestBytes8HashTreeRoot(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := tt.input.HashTreeRoot() - require.NoError(t, err, "Test case: %s", tt.name) + got := tt.input.HashTreeRoot() require.Equal(t, tt.want, got, "Test case: %s", tt.name) }) } diff --git a/mod/primitives/pkg/bytes/b96.go b/mod/primitives/pkg/bytes/b96.go index 9d086b2442..b31df36e59 100644 --- a/mod/primitives/pkg/bytes/b96.go +++ b/mod/primitives/pkg/bytes/b96.go @@ -73,18 +73,13 @@ func (h *B96) UnmarshalJSON(input []byte) error { /* SSZMarshaler */ /* -------------------------------------------------------------------------- */ -// SizeSSZ returns the size of its SSZ encoding in bytes. -func (h B96) SizeSSZ() uint32 { - return B96Size -} - // MarshalSSZ implements the SSZ marshaling for B96. func (h B96) MarshalSSZ() ([]byte, error) { return h[:], nil } // HashTreeRoot returns the hash tree root of the B96. -func (h B96) HashTreeRoot() (B32, error) { +func (h B96) HashTreeRoot() B32 { //nolint:mnd // for a tree height of 2 we need 4 working chunks. result := make([][32]byte, 4) copy(result[0][:], h[:32]) @@ -92,5 +87,5 @@ func (h B96) HashTreeRoot() (B32, error) { copy(result[2][:], h[64:96]) gohashtree.HashChunks(result, result) gohashtree.HashChunks(result, result) - return result[0], nil + return result[0] } diff --git a/mod/primitives/pkg/bytes/b96_test.go b/mod/primitives/pkg/bytes/b96_test.go index cae00a1c78..d8e5f1f899 100644 --- a/mod/primitives/pkg/bytes/b96_test.go +++ b/mod/primitives/pkg/bytes/b96_test.go @@ -45,8 +45,7 @@ func TestB96_HashTreeRoot(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - result, err := tt.input.HashTreeRoot() - require.NoError(t, err) + result := tt.input.HashTreeRoot() require.Equal(t, tt.want, result) }) } @@ -74,12 +73,6 @@ func BenchmarkB96_UnmarshalJSON(b *testing.B) { } } -func TestB96SizeSSZ(t *testing.T) { - var b bytes.B96 - require.Equal(t, bytes.B96Size, int(b.SizeSSZ()), - "SizeSSZ should return the correct size") -} - func TestB96MarshalSSZ(t *testing.T) { tests := []struct { name string diff --git a/mod/primitives/pkg/bytes/b_test.go b/mod/primitives/pkg/bytes/b_test.go index 86af2cd49b..612d72cd6b 100644 --- a/mod/primitives/pkg/bytes/b_test.go +++ b/mod/primitives/pkg/bytes/b_test.go @@ -594,8 +594,7 @@ func TestHashTreeRoot(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - result, err := tt.input.HashTreeRoot() - require.NoError(t, err, "Test case: %s", tt.name) + result := tt.input.HashTreeRoot() require.Equal(t, tt.want, result, "Test case: %s", tt.name) }) } diff --git a/mod/primitives/pkg/constraints/encoding.go b/mod/primitives/pkg/constraints/encoding.go index a774415abe..8d6fbaa95a 100644 --- a/mod/primitives/pkg/constraints/encoding.go +++ b/mod/primitives/pkg/constraints/encoding.go @@ -44,7 +44,7 @@ type SSZUnmarshaler interface { // their hash tree root. type SSZRootable interface { // HashTreeRoot computes the hash tree root of the object. - HashTreeRoot() (common.Root, error) + HashTreeRoot() common.Root } // SSZMarshallable is an interface that combines diff --git a/mod/primitives/pkg/eip4844/kzg_commitment.go b/mod/primitives/pkg/eip4844/kzg_commitment.go index 2db77b57aa..afe53bf9ae 100644 --- a/mod/primitives/pkg/eip4844/kzg_commitment.go +++ b/mod/primitives/pkg/eip4844/kzg_commitment.go @@ -54,9 +54,9 @@ func (c KZGCommitment) ToHashChunks() [][32]byte { } // HashTreeRoot returns the hash tree root of the commitment. -func (c KZGCommitment) HashTreeRoot() (common.Root, error) { +func (c KZGCommitment) HashTreeRoot() common.Root { chunks := c.ToHashChunks() - return chunks[0], nil + return chunks[0] } // UnmarshalJSON parses a commitment in hex syntax. @@ -89,15 +89,10 @@ func (c KZGCommitments[HashT]) ToVersionedHashes() []HashT { // Leafify converts the commitments to a slice of leaves. Each leaf is the // hash tree root of each commitment. -func (c KZGCommitments[HashT]) Leafify() ([][32]byte, error) { - var ( - leaves = make([][32]byte, len(c)) - err error - ) +func (c KZGCommitments[HashT]) Leafify() []common.Root { + leaves := make([]common.Root, len(c)) for i, commitment := range c { - if leaves[i], err = commitment.HashTreeRoot(); err != nil { - return nil, err - } + leaves[i] = commitment.HashTreeRoot() } - return leaves, nil + return leaves } diff --git a/mod/primitives/pkg/eip4844/kzg_commitment_test.go b/mod/primitives/pkg/eip4844/kzg_commitment_test.go index e7dcdaa92a..0345b7cd8e 100644 --- a/mod/primitives/pkg/eip4844/kzg_commitment_test.go +++ b/mod/primitives/pkg/eip4844/kzg_commitment_test.go @@ -97,8 +97,7 @@ func TestKZGCommitmentHashTreeRoot(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - hashTreeRoot, err := tt.input.HashTreeRoot() - require.NoError(t, err) + hashTreeRoot := tt.input.HashTreeRoot() require.Equal( t, tt.expected, @@ -228,14 +227,12 @@ func TestKZGCommitments_Leafify(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Dynamically compute expected values based on input - expected := make([][32]byte, len(tt.input)) + expected := make([]common.Root, len(tt.input)) for i, commitment := range tt.input { expected[i] = commitment.ToHashChunks()[0] } - commitments := eip4844.KZGCommitments[[32]byte](tt.input) - leaves, err := commitments.Leafify() - require.NoError(t, err) + leaves := eip4844.KZGCommitments[common.Root](tt.input).Leafify() require.Equal(t, expected, leaves, "Leaves do not match expected for test: "+tt.name) }) diff --git a/mod/primitives/pkg/merkle/tree.go b/mod/primitives/pkg/merkle/tree.go index 9570f61f4a..7d4c6e6ff1 100644 --- a/mod/primitives/pkg/merkle/tree.go +++ b/mod/primitives/pkg/merkle/tree.go @@ -177,17 +177,17 @@ func (m *Tree[RootT]) Root() [32]byte { // HashTreeRoot returns the Root of the Merkle tree with the // number of leaves mixed in. -func (m *Tree[RootT]) HashTreeRoot() (common.Root, error) { +func (m *Tree[RootT]) HashTreeRoot() common.Root { numItems := uint64(len(m.leaves)) if len(m.leaves) == 1 && m.leaves[0] == zero.Hashes[0] { numItems = 0 } - return m.hasher.MixIn(m.Root(), numItems), nil + return m.hasher.MixIn(m.Root(), numItems) } // MerkleProof computes a proof from a tree's branches using a Merkle index. -func (m *Tree[RootT]) MerkleProof(leafIndex uint64) ([][32]byte, error) { +func (m *Tree[RootT]) MerkleProof(leafIndex uint64) ([]RootT, error) { numLeaves := uint64(len(m.branches[0])) if leafIndex >= numLeaves { return nil, errors.Newf( @@ -196,7 +196,7 @@ func (m *Tree[RootT]) MerkleProof(leafIndex uint64) ([][32]byte, error) { leafIndex, ) } - proof := make([][32]byte, m.depth) + proof := make([]RootT, m.depth) for i := range m.depth { subIndex := (leafIndex >> i) ^ 1 if subIndex < uint64(len(m.branches[i])) { @@ -212,7 +212,7 @@ func (m *Tree[RootT]) MerkleProof(leafIndex uint64) ([][32]byte, error) { // index. func (m *Tree[RootT]) MerkleProofWithMixin( index uint64, -) ([][32]byte, error) { +) ([]RootT, error) { proof, err := m.MerkleProof(index) if err != nil { return nil, err diff --git a/mod/primitives/pkg/merkle/tree_fuzz_test.go b/mod/primitives/pkg/merkle/tree_fuzz_test.go index 98e4293086..be36dd7ae8 100644 --- a/mod/primitives/pkg/merkle/tree_fuzz_test.go +++ b/mod/primitives/pkg/merkle/tree_fuzz_test.go @@ -60,8 +60,7 @@ func FuzzTree_IsValidMerkleBranch(f *testing.F) { proof, err := m.MerkleProofWithMixin(0) require.NoError(f, err) require.Len(f, proof, int(depth)+1) - root, err := m.HashTreeRoot() - require.NoError(f, err) + root := m.HashTreeRoot() var proofRaw []byte for _, p := range proof { proofRaw = append(proofRaw, p[:]...) diff --git a/mod/primitives/pkg/merkle/tree_test.go b/mod/primitives/pkg/merkle/tree_test.go index bb6e361311..6b97b8232e 100644 --- a/mod/primitives/pkg/merkle/tree_test.go +++ b/mod/primitives/pkg/merkle/tree_test.go @@ -91,8 +91,7 @@ func TestMerkleTree_IsValidMerkleBranch(t *testing.T) { int(treeDepth)+1, ) - root, err := m.HashTreeRoot() - require.NoError(t, err) + root := m.HashTreeRoot() require.True(t, merkle.VerifyProof( root, items[0], 0, proof, ), "First Merkle proof did not verify") @@ -145,8 +144,7 @@ func TestMerkleTree_VerifyProof(t *testing.T) { proof, int(treeDepth)+1, ) - root, err := m.HashTreeRoot() - require.NoError(t, err) + root := m.HashTreeRoot() if ok := merkle.VerifyProof(root, items[0], 0, proof); !ok { t.Error("First Merkle proof did not verify") } @@ -200,8 +198,7 @@ func TestMerkleTree_VerifyProof_TrieUpdated(t *testing.T) { require.NoError(t, err) proof, err := m.MerkleProofWithMixin(0) require.NoError(t, err) - root, err := m.HashTreeRoot() - require.NoError(t, err) + root := m.HashTreeRoot() require.True( t, merkle.VerifyProof( @@ -216,8 +213,7 @@ func TestMerkleTree_VerifyProof_TrieUpdated(t *testing.T) { require.NoError(t, m.Insert(byteslib.ToBytes32([]byte{5}), 3)) proof, err = m.MerkleProofWithMixin(3) require.NoError(t, err) - root, err = m.HashTreeRoot() - require.NoError(t, err) + root = m.HashTreeRoot() require.True(t, merkle.VerifyProof( root, [32]byte{5}, 3, proof, ), "Second Merkle proof did not verify") @@ -316,12 +312,10 @@ func BenchmarkIsValidMerkleBranch(b *testing.B) { proof, err := m.MerkleProofWithMixin(2) require.NoError(b, err) - root, err := m.HashTreeRoot() - require.NoError(b, err) b.StartTimer() for i := 0; i < b.N; i++ { ok := merkle.IsValidMerkleBranch( - items[2], proof, treeDepth+1, 2, root, + items[2], proof, treeDepth+1, 2, m.HashTreeRoot(), ) require.True(b, ok, "Merkle proof did not verify") } diff --git a/mod/state-transition/pkg/core/interfaces.go b/mod/state-transition/pkg/core/interfaces.go index 8cd1cd4ee2..600636f89f 100644 --- a/mod/state-transition/pkg/core/interfaces.go +++ b/mod/state-transition/pkg/core/interfaces.go @@ -48,7 +48,7 @@ type BeaconState[ Copy() T Save() Context() context.Context - HashTreeRoot() (common.Root, error) + HashTreeRoot() common.Root ReadOnlyBeaconState[ BeaconBlockHeaderT, Eth1DataT, ExecutionPayloadHeaderT, ForkT, ValidatorT, ValidatorsT, WithdrawalT, diff --git a/mod/state-transition/pkg/core/state/statedb.go b/mod/state-transition/pkg/core/state/statedb.go index 8f5e126422..d27f817e03 100644 --- a/mod/state-transition/pkg/core/state/statedb.go +++ b/mod/state-transition/pkg/core/state/statedb.go @@ -404,10 +404,10 @@ func (s *StateDB[ // HashTreeRoot is the interface for the beacon store. func (s *StateDB[ _, _, _, _, _, _, _, _, _, _, -]) HashTreeRoot() (common.Root, error) { +]) HashTreeRoot() common.Root { st, err := s.GetMarshallable() if err != nil { - return [32]byte{}, err + panic(err) } return st.HashTreeRoot() } diff --git a/mod/state-transition/pkg/core/state_processor.go b/mod/state-transition/pkg/core/state_processor.go index 9425216cef..08236c12e4 100644 --- a/mod/state-transition/pkg/core/state_processor.go +++ b/mod/state-transition/pkg/core/state_processor.go @@ -230,12 +230,7 @@ func (sp *StateProcessor[ } // Before we make any changes, we calculate the previous state root. - prevStateRoot, err := st.HashTreeRoot() - if err != nil { - return err - } - - // We update our state roots and block roots. + prevStateRoot := st.HashTreeRoot() if err = st.UpdateStateRootAtIndex( stateSlot.Unwrap()%sp.cs.SlotsPerHistoricalRoot(), prevStateRoot, ); err != nil { @@ -259,19 +254,10 @@ func (sp *StateProcessor[ } // We update the block root. - var prevBlockRoot common.Root - prevBlockRoot, err = latestHeader.HashTreeRoot() - if err != nil { - return err - } - - if err = st.UpdateBlockRootAtIndex( - stateSlot.Unwrap()%sp.cs.SlotsPerHistoricalRoot(), prevBlockRoot, - ); err != nil { - return err - } - - return nil + return st.UpdateBlockRootAtIndex( + stateSlot.Unwrap()%sp.cs.SlotsPerHistoricalRoot(), + latestHeader.HashTreeRoot(), + ) } // ProcessBlock processes the block, it optionally verifies the @@ -331,9 +317,8 @@ func (sp *StateProcessor[ // Ensure the calculated state root matches the state root on // the block. - if stateRoot, err := st.HashTreeRoot(); err != nil { - return err - } else if blk.GetStateRoot() != stateRoot { + stateRoot := st.HashTreeRoot() + if blk.GetStateRoot() != st.HashTreeRoot() { return errors.Wrapf( ErrStateRootMismatch, "expected %s, got %s", stateRoot, blk.GetStateRoot(), @@ -372,9 +357,8 @@ func (sp *StateProcessor[ slot math.Slot err error latestBlockHeader BeaconBlockHeaderT - parentBlockRoot common.Root - bodyRoot common.Root - proposer ValidatorT + + proposer ValidatorT ) // Ensure the block slot matches the state slot. @@ -396,9 +380,10 @@ func (sp *StateProcessor[ ErrBlockSlotTooLow, "expected: > %d, got: %d", latestBlockHeader.GetSlot(), blk.GetSlot(), ) - } else if parentBlockRoot, err = latestBlockHeader.HashTreeRoot(); err != nil { - return err - } else if parentBlockRoot != blk.GetParentBlockRoot() { + } + + if parentBlockRoot := latestBlockHeader. + HashTreeRoot(); parentBlockRoot != blk.GetParentBlockRoot() { return errors.Wrapf(ErrParentRootMismatch, "expected: %s, got: %s", parentBlockRoot.String(), blk.GetParentBlockRoot().String(), @@ -417,9 +402,8 @@ func (sp *StateProcessor[ // Calculate the body root to place on the header. var lbh BeaconBlockHeaderT - if bodyRoot, err = blk.GetBody().HashTreeRoot(); err != nil { - return err - } else if err = st.SetLatestBlockHeader( + bodyRoot := blk.GetBody().HashTreeRoot() + if err = st.SetLatestBlockHeader( lbh.New( blk.GetSlot(), blk.GetProposerIndex(), diff --git a/mod/state-transition/pkg/core/state_processor_genesis.go b/mod/state-transition/pkg/core/state_processor_genesis.go index 9548ef41c1..6da48220fd 100644 --- a/mod/state-transition/pkg/core/state_processor_genesis.go +++ b/mod/state-transition/pkg/core/state_processor_genesis.go @@ -75,20 +75,16 @@ func (sp *StateProcessor[ // TODO: we need to handle common.Version vs // uint32 better. - bodyRoot, err := blkBody.Empty( + bodyRoot := blkBody.Empty( version.ToUint32(genesisVersion)).HashTreeRoot() - if err != nil { - return nil, err - } - - if err = st.SetLatestBlockHeader(blkHeader.New( + if err := st.SetLatestBlockHeader(blkHeader.New( 0, 0, common.Root{}, common.Root{}, bodyRoot, )); err != nil { return nil, err } for i := range sp.cs.EpochsPerHistoricalVector() { - if err = st.UpdateRandaoMixAtIndex( + if err := st.UpdateRandaoMixAtIndex( i, common.Bytes32(executionPayloadHeader.GetBlockHash()), ); err != nil { @@ -97,8 +93,7 @@ func (sp *StateProcessor[ } for _, deposit := range deposits { - // TODO: process deposits into eth1 data. - if err = sp.processDeposit(st, deposit); err != nil { + if err := sp.processDeposit(st, deposit); err != nil { return nil, err } } diff --git a/mod/state-transition/pkg/core/state_processor_randao.go b/mod/state-transition/pkg/core/state_processor_randao.go index d0ec7f2ea7..8ed85d81e5 100644 --- a/mod/state-transition/pkg/core/state_processor_randao.go +++ b/mod/state-transition/pkg/core/state_processor_randao.go @@ -66,13 +66,9 @@ func (sp *StateProcessor[ ) if !skipVerification { - var signingRoot common.Root - signingRoot, err = fd.ComputeRandaoSigningRoot( - sp.cs.DomainTypeRandao(), epoch) - if err != nil { - return err - } - + signingRoot := fd.ComputeRandaoSigningRoot( + sp.cs.DomainTypeRandao(), epoch, + ) reveal := body.GetRandaoReveal() if err = sp.signer.VerifySignature( proposer.GetPubkey(), diff --git a/mod/state-transition/pkg/core/types.go b/mod/state-transition/pkg/core/types.go index 06ddf06180..b99a8fd092 100644 --- a/mod/state-transition/pkg/core/types.go +++ b/mod/state-transition/pkg/core/types.go @@ -78,7 +78,7 @@ type BeaconBlockBody[ // GetDeposits returns the list of deposits. GetDeposits() []DepositT // HashTreeRoot returns the hash tree root of the block body. - HashTreeRoot() (common.Root, error) + HashTreeRoot() common.Root // GetBlobKzgCommitments returns the KZG commitments for the blobs. GetBlobKzgCommitments() eip4844.KZGCommitments[gethprimitives.ExecutionHash] } @@ -92,7 +92,7 @@ type BeaconBlockHeader[BeaconBlockHeaderT any] interface { stateRoot common.Root, bodyRoot common.Root, ) BeaconBlockHeaderT - HashTreeRoot() (common.Root, error) + HashTreeRoot() common.Root GetSlot() math.Slot GetProposerIndex() math.ValidatorIndex GetParentBlockRoot() common.Root @@ -196,7 +196,7 @@ type ForkData[ForkDataT any] interface { ComputeRandaoSigningRoot( domainType common.DomainType, epoch math.Epoch, - ) (common.Root, error) + ) common.Root } // Validator represents an interface for a validator with generic type diff --git a/mod/storage/pkg/block/store.go b/mod/storage/pkg/block/store.go index 3987bec539..cf47182844 100644 --- a/mod/storage/pkg/block/store.go +++ b/mod/storage/pkg/block/store.go @@ -95,11 +95,8 @@ func (kv *KVStore[BeaconBlockT]) Set(slot uint64, blk BeaconBlockT) error { kv.mu.Lock() defer kv.mu.Unlock() kv.cdc.SetActiveForkVersion(blk.Version()) - root, err := blk.HashTreeRoot() - if err != nil { - return err - } - if err = kv.roots.Set(context.TODO(), root[:], slot); err != nil { + root := blk.HashTreeRoot() + if err := kv.roots.Set(context.TODO(), root[:], slot); err != nil { return err } return kv.blocks.Set(context.TODO(), slot, blk) diff --git a/mod/storage/pkg/block/types.go b/mod/storage/pkg/block/types.go index a34ad74b58..0e83476395 100644 --- a/mod/storage/pkg/block/types.go +++ b/mod/storage/pkg/block/types.go @@ -29,5 +29,5 @@ type BeaconBlock[T any] interface { constraints.SSZMarshallable NewFromSSZ(bz []byte, version uint32) (T, error) Version() uint32 - HashTreeRoot() (common.Root, error) + HashTreeRoot() common.Root } diff --git a/testing/quick/compare_test.go b/testing/quick/compare_test.go index e79e6666ef..5276d7d938 100644 --- a/testing/quick/compare_test.go +++ b/testing/quick/compare_test.go @@ -56,11 +56,7 @@ func TestExecutionPayloadHashTreeRootZrnt(t *testing.T) { payload.LogsBloom = logsBloom payload.BaseFeePerGas = math.NewU256(123) - typeRoot, err := payload.HashTreeRoot() - if err != nil { - t.Log("Failed to calculate HashTreeRoot on payload:", err) - return false - } + typeRoot := payload.HashTreeRoot() baseFeePerGas := zview.Uint256View{} baseFeePerGas.SetFromBig(payload.BaseFeePerGas.ToBig()) @@ -84,13 +80,9 @@ func TestExecutionPayloadHashTreeRootZrnt(t *testing.T) { BlobGasUsed: zview.Uint64View(payload.BlobGasUsed.Unwrap()), ExcessBlobGas: zview.Uint64View(payload.ExcessBlobGas.Unwrap()), } - zRoot := zpayload.HashTreeRoot(spec, hFn) - containerRoot, err := payload.HashTreeRoot() - if err != nil { - t.Log("Failed to calculate HashTreeRoot on container payload:", err) - return false - } + zRoot := zpayload.HashTreeRoot(spec, hFn) + containerRoot := payload.HashTreeRoot() return bytes.Equal(typeRoot[:], containerRoot[:]) && bytes.Equal(typeRoot[:], zRoot[:])