Skip to content

Commit

Permalink
Merge branch 'main' into decouple-runtime
Browse files Browse the repository at this point in the history
  • Loading branch information
archbear authored Jun 19, 2024
2 parents 1ed9c26 + 72a9b26 commit 166be22
Show file tree
Hide file tree
Showing 6 changed files with 162 additions and 81 deletions.
21 changes: 14 additions & 7 deletions build/scripts/devtools.mk
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,20 @@ yap: ## the yap cave
@go run ./mod/cli/pkg/utils/yap/yap.go

tidy-sync-check:
@$(MAKE) repo-rinse tidy sync
@if [ -n "$$(git status --porcelain)" ]; then \
@{ \
pre_tidy_diff=$$(git diff --ignore-space-change); \
$(MAKE) repo-rinse tidy sync; \
post_tidy_diff=$$(git diff --ignore-space-change); \
echo "$$pre_tidy_diff" > pre_tidy.diff; \
echo "$$post_tidy_diff" > post_tidy.diff; \
cmp -s pre_tidy.diff post_tidy.diff; \
diff_status=$$?; \
if [ $$diff_status -ne 0 ]; then \
echo "Tidy and sync operations resulted in changes"; \
git status -s; \
git diff --exit-code; \
fi

diff pre_tidy.diff post_tidy.diff; \
fi; \
rm -f pre_tidy.diff post_tidy.diff; \
exit $$diff_status; \
}

.PHONY: format build test-unit bet

1 change: 1 addition & 0 deletions mod/cli/pkg/commands/genesis/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ func Commands(
AddGenesisDepositCmd(cs),
CollectGenesisDepositsCmd(),
AddExecutionPayloadCmd(),
GetGenesisValidatorRootCmd(cs),
)

// Add additional commands
Expand Down
97 changes: 97 additions & 0 deletions mod/cli/pkg/commands/genesis/root.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// 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 genesis

import (
"encoding/json"

"github.com/berachain/beacon-kit/mod/consensus-types/pkg/types"
"github.com/berachain/beacon-kit/mod/errors"
"github.com/berachain/beacon-kit/mod/primitives"
"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/math"
"github.com/berachain/beacon-kit/mod/primitives/pkg/ssz"
"github.com/spf13/afero"
"github.com/spf13/cobra"
)

type Genesis struct {
AppState struct {
Beacon struct {
Deposits []struct {
Pubkey bytes.B48 `json:"pubkey"`
Credentials bytes.B32 `json:"credentials"`
Amount math.U64 `json:"amount"`
Signature string `json:"signature"`
Index int `json:"index"`
} `json:"deposits"`
} `json:"beacon"`
} `json:"app_state"`
}

func GetGenesisValidatorRootCmd(cs primitives.ChainSpec) *cobra.Command {
cmd := &cobra.Command{
Use: "validator-root [beacond/genesis.json]",
Short: "gets and returns the genesis validator root",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
// Read the genesis file.
genesisBz, err := afero.ReadFile(afero.NewOsFs(), args[0])
if err != nil {
return errors.Wrap(err, "failed to genesis json file")
}

var genesis Genesis
// Unmarshal JSON data into the Genesis struct
err = json.Unmarshal(genesisBz, &genesis)
if err != nil {
return errors.Wrap(err, "failed to unmarshal JSON")
}

depositCount := uint64(len(genesis.AppState.Beacon.Deposits))
validators := make([]*types.Validator, depositCount)
for i, deposit := range genesis.AppState.Beacon.Deposits {
var val *types.Validator
validators[i] = val.New(
deposit.Pubkey,
types.WithdrawalCredentials(deposit.Credentials),
deposit.Amount,
math.Gwei(cs.EffectiveBalanceIncrement()),
math.Gwei(cs.MaxEffectiveBalance()),
)
}

var validatorsRoot primitives.Root
validatorsRoot, err = ssz.MerkleizeListComposite[
common.ChainSpec, math.U64,
](validators, uint64(len(validators)))
if err != nil {
return errors.Wrap(err, "failed to get validators root")
}

cmd.Printf("%s\n", validatorsRoot)
return nil
},
}

return cmd
}
99 changes: 37 additions & 62 deletions mod/primitives/pkg/net/jwt/jwt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,13 @@
package jwt_test

import (
"reflect"
"strings"
"testing"

"github.com/berachain/beacon-kit/mod/primitives/pkg/common"
"github.com/berachain/beacon-kit/mod/primitives/pkg/hex"
"github.com/berachain/beacon-kit/mod/primitives/pkg/net/jwt"
"github.com/stretchr/testify/require"
)

func TestNewFromHex(t *testing.T) {
Expand Down Expand Up @@ -74,14 +74,11 @@ func TestNewFromHex(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := jwt.NewFromHex(tt.hexStr)
if (err != nil) != tt.wantErr {
t.Errorf("NewFromHex() error = %v, wantErr %v", err, tt.wantErr)
if tt.wantErr {
require.Error(t, err)
return
}

if !reflect.DeepEqual(got, tt.want) {
t.Errorf("NewFromHex() = %v, want %v", got, tt.want)
}
require.Equal(t, tt.want, got)
})
}
}
Expand All @@ -105,95 +102,73 @@ func TestSecretString(t *testing.T) {

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.secret.String(); got != tt.want {
t.Errorf("Secret.String() = %v, want %v", got, tt.want)
}
require.Equal(
t,
tt.want,
tt.secret.String(),
"Secret.String() mismatch",
)
})
}
}

