Skip to content

Commit 0c4e616

Browse files
authored
Feat/impl weights (#63)
* extract test helper * refactor the way metadata is attributed to dispatchable functions * implement weights during pre/post dispatch and hooks
1 parent ba26780 commit 0c4e616

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+1060
-454
lines changed

build/runtime.wasm

78.1 KB
Binary file not shown.

constants/weight.go

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package constants
2+
3+
import (
4+
sc "github.com/LimeChain/goscale"
5+
"github.com/LimeChain/gosemble/primitives/types"
6+
)
7+
8+
// TODO: needs to be benchmarked
9+
const FiveMbPerBlockPerExtrinsic sc.U32 = 1024 // TODO: 5 * 1024 * 1024
10+
11+
const WeightRefTimePerSecond sc.U64 = 1_000_000_000_000
12+
const WeightRefTimePerNanos sc.U64 = 1_000_000_000
13+
14+
// TODO: update according to the DB used
15+
// this will be the weight used throughout the runtime.
16+
var DbWeight types.RuntimeDbWeight = types.RuntimeDbWeight{
17+
Read: 25_000 * WeightRefTimePerNanos,
18+
Write: 100_000 * WeightRefTimePerNanos,
19+
}
20+
21+
// Time to execute a NO-OP extrinsic, for example `System::remark`.
22+
// Calculated by multiplying the *Average* with `1.0` and adding `0`.
23+
//
24+
// Stats nanoseconds:
25+
//
26+
// Min, Max: 99_481, 103_304
27+
// Average: 99_840
28+
// Median: 99_795
29+
// Std-Dev: 376.17
30+
//
31+
// Percentiles nanoseconds:
32+
//
33+
// 99th: 100_078
34+
// 95th: 100_051
35+
// 75th: 99_916
36+
var ExtrinsicBaseWeight types.Weight = types.WeightFromParts(WeightRefTimePerNanos.SaturatingMul(99_840), 0)
37+
38+
// Time to execute an empty block.
39+
// Calculated by multiplying the *Average* with `1.0` and adding `0`.
40+
//
41+
// Stats nanoseconds:
42+
//
43+
// Min, Max: 377_722, 414_752
44+
// Average: 381_015
45+
// Median: 379_751
46+
// Std-Dev: 5462.64
47+
//
48+
// Percentiles nanoseconds:
49+
//
50+
// 99th: 413_074
51+
// 95th: 384_876
52+
// 75th: 380_642
53+
var BlockExecutionWeight types.Weight = types.WeightFromParts(WeightRefTimePerNanos.SaturatingMul(381_015), 0)

execution/extrinsic/dispatch.go

Lines changed: 55 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -2,78 +2,84 @@ package extrinsic
22

33
import (
44
"bytes"
5+
"fmt"
56

67
sc "github.com/LimeChain/goscale"
78
"github.com/LimeChain/gosemble/frame/system"
89
"github.com/LimeChain/gosemble/frame/timestamp"
910
"github.com/LimeChain/gosemble/primitives/log"
10-
"github.com/LimeChain/gosemble/primitives/support"
1111
"github.com/LimeChain/gosemble/primitives/types"
1212
)
1313

14+
func GetDispatchInfo(xt types.CheckedExtrinsic) types.DispatchInfo {
15+
// TODO: add more module functions
16+
switch xt.Function.CallIndex.ModuleIndex {
17+
case system.Module.Index():
18+
switch xt.Function.CallIndex.FunctionIndex {
19+
case system.Module.Remark.Index():
20+
baseWeight := system.Module.Remark.BaseWeight(xt.Function.Args)
21+
22+
return types.DispatchInfo{
23+
Weight: system.Module.Remark.WeightInfo(baseWeight, xt.Function.Args),
24+
Class: system.Module.Remark.ClassifyDispatch(baseWeight, xt.Function.Args),
25+
PaysFee: system.Module.Remark.PaysFee(baseWeight, xt.Function.Args),
26+
}
27+
}
28+
29+
case timestamp.Module.Index():
30+
switch xt.Function.CallIndex.FunctionIndex {
31+
case timestamp.Module.Set.Index():
32+
baseWeight := timestamp.Module.Set.BaseWeight(xt.Function.Args)
33+
34+
return types.DispatchInfo{
35+
Weight: timestamp.Module.Set.WeightInfo(baseWeight, xt.Function.Args),
36+
Class: timestamp.Module.Set.ClassifyDispatch(baseWeight, xt.Function.Args),
37+
PaysFee: timestamp.Module.Set.PaysFee(baseWeight, xt.Function.Args),
38+
}
39+
}
40+
41+
default:
42+
log.Trace(fmt.Sprintf("module with index %d not found", xt.Function.CallIndex.ModuleIndex))
43+
}
44+
45+
log.Trace(fmt.Sprintf("function with index %d not found", xt.Function.CallIndex.FunctionIndex))
46+
return types.DispatchInfo{
47+
Weight: types.WeightFromParts(sc.U64(len(xt.Bytes())), sc.U64(0)),
48+
Class: types.NewDispatchClassNormal(),
49+
PaysFee: types.NewPaysYes(),
50+
}
51+
}
52+
1453
func Dispatch(call types.Call, maybeWho types.RuntimeOrigin) (ok types.PostDispatchInfo, err types.DispatchResultWithPostInfo[types.PostDispatchInfo]) {
54+
// TODO: Add more modules and functions
1555
switch call.CallIndex.ModuleIndex {
16-
// TODO: Add more modules
17-
case system.Module.Index:
56+
case system.Module.Index():
1857
switch call.CallIndex.FunctionIndex {
19-
// TODO: Add more functions
20-
case system.Module.Functions["remark"].Index:
21-
// TODO: Implement
58+
case system.Module.Remark.Index():
59+
res := system.Module.Remark.Dispatch(maybeWho, call.Args)
60+
if res.HasError {
61+
err = res
62+
return ok, err
63+
}
64+
ok = res.Ok
2265
default:
23-
log.Critical("system.function with index " + string(call.CallIndex.FunctionIndex) + "not found")
66+
log.Trace(fmt.Sprintf("function index %d not found", call.CallIndex.FunctionIndex))
2467
}
25-
case timestamp.Module.Index:
68+
case timestamp.Module.Index():
2669
switch call.CallIndex.FunctionIndex {
27-
// TODO: Add more functions
28-
case timestamp.Module.Functions["set"].Index:
70+
case timestamp.Module.Set.Index():
2971
buffer := &bytes.Buffer{}
3072
buffer.Write(sc.SequenceU8ToBytes(call.Args))
3173
compactTs := sc.DecodeCompact(buffer)
3274
ts := sc.U64(compactTs.ToBigInt().Uint64())
33-
34-
timestamp.Set(ts)
75+
timestamp.Module.Set.Dispatch(types.NewRawOriginNone(), ts)
3576
default:
36-
log.Critical("timestamp.function with index " + string(call.CallIndex.FunctionIndex) + "not found")
77+
log.Trace(fmt.Sprintf("function index %d not found", call.CallIndex.FunctionIndex))
3778
}
3879

3980
default:
40-
log.Critical("module with index " + string(call.CallIndex.ModuleIndex) + "not found")
81+
log.Trace(fmt.Sprintf("module with index %d not found", call.CallIndex.ModuleIndex))
4182
}
4283

4384
return ok, err
4485
}
45-
46-
func GetDispatchInfo(xt types.CheckedExtrinsic) types.DispatchInfo {
47-
switch xt.Function.CallIndex.ModuleIndex {
48-
// TODO: Add more modules
49-
case system.Module.Index:
50-
// TODO: Implement
51-
return types.DispatchInfo{
52-
Weight: types.WeightFromRefTime(sc.U64(len(xt.Bytes()))),
53-
Class: types.NewDispatchClassNormal(),
54-
PaysFee: types.NewPaysYes(),
55-
}
56-
57-
case timestamp.Module.Index:
58-
switch xt.Function.CallIndex.FunctionIndex {
59-
// TODO: Add more functions
60-
case timestamp.Module.Functions["set"].Index:
61-
baseWeight := timestamp.Module.Functions["set"].BaseWeight
62-
weight := support.WeighData(baseWeight, xt.Function.Args)
63-
class := support.ClassifyDispatch(baseWeight)
64-
paysFee := support.PaysFee(baseWeight)
65-
66-
return types.DispatchInfo{
67-
Weight: weight,
68-
Class: class,
69-
PaysFee: paysFee,
70-
}
71-
default:
72-
log.Critical("system.function with index " + string(xt.Function.CallIndex.ModuleIndex) + "not found")
73-
}
74-
default:
75-
log.Critical("module with index " + string(xt.Function.CallIndex.ModuleIndex) + "not found")
76-
}
77-
78-
panic("unreachable")
79-
}

execution/extrinsic/unsigned_validator.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,17 +33,17 @@ func (v UnsignedValidatorForChecked) ValidateUnsigned(_source types.TransactionS
3333
noUnsignedValidatorError := types.NewTransactionValidityError(types.NewUnknownTransactionNoUnsignedValidator())
3434
// TODO: Add more modules
3535
switch call.CallIndex.ModuleIndex {
36-
case system.Module.Index:
36+
case system.Module.Index():
3737
switch call.CallIndex.FunctionIndex {
38-
case system.Module.Functions["remark"].Index:
38+
case system.Module.Remark.Index():
3939
ok = types.DefaultValidTransaction()
4040
default:
4141
err = noUnsignedValidatorError
4242
}
4343

44-
case timestamp.Module.Index:
44+
case timestamp.Module.Index():
4545
switch call.CallIndex.FunctionIndex {
46-
case timestamp.Module.Functions["set"].Index:
46+
case timestamp.Module.Set.Index():
4747
ok = types.DefaultValidTransaction()
4848
default:
4949
err = noUnsignedValidatorError

execution/inherent/check_inherents.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,9 @@ func CheckInherents(data types.InherentData, block types.Block) types.CheckInher
2121
call := extrinsic.Function
2222

2323
switch call.CallIndex.ModuleIndex {
24-
case timestamp.Module.Index:
25-
for funcKey := range timestamp.Module.Functions {
26-
if call.CallIndex.FunctionIndex == timestamp.Module.Functions[funcKey].Index {
24+
case timestamp.Module.Index():
25+
for _, moduleFn := range timestamp.Module.Functions() {
26+
if call.CallIndex.FunctionIndex == moduleFn.Index() {
2727
isInherent = true
2828
err := timestamp.CheckInherent(call, data)
2929
if err != nil {

frame/aura/aura.go

Lines changed: 0 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -35,48 +35,6 @@ func SlotDuration() int64 {
3535
return utils.BytesToOffsetAndSize(slotDuration.Bytes())
3636
}
3737

38-
func OnInitialize() types.Weight {
39-
slot := currentSlotFromDigests()
40-
41-
if slot.HasValue {
42-
newSlot := slot.Value
43-
44-
auraHash := hashing.Twox128(constants.KeyAura)
45-
currentSlotHash := hashing.Twox128(constants.KeyCurrentSlot)
46-
47-
currentSlot := storage.GetDecode(append(auraHash, currentSlotHash...), sc.DecodeU64)
48-
49-
if currentSlot >= newSlot {
50-
log.Critical("Slot must increase")
51-
}
52-
53-
storage.Set(append(auraHash, currentSlotHash...), newSlot.Bytes())
54-
55-
totalAuthorities := totalAuthorities()
56-
if totalAuthorities.HasValue {
57-
_ = currentSlot % totalAuthorities.Value
58-
59-
// TODO: implement once Session module is added
60-
/*
61-
if T::DisabledValidators::is_disabled(authority_index as u32) {
62-
panic!(
63-
"Validator with index {:?} is disabled and should not be attempting to author blocks.",
64-
authority_index,
65-
);
66-
}
67-
*/
68-
}
69-
70-
// TODO: db weight
71-
// return T::DbWeight::get().reads_writes(2, 1)
72-
} else {
73-
// TODO: db weight
74-
// return T::DbWeight::get().reads(1)
75-
}
76-
77-
return types.Weight{}
78-
}
79-
8038
func OnGenesisSession() {
8139
// TODO: implement once Session module is added
8240
}

frame/aura/hooks.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package aura
2+
3+
import (
4+
sc "github.com/LimeChain/goscale"
5+
"github.com/LimeChain/gosemble/constants"
6+
"github.com/LimeChain/gosemble/primitives/hashing"
7+
"github.com/LimeChain/gosemble/primitives/log"
8+
"github.com/LimeChain/gosemble/primitives/storage"
9+
"github.com/LimeChain/gosemble/primitives/types"
10+
)
11+
12+
func OnInitialize() types.Weight {
13+
slot := currentSlotFromDigests()
14+
15+
if slot.HasValue {
16+
newSlot := slot.Value
17+
18+
auraHash := hashing.Twox128(constants.KeyAura)
19+
currentSlotHash := hashing.Twox128(constants.KeyCurrentSlot)
20+
21+
currentSlot := storage.GetDecode(append(auraHash, currentSlotHash...), sc.DecodeU64)
22+
23+
if currentSlot >= newSlot {
24+
log.Critical("Slot must increase")
25+
}
26+
27+
storage.Set(append(auraHash, currentSlotHash...), newSlot.Bytes())
28+
29+
totalAuthorities := totalAuthorities()
30+
if totalAuthorities.HasValue {
31+
_ = currentSlot % totalAuthorities.Value
32+
33+
// TODO: implement once Session module is added
34+
/*
35+
if T::DisabledValidators::is_disabled(authority_index as u32) {
36+
panic!(
37+
"Validator with index {:?} is disabled and should not be attempting to author blocks.",
38+
authority_index,
39+
);
40+
}
41+
*/
42+
}
43+
44+
return constants.DbWeight.ReadsWrites(2, 1)
45+
} else {
46+
return constants.DbWeight.Reads(1)
47+
}
48+
}

frame/block_builder/block_builder.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ func FinalizeBlock() int64 {
6969

7070
blockNumber := system.StorageGetBlockNumber()
7171

72-
system.IdleAndFinalizeHook(blockNumber)
72+
executive.IdleAndFinalizeHook(blockNumber)
7373

7474
header := system.Finalize()
7575
encodedHeader := header.Bytes()

0 commit comments

Comments
 (0)