cleanup: Reduce and normalize import path aliasing. (#6975)

The code in the Tendermint repository makes heavy use of import aliasing.
This is made necessary by our extensive reuse of common base package names, and
by repetition of similar names across different subdirectories.

Unfortunately we have not been very consistent about which packages we alias in
various circumstances, and the aliases we use vary. In the spirit of the advice
in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports,
his change makes an effort to clean up and normalize import aliasing.

This change makes no API or behavioral changes. It is a pure cleanup intended
o help make the code more readable to developers (including myself) trying to
understand what is being imported where.

Only unexported names have been modified, and the changes were generated and
applied mechanically with gofmt -r and comby, respecting the lexical and
syntactic rules of Go.  Even so, I did not fix every inconsistency. Where the
changes would be too disruptive, I left it alone.

The principles I followed in this cleanup are:

- Remove aliases that restate the package name.
- Remove aliases where the base package name is unambiguous.
- Move overly-terse abbreviations from the import to the usage site.
- Fix lexical issues (remove underscores, remove capitalization).
- Fix import groupings to more closely match the style guide.
- Group blank (side-effecting) imports and ensure they are commented.
- Add aliases to multiple imports with the same base package name.
This commit is contained in:
M. J. Fromberger
2021-09-23 07:52:07 -07:00
committed by GitHub
parent c9beef796d
commit cf7537ea5f
127 changed files with 1473 additions and 1473 deletions
+8 -8
View File
@@ -6,13 +6,13 @@ import (
"sync"
"time"
bc "github.com/tendermint/tendermint/internal/blocksync"
cons "github.com/tendermint/tendermint/internal/consensus"
"github.com/tendermint/tendermint/internal/blocksync"
"github.com/tendermint/tendermint/internal/consensus"
"github.com/tendermint/tendermint/internal/p2p"
sm "github.com/tendermint/tendermint/internal/state"
"github.com/tendermint/tendermint/libs/log"
"github.com/tendermint/tendermint/libs/service"
tmSync "github.com/tendermint/tendermint/libs/sync"
tmsync "github.com/tendermint/tendermint/libs/sync"
bcproto "github.com/tendermint/tendermint/proto/tendermint/blocksync"
"github.com/tendermint/tendermint/store"
"github.com/tendermint/tendermint/types"
@@ -36,7 +36,7 @@ var (
Priority: 5,
SendQueueCapacity: 1000,
RecvBufferCapacity: 1024,
RecvMessageCapacity: bc.MaxMsgSize,
RecvMessageCapacity: blocksync.MaxMsgSize,
MaxSendBytes: 100,
},
},
@@ -85,7 +85,7 @@ type Reactor struct {
store *store.BlockStore
pool *BlockPool
consReactor consensusReactor
blockSync *tmSync.AtomicBool
blockSync *tmsync.AtomicBool
blockSyncCh *p2p.Channel
// blockSyncOutBridgeCh defines a channel that acts as a bridge between sending Envelope
@@ -107,7 +107,7 @@ type Reactor struct {
// stopping the p2p Channel(s).
poolWG sync.WaitGroup
metrics *cons.Metrics
metrics *consensus.Metrics
syncStartTime time.Time
}
@@ -122,7 +122,7 @@ func NewReactor(
blockSyncCh *p2p.Channel,
peerUpdates *p2p.PeerUpdates,
blockSync bool,
metrics *cons.Metrics,
metrics *consensus.Metrics,
) (*Reactor, error) {
if state.LastBlockHeight != store.Height() {
return nil, fmt.Errorf("state (%v) and store (%v) height mismatch", state.LastBlockHeight, store.Height())
@@ -142,7 +142,7 @@ func NewReactor(
store: store,
pool: NewBlockPool(startHeight, requestsCh, errorsCh),
consReactor: consReactor,
blockSync: tmSync.NewBool(blockSync),
blockSync: tmsync.NewBool(blockSync),
requestsCh: requestsCh,
errorsCh: errorsCh,
blockSyncCh: blockSyncCh,
+17 -17
View File
@@ -6,11 +6,12 @@ import (
"time"
"github.com/stretchr/testify/require"
dbm "github.com/tendermint/tm-db"
abciclient "github.com/tendermint/tendermint/abci/client"
abci "github.com/tendermint/tendermint/abci/types"
cfg "github.com/tendermint/tendermint/config"
cons "github.com/tendermint/tendermint/internal/consensus"
"github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/internal/consensus"
"github.com/tendermint/tendermint/internal/mempool/mock"
"github.com/tendermint/tendermint/internal/p2p"
"github.com/tendermint/tendermint/internal/p2p/p2ptest"
@@ -22,7 +23,6 @@ import (
bcproto "github.com/tendermint/tendermint/proto/tendermint/blocksync"
"github.com/tendermint/tendermint/store"
"github.com/tendermint/tendermint/types"
dbm "github.com/tendermint/tm-db"
)
type reactorTestSuite struct {
@@ -165,7 +165,7 @@ func (rts *reactorTestSuite) addNode(t *testing.T,
rts.blockSyncChannels[nodeID],
rts.peerUpdates[nodeID],
rts.blockSync,
cons.NopMetrics())
consensus.NopMetrics())
require.NoError(t, err)
require.NoError(t, rts.reactors[nodeID].Start())
@@ -182,10 +182,10 @@ func (rts *reactorTestSuite) start(t *testing.T) {
}
func TestReactor_AbruptDisconnect(t *testing.T) {
config := cfg.ResetTestRoot("block_sync_reactor_test")
defer os.RemoveAll(config.RootDir)
cfg := config.ResetTestRoot("block_sync_reactor_test")
defer os.RemoveAll(cfg.RootDir)
genDoc, privVals := factory.RandGenesisDoc(config, 1, false, 30)
genDoc, privVals := factory.RandGenesisDoc(cfg, 1, false, 30)
maxBlockHeight := int64(64)
rts := setup(t, genDoc, privVals[0], []int64{maxBlockHeight, 0}, 0)
@@ -217,10 +217,10 @@ func TestReactor_AbruptDisconnect(t *testing.T) {
}
func TestReactor_SyncTime(t *testing.T) {
config := cfg.ResetTestRoot("block_sync_reactor_test")
defer os.RemoveAll(config.RootDir)
cfg := config.ResetTestRoot("block_sync_reactor_test")
defer os.RemoveAll(cfg.RootDir)
genDoc, privVals := factory.RandGenesisDoc(config, 1, false, 30)
genDoc, privVals := factory.RandGenesisDoc(cfg, 1, false, 30)
maxBlockHeight := int64(101)
rts := setup(t, genDoc, privVals[0], []int64{maxBlockHeight, 0}, 0)
@@ -240,10 +240,10 @@ func TestReactor_SyncTime(t *testing.T) {
}
func TestReactor_NoBlockResponse(t *testing.T) {
config := cfg.ResetTestRoot("block_sync_reactor_test")
defer os.RemoveAll(config.RootDir)
cfg := config.ResetTestRoot("block_sync_reactor_test")
defer os.RemoveAll(cfg.RootDir)
genDoc, privVals := factory.RandGenesisDoc(config, 1, false, 30)
genDoc, privVals := factory.RandGenesisDoc(cfg, 1, false, 30)
maxBlockHeight := int64(65)
rts := setup(t, genDoc, privVals[0], []int64{maxBlockHeight, 0}, 0)
@@ -287,11 +287,11 @@ func TestReactor_BadBlockStopsPeer(t *testing.T) {
// See: https://github.com/tendermint/tendermint/issues/6005
t.SkipNow()
config := cfg.ResetTestRoot("block_sync_reactor_test")
defer os.RemoveAll(config.RootDir)
cfg := config.ResetTestRoot("block_sync_reactor_test")
defer os.RemoveAll(cfg.RootDir)
maxBlockHeight := int64(48)
genDoc, privVals := factory.RandGenesisDoc(config, 1, false, 30)
genDoc, privVals := factory.RandGenesisDoc(cfg, 1, false, 30)
rts := setup(t, genDoc, privVals[0], []int64{maxBlockHeight, 0, 0, 0, 0}, 1000)
@@ -325,7 +325,7 @@ func TestReactor_BadBlockStopsPeer(t *testing.T) {
//
// XXX: This causes a potential race condition.
// See: https://github.com/tendermint/tendermint/issues/6005
otherGenDoc, otherPrivVals := factory.RandGenesisDoc(config, 1, false, 30)
otherGenDoc, otherPrivVals := factory.RandGenesisDoc(cfg, 1, false, 30)
newNode := rts.network.MakeNode(t, p2ptest.NodeOptions{
MaxPeers: uint16(len(rts.nodes) + 1),
MaxConnected: uint16(len(rts.nodes) + 1),
+5 -5
View File
@@ -3,7 +3,7 @@ package v2
import (
"fmt"
tmState "github.com/tendermint/tendermint/internal/state"
tmstate "github.com/tendermint/tendermint/internal/state"
"github.com/tendermint/tendermint/types"
)
@@ -36,7 +36,7 @@ func (e pcBlockProcessed) String() string {
type pcFinished struct {
priorityNormal
blocksSynced int
tmState tmState.State
tmState tmstate.State
}
func (p pcFinished) Error() string {
@@ -148,11 +148,11 @@ func (state *pcState) handle(event Event) (Event, error) {
return noOp, nil
case rProcessBlock:
tmState := state.context.tmState()
tmstate := state.context.tmState()
firstItem, secondItem, err := state.nextTwo()
if err != nil {
if state.draining {
return pcFinished{tmState: tmState, blocksSynced: state.blocksSynced}, nil
return pcFinished{tmState: tmstate, blocksSynced: state.blocksSynced}, nil
}
return noOp, nil
}
@@ -164,7 +164,7 @@ func (state *pcState) handle(event Event) (Event, error) {
)
// verify if +second+ last commit "confirms" +first+ block
err = state.context.verifyCommit(tmState.ChainID, firstID, first.Height, second.LastCommit)
err = state.context.verifyCommit(tmstate.ChainID, firstID, first.Height, second.LastCommit)
if err != nil {
state.purgePeer(firstItem.peerID)
if firstItem.peerID != secondItem.peerID {
+3 -3
View File
@@ -3,7 +3,7 @@ package v2
import (
"fmt"
cons "github.com/tendermint/tendermint/internal/consensus"
"github.com/tendermint/tendermint/internal/consensus"
"github.com/tendermint/tendermint/internal/state"
"github.com/tendermint/tendermint/types"
)
@@ -21,10 +21,10 @@ type pContext struct {
store blockStore
applier blockApplier
state state.State
metrics *cons.Metrics
metrics *consensus.Metrics
}
func newProcessorContext(st blockStore, ex blockApplier, s state.State, m *cons.Metrics) *pContext {
func newProcessorContext(st blockStore, ex blockApplier, s state.State, m *consensus.Metrics) *pContext {
return &pContext{
store: st,
applier: ex,
+5 -5
View File
@@ -5,7 +5,7 @@ import (
"github.com/stretchr/testify/assert"
tmState "github.com/tendermint/tendermint/internal/state"
tmstate "github.com/tendermint/tendermint/internal/state"
"github.com/tendermint/tendermint/types"
)
@@ -33,7 +33,7 @@ func makePcBlock(height int64) *types.Block {
// makeState takes test parameters and creates a specific processor state.
func makeState(p *params) *pcState {
var (
tmState = tmState.State{LastBlockHeight: p.height}
tmState = tmstate.State{LastBlockHeight: p.height}
context = newMockProcessorContext(tmState, p.verBL, p.appBL)
)
state := newPcState(context)
@@ -207,7 +207,7 @@ func TestRProcessBlockSuccess(t *testing.T) {
{ // finish when H+1 or/and H+2 are missing
event: rProcessBlock{},
wantState: &params{height: 1, items: []pcBlock{{"P2", 2}, {"P1", 4}}, blocksSynced: 1, draining: true},
wantNextEvent: pcFinished{tmState: tmState.State{LastBlockHeight: 1}, blocksSynced: 1},
wantNextEvent: pcFinished{tmState: tmstate.State{LastBlockHeight: 1}, blocksSynced: 1},
},
},
},
@@ -271,7 +271,7 @@ func TestScFinishedEv(t *testing.T) {
{
currentState: &params{height: 100, items: []pcBlock{}, blocksSynced: 100}, event: scFinishedEv{},
wantState: &params{height: 100, items: []pcBlock{}, blocksSynced: 100},
wantNextEvent: pcFinished{tmState: tmState.State{LastBlockHeight: 100}, blocksSynced: 100},
wantNextEvent: pcFinished{tmState: tmstate.State{LastBlockHeight: 100}, blocksSynced: 100},
},
},
},
@@ -282,7 +282,7 @@ func TestScFinishedEv(t *testing.T) {
currentState: &params{height: 100, items: []pcBlock{
{"P1", 101}}, blocksSynced: 100}, event: scFinishedEv{},
wantState: &params{height: 100, items: []pcBlock{{"P1", 101}}, blocksSynced: 100},
wantNextEvent: pcFinished{tmState: tmState.State{LastBlockHeight: 100}, blocksSynced: 100},
wantNextEvent: pcFinished{tmState: tmstate.State{LastBlockHeight: 100}, blocksSynced: 100},
},
},
},
+6 -6
View File
@@ -5,11 +5,11 @@ import (
"fmt"
"time"
proto "github.com/gogo/protobuf/proto"
"github.com/gogo/protobuf/proto"
bc "github.com/tendermint/tendermint/internal/blocksync"
"github.com/tendermint/tendermint/internal/blocksync"
"github.com/tendermint/tendermint/internal/blocksync/v2/internal/behavior"
cons "github.com/tendermint/tendermint/internal/consensus"
"github.com/tendermint/tendermint/internal/consensus"
tmsync "github.com/tendermint/tendermint/internal/libs/sync"
"github.com/tendermint/tendermint/internal/p2p"
"github.com/tendermint/tendermint/internal/state"
@@ -61,7 +61,7 @@ type blockApplier interface {
// XXX: unify naming in this package around tmState
func newReactor(state state.State, store blockStore, reporter behavior.Reporter,
blockApplier blockApplier, blockSync bool, metrics *cons.Metrics) *BlockchainReactor {
blockApplier blockApplier, blockSync bool, metrics *consensus.Metrics) *BlockchainReactor {
initHeight := state.LastBlockHeight + 1
if initHeight == 1 {
initHeight = state.InitialHeight
@@ -91,7 +91,7 @@ func NewBlockchainReactor(
blockApplier blockApplier,
store blockStore,
blockSync bool,
metrics *cons.Metrics) *BlockchainReactor {
metrics *consensus.Metrics) *BlockchainReactor {
reporter := behavior.NewMockReporter()
return newReactor(state, store, reporter, blockApplier, blockSync, metrics)
}
@@ -605,7 +605,7 @@ func (r *BlockchainReactor) GetChannels() []*p2p.ChannelDescriptor {
Priority: 5,
SendQueueCapacity: 2000,
RecvBufferCapacity: 1024,
RecvMessageCapacity: bc.MaxMsgSize,
RecvMessageCapacity: blocksync.MaxMsgSize,
},
}
}
+9 -9
View File
@@ -15,9 +15,9 @@ import (
abciclient "github.com/tendermint/tendermint/abci/client"
abci "github.com/tendermint/tendermint/abci/types"
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/internal/blocksync/v2/internal/behavior"
cons "github.com/tendermint/tendermint/internal/consensus"
"github.com/tendermint/tendermint/internal/consensus"
"github.com/tendermint/tendermint/internal/mempool/mock"
"github.com/tendermint/tendermint/internal/p2p"
"github.com/tendermint/tendermint/internal/p2p/conn"
@@ -177,7 +177,7 @@ func newTestReactor(t *testing.T, p testReactorParams) *BlockchainReactor {
require.NoError(t, err)
}
r := newReactor(state, store, reporter, appl, true, cons.NopMetrics())
r := newReactor(state, store, reporter, appl, true, consensus.NopMetrics())
logger := log.TestingLogger()
r.SetLogger(logger.With("module", "blockchain"))
@@ -365,9 +365,9 @@ func TestReactorHelperMode(t *testing.T) {
channelID = byte(0x40)
)
config := cfg.ResetTestRoot("blockchain_reactor_v2_test")
defer os.RemoveAll(config.RootDir)
genDoc, privVals := factory.RandGenesisDoc(config, 1, false, 30)
cfg := config.ResetTestRoot("blockchain_reactor_v2_test")
defer os.RemoveAll(cfg.RootDir)
genDoc, privVals := factory.RandGenesisDoc(cfg, 1, false, 30)
params := testReactorParams{
logger: log.TestingLogger(),
@@ -455,9 +455,9 @@ func TestReactorHelperMode(t *testing.T) {
}
func TestReactorSetSwitchNil(t *testing.T) {
config := cfg.ResetTestRoot("blockchain_reactor_v2_test")
defer os.RemoveAll(config.RootDir)
genDoc, privVals := factory.RandGenesisDoc(config, 1, false, 30)
cfg := config.ResetTestRoot("blockchain_reactor_v2_test")
defer os.RemoveAll(cfg.RootDir)
genDoc, privVals := factory.RandGenesisDoc(cfg, 1, false, 30)
reactor := newTestReactor(t, testReactorParams{
logger: log.TestingLogger(),
+2 -1
View File
@@ -10,6 +10,8 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
dbm "github.com/tendermint/tm-db"
abciclient "github.com/tendermint/tendermint/abci/client"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/internal/evidence"
@@ -23,7 +25,6 @@ import (
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/tendermint/tendermint/store"
"github.com/tendermint/tendermint/types"
dbm "github.com/tendermint/tm-db"
)
// Byzantine node sends two different prevotes (nil and blockID) to the same
+35 -37
View File
@@ -7,21 +7,19 @@ import (
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
"path"
dbm "github.com/tendermint/tm-db"
abciclient "github.com/tendermint/tendermint/abci/client"
"github.com/tendermint/tendermint/abci/example/kvstore"
abci "github.com/tendermint/tendermint/abci/types"
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/config"
cstypes "github.com/tendermint/tendermint/internal/consensus/types"
tmsync "github.com/tendermint/tendermint/internal/libs/sync"
mempoolv0 "github.com/tendermint/tendermint/internal/mempool/v0"
@@ -49,10 +47,10 @@ const (
// test.
type cleanupFunc func()
func configSetup(t *testing.T) *cfg.Config {
func configSetup(t *testing.T) *config.Config {
t.Helper()
config := ResetConfig("consensus_reactor_test")
cfg := ResetConfig("consensus_reactor_test")
consensusReplayConfig := ResetConfig("consensus_replay_test")
configStateTest := ResetConfig("consensus_state_test")
@@ -60,13 +58,13 @@ func configSetup(t *testing.T) *cfg.Config {
configByzantineTest := ResetConfig("consensus_byzantine_test")
t.Cleanup(func() {
os.RemoveAll(config.RootDir)
os.RemoveAll(cfg.RootDir)
os.RemoveAll(consensusReplayConfig.RootDir)
os.RemoveAll(configStateTest.RootDir)
os.RemoveAll(configMempoolTest.RootDir)
os.RemoveAll(configByzantineTest.RootDir)
})
return config
return cfg
}
func ensureDir(dir string, mode os.FileMode) {
@@ -75,8 +73,8 @@ func ensureDir(dir string, mode os.FileMode) {
}
}
func ResetConfig(name string) *cfg.Config {
return cfg.ResetTestRoot(name)
func ResetConfig(name string) *config.Config {
return config.ResetTestRoot(name)
}
//-------------------------------------------------------------------------------
@@ -102,7 +100,7 @@ func newValidatorStub(privValidator types.PrivValidator, valIndex int32) *valida
}
func (vs *validatorStub) signVote(
config *cfg.Config,
cfg *config.Config,
voteType tmproto.SignedMsgType,
hash []byte,
header types.PartSetHeader) (*types.Vote, error) {
@@ -122,7 +120,7 @@ func (vs *validatorStub) signVote(
BlockID: types.BlockID{Hash: hash, PartSetHeader: header},
}
v := vote.ToProto()
if err := vs.PrivValidator.SignVote(context.Background(), config.ChainID(), v); err != nil {
if err := vs.PrivValidator.SignVote(context.Background(), cfg.ChainID(), v); err != nil {
return nil, fmt.Errorf("sign vote failed: %w", err)
}
@@ -141,12 +139,12 @@ func (vs *validatorStub) signVote(
// Sign vote for type/hash/header
func signVote(
vs *validatorStub,
config *cfg.Config,
cfg *config.Config,
voteType tmproto.SignedMsgType,
hash []byte,
header types.PartSetHeader) *types.Vote {
v, err := vs.signVote(config, voteType, hash, header)
v, err := vs.signVote(cfg, voteType, hash, header)
if err != nil {
panic(fmt.Errorf("failed to sign vote: %v", err))
}
@@ -157,14 +155,14 @@ func signVote(
}
func signVotes(
config *cfg.Config,
cfg *config.Config,
voteType tmproto.SignedMsgType,
hash []byte,
header types.PartSetHeader,
vss ...*validatorStub) []*types.Vote {
votes := make([]*types.Vote, len(vss))
for i, vs := range vss {
votes[i] = signVote(vs, config, voteType, hash, header)
votes[i] = signVote(vs, cfg, voteType, hash, header)
}
return votes
}
@@ -255,14 +253,14 @@ func addVotes(to *State, votes ...*types.Vote) {
}
func signAddVotes(
config *cfg.Config,
cfg *config.Config,
to *State,
voteType tmproto.SignedMsgType,
hash []byte,
header types.PartSetHeader,
vss ...*validatorStub,
) {
votes := signVotes(config, voteType, hash, header, vss...)
votes := signVotes(cfg, voteType, hash, header, vss...)
addVotes(to, votes...)
}
@@ -387,12 +385,12 @@ func subscribeToVoter(cs *State, addr []byte) <-chan tmpubsub.Message {
// consensus states
func newState(state sm.State, pv types.PrivValidator, app abci.Application) *State {
config := cfg.ResetTestRoot("consensus_state_test")
return newStateWithConfig(config, state, pv, app)
cfg := config.ResetTestRoot("consensus_state_test")
return newStateWithConfig(cfg, state, pv, app)
}
func newStateWithConfig(
thisConfig *cfg.Config,
thisConfig *config.Config,
state sm.State,
pv types.PrivValidator,
app abci.Application,
@@ -402,7 +400,7 @@ func newStateWithConfig(
}
func newStateWithConfigAndBlockStore(
thisConfig *cfg.Config,
thisConfig *config.Config,
state sm.State,
pv types.PrivValidator,
app abci.Application,
@@ -444,10 +442,10 @@ func newStateWithConfigAndBlockStore(
return cs
}
func loadPrivValidator(config *cfg.Config) *privval.FilePV {
privValidatorKeyFile := config.PrivValidator.KeyFile()
func loadPrivValidator(cfg *config.Config) *privval.FilePV {
privValidatorKeyFile := cfg.PrivValidator.KeyFile()
ensureDir(filepath.Dir(privValidatorKeyFile), 0700)
privValidatorStateFile := config.PrivValidator.StateFile()
privValidatorStateFile := cfg.PrivValidator.StateFile()
privValidator, err := privval.LoadOrGenFilePV(privValidatorKeyFile, privValidatorStateFile)
if err != nil {
panic(err)
@@ -456,9 +454,9 @@ func loadPrivValidator(config *cfg.Config) *privval.FilePV {
return privValidator
}
func randState(config *cfg.Config, nValidators int) (*State, []*validatorStub) {
func randState(cfg *config.Config, nValidators int) (*State, []*validatorStub) {
// Get State
state, privVals := randGenesisState(config, nValidators, false, 10)
state, privVals := randGenesisState(cfg, nValidators, false, 10)
vss := make([]*validatorStub, nValidators)
@@ -704,15 +702,15 @@ func consensusLogger() log.Logger {
func randConsensusState(
t *testing.T,
config *cfg.Config,
cfg *config.Config,
nValidators int,
testName string,
tickerFunc func() TimeoutTicker,
appFunc func() abci.Application,
configOpts ...func(*cfg.Config),
configOpts ...func(*config.Config),
) ([]*State, cleanupFunc) {
genDoc, privVals := factory.RandGenesisDoc(config, nValidators, false, 30)
genDoc, privVals := factory.RandGenesisDoc(cfg, nValidators, false, 30)
css := make([]*State, nValidators)
logger := consensusLogger()
@@ -759,18 +757,18 @@ func randConsensusState(
// nPeers = nValidators + nNotValidator
func randConsensusNetWithPeers(
config *cfg.Config,
cfg *config.Config,
nValidators,
nPeers int,
testName string,
tickerFunc func() TimeoutTicker,
appFunc func(string) abci.Application,
) ([]*State, *types.GenesisDoc, *cfg.Config, cleanupFunc) {
genDoc, privVals := factory.RandGenesisDoc(config, nValidators, false, testMinPower)
) ([]*State, *types.GenesisDoc, *config.Config, cleanupFunc) {
genDoc, privVals := factory.RandGenesisDoc(cfg, nValidators, false, testMinPower)
css := make([]*State, nPeers)
logger := consensusLogger()
var peer0Config *cfg.Config
var peer0Config *config.Config
configRootDirs := make([]string, 0, nPeers)
for i := 0; i < nPeers; i++ {
state, _ := sm.MakeGenesisState(genDoc)
@@ -799,7 +797,7 @@ func randConsensusNetWithPeers(
}
}
app := appFunc(path.Join(config.DBDir(), fmt.Sprintf("%s_%d", testName, i)))
app := appFunc(path.Join(cfg.DBDir(), fmt.Sprintf("%s_%d", testName, i)))
vals := types.TM2PB.ValidatorUpdates(state.Validators)
if _, ok := app.(*kvstore.PersistentKVStoreApplication); ok {
// simulate handshake, receive app version. If don't do this, replay test will fail
@@ -820,12 +818,12 @@ func randConsensusNetWithPeers(
}
func randGenesisState(
config *cfg.Config,
cfg *config.Config,
numValidators int,
randPower bool,
minPower int64) (sm.State, []types.PrivValidator) {
genDoc, privValidators := factory.RandGenesisDoc(config, numValidators, randPower, minPower)
genDoc, privValidators := factory.RandGenesisDoc(cfg, numValidators, randPower, minPower)
s0, _ := sm.MakeGenesisState(genDoc)
return s0, privValidators
}
+5 -6
View File
@@ -10,20 +10,19 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
dbm "github.com/tendermint/tm-db"
"github.com/tendermint/tendermint/abci/example/code"
abci "github.com/tendermint/tendermint/abci/types"
mempl "github.com/tendermint/tendermint/internal/mempool"
"github.com/tendermint/tendermint/internal/mempool"
sm "github.com/tendermint/tendermint/internal/state"
"github.com/tendermint/tendermint/store"
"github.com/tendermint/tendermint/types"
)
// for testing
func assertMempool(txn txNotifier) mempl.Mempool {
return txn.(mempl.Mempool)
func assertMempool(txn txNotifier) mempool.Mempool {
return txn.(mempool.Mempool)
}
func TestMempoolNoProgressUntilTxsAvailable(t *testing.T) {
@@ -113,7 +112,7 @@ func deliverTxsRange(cs *State, start, end int) {
for i := start; i < end; i++ {
txBytes := make([]byte, 8)
binary.BigEndian.PutUint64(txBytes, uint64(i))
err := assertMempool(cs.txNotifier).CheckTx(context.Background(), txBytes, nil, mempl.TxInfo{})
err := assertMempool(cs.txNotifier).CheckTx(context.Background(), txBytes, nil, mempool.TxInfo{})
if err != nil {
panic(fmt.Sprintf("Error after CheckTx: %v", err))
}
@@ -179,7 +178,7 @@ func TestMempoolRmBadTx(t *testing.T) {
return
}
checkTxRespCh <- struct{}{}
}, mempl.TxInfo{})
}, mempool.TxInfo{})
if err != nil {
t.Errorf("error after CheckTx: %v", err)
return
+22 -22
View File
@@ -12,12 +12,13 @@ import (
"github.com/fortytw2/leaktest"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
dbm "github.com/tendermint/tm-db"
abciclient "github.com/tendermint/tendermint/abci/client"
"github.com/tendermint/tendermint/abci/example/kvstore"
abci "github.com/tendermint/tendermint/abci/types"
cfg "github.com/tendermint/tendermint/config"
cryptoenc "github.com/tendermint/tendermint/crypto/encoding"
"github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/crypto/encoding"
tmsync "github.com/tendermint/tendermint/internal/libs/sync"
"github.com/tendermint/tendermint/internal/mempool"
mempoolv0 "github.com/tendermint/tendermint/internal/mempool/v0"
@@ -31,7 +32,6 @@ import (
tmcons "github.com/tendermint/tendermint/proto/tendermint/consensus"
"github.com/tendermint/tendermint/store"
"github.com/tendermint/tendermint/types"
dbm "github.com/tendermint/tm-db"
)
var (
@@ -273,11 +273,11 @@ func ensureBlockSyncStatus(t *testing.T, msg tmpubsub.Message, complete bool, he
}
func TestReactorBasic(t *testing.T) {
config := configSetup(t)
cfg := configSetup(t)
n := 4
states, cleanup := randConsensusState(t,
config, n, "consensus_reactor_test",
cfg, n, "consensus_reactor_test",
newMockTickerFunc(true), newKVStore)
t.Cleanup(cleanup)
@@ -316,14 +316,14 @@ func TestReactorBasic(t *testing.T) {
}
func TestReactorWithEvidence(t *testing.T) {
config := configSetup(t)
cfg := configSetup(t)
n := 4
testName := "consensus_reactor_test"
tickerFunc := newMockTickerFunc(true)
appFunc := newKVStore
genDoc, privVals := factory.RandGenesisDoc(config, n, false, 30)
genDoc, privVals := factory.RandGenesisDoc(cfg, n, false, 30)
states := make([]*State, n)
logger := consensusLogger()
@@ -360,7 +360,7 @@ func TestReactorWithEvidence(t *testing.T) {
// everyone includes evidence of another double signing
vIdx := (i + 1) % n
ev := types.NewMockDuplicateVoteEvidenceWithValidator(1, defaultTestTime, privVals[vIdx], config.ChainID())
ev := types.NewMockDuplicateVoteEvidenceWithValidator(1, defaultTestTime, privVals[vIdx], cfg.ChainID())
evpool := &statemocks.EvidencePool{}
evpool.On("CheckEvidence", mock.AnythingOfType("types.EvidenceList")).Return(nil)
evpool.On("PendingEvidence", mock.AnythingOfType("int64")).Return([]types.Evidence{
@@ -412,17 +412,17 @@ func TestReactorWithEvidence(t *testing.T) {
}
func TestReactorCreatesBlockWhenEmptyBlocksFalse(t *testing.T) {
config := configSetup(t)
cfg := configSetup(t)
n := 4
states, cleanup := randConsensusState(
t,
config,
cfg,
n,
"consensus_reactor_test",
newMockTickerFunc(true),
newKVStore,
func(c *cfg.Config) {
func(c *config.Config) {
c.Consensus.CreateEmptyBlocks = false
},
)
@@ -462,11 +462,11 @@ func TestReactorCreatesBlockWhenEmptyBlocksFalse(t *testing.T) {
}
func TestReactorRecordsVotesAndBlockParts(t *testing.T) {
config := configSetup(t)
cfg := configSetup(t)
n := 4
states, cleanup := randConsensusState(t,
config, n, "consensus_reactor_test",
cfg, n, "consensus_reactor_test",
newMockTickerFunc(true), newKVStore)
t.Cleanup(cleanup)
@@ -521,12 +521,12 @@ func TestReactorRecordsVotesAndBlockParts(t *testing.T) {
}
func TestReactorVotingPowerChange(t *testing.T) {
config := configSetup(t)
cfg := configSetup(t)
n := 4
states, cleanup := randConsensusState(
t,
config,
cfg,
n,
"consensus_voting_power_changes_test",
newMockTickerFunc(true),
@@ -573,7 +573,7 @@ func TestReactorVotingPowerChange(t *testing.T) {
val1PubKey, err := states[0].privValidator.GetPubKey(context.Background())
require.NoError(t, err)
val1PubKeyABCI, err := cryptoenc.PubKeyToProto(val1PubKey)
val1PubKeyABCI, err := encoding.PubKeyToProto(val1PubKey)
require.NoError(t, err)
updateValidatorTx := kvstore.MakeValSetChangeTx(val1PubKeyABCI, 25)
@@ -622,12 +622,12 @@ func TestReactorVotingPowerChange(t *testing.T) {
}
func TestReactorValidatorSetChanges(t *testing.T) {
config := configSetup(t)
cfg := configSetup(t)
nPeers := 7
nVals := 4
states, _, _, cleanup := randConsensusNetWithPeers(
config,
cfg,
nVals,
nPeers,
"consensus_val_set_changes_test",
@@ -668,7 +668,7 @@ func TestReactorValidatorSetChanges(t *testing.T) {
newValidatorPubKey1, err := states[nVals].privValidator.GetPubKey(context.Background())
require.NoError(t, err)
valPubKey1ABCI, err := cryptoenc.PubKeyToProto(newValidatorPubKey1)
valPubKey1ABCI, err := encoding.PubKeyToProto(newValidatorPubKey1)
require.NoError(t, err)
newValidatorTx1 := kvstore.MakeValSetChangeTx(valPubKey1ABCI, testMinPower)
@@ -701,7 +701,7 @@ func TestReactorValidatorSetChanges(t *testing.T) {
updateValidatorPubKey1, err := states[nVals].privValidator.GetPubKey(context.Background())
require.NoError(t, err)
updatePubKey1ABCI, err := cryptoenc.PubKeyToProto(updateValidatorPubKey1)
updatePubKey1ABCI, err := encoding.PubKeyToProto(updateValidatorPubKey1)
require.NoError(t, err)
updateValidatorTx1 := kvstore.MakeValSetChangeTx(updatePubKey1ABCI, 25)
@@ -721,7 +721,7 @@ func TestReactorValidatorSetChanges(t *testing.T) {
newValidatorPubKey2, err := states[nVals+1].privValidator.GetPubKey(context.Background())
require.NoError(t, err)
newVal2ABCI, err := cryptoenc.PubKeyToProto(newValidatorPubKey2)
newVal2ABCI, err := encoding.PubKeyToProto(newValidatorPubKey2)
require.NoError(t, err)
newValidatorTx2 := kvstore.MakeValSetChangeTx(newVal2ABCI, testMinPower)
@@ -729,7 +729,7 @@ func TestReactorValidatorSetChanges(t *testing.T) {
newValidatorPubKey3, err := states[nVals+2].privValidator.GetPubKey(context.Background())
require.NoError(t, err)
newVal3ABCI, err := cryptoenc.PubKeyToProto(newValidatorPubKey3)
newVal3ABCI, err := encoding.PubKeyToProto(newValidatorPubKey3)
require.NoError(t, err)
newValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, testMinPower)
+9 -9
View File
@@ -12,7 +12,7 @@ import (
dbm "github.com/tendermint/tm-db"
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/internal/proxy"
sm "github.com/tendermint/tendermint/internal/state"
"github.com/tendermint/tendermint/libs/log"
@@ -31,8 +31,8 @@ const (
// replay messages interactively or all at once
// replay the wal file
func RunReplayFile(config cfg.BaseConfig, csConfig *cfg.ConsensusConfig, console bool) {
consensusState := newConsensusStateForReplay(config, csConfig)
func RunReplayFile(cfg config.BaseConfig, csConfig *config.ConsensusConfig, console bool) {
consensusState := newConsensusStateForReplay(cfg, csConfig)
if err := consensusState.ReplayFile(csConfig.WalFile(), console); err != nil {
tmos.Exit(fmt.Sprintf("Error during consensus replay: %v", err))
@@ -286,22 +286,22 @@ func (pb *playback) replayConsoleLoop() int {
//--------------------------------------------------------------------------------
// convenience for replay mode
func newConsensusStateForReplay(config cfg.BaseConfig, csConfig *cfg.ConsensusConfig) *State {
dbType := dbm.BackendType(config.DBBackend)
func newConsensusStateForReplay(cfg config.BaseConfig, csConfig *config.ConsensusConfig) *State {
dbType := dbm.BackendType(cfg.DBBackend)
// Get BlockStore
blockStoreDB, err := dbm.NewDB("blockstore", dbType, config.DBDir())
blockStoreDB, err := dbm.NewDB("blockstore", dbType, cfg.DBDir())
if err != nil {
tmos.Exit(err.Error())
}
blockStore := store.NewBlockStore(blockStoreDB)
// Get State
stateDB, err := dbm.NewDB("state", dbType, config.DBDir())
stateDB, err := dbm.NewDB("state", dbType, cfg.DBDir())
if err != nil {
tmos.Exit(err.Error())
}
stateStore := sm.NewStore(stateDB)
gdoc, err := sm.MakeGenesisDocFromFile(config.GenesisFile())
gdoc, err := sm.MakeGenesisDocFromFile(cfg.GenesisFile())
if err != nil {
tmos.Exit(err.Error())
}
@@ -311,7 +311,7 @@ func newConsensusStateForReplay(config cfg.BaseConfig, csConfig *cfg.ConsensusCo
}
// Create proxyAppConn connection (consensus, mempool, query)
clientCreator, _ := proxy.DefaultClientCreator(config.ProxyApp, config.ABCI, config.DBDir())
clientCreator, _ := proxy.DefaultClientCreator(cfg.ProxyApp, cfg.ABCI, cfg.DBDir())
proxyApp := proxy.NewAppConns(clientCreator)
err = proxyApp.Start()
if err != nil {
+5 -5
View File
@@ -6,7 +6,7 @@ import (
abciclient "github.com/tendermint/tendermint/abci/client"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/internal/libs/clist"
mempl "github.com/tendermint/tendermint/internal/mempool"
"github.com/tendermint/tendermint/internal/mempool"
"github.com/tendermint/tendermint/internal/proxy"
tmstate "github.com/tendermint/tendermint/proto/tendermint/state"
"github.com/tendermint/tendermint/types"
@@ -16,12 +16,12 @@ import (
type emptyMempool struct{}
var _ mempl.Mempool = emptyMempool{}
var _ mempool.Mempool = emptyMempool{}
func (emptyMempool) Lock() {}
func (emptyMempool) Unlock() {}
func (emptyMempool) Size() int { return 0 }
func (emptyMempool) CheckTx(_ context.Context, _ types.Tx, _ func(*abci.Response), _ mempl.TxInfo) error {
func (emptyMempool) CheckTx(_ context.Context, _ types.Tx, _ func(*abci.Response), _ mempool.TxInfo) error {
return nil
}
func (emptyMempool) ReapMaxBytesMaxGas(_, _ int64) types.Txs { return types.Txs{} }
@@ -30,8 +30,8 @@ func (emptyMempool) Update(
_ int64,
_ types.Txs,
_ []*abci.ResponseDeliverTx,
_ mempl.PreCheckFunc,
_ mempl.PostCheckFunc,
_ mempool.PreCheckFunc,
_ mempool.PostCheckFunc,
) error {
return nil
}
+58 -58
View File
@@ -22,10 +22,10 @@ import (
abciclient "github.com/tendermint/tendermint/abci/client"
"github.com/tendermint/tendermint/abci/example/kvstore"
abci "github.com/tendermint/tendermint/abci/types"
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/crypto"
cryptoenc "github.com/tendermint/tendermint/crypto/encoding"
mempl "github.com/tendermint/tendermint/internal/mempool"
"github.com/tendermint/tendermint/crypto/encoding"
"github.com/tendermint/tendermint/internal/mempool"
"github.com/tendermint/tendermint/internal/proxy"
sm "github.com/tendermint/tendermint/internal/state"
sf "github.com/tendermint/tendermint/internal/state/test/factory"
@@ -54,7 +54,7 @@ import (
// and which ones we need the wal for - then we'd also be able to only flush the
// wal writer when we need to, instead of with every message.
func startNewStateAndWaitForBlock(t *testing.T, consensusReplayConfig *cfg.Config,
func startNewStateAndWaitForBlock(t *testing.T, consensusReplayConfig *config.Config,
lastBlockHeight int64, blockDB dbm.DB, stateStore sm.Store) {
logger := log.TestingLogger()
state, err := sm.MakeGenesisStateFromFile(consensusReplayConfig.GenesisFile())
@@ -103,7 +103,7 @@ func sendTxs(ctx context.Context, cs *State) {
return
default:
tx := []byte{byte(i)}
if err := assertMempool(cs.txNotifier).CheckTx(context.Background(), tx, nil, mempl.TxInfo{}); err != nil {
if err := assertMempool(cs.txNotifier).CheckTx(context.Background(), tx, nil, mempool.TxInfo{}); err != nil {
panic(err)
}
i++
@@ -137,7 +137,7 @@ func TestWALCrash(t *testing.T) {
}
}
func crashWALandCheckLiveness(t *testing.T, consensusReplayConfig *cfg.Config,
func crashWALandCheckLiveness(t *testing.T, consensusReplayConfig *config.Config,
initFn func(dbm.DB, *State, context.Context), heightToStop int64) {
walPanicked := make(chan error)
crashingWal := &crashingWAL{panicCh: walPanicked, heightToStop: heightToStop}
@@ -286,12 +286,12 @@ func (w *crashingWAL) Wait() { w.next.Wait() }
//------------------------------------------------------------------------------------------
type simulatorTestSuite struct {
GenesisState sm.State
Config *cfg.Config
Config *config.Config
Chain []*types.Block
Commits []*types.Commit
CleanupFunc cleanupFunc
Mempool mempl.Mempool
Mempool mempool.Mempool
Evpool sm.EvidencePool
}
@@ -311,7 +311,7 @@ var modes = []uint{0, 1, 2, 3}
// This is actually not a test, it's for storing validator change tx data for testHandshakeReplay
func setupSimulator(t *testing.T) *simulatorTestSuite {
t.Helper()
config := configSetup(t)
cfg := configSetup(t)
sim := &simulatorTestSuite{
Mempool: emptyMempool{},
@@ -321,14 +321,14 @@ func setupSimulator(t *testing.T) *simulatorTestSuite {
nPeers := 7
nVals := 4
css, genDoc, config, cleanup := randConsensusNetWithPeers(
config,
css, genDoc, cfg, cleanup := randConsensusNetWithPeers(
cfg,
nVals,
nPeers,
"replay_test",
newMockTickerFunc(true),
newPersistentKVStoreWithPath)
sim.Config = config
sim.Config = cfg
sim.GenesisState, _ = sm.MakeGenesisState(genDoc)
sim.CleanupFunc = cleanup
@@ -361,10 +361,10 @@ func setupSimulator(t *testing.T) *simulatorTestSuite {
incrementHeight(vss...)
newValidatorPubKey1, err := css[nVals].privValidator.GetPubKey(context.Background())
require.NoError(t, err)
valPubKey1ABCI, err := cryptoenc.PubKeyToProto(newValidatorPubKey1)
valPubKey1ABCI, err := encoding.PubKeyToProto(newValidatorPubKey1)
require.NoError(t, err)
newValidatorTx1 := kvstore.MakeValSetChangeTx(valPubKey1ABCI, testMinPower)
err = assertMempool(css[0].txNotifier).CheckTx(context.Background(), newValidatorTx1, nil, mempl.TxInfo{})
err = assertMempool(css[0].txNotifier).CheckTx(context.Background(), newValidatorTx1, nil, mempool.TxInfo{})
assert.Nil(t, err)
propBlock, _ := css[0].createProposalBlock() // changeProposer(t, cs1, vs2)
propBlockParts := propBlock.MakePartSet(partSize)
@@ -372,7 +372,7 @@ func setupSimulator(t *testing.T) *simulatorTestSuite {
proposal := types.NewProposal(vss[1].Height, round, -1, blockID)
p := proposal.ToProto()
if err := vss[1].SignProposal(context.Background(), config.ChainID(), p); err != nil {
if err := vss[1].SignProposal(context.Background(), cfg.ChainID(), p); err != nil {
t.Fatal("failed to sign bad proposal", err)
}
proposal.Signature = p.Signature
@@ -393,10 +393,10 @@ func setupSimulator(t *testing.T) *simulatorTestSuite {
incrementHeight(vss...)
updateValidatorPubKey1, err := css[nVals].privValidator.GetPubKey(context.Background())
require.NoError(t, err)
updatePubKey1ABCI, err := cryptoenc.PubKeyToProto(updateValidatorPubKey1)
updatePubKey1ABCI, err := encoding.PubKeyToProto(updateValidatorPubKey1)
require.NoError(t, err)
updateValidatorTx1 := kvstore.MakeValSetChangeTx(updatePubKey1ABCI, 25)
err = assertMempool(css[0].txNotifier).CheckTx(context.Background(), updateValidatorTx1, nil, mempl.TxInfo{})
err = assertMempool(css[0].txNotifier).CheckTx(context.Background(), updateValidatorTx1, nil, mempool.TxInfo{})
assert.Nil(t, err)
propBlock, _ = css[0].createProposalBlock() // changeProposer(t, cs1, vs2)
propBlockParts = propBlock.MakePartSet(partSize)
@@ -404,7 +404,7 @@ func setupSimulator(t *testing.T) *simulatorTestSuite {
proposal = types.NewProposal(vss[2].Height, round, -1, blockID)
p = proposal.ToProto()
if err := vss[2].SignProposal(context.Background(), config.ChainID(), p); err != nil {
if err := vss[2].SignProposal(context.Background(), cfg.ChainID(), p); err != nil {
t.Fatal("failed to sign bad proposal", err)
}
proposal.Signature = p.Signature
@@ -425,17 +425,17 @@ func setupSimulator(t *testing.T) *simulatorTestSuite {
incrementHeight(vss...)
newValidatorPubKey2, err := css[nVals+1].privValidator.GetPubKey(context.Background())
require.NoError(t, err)
newVal2ABCI, err := cryptoenc.PubKeyToProto(newValidatorPubKey2)
newVal2ABCI, err := encoding.PubKeyToProto(newValidatorPubKey2)
require.NoError(t, err)
newValidatorTx2 := kvstore.MakeValSetChangeTx(newVal2ABCI, testMinPower)
err = assertMempool(css[0].txNotifier).CheckTx(context.Background(), newValidatorTx2, nil, mempl.TxInfo{})
err = assertMempool(css[0].txNotifier).CheckTx(context.Background(), newValidatorTx2, nil, mempool.TxInfo{})
assert.Nil(t, err)
newValidatorPubKey3, err := css[nVals+2].privValidator.GetPubKey(context.Background())
require.NoError(t, err)
newVal3ABCI, err := cryptoenc.PubKeyToProto(newValidatorPubKey3)
newVal3ABCI, err := encoding.PubKeyToProto(newValidatorPubKey3)
require.NoError(t, err)
newValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, testMinPower)
err = assertMempool(css[0].txNotifier).CheckTx(context.Background(), newValidatorTx3, nil, mempl.TxInfo{})
err = assertMempool(css[0].txNotifier).CheckTx(context.Background(), newValidatorTx3, nil, mempool.TxInfo{})
assert.Nil(t, err)
propBlock, _ = css[0].createProposalBlock() // changeProposer(t, cs1, vs2)
propBlockParts = propBlock.MakePartSet(partSize)
@@ -463,7 +463,7 @@ func setupSimulator(t *testing.T) *simulatorTestSuite {
proposal = types.NewProposal(vss[3].Height, round, -1, blockID)
p = proposal.ToProto()
if err := vss[3].SignProposal(context.Background(), config.ChainID(), p); err != nil {
if err := vss[3].SignProposal(context.Background(), cfg.ChainID(), p); err != nil {
t.Fatal("failed to sign bad proposal", err)
}
proposal.Signature = p.Signature
@@ -475,7 +475,7 @@ func setupSimulator(t *testing.T) *simulatorTestSuite {
ensureNewProposal(proposalCh, height, round)
removeValidatorTx2 := kvstore.MakeValSetChangeTx(newVal2ABCI, 0)
err = assertMempool(css[0].txNotifier).CheckTx(context.Background(), removeValidatorTx2, nil, mempl.TxInfo{})
err = assertMempool(css[0].txNotifier).CheckTx(context.Background(), removeValidatorTx2, nil, mempool.TxInfo{})
assert.Nil(t, err)
rs = css[0].GetRoundState()
@@ -514,7 +514,7 @@ func setupSimulator(t *testing.T) *simulatorTestSuite {
height++
incrementHeight(vss...)
removeValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, 0)
err = assertMempool(css[0].txNotifier).CheckTx(context.Background(), removeValidatorTx3, nil, mempl.TxInfo{})
err = assertMempool(css[0].txNotifier).CheckTx(context.Background(), removeValidatorTx3, nil, mempool.TxInfo{})
assert.Nil(t, err)
propBlock, _ = css[0].createProposalBlock() // changeProposer(t, cs1, vs2)
propBlockParts = propBlock.MakePartSet(partSize)
@@ -526,7 +526,7 @@ func setupSimulator(t *testing.T) *simulatorTestSuite {
selfIndex = valIndexFn(0)
proposal = types.NewProposal(vss[1].Height, round, -1, blockID)
p = proposal.ToProto()
if err := vss[1].SignProposal(context.Background(), config.ChainID(), p); err != nil {
if err := vss[1].SignProposal(context.Background(), cfg.ChainID(), p); err != nil {
t.Fatal("failed to sign bad proposal", err)
}
proposal.Signature = p.Signature
@@ -611,8 +611,8 @@ func TestHandshakeReplayNone(t *testing.T) {
// Test mockProxyApp should not panic when app return ABCIResponses with some empty ResponseDeliverTx
func TestMockProxyApp(t *testing.T) {
sim := setupSimulator(t) // setup config and simulator
config := sim.Config
assert.NotNil(t, config)
cfg := sim.Config
assert.NotNil(t, cfg)
logger := log.TestingLogger()
var validTxs, invalidTxs = 0, 0
@@ -687,7 +687,7 @@ func testHandshakeReplay(t *testing.T, sim *simulatorTestSuite, nBlocks int, mod
var stateDB dbm.DB
var genesisState sm.State
config := sim.Config
cfg := sim.Config
if testValidatorsChange {
testConfig := ResetConfig(fmt.Sprintf("%s_%v_m", t.Name(), mode))
@@ -695,19 +695,19 @@ func testHandshakeReplay(t *testing.T, sim *simulatorTestSuite, nBlocks int, mod
stateDB = dbm.NewMemDB()
genesisState = sim.GenesisState
config = sim.Config
cfg = sim.Config
chain = append([]*types.Block{}, sim.Chain...) // copy chain
commits = sim.Commits
store = newMockBlockStore(config, genesisState.ConsensusParams)
store = newMockBlockStore(cfg, genesisState.ConsensusParams)
} else { // test single node
testConfig := ResetConfig(fmt.Sprintf("%s_%v_s", t.Name(), mode))
defer func() { _ = os.RemoveAll(testConfig.RootDir) }()
walBody, err := WALWithNBlocks(t, numBlocks)
require.NoError(t, err)
walFile := tempWALWithData(walBody)
config.Consensus.SetWalFile(walFile)
cfg.Consensus.SetWalFile(walFile)
privVal, err := privval.LoadFilePV(config.PrivValidator.KeyFile(), config.PrivValidator.StateFile())
privVal, err := privval.LoadFilePV(cfg.PrivValidator.KeyFile(), cfg.PrivValidator.StateFile())
require.NoError(t, err)
wal, err := NewWAL(walFile)
@@ -724,7 +724,7 @@ func testHandshakeReplay(t *testing.T, sim *simulatorTestSuite, nBlocks int, mod
require.NoError(t, err)
pubKey, err := privVal.GetPubKey(context.Background())
require.NoError(t, err)
stateDB, genesisState, store = stateAndStore(config, pubKey, kvstore.ProtocolVersion)
stateDB, genesisState, store = stateAndStore(cfg, pubKey, kvstore.ProtocolVersion)
}
stateStore := sm.NewStore(stateDB)
@@ -733,12 +733,12 @@ func testHandshakeReplay(t *testing.T, sim *simulatorTestSuite, nBlocks int, mod
state := genesisState.Copy()
// run the chain through state.ApplyBlock to build up the tendermint state
state = buildTMStateFromChain(config, sim.Mempool, sim.Evpool, stateStore, state, chain, nBlocks, mode, store)
state = buildTMStateFromChain(cfg, sim.Mempool, sim.Evpool, stateStore, state, chain, nBlocks, mode, store)
latestAppHash := state.AppHash
// make a new client creator
kvstoreApp := kvstore.NewPersistentKVStoreApplication(
filepath.Join(config.DBDir(), fmt.Sprintf("replay_test_%d_%d_a_r%d", nBlocks, mode, rand.Int())))
filepath.Join(cfg.DBDir(), fmt.Sprintf("replay_test_%d_%d_a_r%d", nBlocks, mode, rand.Int())))
t.Cleanup(func() { require.NoError(t, kvstoreApp.Close()) })
clientCreator2 := abciclient.NewLocalCreator(kvstoreApp)
@@ -763,7 +763,7 @@ func testHandshakeReplay(t *testing.T, sim *simulatorTestSuite, nBlocks int, mod
}
// now start the app using the handshake - it should sync
genDoc, _ := sm.MakeGenesisDocFromFile(config.GenesisFile())
genDoc, _ := sm.MakeGenesisDocFromFile(cfg.GenesisFile())
handshaker := NewHandshaker(stateStore, state, store, genDoc)
proxyApp := proxy.NewAppConns(clientCreator2)
if err := proxyApp.Start(); err != nil {
@@ -811,7 +811,7 @@ func testHandshakeReplay(t *testing.T, sim *simulatorTestSuite, nBlocks int, mod
}
func applyBlock(stateStore sm.Store,
mempool mempl.Mempool,
mempool mempool.Mempool,
evpool sm.EvidencePool,
st sm.State,
blk *types.Block,
@@ -831,7 +831,7 @@ func applyBlock(stateStore sm.Store,
func buildAppStateFromChain(
proxyApp proxy.AppConns,
stateStore sm.Store,
mempool mempl.Mempool,
mempool mempool.Mempool,
evpool sm.EvidencePool,
state sm.State,
chain []*types.Block,
@@ -878,8 +878,8 @@ func buildAppStateFromChain(
}
func buildTMStateFromChain(
config *cfg.Config,
mempool mempl.Mempool,
cfg *config.Config,
mempool mempool.Mempool,
evpool sm.EvidencePool,
stateStore sm.Store,
state sm.State,
@@ -889,7 +889,7 @@ func buildTMStateFromChain(
blockStore *mockBlockStore) sm.State {
// run the whole chain against this client to build up the tendermint state
kvstoreApp := kvstore.NewPersistentKVStoreApplication(
filepath.Join(config.DBDir(), fmt.Sprintf("replay_test_%d_%d_t", nBlocks, mode)))
filepath.Join(cfg.DBDir(), fmt.Sprintf("replay_test_%d_%d_t", nBlocks, mode)))
defer kvstoreApp.Close()
clientCreator := abciclient.NewLocalCreator(kvstoreApp)
@@ -938,16 +938,16 @@ func TestHandshakePanicsIfAppReturnsWrongAppHash(t *testing.T) {
// - 0x01
// - 0x02
// - 0x03
config := ResetConfig("handshake_test_")
t.Cleanup(func() { os.RemoveAll(config.RootDir) })
privVal, err := privval.LoadFilePV(config.PrivValidator.KeyFile(), config.PrivValidator.StateFile())
cfg := ResetConfig("handshake_test_")
t.Cleanup(func() { os.RemoveAll(cfg.RootDir) })
privVal, err := privval.LoadFilePV(cfg.PrivValidator.KeyFile(), cfg.PrivValidator.StateFile())
require.NoError(t, err)
const appVersion = 0x0
pubKey, err := privVal.GetPubKey(context.Background())
require.NoError(t, err)
stateDB, state, store := stateAndStore(config, pubKey, appVersion)
stateDB, state, store := stateAndStore(cfg, pubKey, appVersion)
stateStore := sm.NewStore(stateDB)
genDoc, _ := sm.MakeGenesisDocFromFile(config.GenesisFile())
genDoc, _ := sm.MakeGenesisDocFromFile(cfg.GenesisFile())
state.LastValidators = state.Validators.Copy()
// mode = 0 for committing all the blocks
blocks := sf.MakeBlocks(3, &state, privVal)
@@ -1153,14 +1153,14 @@ func readPieceFromWAL(msg *TimedWALMessage) interface{} {
// fresh state and mock store
func stateAndStore(
config *cfg.Config,
cfg *config.Config,
pubKey crypto.PubKey,
appVersion uint64) (dbm.DB, sm.State, *mockBlockStore) {
stateDB := dbm.NewMemDB()
stateStore := sm.NewStore(stateDB)
state, _ := sm.MakeGenesisStateFromFile(config.GenesisFile())
state, _ := sm.MakeGenesisStateFromFile(cfg.GenesisFile())
state.Version.Consensus.App = appVersion
store := newMockBlockStore(config, state.ConsensusParams)
store := newMockBlockStore(cfg, state.ConsensusParams)
if err := stateStore.Save(state); err != nil {
panic(err)
}
@@ -1171,7 +1171,7 @@ func stateAndStore(
// mock block store
type mockBlockStore struct {
config *cfg.Config
cfg *config.Config
params types.ConsensusParams
chain []*types.Block
commits []*types.Commit
@@ -1179,8 +1179,8 @@ type mockBlockStore struct {
}
// TODO: NewBlockStore(db.NewMemDB) ...
func newMockBlockStore(config *cfg.Config, params types.ConsensusParams) *mockBlockStore {
return &mockBlockStore{config, params, nil, nil, 0}
func newMockBlockStore(cfg *config.Config, params types.ConsensusParams) *mockBlockStore {
return &mockBlockStore{cfg, params, nil, nil, 0}
}
func (bs *mockBlockStore) Height() int64 { return int64(len(bs.chain)) }
@@ -1228,20 +1228,20 @@ func TestHandshakeUpdatesValidators(t *testing.T) {
app := &initChainApp{vals: types.TM2PB.ValidatorUpdates(vals)}
clientCreator := abciclient.NewLocalCreator(app)
config := ResetConfig("handshake_test_")
t.Cleanup(func() { _ = os.RemoveAll(config.RootDir) })
cfg := ResetConfig("handshake_test_")
t.Cleanup(func() { _ = os.RemoveAll(cfg.RootDir) })
privVal, err := privval.LoadFilePV(config.PrivValidator.KeyFile(), config.PrivValidator.StateFile())
privVal, err := privval.LoadFilePV(cfg.PrivValidator.KeyFile(), cfg.PrivValidator.StateFile())
require.NoError(t, err)
pubKey, err := privVal.GetPubKey(context.Background())
require.NoError(t, err)
stateDB, state, store := stateAndStore(config, pubKey, 0x0)
stateDB, state, store := stateAndStore(cfg, pubKey, 0x0)
stateStore := sm.NewStore(stateDB)
oldValAddr := state.Validators.Validators[0].Address
// now start the app using the handshake - it should sync
genDoc, _ := sm.MakeGenesisDocFromFile(config.GenesisFile())
genDoc, _ := sm.MakeGenesisDocFromFile(cfg.GenesisFile())
handshaker := NewHandshaker(stateStore, state, store, genDoc)
proxyApp := proxy.NewAppConns(clientCreator)
if err := proxyApp.Start(); err != nil {
+4 -4
View File
@@ -12,7 +12,7 @@ import (
"github.com/gogo/protobuf/proto"
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/crypto"
cstypes "github.com/tendermint/tendermint/internal/consensus/types"
"github.com/tendermint/tendermint/internal/libs/fail"
@@ -80,7 +80,7 @@ type State struct {
service.BaseService
// config details
config *cfg.ConsensusConfig
config *config.ConsensusConfig
privValidator types.PrivValidator // for signing votes
privValidatorType types.PrivValidatorType
@@ -152,7 +152,7 @@ type StateOption func(*State)
// NewState returns a new State.
func NewState(
config *cfg.ConsensusConfig,
cfg *config.ConsensusConfig,
state sm.State,
blockExec *sm.BlockExecutor,
blockStore sm.BlockStore,
@@ -161,7 +161,7 @@ func NewState(
options ...StateOption,
) *State {
cs := &State{
config: config,
config: cfg,
blockExec: blockExec,
blockStore: blockStore,
txNotifier: txNotifier,
@@ -6,7 +6,7 @@ import (
"os"
"testing"
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/crypto/tmhash"
"github.com/tendermint/tendermint/internal/test/factory"
tmrand "github.com/tendermint/tendermint/libs/rand"
@@ -15,19 +15,19 @@ import (
"github.com/tendermint/tendermint/types"
)
var config *cfg.Config // NOTE: must be reset for each _test.go file
var cfg *config.Config // NOTE: must be reset for each _test.go file
func TestMain(m *testing.M) {
config = cfg.ResetTestRoot("consensus_height_vote_set_test")
cfg = config.ResetTestRoot("consensus_height_vote_set_test")
code := m.Run()
os.RemoveAll(config.RootDir)
os.RemoveAll(cfg.RootDir)
os.Exit(code)
}
func TestPeerCatchupRounds(t *testing.T) {
valSet, privVals := factory.RandValidatorSet(10, 1)
hvs := NewHeightVoteSet(config.ChainID(), 1, valSet)
hvs := NewHeightVoteSet(cfg.ChainID(), 1, valSet)
vote999_0 := makeVoteHR(t, 1, 0, 999, privVals)
added, err := hvs.AddVote(vote999_0, "peer1")
@@ -75,7 +75,7 @@ func makeVoteHR(t *testing.T, height int64, valIndex, round int32, privVals []ty
Type: tmproto.PrecommitType,
BlockID: types.BlockID{Hash: randBytes, PartSetHeader: types.PartSetHeader{}},
}
chainID := config.ChainID()
chainID := cfg.ChainID()
v := vote.ToProto()
err = privVal.SignVote(context.Background(), chainID, v)
+11 -11
View File
@@ -11,11 +11,11 @@ import (
"time"
"github.com/stretchr/testify/require"
db "github.com/tendermint/tm-db"
dbm "github.com/tendermint/tm-db"
abciclient "github.com/tendermint/tendermint/abci/client"
"github.com/tendermint/tendermint/abci/example/kvstore"
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/internal/proxy"
sm "github.com/tendermint/tendermint/internal/state"
"github.com/tendermint/tendermint/libs/log"
@@ -30,9 +30,9 @@ import (
// (byteBufferWAL) and waits until numBlocks are created.
// If the node fails to produce given numBlocks, it returns an error.
func WALGenerateNBlocks(t *testing.T, wr io.Writer, numBlocks int) (err error) {
config := getConfig(t)
cfg := getConfig(t)
app := kvstore.NewPersistentKVStoreApplication(filepath.Join(config.DBDir(), "wal_generator"))
app := kvstore.NewPersistentKVStoreApplication(filepath.Join(cfg.DBDir(), "wal_generator"))
t.Cleanup(func() { require.NoError(t, app.Close()) })
logger := log.TestingLogger().With("wal_generator", "wal_generator")
@@ -41,17 +41,17 @@ func WALGenerateNBlocks(t *testing.T, wr io.Writer, numBlocks int) (err error) {
// COPY PASTE FROM node.go WITH A FEW MODIFICATIONS
// NOTE: we can't import node package because of circular dependency.
// NOTE: we don't do handshake so need to set state.Version.Consensus.App directly.
privValidatorKeyFile := config.PrivValidator.KeyFile()
privValidatorStateFile := config.PrivValidator.StateFile()
privValidatorKeyFile := cfg.PrivValidator.KeyFile()
privValidatorStateFile := cfg.PrivValidator.StateFile()
privValidator, err := privval.LoadOrGenFilePV(privValidatorKeyFile, privValidatorStateFile)
if err != nil {
return err
}
genDoc, err := types.GenesisDocFromFile(config.GenesisFile())
genDoc, err := types.GenesisDocFromFile(cfg.GenesisFile())
if err != nil {
return fmt.Errorf("failed to read genesis file: %w", err)
}
blockStoreDB := db.NewMemDB()
blockStoreDB := dbm.NewMemDB()
stateDB := blockStoreDB
stateStore := sm.NewStore(stateDB)
state, err := sm.MakeGenesisState(genDoc)
@@ -89,7 +89,7 @@ func WALGenerateNBlocks(t *testing.T, wr io.Writer, numBlocks int) (err error) {
mempool := emptyMempool{}
evpool := sm.EmptyEvidencePool{}
blockExec := sm.NewBlockExecutor(stateStore, log.TestingLogger(), proxyApp.Consensus(), mempool, evpool, blockStore)
consensusState := NewState(config.Consensus, state.Copy(), blockExec, blockStore, mempool, evpool)
consensusState := NewState(cfg.Consensus, state.Copy(), blockExec, blockStore, mempool, evpool)
consensusState.SetLogger(logger)
consensusState.SetEventBus(eventBus)
if privValidator != nil && privValidator != (*privval.FilePV)(nil) {
@@ -153,8 +153,8 @@ func makeAddrs() (string, string, string) {
}
// getConfig returns a config for test cases
func getConfig(t *testing.T) *cfg.Config {
c := cfg.ResetTestRoot(t.Name())
func getConfig(t *testing.T) *config.Config {
c := config.ResetTestRoot(t.Name())
// and we use random ports to run in parallel
tm, rpc, grpc := makeAddrs()
-1
View File
@@ -8,7 +8,6 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
dbm "github.com/tendermint/tm-db"
"github.com/tendermint/tendermint/crypto"
+5 -5
View File
@@ -5,19 +5,19 @@ import (
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/internal/libs/clist"
mempl "github.com/tendermint/tendermint/internal/mempool"
"github.com/tendermint/tendermint/internal/mempool"
"github.com/tendermint/tendermint/types"
)
// Mempool is an empty implementation of a Mempool, useful for testing.
type Mempool struct{}
var _ mempl.Mempool = Mempool{}
var _ mempool.Mempool = Mempool{}
func (Mempool) Lock() {}
func (Mempool) Unlock() {}
func (Mempool) Size() int { return 0 }
func (Mempool) CheckTx(_ context.Context, _ types.Tx, _ func(*abci.Response), _ mempl.TxInfo) error {
func (Mempool) CheckTx(_ context.Context, _ types.Tx, _ func(*abci.Response), _ mempool.TxInfo) error {
return nil
}
func (Mempool) ReapMaxBytesMaxGas(_, _ int64) types.Txs { return types.Txs{} }
@@ -26,8 +26,8 @@ func (Mempool) Update(
_ int64,
_ types.Txs,
_ []*abci.ResponseDeliverTx,
_ mempl.PreCheckFunc,
_ mempl.PostCheckFunc,
_ mempool.PreCheckFunc,
_ mempool.PostCheckFunc,
) error {
return nil
}
+6 -6
View File
@@ -8,7 +8,7 @@ import (
"sync/atomic"
abci "github.com/tendermint/tendermint/abci/types"
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/internal/libs/clist"
tmsync "github.com/tendermint/tendermint/internal/libs/sync"
"github.com/tendermint/tendermint/internal/mempool"
@@ -32,7 +32,7 @@ type CListMempool struct {
notifiedTxsAvailable bool
txsAvailable chan struct{} // fires once for each height, when the mempool is not empty
config *cfg.MempoolConfig
config *config.MempoolConfig
// Exclusive mutex for Update method to prevent concurrent execution of
// CheckTx or ReapMaxBytesMaxGas(ReapMaxTxs) methods.
@@ -69,14 +69,14 @@ type CListMempoolOption func(*CListMempool)
// NewCListMempool returns a new mempool with the given configuration and
// connection to an application.
func NewCListMempool(
config *cfg.MempoolConfig,
cfg *config.MempoolConfig,
proxyAppConn proxy.AppConnMempool,
height int64,
options ...CListMempoolOption,
) *CListMempool {
mp := &CListMempool{
config: config,
config: cfg,
proxyAppConn: proxyAppConn,
txs: clist.New(),
height: height,
@@ -86,8 +86,8 @@ func NewCListMempool(
metrics: mempool.NopMetrics(),
}
if config.CacheSize > 0 {
mp.cache = mempool.NewLRUTxCache(config.CacheSize)
if cfg.CacheSize > 0 {
mp.cache = mempool.NewLRUTxCache(cfg.CacheSize)
} else {
mp.cache = mempool.NopTxCache{}
}
+12 -12
View File
@@ -19,7 +19,7 @@ import (
"github.com/tendermint/tendermint/abci/example/kvstore"
abciserver "github.com/tendermint/tendermint/abci/server"
abci "github.com/tendermint/tendermint/abci/types"
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/internal/mempool"
"github.com/tendermint/tendermint/libs/log"
tmrand "github.com/tendermint/tendermint/libs/rand"
@@ -32,10 +32,10 @@ import (
type cleanupFunc func()
func newMempoolWithApp(cc abciclient.Creator) (*CListMempool, cleanupFunc) {
return newMempoolWithAppAndConfig(cc, cfg.ResetTestRoot("mempool_test"))
return newMempoolWithAppAndConfig(cc, config.ResetTestRoot("mempool_test"))
}
func newMempoolWithAppAndConfig(cc abciclient.Creator, config *cfg.Config) (*CListMempool, cleanupFunc) {
func newMempoolWithAppAndConfig(cc abciclient.Creator, cfg *config.Config) (*CListMempool, cleanupFunc) {
appConnMem, _ := cc()
appConnMem.SetLogger(log.TestingLogger().With("module", "abci-client", "connection", "mempool"))
err := appConnMem.Start()
@@ -43,10 +43,10 @@ func newMempoolWithAppAndConfig(cc abciclient.Creator, config *cfg.Config) (*CLi
panic(err)
}
mp := NewCListMempool(config.Mempool, appConnMem, 0)
mp := NewCListMempool(cfg.Mempool, appConnMem, 0)
mp.SetLogger(log.TestingLogger())
return mp, func() { os.RemoveAll(config.RootDir) }
return mp, func() { os.RemoveAll(cfg.RootDir) }
}
func ensureNoFire(t *testing.T, ch <-chan struct{}, timeoutMS int) {
@@ -217,7 +217,7 @@ func TestMempoolUpdate(t *testing.T) {
func TestMempool_KeepInvalidTxsInCache(t *testing.T) {
app := kvstore.NewApplication()
cc := abciclient.NewLocalCreator(app)
wcfg := cfg.DefaultConfig()
wcfg := config.DefaultConfig()
wcfg.Mempool.KeepInvalidTxsInCache = true
mp, cleanup := newMempoolWithAppAndConfig(cc, wcfg)
defer cleanup()
@@ -465,9 +465,9 @@ func TestMempool_CheckTxChecksTxSize(t *testing.T) {
func TestMempoolTxsBytes(t *testing.T) {
app := kvstore.NewApplication()
cc := abciclient.NewLocalCreator(app)
config := cfg.ResetTestRoot("mempool_test")
config.Mempool.MaxTxsBytes = 10
mp, cleanup := newMempoolWithAppAndConfig(cc, config)
cfg := config.ResetTestRoot("mempool_test")
cfg.Mempool.MaxTxsBytes = 10
mp, cleanup := newMempoolWithAppAndConfig(cc, cfg)
defer cleanup()
// 1. zero by default
@@ -564,8 +564,8 @@ func TestMempoolRemoteAppConcurrency(t *testing.T) {
t.Error(err)
}
})
config := cfg.ResetTestRoot("mempool_test")
mp, cleanup := newMempoolWithAppAndConfig(cc, config)
cfg := config.ResetTestRoot("mempool_test")
mp, cleanup := newMempoolWithAppAndConfig(cc, cfg)
defer cleanup()
// generate small number of txs
@@ -577,7 +577,7 @@ func TestMempoolRemoteAppConcurrency(t *testing.T) {
}
// simulate a group of peers sending them over and over
N := config.Mempool.Size
N := cfg.Mempool.Size
maxPeers := 5
for i := 0; i < N; i++ {
peerID := mrand.Intn(maxPeers)
+8 -8
View File
@@ -8,7 +8,7 @@ import (
"sync"
"time"
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/internal/libs/clist"
tmsync "github.com/tendermint/tendermint/internal/libs/sync"
"github.com/tendermint/tendermint/internal/mempool"
@@ -37,7 +37,7 @@ type PeerManager interface {
type Reactor struct {
service.BaseService
config *cfg.MempoolConfig
cfg *config.MempoolConfig
mempool *CListMempool
ids *mempool.MempoolIDs
@@ -61,7 +61,7 @@ type Reactor struct {
// NewReactor returns a reference to a new reactor.
func NewReactor(
logger log.Logger,
config *cfg.MempoolConfig,
cfg *config.MempoolConfig,
peerMgr PeerManager,
mp *CListMempool,
mempoolCh *p2p.Channel,
@@ -69,7 +69,7 @@ func NewReactor(
) *Reactor {
r := &Reactor{
config: config,
cfg: cfg,
peerMgr: peerMgr,
mempool: mp,
ids: mempool.NewMempoolIDs(),
@@ -90,8 +90,8 @@ func NewReactor(
//
// TODO: Remove once p2p refactor is complete.
// ref: https://github.com/tendermint/tendermint/issues/5670
func GetChannelShims(config *cfg.MempoolConfig) map[p2p.ChannelID]*p2p.ChannelDescriptorShim {
largestTx := make([]byte, config.MaxTxBytes)
func GetChannelShims(cfg *config.MempoolConfig) map[p2p.ChannelID]*p2p.ChannelDescriptorShim {
largestTx := make([]byte, cfg.MaxTxBytes)
batchMsg := protomem.Message{
Sum: &protomem.Message_Txs{
Txs: &protomem.Txs{Txs: [][]byte{largestTx}},
@@ -117,7 +117,7 @@ func GetChannelShims(config *cfg.MempoolConfig) map[p2p.ChannelID]*p2p.ChannelDe
// messages on that p2p channel accordingly. The caller must be sure to execute
// OnStop to ensure the outbound p2p Channels are closed.
func (r *Reactor) OnStart() error {
if !r.config.Broadcast {
if !r.cfg.Broadcast {
r.Logger.Info("tx broadcasting is disabled")
}
@@ -254,7 +254,7 @@ func (r *Reactor) processPeerUpdate(peerUpdate p2p.PeerUpdate) {
return
}
if r.config.Broadcast {
if r.cfg.Broadcast {
// Check if we've already started a goroutine for this peer, if not we create
// a new done channel so we can explicitly close the goroutine if the peer
// is later removed, we increment the waitgroup so the reactor can stop
+17 -17
View File
@@ -11,7 +11,7 @@ import (
abciclient "github.com/tendermint/tendermint/abci/client"
"github.com/tendermint/tendermint/abci/example/kvstore"
abci "github.com/tendermint/tendermint/abci/types"
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/internal/mempool"
"github.com/tendermint/tendermint/internal/p2p"
"github.com/tendermint/tendermint/internal/p2p/p2ptest"
@@ -36,7 +36,7 @@ type reactorTestSuite struct {
nodes []types.NodeID
}
func setup(t *testing.T, cfg *cfg.MempoolConfig, numNodes int, chBuf uint) *reactorTestSuite {
func setup(t *testing.T, config *config.MempoolConfig, numNodes int, chBuf uint) *reactorTestSuite {
t.Helper()
rts := &reactorTestSuite{
@@ -68,7 +68,7 @@ func setup(t *testing.T, cfg *cfg.MempoolConfig, numNodes int, chBuf uint) *reac
rts.reactors[nodeID] = NewReactor(
rts.logger.With("nodeID", nodeID),
cfg,
config,
rts.network.Nodes[nodeID].PeerManager,
mempool,
rts.mempoolChnnels[nodeID],
@@ -158,9 +158,9 @@ func (rts *reactorTestSuite) waitForTxns(t *testing.T, txs types.Txs, ids ...typ
func TestReactorBroadcastTxs(t *testing.T) {
numTxs := 1000
numNodes := 10
config := cfg.TestConfig()
cfg := config.TestConfig()
rts := setup(t, config.Mempool, numNodes, 0)
rts := setup(t, cfg.Mempool, numNodes, 0)
primary := rts.nodes[0]
secondaries := rts.nodes[1:]
@@ -185,9 +185,9 @@ func TestReactorBroadcastTxs(t *testing.T) {
func TestReactorConcurrency(t *testing.T) {
numTxs := 5
numNodes := 2
config := cfg.TestConfig()
cfg := config.TestConfig()
rts := setup(t, config.Mempool, numNodes, 0)
rts := setup(t, cfg.Mempool, numNodes, 0)
primary := rts.nodes[0]
secondary := rts.nodes[1]
@@ -244,9 +244,9 @@ func TestReactorConcurrency(t *testing.T) {
func TestReactorNoBroadcastToSender(t *testing.T) {
numTxs := 1000
numNodes := 2
config := cfg.TestConfig()
cfg := config.TestConfig()
rts := setup(t, config.Mempool, numNodes, uint(numTxs))
rts := setup(t, cfg.Mempool, numNodes, uint(numTxs))
primary := rts.nodes[0]
secondary := rts.nodes[1]
@@ -267,16 +267,16 @@ func TestReactorNoBroadcastToSender(t *testing.T) {
func TestReactor_MaxTxBytes(t *testing.T) {
numNodes := 2
config := cfg.TestConfig()
cfg := config.TestConfig()
rts := setup(t, config.Mempool, numNodes, 0)
rts := setup(t, cfg.Mempool, numNodes, 0)
primary := rts.nodes[0]
secondary := rts.nodes[1]
// Broadcast a tx, which has the max size and ensure it's received by the
// second reactor.
tx1 := tmrand.Bytes(config.Mempool.MaxTxBytes)
tx1 := tmrand.Bytes(cfg.Mempool.MaxTxBytes)
err := rts.reactors[primary].mempool.CheckTx(
context.Background(),
tx1,
@@ -297,7 +297,7 @@ func TestReactor_MaxTxBytes(t *testing.T) {
rts.reactors[secondary].mempool.Flush()
// broadcast a tx, which is beyond the max size and ensure it's not sent
tx2 := tmrand.Bytes(config.Mempool.MaxTxBytes + 1)
tx2 := tmrand.Bytes(cfg.Mempool.MaxTxBytes + 1)
err = rts.mempools[primary].CheckTx(context.Background(), tx2, nil, mempool.TxInfo{SenderID: mempool.UnknownPeerID})
require.Error(t, err)
@@ -305,11 +305,11 @@ func TestReactor_MaxTxBytes(t *testing.T) {
}
func TestDontExhaustMaxActiveIDs(t *testing.T) {
config := cfg.TestConfig()
cfg := config.TestConfig()
// we're creating a single node network, but not starting the
// network.
rts := setup(t, config.Mempool, 1, mempool.MaxActiveIDs+1)
rts := setup(t, cfg.Mempool, 1, mempool.MaxActiveIDs+1)
nodeID := rts.nodes[0]
@@ -374,9 +374,9 @@ func TestBroadcastTxForPeerStopsWhenPeerStops(t *testing.T) {
t.Skip("skipping test in short mode")
}
config := cfg.TestConfig()
cfg := config.TestConfig()
rts := setup(t, config.Mempool, 2, 0)
rts := setup(t, cfg.Mempool, 2, 0)
primary := rts.nodes[0]
secondary := rts.nodes[1]
+8 -8
View File
@@ -8,7 +8,7 @@ import (
"sync"
"time"
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/internal/libs/clist"
tmsync "github.com/tendermint/tendermint/internal/libs/sync"
"github.com/tendermint/tendermint/internal/mempool"
@@ -37,7 +37,7 @@ type PeerManager interface {
type Reactor struct {
service.BaseService
config *cfg.MempoolConfig
cfg *config.MempoolConfig
mempool *TxMempool
ids *mempool.MempoolIDs
@@ -65,7 +65,7 @@ type Reactor struct {
// NewReactor returns a reference to a new reactor.
func NewReactor(
logger log.Logger,
config *cfg.MempoolConfig,
cfg *config.MempoolConfig,
peerMgr PeerManager,
txmp *TxMempool,
mempoolCh *p2p.Channel,
@@ -73,7 +73,7 @@ func NewReactor(
) *Reactor {
r := &Reactor{
config: config,
cfg: cfg,
peerMgr: peerMgr,
mempool: txmp,
ids: mempool.NewMempoolIDs(),
@@ -97,8 +97,8 @@ func defaultObservePanic(r interface{}) {}
//
// TODO: Remove once p2p refactor is complete.
// ref: https://github.com/tendermint/tendermint/issues/5670
func GetChannelShims(config *cfg.MempoolConfig) map[p2p.ChannelID]*p2p.ChannelDescriptorShim {
largestTx := make([]byte, config.MaxTxBytes)
func GetChannelShims(cfg *config.MempoolConfig) map[p2p.ChannelID]*p2p.ChannelDescriptorShim {
largestTx := make([]byte, cfg.MaxTxBytes)
batchMsg := protomem.Message{
Sum: &protomem.Message_Txs{
Txs: &protomem.Txs{Txs: [][]byte{largestTx}},
@@ -124,7 +124,7 @@ func GetChannelShims(config *cfg.MempoolConfig) map[p2p.ChannelID]*p2p.ChannelDe
// messages on that p2p channel accordingly. The caller must be sure to execute
// OnStop to ensure the outbound p2p Channels are closed.
func (r *Reactor) OnStart() error {
if !r.config.Broadcast {
if !r.cfg.Broadcast {
r.Logger.Info("tx broadcasting is disabled")
}
@@ -262,7 +262,7 @@ func (r *Reactor) processPeerUpdate(peerUpdate p2p.PeerUpdate) {
return
}
if r.config.Broadcast {
if r.cfg.Broadcast {
// Check if we've already started a goroutine for this peer, if not we create
// a new done channel so we can explicitly close the goroutine if the peer
// is later removed, we increment the waitgroup so the reactor can stop
@@ -13,7 +13,7 @@ import (
"github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/crypto/ed25519"
cryptoenc "github.com/tendermint/tendermint/crypto/encoding"
"github.com/tendermint/tendermint/crypto/encoding"
"github.com/tendermint/tendermint/internal/libs/protoio"
tmp2p "github.com/tendermint/tendermint/proto/tendermint/p2p"
)
@@ -113,7 +113,7 @@ func (c *evilConn) Read(data []byte) (n int, err error) {
case 1:
signature := c.signChallenge()
if !c.badAuthSignature {
pkpb, err := cryptoenc.PubKeyToProto(c.privKey.PubKey())
pkpb, err := encoding.PubKeyToProto(c.privKey.PubKey())
if err != nil {
panic(err)
}
+3 -3
View File
@@ -23,7 +23,7 @@ import (
"github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/crypto/ed25519"
cryptoenc "github.com/tendermint/tendermint/crypto/encoding"
"github.com/tendermint/tendermint/crypto/encoding"
"github.com/tendermint/tendermint/internal/libs/protoio"
tmsync "github.com/tendermint/tendermint/internal/libs/sync"
"github.com/tendermint/tendermint/libs/async"
@@ -406,7 +406,7 @@ func shareAuthSignature(sc io.ReadWriter, pubKey crypto.PubKey, signature []byte
// Send our info and receive theirs in tandem.
var trs, _ = async.Parallel(
func(_ int) (val interface{}, abort bool, err error) {
pbpk, err := cryptoenc.PubKeyToProto(pubKey)
pbpk, err := encoding.PubKeyToProto(pubKey)
if err != nil {
return nil, true, err
}
@@ -423,7 +423,7 @@ func shareAuthSignature(sc io.ReadWriter, pubKey crypto.PubKey, signature []byte
return nil, true, err // abort
}
pk, err := cryptoenc.PubKeyFromProto(pba.PubKey)
pk, err := encoding.PubKeyFromProto(pba.PubKey)
if err != nil {
return nil, true, err // abort
}
+2 -1
View File
@@ -6,9 +6,10 @@ import (
"time"
"github.com/stretchr/testify/require"
dbm "github.com/tendermint/tm-db"
"github.com/tendermint/tendermint/crypto/ed25519"
"github.com/tendermint/tendermint/types"
dbm "github.com/tendermint/tm-db"
)
func TestPeerScoring(t *testing.T) {
+35 -35
View File
@@ -14,7 +14,7 @@ import (
"github.com/tendermint/tendermint/internal/p2p/p2ptest"
"github.com/tendermint/tendermint/internal/p2p/pex"
"github.com/tendermint/tendermint/libs/log"
proto "github.com/tendermint/tendermint/proto/tendermint/p2p"
p2pproto "github.com/tendermint/tendermint/proto/tendermint/p2p"
"github.com/tendermint/tendermint/types"
)
@@ -45,7 +45,7 @@ func TestReactorBasic(t *testing.T) {
// assert that when a mock node sends a request it receives a response (and
// the correct one)
testNet.sendRequest(t, firstNode, secondNode, true)
testNet.listenForResponse(t, secondNode, firstNode, shortWait, []proto.PexAddressV2(nil))
testNet.listenForResponse(t, secondNode, firstNode, shortWait, []p2pproto.PexAddressV2(nil))
}
func TestReactorConnectFullNetwork(t *testing.T) {
@@ -71,17 +71,17 @@ func TestReactorSendsRequestsTooOften(t *testing.T) {
r.pexInCh <- p2p.Envelope{
From: badNode,
Message: &proto.PexRequestV2{},
Message: &p2pproto.PexRequestV2{},
}
resp := <-r.pexOutCh
msg, ok := resp.Message.(*proto.PexResponseV2)
msg, ok := resp.Message.(*p2pproto.PexResponseV2)
require.True(t, ok)
require.Empty(t, msg.Addresses)
r.pexInCh <- p2p.Envelope{
From: badNode,
Message: &proto.PexRequestV2{},
Message: &p2pproto.PexRequestV2{},
}
peerErr := <-r.pexErrCh
@@ -136,10 +136,10 @@ func TestReactorErrorsOnReceivingTooManyPeers(t *testing.T) {
require.NoError(t, err)
require.True(t, added)
addresses := make([]proto.PexAddressV2, 101)
addresses := make([]p2pproto.PexAddressV2, 101)
for i := 0; i < len(addresses); i++ {
nodeAddress := p2p.NodeAddress{Protocol: p2p.MemoryProtocol, NodeID: randomNodeID(t)}
addresses[i] = proto.PexAddressV2{
addresses[i] = p2pproto.PexAddressV2{
URL: nodeAddress.String(),
}
}
@@ -152,12 +152,12 @@ func TestReactorErrorsOnReceivingTooManyPeers(t *testing.T) {
select {
// wait for a request and then send a response with too many addresses
case req := <-r.pexOutCh:
if _, ok := req.Message.(*proto.PexRequestV2); !ok {
if _, ok := req.Message.(*p2pproto.PexRequestV2); !ok {
t.Fatal("expected v2 pex request")
}
r.pexInCh <- p2p.Envelope{
From: peer.NodeID,
Message: &proto.PexResponseV2{
Message: &p2pproto.PexResponseV2{
Addresses: addresses,
},
}
@@ -290,7 +290,7 @@ func setupSingle(t *testing.T) *singleTestReactor {
pexErrCh := make(chan p2p.PeerError, chBuf)
pexCh := p2p.NewChannel(
p2p.ChannelID(pex.PexChannel),
new(proto.PexMessage),
new(p2pproto.PexMessage),
pexInCh,
pexOutCh,
pexErrCh,
@@ -381,7 +381,7 @@ func setupNetwork(t *testing.T, opts testOptions) *reactorTestSuite {
// NOTE: we don't assert that the channels get drained after stopping the
// reactor
rts.pexChannels = rts.network.MakeChannelsNoCleanup(
t, pex.ChannelDescriptor(), new(proto.PexMessage), chBuf,
t, pex.ChannelDescriptor(), new(p2pproto.PexMessage), chBuf,
)
idx := 0
@@ -447,7 +447,7 @@ func (r *reactorTestSuite) addNodes(t *testing.T, nodes int) {
r.network.Nodes[node.NodeID] = node
nodeID := node.NodeID
r.pexChannels[nodeID] = node.MakeChannelNoCleanup(
t, pex.ChannelDescriptor(), new(proto.PexMessage), r.opts.BufferSize,
t, pex.ChannelDescriptor(), new(p2pproto.PexMessage), r.opts.BufferSize,
)
r.peerChans[nodeID] = make(chan p2p.PeerUpdate, r.opts.BufferSize)
r.peerUpdates[nodeID] = p2p.NewPeerUpdates(r.peerChans[nodeID], r.opts.BufferSize)
@@ -488,11 +488,11 @@ func (r *reactorTestSuite) listenForRequest(t *testing.T, fromNode, toNode int,
r.logger.Info("Listening for request", "from", fromNode, "to", toNode)
to, from := r.checkNodePair(t, toNode, fromNode)
conditional := func(msg p2p.Envelope) bool {
_, ok := msg.Message.(*proto.PexRequestV2)
_, ok := msg.Message.(*p2pproto.PexRequestV2)
return ok && msg.From == from
}
assertion := func(t *testing.T, msg p2p.Envelope) bool {
require.Equal(t, &proto.PexRequestV2{}, msg.Message)
require.Equal(t, &p2pproto.PexRequestV2{}, msg.Message)
return true
}
r.listenFor(t, to, conditional, assertion, waitPeriod)
@@ -507,11 +507,11 @@ func (r *reactorTestSuite) pingAndlistenForNAddresses(
r.logger.Info("Listening for addresses", "from", fromNode, "to", toNode)
to, from := r.checkNodePair(t, toNode, fromNode)
conditional := func(msg p2p.Envelope) bool {
_, ok := msg.Message.(*proto.PexResponseV2)
_, ok := msg.Message.(*p2pproto.PexResponseV2)
return ok && msg.From == from
}
assertion := func(t *testing.T, msg p2p.Envelope) bool {
m, ok := msg.Message.(*proto.PexResponseV2)
m, ok := msg.Message.(*p2pproto.PexResponseV2)
if !ok {
require.Fail(t, "expected pex response v2")
return true
@@ -534,17 +534,17 @@ func (r *reactorTestSuite) listenForResponse(
t *testing.T,
fromNode, toNode int,
waitPeriod time.Duration,
addresses []proto.PexAddressV2,
addresses []p2pproto.PexAddressV2,
) {
r.logger.Info("Listening for response", "from", fromNode, "to", toNode)
to, from := r.checkNodePair(t, toNode, fromNode)
conditional := func(msg p2p.Envelope) bool {
_, ok := msg.Message.(*proto.PexResponseV2)
_, ok := msg.Message.(*p2pproto.PexResponseV2)
r.logger.Info("message", msg, "ok", ok)
return ok && msg.From == from
}
assertion := func(t *testing.T, msg p2p.Envelope) bool {
require.Equal(t, &proto.PexResponseV2{Addresses: addresses}, msg.Message)
require.Equal(t, &p2pproto.PexResponseV2{Addresses: addresses}, msg.Message)
return true
}
r.listenFor(t, to, conditional, assertion, waitPeriod)
@@ -554,16 +554,16 @@ func (r *reactorTestSuite) listenForLegacyResponse(
t *testing.T,
fromNode, toNode int,
waitPeriod time.Duration,
addresses []proto.PexAddress,
addresses []p2pproto.PexAddress,
) {
r.logger.Info("Listening for response", "from", fromNode, "to", toNode)
to, from := r.checkNodePair(t, toNode, fromNode)
conditional := func(msg p2p.Envelope) bool {
_, ok := msg.Message.(*proto.PexResponse)
_, ok := msg.Message.(*p2pproto.PexResponse)
return ok && msg.From == from
}
assertion := func(t *testing.T, msg p2p.Envelope) bool {
require.Equal(t, &proto.PexResponse{Addresses: addresses}, msg.Message)
require.Equal(t, &p2pproto.PexResponse{Addresses: addresses}, msg.Message)
return true
}
r.listenFor(t, to, conditional, assertion, waitPeriod)
@@ -595,26 +595,26 @@ func (r *reactorTestSuite) listenForPeerUpdate(
}
}
func (r *reactorTestSuite) getV2AddressesFor(nodes []int) []proto.PexAddressV2 {
addresses := make([]proto.PexAddressV2, len(nodes))
func (r *reactorTestSuite) getV2AddressesFor(nodes []int) []p2pproto.PexAddressV2 {
addresses := make([]p2pproto.PexAddressV2, len(nodes))
for idx, node := range nodes {
nodeID := r.nodes[node]
addresses[idx] = proto.PexAddressV2{
addresses[idx] = p2pproto.PexAddressV2{
URL: r.network.Nodes[nodeID].NodeAddress.String(),
}
}
return addresses
}
func (r *reactorTestSuite) getAddressesFor(t *testing.T, nodes []int) []proto.PexAddress {
addresses := make([]proto.PexAddress, len(nodes))
func (r *reactorTestSuite) getAddressesFor(t *testing.T, nodes []int) []p2pproto.PexAddress {
addresses := make([]p2pproto.PexAddress, len(nodes))
for idx, node := range nodes {
nodeID := r.nodes[node]
nodeAddrs := r.network.Nodes[nodeID].NodeAddress
endpoints, err := nodeAddrs.Resolve(context.Background())
require.NoError(t, err)
require.Len(t, endpoints, 1)
addresses[idx] = proto.PexAddress{
addresses[idx] = p2pproto.PexAddress{
ID: string(nodeAddrs.NodeID),
IP: endpoints[0].IP.String(),
Port: uint32(endpoints[0].Port),
@@ -628,12 +628,12 @@ func (r *reactorTestSuite) sendRequest(t *testing.T, fromNode, toNode int, v2 bo
if v2 {
r.pexChannels[from].Out <- p2p.Envelope{
To: to,
Message: &proto.PexRequestV2{},
Message: &p2pproto.PexRequestV2{},
}
} else {
r.pexChannels[from].Out <- p2p.Envelope{
To: to,
Message: &proto.PexRequest{},
Message: &p2pproto.PexRequest{},
}
}
}
@@ -649,7 +649,7 @@ func (r *reactorTestSuite) sendResponse(
addrs := r.getV2AddressesFor(withNodes)
r.pexChannels[from].Out <- p2p.Envelope{
To: to,
Message: &proto.PexResponseV2{
Message: &p2pproto.PexResponseV2{
Addresses: addrs,
},
}
@@ -657,7 +657,7 @@ func (r *reactorTestSuite) sendResponse(
addrs := r.getAddressesFor(t, withNodes)
r.pexChannels[from].Out <- p2p.Envelope{
To: to,
Message: &proto.PexResponse{
Message: &p2pproto.PexResponse{
Addresses: addrs,
},
}
@@ -764,8 +764,8 @@ func (r *reactorTestSuite) connectPeers(t *testing.T, sourceNode, targetNode int
}
// nolint: unused
func (r *reactorTestSuite) pexAddresses(t *testing.T, nodeIndices []int) []proto.PexAddress {
var addresses []proto.PexAddress
func (r *reactorTestSuite) pexAddresses(t *testing.T, nodeIndices []int) []p2pproto.PexAddress {
var addresses []p2pproto.PexAddress
for _, i := range nodeIndices {
if i < len(r.nodes) {
require.Fail(t, "index for pex address is greater than number of nodes")
@@ -777,7 +777,7 @@ func (r *reactorTestSuite) pexAddresses(t *testing.T, nodeIndices []int) []proto
require.NoError(t, err)
for _, endpoint := range endpoints {
if endpoint.IP != nil {
addresses = append(addresses, proto.PexAddress{
addresses = append(addresses, p2pproto.PexAddress{
ID: string(nodeAddrs.NodeID),
IP: endpoint.IP.String(),
Port: uint32(endpoint.Port),
+5 -5
View File
@@ -4,7 +4,7 @@ import (
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/internal/proxy"
"github.com/tendermint/tendermint/libs/bytes"
ctypes "github.com/tendermint/tendermint/rpc/coretypes"
"github.com/tendermint/tendermint/rpc/coretypes"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
@@ -16,7 +16,7 @@ func (env *Environment) ABCIQuery(
data bytes.HexBytes,
height int64,
prove bool,
) (*ctypes.ResultABCIQuery, error) {
) (*coretypes.ResultABCIQuery, error) {
resQuery, err := env.ProxyAppQuery.QuerySync(ctx.Context(), abci.RequestQuery{
Path: path,
Data: data,
@@ -27,16 +27,16 @@ func (env *Environment) ABCIQuery(
return nil, err
}
return &ctypes.ResultABCIQuery{Response: *resQuery}, nil
return &coretypes.ResultABCIQuery{Response: *resQuery}, nil
}
// ABCIInfo gets some info about the application.
// More: https://docs.tendermint.com/master/rpc/#/ABCI/abci_info
func (env *Environment) ABCIInfo(ctx *rpctypes.Context) (*ctypes.ResultABCIInfo, error) {
func (env *Environment) ABCIInfo(ctx *rpctypes.Context) (*coretypes.ResultABCIInfo, error) {
resInfo, err := env.ProxyAppQuery.InfoSync(ctx.Context(), proxy.RequestInfo)
if err != nil {
return nil, err
}
return &ctypes.ResultABCIInfo{Response: *resInfo}, nil
return &coretypes.ResultABCIInfo{Response: *resInfo}, nil
}
+21 -21
View File
@@ -8,7 +8,7 @@ import (
"github.com/tendermint/tendermint/libs/bytes"
tmmath "github.com/tendermint/tendermint/libs/math"
tmquery "github.com/tendermint/tendermint/libs/pubsub/query"
ctypes "github.com/tendermint/tendermint/rpc/coretypes"
"github.com/tendermint/tendermint/rpc/coretypes"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
"github.com/tendermint/tendermint/types"
)
@@ -25,7 +25,7 @@ import (
// More: https://docs.tendermint.com/master/rpc/#/Info/blockchain
func (env *Environment) BlockchainInfo(
ctx *rpctypes.Context,
minHeight, maxHeight int64) (*ctypes.ResultBlockchainInfo, error) {
minHeight, maxHeight int64) (*coretypes.ResultBlockchainInfo, error) {
const limit int64 = 20
@@ -49,7 +49,7 @@ func (env *Environment) BlockchainInfo(
}
}
return &ctypes.ResultBlockchainInfo{
return &coretypes.ResultBlockchainInfo{
LastHeight: env.BlockStore.Height(),
BlockMetas: blockMetas}, nil
}
@@ -60,7 +60,7 @@ func (env *Environment) BlockchainInfo(
func filterMinMax(base, height, min, max, limit int64) (int64, int64, error) {
// filter negatives
if min < 0 || max < 0 {
return min, max, ctypes.ErrZeroOrNegativeHeight
return min, max, coretypes.ErrZeroOrNegativeHeight
}
// adjust for default values
@@ -83,7 +83,7 @@ func filterMinMax(base, height, min, max, limit int64) (int64, int64, error) {
if min > max {
return min, max, fmt.Errorf("%w: min height %d can't be greater than max height %d",
ctypes.ErrInvalidRequest, min, max)
coretypes.ErrInvalidRequest, min, max)
}
return min, max, nil
}
@@ -91,7 +91,7 @@ func filterMinMax(base, height, min, max, limit int64) (int64, int64, error) {
// Block gets block at a given height.
// If no height is provided, it will fetch the latest block.
// More: https://docs.tendermint.com/master/rpc/#/Info/block
func (env *Environment) Block(ctx *rpctypes.Context, heightPtr *int64) (*ctypes.ResultBlock, error) {
func (env *Environment) Block(ctx *rpctypes.Context, heightPtr *int64) (*coretypes.ResultBlock, error) {
height, err := env.getHeight(env.BlockStore.Height(), heightPtr)
if err != nil {
return nil, err
@@ -99,33 +99,33 @@ func (env *Environment) Block(ctx *rpctypes.Context, heightPtr *int64) (*ctypes.
blockMeta := env.BlockStore.LoadBlockMeta(height)
if blockMeta == nil {
return &ctypes.ResultBlock{BlockID: types.BlockID{}, Block: nil}, nil
return &coretypes.ResultBlock{BlockID: types.BlockID{}, Block: nil}, nil
}
block := env.BlockStore.LoadBlock(height)
return &ctypes.ResultBlock{BlockID: blockMeta.BlockID, Block: block}, nil
return &coretypes.ResultBlock{BlockID: blockMeta.BlockID, Block: block}, nil
}
// BlockByHash gets block by hash.
// More: https://docs.tendermint.com/master/rpc/#/Info/block_by_hash
func (env *Environment) BlockByHash(ctx *rpctypes.Context, hash bytes.HexBytes) (*ctypes.ResultBlock, error) {
func (env *Environment) BlockByHash(ctx *rpctypes.Context, hash bytes.HexBytes) (*coretypes.ResultBlock, error) {
// N.B. The hash parameter is HexBytes so that the reflective parameter
// decoding logic in the HTTP service will correctly translate from JSON.
// See https://github.com/tendermint/tendermint/issues/6802 for context.
block := env.BlockStore.LoadBlockByHash(hash)
if block == nil {
return &ctypes.ResultBlock{BlockID: types.BlockID{}, Block: nil}, nil
return &coretypes.ResultBlock{BlockID: types.BlockID{}, Block: nil}, nil
}
// If block is not nil, then blockMeta can't be nil.
blockMeta := env.BlockStore.LoadBlockMeta(block.Height)
return &ctypes.ResultBlock{BlockID: blockMeta.BlockID, Block: block}, nil
return &coretypes.ResultBlock{BlockID: blockMeta.BlockID, Block: block}, nil
}
// Commit gets block commit at a given height.
// If no height is provided, it will fetch the commit for the latest block.
// More: https://docs.tendermint.com/master/rpc/#/Info/commit
func (env *Environment) Commit(ctx *rpctypes.Context, heightPtr *int64) (*ctypes.ResultCommit, error) {
func (env *Environment) Commit(ctx *rpctypes.Context, heightPtr *int64) (*coretypes.ResultCommit, error) {
height, err := env.getHeight(env.BlockStore.Height(), heightPtr)
if err != nil {
return nil, err
@@ -144,7 +144,7 @@ func (env *Environment) Commit(ctx *rpctypes.Context, heightPtr *int64) (*ctypes
// NOTE: we can't yet ensure atomicity of operations in asserting
// whether this is the latest height and retrieving the seen commit
if commit != nil && commit.Height == height {
return ctypes.NewResultCommit(&header, commit, false), nil
return coretypes.NewResultCommit(&header, commit, false), nil
}
}
@@ -153,7 +153,7 @@ func (env *Environment) Commit(ctx *rpctypes.Context, heightPtr *int64) (*ctypes
if commit == nil {
return nil, nil
}
return ctypes.NewResultCommit(&header, commit, true), nil
return coretypes.NewResultCommit(&header, commit, true), nil
}
// BlockResults gets ABCIResults at a given height.
@@ -163,7 +163,7 @@ func (env *Environment) Commit(ctx *rpctypes.Context, heightPtr *int64) (*ctypes
// Thus response.results.deliver_tx[5] is the results of executing
// getBlock(h).Txs[5]
// More: https://docs.tendermint.com/master/rpc/#/Info/block_results
func (env *Environment) BlockResults(ctx *rpctypes.Context, heightPtr *int64) (*ctypes.ResultBlockResults, error) {
func (env *Environment) BlockResults(ctx *rpctypes.Context, heightPtr *int64) (*coretypes.ResultBlockResults, error) {
height, err := env.getHeight(env.BlockStore.Height(), heightPtr)
if err != nil {
return nil, err
@@ -179,7 +179,7 @@ func (env *Environment) BlockResults(ctx *rpctypes.Context, heightPtr *int64) (*
totalGasUsed += tx.GetGasUsed()
}
return &ctypes.ResultBlockResults{
return &coretypes.ResultBlockResults{
Height: height,
TxsResults: results.DeliverTxs,
TotalGasUsed: totalGasUsed,
@@ -197,7 +197,7 @@ func (env *Environment) BlockSearch(
query string,
pagePtr, perPagePtr *int,
orderBy string,
) (*ctypes.ResultBlockSearch, error) {
) (*coretypes.ResultBlockSearch, error) {
if !indexer.KVSinkEnabled(env.EventSinks) {
return nil, fmt.Errorf("block searching is disabled due to no kvEventSink")
@@ -229,7 +229,7 @@ func (env *Environment) BlockSearch(
sort.Slice(results, func(i, j int) bool { return results[i] < results[j] })
default:
return nil, fmt.Errorf("expected order_by to be either `asc` or `desc` or empty: %w", ctypes.ErrInvalidRequest)
return nil, fmt.Errorf("expected order_by to be either `asc` or `desc` or empty: %w", coretypes.ErrInvalidRequest)
}
// paginate results
@@ -244,13 +244,13 @@ func (env *Environment) BlockSearch(
skipCount := validateSkipCount(page, perPage)
pageSize := tmmath.MinInt(perPage, totalCount-skipCount)
apiResults := make([]*ctypes.ResultBlock, 0, pageSize)
apiResults := make([]*coretypes.ResultBlock, 0, pageSize)
for i := skipCount; i < skipCount+pageSize; i++ {
block := env.BlockStore.LoadBlock(results[i])
if block != nil {
blockMeta := env.BlockStore.LoadBlockMeta(block.Height)
if blockMeta != nil {
apiResults = append(apiResults, &ctypes.ResultBlock{
apiResults = append(apiResults, &coretypes.ResultBlock{
Block: block,
BlockID: blockMeta.BlockID,
})
@@ -258,5 +258,5 @@ func (env *Environment) BlockSearch(
}
}
return &ctypes.ResultBlockSearch{Blocks: apiResults, TotalCount: totalCount}, nil
return &coretypes.ResultBlockSearch{Blocks: apiResults, TotalCount: totalCount}, nil
}
+3 -3
View File
@@ -12,7 +12,7 @@ import (
abci "github.com/tendermint/tendermint/abci/types"
sm "github.com/tendermint/tendermint/internal/state"
tmstate "github.com/tendermint/tendermint/proto/tendermint/state"
ctypes "github.com/tendermint/tendermint/rpc/coretypes"
"github.com/tendermint/tendermint/rpc/coretypes"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
"github.com/tendermint/tendermint/types"
)
@@ -89,12 +89,12 @@ func TestBlockResults(t *testing.T) {
testCases := []struct {
height int64
wantErr bool
wantRes *ctypes.ResultBlockResults
wantRes *coretypes.ResultBlockResults
}{
{-1, true, nil},
{0, true, nil},
{101, true, nil},
{100, false, &ctypes.ResultBlockResults{
{100, false, &coretypes.ResultBlockResults{
Height: 100,
TxsResults: results.DeliverTxs,
TotalGasUsed: 15,
+16 -16
View File
@@ -3,9 +3,9 @@ package core
import (
"errors"
cm "github.com/tendermint/tendermint/internal/consensus"
"github.com/tendermint/tendermint/internal/consensus"
tmmath "github.com/tendermint/tendermint/libs/math"
ctypes "github.com/tendermint/tendermint/rpc/coretypes"
"github.com/tendermint/tendermint/rpc/coretypes"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
"github.com/tendermint/tendermint/types"
)
@@ -20,7 +20,7 @@ import (
func (env *Environment) Validators(
ctx *rpctypes.Context,
heightPtr *int64,
pagePtr, perPagePtr *int) (*ctypes.ResultValidators, error) {
pagePtr, perPagePtr *int) (*coretypes.ResultValidators, error) {
// The latest validator that we know is the NextValidator of the last block.
height, err := env.getHeight(env.latestUncommittedHeight(), heightPtr)
@@ -44,7 +44,7 @@ func (env *Environment) Validators(
v := validators.Validators[skipCount : skipCount+tmmath.MinInt(perPage, totalCount-skipCount)]
return &ctypes.ResultValidators{
return &coretypes.ResultValidators{
BlockHeight: height,
Validators: v,
Count: len(v),
@@ -54,16 +54,16 @@ func (env *Environment) Validators(
// DumpConsensusState dumps consensus state.
// UNSTABLE
// More: https://docs.tendermint.com/master/rpc/#/Info/dump_consensus_state
func (env *Environment) DumpConsensusState(ctx *rpctypes.Context) (*ctypes.ResultDumpConsensusState, error) {
func (env *Environment) DumpConsensusState(ctx *rpctypes.Context) (*coretypes.ResultDumpConsensusState, error) {
// Get Peer consensus states.
var peerStates []ctypes.PeerStateInfo
var peerStates []coretypes.PeerStateInfo
switch {
case env.P2PPeers != nil:
peers := env.P2PPeers.Peers().List()
peerStates = make([]ctypes.PeerStateInfo, 0, len(peers))
peerStates = make([]coretypes.PeerStateInfo, 0, len(peers))
for _, peer := range peers {
peerState, ok := peer.Get(types.PeerStateKey).(*cm.PeerState)
peerState, ok := peer.Get(types.PeerStateKey).(*consensus.PeerState)
if !ok { // peer does not have a state yet
continue
}
@@ -71,7 +71,7 @@ func (env *Environment) DumpConsensusState(ctx *rpctypes.Context) (*ctypes.Resul
if err != nil {
return nil, err
}
peerStates = append(peerStates, ctypes.PeerStateInfo{
peerStates = append(peerStates, coretypes.PeerStateInfo{
// Peer basic info.
NodeAddress: peer.SocketAddr().String(),
// Peer consensus state.
@@ -80,7 +80,7 @@ func (env *Environment) DumpConsensusState(ctx *rpctypes.Context) (*ctypes.Resul
}
case env.PeerManager != nil:
peers := env.PeerManager.Peers()
peerStates = make([]ctypes.PeerStateInfo, 0, len(peers))
peerStates = make([]coretypes.PeerStateInfo, 0, len(peers))
for _, pid := range peers {
peerState, ok := env.ConsensusReactor.GetPeerState(pid)
if !ok {
@@ -94,7 +94,7 @@ func (env *Environment) DumpConsensusState(ctx *rpctypes.Context) (*ctypes.Resul
addr := env.PeerManager.Addresses(pid)
if len(addr) >= 1 {
peerStates = append(peerStates, ctypes.PeerStateInfo{
peerStates = append(peerStates, coretypes.PeerStateInfo{
// Peer basic info.
NodeAddress: addr[0].String(),
// Peer consensus state.
@@ -111,7 +111,7 @@ func (env *Environment) DumpConsensusState(ctx *rpctypes.Context) (*ctypes.Resul
if err != nil {
return nil, err
}
return &ctypes.ResultDumpConsensusState{
return &coretypes.ResultDumpConsensusState{
RoundState: roundState,
Peers: peerStates}, nil
}
@@ -119,10 +119,10 @@ func (env *Environment) DumpConsensusState(ctx *rpctypes.Context) (*ctypes.Resul
// ConsensusState returns a concise summary of the consensus state.
// UNSTABLE
// More: https://docs.tendermint.com/master/rpc/#/Info/consensus_state
func (env *Environment) GetConsensusState(ctx *rpctypes.Context) (*ctypes.ResultConsensusState, error) {
func (env *Environment) GetConsensusState(ctx *rpctypes.Context) (*coretypes.ResultConsensusState, error) {
// Get self round state.
bz, err := env.ConsensusState.GetRoundStateSimpleJSON()
return &ctypes.ResultConsensusState{RoundState: bz}, err
return &coretypes.ResultConsensusState{RoundState: bz}, err
}
// ConsensusParams gets the consensus parameters at the given block height.
@@ -130,7 +130,7 @@ func (env *Environment) GetConsensusState(ctx *rpctypes.Context) (*ctypes.Result
// More: https://docs.tendermint.com/master/rpc/#/Info/consensus_params
func (env *Environment) ConsensusParams(
ctx *rpctypes.Context,
heightPtr *int64) (*ctypes.ResultConsensusParams, error) {
heightPtr *int64) (*coretypes.ResultConsensusParams, error) {
// The latest consensus params that we know is the consensus params after the
// last block.
@@ -144,7 +144,7 @@ func (env *Environment) ConsensusParams(
return nil, err
}
return &ctypes.ResultConsensusParams{
return &coretypes.ResultConsensusParams{
BlockHeight: height,
ConsensusParams: consensusParams}, nil
}
+3 -3
View File
@@ -1,12 +1,12 @@
package core
import (
ctypes "github.com/tendermint/tendermint/rpc/coretypes"
"github.com/tendermint/tendermint/rpc/coretypes"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
// UnsafeFlushMempool removes all transactions from the mempool.
func (env *Environment) UnsafeFlushMempool(ctx *rpctypes.Context) (*ctypes.ResultUnsafeFlushMempool, error) {
func (env *Environment) UnsafeFlushMempool(ctx *rpctypes.Context) (*coretypes.ResultUnsafeFlushMempool, error) {
env.Mempool.Flush()
return &ctypes.ResultUnsafeFlushMempool{}, nil
return &coretypes.ResultUnsafeFlushMempool{}, nil
}
+10 -10
View File
@@ -5,10 +5,10 @@ import (
"fmt"
"time"
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/internal/consensus"
mempl "github.com/tendermint/tendermint/internal/mempool"
"github.com/tendermint/tendermint/internal/mempool"
"github.com/tendermint/tendermint/internal/p2p"
"github.com/tendermint/tendermint/internal/proxy"
sm "github.com/tendermint/tendermint/internal/state"
@@ -16,7 +16,7 @@ import (
"github.com/tendermint/tendermint/internal/statesync"
tmjson "github.com/tendermint/tendermint/libs/json"
"github.com/tendermint/tendermint/libs/log"
ctypes "github.com/tendermint/tendermint/rpc/coretypes"
"github.com/tendermint/tendermint/rpc/coretypes"
"github.com/tendermint/tendermint/types"
)
@@ -96,13 +96,13 @@ type Environment struct {
GenDoc *types.GenesisDoc // cache the genesis structure
EventSinks []indexer.EventSink
EventBus *types.EventBus // thread safe
Mempool mempl.Mempool
Mempool mempool.Mempool
BlockSyncReactor consensus.BlockSyncReactor
StateSyncMetricer statesync.Metricer
Logger log.Logger
Config cfg.RPCConfig
Config config.RPCConfig
// cache of chunked genesis data.
genChunks []string
@@ -113,7 +113,7 @@ type Environment struct {
func validatePage(pagePtr *int, perPage, totalCount int) (int, error) {
// this can only happen if we haven't first run validatePerPage
if perPage < 1 {
panic(fmt.Errorf("%w (%d)", ctypes.ErrZeroOrNegativePerPage, perPage))
panic(fmt.Errorf("%w (%d)", coretypes.ErrZeroOrNegativePerPage, perPage))
}
if pagePtr == nil { // no page parameter
@@ -126,7 +126,7 @@ func validatePage(pagePtr *int, perPage, totalCount int) (int, error) {
}
page := *pagePtr
if page <= 0 || page > pages {
return 1, fmt.Errorf("%w expected range: [1, %d], given %d", ctypes.ErrPageOutOfRange, pages, page)
return 1, fmt.Errorf("%w expected range: [1, %d], given %d", coretypes.ErrPageOutOfRange, pages, page)
}
return page, nil
@@ -191,15 +191,15 @@ func (env *Environment) getHeight(latestHeight int64, heightPtr *int64) (int64,
if heightPtr != nil {
height := *heightPtr
if height <= 0 {
return 0, fmt.Errorf("%w (requested height: %d)", ctypes.ErrZeroOrNegativeHeight, height)
return 0, fmt.Errorf("%w (requested height: %d)", coretypes.ErrZeroOrNegativeHeight, height)
}
if height > latestHeight {
return 0, fmt.Errorf("%w (requested height: %d, blockchain height: %d)",
ctypes.ErrHeightExceedsChainHead, height, latestHeight)
coretypes.ErrHeightExceedsChainHead, height, latestHeight)
}
base := env.BlockStore.Base()
if height < base {
return 0, fmt.Errorf("%w (requested height: %d, base height: %d)", ctypes.ErrHeightNotAvailable, height, base)
return 0, fmt.Errorf("%w (requested height: %d, base height: %d)", coretypes.ErrHeightNotAvailable, height, base)
}
return height, nil
}
+8 -8
View File
@@ -7,7 +7,7 @@ import (
tmpubsub "github.com/tendermint/tendermint/libs/pubsub"
tmquery "github.com/tendermint/tendermint/libs/pubsub/query"
ctypes "github.com/tendermint/tendermint/rpc/coretypes"
"github.com/tendermint/tendermint/rpc/coretypes"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
@@ -18,7 +18,7 @@ const (
// Subscribe for events via WebSocket.
// More: https://docs.tendermint.com/master/rpc/#/Websocket/subscribe
func (env *Environment) Subscribe(ctx *rpctypes.Context, query string) (*ctypes.ResultSubscribe, error) {
func (env *Environment) Subscribe(ctx *rpctypes.Context, query string) (*coretypes.ResultSubscribe, error) {
addr := ctx.RemoteAddr()
if env.EventBus.NumClients() >= env.Config.MaxSubscriptionClients {
@@ -49,7 +49,7 @@ func (env *Environment) Subscribe(ctx *rpctypes.Context, query string) (*ctypes.
select {
case msg := <-sub.Out():
var (
resultEvent = &ctypes.ResultEvent{Query: query, Data: msg.Data(), Events: msg.Events()}
resultEvent = &coretypes.ResultEvent{Query: query, Data: msg.Data(), Events: msg.Events()}
resp = rpctypes.NewRPCSuccessResponse(subscriptionID, resultEvent)
)
writeCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
@@ -80,12 +80,12 @@ func (env *Environment) Subscribe(ctx *rpctypes.Context, query string) (*ctypes.
}
}()
return &ctypes.ResultSubscribe{}, nil
return &coretypes.ResultSubscribe{}, nil
}
// Unsubscribe from events via WebSocket.
// More: https://docs.tendermint.com/master/rpc/#/Websocket/unsubscribe
func (env *Environment) Unsubscribe(ctx *rpctypes.Context, query string) (*ctypes.ResultUnsubscribe, error) {
func (env *Environment) Unsubscribe(ctx *rpctypes.Context, query string) (*coretypes.ResultUnsubscribe, error) {
args := tmpubsub.UnsubscribeArgs{Subscriber: ctx.RemoteAddr()}
env.Logger.Info("Unsubscribe from query", "remote", args.Subscriber, "subscription", query)
@@ -100,17 +100,17 @@ func (env *Environment) Unsubscribe(ctx *rpctypes.Context, query string) (*ctype
if err != nil {
return nil, err
}
return &ctypes.ResultUnsubscribe{}, nil
return &coretypes.ResultUnsubscribe{}, nil
}
// UnsubscribeAll from all events via WebSocket.
// More: https://docs.tendermint.com/master/rpc/#/Websocket/unsubscribe_all
func (env *Environment) UnsubscribeAll(ctx *rpctypes.Context) (*ctypes.ResultUnsubscribe, error) {
func (env *Environment) UnsubscribeAll(ctx *rpctypes.Context) (*coretypes.ResultUnsubscribe, error) {
addr := ctx.RemoteAddr()
env.Logger.Info("Unsubscribe from all", "remote", addr)
err := env.EventBus.UnsubscribeAll(ctx.Context(), addr)
if err != nil {
return nil, err
}
return &ctypes.ResultUnsubscribe{}, nil
return &coretypes.ResultUnsubscribe{}, nil
}
+4 -4
View File
@@ -3,7 +3,7 @@ package core
import (
"fmt"
ctypes "github.com/tendermint/tendermint/rpc/coretypes"
"github.com/tendermint/tendermint/rpc/coretypes"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
"github.com/tendermint/tendermint/types"
)
@@ -12,10 +12,10 @@ import (
// More: https://docs.tendermint.com/master/rpc/#/Evidence/broadcast_evidence
func (env *Environment) BroadcastEvidence(
ctx *rpctypes.Context,
ev types.Evidence) (*ctypes.ResultBroadcastEvidence, error) {
ev types.Evidence) (*coretypes.ResultBroadcastEvidence, error) {
if ev == nil {
return nil, fmt.Errorf("%w: no evidence was provided", ctypes.ErrInvalidRequest)
return nil, fmt.Errorf("%w: no evidence was provided", coretypes.ErrInvalidRequest)
}
if err := ev.ValidateBasic(); err != nil {
@@ -25,5 +25,5 @@ func (env *Environment) BroadcastEvidence(
if err := env.EvidencePool.AddEvidence(ev); err != nil {
return nil, fmt.Errorf("failed to add evidence: %w", err)
}
return &ctypes.ResultBroadcastEvidence{Hash: ev.Hash()}, nil
return &coretypes.ResultBroadcastEvidence{Hash: ev.Hash()}, nil
}
+3 -3
View File
@@ -1,13 +1,13 @@
package core
import (
ctypes "github.com/tendermint/tendermint/rpc/coretypes"
"github.com/tendermint/tendermint/rpc/coretypes"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
// Health gets node health. Returns empty result (200 OK) on success, no
// response - in case of an error.
// More: https://docs.tendermint.com/master/rpc/#/Info/health
func (env *Environment) Health(ctx *rpctypes.Context) (*ctypes.ResultHealth, error) {
return &ctypes.ResultHealth{}, nil
func (env *Environment) Health(ctx *rpctypes.Context) (*coretypes.ResultHealth, error) {
return &coretypes.ResultHealth{}, nil
}
+20 -20
View File
@@ -7,9 +7,9 @@ import (
"time"
abci "github.com/tendermint/tendermint/abci/types"
mempl "github.com/tendermint/tendermint/internal/mempool"
"github.com/tendermint/tendermint/internal/mempool"
tmpubsub "github.com/tendermint/tendermint/libs/pubsub"
ctypes "github.com/tendermint/tendermint/rpc/coretypes"
"github.com/tendermint/tendermint/rpc/coretypes"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
"github.com/tendermint/tendermint/types"
)
@@ -20,25 +20,25 @@ import (
// BroadcastTxAsync returns right away, with no response. Does not wait for
// CheckTx nor DeliverTx results.
// More: https://docs.tendermint.com/master/rpc/#/Tx/broadcast_tx_async
func (env *Environment) BroadcastTxAsync(ctx *rpctypes.Context, tx types.Tx) (*ctypes.ResultBroadcastTx, error) {
err := env.Mempool.CheckTx(ctx.Context(), tx, nil, mempl.TxInfo{})
func (env *Environment) BroadcastTxAsync(ctx *rpctypes.Context, tx types.Tx) (*coretypes.ResultBroadcastTx, error) {
err := env.Mempool.CheckTx(ctx.Context(), tx, nil, mempool.TxInfo{})
if err != nil {
return nil, err
}
return &ctypes.ResultBroadcastTx{Hash: tx.Hash()}, nil
return &coretypes.ResultBroadcastTx{Hash: tx.Hash()}, nil
}
// BroadcastTxSync returns with the response from CheckTx. Does not wait for
// DeliverTx result.
// More: https://docs.tendermint.com/master/rpc/#/Tx/broadcast_tx_sync
func (env *Environment) BroadcastTxSync(ctx *rpctypes.Context, tx types.Tx) (*ctypes.ResultBroadcastTx, error) {
func (env *Environment) BroadcastTxSync(ctx *rpctypes.Context, tx types.Tx) (*coretypes.ResultBroadcastTx, error) {
resCh := make(chan *abci.Response, 1)
err := env.Mempool.CheckTx(
ctx.Context(),
tx,
func(res *abci.Response) { resCh <- res },
mempl.TxInfo{},
mempool.TxInfo{},
)
if err != nil {
return nil, err
@@ -47,7 +47,7 @@ func (env *Environment) BroadcastTxSync(ctx *rpctypes.Context, tx types.Tx) (*ct
res := <-resCh
r := res.GetCheckTx()
return &ctypes.ResultBroadcastTx{
return &coretypes.ResultBroadcastTx{
Code: r.Code,
Data: r.Data,
Log: r.Log,
@@ -59,7 +59,7 @@ func (env *Environment) BroadcastTxSync(ctx *rpctypes.Context, tx types.Tx) (*ct
// BroadcastTxCommit returns with the responses from CheckTx and DeliverTx.
// More: https://docs.tendermint.com/master/rpc/#/Tx/broadcast_tx_commit
func (env *Environment) BroadcastTxCommit(ctx *rpctypes.Context, tx types.Tx) (*ctypes.ResultBroadcastTxCommit, error) {
func (env *Environment) BroadcastTxCommit(ctx *rpctypes.Context, tx types.Tx) (*coretypes.ResultBroadcastTxCommit, error) { //nolint:lll
subscriber := ctx.RemoteAddr()
if env.EventBus.NumClients() >= env.Config.MaxSubscriptionClients {
@@ -91,7 +91,7 @@ func (env *Environment) BroadcastTxCommit(ctx *rpctypes.Context, tx types.Tx) (*
ctx.Context(),
tx,
func(res *abci.Response) { checkTxResCh <- res },
mempl.TxInfo{},
mempool.TxInfo{},
)
if err != nil {
env.Logger.Error("Error on broadcastTxCommit", "err", err)
@@ -102,7 +102,7 @@ func (env *Environment) BroadcastTxCommit(ctx *rpctypes.Context, tx types.Tx) (*
checkTxRes := checkTxResMsg.GetCheckTx()
if checkTxRes.Code != abci.CodeTypeOK {
return &ctypes.ResultBroadcastTxCommit{
return &coretypes.ResultBroadcastTxCommit{
CheckTx: *checkTxRes,
DeliverTx: abci.ResponseDeliverTx{},
Hash: tx.Hash(),
@@ -113,7 +113,7 @@ func (env *Environment) BroadcastTxCommit(ctx *rpctypes.Context, tx types.Tx) (*
select {
case msg := <-deliverTxSub.Out(): // The tx was included in a block.
deliverTxRes := msg.Data().(types.EventDataTx)
return &ctypes.ResultBroadcastTxCommit{
return &coretypes.ResultBroadcastTxCommit{
CheckTx: *checkTxRes,
DeliverTx: deliverTxRes.Result,
Hash: tx.Hash(),
@@ -128,7 +128,7 @@ func (env *Environment) BroadcastTxCommit(ctx *rpctypes.Context, tx types.Tx) (*
}
err = fmt.Errorf("deliverTxSub was canceled (reason: %s)", reason)
env.Logger.Error("Error on broadcastTxCommit", "err", err)
return &ctypes.ResultBroadcastTxCommit{
return &coretypes.ResultBroadcastTxCommit{
CheckTx: *checkTxRes,
DeliverTx: abci.ResponseDeliverTx{},
Hash: tx.Hash(),
@@ -136,7 +136,7 @@ func (env *Environment) BroadcastTxCommit(ctx *rpctypes.Context, tx types.Tx) (*
case <-time.After(env.Config.TimeoutBroadcastTxCommit):
err = errors.New("timed out waiting for tx to be included in a block")
env.Logger.Error("Error on broadcastTxCommit", "err", err)
return &ctypes.ResultBroadcastTxCommit{
return &coretypes.ResultBroadcastTxCommit{
CheckTx: *checkTxRes,
DeliverTx: abci.ResponseDeliverTx{},
Hash: tx.Hash(),
@@ -147,12 +147,12 @@ func (env *Environment) BroadcastTxCommit(ctx *rpctypes.Context, tx types.Tx) (*
// UnconfirmedTxs gets unconfirmed transactions (maximum ?limit entries)
// including their number.
// More: https://docs.tendermint.com/master/rpc/#/Info/unconfirmed_txs
func (env *Environment) UnconfirmedTxs(ctx *rpctypes.Context, limitPtr *int) (*ctypes.ResultUnconfirmedTxs, error) {
func (env *Environment) UnconfirmedTxs(ctx *rpctypes.Context, limitPtr *int) (*coretypes.ResultUnconfirmedTxs, error) {
// reuse per_page validator
limit := env.validatePerPage(limitPtr)
txs := env.Mempool.ReapMaxTxs(limit)
return &ctypes.ResultUnconfirmedTxs{
return &coretypes.ResultUnconfirmedTxs{
Count: len(txs),
Total: env.Mempool.Size(),
TotalBytes: env.Mempool.SizeBytes(),
@@ -161,8 +161,8 @@ func (env *Environment) UnconfirmedTxs(ctx *rpctypes.Context, limitPtr *int) (*c
// NumUnconfirmedTxs gets number of unconfirmed transactions.
// More: https://docs.tendermint.com/master/rpc/#/Info/num_unconfirmed_txs
func (env *Environment) NumUnconfirmedTxs(ctx *rpctypes.Context) (*ctypes.ResultUnconfirmedTxs, error) {
return &ctypes.ResultUnconfirmedTxs{
func (env *Environment) NumUnconfirmedTxs(ctx *rpctypes.Context) (*coretypes.ResultUnconfirmedTxs, error) {
return &coretypes.ResultUnconfirmedTxs{
Count: env.Mempool.Size(),
Total: env.Mempool.Size(),
TotalBytes: env.Mempool.SizeBytes()}, nil
@@ -171,10 +171,10 @@ func (env *Environment) NumUnconfirmedTxs(ctx *rpctypes.Context) (*ctypes.Result
// CheckTx checks the transaction without executing it. The transaction won't
// be added to the mempool either.
// More: https://docs.tendermint.com/master/rpc/#/Tx/check_tx
func (env *Environment) CheckTx(ctx *rpctypes.Context, tx types.Tx) (*ctypes.ResultCheckTx, error) {
func (env *Environment) CheckTx(ctx *rpctypes.Context, tx types.Tx) (*coretypes.ResultCheckTx, error) {
res, err := env.ProxyAppMempool.CheckTxSync(ctx.Context(), abci.RequestCheckTx{Tx: tx})
if err != nil {
return nil, err
}
return &ctypes.ResultCheckTx{ResponseCheckTx: *res}, nil
return &coretypes.ResultCheckTx{ResponseCheckTx: *res}, nil
}
+23 -23
View File
@@ -6,21 +6,21 @@ import (
"strings"
"github.com/tendermint/tendermint/internal/p2p"
ctypes "github.com/tendermint/tendermint/rpc/coretypes"
"github.com/tendermint/tendermint/rpc/coretypes"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
// NetInfo returns network info.
// More: https://docs.tendermint.com/master/rpc/#/Info/net_info
func (env *Environment) NetInfo(ctx *rpctypes.Context) (*ctypes.ResultNetInfo, error) {
var peers []ctypes.Peer
func (env *Environment) NetInfo(ctx *rpctypes.Context) (*coretypes.ResultNetInfo, error) {
var peers []coretypes.Peer
switch {
case env.P2PPeers != nil:
peersList := env.P2PPeers.Peers().List()
peers = make([]ctypes.Peer, 0, len(peersList))
peers = make([]coretypes.Peer, 0, len(peersList))
for _, peer := range peersList {
peers = append(peers, ctypes.Peer{
peers = append(peers, coretypes.Peer{
ID: peer.ID(),
URL: peer.SocketAddr().String(),
})
@@ -33,7 +33,7 @@ func (env *Environment) NetInfo(ctx *rpctypes.Context) (*ctypes.ResultNetInfo, e
continue
}
peers = append(peers, ctypes.Peer{
peers = append(peers, coretypes.Peer{
ID: peer,
URL: addrs[0].String(),
})
@@ -42,7 +42,7 @@ func (env *Environment) NetInfo(ctx *rpctypes.Context) (*ctypes.ResultNetInfo, e
return nil, errors.New("peer management system does not support NetInfo responses")
}
return &ctypes.ResultNetInfo{
return &coretypes.ResultNetInfo{
Listening: env.P2PTransport.IsListening(),
Listeners: env.P2PTransport.Listeners(),
NPeers: len(peers),
@@ -51,19 +51,19 @@ func (env *Environment) NetInfo(ctx *rpctypes.Context) (*ctypes.ResultNetInfo, e
}
// UnsafeDialSeeds dials the given seeds (comma-separated id@IP:PORT).
func (env *Environment) UnsafeDialSeeds(ctx *rpctypes.Context, seeds []string) (*ctypes.ResultDialSeeds, error) {
func (env *Environment) UnsafeDialSeeds(ctx *rpctypes.Context, seeds []string) (*coretypes.ResultDialSeeds, error) {
if env.P2PPeers == nil {
return nil, errors.New("peer management system does not support this operation")
}
if len(seeds) == 0 {
return &ctypes.ResultDialSeeds{}, fmt.Errorf("%w: no seeds provided", ctypes.ErrInvalidRequest)
return &coretypes.ResultDialSeeds{}, fmt.Errorf("%w: no seeds provided", coretypes.ErrInvalidRequest)
}
env.Logger.Info("DialSeeds", "seeds", seeds)
if err := env.P2PPeers.DialPeersAsync(seeds); err != nil {
return &ctypes.ResultDialSeeds{}, err
return &coretypes.ResultDialSeeds{}, err
}
return &ctypes.ResultDialSeeds{Log: "Dialing seeds in progress. See /net_info for details"}, nil
return &coretypes.ResultDialSeeds{Log: "Dialing seeds in progress. See /net_info for details"}, nil
}
// UnsafeDialPeers dials the given peers (comma-separated id@IP:PORT),
@@ -71,19 +71,19 @@ func (env *Environment) UnsafeDialSeeds(ctx *rpctypes.Context, seeds []string) (
func (env *Environment) UnsafeDialPeers(
ctx *rpctypes.Context,
peers []string,
persistent, unconditional, private bool) (*ctypes.ResultDialPeers, error) {
persistent, unconditional, private bool) (*coretypes.ResultDialPeers, error) {
if env.P2PPeers == nil {
return nil, errors.New("peer management system does not support this operation")
}
if len(peers) == 0 {
return &ctypes.ResultDialPeers{}, fmt.Errorf("%w: no peers provided", ctypes.ErrInvalidRequest)
return &coretypes.ResultDialPeers{}, fmt.Errorf("%w: no peers provided", coretypes.ErrInvalidRequest)
}
ids, err := getIDs(peers)
if err != nil {
return &ctypes.ResultDialPeers{}, err
return &coretypes.ResultDialPeers{}, err
}
env.Logger.Info("DialPeers", "peers", peers, "persistent",
@@ -91,40 +91,40 @@ func (env *Environment) UnsafeDialPeers(
if persistent {
if err := env.P2PPeers.AddPersistentPeers(peers); err != nil {
return &ctypes.ResultDialPeers{}, err
return &coretypes.ResultDialPeers{}, err
}
}
if private {
if err := env.P2PPeers.AddPrivatePeerIDs(ids); err != nil {
return &ctypes.ResultDialPeers{}, err
return &coretypes.ResultDialPeers{}, err
}
}
if unconditional {
if err := env.P2PPeers.AddUnconditionalPeerIDs(ids); err != nil {
return &ctypes.ResultDialPeers{}, err
return &coretypes.ResultDialPeers{}, err
}
}
if err := env.P2PPeers.DialPeersAsync(peers); err != nil {
return &ctypes.ResultDialPeers{}, err
return &coretypes.ResultDialPeers{}, err
}
return &ctypes.ResultDialPeers{Log: "Dialing peers in progress. See /net_info for details"}, nil
return &coretypes.ResultDialPeers{Log: "Dialing peers in progress. See /net_info for details"}, nil
}
// Genesis returns genesis file.
// More: https://docs.tendermint.com/master/rpc/#/Info/genesis
func (env *Environment) Genesis(ctx *rpctypes.Context) (*ctypes.ResultGenesis, error) {
func (env *Environment) Genesis(ctx *rpctypes.Context) (*coretypes.ResultGenesis, error) {
if len(env.genChunks) > 1 {
return nil, errors.New("genesis response is large, please use the genesis_chunked API instead")
}
return &ctypes.ResultGenesis{Genesis: env.GenDoc}, nil
return &coretypes.ResultGenesis{Genesis: env.GenDoc}, nil
}
func (env *Environment) GenesisChunked(ctx *rpctypes.Context, chunk uint) (*ctypes.ResultGenesisChunk, error) {
func (env *Environment) GenesisChunked(ctx *rpctypes.Context, chunk uint) (*coretypes.ResultGenesisChunk, error) {
if env.genChunks == nil {
return nil, fmt.Errorf("service configuration error, genesis chunks are not initialized")
}
@@ -139,7 +139,7 @@ func (env *Environment) GenesisChunked(ctx *rpctypes.Context, chunk uint) (*ctyp
return nil, fmt.Errorf("there are %d chunks, %d is invalid", len(env.genChunks)-1, id)
}
return &ctypes.ResultGenesisChunk{
return &coretypes.ResultGenesisChunk{
TotalChunks: len(env.genChunks),
ChunkNumber: id,
Data: env.genChunks[id],
+3 -3
View File
@@ -6,14 +6,14 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/internal/p2p"
"github.com/tendermint/tendermint/libs/log"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
func TestUnsafeDialSeeds(t *testing.T) {
sw := p2p.MakeSwitch(cfg.DefaultP2PConfig(), 1, "testing", "123.123.123",
sw := p2p.MakeSwitch(config.DefaultP2PConfig(), 1, "testing", "123.123.123",
func(n int, sw *p2p.Switch) *p2p.Switch { return sw }, log.TestingLogger())
err := sw.Start()
require.NoError(t, err)
@@ -48,7 +48,7 @@ func TestUnsafeDialSeeds(t *testing.T) {
}
func TestUnsafeDialPeers(t *testing.T) {
sw := p2p.MakeSwitch(cfg.DefaultP2PConfig(), 1, "testing", "123.123.123",
sw := p2p.MakeSwitch(config.DefaultP2PConfig(), 1, "testing", "123.123.123",
func(n int, sw *p2p.Switch) *p2p.Switch { return sw }, log.TestingLogger())
sw.SetAddrBook(&p2p.AddrBookMock{
Addrs: make(map[string]struct{}),
+6 -6
View File
@@ -5,7 +5,7 @@ import (
"time"
tmbytes "github.com/tendermint/tendermint/libs/bytes"
ctypes "github.com/tendermint/tendermint/rpc/coretypes"
"github.com/tendermint/tendermint/rpc/coretypes"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
"github.com/tendermint/tendermint/types"
)
@@ -13,7 +13,7 @@ import (
// Status returns Tendermint status including node info, pubkey, latest block
// hash, app hash, block height, current max peer block height, and time.
// More: https://docs.tendermint.com/master/rpc/#/Info/status
func (env *Environment) Status(ctx *rpctypes.Context) (*ctypes.ResultStatus, error) {
func (env *Environment) Status(ctx *rpctypes.Context) (*coretypes.ResultStatus, error) {
var (
earliestBlockHeight int64
earliestBlockHash tmbytes.HexBytes
@@ -50,17 +50,17 @@ func (env *Environment) Status(ctx *rpctypes.Context) (*ctypes.ResultStatus, err
if val := env.validatorAtHeight(env.latestUncommittedHeight()); val != nil {
votingPower = val.VotingPower
}
validatorInfo := ctypes.ValidatorInfo{}
validatorInfo := coretypes.ValidatorInfo{}
if env.PubKey != nil {
validatorInfo = ctypes.ValidatorInfo{
validatorInfo = coretypes.ValidatorInfo{
Address: env.PubKey.Address(),
PubKey: env.PubKey,
VotingPower: votingPower,
}
}
result := &ctypes.ResultStatus{
result := &coretypes.ResultStatus{
NodeInfo: env.P2PTransport.NodeInfo(),
SyncInfo: ctypes.SyncInfo{
SyncInfo: coretypes.SyncInfo{
LatestBlockHash: latestBlockHash,
LatestAppHash: latestAppHash,
LatestBlockHeight: latestHeight,
+8 -8
View File
@@ -9,7 +9,7 @@ import (
"github.com/tendermint/tendermint/libs/bytes"
tmmath "github.com/tendermint/tendermint/libs/math"
tmquery "github.com/tendermint/tendermint/libs/pubsub/query"
ctypes "github.com/tendermint/tendermint/rpc/coretypes"
"github.com/tendermint/tendermint/rpc/coretypes"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
"github.com/tendermint/tendermint/types"
)
@@ -18,7 +18,7 @@ import (
// transaction is in the mempool, invalidated, or was not sent in the first
// place.
// More: https://docs.tendermint.com/master/rpc/#/Info/tx
func (env *Environment) Tx(ctx *rpctypes.Context, hash bytes.HexBytes, prove bool) (*ctypes.ResultTx, error) {
func (env *Environment) Tx(ctx *rpctypes.Context, hash bytes.HexBytes, prove bool) (*coretypes.ResultTx, error) {
// if index is disabled, return error
// N.B. The hash parameter is HexBytes so that the reflective parameter
@@ -45,7 +45,7 @@ func (env *Environment) Tx(ctx *rpctypes.Context, hash bytes.HexBytes, prove boo
proof = block.Data.Txs.Proof(int(index)) // XXX: overflow on 32-bit machines
}
return &ctypes.ResultTx{
return &coretypes.ResultTx{
Hash: hash,
Height: height,
Index: index,
@@ -68,7 +68,7 @@ func (env *Environment) TxSearch(
prove bool,
pagePtr, perPagePtr *int,
orderBy string,
) (*ctypes.ResultTxSearch, error) {
) (*coretypes.ResultTxSearch, error) {
if !indexer.KVSinkEnabled(env.EventSinks) {
return nil, fmt.Errorf("transaction searching is disabled due to no kvEventSink")
@@ -103,7 +103,7 @@ func (env *Environment) TxSearch(
return results[i].Height < results[j].Height
})
default:
return nil, fmt.Errorf("expected order_by to be either `asc` or `desc` or empty: %w", ctypes.ErrInvalidRequest)
return nil, fmt.Errorf("expected order_by to be either `asc` or `desc` or empty: %w", coretypes.ErrInvalidRequest)
}
// paginate results
@@ -118,7 +118,7 @@ func (env *Environment) TxSearch(
skipCount := validateSkipCount(page, perPage)
pageSize := tmmath.MinInt(perPage, totalCount-skipCount)
apiResults := make([]*ctypes.ResultTx, 0, pageSize)
apiResults := make([]*coretypes.ResultTx, 0, pageSize)
for i := skipCount; i < skipCount+pageSize; i++ {
r := results[i]
@@ -128,7 +128,7 @@ func (env *Environment) TxSearch(
proof = block.Data.Txs.Proof(int(r.Index)) // XXX: overflow on 32-bit machines
}
apiResults = append(apiResults, &ctypes.ResultTx{
apiResults = append(apiResults, &coretypes.ResultTx{
Hash: types.Tx(r.Tx).Hash(),
Height: r.Height,
Index: r.Index,
@@ -138,7 +138,7 @@ func (env *Environment) TxSearch(
})
}
return &ctypes.ResultTxSearch{Txs: apiResults, TotalCount: totalCount}, nil
return &coretypes.ResultTxSearch{Txs: apiResults, TotalCount: totalCount}, nil
}
}
+6 -6
View File
@@ -7,9 +7,9 @@ import (
"time"
abci "github.com/tendermint/tendermint/abci/types"
cryptoenc "github.com/tendermint/tendermint/crypto/encoding"
"github.com/tendermint/tendermint/crypto/encoding"
"github.com/tendermint/tendermint/internal/libs/fail"
mempl "github.com/tendermint/tendermint/internal/mempool"
"github.com/tendermint/tendermint/internal/mempool"
"github.com/tendermint/tendermint/internal/proxy"
"github.com/tendermint/tendermint/libs/log"
tmstate "github.com/tendermint/tendermint/proto/tendermint/state"
@@ -37,7 +37,7 @@ type BlockExecutor struct {
// manage the mempool lock during commit
// and update both with block results after commit.
mempool mempl.Mempool
mempool mempool.Mempool
evpool EvidencePool
logger log.Logger
@@ -61,7 +61,7 @@ func NewBlockExecutor(
stateStore Store,
logger log.Logger,
proxyApp proxy.AppConnConsensus,
mempool mempl.Mempool,
pool mempool.Mempool,
evpool EvidencePool,
blockStore BlockStore,
options ...BlockExecutorOption,
@@ -70,7 +70,7 @@ func NewBlockExecutor(
store: stateStore,
proxyApp: proxyApp,
eventBus: types.NopEventBus{},
mempool: mempool,
mempool: pool,
evpool: evpool,
logger: logger,
metrics: NopMetrics(),
@@ -424,7 +424,7 @@ func validateValidatorUpdates(abciUpdates []abci.ValidatorUpdate,
}
// Check if validator's pubkey matches an ABCI type in the consensus params
pk, err := cryptoenc.PubKeyFromProto(valUpdate.PubKey)
pk, err := encoding.PubKeyFromProto(valUpdate.PubKey)
if err != nil {
return err
}
+8 -8
View File
@@ -8,12 +8,13 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
dbm "github.com/tendermint/tm-db"
abciclient "github.com/tendermint/tendermint/abci/client"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/crypto/ed25519"
cryptoenc "github.com/tendermint/tendermint/crypto/encoding"
"github.com/tendermint/tendermint/crypto/encoding"
"github.com/tendermint/tendermint/crypto/tmhash"
mmock "github.com/tendermint/tendermint/internal/mempool/mock"
"github.com/tendermint/tendermint/internal/proxy"
@@ -25,7 +26,6 @@ import (
"github.com/tendermint/tendermint/store"
"github.com/tendermint/tendermint/types"
"github.com/tendermint/tendermint/version"
dbm "github.com/tendermint/tm-db"
)
var (
@@ -218,9 +218,9 @@ func TestBeginBlockByzantineValidators(t *testing.T) {
func TestValidateValidatorUpdates(t *testing.T) {
pubkey1 := ed25519.GenPrivKey().PubKey()
pubkey2 := ed25519.GenPrivKey().PubKey()
pk1, err := cryptoenc.PubKeyToProto(pubkey1)
pk1, err := encoding.PubKeyToProto(pubkey1)
assert.NoError(t, err)
pk2, err := cryptoenc.PubKeyToProto(pubkey2)
pk2, err := encoding.PubKeyToProto(pubkey2)
assert.NoError(t, err)
defaultValidatorParams := types.ValidatorParams{PubKeyTypes: []string{types.ABCIPubKeyTypeEd25519}}
@@ -278,9 +278,9 @@ func TestUpdateValidators(t *testing.T) {
pubkey2 := ed25519.GenPrivKey().PubKey()
val2 := types.NewValidator(pubkey2, 20)
pk, err := cryptoenc.PubKeyToProto(pubkey1)
pk, err := encoding.PubKeyToProto(pubkey1)
require.NoError(t, err)
pk2, err := cryptoenc.PubKeyToProto(pubkey2)
pk2, err := encoding.PubKeyToProto(pubkey2)
require.NoError(t, err)
testCases := []struct {
@@ -385,7 +385,7 @@ func TestEndBlockValidatorUpdates(t *testing.T) {
blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: block.MakePartSet(testPartSize).Header()}
pubkey := ed25519.GenPrivKey().PubKey()
pk, err := cryptoenc.PubKeyToProto(pubkey)
pk, err := encoding.PubKeyToProto(pubkey)
require.NoError(t, err)
app.ValidatorUpdates = []abci.ValidatorUpdate{
{PubKey: pk, Power: 10},
@@ -442,7 +442,7 @@ func TestEndBlockValidatorUpdatesResultingInEmptySet(t *testing.T) {
block := sf.MakeBlock(state, 1, new(types.Commit))
blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: block.MakePartSet(testPartSize).Header()}
vp, err := cryptoenc.PubKeyToProto(state.Validators.Validators[0].PubKey)
vp, err := encoding.PubKeyToProto(state.Validators.Validators[0].PubKey)
require.NoError(t, err)
// Remove the only validator
app.ValidatorUpdates = []abci.ValidatorUpdate{
+4 -4
View File
@@ -11,7 +11,7 @@ import (
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/crypto/ed25519"
cryptoenc "github.com/tendermint/tendermint/crypto/encoding"
"github.com/tendermint/tendermint/crypto/encoding"
"github.com/tendermint/tendermint/internal/proxy"
sm "github.com/tendermint/tendermint/internal/state"
sf "github.com/tendermint/tendermint/internal/state/test/factory"
@@ -148,11 +148,11 @@ func makeHeaderPartsResponsesValPubKeyChange(
// If the pubkey is new, remove the old and add the new.
_, val := state.NextValidators.GetByIndex(0)
if !bytes.Equal(pubkey.Bytes(), val.PubKey.Bytes()) {
vPbPk, err := cryptoenc.PubKeyToProto(val.PubKey)
vPbPk, err := encoding.PubKeyToProto(val.PubKey)
if err != nil {
panic(err)
}
pbPk, err := cryptoenc.PubKeyToProto(pubkey)
pbPk, err := encoding.PubKeyToProto(pubkey)
if err != nil {
panic(err)
}
@@ -181,7 +181,7 @@ func makeHeaderPartsResponsesValPowerChange(
// If the pubkey is new, remove the old and add the new.
_, val := state.NextValidators.GetByIndex(0)
if val.VotingPower != power {
vPbPk, err := cryptoenc.PubKeyToProto(val.PubKey)
vPbPk, err := encoding.PubKeyToProto(val.PubKey)
if err != nil {
panic(err)
}
+3 -2
View File
@@ -6,15 +6,16 @@ import (
"testing"
"github.com/stretchr/testify/require"
dbm "github.com/tendermint/tm-db"
abci "github.com/tendermint/tendermint/abci/types"
blockidxkv "github.com/tendermint/tendermint/internal/state/indexer/block/kv"
"github.com/tendermint/tendermint/libs/pubsub/query"
"github.com/tendermint/tendermint/types"
db "github.com/tendermint/tm-db"
)
func TestBlockIndexer(t *testing.T) {
store := db.NewPrefixDB(db.NewMemDB(), []byte("block_events"))
store := dbm.NewPrefixDB(dbm.NewMemDB(), []byte("block_events"))
indexer := blockidxkv.New(store)
require.NoError(t, indexer.Index(types.EventDataNewBlockHeader{
@@ -9,11 +9,11 @@ import (
"time"
"github.com/adlio/schema"
_ "github.com/lib/pq"
dockertest "github.com/ory/dockertest"
"github.com/ory/dockertest/docker"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
dbm "github.com/tendermint/tm-db"
abci "github.com/tendermint/tendermint/abci/types"
indexer "github.com/tendermint/tendermint/internal/state/indexer"
@@ -21,7 +21,9 @@ import (
psql "github.com/tendermint/tendermint/internal/state/indexer/sink/psql"
tmlog "github.com/tendermint/tendermint/libs/log"
"github.com/tendermint/tendermint/types"
db "github.com/tendermint/tm-db"
// Register the Postgre database driver.
_ "github.com/lib/pq"
)
var psqldb *sql.DB
@@ -55,7 +57,7 @@ func TestIndexerServiceIndexesBlocks(t *testing.T) {
pool, err := setupDB(t)
assert.Nil(t, err)
store := db.NewMemDB()
store := dbm.NewMemDB()
eventSinks := []indexer.EventSink{kv.NewEventSink(store), pSink}
assert.True(t, indexer.KVSinkEnabled(eventSinks))
assert.True(t, indexer.IndexingEnabled(eventSinks))
+2 -1
View File
@@ -3,13 +3,14 @@ package kv
import (
"context"
dbm "github.com/tendermint/tm-db"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/internal/state/indexer"
kvb "github.com/tendermint/tendermint/internal/state/indexer/block/kv"
kvt "github.com/tendermint/tendermint/internal/state/indexer/tx/kv"
"github.com/tendermint/tendermint/libs/pubsub/query"
"github.com/tendermint/tendermint/types"
dbm "github.com/tendermint/tm-db"
)
var _ indexer.EventSink = (*EventSink)(nil)
+9 -8
View File
@@ -5,6 +5,8 @@ import (
"fmt"
"testing"
dbm "github.com/tendermint/tm-db"
"github.com/gogo/protobuf/proto"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -13,21 +15,20 @@ import (
kvtx "github.com/tendermint/tendermint/internal/state/indexer/tx/kv"
"github.com/tendermint/tendermint/libs/pubsub/query"
"github.com/tendermint/tendermint/types"
db "github.com/tendermint/tm-db"
)
func TestType(t *testing.T) {
kvSink := NewEventSink(db.NewMemDB())
kvSink := NewEventSink(dbm.NewMemDB())
assert.Equal(t, indexer.KV, kvSink.Type())
}
func TestStop(t *testing.T) {
kvSink := NewEventSink(db.NewMemDB())
kvSink := NewEventSink(dbm.NewMemDB())
assert.Nil(t, kvSink.Stop())
}
func TestBlockFuncs(t *testing.T) {
store := db.NewPrefixDB(db.NewMemDB(), []byte("block_events"))
store := dbm.NewPrefixDB(dbm.NewMemDB(), []byte("block_events"))
indexer := NewEventSink(store)
require.NoError(t, indexer.IndexBlockEvents(types.EventDataNewBlockHeader{
@@ -158,7 +159,7 @@ func TestBlockFuncs(t *testing.T) {
}
func TestTxSearchWithCancelation(t *testing.T) {
indexer := NewEventSink(db.NewMemDB())
indexer := NewEventSink(dbm.NewMemDB())
txResult := txResultWithEvents([]abci.Event{
{Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: "1", Index: true}}},
@@ -180,7 +181,7 @@ func TestTxSearchWithCancelation(t *testing.T) {
}
func TestTxSearchDeprecatedIndexing(t *testing.T) {
esdb := db.NewMemDB()
esdb := dbm.NewMemDB()
indexer := NewEventSink(esdb)
// index tx using events indexing (composite key)
@@ -260,7 +261,7 @@ func TestTxSearchDeprecatedIndexing(t *testing.T) {
}
func TestTxSearchOneTxWithMultipleSameTagsButDifferentValues(t *testing.T) {
indexer := NewEventSink(db.NewMemDB())
indexer := NewEventSink(dbm.NewMemDB())
txResult := txResultWithEvents([]abci.Event{
{Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: "1", Index: true}}},
@@ -282,7 +283,7 @@ func TestTxSearchOneTxWithMultipleSameTagsButDifferentValues(t *testing.T) {
}
func TestTxSearchMultipleTxs(t *testing.T) {
indexer := NewEventSink(db.NewMemDB())
indexer := NewEventSink(dbm.NewMemDB())
// indexed first, but bigger height (to test the order of transactions)
txResult := txResultWithEvents([]abci.Event{
+8 -9
View File
@@ -10,8 +10,7 @@ import (
"github.com/gogo/protobuf/proto"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
db "github.com/tendermint/tm-db"
dbm "github.com/tendermint/tm-db"
abci "github.com/tendermint/tendermint/abci/types"
indexer "github.com/tendermint/tendermint/internal/state/indexer"
@@ -21,7 +20,7 @@ import (
)
func TestTxIndex(t *testing.T) {
txIndexer := NewTxIndex(db.NewMemDB())
txIndexer := NewTxIndex(dbm.NewMemDB())
tx := types.Tx("HELLO WORLD")
txResult := &abci.TxResult{
@@ -67,7 +66,7 @@ func TestTxIndex(t *testing.T) {
}
func TestTxSearch(t *testing.T) {
indexer := NewTxIndex(db.NewMemDB())
indexer := NewTxIndex(dbm.NewMemDB())
txResult := txResultWithEvents([]abci.Event{
{Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: "1", Index: true}}},
@@ -147,7 +146,7 @@ func TestTxSearch(t *testing.T) {
}
func TestTxSearchWithCancelation(t *testing.T) {
indexer := NewTxIndex(db.NewMemDB())
indexer := NewTxIndex(dbm.NewMemDB())
txResult := txResultWithEvents([]abci.Event{
{Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: "1", Index: true}}},
@@ -165,7 +164,7 @@ func TestTxSearchWithCancelation(t *testing.T) {
}
func TestTxSearchDeprecatedIndexing(t *testing.T) {
indexer := NewTxIndex(db.NewMemDB())
indexer := NewTxIndex(dbm.NewMemDB())
// index tx using events indexing (composite key)
txResult1 := txResultWithEvents([]abci.Event{
@@ -244,7 +243,7 @@ func TestTxSearchDeprecatedIndexing(t *testing.T) {
}
func TestTxSearchOneTxWithMultipleSameTagsButDifferentValues(t *testing.T) {
indexer := NewTxIndex(db.NewMemDB())
indexer := NewTxIndex(dbm.NewMemDB())
txResult := txResultWithEvents([]abci.Event{
{Type: "account", Attributes: []abci.EventAttribute{{Key: "number", Value: "1", Index: true}}},
@@ -266,7 +265,7 @@ func TestTxSearchOneTxWithMultipleSameTagsButDifferentValues(t *testing.T) {
}
func TestTxSearchMultipleTxs(t *testing.T) {
indexer := NewTxIndex(db.NewMemDB())
indexer := NewTxIndex(dbm.NewMemDB())
// indexed first, but bigger height (to test the order of transactions)
txResult := txResultWithEvents([]abci.Event{
@@ -339,7 +338,7 @@ func benchmarkTxIndex(txsCount int64, b *testing.B) {
require.NoError(b, err)
defer os.RemoveAll(dir)
store, err := db.NewDB("tx_index", "goleveldb", dir)
store, err := dbm.NewDB("tx_index", "goleveldb", dir)
require.NoError(b, err)
txIndexer := NewTxIndex(store)
+25 -26
View File
@@ -12,36 +12,35 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
dbm "github.com/tendermint/tm-db"
abci "github.com/tendermint/tendermint/abci/types"
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/crypto/ed25519"
cryptoenc "github.com/tendermint/tendermint/crypto/encoding"
"github.com/tendermint/tendermint/crypto/encoding"
sm "github.com/tendermint/tendermint/internal/state"
sf "github.com/tendermint/tendermint/internal/state/test/factory"
statefactory "github.com/tendermint/tendermint/internal/state/test/factory"
tmstate "github.com/tendermint/tendermint/proto/tendermint/state"
"github.com/tendermint/tendermint/types"
)
// setupTestCase does setup common to all test cases.
func setupTestCase(t *testing.T) (func(t *testing.T), dbm.DB, sm.State) {
config := cfg.ResetTestRoot("state_")
dbType := dbm.BackendType(config.DBBackend)
stateDB, err := dbm.NewDB("state", dbType, config.DBDir())
cfg := config.ResetTestRoot("state_")
dbType := dbm.BackendType(cfg.DBBackend)
stateDB, err := dbm.NewDB("state", dbType, cfg.DBDir())
require.NoError(t, err)
stateStore := sm.NewStore(stateDB)
state, err := stateStore.Load()
require.NoError(t, err)
require.Empty(t, state)
state, err = sm.MakeGenesisStateFromFile(config.GenesisFile())
state, err = sm.MakeGenesisStateFromFile(cfg.GenesisFile())
assert.NoError(t, err)
assert.NotNil(t, state)
err = stateStore.Save(state)
require.NoError(t, err)
tearDown := func(t *testing.T) { os.RemoveAll(config.RootDir) }
tearDown := func(t *testing.T) { os.RemoveAll(cfg.RootDir) }
return tearDown, stateDB, state
}
@@ -106,7 +105,7 @@ func TestABCIResponsesSaveLoad1(t *testing.T) {
state.LastBlockHeight++
// Build mock responses.
block := sf.MakeBlock(state, 2, new(types.Commit))
block := statefactory.MakeBlock(state, 2, new(types.Commit))
abciResponses := new(tmstate.ABCIResponses)
dtxs := make([]*abci.ResponseDeliverTx, 2)
@@ -114,7 +113,7 @@ func TestABCIResponsesSaveLoad1(t *testing.T) {
abciResponses.DeliverTxs[0] = &abci.ResponseDeliverTx{Data: []byte("foo"), Events: nil}
abciResponses.DeliverTxs[1] = &abci.ResponseDeliverTx{Data: []byte("bar"), Log: "ok", Events: nil}
pbpk, err := cryptoenc.PubKeyToProto(ed25519.GenPrivKey().PubKey())
pbpk, err := encoding.PubKeyToProto(ed25519.GenPrivKey().PubKey())
require.NoError(t, err)
abciResponses.EndBlock = &abci.ResponseEndBlock{ValidatorUpdates: []abci.ValidatorUpdate{{PubKey: pbpk, Power: 10}}}
@@ -448,7 +447,7 @@ func TestProposerPriorityDoesNotGetResetToZero(t *testing.T) {
// NewValidatorSet calls IncrementProposerPriority but uses on a copy of val1
assert.EqualValues(t, 0, val1.ProposerPriority)
block := sf.MakeBlock(state, state.LastBlockHeight+1, new(types.Commit))
block := statefactory.MakeBlock(state, state.LastBlockHeight+1, new(types.Commit))
blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: block.MakePartSet(testPartSize).Header()}
abciResponses := &tmstate.ABCIResponses{
BeginBlock: &abci.ResponseBeginBlock{},
@@ -465,7 +464,7 @@ func TestProposerPriorityDoesNotGetResetToZero(t *testing.T) {
// add a validator
val2PubKey := ed25519.GenPrivKey().PubKey()
val2VotingPower := int64(100)
fvp, err := cryptoenc.PubKeyToProto(val2PubKey)
fvp, err := encoding.PubKeyToProto(val2PubKey)
require.NoError(t, err)
updateAddVal := abci.ValidatorUpdate{PubKey: fvp, Power: val2VotingPower}
@@ -562,7 +561,7 @@ func TestProposerPriorityProposerAlternates(t *testing.T) {
// we only have one validator:
assert.Equal(t, val1PubKey.Address(), state.Validators.Proposer.Address)
block := sf.MakeBlock(state, state.LastBlockHeight+1, new(types.Commit))
block := statefactory.MakeBlock(state, state.LastBlockHeight+1, new(types.Commit))
blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: block.MakePartSet(testPartSize).Header()}
// no updates:
abciResponses := &tmstate.ABCIResponses{
@@ -583,7 +582,7 @@ func TestProposerPriorityProposerAlternates(t *testing.T) {
// add a validator with the same voting power as the first
val2PubKey := ed25519.GenPrivKey().PubKey()
fvp, err := cryptoenc.PubKeyToProto(val2PubKey)
fvp, err := encoding.PubKeyToProto(val2PubKey)
require.NoError(t, err)
updateAddVal := abci.ValidatorUpdate{PubKey: fvp, Power: val1VotingPower}
validatorUpdates, err = types.PB2TM.ValidatorUpdates([]abci.ValidatorUpdate{updateAddVal})
@@ -749,7 +748,7 @@ func TestLargeGenesisValidator(t *testing.T) {
validatorUpdates, err := types.PB2TM.ValidatorUpdates(abciResponses.EndBlock.ValidatorUpdates)
require.NoError(t, err)
block := sf.MakeBlock(oldState, oldState.LastBlockHeight+1, new(types.Commit))
block := statefactory.MakeBlock(oldState, oldState.LastBlockHeight+1, new(types.Commit))
blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: block.MakePartSet(testPartSize).Header()}
updatedState, err := sm.UpdateState(oldState, blockID, &block.Header, abciResponses, validatorUpdates)
@@ -769,7 +768,7 @@ func TestLargeGenesisValidator(t *testing.T) {
// see: https://github.com/tendermint/tendermint/issues/2960
firstAddedValPubKey := ed25519.GenPrivKey().PubKey()
firstAddedValVotingPower := int64(10)
fvp, err := cryptoenc.PubKeyToProto(firstAddedValPubKey)
fvp, err := encoding.PubKeyToProto(firstAddedValPubKey)
require.NoError(t, err)
firstAddedVal := abci.ValidatorUpdate{PubKey: fvp, Power: firstAddedValVotingPower}
validatorUpdates, err := types.PB2TM.ValidatorUpdates([]abci.ValidatorUpdate{firstAddedVal})
@@ -778,7 +777,7 @@ func TestLargeGenesisValidator(t *testing.T) {
BeginBlock: &abci.ResponseBeginBlock{},
EndBlock: &abci.ResponseEndBlock{ValidatorUpdates: []abci.ValidatorUpdate{firstAddedVal}},
}
block := sf.MakeBlock(oldState, oldState.LastBlockHeight+1, new(types.Commit))
block := statefactory.MakeBlock(oldState, oldState.LastBlockHeight+1, new(types.Commit))
blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: block.MakePartSet(testPartSize).Header()}
updatedState, err := sm.UpdateState(oldState, blockID, &block.Header, abciResponses, validatorUpdates)
require.NoError(t, err)
@@ -793,7 +792,7 @@ func TestLargeGenesisValidator(t *testing.T) {
validatorUpdates, err := types.PB2TM.ValidatorUpdates(abciResponses.EndBlock.ValidatorUpdates)
require.NoError(t, err)
block := sf.MakeBlock(lastState, lastState.LastBlockHeight+1, new(types.Commit))
block := statefactory.MakeBlock(lastState, lastState.LastBlockHeight+1, new(types.Commit))
blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: block.MakePartSet(testPartSize).Header()}
updatedStateInner, err := sm.UpdateState(lastState, blockID, &block.Header, abciResponses, validatorUpdates)
@@ -816,7 +815,7 @@ func TestLargeGenesisValidator(t *testing.T) {
// add 10 validators with the same voting power as the one added directly after genesis:
for i := 0; i < 10; i++ {
addedPubKey := ed25519.GenPrivKey().PubKey()
ap, err := cryptoenc.PubKeyToProto(addedPubKey)
ap, err := encoding.PubKeyToProto(addedPubKey)
require.NoError(t, err)
addedVal := abci.ValidatorUpdate{PubKey: ap, Power: firstAddedValVotingPower}
validatorUpdates, err := types.PB2TM.ValidatorUpdates([]abci.ValidatorUpdate{addedVal})
@@ -826,7 +825,7 @@ func TestLargeGenesisValidator(t *testing.T) {
BeginBlock: &abci.ResponseBeginBlock{},
EndBlock: &abci.ResponseEndBlock{ValidatorUpdates: []abci.ValidatorUpdate{addedVal}},
}
block := sf.MakeBlock(oldState, oldState.LastBlockHeight+1, new(types.Commit))
block := statefactory.MakeBlock(oldState, oldState.LastBlockHeight+1, new(types.Commit))
blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: block.MakePartSet(testPartSize).Header()}
state, err = sm.UpdateState(state, blockID, &block.Header, abciResponses, validatorUpdates)
require.NoError(t, err)
@@ -834,14 +833,14 @@ func TestLargeGenesisValidator(t *testing.T) {
require.Equal(t, 10+2, len(state.NextValidators.Validators))
// remove genesis validator:
gp, err := cryptoenc.PubKeyToProto(genesisPubKey)
gp, err := encoding.PubKeyToProto(genesisPubKey)
require.NoError(t, err)
removeGenesisVal := abci.ValidatorUpdate{PubKey: gp, Power: 0}
abciResponses = &tmstate.ABCIResponses{
BeginBlock: &abci.ResponseBeginBlock{},
EndBlock: &abci.ResponseEndBlock{ValidatorUpdates: []abci.ValidatorUpdate{removeGenesisVal}},
}
block = sf.MakeBlock(oldState, oldState.LastBlockHeight+1, new(types.Commit))
block = statefactory.MakeBlock(oldState, oldState.LastBlockHeight+1, new(types.Commit))
blockID = types.BlockID{Hash: block.Hash(), PartSetHeader: block.MakePartSet(testPartSize).Header()}
validatorUpdates, err = types.PB2TM.ValidatorUpdates(abciResponses.EndBlock.ValidatorUpdates)
require.NoError(t, err)
@@ -862,7 +861,7 @@ func TestLargeGenesisValidator(t *testing.T) {
}
validatorUpdates, err = types.PB2TM.ValidatorUpdates(abciResponses.EndBlock.ValidatorUpdates)
require.NoError(t, err)
block = sf.MakeBlock(curState, curState.LastBlockHeight+1, new(types.Commit))
block = statefactory.MakeBlock(curState, curState.LastBlockHeight+1, new(types.Commit))
blockID = types.BlockID{Hash: block.Hash(), PartSetHeader: block.MakePartSet(testPartSize).Header()}
curState, err = sm.UpdateState(curState, blockID, &block.Header, abciResponses, validatorUpdates)
require.NoError(t, err)
@@ -887,7 +886,7 @@ func TestLargeGenesisValidator(t *testing.T) {
validatorUpdates, err := types.PB2TM.ValidatorUpdates(abciResponses.EndBlock.ValidatorUpdates)
require.NoError(t, err)
block := sf.MakeBlock(updatedState, updatedState.LastBlockHeight+1, new(types.Commit))
block := statefactory.MakeBlock(updatedState, updatedState.LastBlockHeight+1, new(types.Commit))
blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: block.MakePartSet(testPartSize).Header()}
updatedState, err = sm.UpdateState(updatedState, blockID, &block.Header, abciResponses, validatorUpdates)
@@ -982,7 +981,7 @@ func TestStateMakeBlock(t *testing.T) {
proposerAddress := state.Validators.GetProposer().Address
stateVersion := state.Version.Consensus
block := sf.MakeBlock(state, 2, new(types.Commit))
block := statefactory.MakeBlock(state, 2, new(types.Commit))
// test we set some fields
assert.Equal(t, stateVersion, block.Version)
+6 -7
View File
@@ -7,11 +7,10 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
dbm "github.com/tendermint/tm-db"
abci "github.com/tendermint/tendermint/abci/types"
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/crypto/ed25519"
sm "github.com/tendermint/tendermint/internal/state"
@@ -102,13 +101,13 @@ func TestStoreLoadValidators(t *testing.T) {
func BenchmarkLoadValidators(b *testing.B) {
const valSetSize = 100
config := cfg.ResetTestRoot("state_")
defer os.RemoveAll(config.RootDir)
dbType := dbm.BackendType(config.DBBackend)
stateDB, err := dbm.NewDB("state", dbType, config.DBDir())
cfg := config.ResetTestRoot("state_")
defer os.RemoveAll(cfg.RootDir)
dbType := dbm.BackendType(cfg.DBBackend)
stateDB, err := dbm.NewDB("state", dbType, cfg.DBDir())
require.NoError(b, err)
stateStore := sm.NewStore(stateDB)
state, err := sm.MakeGenesisStateFromFile(config.GenesisFile())
state, err := sm.MakeGenesisStateFromFile(cfg.GenesisFile())
if err != nil {
b.Fatal(err)
}
+5 -5
View File
@@ -1,22 +1,22 @@
package state
import (
mempl "github.com/tendermint/tendermint/internal/mempool"
"github.com/tendermint/tendermint/internal/mempool"
"github.com/tendermint/tendermint/types"
)
// TxPreCheck returns a function to filter transactions before processing.
// The function limits the size of a transaction to the block's maximum data size.
func TxPreCheck(state State) mempl.PreCheckFunc {
func TxPreCheck(state State) mempool.PreCheckFunc {
maxDataBytes := types.MaxDataBytesNoEvidence(
state.ConsensusParams.Block.MaxBytes,
state.Validators.Size(),
)
return mempl.PreCheckMaxBytes(maxDataBytes)
return mempool.PreCheckMaxBytes(maxDataBytes)
}
// TxPostCheck returns a function to filter transactions after processing.
// The function limits the gas wanted by a transaction to the block's maximum total gas.
func TxPostCheck(state State) mempl.PostCheckFunc {
return mempl.PostCheckMaxGas(state.ConsensusParams.Block.MaxGas)
func TxPostCheck(state State) mempool.PostCheckFunc {
return mempool.PostCheckMaxGas(state.ConsensusParams.Block.MaxGas)
}
+10 -10
View File
@@ -8,6 +8,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
dbm "github.com/tendermint/tm-db"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/crypto/ed25519"
@@ -15,14 +16,13 @@ import (
memmock "github.com/tendermint/tendermint/internal/mempool/mock"
sm "github.com/tendermint/tendermint/internal/state"
"github.com/tendermint/tendermint/internal/state/mocks"
sf "github.com/tendermint/tendermint/internal/state/test/factory"
"github.com/tendermint/tendermint/internal/test/factory"
statefactory "github.com/tendermint/tendermint/internal/state/test/factory"
testfactory "github.com/tendermint/tendermint/internal/test/factory"
"github.com/tendermint/tendermint/libs/log"
tmtime "github.com/tendermint/tendermint/libs/time"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/tendermint/tendermint/store"
"github.com/tendermint/tendermint/types"
dbm "github.com/tendermint/tm-db"
)
const validationTestsStopHeight int64 = 10
@@ -90,7 +90,7 @@ func TestValidateBlockHeader(t *testing.T) {
Invalid blocks don't pass
*/
for _, tc := range testCases {
block := sf.MakeBlock(state, height, lastCommit)
block := statefactory.MakeBlock(state, height, lastCommit)
tc.malleateBlock(block)
err := blockExec.ValidateBlock(state, block)
t.Logf("%s: %v", tc.name, err)
@@ -107,7 +107,7 @@ func TestValidateBlockHeader(t *testing.T) {
}
nextHeight := validationTestsStopHeight
block := sf.MakeBlock(state, nextHeight, lastCommit)
block := statefactory.MakeBlock(state, nextHeight, lastCommit)
state.InitialHeight = nextHeight + 1
err := blockExec.ValidateBlock(state, block)
require.Error(t, err, "expected an error when state is ahead of block")
@@ -141,7 +141,7 @@ func TestValidateBlockCommit(t *testing.T) {
#2589: ensure state.LastValidators.VerifyCommit fails here
*/
// should be height-1 instead of height
wrongHeightVote, err := factory.MakeVote(
wrongHeightVote, err := testfactory.MakeVote(
privVals[proposerAddr.String()],
chainID,
1,
@@ -158,7 +158,7 @@ func TestValidateBlockCommit(t *testing.T) {
state.LastBlockID,
[]types.CommitSig{wrongHeightVote.CommitSig()},
)
block := sf.MakeBlock(state, height, wrongHeightCommit)
block := statefactory.MakeBlock(state, height, wrongHeightCommit)
err = blockExec.ValidateBlock(state, block)
_, isErrInvalidCommitHeight := err.(types.ErrInvalidCommitHeight)
require.True(t, isErrInvalidCommitHeight, "expected ErrInvalidCommitHeight at height %d but got: %v", height, err)
@@ -166,7 +166,7 @@ func TestValidateBlockCommit(t *testing.T) {
/*
#2589: test len(block.LastCommit.Signatures) == state.LastValidators.Size()
*/
block = sf.MakeBlock(state, height, wrongSigsCommit)
block = statefactory.MakeBlock(state, height, wrongSigsCommit)
err = blockExec.ValidateBlock(state, block)
_, isErrInvalidCommitSignatures := err.(types.ErrInvalidCommitSignatures)
require.True(t, isErrInvalidCommitSignatures,
@@ -195,7 +195,7 @@ func TestValidateBlockCommit(t *testing.T) {
/*
wrongSigsCommit is fine except for the extra bad precommit
*/
goodVote, err := factory.MakeVote(
goodVote, err := testfactory.MakeVote(
privVals[proposerAddr.String()],
chainID,
1,
@@ -278,7 +278,7 @@ func TestValidateBlockEvidence(t *testing.T) {
evidence = append(evidence, newEv)
currentBytes += int64(len(newEv.Bytes()))
}
block, _ := state.MakeBlock(height, factory.MakeTenTxs(height), lastCommit, evidence, proposerAddr)
block, _ := state.MakeBlock(height, testfactory.MakeTenTxs(height), lastCommit, evidence, proposerAddr)
err := blockExec.ValidateBlock(state, block)
if assert.Error(t, err) {
_, ok := err.(*types.ErrEvidenceOverflow)
+2 -2
View File
@@ -9,7 +9,7 @@ import (
"github.com/tendermint/tendermint/internal/p2p"
"github.com/tendermint/tendermint/light/provider"
ssproto "github.com/tendermint/tendermint/proto/tendermint/statesync"
proto "github.com/tendermint/tendermint/proto/tendermint/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/tendermint/tendermint/types"
)
@@ -109,7 +109,7 @@ func (d *Dispatcher) dispatch(peer types.NodeID, height int64) (chan *types.Ligh
// Respond allows the underlying process which receives requests on the
// requestCh to respond with the respective light block. A nil response is used to
// represent that the receiver of the request does not have a light block at that height.
func (d *Dispatcher) Respond(lb *proto.LightBlock, peer types.NodeID) error {
func (d *Dispatcher) Respond(lb *tmproto.LightBlock, peer types.NodeID) error {
d.mtx.Lock()
defer d.mtx.Unlock()
+3 -3
View File
@@ -3,13 +3,13 @@ package factory
import (
"sort"
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/config"
tmtime "github.com/tendermint/tendermint/libs/time"
"github.com/tendermint/tendermint/types"
)
func RandGenesisDoc(
config *cfg.Config,
cfg *config.Config,
numValidators int,
randPower bool,
minPower int64) (*types.GenesisDoc, []types.PrivValidator) {
@@ -29,7 +29,7 @@ func RandGenesisDoc(
return &types.GenesisDoc{
GenesisTime: tmtime.Now(),
InitialHeight: 1,
ChainID: config.ChainID(),
ChainID: cfg.ChainID(),
Validators: validators,
}, privValidators
}