Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(grandpa): update #411

Merged
merged 8 commits into from
Jun 6, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@
// 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 @@
return m.memUtils.BytesToOffsetAndSize(authorities.Bytes())
}

func (m Module) CurrentSetId() int64 {
setId, err := m.grandpa.CurrentSetId()
failfmi marked this conversation as resolved.
Show resolved Hide resolved
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)

Check warning on line 74 in api/grandpa/module.go

View check run for this annotation

Codecov / codecov/patch

api/grandpa/module.go#L72-L74

Added lines #L72 - L74 were not covered by tests

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

Check warning on line 78 in api/grandpa/module.go

View check run for this annotation

Codecov / codecov/patch

api/grandpa/module.go#L76-L78

Added lines #L76 - L78 were not covered by tests
}

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

Check warning on line 83 in api/grandpa/module.go

View check run for this annotation

Codecov / codecov/patch

api/grandpa/module.go#L81-L83

Added lines #L81 - L83 were not covered by tests
}

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

Check warning on line 88 in api/grandpa/module.go

View check run for this annotation

Codecov / codecov/patch

api/grandpa/module.go#L86-L88

Added lines #L86 - L88 were not covered by tests
}

res, err := m.grandpa.SubmitUnsignedEquivocationReport(equivocationProof, keyOwnerProof)
failfmi marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
m.logger.Critical(err.Error())

Check warning on line 93 in api/grandpa/module.go

View check run for this annotation

Codecov / codecov/patch

api/grandpa/module.go#L91-L93

Added lines #L91 - L93 were not covered by tests
}

return m.memUtils.BytesToOffsetAndSize(res.Bytes())

Check warning on line 96 in api/grandpa/module.go

View check run for this annotation

Codecov / codecov/patch

api/grandpa/module.go#L96

Added line #L96 was not covered by tests
}

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

Check warning on line 101 in api/grandpa/module.go

View check run for this annotation

Codecov / codecov/patch

api/grandpa/module.go#L99-L101

Added lines #L99 - L101 were not covered by tests

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

Check warning on line 105 in api/grandpa/module.go

View check run for this annotation

Codecov / codecov/patch

api/grandpa/module.go#L103-L105

Added lines #L103 - L105 were not covered by tests
}

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

Check warning on line 110 in api/grandpa/module.go

View check run for this annotation

Codecov / codecov/patch

api/grandpa/module.go#L108-L110

Added lines #L108 - L110 were not covered by tests
}

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

Check warning on line 114 in api/grandpa/module.go

View check run for this annotation

Codecov / codecov/patch

api/grandpa/module.go#L113-L114

Added lines #L113 - L114 were not covered by tests

}

// 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 @@
" 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("CurrentSetId").Return(id, nil)
mockMemoryUtils.On("BytesToOffsetAndSize", id.Bytes()).Return(int64(13))

target.CurrentSetId()

mockGrandpa.AssertCalled(t, "CurrentSetId")
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("CurrentSetId").Return(sc.U64(0), expectedErr)

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

mockGrandpa.AssertCalled(t, "CurrentSetId")
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,
}
}
7 changes: 7 additions & 0 deletions frame/authorship/constants.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package authorship

type consts struct{}

func newConstants() *consts {
return &consts{}
}
failfmi marked this conversation as resolved.
Show resolved Hide resolved
Loading