func TestNewRandom(t *testing.T) {
secret, err := jwt.NewRandom()
if err != nil {
t.Errorf("NewRandom() error = %v, wantErr %v", err, false)
}
if len(secret) == 0 {
t.Errorf("NewRandom() generated an empty secret")
}

if len(secret.Bytes()) != 32 {
t.Errorf(
"NewRandom() generated a secret of incorrect length: got %d, want %d",
len(secret.Bytes()),
32,
)
}
require.NoError(t, err, "NewRandom() error")
require.Len(t, secret.Bytes(), 32, "NewRandom() length mismatch")
}

func TestSecretBytes(t *testing.T) {
expectedLength := 32 // Assuming the secret is expected to be 32 bytes long
secret, _ := jwt.NewRandom()
bytes := secret.Bytes()
if len(bytes) != expectedLength {
t.Errorf("Bytes() length = %d, want %d", len(bytes), expectedLength)
}
require.Len(t, bytes, expectedLength, "Bytes() length mismatch")
}

func TestSecretHexWithFixedInput(t *testing.T) {
expectedHex := "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"
// Since the secret is 32 bytes, its hex representation should be 64
// characters
// long
expectedHexLength := 64

secret, err := jwt.NewFromHex(expectedHex)
if err != nil {
t.Fatalf("NewFromHex() error = %v", err)
}
require.NoError(t, err, "NewFromHex() error")

hexStr := secret.Hex()
if hexStr != expectedHex {
t.Errorf("Hex() = %s, want %s", hexStr, expectedHex)
}
require.Equal(t, expectedHex, hexStr, "Hex() output mismatch")

// Check if the hex string is of the expected length and format.
if len(hexStr) != expectedHexLength+2 {
t.Errorf("Hex() length = %d, want %d", len(hexStr), expectedHexLength)
}
require.Len(t, hexStr, expectedHexLength+2, "Hex() length mismatch")

// Strip the '0x' prefix and check if the remaining string is valid hex.
hexStr = strings.TrimPrefix(hexStr, "0x")
if len(hexStr) != expectedHexLength {
t.Errorf(
"Hex() length after stripping '0x' = %d, want %d",
len(hexStr), expectedHexLength)
}

if !jwt.HexRegexp.MatchString(hexStr) {
t.Errorf(
"Hex() output does not match hexadecimal format, got: %s", hexStr,
)
}
require.Len(
t,
hexStr,
expectedHexLength,
"Hex() length after stripping '0x' mismatch",
)
require.True(
t,
jwt.HexRegexp.MatchString(hexStr),
"Hex() output does not match hexadecimal format",
)
}

func TestSecretRoundTripEncoding(t *testing.T) {
originalSecret, err := jwt.NewRandom()
if err != nil {
t.Fatalf("NewRandom() error = %v, wantErr %v", err, false)
}
require.NoError(t, err, "NewRandom() error")

// Encode the original secret to hex string
encodedSecret := hex.FromBytes(originalSecret.Bytes())

// Decode the hex string back to secret
decodedSecret, err := jwt.NewFromHex(encodedSecret.Unwrap())
if err != nil {
t.Fatalf("NewFromHex() error = %v", err)
}
require.NoError(t, err, "NewFromHex() error")

// Compare the original and decoded secrets
if !reflect.DeepEqual(originalSecret, decodedSecret) {
t.Errorf(
"Round trip encoding failed. Original: %v, Decoded: %v",
originalSecret, decodedSecret,
)
}
require.Equal(
t,
originalSecret,
decodedSecret,
"Round trip encoding failed",
)
}
7 changes: 1 addition & 6 deletions mod/state-transition/pkg/core/state_processor_genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,6 @@ func (sp *StateProcessor[
}
}

// Prime the db so that processDeposit doesn't fail.
if err = st.SetGenesisValidatorsRoot(primitives.Root{}); err != nil {
return nil, err
}

for _, deposit := range deposits {
// TODO: process deposits into eth1 data.
if err = sp.processDeposit(st, deposit); err != nil {
Expand All @@ -121,7 +116,7 @@ func (sp *StateProcessor[

var validatorsRoot primitives.Root
validatorsRoot, err = ssz.MerkleizeListComposite[
common.ChainSpec, math.U64, [32]byte,
common.ChainSpec, math.U64,
](validators, uint64(len(validators)))
if err != nil {
return nil, err
Expand Down
18 changes: 12 additions & 6 deletions mod/state-transition/pkg/core/state_processor_staking.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,18 +163,24 @@ func (sp *StateProcessor[
err error
)

// Get the genesis validators root to be used to find fork data later.
genesisValidatorsRoot, err = st.GetGenesisValidatorsRoot()
if err != nil {
return err
}

// Get the current epoch.
// Get the current slot.
slot, err := st.GetSlot()
if err != nil {
return err
}

// At genesis, the validators sign over an empty root.
if slot == 0 {
genesisValidatorsRoot = primitives.Root{}
} else {
// Get the genesis validators root to be used to find fork data later.
genesisValidatorsRoot, err = st.GetGenesisValidatorsRoot()
if err != nil {
return err
}
}

epoch = sp.cs.SlotToEpoch(slot)

// Verify that the message was signed correctly.
Expand Down

0 comments on commit 166be22

Please sign in to comment.