Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
62748b0
reset branch for new head
jimjbrettj Sep 27, 2022
1d651bc
fix genesis
jimjbrettj Sep 27, 2022
b5e7dee
remove unneeded code
jimjbrettj Sep 27, 2022
c2f3017
add missing helper func
jimjbrettj Sep 27, 2022
e66f967
retrieve old core helper from git history
jimjbrettj Sep 27, 2022
811f964
remove unneeded diff
jimjbrettj Sep 27, 2022
9a83c71
remove nil checks from createTestService
jimjbrettj Sep 28, 2022
453c50c
respond to feedback
jimjbrettj Sep 28, 2022
51b331e
feedback
jimjbrettj Oct 4, 2022
621514f
fix author integration tests
jimjbrettj Oct 4, 2022
774f976
clean up handle block async logic
jimjbrettj Oct 5, 2022
7028dc2
make maintainTxnPool return error
jimjbrettj Oct 5, 2022
2cf6d8e
add bestBlockHash as input to maintainTxnPool
jimjbrettj Oct 12, 2022
f45c1f9
add panics to handle blocks async
jimjbrettj Oct 12, 2022
f87fbdd
construct config at once in test helper
jimjbrettj Oct 12, 2022
092ba0f
fix core test
jimjbrettj Oct 12, 2022
7dc03d9
update go mod
jimjbrettj Oct 12, 2022
0890725
finish feedback
jimjbrettj Oct 12, 2022
4c98707
fix core tests
jimjbrettj Oct 13, 2022
f7645b2
lint
jimjbrettj Oct 13, 2022
ec61473
remove log
jimjbrettj Oct 17, 2022
3f87fbd
Update lib/common/hasher_test.go
jimjbrettj Oct 17, 2022
a8a282d
Update lib/common/hasher_test.go
jimjbrettj Oct 17, 2022
fe26434
Update dot/core/messages_test.go
jimjbrettj Oct 17, 2022
0259b40
Update dot/core/service.go
jimjbrettj Oct 17, 2022
61246d7
Update dot/core/service.go
jimjbrettj Oct 17, 2022
8a9e268
Update dot/core/service_test.go
jimjbrettj Oct 17, 2022
e6c06b1
Update dot/core/service_test.go
jimjbrettj Oct 17, 2022
fd7f33f
Update dot/core/service_test.go
jimjbrettj Oct 17, 2022
017ce25
Update dot/core/service_test.go
jimjbrettj Oct 17, 2022
a1f7d0e
Update dot/core/service_test.go
jimjbrettj Oct 17, 2022
e776bb6
Update dot/core/service_test.go
jimjbrettj Oct 17, 2022
e57e70e
Update dot/core/service_test.go
jimjbrettj Oct 17, 2022
93ca14b
fix core tests
jimjbrettj Oct 17, 2022
3ac1392
remove errors.Is in handleChainReorg test to handle formatted errors
jimjbrettj Oct 17, 2022
472a21b
make taggedTransactionQueueVersion a receiver func
jimjbrettj Oct 17, 2022
52e58f0
feedback
jimjbrettj Oct 17, 2022
9b3fb44
rename allTxnsAreValid
jimjbrettj Oct 18, 2022
7e69fd6
respond to feedback
jimjbrettj Oct 18, 2022
763941f
fix tests
jimjbrettj Oct 19, 2022
79adb4b
feedback
jimjbrettj Oct 21, 2022
57de89d
add todos to remove panic in handleBlockAsync
jimjbrettj Oct 22, 2022
9b172fe
fix logs
jimjbrettj Oct 24, 2022
19bb3c7
fix handleBlockImport to match dev
jimjbrettj Oct 24, 2022
0431bfb
Update lib/runtime/version.go
jimjbrettj Oct 24, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 2 additions & 7 deletions dot/core/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,12 @@ import (
)

