Skip to content

Commit

Permalink
feat(grandpa): update (#411)
Browse files Browse the repository at this point in the history
* remove duplicate Authority type representation
* remove versioned authority list representation
* grandpa module. refactor
* add authorship module. grandpa additions and coverage
* cleanup and more tests
* address pr comments
  • Loading branch information
radkomih authored Jun 6, 2024
1 parent b735df7 commit 0404434
Show file tree
Hide file tree
Showing 134 changed files with 5,785 additions and 891 deletions.
13 changes: 6 additions & 7 deletions api/babe/module_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,18 @@ import (
)

var (
pubKey1 = primitives.Sr25519PublicKey{FixedSequence: sc.NewFixedSequence[sc.U8](32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)}

epochDuration = sc.U64(1000)
slotDuration = epochDuration / 100

genesisEpochConfig = babetypes.EpochConfiguration{
C: types.RationalValue{Numerator: 1, Denominator: 4},
C: types.Tuple2U64{First: 1, Second: 4},
AllowedSlots: babetypes.NewPrimaryAndSecondaryPlainSlots(),
}

authorities = sc.Sequence[babetypes.Authority]{
babetypes.Authority{
Key: types.Sr25519PublicKey{FixedSequence: sc.BytesToFixedSequenceU8([]byte{1, 2, 3})},
Weight: sc.U64(1),
},
authorities = sc.Sequence[primitives.Authority]{
primitives.Authority{Id: primitives.AccountId(pubKey1), Weight: sc.U64(1)},
}

randomness = babetypes.Randomness(sc.BytesToFixedSequenceU8([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}))
Expand Down Expand Up @@ -114,7 +113,7 @@ func Test_Configuration_Empty_Config(t *testing.T) {
func Test_Configuration_Stored_Config(t *testing.T) {
setup()

someStoredConfig := babetypes.EpochConfiguration{C: types.RationalValue{Numerator: 1, Denominator: 1}}
someStoredConfig := babetypes.EpochConfiguration{C: types.Tuple2U64{First: 1, Second: 1}}

expectedConfig := config
expectedConfig.C = someStoredConfig.C
Expand Down
71 changes: 69 additions & 2 deletions api/grandpa/module.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
package grandpa

import (
"bytes"

sc "github.com/LimeChain/goscale"
"github.com/LimeChain/gosemble/constants/metadata"
"github.com/LimeChain/gosemble/frame/grandpa"
grandpatypes "github.com/LimeChain/gosemble/primitives/grandpa"
"github.com/LimeChain/gosemble/primitives/hashing"
"github.com/LimeChain/gosemble/primitives/log"
"github.com/LimeChain/gosemble/primitives/session"
primitives "github.com/LimeChain/gosemble/primitives/types"
"github.com/LimeChain/gosemble/utils"
)
Expand All @@ -20,12 +24,12 @@ const (
// For more information about API definition, see:
// https://spec.polkadot.network/chap-runtime-api#id-module-grandpaapi
type Module struct {
grandpa grandpa.GrandpaModule
grandpa grandpa.Module
memUtils utils.WasmMemoryTranslator
logger log.Logger
}

func New(grandpa grandpa.GrandpaModule, logger log.Logger) Module {
func New(grandpa grandpa.Module, logger log.Logger) Module {
return Module{
grandpa: grandpa,
memUtils: utils.NewMemoryTranslator(),
Expand Down Expand Up @@ -57,6 +61,60 @@ func (m Module) Authorities() int64 {
return m.memUtils.BytesToOffsetAndSize(authorities.Bytes())
}

func (m Module) CurrentSetId() int64 {
setId, err := m.grandpa.StorageSetId()
if err != nil {
m.logger.Critical(err.Error())
}
return m.memUtils.BytesToOffsetAndSize(setId.Bytes())
}

func (m Module) SubmitReportEquivocationUnsignedExtrinsic(dataPtr int32, dataLen int32) int64 {
b := m.memUtils.GetWasmMemorySlice(dataPtr, dataLen)
buffer := bytes.NewBuffer(b)

equivocationProof, err := grandpatypes.DecodeEquivocationProof(buffer)
if err != nil {
m.logger.Critical(err.Error())
}

opaqueKeyOwnershipProof, err := sc.DecodeSequence[sc.U8](buffer)
if err != nil {
m.logger.Critical(err.Error())
}

keyOwnerProof, err := session.DecodeMembershipProof(bytes.NewBuffer(sc.SequenceU8ToBytes(opaqueKeyOwnershipProof)))
if err != nil {
m.logger.Critical(err.Error())
}

err = m.grandpa.SubmitUnsignedEquivocationReport(equivocationProof, keyOwnerProof)
if err != nil {
m.logger.Critical(err.Error())
}

return m.memUtils.BytesToOffsetAndSize(sc.NewOption[sc.Empty](nil).Bytes())
}

func (m Module) GenerateKeyOwnershipProof(dataPtr int32, dataLen int32) int64 {
b := m.memUtils.GetWasmMemorySlice(dataPtr, dataLen)
buffer := bytes.NewBuffer(b)

_, err := sc.DecodeU64(buffer)
if err != nil {
m.logger.Critical(err.Error())
}

authorityId, err := primitives.DecodeAccountId(buffer)
if err != nil {
m.logger.Critical(err.Error())
}

res := m.grandpa.HistoricalKeyOwnershipProof(authorityId)
return m.memUtils.BytesToOffsetAndSize(res.Bytes())

}

// Metadata returns the runtime api metadata of the module.
func (m Module) Metadata() primitives.RuntimeApiMetadata {
methods := sc.Sequence[primitives.RuntimeApiMethodMetadata]{
Expand All @@ -73,6 +131,15 @@ func (m Module) Metadata() primitives.RuntimeApiMetadata {
" is finalized by the authorities from block B-1.",
},
},

primitives.RuntimeApiMethodMetadata{
Name: "current_set_id",
Inputs: sc.Sequence[primitives.RuntimeApiMethodParamMetadata]{},
Output: sc.ToCompact(metadata.PrimitiveTypesU64),
Docs: sc.Sequence[sc.Str]{
"Get current GRANDPA authority set id.",
},
},
}

return primitives.RuntimeApiMetadata{
Expand Down
39 changes: 39 additions & 0 deletions api/grandpa/module_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,37 @@ func Test_Authorities_Panics(t *testing.T) {
mockGrandpa.AssertCalled(t, "Authorities")
}

func Test_CurrentSetId(t *testing.T) {
setup()

id := sc.U64(1)

mockGrandpa.On("StorageSetId").Return(id, nil)
mockMemoryUtils.On("BytesToOffsetAndSize", id.Bytes()).Return(int64(13))

target.CurrentSetId()

mockGrandpa.AssertCalled(t, "StorageSetId")
mockMemoryUtils.AssertCalled(t, "BytesToOffsetAndSize", id.Bytes())
mockMemoryUtils.AssertNumberOfCalls(t, "BytesToOffsetAndSize", 1)
}

func Test_CurrentSetId_Error(t *testing.T) {
setup()

expectedErr := errors.New("error")

mockGrandpa.On("StorageSetId").Return(sc.U64(0), expectedErr)

assert.PanicsWithValue(t,
expectedErr.Error(),
func() { target.CurrentSetId() },
)

mockGrandpa.AssertCalled(t, "StorageSetId")
mockMemoryUtils.AssertNumberOfCalls(t, "BytesToOffsetAndSize", 0)
}

func Test_Module_Metadata(t *testing.T) {
setup()

Expand All @@ -99,6 +130,14 @@ func Test_Module_Metadata(t *testing.T) {
" is finalized by the authorities from block B-1.",
},
},
types.RuntimeApiMethodMetadata{
Name: "current_set_id",
Inputs: sc.Sequence[types.RuntimeApiMethodParamMetadata]{},
Output: sc.ToCompact(metadata.PrimitiveTypesU64),
Docs: sc.Sequence[sc.Str]{
"Get current GRANDPA authority set id.",
},
},
},
Docs: sc.Sequence[sc.Str]{
" APIs for integrating the GRANDPA finality gadget into runtimes.",
Expand Down
73 changes: 73 additions & 0 deletions api/metadata/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,30 @@ func (m Module) basicTypes() sc.Sequence[primitives.MetadataType] {
primitives.NewMetadataTypeParameter(metadata.TypesAddress32, "T"),
),

primitives.NewMetadataTypeWithParam(
metadata.TypesOptionU64,
"Option[U64]",
sc.Sequence[sc.Str]{"Option"},
primitives.NewMetadataTypeDefinitionVariant(
sc.Sequence[primitives.MetadataDefinitionVariant]{
primitives.NewMetadataDefinitionVariant(
"None",
sc.Sequence[primitives.MetadataTypeDefinitionField]{},
optionNoneIdx,
"",
),
primitives.NewMetadataDefinitionVariant(
"Some",
sc.Sequence[primitives.MetadataTypeDefinitionField]{
primitives.NewMetadataTypeDefinitionField(metadata.PrimitiveTypesU64),
},
optionSomeIdx,
"",
),
}),
primitives.NewMetadataTypeParameter(metadata.TypesAddress32, "T"),
),

primitives.NewMetadataTypeWithPath(metadata.TypesKeyTypeId, "KeyTypeId", sc.Sequence[sc.Str]{"sp_core", "crypto", "KeyTypeId"}, primitives.NewMetadataTypeDefinitionComposite(
sc.Sequence[primitives.MetadataTypeDefinitionField]{primitives.NewMetadataTypeDefinitionFieldWithName(metadata.TypesFixedSequence4U8, "[u8; 4]")},
)),
Expand Down Expand Up @@ -857,6 +881,55 @@ func (m Module) basicTypes() sc.Sequence[primitives.MetadataType] {
},
),
),

// 161
primitives.NewMetadataType(
metadata.TypesTuple2U64,
"Tuple<u64, u64>",
primitives.NewMetadataTypeDefinitionTuple(
sc.Sequence[sc.Compact]{
sc.ToCompact(metadata.PrimitiveTypesU64),
sc.ToCompact(metadata.PrimitiveTypesU64),
},
),
),

// 521
primitives.NewMetadataType(
metadata.TypesAuthority,
"Authority",
primitives.NewMetadataTypeDefinitionTuple(
sc.Sequence[sc.Compact]{
sc.ToCompact(metadata.TypesSr25519PubKey),
sc.ToCompact(metadata.PrimitiveTypesU64),
},
),
),

// 522
primitives.NewMetadataType(
metadata.TypesSequenceAuthority,
"SequenceAuthority",
primitives.NewMetadataTypeDefinitionSequence(
sc.ToCompact(metadata.TypesAuthority),
),
),

// 520
primitives.NewMetadataTypeWithParams(
metadata.TypesBoundedVecAuthority,
"WeakBoundedVec<(AuthorityId, AuthorityWeight), T::MaxAuthorities>",
sc.Sequence[sc.Str]{"bounded_collections", "weak_bounded_vec", "WeakBoundedVec"},
primitives.NewMetadataTypeDefinitionComposite(
sc.Sequence[primitives.MetadataTypeDefinitionField]{
primitives.NewMetadataTypeDefinitionFieldWithName(metadata.TypesSequenceAuthority, "Vec<T>"),
},
),
sc.Sequence[primitives.MetadataTypeParameter]{
primitives.NewMetadataTypeParameter(metadata.TypesAuthority, "T"),
primitives.NewMetadataEmptyTypeParameter("S"),
},
),
}
}

Expand Down
Binary file modified build/runtime.wasm
Binary file not shown.
16 changes: 12 additions & 4 deletions constants/metadata/metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -190,16 +190,18 @@ const (
TypesSudoCalls
TypesSudoErrors

TypesRationalValueU64
TypesAuthority
TypesSequenceAuthority
TypesBoundedVecAuthority

TypesTuple2U64
TypesSlot
TypesOptionFixedSequence32U8
TypesVrfSignature
TypesAllowedSlots
TypesPreDigest
TypesOptionPreDigest
TypesBabeAuthority
TypesBabeSequenceAuthority
TypesBabeBoundedVecAuthority

TypesBabeEpochConfiguration
TypesBabeNextConfigDescriptor
TypesBabeSkippedEpoch
Expand All @@ -212,4 +214,10 @@ const (
TypesBabeSecondaryVRFPreDigest
TypesBabeErrors
TypesBabeCalls

TypesOptionU64
TypesGrandpaStoredState
TypesGrandpaStoredPendingChange
TypesGrandpaEvent
TypesGrandpaCalls
)
2 changes: 1 addition & 1 deletion constants/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,4 @@ const (
)

// 1 in 4 blocks (on average, not counting collisions) will be primary BABE blocks.
var PrimaryProbability = types.RationalValue{Numerator: 1, Denominator: 4}
var PrimaryProbability = types.Tuple2U64{First: 1, Second: 4}
28 changes: 28 additions & 0 deletions env/offchain.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
//go:build !nonwasmenv

package env

// TODO
/*
Offchain:
*/

// ext_offchain_local_storage_clear_version_1
// ext_offchain_is_validator_version_1
// ext_offchain_local_storage_compare_and_set_version_1
// ext_offchain_local_storage_get_version_1
// ext_offchain_local_storage_set_version_1
// ext_offchain_network_state_version_1
// ext_offchain_random_seed_version_1

//go:wasmimport env ext_offchain_submit_transaction_version_1
func ExtOffchainSubmitTransactionVersion1(data int64) int64

// ext_offchain_timestamp_version_1
// ext_offchain_sleep_until_version_1
// ext_offchain_http_request_start_version_1
// ext_offchain_http_request_add_header_version_1
// ext_offchain_http_request_write_body_version_1
// ext_offchain_http_response_wait_version_1
// ext_offchain_http_response_headers_version_1
// ext_offchain_http_response_read_body_version_1
7 changes: 7 additions & 0 deletions env/offchain_nonwasm.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
//go:build nonwasmenv

package env

func ExtOffchainSubmitTransactionVersion1(data int64) int64 {
panic("not implemented")
}
20 changes: 20 additions & 0 deletions frame/authorship/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package authorship

import (
"github.com/LimeChain/gosemble/frame/system"
primitives "github.com/LimeChain/gosemble/primitives/types"
)

type Config struct {
FindAuthor primitives.FindAuthor[primitives.AccountId]
EventHandler EventHandler
SystemModule system.Module
}

func NewConfig(findAuthor primitives.FindAuthor[primitives.AccountId], eventHandler EventHandler, systemModule system.Module) *Config {
return &Config{
FindAuthor: findAuthor,
EventHandler: eventHandler,
SystemModule: systemModule,
}
}
Loading

0 comments on commit 0404434

Please sign in to comment.