Skip to content

Commit

Permalink
implement babe
Browse files Browse the repository at this point in the history
  • Loading branch information
radkomih committed Apr 19, 2024
1 parent 3f05cf1 commit c18092b
Show file tree
Hide file tree
Showing 97 changed files with 5,919 additions and 402 deletions.
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,6 @@
[submodule "polkadot-sdk"]
path = polkadot-sdk
url = [email protected]:LimeChain/polkadot-sdk.git
[submodule "go-schnorrkel"]
path = go-schnorrkel
url = [email protected]:LimeChain/go-schnorrkel.git
26 changes: 18 additions & 8 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ CURRENT_DIR = $(shell pwd)

# runtime template configuration
BUILD_PATH = build/runtime.wasm
RUNTIME_TEMPLATE_DIR = runtime/templates/pos
RUNTIME_TEMPLATE_DIR = runtime/templates/poa

# docker image configuration
SRC_DIR = /src/examples/wasm/gosemble
Expand All @@ -11,15 +11,16 @@ IMAGE = tinygo/${TARGET}
# tinygo compiler configuration
VERSION = 0.31.0-dev
TARGET = polkawasm
OPT_LEVEL = s # 0, 1, 2, s, z
GC = extalloc # extalloc, extalloc_leaking
WASMOPT_PATH = /tinygo/lib/binaryen/bin/wasm-opt

# runtime build commands
DOCKER_BUILD_TINYGO = docker build --tag $(IMAGE):$(VERSION)-$(GC) -f tinygo/Dockerfile.$(TARGET) tinygo
DOCKER_RUN_TINYGO = docker run --rm -v $(CURRENT_DIR):$(SRC_DIR) -w $(SRC_DIR) $(IMAGE):$(VERSION)-$(GC) /bin/bash -c

TINYGO_BUILD_COMMAND_NODEBUG = tinygo build --no-debug -opt s -gc=$(GC) -target=$(TARGET)
TINYGO_BUILD_COMMAND = tinygo build -gc=$(GC) -opt s -target=$(TARGET)
TINYGO_BUILD_COMMAND_NODEBUG = tinygo build --no-debug -opt=$(OPT_LEVEL) -gc=$(GC) -target=$(TARGET)
TINYGO_BUILD_COMMAND = tinygo build -opt=$(OPT_LEVEL) -gc=$(GC) -target=$(TARGET)

RUNTIME_BUILD_NODEBUG = "WASMOPT="$(WASMOPT_PATH)" $(TINYGO_BUILD_COMMAND_NODEBUG) -o=$(SRC_DIR)/$(BUILD_PATH) $(SRC_DIR)/runtime/"
RUNTIME_BUILD = "WASMOPT="$(WASMOPT_PATH)" $(TINYGO_BUILD_COMMAND) -o=$(SRC_DIR)/$(BUILD_PATH) $(SRC_DIR)/runtime/"
Expand Down Expand Up @@ -134,6 +135,12 @@ start-network:
cd ../../../..; \
WASMTIME_BACKTRACE_DETAILS=1 RUST_LOG=runtime=trace ./target/release/node-template --dev --execution=wasm

start-network-babe:
cd polkadot-sdk/substrate/bin/node/cli; \
cargo build --release; \
cd ../../../..; \
WASMTIME_BACKTRACE_DETAILS=1 RUST_LOG=runtime=trace ./target/release/substrate-node --dev --execution=wasm

# gossamer node configuration
CHAIN_SPEC_PLAIN = ../testdata/chain-spec/plain.json
CHAIN_SPEC_UPDATED = ../testdata/chain-spec/plain-updated.json
Expand All @@ -144,7 +151,7 @@ gossamer-build:
@cd gossamer; \
make build;

gossamer-build-spec:
gossamer-import-runtime:
@cd gossamer; \
rm -f $(CHAIN_SPEC_UPDATED); \
./bin/gossamer import-runtime --wasm-file ../$(BUILD_PATH) --chain $(CHAIN_SPEC_PLAIN) > $(CHAIN_SPEC_UPDATED); \
Expand All @@ -153,14 +160,17 @@ gossamer-build-spec:

gossamer-init:
@cd gossamer; \
rm -rf tmp/gossamer; \
./bin/gossamer init --base-path $(GOSSAMER_BASE_PATH) --chain $(CHAIN_SPEC_RAW) --key alice;
rm -rf $(GOSSAMER_BASE_PATH); \
./bin/gossamer init --force \
--base-path $(GOSSAMER_BASE_PATH) \
--chain $(CHAIN_SPEC_RAW) \
--key alice;

gossamer-start: gossamer-build gossamer-build-spec gossamer-init
gossamer-start: gossamer-build gossamer-import-runtime gossamer-init
@cd gossamer; \
./bin/gossamer \
--base-path $(GOSSAMER_BASE_PATH) \
--rpc-external \
--ws-external \
--ws-port 8546 \
--key alice;
--key alice;
8 changes: 0 additions & 8 deletions api/babe/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,6 @@ func (m Module) Configuration() int64 {
AllowedSlots: epochConfig.AllowedSlots,
}

