Skip to content

Commit

Permalink
simplified genesis tests
Browse files Browse the repository at this point in the history
  • Loading branch information
abi87 committed Sep 12, 2024
1 parent e0e7334 commit 0bd4ffa
Show file tree
Hide file tree
Showing 6 changed files with 160 additions and 66 deletions.
2 changes: 1 addition & 1 deletion mod/consensus/pkg/miniavalanche/vm/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ var (
// Entry point for node to build the VM
type Factory struct {
Config Config
Middleware middleware.VMMiddleware
Middleware *middleware.VMMiddleware
}

func (f *Factory) New(logging.Logger) (interface{}, error) {
Expand Down
14 changes: 14 additions & 0 deletions mod/consensus/pkg/miniavalanche/vm/genesis.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package vm

import (
"encoding/json"
"fmt"
"time"

"github.com/ava-labs/avalanchego/ids"

"github.com/berachain/beacon-kit/mod/consensus-types/pkg/types"
"github.com/berachain/beacon-kit/mod/consensus/pkg/miniavalanche/block"
"github.com/berachain/beacon-kit/mod/consensus/pkg/miniavalanche/encoding"
)
Expand All @@ -18,6 +20,18 @@ type Genesis struct {
EthGenesis []byte
}

// defaultEthGenesis implements the default genesis state for the application.
// This should return a map of module names to their respective default
// genesis states.
func defaultEthGenesis() (map[string]json.RawMessage, error) {
var (
gen = make(map[string]json.RawMessage)
err error
)
gen["beacon"], err = json.Marshal(types.DefaultGenesisDeneb())
return gen, err
}

// process genesisBytes and from them build:
// genesis block, the first block in the chain (and only one until we unlock block creation)
// genesis validators, the validators initially responsible for the chain
Expand Down
45 changes: 14 additions & 31 deletions mod/consensus/pkg/miniavalanche/vm/genesis_tools_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package vm

import (
"embed"
"encoding/json"
"log"
"testing"
Expand All @@ -11,17 +10,18 @@ import (
)

var (
//go:embed test-eth-genesis.json
testEthGenesisContent embed.FS

testValidators []*Validator
testEthGenesisBytes []byte
testGenesisValidators []*Validator
testEthGenesisBytes []byte
)

func init() {
// init testEthGenesisBytes
var err error
testEthGenesisBytes, err = testEthGenesisContent.ReadFile("test-eth-genesis.json")
ethGen, err := defaultEthGenesis()
// testEthGenesisContent.ReadFile("test-eth-genesis.json")
if err != nil {
log.Fatal(err)
}
testEthGenesisBytes, err = json.Marshal(ethGen)
if err != nil {
log.Fatal(err)
}
Expand All @@ -35,7 +35,7 @@ func init() {
if err != nil {
log.Fatal(err)
}
testValidators = []*Validator{val0, val1}
testGenesisValidators = []*Validator{val0, val1}
}

func TestEthGenesisEncoding(t *testing.T) {
Expand All @@ -45,12 +45,12 @@ func TestEthGenesisEncoding(t *testing.T) {
genesisData := &Base64Genesis{
Validators: []Base64GenesisValidator{
{
NodeID: testValidators[0].NodeID.String(),
Weight: testValidators[0].Weight,
NodeID: testGenesisValidators[0].NodeID.String(),
Weight: testGenesisValidators[0].Weight,
},
{
NodeID: testValidators[1].NodeID.String(),
Weight: testValidators[1].Weight,
NodeID: testGenesisValidators[1].NodeID.String(),
Weight: testGenesisValidators[1].Weight,
},
},
EthGenesis: string(testEthGenesisBytes),
Expand All @@ -66,23 +66,6 @@ func TestEthGenesisEncoding(t *testing.T) {

_, rValidators, rGenEthData, err := parseGenesis(parsedGenesisData)
r.NoError(err)
r.Equal(testValidators, rValidators)
r.Equal(testGenesisValidators, rValidators)
r.Equal(testEthGenesisBytes, rGenEthData)

// check eth genesis content
var genesisState map[string]json.RawMessage
r.NoError(json.Unmarshal(testEthGenesisBytes, &genesisState))

beaconMsg, found := genesisState["beacon"]
r.True(found)

var data map[string]json.RawMessage
r.NoError(json.Unmarshal([]byte(beaconMsg), &data))

_, found = data["fork_version"]
r.True(found)
_, found = data["deposits"]
r.True(found)
_, found = data["execution_payload_header"]
r.True(found)
}
33 changes: 0 additions & 33 deletions mod/consensus/pkg/miniavalanche/vm/test-eth-genesis.json

This file was deleted.

2 changes: 1 addition & 1 deletion mod/consensus/pkg/miniavalanche/vm/vm.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ type VM struct {
chainCtx *snow.Context

// middleware interfaces with the bus to send/receive data from the EVM
middleware middleware.VMMiddleware
middleware *middleware.VMMiddleware

db database.Database
state chainState
Expand Down
130 changes: 130 additions & 0 deletions mod/consensus/pkg/miniavalanche/vm/vm_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
package vm

import (
"context"
"fmt"
"testing"

"github.com/ava-labs/avalanchego/database/memdb"
"github.com/ava-labs/avalanchego/snow/engine/common"
"github.com/ava-labs/avalanchego/snow/snowtest"
"github.com/ava-labs/avalanchego/snow/validators"
"github.com/ava-labs/avalanchego/utils/logging"
"github.com/berachain/beacon-kit/mod/async/pkg/types"
"github.com/berachain/beacon-kit/mod/consensus/pkg/miniavalanche/middleware"
"github.com/berachain/beacon-kit/mod/log/pkg/noop"
"github.com/berachain/beacon-kit/mod/primitives/pkg/async"
"github.com/berachain/beacon-kit/mod/primitives/pkg/transition"
"github.com/stretchr/testify/require"
)

var _ types.EventDispatcher = (*genesisDispatcherStub)(nil)

// genesisDispatcherStub allows loading expections around VM-middleware interactions
// upon VM.Initialize
type genesisDispatcherStub struct {
brokers map[async.EventID]any
}

func (d *genesisDispatcherStub) Publish(event async.BaseEvent) error {
_, found := d.brokers[event.ID()]
if !found {
return fmt.Errorf("can't publish event %v", event.ID())
}

if event.ID() == async.GenesisDataReceived {
// as soon as VM published the genesis, send back
// the async.GenesisDataProcessed event
ch, found := d.brokers[async.GenesisDataProcessed]
if !found {
return fmt.Errorf("VM has not subscribed for async.GenesisDataProcessed event")
}
genCh, ok := ch.(chan async.Event[transition.ValidatorUpdates])
if !ok {
return fmt.Errorf("unexpected channel type %T", ch)
}

go func() {
noUpdatesEvt := async.NewEvent[transition.ValidatorUpdates](
context.TODO(),
async.GenesisDataProcessed,
transition.ValidatorUpdates{},
)
genCh <- noUpdatesEvt
}()
}

return nil
}

func (d *genesisDispatcherStub) Subscribe(eventID async.EventID, ch any) error {
d.brokers[eventID] = ch
return nil
}
func (d *genesisDispatcherStub) Unsubscribe(eventID async.EventID, ch any) error { return nil }

func TestVMInitialization(t *testing.T) {
r := require.New(t)

// setup VM
var (
beaconLogger = noop.NewLogger[any]()
avaLogger = logging.NoLog{} // TODO: consolidate logs
dp = &genesisDispatcherStub{
brokers: make(map[async.EventID]any),
}
mdw = middleware.NewABCIMiddleware(dp, beaconLogger)
f = Factory{
Config: Config{
Validators: validators.NewManager(),
},
Middleware: mdw,
}

ctx = context.TODO()
msgChan = make(chan common.Message, 1)
chainCtx = snowtest.Context(t, snowtest.PChainID)
db = memdb.New()
)

vmIntf, err := f.New(avaLogger)
r.NoError(err)
r.IsType(vmIntf, &VM{})
vm := vmIntf.(*VM)

genesisBytes, err := setupTestGenesis()
r.NoError(err)

// Start middleware before initializing VM
dp.Subscribe(async.GenesisDataReceived, nil) // allows VM to publish genesis data
r.NoError(mdw.Start(ctx))

// test initialization
err = vm.Initialize(ctx, chainCtx, db, genesisBytes, nil, nil, msgChan, nil, nil)
r.NoError(err)
}

func setupTestGenesis() ([]byte, error) {
genesisData := &Base64Genesis{
Validators: []Base64GenesisValidator{
{
NodeID: testGenesisValidators[0].NodeID.String(),
Weight: testGenesisValidators[0].Weight,
},
{
NodeID: testGenesisValidators[1].NodeID.String(),
Weight: testGenesisValidators[1].Weight,
},
},
EthGenesis: string(testEthGenesisBytes),
}

// marshal genesis
genContent, err := BuildBase64GenesisString(genesisData)
if err != nil {
return nil, err
}

// unmarshal genesis
return ParseBase64StringToBytes(genContent)
}

0 comments on commit 0bd4ffa

Please sign in to comment.