var (

// ErrServiceStopped is returned when the service has been stopped
ErrServiceStopped = errors.New("service has been stopped")

// ErrInvalidBlock is returned when a block cannot be verified
ErrInvalidBlock = errors.New("could not verify block")

ErrNilRuntime = errors.New("cannot have nil runtime")

ErrNilBlockHandlerParameter = errors.New("unable to handle block due to nil parameter")

// ErrEmptyRuntimeCode is returned when the storage :code is empty
ErrEmptyRuntimeCode = errors.New("new :code is empty")

errInvalidTransactionQueueVersion = errors.New("invalid transaction queue version")
)
125 changes: 125 additions & 0 deletions dot/core/helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@
package core

import (
"bytes"
"path/filepath"
"testing"

"github.com/ChainSafe/gossamer/dot/network"
"github.com/ChainSafe/gossamer/dot/state"
"github.com/ChainSafe/gossamer/dot/types"
"github.com/ChainSafe/gossamer/internal/log"
Expand All @@ -19,10 +21,133 @@ import (
"github.com/ChainSafe/gossamer/lib/runtime/wasmer"
"github.com/ChainSafe/gossamer/lib/trie"
"github.com/ChainSafe/gossamer/lib/utils"
"github.com/ChainSafe/gossamer/pkg/scale"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)

func balanceKey(t *testing.T, pub []byte) (bKey []byte) {
t.Helper()

h0, err := common.Twox128Hash([]byte("System"))
require.NoError(t, err)
h1, err := common.Twox128Hash([]byte("Account"))
require.NoError(t, err)
h2, err := common.Blake2b128(pub)
require.NoError(t, err)
return bytes.Join([][]byte{h0, h1, h2, pub}, nil)
}

// Creates test service, used now for testing txnPool but can be used elsewhere when needed
func createTestService(t *testing.T, genesisFilePath string,
pubKey []byte, accountInfo types.AccountInfo, ctrl *gomock.Controller) (service *Service, encodedExtrinsic []byte) {
t.Helper()

gen, err := genesis.NewGenesisFromJSONRaw(genesisFilePath)
require.NoError(t, err)

genesisTrie, err := wasmer.NewTrieFromGenesis(*gen)
require.NoError(t, err)

// Extrinsic and context related stuff
aliceBalanceKey := balanceKey(t, pubKey)
encodedAccountInfo, err := scale.Marshal(accountInfo)
require.NoError(t, err)

genesisHeader := &types.Header{
StateRoot: genesisTrie.MustHash(),
Number: 0,
}

cfgKeystore := keystore.NewGlobalKeystore()
kp, err := sr25519.GenerateKeypair()
require.NoError(t, err)
err = cfgKeystore.Acco.Insert(kp)
require.NoError(t, err)

// Create state service
var stateSrvc *state.Service
testDatadirPath := t.TempDir()

// Set up block and storage state
telemetryMock := NewMockClient(ctrl)
telemetryMock.EXPECT().SendMessage(gomock.Any()).AnyTimes()
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In SendMessage try to make the type telemetry.Message

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Having trouble with this. Can I pass in an interface like that? Or do I need to instantiate it and am just being dumb somehow when I am tring

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Try something like

	var k telemetry.Message
	telemetryMock.EXPECT().SendMessage(gomock.AssignableToTypeOf(k)).AnyTimes()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hm this is still not working. Tried a couple variants of this and seems to not be a fan still.


stateConfig := state.Config{
Path: testDatadirPath,
LogLevel: log.Critical,
Telemetry: telemetryMock,
}

stateSrvc = state.NewService(stateConfig)
stateSrvc.UseMemDB()

err = stateSrvc.Initialise(gen, genesisHeader, &genesisTrie)
require.NoError(t, err)

// Start state service
err = stateSrvc.Start()
require.NoError(t, err)

cfgBlockState := stateSrvc.Block
cfgStorageState := stateSrvc.Storage
cfgCodeSubstitutedState := stateSrvc.Base

var rtCfg wasmer.Config
rtCfg.Storage = rtstorage.NewTrieState(&genesisTrie)

rtCfg.CodeHash, err = cfgStorageState.LoadCodeHash(nil)
require.NoError(t, err)

nodeStorage := runtime.NodeStorage{}
nodeStorage.BaseDB = stateSrvc.Base

rtCfg.NodeStorage = nodeStorage

cfgRuntime, err := wasmer.NewRuntimeFromGenesis(rtCfg)
require.NoError(t, err)

cfgRuntime.(*wasmer.Instance).GetContext().Storage.Set(aliceBalanceKey, encodedAccountInfo)
// this key is System.UpgradedToDualRefCount -> set to true since all accounts have been upgraded to v0.9 format
cfgRuntime.(*wasmer.Instance).GetContext().Storage.Set(common.UpgradedToDualRefKey, []byte{1})

cfgBlockState.StoreRuntime(cfgBlockState.BestBlockHash(), cfgRuntime)

// Hash of encrypted centrifuge extrinsic
testCallArguments := []byte{0xab, 0xcd}
extHex := runtime.NewTestExtrinsic(t, cfgRuntime, genesisHeader.Hash(), cfgBlockState.BestBlockHash(),
0, "System.remark", testCallArguments)
encodedExtrinsic = common.MustHexToBytes(extHex)

cfgCodeSubstitutes := make(map[common.Hash]string)

genesisData, err := cfgCodeSubstitutedState.LoadGenesisData()
require.NoError(t, err)

for k, v := range genesisData.CodeSubstitutes {
cfgCodeSubstitutes[common.MustHexToHash(k)] = v
}

cfgCodeSubstitutedState = stateSrvc.Base

cfg := &Config{
Keystore: cfgKeystore,
LogLvl: log.Critical,
BlockState: cfgBlockState,
StorageState: cfgStorageState,
TransactionState: stateSrvc.Transaction,
EpochState: stateSrvc.Epoch,
CodeSubstitutedState: cfgCodeSubstitutedState,
Runtime: cfgRuntime,
Network: new(network.Service),
CodeSubstitutes: cfgCodeSubstitutes,
}
service, err = NewService(cfg)
require.NoError(t, err)

return service, encodedExtrinsic
}

// NewTestService creates a new test core service
func NewTestService(t *testing.T, cfg *Config) *Service {
t.Helper()
Expand Down
13 changes: 8 additions & 5 deletions dot/core/messages.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,11 @@ func (s *Service) validateTransaction(head *types.Header, rt RuntimeInstance,
rt.SetContextStorage(ts)

// validate each transaction
externalExt := types.Extrinsic(append([]byte{byte(types.TxnExternal)}, tx...))
externalExt, err := s.buildExternalTransaction(rt, tx)
if err != nil {
return nil, fmt.Errorf("building external transaction: %w", err)
}

validity, err = rt.ValidateTransaction(externalExt)
if err != nil {
logger.Debugf("failed to validate transaction: %s", err)
Expand Down Expand Up @@ -72,12 +76,10 @@ func (s *Service) HandleTransactionMessage(peerID peer.ID, msg *network.Transact

allTxnsAreValid := true
for _, tx := range txs {
txnIsValid := true
validity, err := s.validateTransaction(head, rt, tx)
if err != nil {
txnIsValid = false
allTxnsAreValid = false
switch err := err.(type) {
switch err.(type) {
case runtime.InvalidTransaction:
s.net.ReportPeer(peerset.ReputationChange{
Value: peerset.BadTransactionValue,
Expand All @@ -87,9 +89,10 @@ func (s *Service) HandleTransactionMessage(peerID peer.ID, msg *network.Transact
default:
return false, fmt.Errorf("validating transaction from peerID %s: %w", peerID, err)
}
continue
}

if txnIsValid && validity.Propagate {
if validity.Propagate {
// find tx(s) that should propagate
toPropagate = append(toPropagate, tx)
}
Expand Down
8 changes: 7 additions & 1 deletion dot/core/messages_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,17 @@ func TestService_HandleBlockProduced(t *testing.T) {
err = digest.Add(*prd)
require.NoError(t, err)

// Used to define the state root of new block for testing
parentHash := s.blockState.GenesisHash()
genesisBlock, err := s.blockState.GetBlockByHash(parentHash)
require.NoError(t, err)

newBlock := types.Block{
Header: types.Header{
Number: 1,
ParentHash: s.blockState.BestBlockHash(),
ParentHash: parentHash,
Digest: digest,
StateRoot: genesisBlock.Header.StateRoot,
},
Body: *types.NewBody([]types.Extrinsic{}),
}
Expand Down
38 changes: 33 additions & 5 deletions dot/core/messages_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package core

import (
"bytes"
"errors"
"testing"

Expand Down Expand Up @@ -44,8 +45,9 @@ type mockGetRuntime struct {
}

type mockBlockState struct {
bestHeader *mockBestHeader
getRuntime *mockGetRuntime
bestHeader *mockBestHeader
getRuntime *mockGetRuntime
callsBestBlockHash bool
}

type mockStorageState struct {
Expand Down Expand Up @@ -252,6 +254,7 @@ func TestServiceHandleTransactionMessage(t *testing.T) {
getRuntime: &mockGetRuntime{
runtime: runtimeMock2,
},
callsBestBlockHash: true,
},
mockStorageState: &mockStorageState{
input: &common.Hash{},
Expand All @@ -261,8 +264,12 @@ func TestServiceHandleTransactionMessage(t *testing.T) {
runtime: runtimeMock2,
setContextStorage: &mockSetContextStorage{trieState: &storage.TrieState{}},
validateTxn: &mockValidateTxn{
input: types.Extrinsic(append([]byte{byte(types.TxnExternal)}, testExtrinsic[0]...)),
err: invalidTransaction,
input: types.Extrinsic(bytes.Join([][]byte{
{byte(types.TxnExternal)},
testExtrinsic[0],
testEmptyHeader.StateRoot.ToBytes(),
}, nil)),
err: invalidTransaction,
},
},
args: args{
Expand Down Expand Up @@ -291,6 +298,7 @@ func TestServiceHandleTransactionMessage(t *testing.T) {
getRuntime: &mockGetRuntime{
runtime: runtimeMock3,
},
callsBestBlockHash: true,
},
mockStorageState: &mockStorageState{
input: &common.Hash{},
Expand All @@ -308,7 +316,11 @@ func TestServiceHandleTransactionMessage(t *testing.T) {
runtime: runtimeMock3,
setContextStorage: &mockSetContextStorage{trieState: &storage.TrieState{}},
validateTxn: &mockValidateTxn{
input: types.Extrinsic(append([]byte{byte(types.TxnExternal)}, testExtrinsic[0]...)),
input: types.Extrinsic(bytes.Join([][]byte{
{byte(types.TxnExternal)},
testExtrinsic[0],
testEmptyHeader.StateRoot.ToBytes(),
}, nil)),
validity: &transaction.Validity{Propagate: true},
},
},
Expand Down Expand Up @@ -344,6 +356,9 @@ func TestServiceHandleTransactionMessage(t *testing.T) {
tt.mockBlockState.getRuntime.runtime,
tt.mockBlockState.getRuntime.err)
}
if tt.mockBlockState.callsBestBlockHash {
blockState.EXPECT().BestBlockHash().Return(common.Hash{})
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could use .AnyTimes(), then you won't need callsBestBlockHash

blockState.EXPECT().BestBlockHash().Return(common.Hash{}).AnyTimes()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we are tryin to avoid using .AnyTimes()

}
s.blockState = blockState
}
if tt.mockStorageState != nil {
Expand All @@ -365,6 +380,19 @@ func TestServiceHandleTransactionMessage(t *testing.T) {
rt.EXPECT().SetContextStorage(tt.mockRuntime.setContextStorage.trieState)
rt.EXPECT().ValidateTransaction(tt.mockRuntime.validateTxn.input).
Return(tt.mockRuntime.validateTxn.validity, tt.mockRuntime.validateTxn.err)
rt.EXPECT().Version().Return(runtime.Version{
SpecName: []byte("polkadot"),
ImplName: []byte("parity-polkadot"),
AuthoringVersion: authoringVersion,
SpecVersion: specVersion,
ImplVersion: implVersion,
APIItems: []runtime.APIItem{{
Name: common.MustBlake2b8([]byte("TaggedTransactionQueue")),
Ver: 3,
}},
TransactionVersion: transactionVersion,
StateVersion: stateVersion,
})
}

res, err := s.HandleTransactionMessage(tt.args.peerID, tt.args.msg)
Expand Down
Loading