m.logger.Warn("BABE API: Configuration")

return m.memUtils.BytesToOffsetAndSize(config.Bytes())
}

Expand All @@ -133,8 +131,6 @@ func (m Module) CurrentEpochStart() int64 {
m.logger.Critical(err.Error())
}

m.logger.Warn("BABE API: Current Epoch Start")

return m.memUtils.BytesToOffsetAndSize(epochStart.Bytes())
}

Expand All @@ -145,8 +141,6 @@ func (m Module) CurrentEpoch() int64 {
m.logger.Critical(err.Error())
}

m.logger.Warn("BABE API: Current Epoch")

return m.memUtils.BytesToOffsetAndSize(epoch.Bytes())
}

Expand All @@ -158,8 +152,6 @@ func (m Module) NextEpoch() int64 {
m.logger.Critical(err.Error())
}

m.logger.Warn("BABE API: Next Epoch")

return m.memUtils.BytesToOffsetAndSize(epoch.Bytes())
}

Expand Down
4 changes: 1 addition & 3 deletions benchmarking/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ package benchmarking

import (
"flag"

"github.com/LimeChain/gosemble/testhelpers"
)

// cmd flags and other options related to benchmarking
Expand All @@ -18,7 +16,7 @@ type benchmarkingConfig struct {

func initBenchmarkingConfig() benchmarkingConfig {
cfg := benchmarkingConfig{}
cfg.WasmRuntime = testhelpers.RuntimeWasm
cfg.WasmRuntime = "../build/runtime.wasm"
flag.IntVar(&cfg.Steps, "steps", 50, "Select how many samples we should take across the variable components.")
flag.IntVar(&cfg.Repeat, "repeat", 20, "Select how many repetitions of this benchmark should run from within the wasm.")
flag.IntVar(&cfg.HeapPages, "heap-pages", 4096, "Cache heap allocation pages.")
Expand Down
35 changes: 34 additions & 1 deletion benchmarking/instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"github.com/LimeChain/gosemble/primitives/benchmarking"
benchmarkingtypes "github.com/LimeChain/gosemble/primitives/benchmarking"
primitives "github.com/LimeChain/gosemble/primitives/types"
"github.com/LimeChain/gosemble/testhelpers"
cscale "github.com/centrifuge/go-substrate-rpc-client/v4/scale"
"github.com/centrifuge/go-substrate-rpc-client/v4/signature"
ctypes "github.com/centrifuge/go-substrate-rpc-client/v4/types"
Expand Down Expand Up @@ -149,8 +150,40 @@ func (i *Instance) InitializeBlock(blockNumber uint, timestamp uint64) error {
return err
}

header := gossamertypes.NewHeader(parentHash, common.Hash{}, common.Hash{}, blockNumber, digest)
// babeConfigurationBytes, err := i.runtime.Exec("BabeApi_configuration", []byte{})
// if err != nil {
// return err
// }

// buffer := bytes.NewBuffer(babeConfigurationBytes)

// babeConfiguration, err := babetypes.DecodeConfiguration(buffer)
// if err != nil {
// return err
// }

// slot := sc.U64(timestamp) / babeConfiguration.SlotDuration

// babeHeader := gossamertypes.NewBabeDigest()
// err = babeHeader.SetValue(*gossamertypes.NewBabePrimaryPreDigest(0, uint64(slot), [32]byte{}, [64]byte{}))
// if err != nil {
// return err
// }

// data, err := scale.Marshal(babeHeader)
// if err != nil {
// return err
// }

// preDigest := gossamertypes.NewBABEPreRuntimeDigest(data)

// digest := gossamertypes.NewDigest()
// err = digest.Add(*preDigest)
// if err != nil {
// return err
// }

header := gossamertypes.NewHeader(testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), digest)
bytesHeader, err := scale.Marshal(*header)
if err != nil {
return err
Expand Down
21 changes: 20 additions & 1 deletion constants/metadata/metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,26 @@ const (
TypesSudoCalls
TypesSudoErrors

TypesRationalValueU64
TypesSlot
TypesOptionFixedSequence32U8
TypesVrfSignature
TypesAllowedSlots
TypesPreDigest
TypesOptionPreDigest
TypesBabeAuthority
TypesBabeSequenceAuthority
TypesBabeBoundedVecAuthority
TypesBabeEpochConfiguration
TypesBabeNextConfigDescriptor
TypesBabeSkippedEpoch
TypesBabeFixedSequenceSkippedEpoch
TypesBabeBoundedVecSkippedEpoch
TypesBabeConfiguration
TypesBabeEpoch
TypesBabeStorageAuthorities
TypesBabePrimaryPreDigest
TypesBabeSecondaryPlainPreDigest
TypesBabeSecondaryVRFPreDigest
TypesBabeErrors
TypesBabeCalls
)
13 changes: 11 additions & 2 deletions frame/aura/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ package aura
import (
"bytes"
"errors"
"reflect"

"github.com/LimeChain/gosemble/frame/system"
"github.com/LimeChain/gosemble/primitives/log"
"reflect"

sc "github.com/LimeChain/goscale"
"github.com/LimeChain/gosemble/constants/metadata"
Expand Down Expand Up @@ -131,7 +132,15 @@ func (m Module) OnInitialize(_ sc.U64) (primitives.Weight, error) {
if totalAuthorities.HasValue {
authorityIndex := currentSlot % totalAuthorities.Value

if m.disabledValidators != nil && m.disabledValidators.IsDisabled(sc.U32(authorityIndex)) {
var disabled bool
if m.disabledValidators != nil {
disabled, err = m.disabledValidators.IsDisabled(sc.U32(authorityIndex))
if err != nil {
return primitives.Weight{}, err
}
}

if disabled {
m.logger.Criticalf("Validator with index [%d] is disabled and should not be attempting to author blocks.", authorityIndex)
}
}
Expand Down
103 changes: 103 additions & 0 deletions frame/babe/call_plan_config_change.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package babe

import (
"bytes"
"reflect"

sc "github.com/LimeChain/goscale"
"github.com/LimeChain/gosemble/frame/support"
babetypes "github.com/LimeChain/gosemble/primitives/babe"
primitives "github.com/LimeChain/gosemble/primitives/types"
)

// The epoch config change is recorded and will be enacted on
// the next call to `enact_epoch_change`. The config will be activated one epoch after.
// Multiple calls to this method will replace any existing planned config change that had
// not been enacted yet.
type callPlanConfigChange struct {
primitives.Callable
storagePendingEpochConfigChange support.StorageValue[NextConfigDescriptor]
}

func newCallPlanConfigChange(moduleId sc.U8, functionId sc.U8, storagePendingEpochConfigChange support.StorageValue[NextConfigDescriptor]) primitives.Call {
call := callPlanConfigChange{
Callable: primitives.Callable{
ModuleId: moduleId,
FunctionId: functionId,
Arguments: sc.NewVaryingData(NextConfigDescriptor{}),
},
storagePendingEpochConfigChange: storagePendingEpochConfigChange,
}

return call
}

func (c callPlanConfigChange) DecodeArgs(buffer *bytes.Buffer) (primitives.Call, error) {
nextConfigDescriptor, err := DecodeNextConfigDescriptor(buffer)
if err != nil {
return nil, err
}
c.Arguments = sc.NewVaryingData(nextConfigDescriptor)
return c, nil
}

func (c callPlanConfigChange) Encode(buffer *bytes.Buffer) error {
return c.Callable.Encode(buffer)
}

func (c callPlanConfigChange) Bytes() []byte {
return c.Callable.Bytes()
}

func (c callPlanConfigChange) ModuleIndex() sc.U8 {
return c.Callable.ModuleIndex()
}

func (c callPlanConfigChange) FunctionIndex() sc.U8 {
return c.Callable.FunctionIndex()
}

func (c callPlanConfigChange) Args() sc.VaryingData {
return c.Callable.Args()
}

func (c callPlanConfigChange) BaseWeight() primitives.Weight {
return callPlanConfigChangeWeight(primitives.RuntimeDbWeight{})
}

func (_ callPlanConfigChange) WeighData(baseWeight primitives.Weight) primitives.Weight {
return primitives.WeightFromParts(baseWeight.RefTime, 0)
}

func (_ callPlanConfigChange) ClassifyDispatch(baseWeight primitives.Weight) primitives.DispatchClass {
return primitives.NewDispatchClassNormal()
}

func (_ callPlanConfigChange) PaysFee(baseWeight primitives.Weight) primitives.Pays {
return primitives.PaysYes
}

func (c callPlanConfigChange) Dispatch(origin primitives.RuntimeOrigin, args sc.VaryingData) (primitives.PostDispatchInfo, error) {
// TODO: enable once 'sudo' module is implemented
//
// err := EnsureRoot(origin)
// if err != nil {
// return primitives.PostDispatchInfo{}, err
// }

config := args[0].(NextConfigDescriptor)

if reflect.TypeOf(config) == reflect.TypeOf(NextConfigDescriptor{}) && reflect.TypeOf(config.V1) == reflect.TypeOf(babetypes.EpochConfiguration{}) {
if !((config.V1.C.Numerator != 0 || !reflect.DeepEqual(config.V1.AllowedSlots, babetypes.NewPrimarySlots())) && config.V1.C.Denominator != 0) {
return primitives.PostDispatchInfo{}, NewDispatchErrorInvalidConfiguration(c.ModuleId)
}
}

c.storagePendingEpochConfigChange.Put(config)

return primitives.PostDispatchInfo{}, nil
}

func (_ callPlanConfigChange) Docs() string {
return "Plan an epoch config change."
}
Loading

0 comments on commit c18092b

Please sign in to comment.