diff --git a/build/runtime.wasm b/build/runtime.wasm index ae85b3cc..4836df35 100755 Binary files a/build/runtime.wasm and b/build/runtime.wasm differ diff --git a/docs/docs/development/api.md b/docs/docs/development/api.md index 07e67a25..e058811d 100644 --- a/docs/docs/development/api.md +++ b/docs/docs/development/api.md @@ -14,6 +14,7 @@ Contains modules of the [Runtime API Specification](https://spec.polkadot.networ |--------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------| | [AccountNonceApi](https://github.com/limechain/gosemble/tree/develop/api/account_nonce) | Provides logic to get an account's nonce. | | [AuraApi](https://github.com/limechain/gosemble/tree/develop/api/aura) | Manages block authoring AuRa consensus mechanism. | +| [BabeApi](https://github.com/limechain/gosemble/tree/develop/api/babe) | Manages block authoring BABE consensus mechanism. | | [Benchmarking](https://github.com/limechain/gosemble/tree/develop/api/benchmarking) | Provides functionality for benchmarking extrinsic calls and system hooks. | | [BlockBuilder](https://github.com/limechain/gosemble/tree/develop/api/block_builder) | Provides functionality for building and finalizing a block. | | [Core](https://github.com/limechain/gosemble/tree/develop/api/core) | Provides functionality for initialising and executing a block. | diff --git a/docs/docs/development/modules.md b/docs/docs/development/modules.md index 71285088..98c50028 100644 --- a/docs/docs/development/modules.md +++ b/docs/docs/development/modules.md @@ -25,6 +25,7 @@ These modules provide features than can be useful for your blockchain and can be | Name | Description | |-----------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------| | [aura](https://github.com/limechain/gosemble/tree/develop/frame/aura) | Manages the AuRa (Authority Round) consensus mechanism. | +| [babe](https://github.com/limechain/gosemble/tree/develop/frame/babe) | Manages the BABE (Blind Assignment for Blockchain Extension) consensus mechanism. | | [balances](https://github.com/limechain/gosemble/tree/develop/frame/balances) | Provides functionality for handling accounts and balances of native currency. | | [grandpa](https://github.com/limechain/gosemble/tree/develop/frame/grandpa) | Manages the GRANDPA block finalization. | | [session](https://github.com/limechain/gosemble/tree/develop/frame/session) | Allows validators to manage their session keys, handles session rotation. | diff --git a/gossamer b/gossamer index c16f6e16..03b81042 160000 --- a/gossamer +++ b/gossamer @@ -1 +1 @@ -Subproject commit c16f6e1658f4f7516745e8357c83292808d67d49 +Subproject commit 03b8104267ca02abd6521df9a509ca132a701551 diff --git a/runtime/benchmark_sudo_call_set_key_test.go b/runtime/templates/poa/benchmark_sudo_call_set_key_test.go similarity index 71% rename from runtime/benchmark_sudo_call_set_key_test.go rename to runtime/templates/poa/benchmark_sudo_call_set_key_test.go index b725c836..5f5073ca 100644 --- a/runtime/benchmark_sudo_call_set_key_test.go +++ b/runtime/templates/poa/benchmark_sudo_call_set_key_test.go @@ -1,15 +1,17 @@ package main import ( + "testing" + "github.com/LimeChain/gosemble/benchmarking" "github.com/LimeChain/gosemble/primitives/types" + "github.com/LimeChain/gosemble/testhelpers" "github.com/stretchr/testify/assert" - "testing" ) func BenchmarkSudoSetKey(b *testing.B) { benchmarking.RunDispatchCall(b, "../frame/sudo/call_set_key_weight.go", func(i *benchmarking.Instance) { - err := (*i.Storage()).Put(append(keySudoHash, keyKeyHash...), aliceAddress.AsID.ToBytes()) + err := (*i.Storage()).Put(append(testhelpers.KeySudoHash, testhelpers.KeyKeyHash...), aliceAddress.AsID.ToBytes()) assert.NoError(b, err) err = i.ExecuteExtrinsic( @@ -19,6 +21,6 @@ func BenchmarkSudoSetKey(b *testing.B) { ) assert.NoError(b, err) - assert.Equal(b, bobAddress.AsID.ToBytes(), (*i.Storage()).Get(append(keySudoHash, keyKeyHash...))) + assert.Equal(b, bobAddress.AsID.ToBytes(), (*i.Storage()).Get(append(testhelpers.KeySudoHash, testhelpers.KeyKeyHash...))) }) } diff --git a/runtime/benchmark_sudo_call_sudo_as_test.go b/runtime/templates/poa/benchmark_sudo_call_sudo_as_test.go similarity index 80% rename from runtime/benchmark_sudo_call_sudo_as_test.go rename to runtime/templates/poa/benchmark_sudo_call_sudo_as_test.go index 0fff784b..e19bf25c 100644 --- a/runtime/benchmark_sudo_call_sudo_as_test.go +++ b/runtime/templates/poa/benchmark_sudo_call_sudo_as_test.go @@ -1,16 +1,18 @@ package main import ( + "testing" + "github.com/LimeChain/gosemble/benchmarking" "github.com/LimeChain/gosemble/primitives/types" + "github.com/LimeChain/gosemble/testhelpers" ctypes "github.com/centrifuge/go-substrate-rpc-client/v4/types" "github.com/stretchr/testify/assert" - "testing" ) func BenchmarkSudoSudoAs(b *testing.B) { benchmarking.RunDispatchCall(b, "../frame/sudo/call_sudo_as_weight.go", func(i *benchmarking.Instance) { - err := (*i.Storage()).Put(append(keySudoHash, keyKeyHash...), aliceAddress.AsID.ToBytes()) + err := (*i.Storage()).Put(append(testhelpers.KeySudoHash, testhelpers.KeyKeyHash...), aliceAddress.AsID.ToBytes()) assert.NoError(b, err) call, err := ctypes.NewCall(i.Metadata(), "System.remark", []byte{}) diff --git a/runtime/benchmark_sudo_call_sudo_test.go b/runtime/templates/poa/benchmark_sudo_call_sudo_test.go similarity index 79% rename from runtime/benchmark_sudo_call_sudo_test.go rename to runtime/templates/poa/benchmark_sudo_call_sudo_test.go index ec8d3f2c..12c55166 100644 --- a/runtime/benchmark_sudo_call_sudo_test.go +++ b/runtime/templates/poa/benchmark_sudo_call_sudo_test.go @@ -1,16 +1,18 @@ package main import ( + "testing" + "github.com/LimeChain/gosemble/benchmarking" "github.com/LimeChain/gosemble/primitives/types" + "github.com/LimeChain/gosemble/testhelpers" ctypes "github.com/centrifuge/go-substrate-rpc-client/v4/types" "github.com/stretchr/testify/assert" - "testing" ) func BenchmarkSudoSudo(b *testing.B) { benchmarking.RunDispatchCall(b, "../frame/sudo/call_sudo_weight.go", func(i *benchmarking.Instance) { - err := (*i.Storage()).Put(append(keySudoHash, keyKeyHash...), aliceAddress.AsID.ToBytes()) + err := (*i.Storage()).Put(append(testhelpers.KeySudoHash, testhelpers.KeyKeyHash...), aliceAddress.AsID.ToBytes()) assert.NoError(b, err) call, err := ctypes.NewCall(i.Metadata(), "System.remark", []byte{}) diff --git a/runtime/benchmark_sudo_remove_key_test.go b/runtime/templates/poa/benchmark_sudo_remove_key_test.go similarity index 65% rename from runtime/benchmark_sudo_remove_key_test.go rename to runtime/templates/poa/benchmark_sudo_remove_key_test.go index aee5aa5f..b865460b 100644 --- a/runtime/benchmark_sudo_remove_key_test.go +++ b/runtime/templates/poa/benchmark_sudo_remove_key_test.go @@ -1,15 +1,17 @@ package main import ( + "testing" + "github.com/LimeChain/gosemble/benchmarking" "github.com/LimeChain/gosemble/primitives/types" + "github.com/LimeChain/gosemble/testhelpers" "github.com/stretchr/testify/assert" - "testing" ) func BenchmarkSudoRemoveKey(b *testing.B) { benchmarking.RunDispatchCall(b, "../frame/sudo/call_remove_key_weight.go", func(i *benchmarking.Instance) { - err := (*i.Storage()).Put(append(keySudoHash, keyKeyHash...), aliceAddress.AsID.ToBytes()) + err := (*i.Storage()).Put(append(testhelpers.KeySudoHash, testhelpers.KeyKeyHash...), aliceAddress.AsID.ToBytes()) assert.NoError(b, err) err = i.ExecuteExtrinsic( @@ -18,6 +20,6 @@ func BenchmarkSudoRemoveKey(b *testing.B) { ) assert.NoError(b, err) - assert.Nil(b, (*i.Storage()).Get(append(keySudoHash, keyKeyHash...))) + assert.Nil(b, (*i.Storage()).Get(append(testhelpers.KeySudoHash, testhelpers.KeyKeyHash...))) }) } diff --git a/runtime/templates/poa/genesis_builder_test.go b/runtime/templates/poa/genesis_builder_test.go index ccc69671..523ebc50 100644 --- a/runtime/templates/poa/genesis_builder_test.go +++ b/runtime/templates/poa/genesis_builder_test.go @@ -92,5 +92,5 @@ func Test_BuildConfig(t *testing.T) { assert.Equal(t, expectedNextFeeMultiplier.Bytes(), nextFeeMultiplier) // assert sudo key - assert.Equal(t, aliceAddress.AsID.ToBytes(), (*storage).Get(append(keySudoHash, keyKeyHash...))) + assert.Equal(t, aliceAddress.AsID.ToBytes(), (*storage).Get(append(testhelpers.KeySudoHash, testhelpers.KeyKeyHash...))) } diff --git a/runtime/sudo_call_remove_key_test.go b/runtime/templates/poa/sudo_call_remove_key_test.go similarity index 63% rename from runtime/sudo_call_remove_key_test.go rename to runtime/templates/poa/sudo_call_remove_key_test.go index 6ed42d67..692dde8b 100644 --- a/runtime/sudo_call_remove_key_test.go +++ b/runtime/templates/poa/sudo_call_remove_key_test.go @@ -2,17 +2,19 @@ package main import ( "bytes" + "math/big" + "testing" + + "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" "github.com/stretchr/testify/assert" - "math/big" - "testing" ) func Test_Sudo_RemoveKey_Success(t *testing.T) { - rt, storage := newTestRuntime(t) - metadata := runtimeMetadata(t, rt) + rt, storage := testhelpers.NewRuntimeInstance(t) + metadata := testhelpers.RuntimeMetadata(t, rt) runtimeVersion, err := rt.Version() assert.NoError(t, err) @@ -21,11 +23,11 @@ func Test_Sudo_RemoveKey_Success(t *testing.T) { balance, e := big.NewInt(0).SetString("50000000000000000", 10) assert.True(t, e) - setStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) - initializeBlock(t, rt, parentHash, stateRoot, extrinsicsRoot, blockNumber) + testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) + testhelpers.InitializeBlock(t, rt, testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, testhelpers.BlockNumber) // Set Sudo Key - err = (*storage).Put(append(keySudoHash, keyKeyHash...), signature.TestKeyringPairAlice.PublicKey) + err = (*storage).Put(append(testhelpers.KeySudoHash, testhelpers.KeyKeyHash...), signature.TestKeyringPairAlice.PublicKey) assert.NoError(t, err) call, err := ctypes.NewCall(metadata, "Sudo.remove_key") @@ -34,9 +36,9 @@ func Test_Sudo_RemoveKey_Success(t *testing.T) { extrinsic := ctypes.NewExtrinsic(call) o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(parentHash), + BlockHash: ctypes.Hash(testhelpers.ParentHash), Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(parentHash), + GenesisHash: ctypes.Hash(testhelpers.ParentHash), Nonce: ctypes.NewUCompactFromUInt(0), SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), Tip: ctypes.NewUCompactFromUInt(0), @@ -54,13 +56,13 @@ func Test_Sudo_RemoveKey_Success(t *testing.T) { res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) assert.NoError(t, err) - assert.Equal(t, applyExtrinsicResultOutcome.Bytes(), res) - assert.Nil(t, (*storage).Get(append(keySudoHash, keyKeyHash...))) + assert.Equal(t, testhelpers.ApplyExtrinsicResultOutcome.Bytes(), res) + assert.Nil(t, (*storage).Get(append(testhelpers.KeySudoHash, testhelpers.KeyKeyHash...))) } func Test_Sudo_RemoveKey_RequireSudo_EmptyKey(t *testing.T) { - rt, storage := newTestRuntime(t) - metadata := runtimeMetadata(t, rt) + rt, storage := testhelpers.NewRuntimeInstance(t) + metadata := testhelpers.RuntimeMetadata(t, rt) runtimeVersion, err := rt.Version() assert.NoError(t, err) @@ -69,8 +71,8 @@ func Test_Sudo_RemoveKey_RequireSudo_EmptyKey(t *testing.T) { balance, e := big.NewInt(0).SetString("50000000000000000", 10) assert.True(t, e) - setStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) - initializeBlock(t, rt, parentHash, stateRoot, extrinsicsRoot, blockNumber) + testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) + testhelpers.InitializeBlock(t, rt, testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, testhelpers.BlockNumber) call, err := ctypes.NewCall(metadata, "Sudo.remove_key") assert.NoError(t, err) @@ -78,9 +80,9 @@ func Test_Sudo_RemoveKey_RequireSudo_EmptyKey(t *testing.T) { extrinsic := ctypes.NewExtrinsic(call) o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(parentHash), + BlockHash: ctypes.Hash(testhelpers.ParentHash), Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(parentHash), + GenesisHash: ctypes.Hash(testhelpers.ParentHash), Nonce: ctypes.NewUCompactFromUInt(0), SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), Tip: ctypes.NewUCompactFromUInt(0), @@ -98,5 +100,5 @@ func Test_Sudo_RemoveKey_RequireSudo_EmptyKey(t *testing.T) { res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) assert.NoError(t, err) - assert.Equal(t, applyExtrinsicResultSudoRequireSudoErr.Bytes(), res) + assert.Equal(t, testhelpers.ApplyExtrinsicResultSudoRequireSudoErr.Bytes(), res) } diff --git a/runtime/sudo_call_set_key_test.go b/runtime/templates/poa/sudo_call_set_key_test.go similarity index 62% rename from runtime/sudo_call_set_key_test.go rename to runtime/templates/poa/sudo_call_set_key_test.go index 97f52dbe..7a163470 100644 --- a/runtime/sudo_call_set_key_test.go +++ b/runtime/templates/poa/sudo_call_set_key_test.go @@ -2,17 +2,19 @@ package main import ( "bytes" + "math/big" + "testing" + + "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" "github.com/stretchr/testify/assert" - "math/big" - "testing" ) func Test_Sudo_SetKey_Success(t *testing.T) { - rt, storage := newTestRuntime(t) - metadata := runtimeMetadata(t, rt) + rt, storage := testhelpers.NewRuntimeInstance(t) + metadata := testhelpers.RuntimeMetadata(t, rt) runtimeVersion, err := rt.Version() assert.NoError(t, err) @@ -21,15 +23,15 @@ func Test_Sudo_SetKey_Success(t *testing.T) { balance, e := big.NewInt(0).SetString("50000000000000000", 10) assert.True(t, e) - setStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) - initializeBlock(t, rt, parentHash, stateRoot, extrinsicsRoot, blockNumber) + testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) + testhelpers.InitializeBlock(t, rt, testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, testhelpers.BlockNumber) bob, err := ctypes.NewMultiAddressFromHexAccountID( "0x90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22") assert.NoError(t, err) // Set Sudo Key - err = (*storage).Put(append(keySudoHash, keyKeyHash...), signature.TestKeyringPairAlice.PublicKey) + err = (*storage).Put(append(testhelpers.KeySudoHash, testhelpers.KeyKeyHash...), signature.TestKeyringPairAlice.PublicKey) assert.NoError(t, err) call, err := ctypes.NewCall(metadata, "Sudo.set_key", bob) @@ -38,9 +40,9 @@ func Test_Sudo_SetKey_Success(t *testing.T) { extrinsic := ctypes.NewExtrinsic(call) o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(parentHash), + BlockHash: ctypes.Hash(testhelpers.ParentHash), Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(parentHash), + GenesisHash: ctypes.Hash(testhelpers.ParentHash), Nonce: ctypes.NewUCompactFromUInt(0), SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), Tip: ctypes.NewUCompactFromUInt(0), @@ -58,13 +60,13 @@ func Test_Sudo_SetKey_Success(t *testing.T) { res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) assert.NoError(t, err) - assert.Equal(t, applyExtrinsicResultOutcome.Bytes(), res) - assert.Equal(t, bob.AsID.ToBytes(), (*storage).Get(append(keySudoHash, keyKeyHash...))) + assert.Equal(t, testhelpers.ApplyExtrinsicResultOutcome.Bytes(), res) + assert.Equal(t, bob.AsID.ToBytes(), (*storage).Get(append(testhelpers.KeySudoHash, testhelpers.KeyKeyHash...))) } func Test_Sudo_SetKey_RequireSudo(t *testing.T) { - rt, storage := newTestRuntime(t) - metadata := runtimeMetadata(t, rt) + rt, storage := testhelpers.NewRuntimeInstance(t) + metadata := testhelpers.RuntimeMetadata(t, rt) runtimeVersion, err := rt.Version() assert.NoError(t, err) @@ -73,15 +75,15 @@ func Test_Sudo_SetKey_RequireSudo(t *testing.T) { balance, e := big.NewInt(0).SetString("50000000000000000", 10) assert.True(t, e) - setStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) - initializeBlock(t, rt, parentHash, stateRoot, extrinsicsRoot, blockNumber) + testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) + testhelpers.InitializeBlock(t, rt, testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, testhelpers.BlockNumber) bob, err := ctypes.NewMultiAddressFromHexAccountID( "0x90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22") assert.NoError(t, err) // Set bob Sudo Key - err = (*storage).Put(append(keySudoHash, keyKeyHash...), bob.AsID.ToBytes()) + err = (*storage).Put(append(testhelpers.KeySudoHash, testhelpers.KeyKeyHash...), bob.AsID.ToBytes()) assert.NoError(t, err) call, err := ctypes.NewCall(metadata, "Sudo.set_key", bob) @@ -90,9 +92,9 @@ func Test_Sudo_SetKey_RequireSudo(t *testing.T) { extrinsic := ctypes.NewExtrinsic(call) o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(parentHash), + BlockHash: ctypes.Hash(testhelpers.ParentHash), Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(parentHash), + GenesisHash: ctypes.Hash(testhelpers.ParentHash), Nonce: ctypes.NewUCompactFromUInt(0), SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), Tip: ctypes.NewUCompactFromUInt(0), @@ -110,6 +112,6 @@ func Test_Sudo_SetKey_RequireSudo(t *testing.T) { res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) assert.NoError(t, err) - assert.Equal(t, applyExtrinsicResultSudoRequireSudoErr.Bytes(), res) - assert.Equal(t, bob.AsID.ToBytes(), (*storage).Get(append(keySudoHash, keyKeyHash...))) + assert.Equal(t, testhelpers.ApplyExtrinsicResultSudoRequireSudoErr.Bytes(), res) + assert.Equal(t, bob.AsID.ToBytes(), (*storage).Get(append(testhelpers.KeySudoHash, testhelpers.KeyKeyHash...))) } diff --git a/runtime/sudo_call_sudo_as_test.go b/runtime/templates/poa/sudo_call_sudo_as_test.go similarity index 79% rename from runtime/sudo_call_sudo_as_test.go rename to runtime/templates/poa/sudo_call_sudo_as_test.go index 75e1b91f..4bb225d2 100644 --- a/runtime/sudo_call_sudo_as_test.go +++ b/runtime/templates/poa/sudo_call_sudo_as_test.go @@ -2,21 +2,23 @@ package main import ( "bytes" + "math/big" + "testing" + gossamertypes "github.com/ChainSafe/gossamer/dot/types" "github.com/ChainSafe/gossamer/lib/common" "github.com/ChainSafe/gossamer/pkg/scale" "github.com/LimeChain/gosemble/constants" + "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" "github.com/stretchr/testify/assert" - "math/big" - "testing" ) func Test_Sudo_SudoAs_Success(t *testing.T) { - rt, storage := newTestRuntime(t) - metadata := runtimeMetadata(t, rt) + rt, storage := testhelpers.NewRuntimeInstance(t) + metadata := testhelpers.RuntimeMetadata(t, rt) runtimeVersion, err := rt.Version() assert.NoError(t, err) @@ -25,11 +27,11 @@ func Test_Sudo_SudoAs_Success(t *testing.T) { balance, e := big.NewInt(0).SetString("50000000000000000", 10) assert.True(t, e) - keyStorageAccountAlice, aliceAccountInfo := setStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) - initializeBlock(t, rt, parentHash, stateRoot, extrinsicsRoot, blockNumber) + keyStorageAccountAlice, aliceAccountInfo := testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) + testhelpers.InitializeBlock(t, rt, testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, testhelpers.BlockNumber) // Set Sudo Key - err = (*storage).Put(append(keySudoHash, keyKeyHash...), signature.TestKeyringPairAlice.PublicKey) + err = (*storage).Put(append(testhelpers.KeySudoHash, testhelpers.KeyKeyHash...), signature.TestKeyringPairAlice.PublicKey) assert.NoError(t, err) alice, err := ctypes.NewMultiAddressFromAccountID(signature.TestKeyringPairAlice.PublicKey) @@ -50,9 +52,9 @@ func Test_Sudo_SudoAs_Success(t *testing.T) { extrinsic := ctypes.NewExtrinsic(call) o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(parentHash), + BlockHash: ctypes.Hash(testhelpers.ParentHash), Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(parentHash), + GenesisHash: ctypes.Hash(testhelpers.ParentHash), Nonce: ctypes.NewUCompactFromUInt(0), SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), Tip: ctypes.NewUCompactFromUInt(0), @@ -67,15 +69,15 @@ func Test_Sudo_SudoAs_Success(t *testing.T) { err = extrinsic.Encode(*encoder) assert.NoError(t, err) - queryInfo := getQueryInfo(t, rt, extEnc.Bytes()) + queryInfo := testhelpers.GetQueryInfo(t, rt, extEnc.Bytes()) res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) assert.NoError(t, err) - assert.Equal(t, applyExtrinsicResultOutcome.Bytes(), res) + assert.Equal(t, testhelpers.ApplyExtrinsicResultOutcome.Bytes(), res) bobHash, _ := common.Blake2b128(bob.AsID[:]) - keyStorageAccountBob := append(keySystemHash, keyAccountHash...) + keyStorageAccountBob := append(testhelpers.KeySystemHash, testhelpers.KeyAccountHash...) keyStorageAccountBob = append(keyStorageAccountBob, bobHash...) keyStorageAccountBob = append(keyStorageAccountBob, bob.AsID[:]...) bytesStorageBob := (*storage).Get(keyStorageAccountBob) diff --git a/runtime/sudo_call_sudo_test.go b/runtime/templates/poa/sudo_call_sudo_test.go similarity index 79% rename from runtime/sudo_call_sudo_test.go rename to runtime/templates/poa/sudo_call_sudo_test.go index 9089819d..25de702a 100644 --- a/runtime/sudo_call_sudo_test.go +++ b/runtime/templates/poa/sudo_call_sudo_test.go @@ -2,21 +2,23 @@ package main import ( "bytes" + "math/big" + "testing" + gossamertypes "github.com/ChainSafe/gossamer/dot/types" "github.com/ChainSafe/gossamer/lib/common" "github.com/ChainSafe/gossamer/pkg/scale" "github.com/LimeChain/gosemble/constants" + "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" "github.com/stretchr/testify/assert" - "math/big" - "testing" ) func Test_Sudo_Sudo_Success(t *testing.T) { - rt, storage := newTestRuntime(t) - metadata := runtimeMetadata(t, rt) + rt, storage := testhelpers.NewRuntimeInstance(t) + metadata := testhelpers.RuntimeMetadata(t, rt) runtimeVersion, err := rt.Version() assert.NoError(t, err) @@ -25,11 +27,11 @@ func Test_Sudo_Sudo_Success(t *testing.T) { balance, e := big.NewInt(0).SetString("50000000000000000", 10) assert.True(t, e) - keyStorageAccountAlice, aliceAccountInfo := setStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) - initializeBlock(t, rt, parentHash, stateRoot, extrinsicsRoot, blockNumber) + keyStorageAccountAlice, aliceAccountInfo := testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) + testhelpers.InitializeBlock(t, rt, testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, testhelpers.BlockNumber) // Set Sudo Key - err = (*storage).Put(append(keySudoHash, keyKeyHash...), signature.TestKeyringPairAlice.PublicKey) + err = (*storage).Put(append(testhelpers.KeySudoHash, testhelpers.KeyKeyHash...), signature.TestKeyringPairAlice.PublicKey) assert.NoError(t, err) alice, err := ctypes.NewMultiAddressFromAccountID(signature.TestKeyringPairAlice.PublicKey) @@ -50,9 +52,9 @@ func Test_Sudo_Sudo_Success(t *testing.T) { extrinsic := ctypes.NewExtrinsic(call) o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(parentHash), + BlockHash: ctypes.Hash(testhelpers.ParentHash), Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(parentHash), + GenesisHash: ctypes.Hash(testhelpers.ParentHash), Nonce: ctypes.NewUCompactFromUInt(0), SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), Tip: ctypes.NewUCompactFromUInt(0), @@ -67,15 +69,15 @@ func Test_Sudo_Sudo_Success(t *testing.T) { err = extrinsic.Encode(*encoder) assert.NoError(t, err) - queryInfo := getQueryInfo(t, rt, extEnc.Bytes()) + queryInfo := testhelpers.GetQueryInfo(t, rt, extEnc.Bytes()) res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) assert.NoError(t, err) - assert.Equal(t, applyExtrinsicResultOutcome.Bytes(), res) + assert.Equal(t, testhelpers.ApplyExtrinsicResultOutcome.Bytes(), res) bobHash, _ := common.Blake2b128(bob.AsID[:]) - keyStorageAccountBob := append(keySystemHash, keyAccountHash...) + keyStorageAccountBob := append(testhelpers.KeySystemHash, testhelpers.KeyAccountHash...) keyStorageAccountBob = append(keyStorageAccountBob, bobHash...) keyStorageAccountBob = append(keyStorageAccountBob, bob.AsID[:]...) bytesStorageBob := (*storage).Get(keyStorageAccountBob) diff --git a/runtime/sudo_call_sudo_unchecked_weight_test.go b/runtime/templates/poa/sudo_call_sudo_unchecked_weight_test.go similarity index 80% rename from runtime/sudo_call_sudo_unchecked_weight_test.go rename to runtime/templates/poa/sudo_call_sudo_unchecked_weight_test.go index f9e6b449..b491940c 100644 --- a/runtime/sudo_call_sudo_unchecked_weight_test.go +++ b/runtime/templates/poa/sudo_call_sudo_unchecked_weight_test.go @@ -2,21 +2,23 @@ package main import ( "bytes" + "math/big" + "testing" + gossamertypes "github.com/ChainSafe/gossamer/dot/types" "github.com/ChainSafe/gossamer/lib/common" "github.com/ChainSafe/gossamer/pkg/scale" "github.com/LimeChain/gosemble/constants" + "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" "github.com/stretchr/testify/assert" - "math/big" - "testing" ) func Test_Sudo_SudoUncheckedWeight_Success(t *testing.T) { - rt, storage := newTestRuntime(t) - metadata := runtimeMetadata(t, rt) + rt, storage := testhelpers.NewRuntimeInstance(t) + metadata := testhelpers.RuntimeMetadata(t, rt) runtimeVersion, err := rt.Version() assert.NoError(t, err) @@ -25,11 +27,11 @@ func Test_Sudo_SudoUncheckedWeight_Success(t *testing.T) { balance, e := big.NewInt(0).SetString("50000000000000000", 10) assert.True(t, e) - keyStorageAccountAlice, aliceAccountInfo := setStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) - initializeBlock(t, rt, parentHash, stateRoot, extrinsicsRoot, blockNumber) + keyStorageAccountAlice, aliceAccountInfo := testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) + testhelpers.InitializeBlock(t, rt, testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, testhelpers.BlockNumber) // Set Sudo Key - err = (*storage).Put(append(keySudoHash, keyKeyHash...), signature.TestKeyringPairAlice.PublicKey) + err = (*storage).Put(append(testhelpers.KeySudoHash, testhelpers.KeyKeyHash...), signature.TestKeyringPairAlice.PublicKey) assert.NoError(t, err) alice, err := ctypes.NewMultiAddressFromAccountID(signature.TestKeyringPairAlice.PublicKey) @@ -55,9 +57,9 @@ func Test_Sudo_SudoUncheckedWeight_Success(t *testing.T) { extrinsic := ctypes.NewExtrinsic(call) o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(parentHash), + BlockHash: ctypes.Hash(testhelpers.ParentHash), Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(parentHash), + GenesisHash: ctypes.Hash(testhelpers.ParentHash), Nonce: ctypes.NewUCompactFromUInt(0), SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), Tip: ctypes.NewUCompactFromUInt(0), @@ -72,15 +74,15 @@ func Test_Sudo_SudoUncheckedWeight_Success(t *testing.T) { err = extrinsic.Encode(*encoder) assert.NoError(t, err) - queryInfo := getQueryInfo(t, rt, extEnc.Bytes()) + queryInfo := testhelpers.GetQueryInfo(t, rt, extEnc.Bytes()) res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) assert.NoError(t, err) - assert.Equal(t, applyExtrinsicResultOutcome.Bytes(), res) + assert.Equal(t, testhelpers.ApplyExtrinsicResultOutcome.Bytes(), res) bobHash, _ := common.Blake2b128(bob.AsID[:]) - keyStorageAccountBob := append(keySystemHash, keyAccountHash...) + keyStorageAccountBob := append(testhelpers.KeySystemHash, testhelpers.KeyAccountHash...) keyStorageAccountBob = append(keyStorageAccountBob, bobHash...) keyStorageAccountBob = append(keyStorageAccountBob, bob.AsID[:]...) bytesStorageBob := (*storage).Get(keyStorageAccountBob) diff --git a/runtime/templates/pos/account_nonce_test.go b/runtime/templates/pos/account_nonce_test.go deleted file mode 100644 index 655f8af2..00000000 --- a/runtime/templates/pos/account_nonce_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package main - -import ( - "math/big" - "testing" - - "github.com/centrifuge/go-substrate-rpc-client/v4/signature" - - sc "github.com/LimeChain/goscale" - "github.com/LimeChain/gosemble/testhelpers" - "github.com/stretchr/testify/assert" -) - -func Test_AccountNonceApi_account_nonce_Empty(t *testing.T) { - pubKey := signature.TestKeyringPairAlice.PublicKey - - rt, _ := testhelpers.NewRuntimeInstance(t) - - result, err := rt.Exec("AccountNonceApi_account_nonce", pubKey) - assert.NoError(t, err) - - assert.Equal(t, sc.U32(0).Bytes(), result) -} - -func Test_AccountNonceApi_account_nonce(t *testing.T) { - pubKey := signature.TestKeyringPairAlice.PublicKey - rt, storage := testhelpers.NewRuntimeInstance(t) - - nonce := 1 - - testhelpers.SetStorageAccountInfo(t, storage, pubKey, big.NewInt(5), 1) - - result, err := rt.Exec("AccountNonceApi_account_nonce", pubKey) - assert.NoError(t, err) - - assert.Equal(t, sc.U32(nonce).Bytes(), result) -} diff --git a/runtime/templates/pos/babe_test.go b/runtime/templates/pos/babe_api_test.go similarity index 100% rename from runtime/templates/pos/babe_test.go rename to runtime/templates/pos/babe_api_test.go diff --git a/runtime/templates/pos/balances_force_free_test.go b/runtime/templates/pos/balances_force_free_test.go deleted file mode 100644 index ce8d4cbd..00000000 --- a/runtime/templates/pos/balances_force_free_test.go +++ /dev/null @@ -1,67 +0,0 @@ -package main - -import ( - "bytes" - "math/big" - "testing" - - gossamertypes "github.com/ChainSafe/gossamer/dot/types" - "github.com/ChainSafe/gossamer/pkg/scale" - "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" - "github.com/stretchr/testify/assert" -) - -func Test_Balances_ForceFree_BadOrigin(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - metadata := testhelpers.RuntimeMetadata(t, rt) - - alice, err := ctypes.NewMultiAddressFromAccountID(signature.TestKeyringPairAlice.PublicKey) - - call, err := ctypes.NewCall(metadata, "Balances.force_free", alice, ctypes.NewU128(*big.NewInt(10000000000))) - assert.NoError(t, err) - - // Create the extrinsic - ext := ctypes.NewExtrinsic(call) - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - // Set Account Info - balance, ok := big.NewInt(0).SetString("500000000000000", 10) - assert.True(t, ok) - - testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) - - // Sign the transaction using Alice's default account - err = ext.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - extEnc := bytes.Buffer{} - encoder := cscale.NewEncoder(&extEnc) - err = ext.Encode(*encoder) - assert.NoError(t, err) - - header := gossamertypes.NewHeader(testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), gossamertypes.NewDigest()) - encodedHeader, err := scale.Marshal(*header) - assert.NoError(t, err) - - _, err = rt.Exec("Core_initialize_block", encodedHeader) - assert.NoError(t, err) - - res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.NoError(t, err) - - assert.Equal(t, testhelpers.ApplyExtrinsicResultBadOriginErr.Bytes(), res) -} diff --git a/runtime/templates/pos/balances_force_transfer_test.go b/runtime/templates/pos/balances_force_transfer_test.go deleted file mode 100644 index 9d2d60f0..00000000 --- a/runtime/templates/pos/balances_force_transfer_test.go +++ /dev/null @@ -1,71 +0,0 @@ -package main - -import ( - "bytes" - "math/big" - "testing" - - gossamertypes "github.com/ChainSafe/gossamer/dot/types" - "github.com/ChainSafe/gossamer/pkg/scale" - "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" - "github.com/stretchr/testify/assert" -) - -func Test_Balances_ForceTransfer_BadOrigin(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - metadata := testhelpers.RuntimeMetadata(t, rt) - - alice, err := ctypes.NewMultiAddressFromAccountID(signature.TestKeyringPairAlice.PublicKey) - - bob, err := ctypes.NewMultiAddressFromHexAccountID( - "0x90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22") - assert.NoError(t, err) - - call, err := ctypes.NewCall(metadata, "Balances.force_transfer", alice, bob, ctypes.NewUCompactFromUInt(10000000000)) - assert.NoError(t, err) - - // Create the extrinsic - ext := ctypes.NewExtrinsic(call) - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - // Set Account Info - balance, ok := big.NewInt(0).SetString("500000000000000", 10) - assert.True(t, ok) - - testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) - - // Sign the transaction using Alice's default account - err = ext.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - extEnc := bytes.Buffer{} - encoder := cscale.NewEncoder(&extEnc) - err = ext.Encode(*encoder) - assert.NoError(t, err) - - header := gossamertypes.NewHeader(testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), gossamertypes.NewDigest()) - encodedHeader, err := scale.Marshal(*header) - assert.NoError(t, err) - - _, err = rt.Exec("Core_initialize_block", encodedHeader) - assert.NoError(t, err) - - res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.NoError(t, err) - - assert.Equal(t, testhelpers.ApplyExtrinsicResultBadOriginErr.Bytes(), res) -} diff --git a/runtime/templates/pos/balances_set_balance_test.go b/runtime/templates/pos/balances_set_balance_test.go deleted file mode 100644 index b5929d22..00000000 --- a/runtime/templates/pos/balances_set_balance_test.go +++ /dev/null @@ -1,69 +0,0 @@ -package main - -import ( - "bytes" - "math/big" - "testing" - - gossamertypes "github.com/ChainSafe/gossamer/dot/types" - "github.com/ChainSafe/gossamer/pkg/scale" - "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" - "github.com/stretchr/testify/assert" -) - -func Test_Balances_SetBalance_BadOrigin(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - metadata := testhelpers.RuntimeMetadata(t, rt) - - bob, err := ctypes.NewMultiAddressFromHexAccountID( - "0x90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22") - assert.NoError(t, err) - - call, err := ctypes.NewCall(metadata, "Balances.set_balance", bob, ctypes.NewUCompactFromUInt(10000000000), ctypes.NewUCompactFromUInt(10000000000)) - assert.NoError(t, err) - - // Create the extrinsic - ext := ctypes.NewExtrinsic(call) - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - // Set Account Info - balance, ok := big.NewInt(0).SetString("500000000000000", 10) - assert.True(t, ok) - - testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) - - // Sign the transaction using Alice's default account - err = ext.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - extEnc := bytes.Buffer{} - encoder := cscale.NewEncoder(&extEnc) - err = ext.Encode(*encoder) - assert.NoError(t, err) - - header := gossamertypes.NewHeader(testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), gossamertypes.NewDigest()) - encodedHeader, err := scale.Marshal(*header) - assert.NoError(t, err) - - _, err = rt.Exec("Core_initialize_block", encodedHeader) - assert.NoError(t, err) - - res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.NoError(t, err) - - assert.Equal(t, testhelpers.ApplyExtrinsicResultBadOriginErr.Bytes(), res) -} diff --git a/runtime/templates/pos/balances_transfer_all_test.go b/runtime/templates/pos/balances_transfer_all_test.go deleted file mode 100644 index 3480f0b3..00000000 --- a/runtime/templates/pos/balances_transfer_all_test.go +++ /dev/null @@ -1,223 +0,0 @@ -package main - -import ( - "bytes" - "math/big" - "testing" - - gossamertypes "github.com/ChainSafe/gossamer/dot/types" - "github.com/ChainSafe/gossamer/lib/common" - "github.com/ChainSafe/gossamer/pkg/scale" - "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" - "github.com/stretchr/testify/assert" -) - -func Test_Balances_TransferAll_Success_AllowDeath(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - metadata := testhelpers.RuntimeMetadata(t, rt) - - bob, err := ctypes.NewMultiAddressFromHexAccountID( - "0x90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22") - assert.NoError(t, err) - - call, err := ctypes.NewCall(metadata, "Balances.transfer_all", bob, ctypes.NewBool(false)) - assert.NoError(t, err) - - // Create the extrinsic - ext := ctypes.NewExtrinsic(call) - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - // Set Account Info - balance, ok := big.NewInt(0).SetString("500000000000000", 10) - assert.True(t, ok) - - keyStorageAccountAlice, aliceAccountInfo := testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) - - // Sign the transaction using Alice's default account - err = ext.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - extEnc := bytes.Buffer{} - encoder := cscale.NewEncoder(&extEnc) - err = ext.Encode(*encoder) - assert.NoError(t, err) - - header := gossamertypes.NewHeader(testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), gossamertypes.NewDigest()) - encodedHeader, err := scale.Marshal(*header) - assert.NoError(t, err) - - _, err = rt.Exec("Core_initialize_block", encodedHeader) - assert.NoError(t, err) - - queryInfo := testhelpers.GetQueryInfo(t, rt, extEnc.Bytes()) - - res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.NoError(t, err) - assert.Equal(t, testhelpers.ApplyExtrinsicResultOutcome.Bytes(), res) - - bobHash, _ := common.Blake2b128(bob.AsID[:]) - keyStorageAccountBob := append(testhelpers.KeySystemHash, testhelpers.KeyAccountHash...) - keyStorageAccountBob = append(keyStorageAccountBob, bobHash...) - keyStorageAccountBob = append(keyStorageAccountBob, bob.AsID[:]...) - bytesStorageBob := (*storage).Get(keyStorageAccountBob) - - expectedBobAccountInfo := gossamertypes.AccountInfo{ - Nonce: 0, - Consumers: 0, - Producers: 1, - Sufficients: 0, - Data: gossamertypes.AccountData{ - Free: scale.MustNewUint128(big.NewInt(0).Sub(balance, queryInfo.PartialFee.ToBigInt())), - Reserved: scale.MustNewUint128(big.NewInt(0)), - MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - FreeFrozen: scale.MustNewUint128(big.NewInt(0)), - }, - } - - bobAccountInfo := gossamertypes.AccountInfo{} - - err = scale.Unmarshal(bytesStorageBob, &bobAccountInfo) - assert.NoError(t, err) - - assert.Equal(t, expectedBobAccountInfo, bobAccountInfo) - - expectedAliceAccountInfo := gossamertypes.AccountInfo{ - Nonce: 1, - Consumers: 0, - Producers: 1, - Sufficients: 0, - Data: gossamertypes.AccountData{ - Free: scale.MustNewUint128(big.NewInt(0)), - Reserved: scale.MustNewUint128(big.NewInt(0)), - MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - FreeFrozen: scale.MustNewUint128(big.NewInt(0)), - }, - } - - bytesAliceStorage := (*storage).Get(keyStorageAccountAlice) - err = scale.Unmarshal(bytesAliceStorage, &aliceAccountInfo) - assert.NoError(t, err) - - assert.Equal(t, expectedAliceAccountInfo, aliceAccountInfo) -} - -func Test_Balances_TransferAll_Success_KeepAlive(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - metadata := testhelpers.RuntimeMetadata(t, rt) - - bob, err := ctypes.NewMultiAddressFromHexAccountID( - "0x90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22") - assert.NoError(t, err) - - call, err := ctypes.NewCall(metadata, "Balances.transfer_all", bob, ctypes.NewBool(true)) - assert.NoError(t, err) - - // Create the extrinsic - ext := ctypes.NewExtrinsic(call) - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - // Set Account Info - balance, ok := big.NewInt(0).SetString("500000000000000", 10) - assert.True(t, ok) - - testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) - - // Sign the transaction using Alice's default account - err = ext.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - extEnc := bytes.Buffer{} - encoder := cscale.NewEncoder(&extEnc) - err = ext.Encode(*encoder) - assert.NoError(t, err) - - header := gossamertypes.NewHeader(testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), gossamertypes.NewDigest()) - encodedHeader, err := scale.Marshal(*header) - assert.NoError(t, err) - - _, err = rt.Exec("Core_initialize_block", encodedHeader) - assert.NoError(t, err) - - res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.NoError(t, err) - - // TODO: remove once tx payments are implemented - assert.Equal(t, testhelpers.ApplyExtrinsicResultKeepAliveErr.Bytes(), res) - - // TODO: Uncomment once tx payments are implemented, this will be successfully executed, - // for now it fails due to nothing reserved in account executor - //assert.Equal(t, - // primitives.NewApplyExtrinsicResult(primitives.NewDispatchOutcome(nil)).Bytes(), - // res, - //) - - //bobHash, _ := common.Blake2b128(bob.AsID[:]) - //keyStorageAccountBob := append(keySystemHash, keyAccountHash...) - //keyStorageAccountBob = append(keyStorageAccountBob, bobHash...) - //keyStorageAccountBob = append(keyStorageAccountBob, bob.AsID[:]...) - //bytesStorageBob := storage.Get(keyStorageAccountBob) - // - //expectedBobAccountInfo := gossamertypes.AccountInfo{ - // Nonce: 0, - // Consumers: 0, - // Producers: 1, - // Sufficients: 0, - // Data: gossamertypes.AccountData{ - // Free: scale.MustNewUint128(mockBalance), - // Reserved: scale.MustNewUint128(big.NewInt(0)), - // MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - // FreeFrozen: scale.MustNewUint128(big.NewInt(0)), - // }, - //} - // - //bobAccountInfo := gossamertypes.AccountInfo{} - // - //err = scale.Unmarshal(bytesStorageBob, &bobAccountInfo) - //assert.NoError(t, err) - // - //assert.Equal(t, expectedBobAccountInfo, bobAccountInfo) - // - //expectedAliceAccountInfo := gossamertypes.AccountInfo{ - // Nonce: 1, - // Consumers: 0, - // Producers: 0, - // Sufficients: 0, - // Data: gossamertypes.AccountData{ - // Free: scale.MustNewUint128(big.NewInt(0)), - // Reserved: scale.MustNewUint128(big.NewInt(0)), - // MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - // FreeFrozen: scale.MustNewUint128(big.NewInt(0)), - // }, - //} - // - //bytesAliceStorage := storage.Get(keyStorageAccountAlice) - //err = scale.Unmarshal(bytesAliceStorage, &aliceAccountInfo) - //assert.NoError(t, err) - // - //assert.Equal(t, expectedAliceAccountInfo, aliceAccountInfo) -} diff --git a/runtime/templates/pos/balances_transfer_keep_alive_test.go b/runtime/templates/pos/balances_transfer_keep_alive_test.go deleted file mode 100644 index ff057de7..00000000 --- a/runtime/templates/pos/balances_transfer_keep_alive_test.go +++ /dev/null @@ -1,124 +0,0 @@ -package main - -import ( - "bytes" - "math/big" - "testing" - - gossamertypes "github.com/ChainSafe/gossamer/dot/types" - "github.com/ChainSafe/gossamer/lib/common" - "github.com/ChainSafe/gossamer/pkg/scale" - "github.com/LimeChain/gosemble/constants" - "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" - "github.com/stretchr/testify/assert" -) - -func Test_Balances_TransferKeepAlive_Success(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - metadata := testhelpers.RuntimeMetadata(t, rt) - - bob, err := ctypes.NewMultiAddressFromHexAccountID( - "0x90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22") - assert.NoError(t, err) - - transferAmount := big.NewInt(0).SetUint64(constants.Dollar) - - call, err := ctypes.NewCall(metadata, "Balances.transfer_keep_alive", bob, ctypes.NewUCompact(transferAmount)) - assert.NoError(t, err) - - // Create the extrinsic - ext := ctypes.NewExtrinsic(call) - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - // Set Account Info - balance, e := big.NewInt(0).SetString("500000000000000", 10) - assert.True(t, e) - - keyStorageAccountAlice, aliceAccountInfo := testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) - - // Sign the transaction using Alice's default account - err = ext.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - extEnc := bytes.Buffer{} - encoder := cscale.NewEncoder(&extEnc) - err = ext.Encode(*encoder) - assert.NoError(t, err) - - header := gossamertypes.NewHeader(testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), gossamertypes.NewDigest()) - encodedHeader, err := scale.Marshal(*header) - assert.NoError(t, err) - - _, err = rt.Exec("Core_initialize_block", encodedHeader) - assert.NoError(t, err) - - queryInfo := testhelpers.GetQueryInfo(t, rt, extEnc.Bytes()) - - res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.NoError(t, err) - - assert.Equal(t, testhelpers.ApplyExtrinsicResultOutcome.Bytes(), res) - - bobHash, _ := common.Blake2b128(bob.AsID[:]) - keyStorageAccountBob := append(testhelpers.KeySystemHash, testhelpers.KeyAccountHash...) - keyStorageAccountBob = append(keyStorageAccountBob, bobHash...) - keyStorageAccountBob = append(keyStorageAccountBob, bob.AsID[:]...) - bytesStorageBob := (*storage).Get(keyStorageAccountBob) - - expectedBobAccountInfo := gossamertypes.AccountInfo{ - Nonce: 0, - Consumers: 0, - Producers: 1, - Sufficients: 0, - Data: gossamertypes.AccountData{ - Free: scale.MustNewUint128(transferAmount), - Reserved: scale.MustNewUint128(big.NewInt(0)), - MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - FreeFrozen: scale.MustNewUint128(big.NewInt(0)), - }, - } - - bobAccountInfo := gossamertypes.AccountInfo{} - - err = scale.Unmarshal(bytesStorageBob, &bobAccountInfo) - assert.NoError(t, err) - - assert.Equal(t, expectedBobAccountInfo, bobAccountInfo) - - expectedAliceFreeBalance := big.NewInt(0).Sub( - balance, - big.NewInt(0). - Add(transferAmount, queryInfo.PartialFee.ToBigInt())) - expectedAliceAccountInfo := gossamertypes.AccountInfo{ - Nonce: 1, - Consumers: 0, - Producers: 1, - Sufficients: 0, - Data: gossamertypes.AccountData{ - Free: scale.MustNewUint128(expectedAliceFreeBalance), - Reserved: scale.MustNewUint128(big.NewInt(0)), - MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - FreeFrozen: scale.MustNewUint128(big.NewInt(0)), - }, - } - - bytesAliceStorage := (*storage).Get(keyStorageAccountAlice) - err = scale.Unmarshal(bytesAliceStorage, &aliceAccountInfo) - assert.NoError(t, err) - - assert.Equal(t, expectedAliceAccountInfo, aliceAccountInfo) -} diff --git a/runtime/templates/pos/balances_transfer_test.go b/runtime/templates/pos/balances_transfer_test.go deleted file mode 100644 index 4e45c1c6..00000000 --- a/runtime/templates/pos/balances_transfer_test.go +++ /dev/null @@ -1,344 +0,0 @@ -package main - -import ( - "bytes" - "math/big" - "testing" - - gossamertypes "github.com/ChainSafe/gossamer/dot/types" - "github.com/ChainSafe/gossamer/lib/common" - "github.com/ChainSafe/gossamer/lib/crypto/secp256k1" - "github.com/ChainSafe/gossamer/pkg/scale" - "github.com/LimeChain/gosemble/constants" - "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" - "github.com/stretchr/testify/assert" - "golang.org/x/crypto/blake2b" -) - -func Test_Balances_Transfer_Success(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - metadata := testhelpers.RuntimeMetadata(t, rt) - - bob, err := ctypes.NewMultiAddressFromHexAccountID( - "0x90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22") - assert.NoError(t, err) - - transferAmount := big.NewInt(0).SetUint64(constants.Dollar) - - call, err := ctypes.NewCall(metadata, "Balances.transfer", bob, ctypes.NewUCompact(transferAmount)) - assert.NoError(t, err) - - // Create the extrinsic - ext := ctypes.NewExtrinsic(call) - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - // Set Account Info - balance, e := big.NewInt(0).SetString("500000000000000", 10) - assert.True(t, e) - - keyStorageAccountAlice, aliceAccountInfo := testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) - - // Sign the transaction using Alice's default account - err = ext.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - extEnc := bytes.Buffer{} - encoder := cscale.NewEncoder(&extEnc) - err = ext.Encode(*encoder) - assert.NoError(t, err) - - header := gossamertypes.NewHeader(testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), gossamertypes.NewDigest()) - encodedHeader, err := scale.Marshal(*header) - assert.NoError(t, err) - - _, err = rt.Exec("Core_initialize_block", encodedHeader) - assert.NoError(t, err) - - queryInfo := testhelpers.GetQueryInfo(t, rt, extEnc.Bytes()) - - res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.NoError(t, err) - assert.Equal(t, testhelpers.ApplyExtrinsicResultOutcome.Bytes(), res) - - bobHash, _ := common.Blake2b128(bob.AsID[:]) - keyStorageAccountBob := append(testhelpers.KeySystemHash, testhelpers.KeyAccountHash...) - keyStorageAccountBob = append(keyStorageAccountBob, bobHash...) - keyStorageAccountBob = append(keyStorageAccountBob, bob.AsID[:]...) - bytesStorageBob := (*storage).Get(keyStorageAccountBob) - - expectedBobAccountInfo := gossamertypes.AccountInfo{ - Nonce: 0, - Consumers: 0, - Producers: 1, - Sufficients: 0, - Data: gossamertypes.AccountData{ - Free: scale.MustNewUint128(transferAmount), - Reserved: scale.MustNewUint128(big.NewInt(0)), - MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - FreeFrozen: scale.MustNewUint128(big.NewInt(0)), - }, - } - - bobAccountInfo := gossamertypes.AccountInfo{} - - err = scale.Unmarshal(bytesStorageBob, &bobAccountInfo) - assert.NoError(t, err) - - assert.Equal(t, expectedBobAccountInfo, bobAccountInfo) - - expectedAliceFreeBalance := big.NewInt(0).Sub( - balance, - big.NewInt(0). - Add(transferAmount, queryInfo.PartialFee.ToBigInt())) - expectedAliceAccountInfo := gossamertypes.AccountInfo{ - Nonce: 1, - Consumers: 0, - Producers: 1, - Sufficients: 0, - Data: gossamertypes.AccountData{ - Free: scale.MustNewUint128(expectedAliceFreeBalance), - Reserved: scale.MustNewUint128(big.NewInt(0)), - MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - FreeFrozen: scale.MustNewUint128(big.NewInt(0)), - }, - } - - bytesAliceStorage := (*storage).Get(keyStorageAccountAlice) - err = scale.Unmarshal(bytesAliceStorage, &aliceAccountInfo) - assert.NoError(t, err) - - assert.Equal(t, expectedAliceAccountInfo, aliceAccountInfo) -} - -func Test_Balances_Transfer_Invalid_InsufficientBalance(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - metadata := testhelpers.RuntimeMetadata(t, rt) - - bob, err := ctypes.NewMultiAddressFromHexAccountID( - "0x90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22") - assert.NoError(t, err) - - transferAmount := big.NewInt(0).SetUint64(constants.Dollar) - - call, err := ctypes.NewCall(metadata, "Balances.transfer", bob, ctypes.NewUCompact(transferAmount)) - assert.NoError(t, err) - - // Create the extrinsic - ext := ctypes.NewExtrinsic(call) - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - // Set Account Info - balance := big.NewInt(0).Sub(transferAmount, big.NewInt(1)) - testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) - - // Sign the transaction using Alice's default account - err = ext.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - extEnc := bytes.Buffer{} - encoder := cscale.NewEncoder(&extEnc) - err = ext.Encode(*encoder) - assert.NoError(t, err) - - header := gossamertypes.NewHeader(testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), gossamertypes.NewDigest()) - encodedHeader, err := scale.Marshal(*header) - assert.NoError(t, err) - - _, err = rt.Exec("Core_initialize_block", encodedHeader) - assert.NoError(t, err) - - res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.Equal(t, testhelpers.ApplyExtrinsicResultCustomModuleErr.Bytes(), res) -} - -func Test_Balances_Transfer_Invalid_ExistentialDeposit(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - metadata := testhelpers.RuntimeMetadata(t, rt) - - bob, err := ctypes.NewMultiAddressFromHexAccountID( - "0x90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22") - assert.NoError(t, err) - - call, err := ctypes.NewCall(metadata, "Balances.transfer", bob, ctypes.NewUCompactFromUInt(1)) - assert.NoError(t, err) - - // Create the extrinsic - ext := ctypes.NewExtrinsic(call) - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - // Set Account Info - balance, e := big.NewInt(0).SetString("500000000000000", 10) - assert.True(t, e) - - testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) - - // Sign the transaction using Alice's default account - err = ext.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - extEnc := bytes.Buffer{} - encoder := cscale.NewEncoder(&extEnc) - err = ext.Encode(*encoder) - assert.NoError(t, err) - - header := gossamertypes.NewHeader(testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), gossamertypes.NewDigest()) - encodedHeader, err := scale.Marshal(*header) - assert.NoError(t, err) - - _, err = rt.Exec("Core_initialize_block", encodedHeader) - assert.NoError(t, err) - - res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.NoError(t, err) - - assert.Equal(t, testhelpers.ApplyExtrinsicResultExistentialDepositErr.Bytes(), res) -} - -func Test_Balances_Transfer_Ecdsa_Signature(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - metadata := testhelpers.RuntimeMetadata(t, rt) - - secpKeypair, err := secp256k1.GenerateKeypair() - assert.NoError(t, err) - - // Since ECDSA Public Keys are 33 bytes, matching the 32-byte AccountId in the runtime is achieved by blake256(publicKey) - accountId := blake2b.Sum256(secpKeypair.Public().Encode()) - - bob, err := ctypes.NewMultiAddressFromHexAccountID( - "0x90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22") - assert.NoError(t, err) - - transferAmount := big.NewInt(0).SetUint64(constants.Dollar) - - call, err := ctypes.NewCall(metadata, "Balances.transfer", bob, ctypes.NewUCompact(transferAmount)) - assert.NoError(t, err) - - // Create the extrinsic - ext := ctypes.NewExtrinsic(call) - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - // Set Account Info - balance, ok := big.NewInt(0).SetString("500000000000000", 10) - assert.True(t, ok) - - keyStorageAccountAlice, aliceAccountInfo := testhelpers.SetStorageAccountInfo(t, storage, accountId[:], balance, 0) - - err = testhelpers.SignExtrinsicSecp256k1(&ext, o, secpKeypair) - if err != nil { - panic(err) - } - - extEnc := bytes.Buffer{} - encoder := cscale.NewEncoder(&extEnc) - err = ext.Encode(*encoder) - assert.NoError(t, err) - - header := gossamertypes.NewHeader(testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), gossamertypes.NewDigest()) - encodedHeader, err := scale.Marshal(*header) - assert.NoError(t, err) - - _, err = rt.Exec("Core_initialize_block", encodedHeader) - assert.NoError(t, err) - - queryInfo := testhelpers.GetQueryInfo(t, rt, extEnc.Bytes()) - - res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.NoError(t, err) - assert.Equal(t, testhelpers.ApplyExtrinsicResultOutcome.Bytes(), res) - - bobHash, _ := common.Blake2b128(bob.AsID[:]) - keyStorageAccountBob := append(testhelpers.KeySystemHash, testhelpers.KeyAccountHash...) - keyStorageAccountBob = append(keyStorageAccountBob, bobHash...) - keyStorageAccountBob = append(keyStorageAccountBob, bob.AsID[:]...) - bytesStorageBob := (*storage).Get(keyStorageAccountBob) - - expectedBobAccountInfo := gossamertypes.AccountInfo{ - Nonce: 0, - Consumers: 0, - Producers: 1, - Sufficients: 0, - Data: gossamertypes.AccountData{ - Free: scale.MustNewUint128(transferAmount), - Reserved: scale.MustNewUint128(big.NewInt(0)), - MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - FreeFrozen: scale.MustNewUint128(big.NewInt(0)), - }, - } - - bobAccountInfo := gossamertypes.AccountInfo{} - - err = scale.Unmarshal(bytesStorageBob, &bobAccountInfo) - assert.NoError(t, err) - - assert.Equal(t, expectedBobAccountInfo, bobAccountInfo) - - expectedAliceFreeBalance := big.NewInt(0).Sub( - balance, - big.NewInt(0). - Add(transferAmount, queryInfo.PartialFee.ToBigInt())) - expectedAliceAccountInfo := gossamertypes.AccountInfo{ - Nonce: 1, - Consumers: 0, - Producers: 1, - Sufficients: 0, - Data: gossamertypes.AccountData{ - Free: scale.MustNewUint128(expectedAliceFreeBalance), - Reserved: scale.MustNewUint128(big.NewInt(0)), - MiscFrozen: scale.MustNewUint128(big.NewInt(0)), - FreeFrozen: scale.MustNewUint128(big.NewInt(0)), - }, - } - - bytesAliceStorage := (*storage).Get(keyStorageAccountAlice) - err = scale.Unmarshal(bytesAliceStorage, &aliceAccountInfo) - assert.NoError(t, err) - - assert.Equal(t, expectedAliceAccountInfo, aliceAccountInfo) -} diff --git a/runtime/templates/pos/block_builder_apply_extrinsic_test.go b/runtime/templates/pos/block_builder_apply_extrinsic_test.go index d839cc3e..7505e3a8 100644 --- a/runtime/templates/pos/block_builder_apply_extrinsic_test.go +++ b/runtime/templates/pos/block_builder_apply_extrinsic_test.go @@ -1,21 +1,13 @@ package main import ( - "bytes" - "math/big" "testing" "time" gossamertypes "github.com/ChainSafe/gossamer/dot/types" "github.com/ChainSafe/gossamer/pkg/scale" sc "github.com/LimeChain/goscale" - "github.com/LimeChain/gosemble/constants" - babetypes "github.com/LimeChain/gosemble/primitives/babe" - 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" "github.com/stretchr/testify/assert" ) @@ -25,28 +17,11 @@ func Test_ApplyExtrinsic_Timestamp(t *testing.T) { idata := gossamertypes.NewInherentData() time := time.Now().UnixMilli() - babeConfigurationBytes, err := rt.Exec("BabeApi_configuration", []byte{}) - assert.NoError(t, err) - - buffer := bytes.NewBuffer(babeConfigurationBytes) - - babeConfiguration, err := babetypes.DecodeConfiguration(buffer) - assert.NoError(t, err) - - slot := sc.U64(time) / babeConfiguration.SlotDuration - - babeHeader := gossamertypes.NewBabeDigest() - err = babeHeader.SetValue(*gossamertypes.NewBabePrimaryPreDigest(0, uint64(slot), [32]byte{}, [64]byte{})) - assert.NoError(t, err) - data, err := scale.Marshal(babeHeader) - assert.NoError(t, err) - preDigest := gossamertypes.NewBABEPreRuntimeDigest(data) + slot := testhelpers.GetBabeSlot(t, rt, uint64(time)) + digest := testhelpers.NewBabeDigest(t, slot) - digest := gossamertypes.NewDigest() - err = digest.Add(*preDigest) - assert.NoError(t, err) + header := gossamertypes.NewHeader(testhelpers.ParentHash, storageRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), digest) - header := gossamertypes.NewHeader(testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), digest) encodedHeader, err := scale.Marshal(*header) assert.NoError(t, err) @@ -71,201 +46,5 @@ func Test_ApplyExtrinsic_Timestamp(t *testing.T) { assert.Equal(t, []byte{1}, (*storage).Get(append(testhelpers.KeyTimestampHash, testhelpers.KeyTimestampDidUpdateHash...))) assert.Equal(t, sc.U64(time).Bytes(), (*storage).Get(append(testhelpers.KeyTimestampHash, testhelpers.KeyTimestampNowHash...))) - - assert.Equal(t, slot.Bytes(), (*storage).Get(append(testhelpers.KeyBabeHash, testhelpers.KeyCurrentSlotHash...))) -} - -func Test_ApplyExtrinsic_DispatchError_BadProofError(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - metadata := testhelpers.RuntimeMetadata(t, rt) - - digest := gossamertypes.NewDigest() - - header := gossamertypes.NewHeader(testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), digest) - encodedHeader, err := scale.Marshal(*header) - assert.NoError(t, err) - - _, err = rt.Exec("Core_initialize_block", encodedHeader) - assert.NoError(t, err) - - call, err := ctypes.NewCall(metadata, "System.remark", []byte{}) - assert.NoError(t, err) - - extrinsic := ctypes.NewExtrinsic(call) - - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - // Sign the transaction using Alice's default account - err = extrinsic.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - // Switch nonce - extrinsic.Signature.Nonce = ctypes.NewUCompactFromUInt(1) - - extEnc := bytes.Buffer{} - encoder := cscale.NewEncoder(&extEnc) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.NoError(t, err) - - extrinsicIndex := sc.U32(0) - extrinsicIndexValue := (*storage).Get(append(testhelpers.KeySystemHash, sc.NewOption[sc.U32](extrinsicIndex).Bytes()...)) - assert.Equal(t, []byte(nil), extrinsicIndexValue) - - assert.Equal(t, testhelpers.ApplyExtrinsicResultBadProofErr.Bytes(), res) -} - -func Test_ApplyExtrinsic_ExhaustsResourcesError(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - metadata := testhelpers.RuntimeMetadata(t, rt) - - digest := gossamertypes.NewDigest() - - header := gossamertypes.NewHeader(testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), digest) - encodedHeader, err := scale.Marshal(*header) - assert.NoError(t, err) - - _, err = rt.Exec("Core_initialize_block", encodedHeader) - assert.NoError(t, err) - - // Append long args - args := make([]byte, constants.FiveMbPerBlockPerExtrinsic) - - call, err := ctypes.NewCall(metadata, "System.remark", args) - assert.NoError(t, err) - - extrinsic := ctypes.NewExtrinsic(call) - - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - // Sign the transaction using Alice's default account - err = extrinsic.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - extEnc := bytes.Buffer{} - encoder := cscale.NewEncoder(&extEnc) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.NoError(t, err) - - extrinsicIndex := sc.U32(0) - extrinsicIndexValue := (*storage).Get(append(testhelpers.KeySystemHash, sc.NewOption[sc.U32](extrinsicIndex).Bytes()...)) - assert.Equal(t, []byte(nil), extrinsicIndexValue) - - assert.Equal(t, testhelpers.ApplyExtrinsicResultExhaustsResourcesErr.Bytes(), res) -} - -func Test_ApplyExtrinsic_FutureError_InvalidNonce(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - metadata := testhelpers.RuntimeMetadata(t, rt) - - // Set Balance & Nonce - testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, big.NewInt(5), 3) - - digest := gossamertypes.NewDigest() - - header := gossamertypes.NewHeader(testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), digest) - encodedHeader, err := scale.Marshal(*header) - assert.NoError(t, err) - - _, err = rt.Exec("Core_initialize_block", encodedHeader) - assert.NoError(t, err) - - call, err := ctypes.NewCall(metadata, "System.remark", []byte{}) - assert.NoError(t, err) - - extrinsic := ctypes.NewExtrinsic(call) - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(5), // Invalid nonce - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - // Sign the transaction using Alice's default account - err = extrinsic.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - extEnc := bytes.Buffer{} - encoder := cscale.NewEncoder(&extEnc) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - encTransactionValidityResult, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.NoError(t, err) - - buffer := &bytes.Buffer{} - buffer.Write(encTransactionValidityResult) - transactionValidityResult, err := primitives.DecodeTransactionValidityResult(buffer) - assert.Nil(t, err) - - assert.Equal(t, testhelpers.TransactionValidityResultFutureErr, transactionValidityResult) -} - -func Test_ApplyExtrinsic_InvalidLengthPrefix(t *testing.T) { - rt, _ := testhelpers.NewRuntimeInstance(t) - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - metadata := testhelpers.RuntimeMetadata(t, rt) - - call, err := ctypes.NewCall(metadata, "System.remark", []byte{}) - assert.NoError(t, err) - - extrinsic := ctypes.NewExtrinsic(call) - - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - // Sign the transaction using Alice's default account - err = extrinsic.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - extEnc := bytes.Buffer{} - encoder := cscale.NewEncoder(&extEnc) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - // Increase extrinsic length by 1 - bytesExtrinsic := extEnc.Bytes() - bytesExtrinsic[0] += 4 - - _, err = rt.Exec("BlockBuilder_apply_extrinsic", bytesExtrinsic) - assert.Error(t, err) + assert.Equal(t, sc.U64(slot).Bytes(), (*storage).Get(append(testhelpers.KeyBabeHash, testhelpers.KeyCurrentSlotHash...))) } diff --git a/runtime/templates/pos/block_builder_check_inherents_test.go b/runtime/templates/pos/block_builder_check_inherents_test.go deleted file mode 100644 index 6099b8ac..00000000 --- a/runtime/templates/pos/block_builder_check_inherents_test.go +++ /dev/null @@ -1,57 +0,0 @@ -package main - -import ( - "bytes" - "testing" - "time" - - gossamertypes "github.com/ChainSafe/gossamer/dot/types" - "github.com/ChainSafe/gossamer/pkg/scale" - "github.com/LimeChain/gosemble/primitives/types" - "github.com/LimeChain/gosemble/testhelpers" - "github.com/stretchr/testify/assert" -) - -func Test_CheckInherents(t *testing.T) { - expectedCheckInherentsResult := types.NewCheckInherentsResult() - - idata := gossamertypes.NewInherentData() - time := time.Now().UnixMilli() - err := idata.SetInherent(gossamertypes.Timstap0, uint64(time)) - - assert.NoError(t, err) - - ienc, err := idata.Encode() - assert.NoError(t, err) - - rt, _ := testhelpers.NewRuntimeInstance(t) - - inherentExt, err := rt.Exec("BlockBuilder_inherent_extrinsics", ienc) - assert.NoError(t, err) - assert.NotNil(t, inherentExt) - - header := gossamertypes.NewHeader(testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), gossamertypes.NewDigest()) - - var exts [][]byte - err = scale.Unmarshal(inherentExt, &exts) - assert.NoError(t, err) - - block := gossamertypes.Block{ - Header: *header, - Body: gossamertypes.BytesArrayToExtrinsics(exts), - } - - encodedBlock, err := scale.Marshal(block) - assert.NoError(t, err) - - inputData := append(encodedBlock, ienc...) - bytesCheckInherentsResult, err := rt.Exec("BlockBuilder_check_inherents", inputData) - assert.NoError(t, err) - - buffer := &bytes.Buffer{} - buffer.Write(bytesCheckInherentsResult) - checkInherentsResult, err := types.DecodeCheckInherentsResult(buffer) - assert.Nil(t, err) - - assert.Equal(t, expectedCheckInherentsResult, checkInherentsResult) -} diff --git a/runtime/templates/pos/block_builder_inherent_extrinsics_test.go b/runtime/templates/pos/block_builder_inherent_extrinsics_test.go deleted file mode 100644 index cffcefc4..00000000 --- a/runtime/templates/pos/block_builder_inherent_extrinsics_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package main - -import ( - "bytes" - "testing" - "time" - - gossamertypes "github.com/ChainSafe/gossamer/dot/types" - sc "github.com/LimeChain/goscale" - "github.com/LimeChain/gosemble/execution/types" - "github.com/LimeChain/gosemble/primitives/log" - "github.com/LimeChain/gosemble/testhelpers" - "github.com/stretchr/testify/assert" -) - -func Test_BlockBuilder_Inherent_Extrinsics(t *testing.T) { - idata := gossamertypes.NewInherentData() - time := time.Now().UnixMilli() - err := idata.SetInherent(gossamertypes.Timstap0, uint64(time)) - assert.NoError(t, err) - - decoder := types.NewRuntimeDecoder(modules, newSignedExtra(), log.NewLogger()) - - rt, _ := testhelpers.NewRuntimeInstance(t) - metadata := testhelpers.RuntimeMetadata(t, rt) - - expectedExtrinsicBytes := testhelpers.TimestampExtrinsicBytes(t, metadata, uint64(time)) - - ienc, err := idata.Encode() - assert.NoError(t, err) - - inherentExt, err := rt.Exec("BlockBuilder_inherent_extrinsics", ienc) - assert.NoError(t, err) - - assert.NotNil(t, inherentExt) - - buffer := &bytes.Buffer{} - buffer.Write([]byte{inherentExt[0]}) - - totalInherents, err := sc.DecodeCompact[sc.U128](buffer) - assert.Nil(t, err) - assert.Equal(t, int64(1), totalInherents.ToBigInt().Int64()) - buffer.Reset() - - buffer.Write(inherentExt[1:]) - extrinsic, err := decoder.DecodeUncheckedExtrinsic(buffer) - assert.Nil(t, err) - - assert.Equal(t, expectedExtrinsicBytes, extrinsic.Bytes()) -} diff --git a/runtime/templates/pos/core_execute_block_test.go b/runtime/templates/pos/core_execute_block_test.go index 543a6a4c..3b43e229 100644 --- a/runtime/templates/pos/core_execute_block_test.go +++ b/runtime/templates/pos/core_execute_block_test.go @@ -13,7 +13,6 @@ import ( sc "github.com/LimeChain/goscale" "github.com/LimeChain/gosemble/constants" - babetypes "github.com/LimeChain/gosemble/primitives/babe" primitives "github.com/LimeChain/gosemble/primitives/types" "github.com/LimeChain/gosemble/testhelpers" @@ -21,9 +20,9 @@ import ( ) var ( - genesisConfigJson = []byte("{\"system\":{\"code\":\"\"},\"babe\":{\"authorities\":[\"5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY\"],\"epochConfig\":{\"c\":[1,4],\"allowed_slots\":\"PrimarySlots\"}},\"grandpa\":{\"authorities\":[]},\"balances\":{\"balances\":[[\"5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY\",1000000000000000000],[\"5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty\",1000000000000000000],[\"5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y\",1000000000000000000],[\"5DAAnrj7VHTznn2AWBemMuyBwZWs6FNFjdyVXUeYum3PTXFy\",1000000000000000000],[\"5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw\",1000000000000000000],[\"5CiPPseXPECbkjWCa6MnjNokrgYjMqmKndv2rSnekmSK2DjL\",1000000000000000000],[\"5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY\",1000000000000000000],[\"5HpG9w8EBLe5XCrbczpwq5TSXvedjrBGCwqxK1iQ7qUsSWFc\",1000000000000000000],[\"5Ck5SLSHYac6WFt5UZRSsdJjwmpSZq85fd5TRNAdZQVzEAPT\",1000000000000000000],[\"5HKPmK9GYtE1PSLsS1qiYU9xQ9Si1NcEhdeCq9sw5bqu4ns8\",1000000000000000000],[ \"5FCfAonRZgTFrTd9HREEyeJjDpT397KMzizE6T3DvebLFE7n\",1000000000000000000],[\"5CRmqmsiNFExV6VbdmPJViVxrWmkaXXvBrSX8oqBT8R9vmWk\",1000000000000000000]]},\"session\": {\"keys\": [[\"5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY\",\"5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY\",{\"grandpa\":\"5FA9nQDVg267DEd8m1ZypXLBnvN7SFxYwV7ndqSYGiN9TTpu\",\"babe\":\"5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY\"}]]},\"transactionPayment\":{\"multiplier\":\"1\"}}") - dateTime = time.Date(2023, time.January, 2, 3, 4, 5, 6, time.UTC) - storageRoot = common.MustHexToHash("0xd940e147feef433028c8ca2db9ef6c7c51bf6e9538b81301fff3ff24950fa056") // Depends on date + authority1 = gossamertypes.AuthorityRaw{Key: [32]byte{0xd4, 0x35, 0x93, 0xc7, 0x15, 0xfd, 0xd3, 0x1c, 0x61, 0x14, 0x1a, 0xbd, 0x04, 0xa9, 0x9f, 0xd6, 0x82, 0x2c, 0x85, 0x58, 0x85, 0x4c, 0xcd, 0xe3, 0x9a, 0x56, 0x84, 0xe7, 0xa5, 0x6d, 0xa2, 0x7d}, Weight: 0} + dateTime = time.Date(2023, time.January, 2, 3, 4, 5, 6, time.UTC) + storageRoot = common.MustHexToHash("0x48048c3e427fa73c56be0f8859aa0471c836c9fb874f3277f1b19e68a59539c1") // Depends on date ) func Test_BlockExecution(t *testing.T) { @@ -35,33 +34,12 @@ func Test_BlockExecution(t *testing.T) { rt, storage := testhelpers.NewRuntimeInstance(t) metadata := testhelpers.RuntimeMetadata(t, rt) - genesisConfigJsonBytes, err := scale.Marshal(genesisConfigJson) - assert.NoError(t, err) - - _, err = rt.Exec("GenesisBuilder_build_config", genesisConfigJsonBytes) - assert.NoError(t, err) + testhelpers.GenesisBuild(t, rt, testhelpers.GenesisConfigJson) - babeConfigurationBytes, err := rt.Exec("BabeApi_configuration", []byte{}) - assert.NoError(t, err) - - buffer := bytes.NewBuffer(babeConfigurationBytes) + time := dateTime.UnixMilli() - babeConfiguration, err := babetypes.DecodeConfiguration(buffer) - assert.NoError(t, err) - - slot := sc.U64(dateTime.UnixMilli()) / babeConfiguration.SlotDuration - - buffer.Reset() - - babeHeader := gossamertypes.NewBabeDigest() - err = babeHeader.SetValue(*gossamertypes.NewBabePrimaryPreDigest(0, uint64(slot), [32]byte{}, [64]byte{})) - assert.NoError(t, err) - data, err := scale.Marshal(babeHeader) - assert.NoError(t, err) - preDigest := gossamertypes.NewBABEPreRuntimeDigest(data) - digest := gossamertypes.NewDigest() - err = digest.Add(*preDigest) - assert.NoError(t, err) + slot := testhelpers.GetBabeSlot(t, rt, uint64(time)) + digest := testhelpers.NewBabeDigest(t, slot) header := gossamertypes.NewHeader(testhelpers.ParentHash, storageRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), digest) @@ -100,10 +78,10 @@ func Test_BlockExecution(t *testing.T) { assert.Equal(t, testhelpers.ParentHash.ToBytes(), (*storage).Get(blockHashKey)) idata := gossamertypes.NewInherentData() - err = idata.SetInherent(gossamertypes.Timstap0, uint64(dateTime.UnixMilli())) + err = idata.SetInherent(gossamertypes.Timstap0, uint64(time)) assert.NoError(t, err) - expectedExtrinsicBytes := testhelpers.TimestampExtrinsicBytes(t, metadata, uint64(dateTime.UnixMilli())) + expectedExtrinsicBytes := testhelpers.TimestampExtrinsicBytes(t, metadata, uint64(time)) ienc, err := idata.Encode() assert.NoError(t, err) @@ -112,6 +90,7 @@ func Test_BlockExecution(t *testing.T) { assert.NoError(t, err) assert.NotNil(t, inherentExt) + buffer := bytes.NewBuffer([]byte{}) buffer.Write([]byte{inherentExt[0]}) totalInherents, err := sc.DecodeCompact[sc.U128](buffer) @@ -133,113 +112,48 @@ func Test_BlockExecution(t *testing.T) { bytesResult, err := rt.Exec("BlockBuilder_finalize_block", []byte{}) assert.NoError(t, err) + expectedDigest := setupExpectedDigest(t, slot) resultHeader := gossamertypes.NewEmptyHeader() assert.NoError(t, scale.Unmarshal(bytesResult, resultHeader)) resultHeader.Hash() // Call this to be set, otherwise structs do not match... - - // assert.Equal(t, header, resultHeader) + expectedHeader := gossamertypes.NewHeader(testhelpers.ParentHash, storageRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), expectedDigest) + assert.Equal(t, expectedHeader, resultHeader) assert.Equal(t, []byte(nil), (*storage).Get(append(testhelpers.KeyTimestampHash, testhelpers.KeyTimestampDidUpdateHash...))) - assert.Equal(t, sc.U64(dateTime.UnixMilli()).Bytes(), (*storage).Get(append(testhelpers.KeyTimestampHash, testhelpers.KeyTimestampNowHash...))) + assert.Equal(t, sc.U64(time).Bytes(), (*storage).Get(append(testhelpers.KeyTimestampHash, testhelpers.KeyTimestampNowHash...))) assert.Equal(t, []byte(nil), (*storage).Get(testhelpers.KeyExtrinsicIndex)) assert.Equal(t, []byte(nil), (*storage).Get(append(testhelpers.KeySystemHash, testhelpers.KeyExecutionPhaseHash...))) assert.Equal(t, []byte(nil), (*storage).Get(append(testhelpers.KeySystemHash, testhelpers.KeyAllExtrinsicsLenHash...))) assert.Equal(t, []byte(nil), (*storage).Get(append(testhelpers.KeySystemHash, testhelpers.KeyExtrinsicCountHash...))) + expectedEncDigest, err := scale.Marshal(expectedDigest) + assert.NoError(t, err) + assert.Equal(t, testhelpers.ParentHash.ToBytes(), (*storage).Get(append(testhelpers.KeySystemHash, testhelpers.KeyParentHash...))) - // assert.Equal(t, encExpectedDigest, (*storage).Get(append(testhelpers.KeySystemHash, testhelpers.KeyDigestHash...))) + assert.Equal(t, expectedEncDigest, (*storage).Get(append(testhelpers.KeySystemHash, testhelpers.KeyDigestHash...))) assert.Equal(t, encBlockNumber, (*storage).Get(append(testhelpers.KeySystemHash, testhelpers.KeyNumberHash...))) - assert.Equal(t, slot.Bytes(), (*storage).Get(append(testhelpers.KeyBabeHash, testhelpers.KeyCurrentSlotHash...))) + assert.Equal(t, sc.U64(slot).Bytes(), (*storage).Get(append(testhelpers.KeyBabeHash, testhelpers.KeyCurrentSlotHash...))) } -// func Test_ExecuteBlock(t *testing.T) { -// // blockBuilder.Inherent_Extrinsics -// // blockBuilder.ExecuteBlock - -// rt, _ := testhelpers.NewRuntimeInstance(t) -// metadata := testhelpers.RuntimeMetadata(t, rt) - -// babeConfigurationBytes, err := rt.Exec("BabeApi_configuration", []byte{}) -// assert.NoError(t, err) - -// buffer := bytes.NewBuffer(babeConfigurationBytes) - -// babeConfiguration, err := babe.DecodeBabeConfiguration(buffer) -// assert.NoError(t, err) - -// slot := sc.U64(dateTime.UnixMilli()) / babeConfiguration.SlotDuration - -// buffer.Reset() - -// babeHeader := gossamertypes.NewBabeDigest() -// err = babeHeader.SetValue(*gossamertypes.NewBabePrimaryPreDigest(0, uint64(slot), [32]byte{}, [64]byte{})) -// assert.NoError(t, err) -// data, err := scale.Marshal(babeHeader) -// assert.NoError(t, err) -// preDigest := gossamertypes.NewBABEPreRuntimeDigest(data) -// digest := gossamertypes.NewDigest() -// err = digest.Add(*preDigest) -// assert.NoError(t, err) - -// idata := gossamertypes.NewInherentData() -// err = idata.SetInherent(gossamertypes.Timstap0, uint64(dateTime.UnixMilli())) - -// assert.NoError(t, err) - -// ienc, err := idata.Encode() -// assert.NoError(t, err) - -// expectedExtrinsicBytes := testhelpers.TimestampExtrinsicBytes(t, metadata, uint64(dateTime.UnixMilli())) - -// inherentExt, err := rt.Exec("BlockBuilder_inherent_extrinsics", ienc) -// assert.NoError(t, err) -// assert.NotNil(t, inherentExt) - -// buffer.Write([]byte{inherentExt[0]}) - -// totalInherents, err := sc.DecodeCompact[sc.U128](buffer) -// assert.Nil(t, err) -// assert.Equal(t, int64(1), totalInherents.ToBigInt().Int64()) -// buffer.Reset() - -// actualExtrinsic := inherentExt[1:] -// assert.Equal(t, expectedExtrinsicBytes, actualExtrinsic) - -// var exts [][]byte -// err = scale.Unmarshal(inherentExt, &exts) -// assert.Nil(t, err) - -// // expectedStorageDigest, err := scale.Marshal(digest) -// // assert.NoError(t, err) -// // encBlockNumber, err := scale.Marshal(testhelpers.BlockNumber) -// // assert.NoError(t, err) - -// header := gossamertypes.NewHeader(testhelpers.ParentHash, storageRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), digest) - -// block := gossamertypes.Block{ -// Header: *header, -// Body: gossamertypes.BytesArrayToExtrinsics(exts), -// } - -// encodedBlock, err := scale.Marshal(block) -// assert.Nil(t, err) - -// _, err = rt.Exec("Core_execute_block", encodedBlock) -// assert.NoError(t, err) - -// // assert.Equal(t, []byte(nil), (*storage).Get(append(testhelpers.KeyTimestampHash, testhelpers.KeyTimestampDidUpdateHash...))) -// // assert.Equal(t, sc.U64(dateTime.UnixMilli()).Bytes(), (*storage).Get(append(testhelpers.KeyTimestampHash, testhelpers.KeyTimestampNowHash...))) - -// // assert.Equal(t, []byte(nil), (*storage).Get(testhelpers.KeyExtrinsicIndex)) -// // assert.Equal(t, []byte(nil), (*storage).Get(append(testhelpers.KeySystemHash, testhelpers.KeyExecutionPhaseHash...))) -// // assert.Equal(t, []byte(nil), (*storage).Get(append(testhelpers.KeySystemHash, testhelpers.KeyAllExtrinsicsLenHash...))) -// // assert.Equal(t, []byte(nil), (*storage).Get(append(testhelpers.KeySystemHash, testhelpers.KeyExtrinsicCountHash...))) +func setupExpectedDigest(t *testing.T, slot uint64) gossamertypes.Digest { + nextEpoch := gossamertypes.NextEpochData{ + Authorities: []gossamertypes.AuthorityRaw{authority1}, + Randomness: [32]byte{}, + } + babeConsensusDigest := gossamertypes.NewBabeConsensusDigest() + babeConsensusDigest.SetValue(nextEpoch) + encConsensusDigest, err := scale.Marshal(babeConsensusDigest) + assert.NoError(t, err) + nextEpochConsensusDigest := gossamertypes.ConsensusDigest{ + ConsensusEngineID: gossamertypes.BabeEngineID, + Data: encConsensusDigest, + } -// // assert.Equal(t, testhelpers.ParentHash.ToBytes(), (*storage).Get(append(testhelpers.KeySystemHash, testhelpers.KeyParentHash...))) -// // // assert.Equal(t, expectedStorageDigest, (*storage).Get(append(testhelpers.KeySystemHash, testhelpers.KeyDigestHash...))) -// // assert.Equal(t, encBlockNumber, (*storage).Get(append(testhelpers.KeySystemHash, testhelpers.KeyNumberHash...))) + digest := testhelpers.NewBabeDigest(t, slot) + assert.NoError(t, err) + digest.Add(nextEpochConsensusDigest) -// // assert.Equal(t, slot.Bytes(), (*storage).Get(append(testhelpers.KeyBabeHash, testhelpers.KeyCurrentSlotHash...))) -// } + return digest +} diff --git a/runtime/templates/pos/core_version_test.go b/runtime/templates/pos/core_version_test.go deleted file mode 100644 index 5103fbc8..00000000 --- a/runtime/templates/pos/core_version_test.go +++ /dev/null @@ -1,32 +0,0 @@ -package main - -import ( - "bytes" - "testing" - - runtimetypes "github.com/ChainSafe/gossamer/lib/runtime" - "github.com/ChainSafe/gossamer/pkg/scale" - "github.com/LimeChain/gosemble/testhelpers" - "github.com/stretchr/testify/assert" -) - -func Test_CoreVersion(t *testing.T) { - rt, _ := testhelpers.NewRuntimeInstance(t) - - versionEncBytes, err := rt.Exec("Core_version", []byte{}) - assert.NoError(t, err) - - buffer := bytes.NewBuffer(versionEncBytes) - - dec := scale.NewDecoder(buffer) - runtimeVersion := runtimetypes.Version{} - err = dec.Decode(&runtimeVersion) - assert.NoError(t, err) - assert.Equal(t, "node-template", string(runtimeVersion.SpecName)) - assert.Equal(t, "node-template", string(runtimeVersion.ImplName)) - assert.Equal(t, uint32(1), runtimeVersion.AuthoringVersion) - assert.Equal(t, uint32(100), runtimeVersion.SpecVersion) - assert.Equal(t, uint32(1), runtimeVersion.ImplVersion) - assert.Equal(t, uint32(1), runtimeVersion.TransactionVersion) - assert.Equal(t, uint8(1), runtimeVersion.StateVersion) -} diff --git a/runtime/templates/pos/grandpa_test.go b/runtime/templates/pos/grandpa_test.go deleted file mode 100644 index 539430b5..00000000 --- a/runtime/templates/pos/grandpa_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package main - -import ( - "testing" - - "github.com/ChainSafe/gossamer/lib/common" - sc "github.com/LimeChain/goscale" - "github.com/LimeChain/gosemble/frame/grandpa" - "github.com/LimeChain/gosemble/primitives/types" - "github.com/LimeChain/gosemble/testhelpers" - "github.com/stretchr/testify/assert" -) - -func Test_Grandpa_Authorities_Empty(t *testing.T) { - rt, _ := testhelpers.NewRuntimeInstance(t) - - result, err := rt.Exec("GrandpaApi_grandpa_authorities", []byte{}) - assert.NoError(t, err) - - assert.Equal(t, []byte{0}, result) -} - -func Test_Grandpa_Authorities(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - pubKey1 := common.MustHexToBytes("0x88dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee") - pubKey2 := common.MustHexToBytes("0x88dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ef") - weight := sc.U64(1) - - storageAuthorityList := types.VersionedAuthorityList{ - Version: grandpa.AuthorityVersion, - AuthorityList: sc.Sequence[types.Authority]{ - { - Id: types.AccountId{FixedSequence: sc.BytesToFixedSequenceU8(pubKey1)}, - Weight: weight, - }, - { - Id: types.AccountId{FixedSequence: sc.BytesToFixedSequenceU8(pubKey2)}, - Weight: weight, - }, - }, - } - err := (*storage).Put([]byte(":grandpa_authorities"), storageAuthorityList.Bytes()) - assert.NoError(t, err) - - result, err := rt.Exec("GrandpaApi_grandpa_authorities", []byte{}) - assert.NoError(t, err) - - assert.Equal(t, storageAuthorityList.AuthorityList.Bytes(), result) -} diff --git a/runtime/templates/pos/metadata_test.go b/runtime/templates/pos/metadata_test.go deleted file mode 100644 index 375fffa7..00000000 --- a/runtime/templates/pos/metadata_test.go +++ /dev/null @@ -1,150 +0,0 @@ -package main - -import ( - "bytes" - "testing" - - sc "github.com/LimeChain/goscale" - "github.com/LimeChain/gosemble/primitives/types" - "github.com/LimeChain/gosemble/testhelpers" - "github.com/centrifuge/go-substrate-rpc-client/v4/types/codec" - "github.com/stretchr/testify/assert" -) - -func Test_Metadata_Encoding_Success(t *testing.T) { - runtime, _ := testhelpers.NewRuntimeInstance(t) - gossamerMetadata := testhelpers.RuntimeMetadata(t, runtime) - - bMetadata, err := runtime.Metadata() - assert.NoError(t, err) - - buffer := bytes.NewBuffer(bMetadata) - - // Decode Compact Length - _, err = sc.DecodeCompact[sc.U128](buffer) - assert.Nil(t, err) - - // Copy bytes for assertion after re-encode. - bMetadataCopy := make([]byte, buffer.Len()) - copy(bMetadataCopy, buffer.Bytes()) - - metadata, err := types.DecodeMetadata(buffer) - assert.Nil(t, err) - - // Assert encoding of previously decoded - assert.Equal(t, bMetadataCopy, metadata.Bytes()) - - // Encode gossamer Metadata - bGossamerMetadata, err := codec.Encode(gossamerMetadata) - assert.NoError(t, err) - - assert.Equal(t, metadata.Bytes(), bGossamerMetadata) -} - -func Test_Metadata_Versions_Correct_Versions(t *testing.T) { - runtime, _ := testhelpers.NewRuntimeInstance(t) - - metadataVersions, err := runtime.Exec("Metadata_metadata_versions", []byte{}) - assert.NoError(t, err) - - buffer := &bytes.Buffer{} - buffer.Write(metadataVersions) - - versions, err := sc.DecodeSequence[sc.U32](buffer) - assert.Nil(t, err) - buffer.Reset() - - expectedVersions := sc.Sequence[sc.U32]{ - sc.U32(types.MetadataVersion14), - sc.U32(types.MetadataVersion15), - } - - assert.Equal(t, versions, expectedVersions) -} - -func Test_Metadata_At_Version_14(t *testing.T) { - runtime, _ := testhelpers.NewRuntimeInstance(t) - gossamerMetadata := testhelpers.RuntimeMetadata(t, runtime) - - version14 := sc.U32(types.MetadataVersion14) - - bMetadata, err := runtime.Exec("Metadata_metadata_at_version", version14.Bytes()) - assert.NoError(t, err) - - resultOptionMetadataBuffer := bytes.NewBuffer(bMetadata) - - optionMetadata, err := sc.DecodeOptionWith[sc.Sequence[sc.U8]](resultOptionMetadataBuffer, sc.DecodeSequence[sc.U8]) - assert.Nil(t, err) - - metadataV14Bytes := optionMetadata.Value.Bytes() - - buffer := bytes.NewBuffer(metadataV14Bytes) - - // Decode Compact Length - _, err = sc.DecodeCompact[sc.U128](buffer) - assert.Nil(t, err) - - // Copy bytes for assertion after re-encode. - bMetadataCopy := make([]byte, buffer.Len()) - copy(bMetadataCopy, buffer.Bytes()) - - metadata, err := types.DecodeMetadata(buffer) - assert.Nil(t, err) - - assert.Equal(t, bMetadataCopy, metadata.Bytes()) - - bGossamerMetadata, err := codec.Encode(gossamerMetadata) - assert.NoError(t, err) - - assert.Equal(t, metadata.Bytes(), bGossamerMetadata) -} - -func Test_Metadata_At_Version_15(t *testing.T) { - runtime, _ := testhelpers.NewRuntimeInstance(t) - - version15 := sc.U32(types.MetadataVersion15) - - bMetadata, err := runtime.Exec("Metadata_metadata_at_version", version15.Bytes()) - assert.NoError(t, err) - - resultOptionMetadataBuffer := bytes.NewBuffer(bMetadata) - - optionMetadata, err := sc.DecodeOptionWith[sc.Sequence[sc.U8]](resultOptionMetadataBuffer, sc.DecodeSequence[sc.U8]) - assert.Nil(t, err) - - metadataV15Bytes := optionMetadata.Value.Bytes() - - buffer := bytes.NewBuffer(metadataV15Bytes) - - // Decode Compact Length - _, err = sc.DecodeCompact[sc.U128](buffer) - assert.Nil(t, err) - - bMetadataCopy := make([]byte, buffer.Len()) - copy(bMetadataCopy, buffer.Bytes()) - - metadata, err := types.DecodeMetadata(buffer) - assert.Nil(t, err) - - assert.Equal(t, bMetadataCopy, metadata.Bytes()) -} - -func Test_Metadata_At_Version_UnsupportedVersion(t *testing.T) { - runtime, _ := testhelpers.NewRuntimeInstance(t) - - unsupportedVersion := sc.U32(10) - - bMetadata, err := runtime.Exec("Metadata_metadata_at_version", unsupportedVersion.Bytes()) - assert.NoError(t, err) - - buffer := bytes.NewBuffer(bMetadata) - - result, err := sc.DecodeOption[types.Metadata](buffer) - assert.Nil(t, err) - - expectedResult := sc.Option[types.Metadata]{ - HasValue: sc.Bool(false), - } - - assert.Equal(t, result.Bytes(), expectedResult.Bytes()) -} diff --git a/runtime/templates/pos/offchain_worker_test.go b/runtime/templates/pos/offchain_worker_test.go index e4f6004e..cd36718c 100644 --- a/runtime/templates/pos/offchain_worker_test.go +++ b/runtime/templates/pos/offchain_worker_test.go @@ -1,7 +1,6 @@ package main import ( - "bytes" "testing" "time" @@ -9,7 +8,6 @@ import ( "github.com/ChainSafe/gossamer/lib/common" "github.com/ChainSafe/gossamer/pkg/scale" sc "github.com/LimeChain/goscale" - babetypes "github.com/LimeChain/gosemble/primitives/babe" "github.com/LimeChain/gosemble/primitives/types" "github.com/LimeChain/gosemble/testhelpers" "github.com/stretchr/testify/assert" @@ -18,34 +16,11 @@ import ( func Test_Offchain_Worker(t *testing.T) { rt, storage := testhelpers.NewRuntimeInstance(t) - time := time.Date(2023, time.January, 2, 3, 4, 5, 6, time.UTC) + dateTime := time.Date(2023, time.January, 2, 3, 4, 5, 6, time.UTC) + time := dateTime.UnixMilli() - babeConfigurationBytes, err := rt.Exec("BabeApi_configuration", []byte{}) - assert.NoError(t, err) - - buffer := bytes.NewBuffer(babeConfigurationBytes) - - babeConfiguration, err := babetypes.DecodeConfiguration(buffer) - assert.NoError(t, err) - - slot := sc.U64(time.UnixMilli()) / babeConfiguration.SlotDuration - - // preRuntimeDigest := gossamertypes.PreRuntimeDigest{ - // ConsensusEngineID: aura.EngineId, - // Data: slot.Bytes(), - // } - // assert.NoError(t, digest.Add(preRuntimeDigest)) - - babeHeader := gossamertypes.NewBabeDigest() - err = babeHeader.SetValue(*gossamertypes.NewBabePrimaryPreDigest(0, uint64(slot), [32]byte{}, [64]byte{})) - assert.NoError(t, err) - data, err := scale.Marshal(babeHeader) - assert.NoError(t, err) - preDigest := gossamertypes.NewBABEPreRuntimeDigest(data) - - digest := gossamertypes.NewDigest() - err = digest.Add(*preDigest) - assert.NoError(t, err) + slot := testhelpers.GetBabeSlot(t, rt, uint64(time)) + digest := testhelpers.NewBabeDigest(t, slot) header := gossamertypes.NewHeader(testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), digest) diff --git a/runtime/templates/pos/runtime.go b/runtime/templates/pos/runtime.go index 746438a1..078b1f00 100644 --- a/runtime/templates/pos/runtime.go +++ b/runtime/templates/pos/runtime.go @@ -23,6 +23,7 @@ import ( "github.com/LimeChain/gosemble/frame/executive" "github.com/LimeChain/gosemble/frame/grandpa" "github.com/LimeChain/gosemble/frame/session" + "github.com/LimeChain/gosemble/frame/sudo" "github.com/LimeChain/gosemble/frame/system" sysExtensions "github.com/LimeChain/gosemble/frame/system/extensions" tm "github.com/LimeChain/gosemble/frame/testable" @@ -83,6 +84,7 @@ const ( GrandpaIndex BalancesIndex TxPaymentsIndex + SudoIndex TestableIndex = 255 ) @@ -120,7 +122,7 @@ var ( // Modules contains all the modules used by the runtime. modules = initializeModules() extra = newSignedExtra() - decoder = types.NewRuntimeDecoder(modules, extra, logger) + decoder = types.NewRuntimeDecoder(modules, extra, SudoIndex, logger) ) func initializeBlockDefaults() (primitives.BlockWeights, primitives.BlockLength) { @@ -214,6 +216,8 @@ func initializeModules() []primitives.Module { mdGenerator, ) + sudoModule := sudo.New(SudoIndex, sudo.NewConfig(DbWeight, systemModule), mdGenerator, logger) + testableModule := tm.New(TestableIndex, mdGenerator) return []primitives.Module{ @@ -224,6 +228,7 @@ func initializeModules() []primitives.Module { grandpaModule, balancesModule, tpmModule, + sudoModule, testableModule, } } diff --git a/runtime/templates/pos/system_apply_authorized_upgrade_test.go b/runtime/templates/pos/system_apply_authorized_upgrade_test.go deleted file mode 100644 index 7ebf06f3..00000000 --- a/runtime/templates/pos/system_apply_authorized_upgrade_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package main - -import ( - "bytes" - "os" - "testing" - - "github.com/ChainSafe/gossamer/lib/common" - "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" - "github.com/stretchr/testify/assert" -) - -func Test_ApplyAuthorizedUpgrade_DispatchOutcome(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - metadata := testhelpers.RuntimeMetadata(t, rt) - - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - testhelpers.InitializeBlock(t, rt, testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, testhelpers.BlockNumber) - - codeSpecVersion101, err := os.ReadFile(testhelpers.RuntimeWasmSpecVersion101) - assert.NoError(t, err) - codeHash := common.MustBlake2bHash(codeSpecVersion101) - - call, err := ctypes.NewCall(metadata, "System.authorize_upgrade", codeHash) - assert.NoError(t, err) - - extrinsic := ctypes.NewExtrinsic(call) - - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - err = extrinsic.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - extEnc := bytes.Buffer{} - encoder := cscale.NewEncoder(&extEnc) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.NoError(t, err) - - call, err = ctypes.NewCall(metadata, "System.apply_authorized_upgrade", codeSpecVersion101) - assert.NoError(t, err) - - extrinsic = ctypes.NewExtrinsic(call) - - o = ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(1), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - err = extrinsic.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - extEnc = bytes.Buffer{} - encoder = cscale.NewEncoder(&extEnc) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - res, err = rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.NoError(t, err) - - // Runtime version is updated - rt, storage = testhelpers.NewRuntimeInstanceFromCode(t, rt, (*storage).LoadCode()) - - runtimeVersion, err = rt.Version() - assert.NoError(t, err) - assert.Equal(t, runtimeVersion.SpecVersion, uint32(101)) - - assert.Equal(t, testhelpers.ApplyExtrinsicResultOutcome.Bytes(), res) -} diff --git a/runtime/templates/pos/system_authorize_upgrade_test.go b/runtime/templates/pos/system_authorize_upgrade_test.go deleted file mode 100644 index 8e22dcd0..00000000 --- a/runtime/templates/pos/system_authorize_upgrade_test.go +++ /dev/null @@ -1,75 +0,0 @@ -package main - -import ( - "bytes" - "os" - "testing" - - "github.com/ChainSafe/gossamer/lib/common" - sc "github.com/LimeChain/goscale" - "github.com/LimeChain/gosemble/frame/system" - "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" - "github.com/stretchr/testify/assert" -) - -func Test_AuthorizeUpgrade_DispatchOutcome(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - metadata := testhelpers.RuntimeMetadata(t, rt) - - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - testhelpers.InitializeBlock(t, rt, testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, testhelpers.BlockNumber) - - codeSpecVersion101, err := os.ReadFile(testhelpers.RuntimeWasmSpecVersion101) - assert.NoError(t, err) - codeHash := common.MustBlake2bHash(codeSpecVersion101) - - call, err := ctypes.NewCall(metadata, "System.authorize_upgrade", codeHash) - assert.NoError(t, err) - - extrinsic := ctypes.NewExtrinsic(call) - - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - err = extrinsic.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - extEnc := bytes.Buffer{} - encoder := cscale.NewEncoder(&extEnc) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.NoError(t, err) - - upgradeAuthorizationBytes := (*storage).Get(append(testhelpers.KeySystemHash, testhelpers.KeyAuthorizedUpgradeHash...)) - upgradeAuthorization, err := system.DecodeCodeUpgradeAuthorization(bytes.NewBuffer(upgradeAuthorizationBytes)) - assert.NoError(t, err) - - assert.Equal(t, codeHash.ToBytes(), sc.FixedSequenceU8ToBytes(upgradeAuthorization.CodeHash.FixedSequence)) - assert.Equal(t, sc.Bool(true), upgradeAuthorization.CheckVersion) - - // Event are emitted - buffer := &bytes.Buffer{} - buffer.Write((*storage).Get(append(testhelpers.KeySystemHash, testhelpers.KeyEventsHash...))) - - decodedCount, err := sc.DecodeCompact[sc.U32](buffer) - assert.NoError(t, err) - assert.Equal(t, sc.U32(3), decodedCount.Number) - - testhelpers.AssertEmittedSystemEvent(t, system.EventUpgradeAuthorized, buffer) - - assert.Equal(t, testhelpers.ApplyExtrinsicResultOutcome.Bytes(), res) -} diff --git a/runtime/templates/pos/system_kill_prefix_test.go b/runtime/templates/pos/system_kill_prefix_test.go deleted file mode 100644 index b81bfecf..00000000 --- a/runtime/templates/pos/system_kill_prefix_test.go +++ /dev/null @@ -1,71 +0,0 @@ -package main - -import ( - "bytes" - "testing" - - "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" - "github.com/stretchr/testify/assert" -) - -func Test_KillPrefix_DispatchOutcome(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - metadata := testhelpers.RuntimeMetadata(t, rt) - - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - testhelpers.InitializeBlock(t, rt, testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, testhelpers.BlockNumber) - - prefix := []byte("test") - limit := uint32(2) - - call, err := ctypes.NewCall(metadata, "System.kill_prefix", prefix, limit) - assert.NoError(t, err) - - extrinsic := ctypes.NewExtrinsic(call) - - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - err = extrinsic.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - extEnc := bytes.Buffer{} - encoder := cscale.NewEncoder(&extEnc) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - (*storage).Put([]byte("testkey111"), []byte("testvalue1")) - (*storage).Put([]byte("testkey222"), []byte("testvalue2")) - (*storage).Put([]byte("testkey333"), []byte("testvalue3")) - (*storage).Put([]byte("key444"), []byte("testvalue4")) - (*storage).Put([]byte("key555"), []byte("testvalue5")) - - assert.Equal(t, []byte("testvalue1"), (*storage).Get([]byte("testkey111"))) - assert.Equal(t, []byte("testvalue2"), (*storage).Get([]byte("testkey222"))) - assert.Equal(t, []byte("testvalue3"), (*storage).Get([]byte("testkey333"))) - assert.Equal(t, []byte("testvalue4"), (*storage).Get([]byte("key444"))) - assert.Equal(t, []byte("testvalue5"), (*storage).Get([]byte("key555"))) - - res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.NoError(t, err) - - assert.Equal(t, []byte(nil), (*storage).Get([]byte("testkey111"))) - assert.Equal(t, []byte(nil), (*storage).Get([]byte("testkey222"))) - assert.Equal(t, []byte("testvalue3"), (*storage).Get([]byte("testkey333"))) - assert.Equal(t, []byte("testvalue4"), (*storage).Get([]byte("key444"))) - assert.Equal(t, []byte("testvalue5"), (*storage).Get([]byte("key555"))) - - assert.Equal(t, testhelpers.ApplyExtrinsicResultOutcome.Bytes(), res) -} diff --git a/runtime/templates/pos/system_kill_storage_test.go b/runtime/templates/pos/system_kill_storage_test.go deleted file mode 100644 index d2d4d4ad..00000000 --- a/runtime/templates/pos/system_kill_storage_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package main - -import ( - "bytes" - "testing" - - "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" - "github.com/stretchr/testify/assert" -) - -func Test_KillStorage_DispatchOutcome(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - metadata := testhelpers.RuntimeMetadata(t, rt) - - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - testhelpers.InitializeBlock(t, rt, testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, testhelpers.BlockNumber) - - keys := [][]byte{ - []byte("testkey1"), - []byte("testkey2"), - } - - call, err := ctypes.NewCall(metadata, "System.kill_storage", keys) - assert.NoError(t, err) - - extrinsic := ctypes.NewExtrinsic(call) - - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - err = extrinsic.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - extEnc := bytes.Buffer{} - encoder := cscale.NewEncoder(&extEnc) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - (*storage).Put([]byte("testkey1"), []byte("testvalue1")) - (*storage).Put([]byte("testkey2"), []byte("testvalue2")) - (*storage).Put([]byte("testkey3"), []byte("testvalue3")) - - assert.Equal(t, "testvalue1", string((*storage).Get([]byte("testkey1")))) - assert.Equal(t, "testvalue2", string((*storage).Get([]byte("testkey2")))) - - res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.NoError(t, err) - - assert.Equal(t, []byte(nil), (*storage).Get([]byte("testkey1"))) - assert.Equal(t, []byte(nil), (*storage).Get([]byte("testkey2"))) - assert.Equal(t, "testvalue3", string((*storage).Get([]byte("testkey3")))) - - assert.Equal(t, testhelpers.ApplyExtrinsicResultOutcome.Bytes(), res) -} diff --git a/runtime/templates/pos/system_remark_test.go b/runtime/templates/pos/system_remark_test.go deleted file mode 100644 index 26cca752..00000000 --- a/runtime/templates/pos/system_remark_test.go +++ /dev/null @@ -1,96 +0,0 @@ -package main - -import ( - "bytes" - "math/big" - "testing" - - "github.com/ChainSafe/gossamer/lib/common" - "github.com/ChainSafe/gossamer/pkg/scale" - sc "github.com/LimeChain/goscale" - "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" - "github.com/stretchr/testify/assert" -) - -func Test_Remark_Signed_DispatchOutcome(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - metadata := testhelpers.RuntimeMetadata(t, rt) - - // Set Account Info - balance, e := big.NewInt(0).SetString("500000000000000", 10) - assert.True(t, e) - testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) - - testhelpers.InitializeBlock(t, rt, testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, testhelpers.BlockNumber) - - call, err := ctypes.NewCall(metadata, "System.remark", []byte{}) - assert.NoError(t, err) - - extrinsic := ctypes.NewExtrinsic(call) - - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - // Sign the transaction using Alice's default account - err = extrinsic.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - extEnc := bytes.Buffer{} - encoder := cscale.NewEncoder(&extEnc) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.NoError(t, err) - - currentExtrinsicIndex := sc.U32(1) - extrinsicIndexValue := (*storage).Get(testhelpers.KeyExtrinsicIndex) - assert.Equal(t, currentExtrinsicIndex.Bytes(), extrinsicIndexValue) - - keyExtrinsicDataPrefixHash := append(testhelpers.KeySystemHash, testhelpers.KeyExtrinsicDataHash...) - - prevExtrinsic := currentExtrinsicIndex - 1 - hashIndex, err := common.Twox64(prevExtrinsic.Bytes()) - assert.NoError(t, err) - - keyExtrinsic := append(keyExtrinsicDataPrefixHash, hashIndex...) - storageUxt := (*storage).Get(append(keyExtrinsic, prevExtrinsic.Bytes()...)) - - expectedExtrinsicDataStorage, err := scale.Marshal(extEnc.Bytes()) - assert.NoError(t, err) - - assert.Equal(t, expectedExtrinsicDataStorage, storageUxt) - assert.Equal(t, testhelpers.ApplyExtrinsicResultOutcome.Bytes(), res) -} - -func Test_Remark_Unsigned_DispatchOutcome(t *testing.T) { - rt, _ := testhelpers.NewRuntimeInstance(t) - metadata := testhelpers.RuntimeMetadata(t, rt) - - call, err := ctypes.NewCall(metadata, "System.remark", []byte{}) - assert.NoError(t, err) - - extrinsic := ctypes.NewExtrinsic(call) - - extEnc := bytes.Buffer{} - encoder := cscale.NewEncoder(&extEnc) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.NoError(t, err) - - assert.Equal(t, testhelpers.ApplyExtrinsicResultOutcome.Bytes(), res) -} diff --git a/runtime/templates/pos/system_remark_with_event_test.go b/runtime/templates/pos/system_remark_with_event_test.go deleted file mode 100644 index 2ef0b060..00000000 --- a/runtime/templates/pos/system_remark_with_event_test.go +++ /dev/null @@ -1,108 +0,0 @@ -package main - -import ( - "bytes" - "math/big" - "testing" - - sc "github.com/LimeChain/goscale" - "github.com/LimeChain/gosemble/frame/balances" - "github.com/LimeChain/gosemble/frame/system" - "github.com/LimeChain/gosemble/frame/transaction_payment" - "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" - "github.com/stretchr/testify/assert" -) - -func Test_Remark_With_Event_Signed_DispatchOutcome(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - metadata := testhelpers.RuntimeMetadata(t, rt) - - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - // Set account info - balance, e := big.NewInt(0).SetString("500000000000000", 10) - assert.True(t, e) - testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) - - testhelpers.InitializeBlock(t, rt, testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, testhelpers.BlockNumber) - - remarkMsg := sc.BytesToFixedSequenceU8([]byte("ngmi")) - call, err := ctypes.NewCall(metadata, "System.remark_with_event", remarkMsg.Bytes()) - assert.NoError(t, err) - - extrinsic := ctypes.NewExtrinsic(call) - - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - err = extrinsic.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - extEnc := bytes.Buffer{} - encoder := cscale.NewEncoder(&extEnc) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.NoError(t, err) - - // Events are emitted - buffer := &bytes.Buffer{} - - buffer.Write((*storage).Get(append(testhelpers.KeySystemHash, testhelpers.KeyEventCountHash...))) - storageEventCount, err := sc.DecodeU32(buffer) - assert.NoError(t, err) - assert.Equal(t, sc.U32(4), storageEventCount) - - buffer.Reset() - buffer.Write((*storage).Get(append(testhelpers.KeySystemHash, testhelpers.KeyEventsHash...))) - - decodedCount, err := sc.DecodeCompact[sc.U32](buffer) - assert.NoError(t, err) - assert.Equal(t, decodedCount.Number, storageEventCount) - - // balances withdraw event - testhelpers.AssertEmittedBalancesEvent(t, balances.EventWithdraw, buffer) - - // system remarked event - testhelpers.AssertEmittedSystemEvent(t, system.EventRemarked, buffer) - - // txpayment transaction fee paid event - testhelpers.AssertEmittedTransactionPaymentEvent(t, transaction_payment.EventTransactionFeePaid, buffer) - - // system extrinsic success event - testhelpers.AssertEmittedSystemEvent(t, system.EventExtrinsicSuccess, buffer) - - assert.Equal(t, testhelpers.ApplyExtrinsicResultOutcome.Bytes(), res) -} - -func Test_Remark_With_Event_Unsigned_DispatchOutcome(t *testing.T) { - rt, _ := testhelpers.NewRuntimeInstance(t) - metadata := testhelpers.RuntimeMetadata(t, rt) - - call, err := ctypes.NewCall(metadata, "System.remark_with_event", []byte{}) - assert.NoError(t, err) - - extrinsic := ctypes.NewExtrinsic(call) - - extEnc := bytes.Buffer{} - encoder := cscale.NewEncoder(&extEnc) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.NoError(t, err) - - assert.Equal(t, testhelpers.ApplyExtrinsicResultBadOriginErr.Bytes(), res) -} diff --git a/runtime/templates/pos/system_set_code_test.go b/runtime/templates/pos/system_set_code_test.go index 457a8f94..ba627a1a 100644 --- a/runtime/templates/pos/system_set_code_test.go +++ b/runtime/templates/pos/system_set_code_test.go @@ -8,10 +8,6 @@ import ( gossamertypes "github.com/ChainSafe/gossamer/dot/types" "github.com/ChainSafe/gossamer/pkg/scale" sc "github.com/LimeChain/goscale" - "github.com/LimeChain/gosemble/frame/aura" - "github.com/LimeChain/gosemble/frame/system" - "github.com/LimeChain/gosemble/frame/transaction_payment" - "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" @@ -19,107 +15,20 @@ import ( "github.com/stretchr/testify/assert" ) -func Test_SetCode_Success(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - metadata := testhelpers.RuntimeMetadata(t, rt) - - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - testhelpers.InitializeBlock(t, rt, testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, testhelpers.BlockNumber) - - codeSpecVersion101, err := os.ReadFile(testhelpers.RuntimeWasmSpecVersion101) - assert.NoError(t, err) - - call, err := ctypes.NewCall(metadata, "System.set_code", codeSpecVersion101) - assert.NoError(t, err) - - extrinsic := ctypes.NewExtrinsic(call) - - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - err = extrinsic.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - extEnc := bytes.Buffer{} - encoder := cscale.NewEncoder(&extEnc) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.NoError(t, err) - - // Code is written to storage - assert.Equal(t, codeSpecVersion101, (*storage).LoadCode()) - - // Runtime environment upgraded digest item is logged - testhelpers.AssertStorageDigestItem(t, storage, types.DigestItemRuntimeEnvironmentUpgraded) - - // Events are emitted - buffer := &bytes.Buffer{} - - testhelpers.AssertStorageSystemEventCount(t, storage, uint32(3)) - - buffer.Write((*storage).Get(append(testhelpers.KeySystemHash, testhelpers.KeyEventsHash...))) - decodedCount, err := sc.DecodeCompact[sc.U32](buffer) - assert.NoError(t, err) - assert.Equal(t, uint32(decodedCount.Number.(sc.U32)), uint32(3)) - - // Event system code updated - testhelpers.AssertEmittedSystemEvent(t, system.EventCodeUpdated, buffer) - - // Event txpayment transaction fee paid - testhelpers.AssertEmittedTransactionPaymentEvent(t, transaction_payment.EventTransactionFeePaid, buffer) - - // Event system extrinsic success - testhelpers.AssertEmittedSystemEvent(t, system.EventExtrinsicSuccess, buffer) - - // Runtime version is updated - rt, storage = testhelpers.NewRuntimeInstanceFromCode(t, rt, (*storage).LoadCode()) - - runtimeVersion, err = rt.Version() - assert.NoError(t, err) - assert.Equal(t, runtimeVersion.SpecVersion, uint32(101)) - - assert.Equal(t, testhelpers.ApplyExtrinsicResultOutcome.Bytes(), res) -} - func Test_Block_Execution_After_Code_Upgrade(t *testing.T) { - t.Skip() rt, storage := testhelpers.NewRuntimeInstance(t) metadata := testhelpers.RuntimeMetadata(t, rt) runtimeVersion, err := rt.Version() assert.NoError(t, err) - bytesSlotDuration, err := rt.Exec("AuraApi_slot_duration", []byte{}) - assert.NoError(t, err) - - buffer := &bytes.Buffer{} - buffer.Write(bytesSlotDuration) - - slotDuration, err := sc.DecodeU64(buffer) - assert.Nil(t, err) - buffer.Reset() - - slot := sc.U64(dateTime.UnixMilli()) / slotDuration + time := dateTime.UnixMilli() - preRuntimeDigest := gossamertypes.PreRuntimeDigest{ - ConsensusEngineID: aura.EngineId, - Data: slot.Bytes(), - } - digest := gossamertypes.NewDigest() - assert.NoError(t, digest.Add(preRuntimeDigest)) + slot := testhelpers.GetBabeSlot(t, rt, uint64(time)) + digest := testhelpers.NewBabeDigest(t, slot) header := gossamertypes.NewHeader(testhelpers.ParentHash, storageRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), digest) + encodedHeader, err := scale.Marshal(*header) assert.NoError(t, err) @@ -137,6 +46,7 @@ func Test_Block_Execution_After_Code_Upgrade(t *testing.T) { assert.NoError(t, err) assert.NotNil(t, inherentExt) + buffer := bytes.NewBuffer([]byte{}) buffer.Write([]byte{inherentExt[0]}) totalInherents, err := sc.DecodeCompact[sc.U128](buffer) diff --git a/runtime/templates/pos/system_set_code_without_checks_test.go b/runtime/templates/pos/system_set_code_without_checks_test.go deleted file mode 100644 index 21d2b848..00000000 --- a/runtime/templates/pos/system_set_code_without_checks_test.go +++ /dev/null @@ -1,92 +0,0 @@ -package main - -import ( - "bytes" - "os" - "testing" - - sc "github.com/LimeChain/goscale" - "github.com/LimeChain/gosemble/frame/system" - "github.com/LimeChain/gosemble/frame/transaction_payment" - "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" - "github.com/stretchr/testify/assert" -) - -func Test_SetCodeWithoutChecks_DispatchOutcome(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - metadata := testhelpers.RuntimeMetadata(t, rt) - - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - testhelpers.InitializeBlock(t, rt, testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, testhelpers.BlockNumber) - - codeSpecVersion101, err := os.ReadFile(testhelpers.RuntimeWasmSpecVersion101) - assert.NoError(t, err) - - call, err := ctypes.NewCall(metadata, "System.set_code_without_checks", codeSpecVersion101) - assert.NoError(t, err) - - extrinsic := ctypes.NewExtrinsic(call) - - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - err = extrinsic.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - extEnc := bytes.Buffer{} - encoder := cscale.NewEncoder(&extEnc) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.NoError(t, err) - - // Code is written to storage - assert.Equal(t, codeSpecVersion101, (*storage).LoadCode()) - - // Runtime environment upgraded digest item is logged - testhelpers.AssertStorageDigestItem(t, storage, types.DigestItemRuntimeEnvironmentUpgraded) - - // Events are emitted - buffer := &bytes.Buffer{} - - testhelpers.AssertStorageSystemEventCount(t, storage, uint32(3)) - - buffer.Reset() - buffer.Write((*storage).Get(append(testhelpers.KeySystemHash, testhelpers.KeyEventsHash...))) - - decodedCount, err := sc.DecodeCompact[sc.U32](buffer) - assert.NoError(t, err) - assert.Equal(t, uint32(decodedCount.Number.(sc.U32)), uint32(3)) - - // Event system code updated - testhelpers.AssertEmittedSystemEvent(t, system.EventCodeUpdated, buffer) - - // Event txpayment transaction fee paid - testhelpers.AssertEmittedTransactionPaymentEvent(t, transaction_payment.EventTransactionFeePaid, buffer) - - // Event system extrinsic success - testhelpers.AssertEmittedSystemEvent(t, system.EventExtrinsicSuccess, buffer) - - // Runtime version is updated - rt, storage = testhelpers.NewRuntimeInstanceFromCode(t, rt, (*storage).LoadCode()) - - runtimeVersion, err = rt.Version() - assert.NoError(t, err) - assert.Equal(t, runtimeVersion.SpecVersion, uint32(101)) - - assert.Equal(t, testhelpers.ApplyExtrinsicResultOutcome.Bytes(), res) -} diff --git a/runtime/templates/pos/system_set_heap_pages_test.go b/runtime/templates/pos/system_set_heap_pages_test.go deleted file mode 100644 index e8f4714f..00000000 --- a/runtime/templates/pos/system_set_heap_pages_test.go +++ /dev/null @@ -1,79 +0,0 @@ -package main - -import ( - "bytes" - "testing" - - gossamertypes "github.com/ChainSafe/gossamer/dot/types" - "github.com/ChainSafe/gossamer/pkg/scale" - "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" - "github.com/stretchr/testify/assert" -) - -var ( - pages = uint64(5) -) - -var ( - expectedHeapPagesStorage = uint64(0) -) - -func Test_SetHeapPages_DispatchOutcome(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - metadata := testhelpers.RuntimeMetadata(t, rt) - - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - testhelpers.InitializeBlock(t, rt, testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, testhelpers.BlockNumber) - - call, err := ctypes.NewCall(metadata, "System.set_heap_pages", pages) - assert.NoError(t, err) - - extrinsic := ctypes.NewExtrinsic(call) - - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - err = extrinsic.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - extEnc := bytes.Buffer{} - encoder := cscale.NewEncoder(&extEnc) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - heapPagesStorage := uint64(0) - scale.Unmarshal((*storage).Get(testhelpers.KeyHeapPages), &heapPagesStorage) - assert.Equal(t, expectedHeapPagesStorage, heapPagesStorage) - - digestStorage := gossamertypes.NewDigest() - scale.Unmarshal((*storage).Get(append(testhelpers.KeySystemHash, testhelpers.KeyDigestHash...)[:]), &digestStorage) - assert.Equal(t, gossamertypes.Digest(nil), digestStorage) - - res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.NoError(t, err) - - heapPagesStorage = uint64(0) - scale.Unmarshal((*storage).Get(testhelpers.KeyHeapPages), &heapPagesStorage) - expectedHeapPagesStorage = pages - assert.Equal(t, expectedHeapPagesStorage, heapPagesStorage) - - digestStorage = gossamertypes.NewDigest() - scale.Unmarshal((*storage).Get(append(testhelpers.KeySystemHash, testhelpers.KeyDigestHash...)[:]), &digestStorage) - expectedDigestStorage := gossamertypes.Digest(nil) - expectedDigestStorage.Add(gossamertypes.RuntimeEnvironmentUpdated{}) - assert.Equal(t, expectedDigestStorage, digestStorage) - - assert.Equal(t, testhelpers.ApplyExtrinsicResultOutcome.Bytes(), res) -} diff --git a/runtime/templates/pos/system_set_storage_test.go b/runtime/templates/pos/system_set_storage_test.go deleted file mode 100644 index 1dcbe336..00000000 --- a/runtime/templates/pos/system_set_storage_test.go +++ /dev/null @@ -1,73 +0,0 @@ -package main - -import ( - "bytes" - "testing" - - "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" - "github.com/stretchr/testify/assert" -) - -func Test_SetStorage_DispatchOutcome(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - metadata := testhelpers.RuntimeMetadata(t, rt) - - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - // Initialize block - testhelpers.InitializeBlock(t, rt, testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, testhelpers.BlockNumber) - - items := []struct { - Key []byte - Value []byte - }{ - { - Key: []byte("testkey1"), - Value: []byte("testvalue1"), - }, - { - Key: []byte("testkey2"), - Value: []byte("testvalue2"), - }, - } - - call, err := ctypes.NewCall(metadata, "System.set_storage", items) - assert.NoError(t, err) - - extrinsic := ctypes.NewExtrinsic(call) - - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - // Sign the extrinsic - err = extrinsic.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - extEnc := bytes.Buffer{} - encoder := cscale.NewEncoder(&extEnc) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - assert.Equal(t, []byte(nil), (*storage).Get([]byte("testkey1"))) - assert.Equal(t, []byte(nil), (*storage).Get([]byte("testkey2"))) - - res, err := rt.Exec("BlockBuilder_apply_extrinsic", extEnc.Bytes()) - assert.NoError(t, err) - - assert.Equal(t, []byte("testvalue1"), (*storage).Get([]byte("testkey1"))) - assert.Equal(t, []byte("testvalue2"), (*storage).Get([]byte("testkey2"))) - assert.Equal(t, []byte(nil), (*storage).Get([]byte("testkey3"))) - - assert.Equal(t, testhelpers.ApplyExtrinsicResultOutcome.Bytes(), res) -} diff --git a/runtime/templates/pos/transaction_payment_test.go b/runtime/templates/pos/transaction_payment_test.go deleted file mode 100644 index a6afda6a..00000000 --- a/runtime/templates/pos/transaction_payment_test.go +++ /dev/null @@ -1,271 +0,0 @@ -package main - -import ( - "bytes" - "testing" - - "github.com/LimeChain/gosemble/frame/transaction_payment/types" - primitives "github.com/LimeChain/gosemble/primitives/types" - "github.com/LimeChain/gosemble/testhelpers" - - sc "github.com/LimeChain/goscale" - - 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" - "github.com/stretchr/testify/assert" -) - -func Test_TransactionPaymentApi_QueryInfo_Signed_Success(t *testing.T) { - rt, _ := testhelpers.NewRuntimeInstance(t) - - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - metadata := testhelpers.RuntimeMetadata(t, rt) - - call, err := ctypes.NewCall(metadata, "System.remark", []byte{}) - assert.NoError(t, err) - - extrinsic := ctypes.NewExtrinsic(call) - - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - // Sign the transaction using Alice's default account - err = extrinsic.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - buffer := &bytes.Buffer{} - encoder := cscale.NewEncoder(buffer) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - err = sc.U32(buffer.Len()).Encode(buffer) - assert.NoError(t, err) - - bytesRuntimeDispatchInfo, err := rt.Exec("TransactionPaymentApi_query_info", buffer.Bytes()) - assert.NoError(t, err) - - buffer.Reset() - buffer.Write(bytesRuntimeDispatchInfo) - - rdi, err := primitives.DecodeRuntimeDispatchInfo(buffer) - assert.Nil(t, err) - - expectedRdi := primitives.RuntimeDispatchInfo{ - Weight: primitives.WeightFromParts(68_363_334, 0), - Class: primitives.NewDispatchClassNormal(), - PartialFee: sc.NewU128(4_288_948_107), - } - - assert.Equal(t, expectedRdi, rdi) -} - -func Test_TransactionPaymentApi_QueryInfo_Unsigned_Success(t *testing.T) { - rt, _ := testhelpers.NewRuntimeInstance(t) - - metadata := testhelpers.RuntimeMetadata(t, rt) - - call, err := ctypes.NewCall(metadata, "System.remark", []byte{}) - assert.NoError(t, err) - - extrinsic := ctypes.NewExtrinsic(call) - - buffer := &bytes.Buffer{} - encoder := cscale.NewEncoder(buffer) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - err = sc.U32(buffer.Len()).Encode(buffer) - assert.NoError(t, err) - - bytesRuntimeDispatchInfo, err := rt.Exec("TransactionPaymentApi_query_info", buffer.Bytes()) - assert.NoError(t, err) - - buffer.Reset() - buffer.Write(bytesRuntimeDispatchInfo) - - rdi, err := primitives.DecodeRuntimeDispatchInfo(buffer) - assert.Nil(t, err) - - expectedRdi := primitives.RuntimeDispatchInfo{ - Weight: primitives.WeightFromParts(68_363_334, 0), - Class: primitives.NewDispatchClassNormal(), - PartialFee: sc.NewU128(0), - } - - assert.Equal(t, expectedRdi, rdi) -} - -func Test_TransactionPaymentApi_QueryFeeDetails_Signed_Success(t *testing.T) { - rt, _ := testhelpers.NewRuntimeInstance(t) - - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - metadata := testhelpers.RuntimeMetadata(t, rt) - - call, err := ctypes.NewCall(metadata, "System.remark", []byte{}) - assert.NoError(t, err) - - extrinsic := ctypes.NewExtrinsic(call) - - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - // Sign the transaction using Alice's default account - err = extrinsic.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - buffer := &bytes.Buffer{} - encoder := cscale.NewEncoder(buffer) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - err = sc.U32(buffer.Len()).Encode(buffer) - assert.NoError(t, err) - - bytesFeeDetails, err := rt.Exec("TransactionPaymentApi_query_fee_details", buffer.Bytes()) - assert.NoError(t, err) - - buffer.Reset() - buffer.Write(bytesFeeDetails) - - fd, err := types.DecodeFeeDetails(buffer) - assert.Nil(t, err) - - expectedFd := types.FeeDetails{ - InclusionFee: sc.NewOption[types.InclusionFee]( - types.NewInclusionFee( - sc.NewU128(4_288_948_000), - sc.NewU128(107), - sc.NewU128(0), - )), - } - - assert.Equal(t, expectedFd, fd) -} - -func Test_TransactionPaymentApi_QueryFeeDetails_Unsigned_Success(t *testing.T) { - rt, _ := testhelpers.NewRuntimeInstance(t) - metadata := testhelpers.RuntimeMetadata(t, rt) - - call, err := ctypes.NewCall(metadata, "System.remark", []byte{}) - assert.NoError(t, err) - - extrinsic := ctypes.NewExtrinsic(call) - - buffer := &bytes.Buffer{} - encoder := cscale.NewEncoder(buffer) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - err = sc.U32(buffer.Len()).Encode(buffer) - assert.NoError(t, err) - - bytesFeeDetails, err := rt.Exec("TransactionPaymentApi_query_fee_details", buffer.Bytes()) - assert.NoError(t, err) - - buffer.Reset() - buffer.Write(bytesFeeDetails) - - fd, err := types.DecodeFeeDetails(buffer) - assert.Nil(t, err) - - expectedFd := types.FeeDetails{ - InclusionFee: sc.NewOption[types.InclusionFee](nil), - } - - assert.Equal(t, expectedFd, fd) -} - -func Test_TransactionPaymentCallApi_QueryCallInfo_Success(t *testing.T) { - rt, _ := testhelpers.NewRuntimeInstance(t) - metadata := testhelpers.RuntimeMetadata(t, rt) - - call, err := ctypes.NewCall(metadata, "System.remark", []byte{}) - assert.NoError(t, err) - - buffer := &bytes.Buffer{} - encoder := cscale.NewEncoder(buffer) - err = call.CallIndex.Encode(*encoder) - assert.NoError(t, err) - - err = call.Args.Encode(*encoder) - assert.NoError(t, err) - - err = sc.U32(buffer.Len()).Encode(buffer) - assert.NoError(t, err) - - bytesRuntimeDispatchInfo, err := rt.Exec("TransactionPaymentCallApi_query_call_info", buffer.Bytes()) - assert.NoError(t, err) - - buffer.Reset() - buffer.Write(bytesRuntimeDispatchInfo) - - rdi, err := primitives.DecodeRuntimeDispatchInfo(buffer) - assert.Nil(t, err) - - expectedRdi := primitives.RuntimeDispatchInfo{ - Weight: primitives.WeightFromParts(68_363_334, 0), - Class: primitives.NewDispatchClassNormal(), - PartialFee: sc.NewU128(4_288_948_003), - } - - assert.Equal(t, expectedRdi, rdi) -} - -func Test_TransactionPaymentCallApi_QueryCallFeeDetails_Success(t *testing.T) { - rt, _ := testhelpers.NewRuntimeInstance(t) - metadata := testhelpers.RuntimeMetadata(t, rt) - - call, err := ctypes.NewCall(metadata, "System.remark", []byte{}) - assert.NoError(t, err) - - buffer := &bytes.Buffer{} - encoder := cscale.NewEncoder(buffer) - err = call.CallIndex.Encode(*encoder) - assert.NoError(t, err) - - err = call.Args.Encode(*encoder) - assert.NoError(t, err) - - err = sc.U32(buffer.Len()).Encode(buffer) - assert.NoError(t, err) - - bytesFeeDetails, err := rt.Exec("TransactionPaymentCallApi_query_call_fee_details", buffer.Bytes()) - assert.NoError(t, err) - - buffer.Reset() - buffer.Write(bytesFeeDetails) - - fd, err := types.DecodeFeeDetails(buffer) - assert.Nil(t, err) - - expectedFd := types.FeeDetails{ - InclusionFee: sc.NewOption[types.InclusionFee]( - types.NewInclusionFee( - sc.NewU128(4_288_948_000), - sc.NewU128(3), - sc.NewU128(0), - )), - } - - assert.Equal(t, expectedFd, fd) -} diff --git a/runtime/templates/pos/transactional_test.go b/runtime/templates/pos/transactional_test.go deleted file mode 100644 index 731cf248..00000000 --- a/runtime/templates/pos/transactional_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package main - -import ( - "bytes" - "testing" - - "github.com/LimeChain/gosemble/testhelpers" - cscale "github.com/centrifuge/go-substrate-rpc-client/v4/scale" - ctypes "github.com/centrifuge/go-substrate-rpc-client/v4/types" - - "github.com/stretchr/testify/assert" -) - -// TODO: in the test case "Commit_Then_Rollback" the host -// panics with "fatal error: exitsyscall: syscall frame is no longer valid" - -func Test_Storage_Layer_Rollback_Then_Commit(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - - metadata := testhelpers.RuntimeMetadata(t, rt) - - call, err := ctypes.NewCall(metadata, "Testable.test", []byte{}) - assert.NoError(t, err) - - extrinsic := ctypes.NewExtrinsic(call) - - buffer := &bytes.Buffer{} - encoder := cscale.NewEncoder(buffer) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - _, err = rt.Exec("BlockBuilder_apply_extrinsic", buffer.Bytes()) - assert.NoError(t, err) - - assert.Equal(t, []byte{1}, (*storage).Get([]byte("testvalue"))) -} diff --git a/runtime/templates/pos/validate_transaction_test.go b/runtime/templates/pos/validate_transaction_test.go deleted file mode 100644 index c16de4ae..00000000 --- a/runtime/templates/pos/validate_transaction_test.go +++ /dev/null @@ -1,470 +0,0 @@ -package main - -import ( - "bytes" - "math/big" - "os" - "testing" - "time" - - gossamertypes "github.com/ChainSafe/gossamer/dot/types" - "github.com/ChainSafe/gossamer/pkg/scale" - sc "github.com/LimeChain/goscale" - "github.com/LimeChain/gosemble/constants" - 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" - "github.com/stretchr/testify/assert" -) - -func Test_ValidateTransaction_Success(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - metadata := testhelpers.RuntimeMetadata(t, rt) - - // Set Account Info balance otherwise tx payment check will fail. - balance, e := big.NewInt(0).SetString("500000000000000", 10) - assert.True(t, e) - - testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) - - digest := gossamertypes.NewDigest() - - header := gossamertypes.NewHeader(testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), digest) - encodedHeader, err := scale.Marshal(*header) - assert.NoError(t, err) - - _, err = rt.Exec("Core_initialize_block", encodedHeader) - assert.NoError(t, err) - - call, err := ctypes.NewCall(metadata, "System.remark", []byte{}) - assert.NoError(t, err) - - extrinsic := ctypes.NewExtrinsic(call) - - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - // Sign the transaction using Alice's default account - err = extrinsic.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - txSource := primitives.NewTransactionSourceExternal() - blockHash := sc.BytesToFixedSequenceU8(testhelpers.ParentHash.ToBytes()) - - buffer := &bytes.Buffer{} - txSource.Encode(buffer) - - encoder := cscale.NewEncoder(buffer) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - blockHash.Encode(buffer) - - encTransactionValidityResult, err := rt.Exec("TaggedTransactionQueue_validate_transaction", buffer.Bytes()) - assert.NoError(t, err) - - buffer.Reset() - buffer.Write(encTransactionValidityResult) - transactionValidityResult, err := primitives.DecodeTransactionValidityResult(buffer) - assert.Nil(t, err) - - assert.Equal(t, true, transactionValidityResult.IsValidTransaction()) -} - -func Test_ValidateTransaction_InvalidModuleFunctionIndex(t *testing.T) { - rt, _ := testhelpers.NewRuntimeInstance(t) - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - metadata := testhelpers.RuntimeMetadata(t, rt) - - digest := gossamertypes.NewDigest() - - header := gossamertypes.NewHeader(testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), digest) - encodedHeader, err := scale.Marshal(*header) - assert.NoError(t, err) - - _, err = rt.Exec("Core_initialize_block", encodedHeader) - assert.NoError(t, err) - - call, err := ctypes.NewCall(metadata, "System.remark", []byte{}) - assert.NoError(t, err) - - // Change function/section index - call.CallIndex.SectionIndex = 65 - - extrinsic := ctypes.NewExtrinsic(call) - - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - // Sign the transaction using Alice's default account - err = extrinsic.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - txSource := primitives.NewTransactionSourceExternal() - blockHash := sc.BytesToFixedSequenceU8(testhelpers.ParentHash.ToBytes()) - - buffer := &bytes.Buffer{} - txSource.Encode(buffer) - - encoder := cscale.NewEncoder(buffer) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - blockHash.Encode(buffer) - - _, err = rt.Exec("TaggedTransactionQueue_validate_transaction", buffer.Bytes()) - assert.Error(t, err) -} - -func Test_ValidateTransaction_StaleError_InvalidNonce(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - metadata := testhelpers.RuntimeMetadata(t, rt) - - testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, big.NewInt(5), 3) - - digest := gossamertypes.NewDigest() - - header := gossamertypes.NewHeader(testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), digest) - encodedHeader, err := scale.Marshal(*header) - assert.NoError(t, err) - - _, err = rt.Exec("Core_initialize_block", encodedHeader) - assert.NoError(t, err) - - call, err := ctypes.NewCall(metadata, "System.remark", []byte{}) - assert.NoError(t, err) - - extrinsic := ctypes.NewExtrinsic(call) - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(2), // Invalid nonce - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - // Sign the transaction using Alice's default account - err = extrinsic.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - txSource := primitives.NewTransactionSourceExternal() - blockHash := sc.BytesToFixedSequenceU8(testhelpers.ParentHash.ToBytes()) - - buffer := &bytes.Buffer{} - txSource.Encode(buffer) - - encoder := cscale.NewEncoder(buffer) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - blockHash.Encode(buffer) - - encTransactionValidityResult, err := rt.Exec("TaggedTransactionQueue_validate_transaction", buffer.Bytes()) - assert.NoError(t, err) - - buffer.Reset() - buffer.Write(encTransactionValidityResult) - transactionValidityResult, err := primitives.DecodeTransactionValidityResult(buffer) - assert.Nil(t, err) - - assert.Equal(t, testhelpers.TransactionValidityResultStaleErr, transactionValidityResult) -} - -func Test_ValidateTransaction_ExhaustsResourcesError(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - metadata := testhelpers.RuntimeMetadata(t, rt) - - testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, big.NewInt(5), 0) - - digest := gossamertypes.NewDigest() - - header := gossamertypes.NewHeader(testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), digest) - encodedHeader, err := scale.Marshal(*header) - assert.NoError(t, err) - - _, err = rt.Exec("Core_initialize_block", encodedHeader) - assert.NoError(t, err) - - // Append long args - args := make([]byte, constants.FiveMbPerBlockPerExtrinsic) - - call, err := ctypes.NewCall(metadata, "System.remark", args) - assert.NoError(t, err) - - extrinsic := ctypes.NewExtrinsic(call) - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{IsImmortalEra: true}, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - // Sign the transaction using Alice's default account - err = extrinsic.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - txSource := primitives.NewTransactionSourceExternal() - blockHash := sc.BytesToFixedSequenceU8(testhelpers.ParentHash.ToBytes()) - - buffer := &bytes.Buffer{} - txSource.Encode(buffer) - - encoder := cscale.NewEncoder(buffer) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - blockHash.Encode(buffer) - - encTransactionValidityResult, err := rt.Exec("TaggedTransactionQueue_validate_transaction", buffer.Bytes()) - assert.NoError(t, err) - - buffer.Reset() - buffer.Write(encTransactionValidityResult) - transactionValidityResult, err := primitives.DecodeTransactionValidityResult(buffer) - assert.Nil(t, err) - - assert.Equal(t, testhelpers.TransactionValidityResultExhaustsResourcesErr, transactionValidityResult) -} - -func Test_ValidateTransaction_Era(t *testing.T) { - rt, storage := testhelpers.NewRuntimeInstance(t) - runtimeVersion, err := rt.Version() - assert.NoError(t, err) - - metadata := testhelpers.RuntimeMetadata(t, rt) - - // Set Account info due to check tx payment - balance, e := big.NewInt(0).SetString("500000000000000", 10) - assert.True(t, e) - - testhelpers.SetStorageAccountInfo(t, storage, signature.TestKeyringPairAlice.PublicKey, balance, 0) - - digest := gossamertypes.NewDigest() - - header := gossamertypes.NewHeader(testhelpers.ParentHash, testhelpers.StateRoot, testhelpers.ExtrinsicsRoot, uint(testhelpers.BlockNumber), digest) - encodedHeader, err := scale.Marshal(*header) - assert.NoError(t, err) - - _, err = rt.Exec("Core_initialize_block", encodedHeader) - assert.NoError(t, err) - - // set the block number - blockNumber := uint64(16) - blockNumberBytes, err := scale.Marshal(blockNumber) - assert.NoError(t, err) - err = (*storage).Put(append(testhelpers.KeySystemHash, testhelpers.KeyNumberHash...), blockNumberBytes) - assert.NoError(t, err) - - call, err := ctypes.NewCall(metadata, "System.remark", []byte{}) - assert.NoError(t, err) - - extrinsic := ctypes.NewExtrinsic(call) - - o := ctypes.SignatureOptions{ - BlockHash: ctypes.Hash(testhelpers.ParentHash), - Era: ctypes.ExtrinsicEra{ - IsMortalEra: true, - AsMortalEra: ctypes.MortalEra{ - First: 3, // Matched with period 16, current 256 - Second: 0, - }, - }, - GenesisHash: ctypes.Hash(testhelpers.ParentHash), - Nonce: ctypes.NewUCompactFromUInt(0), - SpecVersion: ctypes.U32(runtimeVersion.SpecVersion), - Tip: ctypes.NewUCompactFromUInt(0), - TransactionVersion: ctypes.U32(runtimeVersion.TransactionVersion), - } - - // Sign the transaction using Alice's default account - err = extrinsic.Sign(signature.TestKeyringPairAlice, o) - assert.NoError(t, err) - - txSource := primitives.NewTransactionSourceExternal() - blockHash := sc.BytesToFixedSequenceU8(testhelpers.ParentHash.ToBytes()) - - buffer := &bytes.Buffer{} - txSource.Encode(buffer) - - encoder := cscale.NewEncoder(buffer) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - blockHash.Encode(buffer) - - encTransactionValidityResult, err := rt.Exec("TaggedTransactionQueue_validate_transaction", buffer.Bytes()) - assert.NoError(t, err) - - buffer.Reset() - buffer.Write(encTransactionValidityResult) - transactionValidityResult, err := primitives.DecodeTransactionValidityResult(buffer) - assert.Nil(t, err) - - assert.Equal(t, true, transactionValidityResult.IsValidTransaction()) - - validTransaction, err := transactionValidityResult.AsValidTransaction() - assert.NoError(t, err) - assert.Equal(t, sc.U64(15), validTransaction.Longevity) -} - -func Test_ValidateTransaction_NoUnsignedValidator(t *testing.T) { - rt, _ := testhelpers.NewRuntimeInstance(t) - metadata := testhelpers.RuntimeMetadata(t, rt) - - txSource := primitives.NewTransactionSourceExternal() - blockHash := sc.BytesToFixedSequenceU8(testhelpers.ParentHash.ToBytes()) - - alice, err := ctypes.NewMultiAddressFromAccountID(signature.TestKeyringPairAlice.PublicKey) - assert.NoError(t, err) - - amount := ctypes.NewUCompactFromUInt(constants.Dollar) - - var tests = []struct { - callName string - args []any - }{ - { - callName: "System.remark", - args: []any{[]byte{}}, - }, - { - callName: "Balances.transfer", - args: []any{alice, amount}, - }, - { - callName: "Balances.set_balance", - args: []any{alice, amount, amount}, - }, - { - callName: "Balances.force_transfer", - args: []any{alice, alice, amount}, - }, - { - callName: "Balances.transfer_keep_alive", - args: []any{alice, amount}, - }, - { - callName: "Balances.transfer_all", - args: []any{alice, ctypes.NewBool(false)}, - }, - { - callName: "Balances.force_free", - args: []any{alice, ctypes.NewU128(*big.NewInt(amount.Int64()))}, - }, - } - - for _, test := range tests { - t.Run(test.callName, func(t *testing.T) { - call, err := ctypes.NewCall(metadata, test.callName, test.args...) - - extrinsic := ctypes.NewExtrinsic(call) - - buffer := &bytes.Buffer{} - txSource.Encode(buffer) - - encoder := cscale.NewEncoder(buffer) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - blockHash.Encode(buffer) - - res, err := rt.Exec("TaggedTransactionQueue_validate_transaction", buffer.Bytes()) - - assert.NoError(t, err) - assert.Equal(t, testhelpers.TransactionValidityResultNoUnsignedValidatorErr.Bytes(), res) - }) - } -} - -func Test_ValidateTransaction_MandatoryValidation_Timestamp(t *testing.T) { - rt, _ := testhelpers.NewRuntimeInstance(t) - - idata := gossamertypes.NewInherentData() - time := time.Now().UnixMilli() - - err := idata.SetInherent(gossamertypes.Timstap0, uint64(time)) - assert.NoError(t, err) - - ienc, err := idata.Encode() - assert.NoError(t, err) - inherentExt, err := rt.Exec("BlockBuilder_inherent_extrinsics", ienc) - assert.NoError(t, err) - - txSource := primitives.NewTransactionSourceExternal() - blockHash := sc.BytesToFixedSequenceU8(testhelpers.ParentHash.ToBytes()) - - buffer := &bytes.Buffer{} - txSource.Encode(buffer) - - _, err = buffer.Write(inherentExt[1:]) - assert.NoError(t, err) - - blockHash.Encode(buffer) - - res, err := rt.Exec("TaggedTransactionQueue_validate_transaction", buffer.Bytes()) - assert.NoError(t, err) - - assert.NoError(t, err) - assert.Equal(t, testhelpers.TransactionValidityResultMandatoryValidationErr.Bytes(), res) -} - -func Test_ValidateTransaction_InvalidTransactionCall(t *testing.T) { - rt, _ := testhelpers.NewRuntimeInstance(t) - metadata := testhelpers.RuntimeMetadata(t, rt) - - txSource := primitives.NewTransactionSourceExternal() - blockHash := sc.BytesToFixedSequenceU8(testhelpers.ParentHash.ToBytes()) - - codeSpecVersion101, err := os.ReadFile(testhelpers.RuntimeWasmSpecVersion101) - assert.NoError(t, err) - - call, err := ctypes.NewCall(metadata, "System.apply_authorized_upgrade", codeSpecVersion101) - - extrinsic := ctypes.NewExtrinsic(call) - - buffer := &bytes.Buffer{} - txSource.Encode(buffer) - - encoder := cscale.NewEncoder(buffer) - err = extrinsic.Encode(*encoder) - assert.NoError(t, err) - - blockHash.Encode(buffer) - - res, err := rt.Exec("TaggedTransactionQueue_validate_transaction", buffer.Bytes()) - - assert.NoError(t, err) - assert.Equal(t, testhelpers.TransactionValidityResultCallErr.Bytes(), res) -} diff --git a/testdata/genesis-config/genesis-builder-config.json b/testdata/genesis-config/genesis-builder-config.json index f045394d..1c8fa968 100644 --- a/testdata/genesis-config/genesis-builder-config.json +++ b/testdata/genesis-config/genesis-builder-config.json @@ -78,5 +78,8 @@ } ] ] + }, + "sudo": { + "key": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY" } } \ No newline at end of file diff --git a/testhelpers/testhelpers.go b/testhelpers/testhelpers.go index f3112205..52e50ac8 100644 --- a/testhelpers/testhelpers.go +++ b/testhelpers/testhelpers.go @@ -7,11 +7,8 @@ import ( "math/big" "testing" - "github.com/LimeChain/gosemble/frame/session" "github.com/LimeChain/gosemble/frame/sudo" - "github.com/LimeChain/gosemble/frame/session" - gossamertypes "github.com/ChainSafe/gossamer/dot/types" "github.com/ChainSafe/gossamer/lib/common" "github.com/ChainSafe/gossamer/lib/crypto/secp256k1" @@ -21,8 +18,10 @@ import ( "github.com/ChainSafe/gossamer/pkg/trie" sc "github.com/LimeChain/goscale" "github.com/LimeChain/gosemble/frame/balances" + "github.com/LimeChain/gosemble/frame/session" "github.com/LimeChain/gosemble/frame/system" "github.com/LimeChain/gosemble/frame/transaction_payment" + babetypes "github.com/LimeChain/gosemble/primitives/babe" "github.com/LimeChain/gosemble/primitives/types" primitives "github.com/LimeChain/gosemble/primitives/types" cscale "github.com/centrifuge/go-substrate-rpc-client/v4/scale" @@ -44,61 +43,66 @@ const ( ConsensusFinalizationIndex BalancesIndex TxPaymentsIndex + SudoIndex TestableIndex = 255 ) // keys from all the modules var ( - KeySystemHash, _ = common.Twox128Hash([]byte("System")) - KeyAccountHash, _ = common.Twox128Hash([]byte("Account")) - KeyAllExtrinsicsLenHash, _ = common.Twox128Hash([]byte("AllExtrinsicsLen")) - KeyAuraHash, _ = common.Twox128Hash([]byte("Aura")) - KeyAuthoritiesHash, _ = common.Twox128Hash([]byte("Authorities")) - KeyAuthorizedUpgradeHash, _ = common.Twox128Hash([]byte("AuthorizedUpgrade")) + KeySystemHash, _ = common.Twox128Hash([]byte("System")) + KeyAccountHash, _ = common.Twox128Hash([]byte("Account")) + KeyAllExtrinsicsLenHash, _ = common.Twox128Hash([]byte("AllExtrinsicsLen")) + KeyAuraHash, _ = common.Twox128Hash([]byte("Aura")) + KeyAuthoritiesHash, _ = common.Twox128Hash([]byte("Authorities")) + KeyAuthorizedUpgradeHash, _ = common.Twox128Hash([]byte("AuthorizedUpgrade")) + KeyBlockHash, _ = common.Twox128Hash([]byte("BlockHash")) + KeyCurrentSlotHash, _ = common.Twox128Hash([]byte("CurrentSlot")) + KeyDigestHash, _ = common.Twox128Hash([]byte("Digest")) + KeyEventsHash, _ = common.Twox128Hash([]byte("Events")) + KeyEventCountHash, _ = common.Twox128Hash([]byte("EventCount")) + KeyExecutionPhaseHash, _ = common.Twox128Hash([]byte("ExecutionPhase")) + KeyExtrinsicCountHash, _ = common.Twox128Hash([]byte("ExtrinsicCount")) + KeyExtrinsicIndex = []byte(":extrinsic_index") + KeyHeapPages = []byte(":heappages") + KeyExtrinsicDataHash, _ = common.Twox128Hash([]byte("ExtrinsicData")) + KeyLastRuntimeHash, _ = common.Twox128Hash([]byte("LastRuntimeUpgrade")) + KeyNumberHash, _ = common.Twox128Hash([]byte("Number")) + KeyParentHash, _ = common.Twox128Hash([]byte("ParentHash")) + KeyTimestampHash, _ = common.Twox128Hash([]byte("Timestamp")) + KeyTimestampNowHash, _ = common.Twox128Hash([]byte("Now")) + KeyTimestampDidUpdateHash, _ = common.Twox128Hash([]byte("DidUpdate")) + KeyBlockWeightHash, _ = common.Twox128Hash([]byte("BlockWeight")) + KeyGrandpaAuthorities = []byte(":grandpa_authorities") + KeyBalancesHash, _ = common.Twox128Hash([]byte("Balances")) + KeyTotalIssuanceHash, _ = common.Twox128Hash([]byte("TotalIssuance")) + KeyTransactionPaymentHash, _ = common.Twox128Hash([]byte("TransactionPayment")) + KeyNextFeeMultiplierHash, _ = common.Twox128Hash([]byte("NextFeeMultiplier")) +) + +// Babe storage keys +var ( KeyBabeHash, _ = common.Twox128Hash([]byte("Babe")) - KeyBlockHash, _ = common.Twox128Hash([]byte("BlockHash")) - KeyCurrentSlotHash, _ = common.Twox128Hash([]byte("CurrentSlot")) - KeyDigestHash, _ = common.Twox128Hash([]byte("Digest")) - KeyEventsHash, _ = common.Twox128Hash([]byte("Events")) - KeyEventCountHash, _ = common.Twox128Hash([]byte("EventCount")) - KeyExecutionPhaseHash, _ = common.Twox128Hash([]byte("ExecutionPhase")) - KeyExtrinsicCountHash, _ = common.Twox128Hash([]byte("ExtrinsicCount")) KeyEpochConfigHash, _ = common.Twox128Hash([]byte("EpochConfig")) KeyEpochIndexHash, _ = common.Twox128Hash([]byte("EpochIndex")) - KeyExtrinsicIndex = []byte(":extrinsic_index") - KeyHeapPages = []byte(":heappages") - KeyExtrinsicDataHash, _ = common.Twox128Hash([]byte("ExtrinsicData")) - KeyLastRuntimeHash, _ = common.Twox128Hash([]byte("LastRuntimeUpgrade")) - KeyNumberHash, _ = common.Twox128Hash([]byte("Number")) - KeyParentHash, _ = common.Twox128Hash([]byte("ParentHash")) - KeyTimestampHash, _ = common.Twox128Hash([]byte("Timestamp")) - KeyTimestampNowHash, _ = common.Twox128Hash([]byte("Now")) - KeyTimestampDidUpdateHash, _ = common.Twox128Hash([]byte("DidUpdate")) - KeyBlockWeightHash, _ = common.Twox128Hash([]byte("BlockWeight")) - KeyGrandpaAuthorities = []byte(":grandpa_authorities") - KeyBalancesHash, _ = common.Twox128Hash([]byte("Balances")) - KeyTotalIssuanceHash, _ = common.Twox128Hash([]byte("TotalIssuance")) - KeyTransactionPaymentHash, _ = common.Twox128Hash([]byte("TransactionPayment")) - KeyNextFeeMultiplierHash, _ = common.Twox128Hash([]byte("NextFeeMultiplier")) - KeyRandomnessHash, _ = common.Twox128Hash([]byte("Randomness")) - KeyNextRandomnessHash, _ = common.Twox128Hash([]byte("NextRandomness")) KeyGenesisSlotHash, _ = common.Twox128Hash([]byte("GenesisSlot")) + KeyNextRandomnessHash, _ = common.Twox128Hash([]byte("NextRandomness")) KeyNextAuthoritiesHash, _ = common.Twox128Hash([]byte("NextAuthorities")) KeyNextEpochConfigHash, _ = common.Twox128Hash([]byte("NextEpochConfig")) KeyPendingEpochConfigChangeHash, _ = common.Twox128Hash([]byte("PendingEpochConfigChange")) + KeyRandomnessHash, _ = common.Twox128Hash([]byte("Randomness")) ) // Session storage keys var ( - keySessionHash, _ = common.Twox128Hash([]byte("Session")) - keyNextKeys, _ = common.Twox128Hash([]byte("NextKeys")) - keyKeyOwner, _ = common.Twox128Hash([]byte("KeyOwner")) + KeySessionHash, _ = common.Twox128Hash([]byte("Session")) + KeyNextKeys, _ = common.Twox128Hash([]byte("NextKeys")) + KeyKeyOwner, _ = common.Twox128Hash([]byte("KeyOwner")) ) // Sudo storage keys var ( - keySudoHash, _ = common.Twox128Hash([]byte("Sudo")) - keyKeyHash, _ = common.Twox128Hash([]byte("Key")) + KeySudoHash, _ = common.Twox128Hash([]byte("Sudo")) + KeyKeyHash, _ = common.Twox128Hash([]byte("Key")) ) var ( @@ -182,6 +186,12 @@ var ( ApplyExtrinsicResultSudoRequireSudoErr, _ = primitives.NewApplyExtrinsicResult(dispatchOutcomeSudoRequireSudoErr) ) +var ( + GenesisConfigJson = []byte( + "{\"system\":{\"code\":\"\"},\"babe\":{\"authorities\":[\"5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY\"],\"epochConfig\":{\"c\":[1,4],\"allowed_slots\":\"PrimarySlots\"}},\"grandpa\":{\"authorities\":[]},\"balances\":{\"balances\":[[\"5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY\",1000000000000000000],[\"5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty\",1000000000000000000],[\"5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y\",1000000000000000000],[\"5DAAnrj7VHTznn2AWBemMuyBwZWs6FNFjdyVXUeYum3PTXFy\",1000000000000000000],[\"5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw\",1000000000000000000],[\"5CiPPseXPECbkjWCa6MnjNokrgYjMqmKndv2rSnekmSK2DjL\",1000000000000000000],[\"5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY\",1000000000000000000],[\"5HpG9w8EBLe5XCrbczpwq5TSXvedjrBGCwqxK1iQ7qUsSWFc\",1000000000000000000],[\"5Ck5SLSHYac6WFt5UZRSsdJjwmpSZq85fd5TRNAdZQVzEAPT\",1000000000000000000],[\"5HKPmK9GYtE1PSLsS1qiYU9xQ9Si1NcEhdeCq9sw5bqu4ns8\",1000000000000000000],[ \"5FCfAonRZgTFrTd9HREEyeJjDpT397KMzizE6T3DvebLFE7n\",1000000000000000000],[\"5CRmqmsiNFExV6VbdmPJViVxrWmkaXXvBrSX8oqBT8R9vmWk\",1000000000000000000]]},\"session\": {\"keys\": [[\"5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY\",\"5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY\",{\"grandpa\":\"5FA9nQDVg267DEd8m1ZypXLBnvN7SFxYwV7ndqSYGiN9TTpu\",\"babe\":\"5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY\"}]]},\"transactionPayment\":{\"multiplier\":\"1\"},\"sudo\":{\"key\":\"5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY\"}}", + ) +) + // TODO: // implement "Client" type with the helpers functions // there is also separate "Instance" type for benchmarking that we might get rid of @@ -217,13 +227,13 @@ func RuntimeMetadata(t assert.TestingT, instance *wazero_runtime.Instance) *ctyp return metadata } -func InitializeBlock(t *testing.T, rt *wazero_runtime.Instance, parentHash, stateRoot, extrinsicsRoot common.Hash, blockNumber uint64) { +func InitializeBlock(t *testing.T, instance *wazero_runtime.Instance, parentHash, stateRoot, extrinsicsRoot common.Hash, blockNumber uint64) { digest := gossamertypes.NewDigest() header := gossamertypes.NewHeader(parentHash, stateRoot, extrinsicsRoot, uint(blockNumber), digest) encodedHeader, err := scale.Marshal(*header) assert.NoError(t, err) - _, err = rt.Exec("Core_initialize_block", encodedHeader) + _, err = instance.Exec("Core_initialize_block", encodedHeader) assert.NoError(t, err) } @@ -303,14 +313,14 @@ func SetStorageAccountInfo(t *testing.T, storage *runtime.Storage, account []byt return keyStorageAccount, accountInfo } -func GetQueryInfo(t *testing.T, runtime *wazero_runtime.Instance, extrinsic []byte) primitives.RuntimeDispatchInfo { +func GetQueryInfo(t *testing.T, instance *wazero_runtime.Instance, extrinsic []byte) primitives.RuntimeDispatchInfo { buffer := &bytes.Buffer{} buffer.Write(extrinsic) err := sc.U32(buffer.Len()).Encode(buffer) assert.NoError(t, err) - bytesRuntimeDispatchInfo, err := runtime.Exec("TransactionPaymentApi_query_info", buffer.Bytes()) + bytesRuntimeDispatchInfo, err := instance.Exec("TransactionPaymentApi_query_info", buffer.Bytes()) assert.NoError(t, err) buffer.Reset() @@ -400,7 +410,7 @@ func SignExtrinsicSecp256k1(e *ctypes.Extrinsic, o ctypes.SignatureOptions, keyP func AssertSessionNextKeys(t assert.TestingT, storage *runtime.Storage, account []byte, expectedKey []byte) { accountHash, _ := common.Twox64(account) - keySessionNextKeys := append(keySessionHash, keyNextKeys...) + keySessionNextKeys := append(KeySessionHash, KeyNextKeys...) keySessionNextKeys = append(keySessionNextKeys, accountHash...) keySessionNextKeys = append(keySessionNextKeys, account...) @@ -410,7 +420,7 @@ func AssertSessionNextKeys(t assert.TestingT, storage *runtime.Storage, account func AssertSessionKeyOwner(t assert.TestingT, storage *runtime.Storage, key primitives.SessionKey, expectedOwner []byte) { keyOwnerBytes := key.Bytes() keyOwnerHash, _ := common.Twox64(keyOwnerBytes) - keySessionKeyOwner := append(keySessionHash, keyKeyOwner...) + keySessionKeyOwner := append(KeySessionHash, KeyKeyOwner...) keySessionKeyOwner = append(keySessionKeyOwner, keyOwnerHash...) keySessionKeyOwner = append(keySessionKeyOwner, keyOwnerBytes...) @@ -421,7 +431,7 @@ func AssertSessionKeyOwner(t assert.TestingT, storage *runtime.Storage, key prim func AssertSessionEmptyStorage(t assert.TestingT, storage *runtime.Storage, account []byte, key []byte, keyTypeId [4]byte) { accountHash, _ := common.Twox64(account) - keySessionNextKeys := append(keySessionHash, keyNextKeys...) + keySessionNextKeys := append(KeySessionHash, KeyNextKeys...) keySessionNextKeys = append(keySessionNextKeys, accountHash...) keySessionNextKeys = append(keySessionNextKeys, account...) @@ -429,7 +439,7 @@ func AssertSessionEmptyStorage(t assert.TestingT, storage *runtime.Storage, acco keyOwnerBytes := primitives.NewSessionKey(key, keyTypeId).Bytes() keyOwnerHash, _ := common.Twox64(keyOwnerBytes) - keySessionKeyOwner := append(keySessionHash, keyKeyOwner...) + keySessionKeyOwner := append(KeySessionHash, KeyKeyOwner...) keySessionKeyOwner = append(keySessionKeyOwner, keyOwnerHash...) keySessionKeyOwner = append(keySessionKeyOwner, keyOwnerBytes...) @@ -438,7 +448,7 @@ func AssertSessionEmptyStorage(t assert.TestingT, storage *runtime.Storage, acco func SetSessionKeysStorage(t assert.TestingT, storage *runtime.Storage, account []byte, key []byte, keyTypeId [4]byte) { accountHash, _ := common.Twox64(account) - keySessionNextKeys := append(keySessionHash, keyNextKeys...) + keySessionNextKeys := append(KeySessionHash, KeyNextKeys...) keySessionNextKeys = append(keySessionNextKeys, accountHash...) keySessionNextKeys = append(keySessionNextKeys, account...) @@ -446,9 +456,44 @@ func SetSessionKeysStorage(t assert.TestingT, storage *runtime.Storage, account keyOwnerBytes := primitives.NewSessionKey(key, keyTypeId).Bytes() keyOwnerHash, _ := common.Twox64(keyOwnerBytes) - keySessionKeyOwner := append(keySessionHash, keyKeyOwner...) + keySessionKeyOwner := append(KeySessionHash, KeyKeyOwner...) keySessionKeyOwner = append(keySessionKeyOwner, keyOwnerHash...) keySessionKeyOwner = append(keySessionKeyOwner, keyOwnerBytes...) assert.Nil(t, (*storage).Put(keySessionKeyOwner, account)) } + +func GetBabeSlot(t *testing.T, instance *wazero_runtime.Instance, time uint64) uint64 { + babeConfigurationBytes, err := instance.Exec("BabeApi_configuration", []byte{}) + assert.NoError(t, err) + + babeConfiguration, err := babetypes.DecodeConfiguration(bytes.NewBuffer(babeConfigurationBytes)) + assert.NoError(t, err) + + return time / uint64(babeConfiguration.SlotDuration) +} + +func NewBabeDigest(t *testing.T, slot uint64) gossamertypes.Digest { + primaryDigest := gossamertypes.NewBabePrimaryPreDigest(0, uint64(slot), [32]byte{}, [64]byte{}) + babeDigest := gossamertypes.NewBabeDigest() + err := babeDigest.SetValue(*primaryDigest) + assert.NoError(t, err) + + encPreDigestData, err := scale.Marshal(babeDigest) + assert.NoError(t, err) + + preDigest := gossamertypes.NewBABEPreRuntimeDigest(encPreDigestData) + digest := gossamertypes.NewDigest() + err = digest.Add(*preDigest) + assert.NoError(t, err) + + return digest +} + +func GenesisBuild(t *testing.T, instance *wazero_runtime.Instance, genesisConfig []byte) { + genesisConfigBytes, err := scale.Marshal(genesisConfig) + assert.NoError(t, err) + + _, err = instance.Exec("GenesisBuilder_build_config", genesisConfigBytes) + assert.NoError(t, err) +}