Skip to content

Commit

Permalink
Merge branch 'development' into qdm12-pin-golangcilint
Browse files Browse the repository at this point in the history
  • Loading branch information
qdm12 authored Nov 4, 2021
2 parents 0fb65e6 + dc89892 commit 0aaa3c3
Show file tree
Hide file tree
Showing 17 changed files with 144 additions and 36 deletions.
1 change: 1 addition & 0 deletions chain/gssmr/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ unlock = ""
roles = 4
babe-authority = true
grandpa-authority = true
grandpa-interval = 1

[network]
port = 7001
Expand Down
3 changes: 3 additions & 0 deletions chain/gssmr/defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,9 @@ var (
// DefaultDiscoveryInterval is the default interval for searching for DHT peers
DefaultDiscoveryInterval = time.Second * 10

// DefaultGrandpaInterval is the default time for a grandpa sub-round
DefaultGrandpaInterval = time.Second

// RPCConfig

// DefaultRPCHTTPHost rpc host
Expand Down
9 changes: 3 additions & 6 deletions cmd/gossamer/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -579,6 +579,7 @@ func setDotCoreConfig(ctx *cli.Context, tomlCfg ctoml.CoreConfig, cfg *dot.CoreC
cfg.Roles = tomlCfg.Roles
cfg.BabeAuthority = tomlCfg.Roles == types.AuthorityRole
cfg.GrandpaAuthority = tomlCfg.Roles == types.AuthorityRole
cfg.GrandpaInterval = time.Second * time.Duration(tomlCfg.GrandpaInterval)
cfg.BABELead = ctx.GlobalBool(BABELeadFlag.Name)

// check --roles flag and update node configuration
Expand Down Expand Up @@ -633,6 +634,7 @@ func setDotCoreConfig(ctx *cli.Context, tomlCfg ctoml.CoreConfig, cfg *dot.CoreC
"babe-authority", cfg.BabeAuthority,
"grandpa-authority", cfg.GrandpaAuthority,
"wasm-interpreter", cfg.WasmInterpreter,
"grandpa-interval", cfg.GrandpaInterval,
)
}

Expand All @@ -646,12 +648,7 @@ func setDotNetworkConfig(ctx *cli.Context, tomlCfg ctoml.NetworkConfig, cfg *dot
cfg.MinPeers = tomlCfg.MinPeers
cfg.MaxPeers = tomlCfg.MaxPeers
cfg.PersistentPeers = tomlCfg.PersistentPeers

if tomlCfg.DiscoveryInterval > 0 {
cfg.DiscoveryInterval = time.Second * time.Duration(tomlCfg.DiscoveryInterval)
} else {
cfg.DiscoveryInterval = 0
}
cfg.DiscoveryInterval = time.Second * time.Duration(tomlCfg.DiscoveryInterval)

// check --port flag and update node configuration
if port := ctx.GlobalUint(PortFlag.Name); port != 0 {
Expand Down
2 changes: 2 additions & 0 deletions cmd/gossamer/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,7 @@ func TestCoreConfigFromFlags(t *testing.T) {
BabeAuthority: true,
GrandpaAuthority: true,
WasmInterpreter: gssmr.DefaultWasmInterpreter,
GrandpaInterval: testCfg.Core.GrandpaInterval,
},
},
{
Expand All @@ -420,6 +421,7 @@ func TestCoreConfigFromFlags(t *testing.T) {
BabeAuthority: false,
GrandpaAuthority: false,
WasmInterpreter: gssmr.DefaultWasmInterpreter,
GrandpaInterval: testCfg.Core.GrandpaInterval,
},
},
}
Expand Down
1 change: 1 addition & 0 deletions cmd/gossamer/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ func dotConfigToToml(dcfg *dot.Config) *ctoml.Config {
Roles: dcfg.Core.Roles,
BabeAuthority: dcfg.Core.BabeAuthority,
GrandpaAuthority: dcfg.Core.GrandpaAuthority,
GrandpaInterval: uint32(dcfg.Core.GrandpaInterval / time.Second),
}

cfg.Network = ctoml.NetworkConfig{
Expand Down
2 changes: 2 additions & 0 deletions dot/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ type CoreConfig struct {
BABELead bool
GrandpaAuthority bool
WasmInterpreter string
GrandpaInterval time.Duration
}

// RPCConfig is to marshal/unmarshal toml RPC config vars
Expand Down Expand Up @@ -180,6 +181,7 @@ func GssmrConfig() *Config {
BabeAuthority: gssmr.DefaultBabeAuthority,
GrandpaAuthority: gssmr.DefaultGrandpaAuthority,
WasmInterpreter: gssmr.DefaultWasmInterpreter,
GrandpaInterval: gssmr.DefaultGrandpaInterval,
},
Network: NetworkConfig{
Port: gssmr.DefaultNetworkPort,
Expand Down
1 change: 1 addition & 0 deletions dot/config/toml/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ type CoreConfig struct {
SlotDuration uint64 `toml:"slot-duration,omitempty"`
EpochLength uint64 `toml:"epoch-length,omitempty"`
WasmInterpreter string `toml:"wasm-interpreter,omitempty"`
GrandpaInterval uint32 `toml:"grandpa-interval,omitempty"`
BABELead bool `toml:"babe-lead,omitempty"`
}

Expand Down
1 change: 1 addition & 0 deletions dot/services.go
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,7 @@ func createGRANDPAService(cfg *Config, st *state.Service, dh *digest.Handler, ks
Voters: voters,
Authority: cfg.Core.GrandpaAuthority,
Network: net,
Interval: cfg.Core.GrandpaInterval,
}

if cfg.Core.GrandpaAuthority {
Expand Down
2 changes: 1 addition & 1 deletion dot/types/babe.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func (d *EpochDataRaw) ToEpochData() (*EpochData, error) {
type ConfigData struct {
C1 uint64
C2 uint64
SecondarySlots byte // TODO: this is unused, will need to update BABE verifier to use this (#1863)
SecondarySlots byte
}

// GetSlotFromHeader returns the BABE slot from the given header
Expand Down
53 changes: 35 additions & 18 deletions lib/babe/verify.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,10 @@ import (
// verifierInfo contains the information needed to verify blocks
// it remains the same for an epoch
type verifierInfo struct {
authorities []types.Authority
randomness Randomness
threshold *common.Uint128
authorities []types.Authority
randomness Randomness
threshold *common.Uint128
secondarySlots bool
}

// onDisabledInfo contains information about an authority that's been disabled at a certain
Expand Down Expand Up @@ -224,9 +225,10 @@ func (v *VerificationManager) getVerifierInfo(epoch uint64) (*verifierInfo, erro
}

return &verifierInfo{
authorities: epochData.Authorities,
randomness: epochData.Randomness,
threshold: threshold,
authorities: epochData.Authorities,
randomness: epochData.Randomness,
threshold: threshold,
secondarySlots: configData.SecondarySlots > 0,
}, nil
}

Expand All @@ -247,11 +249,12 @@ func (v *VerificationManager) getConfigData(epoch uint64) (*types.ConfigData, er

// verifier is a BABE verifier for a specific authority set, randomness, and threshold
type verifier struct {
blockState BlockState
epoch uint64
authorities []types.Authority
randomness Randomness
threshold *common.Uint128
blockState BlockState
epoch uint64
authorities []types.Authority
randomness Randomness
threshold *common.Uint128
secondarySlots bool
}

// newVerifier returns a Verifier for the epoch described by the given descriptor
Expand All @@ -261,11 +264,12 @@ func newVerifier(blockState BlockState, epoch uint64, info *verifierInfo) (*veri
}

return &verifier{
blockState: blockState,
epoch: epoch,
authorities: info.authorities,
randomness: info.randomness,
threshold: info.threshold,
blockState: blockState,
epoch: epoch,
authorities: info.authorities,
randomness: info.randomness,
threshold: info.threshold,
secondarySlots: info.secondarySlots,
}, nil
}

Expand Down Expand Up @@ -409,15 +413,28 @@ func (b *verifier) verifyPreRuntimeDigest(digest *types.PreRuntimeDigest) (scale
case types.BabePrimaryPreDigest:
ok, err = b.verifyPrimarySlotWinner(d.AuthorityIndex, d.SlotNumber, d.VRFOutput, d.VRFProof)
case types.BabeSecondaryVRFPreDigest:
if !b.secondarySlots {
ok = false
break
}
pub := b.authorities[d.AuthorityIndex].Key
var pk *sr25519.PublicKey
pk, err = sr25519.NewPublicKey(pub.Encode())

pk, err := sr25519.NewPublicKey(pub.Encode())
if err != nil {
return nil, err
}

ok, err = verifySecondarySlotVRF(&d, pk, b.epoch, len(b.authorities), b.randomness)
if err != nil {
return nil, err
}

case types.BabeSecondaryPlainPreDigest:
if !b.secondarySlots {
ok = false
break
}

ok = true
err = verifySecondarySlotPlain(d.AuthorityIndex, d.SlotNumber, len(b.authorities), b.randomness)
}
Expand Down
69 changes: 65 additions & 4 deletions lib/babe/verify_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,19 @@ package babe
import (
"errors"
"io/ioutil"
"math/big"
"os"
"testing"
"time"

"github.com/ChainSafe/gossamer/lib/genesis"
"github.com/stretchr/testify/require"

"github.com/ChainSafe/gossamer/dot/state"
"github.com/ChainSafe/gossamer/dot/types"
"github.com/ChainSafe/gossamer/lib/common"
"github.com/ChainSafe/gossamer/lib/crypto/sr25519"

"github.com/ChainSafe/gossamer/lib/genesis"
"github.com/ChainSafe/gossamer/pkg/scale"
log "github.com/ChainSafe/log15"
"github.com/stretchr/testify/require"
)

func newTestVerificationManager(t *testing.T, genCfg *types.BabeConfiguration) *VerificationManager {
Expand Down Expand Up @@ -162,6 +163,66 @@ func TestVerificationManager_VerifyBlock_Ok(t *testing.T) {
require.NoError(t, err)
}

func TestVerificationManager_VerifyBlock_Secondary(t *testing.T) {
babeService := createTestService(t, nil)
rt, err := babeService.blockState.GetRuntime(nil)
require.NoError(t, err)

cfg, err := rt.BabeConfiguration()
require.NoError(t, err)

cfg.GenesisAuthorities = types.AuthoritiesToRaw(babeService.epochData.authorities)
cfg.C1 = 1
cfg.C2 = 1
cfg.SecondarySlots = 0

vm := newTestVerificationManager(t, cfg)

kp, err := sr25519.GenerateKeypair()
require.NoError(t, err)

dig := createSecondaryVRFPreDigest(t, kp, 0, uint64(0), uint64(0), Randomness{})

bd := types.NewBabeDigest()
err = bd.Set(dig)
require.NoError(t, err)

bdEnc, err := scale.Marshal(bd)
require.NoError(t, err)

// create pre-digest
preDigest := &types.PreRuntimeDigest{
ConsensusEngineID: types.BabeEngineID,
Data: bdEnc,
}

// create new block header
number := big.NewInt(1)
digest := types.NewDigest()
err = digest.Add(*preDigest)
require.NoError(t, err)

// create seal and add to digest
seal := &types.SealDigest{
ConsensusEngineID: types.BabeEngineID,
Data: []byte{0},
}
require.NoError(t, err)

err = digest.Add(*seal)
require.NoError(t, err)

header, err := types.NewHeader(common.Hash{}, common.Hash{}, common.Hash{}, number, digest)
require.NoError(t, err)

block := types.Block{
Header: *header,
Body: nil,
}
err = vm.VerifyBlock(&block.Header)
require.EqualError(t, err, "failed to verify pre-runtime digest: could not verify slot claim VRF proof")
}

func TestVerificationManager_VerifyBlock_MultipleEpochs(t *testing.T) {
babeService := createTestService(t, nil)
rt, err := babeService.blockState.GetRuntime(nil)
Expand Down
3 changes: 3 additions & 0 deletions lib/grandpa/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,9 @@ var (
// ErrAuthorityNotInSet is returned when a precommit within a justification is signed by a key not in the authority set
ErrAuthorityNotInSet = errors.New("authority is not in set")

// ErrZeroInterval is returned when the grandpa sub-round interval is set to 0
ErrZeroInterval = errors.New("cannot have zero second interval")

errVoteExists = errors.New("already have vote")
errVoteToSignatureMismatch = errors.New("votes and authority count mismatch")
errInvalidVoteBlock = errors.New("block in vote is not descendant of previously finalised block")
Expand Down
19 changes: 12 additions & 7 deletions lib/grandpa/grandpa.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,7 @@ const (
)

var (
// TODO: make this configurable; currently 1s is same as substrate; total round length is interval * 2 (#1869)
interval = time.Second
logger = log.New("pkg", "grandpa")
logger = log.New("pkg", "grandpa")
)

// Service represents the current state of the grandpa protocol
Expand All @@ -63,6 +61,7 @@ type Service struct {
resumed chan struct{} // this channel will be closed when the service resumes
messageHandler *MessageHandler
network Network
interval time.Duration

// current state information
state *State // current state
Expand Down Expand Up @@ -93,6 +92,7 @@ type Config struct {
Voters []Voter
Keypair *ed25519.Keypair
Authority bool
Interval time.Duration
}

// NewService returns a new GRANDPA Service instance.
Expand Down Expand Up @@ -146,6 +146,10 @@ func NewService(cfg *Config) (*Service, error) {
return nil, err
}

if cfg.Interval == 0 {
return nil, ErrZeroInterval
}

ctx, cancel := context.WithCancel(context.Background())
s := &Service{
ctx: ctx,
Expand All @@ -167,6 +171,7 @@ func NewService(cfg *Config) (*Service, error) {
resumed: make(chan struct{}),
network: cfg.Network,
finalisedCh: finalisedCh,
interval: cfg.Interval,
}

s.messageHandler = NewMessageHandler(s, s.blockState)
Expand Down Expand Up @@ -452,7 +457,7 @@ func (s *Service) playGrandpaRound() error {

logger.Debug("receiving pre-vote messages...")
go s.receiveMessages(ctx)
time.Sleep(interval)
time.Sleep(s.interval)

if s.paused.Load().(bool) {
return ErrServicePaused
Expand Down Expand Up @@ -481,7 +486,7 @@ func (s *Service) playGrandpaRound() error {
go s.sendVoteMessage(prevote, vm, roundComplete)

logger.Debug("receiving pre-commit messages...")
time.Sleep(interval)
time.Sleep(s.interval)

if s.paused.Load().(bool) {
return ErrServicePaused
Expand Down Expand Up @@ -514,7 +519,7 @@ func (s *Service) playGrandpaRound() error {
}

func (s *Service) sendVoteMessage(stage Subround, msg *VoteMessage, roundComplete <-chan struct{}) {
ticker := time.NewTicker(interval * 4)
ticker := time.NewTicker(s.interval * 4)
defer ticker.Stop()

for {
Expand All @@ -537,7 +542,7 @@ func (s *Service) sendVoteMessage(stage Subround, msg *VoteMessage, roundComplet

// attemptToFinalize loops until the round is finalisable
func (s *Service) attemptToFinalize() error {
ticker := time.NewTicker(interval / 100)
ticker := time.NewTicker(s.interval / 100)

for {
select {
Expand Down
1 change: 1 addition & 0 deletions lib/grandpa/grandpa_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ func newTestService(t *testing.T) (*Service, *state.Service) {
Keypair: kr.Alice().(*ed25519.Keypair),
Authority: true,
Network: net,
Interval: time.Second,
}

gs, err := NewService(cfg)
Expand Down
Loading

0 comments on commit 0aaa3c3

Please sign in to comment.