From 95980d944bec0b11434d817e32c74f4aadd360bf Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Tue, 10 Jul 2018 18:15:12 +0400 Subject: [PATCH 01/17] [types] add tests for Block and Commit Refs #693 --- types/block.go | 6 +- types/block_test.go | 131 +++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 135 insertions(+), 2 deletions(-) diff --git a/types/block.go b/types/block.go index bc018ee8..e23fd71d 100644 --- a/types/block.go +++ b/types/block.go @@ -107,6 +107,7 @@ func (b *Block) Hash() cmn.HexBytes { // MakePartSet returns a PartSet containing parts of a serialized block. // This is the form in which the block is gossipped to peers. +// CONTRACT: partSize is greater than zero. func (b *Block) MakePartSet(partSize int) *PartSet { if b == nil { return nil @@ -208,7 +209,7 @@ type Header struct { // Hash returns the hash of the header. // Returns nil if ValidatorHash is missing, // since a Header is not valid unless there is -// a ValidaotrsHash (corresponding to the validator set). +// a ValidatorsHash (corresponding to the validator set). func (h *Header) Hash() cmn.HexBytes { if h == nil || len(h.ValidatorsHash) == 0 { return nil @@ -392,6 +393,9 @@ func (commit *Commit) ValidateBasic() error { // Hash returns the hash of the commit func (commit *Commit) Hash() cmn.HexBytes { + if commit == nil { + return nil + } if commit.hash == nil { bs := make([]merkle.Hasher, len(commit.Precommits)) for i, precommit := range commit.Precommits { diff --git a/types/block_test.go b/types/block_test.go index 0948e7b2..1d27a774 100644 --- a/types/block_test.go +++ b/types/block_test.go @@ -10,7 +10,25 @@ import ( cmn "github.com/tendermint/tendermint/libs/common" ) -func TestValidateBlock(t *testing.T) { +func TestBlockAddEvidence(t *testing.T) { + txs := []Tx{Tx("foo"), Tx("bar")} + lastID := makeBlockIDRandom() + h := int64(3) + + voteSet, valSet, vals := randVoteSet(h-1, 1, VoteTypePrecommit, 10, 1) + commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals) + require.NoError(t, err) + + block := MakeBlock(h, txs, commit) + require.NotNil(t, block) + + ev := NewMockGoodEvidence(h, 0, valSet.Validators[0].Address) + block.AddEvidence([]Evidence{ev}) +} + +func TestBlockValidateBasic(t *testing.T) { + require.Error(t, (*Block)(nil).ValidateBasic()) + txs := []Tx{Tx("foo"), Tx("bar")} lastID := makeBlockIDRandom() h := int64(3) @@ -57,6 +75,59 @@ func TestValidateBlock(t *testing.T) { block.DataHash = cmn.RandBytes(len(block.DataHash)) err = block.ValidateBasic() require.Error(t, err) + + // tamper with evidence + block = MakeBlock(h, txs, commit) + block.EvidenceHash = []byte("something else") + err = block.ValidateBasic() + require.Error(t, err) +} + +func TestBlockHash(t *testing.T) { + assert.Nil(t, (*Block)(nil).Hash()) + assert.Nil(t, MakeBlock(int64(3), []Tx{Tx("Hello World")}, nil).Hash()) +} + +func TestBlockMakePartSet(t *testing.T) { + assert.Nil(t, (*Block)(nil).MakePartSet(2)) + + partSet := MakeBlock(int64(3), []Tx{Tx("Hello World")}, nil).MakePartSet(1024) + assert.NotNil(t, partSet) + assert.Equal(t, 1, partSet.Total()) +} + +func TestBlockHashesTo(t *testing.T) { + assert.False(t, (*Block)(nil).HashesTo(nil)) + + lastID := makeBlockIDRandom() + h := int64(3) + voteSet, valSet, vals := randVoteSet(h-1, 1, VoteTypePrecommit, 10, 1) + commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals) + require.NoError(t, err) + + block := MakeBlock(h, []Tx{Tx("Hello World")}, commit) + block.ValidatorsHash = valSet.Hash() + assert.False(t, block.HashesTo([]byte{})) + assert.False(t, block.HashesTo([]byte("something else"))) + assert.True(t, block.HashesTo(block.Hash())) +} + +func TestBlockSize(t *testing.T) { + size := MakeBlock(int64(3), []Tx{Tx("Hello World")}, nil).Size() + if size <= 0 { + t.Fatal("Size of the block is zero or negative") + } +} + +func TestBlockString(t *testing.T) { + assert.Equal(t, "nil-Block", (*Block)(nil).String()) + assert.Equal(t, "nil-Block", (*Block)(nil).StringIndented("")) + assert.Equal(t, "nil-Block", (*Block)(nil).StringShort()) + + block := MakeBlock(int64(3), []Tx{Tx("Hello World")}, nil) + assert.NotEqual(t, "nil-Block", block.String()) + assert.NotEqual(t, "nil-Block", block.StringIndented("")) + assert.NotEqual(t, "nil-Block", block.StringShort()) } func makeBlockIDRandom() BlockID { @@ -86,3 +157,61 @@ func TestNilDataHashDoesntCrash(t *testing.T) { assert.Equal(t, []byte((*Data)(nil).Hash()), nilBytes) assert.Equal(t, []byte(new(Data).Hash()), nilBytes) } + +func TestCommit(t *testing.T) { + lastID := makeBlockIDRandom() + h := int64(3) + voteSet, _, vals := randVoteSet(h-1, 1, VoteTypePrecommit, 10, 1) + commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals) + require.NoError(t, err) + + assert.NotNil(t, commit.FirstPrecommit()) + assert.Equal(t, h-1, commit.Height()) + assert.Equal(t, 1, commit.Round()) + assert.Equal(t, VoteTypePrecommit, commit.Type()) + if commit.Size() <= 0 { + t.Fatalf("commit %v has a zero or negative size: %d", commit, commit.Size()) + } + + require.NotNil(t, commit.BitArray()) + assert.Equal(t, cmn.NewBitArray(10).Size(), commit.BitArray().Size()) + + assert.Equal(t, voteSet.GetByIndex(0), commit.GetByIndex(0)) + assert.True(t, commit.IsCommit()) +} + +func TestCommitValidateBasic(t *testing.T) { + commit := randCommit() + assert.NoError(t, commit.ValidateBasic()) + + // nil precommit is OK + commit = randCommit() + commit.Precommits[0] = nil + assert.NoError(t, commit.ValidateBasic()) + + // tamper with types + commit = randCommit() + commit.Precommits[0].Type = VoteTypePrevote + assert.Error(t, commit.ValidateBasic()) + + // tamper with height + commit = randCommit() + commit.Precommits[0].Height = int64(100) + assert.Error(t, commit.ValidateBasic()) + + // tamper with round + commit = randCommit() + commit.Precommits[0].Round = 100 + assert.Error(t, commit.ValidateBasic()) +} + +func randCommit() *Commit { + lastID := makeBlockIDRandom() + h := int64(3) + voteSet, _, vals := randVoteSet(h-1, 1, VoteTypePrecommit, 10, 1) + commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals) + if err != nil { + panic(err) + } + return commit +} From 1377ef1e1f82fc787786c46b25a970c348947bb7 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Wed, 11 Jul 2018 10:48:54 +0400 Subject: [PATCH 02/17] remove unused TxEventBuffer --- types/event_buffer.go | 50 -------------------------------------- types/event_buffer_test.go | 21 ---------------- 2 files changed, 71 deletions(-) delete mode 100644 types/event_buffer.go delete mode 100644 types/event_buffer_test.go diff --git a/types/event_buffer.go b/types/event_buffer.go deleted file mode 100644 index 18b41014..00000000 --- a/types/event_buffer.go +++ /dev/null @@ -1,50 +0,0 @@ -package types - -// Interface assertions -var _ TxEventPublisher = (*TxEventBuffer)(nil) - -// TxEventBuffer is a buffer of events, which uses a slice to temporarily store -// events. -type TxEventBuffer struct { - next TxEventPublisher - capacity int - events []EventDataTx -} - -// NewTxEventBuffer accepts a TxEventPublisher and returns a new buffer with the given -// capacity. -func NewTxEventBuffer(next TxEventPublisher, capacity int) *TxEventBuffer { - return &TxEventBuffer{ - next: next, - capacity: capacity, - events: make([]EventDataTx, 0, capacity), - } -} - -// Len returns the number of events cached. -func (b TxEventBuffer) Len() int { - return len(b.events) -} - -// PublishEventTx buffers an event to be fired upon finality. -func (b *TxEventBuffer) PublishEventTx(e EventDataTx) error { - b.events = append(b.events, e) - return nil -} - -// Flush publishes events by running next.PublishWithTags on all cached events. -// Blocks. Clears cached events. -func (b *TxEventBuffer) Flush() error { - for _, e := range b.events { - err := b.next.PublishEventTx(e) - if err != nil { - return err - } - } - - // Clear out the elements and set the length to 0 - // but maintain the underlying slice's capacity. - // See Issue https://github.com/tendermint/tendermint/issues/1189 - b.events = b.events[:0] - return nil -} diff --git a/types/event_buffer_test.go b/types/event_buffer_test.go deleted file mode 100644 index 74ae9da2..00000000 --- a/types/event_buffer_test.go +++ /dev/null @@ -1,21 +0,0 @@ -package types - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -type eventBusMock struct{} - -func (eventBusMock) PublishEventTx(e EventDataTx) error { - return nil -} - -func TestEventBuffer(t *testing.T) { - b := NewTxEventBuffer(eventBusMock{}, 1) - b.PublishEventTx(EventDataTx{}) - assert.Equal(t, 1, b.Len()) - b.Flush() - assert.Equal(t, 0, b.Len()) -} From 6fe8ea966aadac7a2e145ad3c2b0ee53b5597f24 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Wed, 11 Jul 2018 11:43:19 +0400 Subject: [PATCH 03/17] remove events we do not emit --- types/event_bus_test.go | 12 ++---------- types/events.go | 10 ---------- 2 files changed, 2 insertions(+), 20 deletions(-) diff --git a/types/event_bus_test.go b/types/event_bus_test.go index 81903004..711e9277 100644 --- a/types/event_bus_test.go +++ b/types/event_bus_test.go @@ -126,11 +126,7 @@ func benchmarkEventBus(numClients int, randQueries bool, randEvents bool, b *tes } } -var events = []string{EventBond, - EventUnbond, - EventRebond, - EventDupeout, - EventFork, +var events = []string{ EventNewBlock, EventNewBlockHeader, EventNewRound, @@ -148,11 +144,7 @@ func randEvent() string { return events[rand.Intn(len(events))] } -var queries = []tmpubsub.Query{EventQueryBond, - EventQueryUnbond, - EventQueryRebond, - EventQueryDupeout, - EventQueryFork, +var queries = []tmpubsub.Query{ EventQueryNewBlock, EventQueryNewBlockHeader, EventQueryNewRound, diff --git a/types/events.go b/types/events.go index 2b87297c..891c6a90 100644 --- a/types/events.go +++ b/types/events.go @@ -10,22 +10,17 @@ import ( // Reserved event types const ( - EventBond = "Bond" EventCompleteProposal = "CompleteProposal" - EventDupeout = "Dupeout" - EventFork = "Fork" EventLock = "Lock" EventNewBlock = "NewBlock" EventNewBlockHeader = "NewBlockHeader" EventNewRound = "NewRound" EventNewRoundStep = "NewRoundStep" EventPolka = "Polka" - EventRebond = "Rebond" EventRelock = "Relock" EventTimeoutPropose = "TimeoutPropose" EventTimeoutWait = "TimeoutWait" EventTx = "Tx" - EventUnbond = "Unbond" EventUnlock = "Unlock" EventVote = "Vote" EventProposalHeartbeat = "ProposalHeartbeat" @@ -113,11 +108,6 @@ const ( ) var ( - EventQueryBond = QueryForEvent(EventBond) - EventQueryUnbond = QueryForEvent(EventUnbond) - EventQueryRebond = QueryForEvent(EventRebond) - EventQueryDupeout = QueryForEvent(EventDupeout) - EventQueryFork = QueryForEvent(EventFork) EventQueryNewBlock = QueryForEvent(EventNewBlock) EventQueryNewBlockHeader = QueryForEvent(EventNewBlockHeader) EventQueryNewRound = QueryForEvent(EventNewRound) From e4db5f8dcd4cc8554bee308d15a7f8b72ebbe5f8 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Wed, 11 Jul 2018 11:53:12 +0400 Subject: [PATCH 04/17] test event bus Refs #693 --- libs/pubsub/query/Makefile | 6 ++-- libs/pubsub/query/query.peg.go | 3 +- types/event_bus_test.go | 60 +++++++++++++++++++++++++++++++++- 3 files changed, 64 insertions(+), 5 deletions(-) diff --git a/libs/pubsub/query/Makefile b/libs/pubsub/query/Makefile index 91030ef0..aef42b2d 100644 --- a/libs/pubsub/query/Makefile +++ b/libs/pubsub/query/Makefile @@ -1,10 +1,10 @@ gen_query_parser: - @go get github.com/pointlander/peg + go get -u -v github.com/pointlander/peg peg -inline -switch query.peg fuzzy_test: - @go get github.com/dvyukov/go-fuzz/go-fuzz - @go get github.com/dvyukov/go-fuzz/go-fuzz-build + go get -u -v github.com/dvyukov/go-fuzz/go-fuzz + go get -u -v github.com/dvyukov/go-fuzz/go-fuzz-build go-fuzz-build github.com/tendermint/tendermint/libs/pubsub/query/fuzz_test go-fuzz -bin=./fuzz_test-fuzz.zip -workdir=./fuzz_test/output diff --git a/libs/pubsub/query/query.peg.go b/libs/pubsub/query/query.peg.go index c86e4a47..c3ac726b 100644 --- a/libs/pubsub/query/query.peg.go +++ b/libs/pubsub/query/query.peg.go @@ -1,6 +1,7 @@ -// nolint package query +//go:generate peg -inline -switch query.peg + import ( "fmt" "math" diff --git a/types/event_bus_test.go b/types/event_bus_test.go index 711e9277..ebd0ac24 100644 --- a/types/event_bus_test.go +++ b/types/event_bus_test.go @@ -11,9 +11,9 @@ import ( "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" + cmn "github.com/tendermint/tendermint/libs/common" tmpubsub "github.com/tendermint/tendermint/libs/pubsub" tmquery "github.com/tendermint/tendermint/libs/pubsub/query" - cmn "github.com/tendermint/tendermint/libs/common" ) func TestEventBusPublishEventTx(t *testing.T) { @@ -59,6 +59,64 @@ func TestEventBusPublishEventTx(t *testing.T) { } } +func TestEventBusPublish(t *testing.T) { + eventBus := NewEventBus() + err := eventBus.Start() + require.NoError(t, err) + defer eventBus.Stop() + + eventsCh := make(chan interface{}) + err = eventBus.Subscribe(context.Background(), "test", tmquery.Empty{}, eventsCh) + require.NoError(t, err) + + const numEventsExpected = 14 + done := make(chan struct{}) + go func() { + numEvents := 0 + for range eventsCh { + numEvents++ + if numEvents >= numEventsExpected { + close(done) + } + } + }() + + err = eventBus.Publish(EventNewBlockHeader, EventDataNewBlockHeader{}) + require.NoError(t, err) + err = eventBus.PublishEventNewBlock(EventDataNewBlock{}) + require.NoError(t, err) + err = eventBus.PublishEventNewBlockHeader(EventDataNewBlockHeader{}) + require.NoError(t, err) + err = eventBus.PublishEventVote(EventDataVote{}) + require.NoError(t, err) + err = eventBus.PublishEventProposalHeartbeat(EventDataProposalHeartbeat{}) + require.NoError(t, err) + err = eventBus.PublishEventNewRoundStep(EventDataRoundState{}) + require.NoError(t, err) + err = eventBus.PublishEventTimeoutPropose(EventDataRoundState{}) + require.NoError(t, err) + err = eventBus.PublishEventTimeoutWait(EventDataRoundState{}) + require.NoError(t, err) + err = eventBus.PublishEventNewRound(EventDataRoundState{}) + require.NoError(t, err) + err = eventBus.PublishEventCompleteProposal(EventDataRoundState{}) + require.NoError(t, err) + err = eventBus.PublishEventPolka(EventDataRoundState{}) + require.NoError(t, err) + err = eventBus.PublishEventUnlock(EventDataRoundState{}) + require.NoError(t, err) + err = eventBus.PublishEventRelock(EventDataRoundState{}) + require.NoError(t, err) + err = eventBus.PublishEventLock(EventDataRoundState{}) + require.NoError(t, err) + + select { + case <-done: + case <-time.After(1 * time.Second): + t.Fatalf("expected to receive %d events after 1 sec.", numEventsExpected) + } +} + func BenchmarkEventBus(b *testing.B) { benchmarks := []struct { name string From 37ce4e549ec482b08e9bba31a2f56cdf8321d6f1 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Wed, 11 Jul 2018 13:28:36 +0400 Subject: [PATCH 05/17] add more tests for evidence Refs #693 --- types/evidence.go | 2 +- types/evidence_test.go | 29 ++++++++++++++++++++++++++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/types/evidence.go b/types/evidence.go index 266375ec..6313f43a 100644 --- a/types/evidence.go +++ b/types/evidence.go @@ -4,7 +4,7 @@ import ( "bytes" "fmt" - "github.com/tendermint/go-amino" + amino "github.com/tendermint/go-amino" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/merkle" diff --git a/types/evidence_test.go b/types/evidence_test.go index 5bbb2a37..54eba01c 100644 --- a/types/evidence_test.go +++ b/types/evidence_test.go @@ -36,7 +36,7 @@ func TestEvidence(t *testing.T) { blockID3 := makeBlockID("blockhash", 10000, "partshash") blockID4 := makeBlockID("blockhash", 10000, "partshash2") - chainID := "mychain" + const chainID = "mychain" vote1 := makeVote(val, chainID, 0, 10, 2, 1, blockID) badVote := makeVote(val, chainID, 0, 10, 2, 1, blockID) @@ -72,3 +72,30 @@ func TestEvidence(t *testing.T) { } } } + +func TestDuplicatedVoteEvidence(t *testing.T) { + ev := randomDuplicatedVoteEvidence() + + assert.True(t, ev.Equal(ev)) + assert.False(t, ev.Equal(&DuplicateVoteEvidence{})) +} + +func TestEvidenceList(t *testing.T) { + ev := randomDuplicatedVoteEvidence() + evl := EvidenceList([]Evidence{ev}) + + assert.NotNil(t, evl.Hash()) + assert.True(t, evl.Has(ev)) + assert.False(t, evl.Has(&DuplicateVoteEvidence{})) +} + +func randomDuplicatedVoteEvidence() *DuplicateVoteEvidence { + val := NewMockPV() + blockID := makeBlockID("blockhash", 1000, "partshash") + blockID2 := makeBlockID("blockhash2", 1000, "partshash") + const chainID = "mychain" + return &DuplicateVoteEvidence{ + VoteA: makeVote(val, chainID, 0, 10, 2, 1, blockID), + VoteB: makeVote(val, chainID, 0, 10, 2, 1, blockID2), + } +} From b271c40783348abeefa123cf112fc1567edc7815 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Wed, 11 Jul 2018 13:36:48 +0400 Subject: [PATCH 06/17] remove deprecated `app_options` field from genesis --- CHANGELOG.md | 5 +++++ consensus/replay.go | 2 +- scripts/wire2amino.go | 9 ++++----- types/genesis.go | 12 +----------- 4 files changed, 11 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6fcab4b8..d34338a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## TBD + +IMPROVEMENTS: +- [genesis] removed deprecated `app_options` field. + ## 0.22.2 *July 10th, 2018* diff --git a/consensus/replay.go b/consensus/replay.go index 3035f75d..dd940998 100644 --- a/consensus/replay.go +++ b/consensus/replay.go @@ -273,7 +273,7 @@ func (h *Handshaker) ReplayBlocks(state sm.State, appHash []byte, appBlockHeight ChainId: h.genDoc.ChainID, ConsensusParams: csParams, Validators: validators, - AppStateBytes: h.genDoc.AppStateJSON, + AppStateBytes: h.genDoc.AppState, } res, err := proxyApp.Consensus().InitChainSync(req) if err != nil { diff --git a/scripts/wire2amino.go b/scripts/wire2amino.go index 867c5735..4933260e 100644 --- a/scripts/wire2amino.go +++ b/scripts/wire2amino.go @@ -29,9 +29,8 @@ type Genesis struct { ConsensusParams *types.ConsensusParams `json:"consensus_params,omitempty"` Validators []GenesisValidator `json:"validators"` AppHash cmn.HexBytes `json:"app_hash"` - AppStateJSON json.RawMessage `json:"app_state,omitempty"` + AppState json.RawMessage `json:"app_state,omitempty"` AppOptions json.RawMessage `json:"app_options,omitempty"` // DEPRECATED - } type NodeKey struct { @@ -112,12 +111,12 @@ func convertGenesis(cdc *amino.Codec, jsonBytes []byte) ([]byte, error) { ChainID: genesis.ChainID, ConsensusParams: genesis.ConsensusParams, // Validators - AppHash: genesis.AppHash, - AppStateJSON: genesis.AppStateJSON, + AppHash: genesis.AppHash, + AppState: genesis.AppState, } if genesis.AppOptions != nil { - genesisNew.AppStateJSON = genesis.AppOptions + genesisNew.AppState = genesis.AppOptions } for _, v := range genesis.Validators { diff --git a/types/genesis.go b/types/genesis.go index 0367c6b2..220ee0e0 100644 --- a/types/genesis.go +++ b/types/genesis.go @@ -26,17 +26,7 @@ type GenesisDoc struct { ConsensusParams *ConsensusParams `json:"consensus_params,omitempty"` Validators []GenesisValidator `json:"validators"` AppHash cmn.HexBytes `json:"app_hash"` - AppStateJSON json.RawMessage `json:"app_state,omitempty"` - AppOptions json.RawMessage `json:"app_options,omitempty"` // DEPRECATED -} - -// AppState returns raw application state. -// TODO: replace with AppState field during next breaking release (0.18) -func (genDoc *GenesisDoc) AppState() json.RawMessage { - if len(genDoc.AppOptions) > 0 { - return genDoc.AppOptions - } - return genDoc.AppStateJSON + AppState json.RawMessage `json:"app_state,omitempty"` } // SaveAs is a utility method for saving GenensisDoc as a JSON file. From 80399e60fb61c91138a5da53eb743c237ec624cc Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Wed, 11 Jul 2018 13:39:05 +0400 Subject: [PATCH 07/17] add tests for events public funcs Refs #693 --- types/events_test.go | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 types/events_test.go diff --git a/types/events_test.go b/types/events_test.go new file mode 100644 index 00000000..a4b71d92 --- /dev/null +++ b/types/events_test.go @@ -0,0 +1,23 @@ +package types + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestQueryTxFor(t *testing.T) { + tx := Tx("foo") + assert.Equal(t, + fmt.Sprintf("tm.event='Tx' AND tx.hash='%X'", tx.Hash()), + EventQueryTxFor(tx).String(), + ) +} + +func TestQueryForEvent(t *testing.T) { + assert.Equal(t, + "tm.event='NewBlock'", + QueryForEvent(EventNewBlock).String(), + ) +} From 3132f7fad497d03a1ad7055a40acfb31533f4b4c Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Wed, 11 Jul 2018 16:03:42 +0400 Subject: [PATCH 08/17] add tests for genesis Refs #693 --- types/genesis_test.go | 45 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/types/genesis_test.go b/types/genesis_test.go index 24398a9a..ee320051 100644 --- a/types/genesis_test.go +++ b/types/genesis_test.go @@ -1,9 +1,13 @@ package types import ( + "io/ioutil" + "os" "testing" + "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto" ) @@ -59,3 +63,44 @@ func TestGenesisGood(t *testing.T) { genDoc, err = GenesisDocFromJSON(genDocBytes) assert.Error(t, err, "expected error for genDoc json with block size of 0") } + +func TestGenesisSaveAs(t *testing.T) { + tmpfile, err := ioutil.TempFile("", "genesis") + require.NoError(t, err) + defer os.Remove(tmpfile.Name()) + + genDoc := randomGenesisDoc() + + // save + genDoc.SaveAs(tmpfile.Name()) + stat, err := tmpfile.Stat() + require.NoError(t, err) + if err != nil && stat.Size() <= 0 { + t.Fatalf("SaveAs failed to write any bytes to %v", tmpfile.Name()) + } + + err = tmpfile.Close() + require.NoError(t, err) + + // load + genDoc2, err := GenesisDocFromFile(tmpfile.Name()) + require.NoError(t, err) + + // fails to unknown reason + // assert.EqualValues(t, genDoc2, genDoc) + assert.Equal(t, genDoc2.Validators, genDoc.Validators) +} + +func TestGenesisValidatorHash(t *testing.T) { + genDoc := randomGenesisDoc() + assert.NotEmpty(t, genDoc.ValidatorHash()) +} + +func randomGenesisDoc() *GenesisDoc { + return &GenesisDoc{ + GenesisTime: time.Now().UTC(), + ChainID: "abc", + Validators: []GenesisValidator{{crypto.GenPrivKeyEd25519().PubKey(), 10, "myval"}}, + ConsensusParams: DefaultConsensusParams(), + } +} From 5a4459935b7cf74800505a52d853029e143219d8 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Wed, 11 Jul 2018 16:22:06 +0400 Subject: [PATCH 09/17] add a test for ConsensusParams#Update Refs #693 --- types/params_test.go | 57 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/types/params_test.go b/types/params_test.go index f645585e..e8e13dba 100644 --- a/types/params_test.go +++ b/types/params_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + abci "github.com/tendermint/tendermint/abci/types" ) func newConsensusParams(blockSize, partSize int) ConsensusParams { @@ -86,3 +87,59 @@ func TestConsensusParamsHash(t *testing.T) { assert.NotEqual(t, hashes[i], hashes[i+1]) } } + +func TestConsensusParamsUpdate(t *testing.T) { + testCases := []struct { + params ConsensusParams + updates *abci.ConsensusParams + updatedParams ConsensusParams + }{ + // empty updates + { + makeParams(1, 2, 3, 4, 5, 6), + &abci.ConsensusParams{}, + makeParams(1, 2, 3, 4, 5, 6), + }, + // negative BlockPartSizeBytes + { + makeParams(1, 2, 3, 4, 5, 6), + &abci.ConsensusParams{ + BlockSize: &abci.BlockSize{ + MaxBytes: -100, + MaxTxs: -200, + MaxGas: -300, + }, + TxSize: &abci.TxSize{ + MaxBytes: -400, + MaxGas: -500, + }, + BlockGossip: &abci.BlockGossip{ + BlockPartSizeBytes: -600, + }, + }, + makeParams(1, 2, 3, 4, 5, 6), + }, + // fine updates + { + makeParams(1, 2, 3, 4, 5, 6), + &abci.ConsensusParams{ + BlockSize: &abci.BlockSize{ + MaxBytes: 100, + MaxTxs: 200, + MaxGas: 300, + }, + TxSize: &abci.TxSize{ + MaxBytes: 400, + MaxGas: 500, + }, + BlockGossip: &abci.BlockGossip{ + BlockPartSizeBytes: 600, + }, + }, + makeParams(100, 200, 300, 400, 500, 600), + }, + } + for _, tc := range testCases { + assert.Equal(t, tc.updatedParams, tc.params.Update(tc.updates)) + } +} From d51b196992d45d600027b86068eb4a119e39db23 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Wed, 11 Jul 2018 16:57:35 +0400 Subject: [PATCH 10/17] improve part set tests Refs #693 --- types/part_set_test.go | 53 +++++++++++++++++++----------------------- 1 file changed, 24 insertions(+), 29 deletions(-) diff --git a/types/part_set_test.go b/types/part_set_test.go index 01437f05..3576e747 100644 --- a/types/part_set_test.go +++ b/types/part_set_test.go @@ -1,10 +1,12 @@ package types import ( - "bytes" "io/ioutil" "testing" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + cmn "github.com/tendermint/tendermint/libs/common" ) @@ -13,24 +15,21 @@ const ( ) func TestBasicPartSet(t *testing.T) { - // Construct random data of size partSize * 100 data := cmn.RandBytes(testPartSize * 100) - partSet := NewPartSetFromData(data, testPartSize) - if len(partSet.Hash()) == 0 { - t.Error("Expected to get hash") - } - if partSet.Total() != 100 { - t.Errorf("Expected to get 100 parts, but got %v", partSet.Total()) - } - if !partSet.IsComplete() { - t.Errorf("PartSet should be complete") - } + + assert.NotEmpty(t, partSet.Hash()) + assert.Equal(t, 100, partSet.Total()) + assert.Equal(t, 100, partSet.BitArray().Size()) + assert.True(t, partSet.HashesTo(partSet.Hash())) + assert.True(t, partSet.IsComplete()) + assert.Equal(t, 100, partSet.Count()) // Test adding parts to a new partSet. partSet2 := NewPartSetFromHeader(partSet.Header()) + assert.True(t, partSet2.HasHeader(partSet.Header())) for i := 0; i < partSet.Total(); i++ { part := partSet.GetPart(i) //t.Logf("\n%v", part) @@ -39,31 +38,28 @@ func TestBasicPartSet(t *testing.T) { t.Errorf("Failed to add part %v, error: %v", i, err) } } + // adding part with invalid index + added, err := partSet2.AddPart(&Part{Index: 10000}) + assert.False(t, added) + assert.Error(t, err) + // adding existing part + added, err = partSet2.AddPart(partSet2.GetPart(0)) + assert.False(t, added) + assert.Nil(t, err) - if !bytes.Equal(partSet.Hash(), partSet2.Hash()) { - t.Error("Expected to get same hash") - } - if partSet2.Total() != 100 { - t.Errorf("Expected to get 100 parts, but got %v", partSet2.Total()) - } - if !partSet2.IsComplete() { - t.Errorf("Reconstructed PartSet should be complete") - } + assert.Equal(t, partSet.Hash(), partSet2.Hash()) + assert.Equal(t, 100, partSet2.Total()) + assert.True(t, partSet2.IsComplete()) // Reconstruct data, assert that they are equal. data2Reader := partSet2.GetReader() data2, err := ioutil.ReadAll(data2Reader) - if err != nil { - t.Errorf("Error reading data2Reader: %v", err) - } - if !bytes.Equal(data, data2) { - t.Errorf("Got wrong data.") - } + require.NoError(t, err) + assert.Equal(t, data, data2) } func TestWrongProof(t *testing.T) { - // Construct random data of size partSize * 100 data := cmn.RandBytes(testPartSize * 100) partSet := NewPartSetFromData(data, testPartSize) @@ -86,5 +82,4 @@ func TestWrongProof(t *testing.T) { if added || err == nil { t.Errorf("Expected to fail adding a part with bad bytes.") } - } From 715ec19c96c1cfc1864691644dbdb8e520f56191 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Thu, 12 Jul 2018 12:31:12 +0400 Subject: [PATCH 11/17] add tests for protobuf Refs #693 --- types/protobuf.go | 2 +- types/protobuf_test.go | 51 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/types/protobuf.go b/types/protobuf.go index ad7362e0..4fe44825 100644 --- a/types/protobuf.go +++ b/types/protobuf.go @@ -78,7 +78,7 @@ func (tm2pb) PubKey(pubKey crypto.PubKey) abci.PubKey { // XXX: panics on nil or unknown pubkey type func (tm2pb) Validators(vals *ValidatorSet) []abci.Validator { - validators := make([]abci.Validator, len(vals.Validators)) + validators := make([]abci.Validator, vals.Size()) for i, val := range vals.Validators { validators[i] = TM2PB.Validator(val) } diff --git a/types/protobuf_test.go b/types/protobuf_test.go index cd986fd8..ce61fa54 100644 --- a/types/protobuf_test.go +++ b/types/protobuf_test.go @@ -2,6 +2,7 @@ package types import ( "testing" + "time" "github.com/stretchr/testify/assert" abci "github.com/tendermint/tendermint/abci/types" @@ -43,6 +44,9 @@ func TestABCIValidators(t *testing.T) { assert.Nil(t, err) assert.Equal(t, tmValExpected, tmVals[0]) + abciVals := TM2PB.Validators(NewValidatorSet(tmVals)) + assert.Equal(t, []abci.Validator{abciVal}, abciVals) + // val with address tmVal.Address = pkEd.Address() @@ -67,3 +71,50 @@ func TestABCIConsensusParams(t *testing.T) { assert.Equal(t, *cp, cp2) } + +func TestABCIHeader(t *testing.T) { + header := &Header{ + Height: int64(3), + Time: time.Now(), + NumTxs: int64(10), + } + abciHeader := TM2PB.Header(header) + + assert.Equal(t, int64(3), abciHeader.Height) +} + +func TestABCIEvidence(t *testing.T) { + val := NewMockPV() + blockID := makeBlockID("blockhash", 1000, "partshash") + blockID2 := makeBlockID("blockhash2", 1000, "partshash") + const chainID = "mychain" + ev := &DuplicateVoteEvidence{ + PubKey: val.GetPubKey(), + VoteA: makeVote(val, chainID, 0, 10, 2, 1, blockID), + VoteB: makeVote(val, chainID, 0, 10, 2, 1, blockID2), + } + abciEv := TM2PB.Evidence( + ev, + NewValidatorSet([]*Validator{NewValidator(val.GetPubKey(), 10)}), + time.Now(), + ) + + assert.Equal(t, "duplicate/vote", abciEv.Type) +} + +type pubKeyEddie struct{} + +func (pubKeyEddie) Address() Address { return []byte{} } +func (pubKeyEddie) Bytes() []byte { return []byte{} } +func (pubKeyEddie) VerifyBytes(msg []byte, sig crypto.Signature) bool { return false } +func (pubKeyEddie) Equals(crypto.PubKey) bool { return false } + +func TestABCIValidatorFromPubKeyAndPower(t *testing.T) { + pubkey := crypto.GenPrivKeyEd25519().PubKey() + + abciVal := TM2PB.ValidatorFromPubKeyAndPower(pubkey, 10) + assert.Equal(t, int64(10), abciVal.Power) + + assert.Panics(t, func() { TM2PB.ValidatorFromPubKeyAndPower(nil, 10) }) + assert.Panics(t, func() { TM2PB.ValidatorFromPubKeyAndPower(pubKeyEddie{}, 10) }) +} From 20bb522592e92106df965727c219b000819a47fa Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Thu, 12 Jul 2018 12:56:26 +0400 Subject: [PATCH 12/17] add tests for ABCIResults#Bytes and tx#IndexByHash --- types/results.go | 9 +++++---- types/results_test.go | 12 +++++++++++ types/tx_test.go | 47 ++++++++++++++++++++++++++----------------- 3 files changed, 45 insertions(+), 23 deletions(-) diff --git a/types/results.go b/types/results.go index 7f8e6093..17d5891c 100644 --- a/types/results.go +++ b/types/results.go @@ -24,15 +24,16 @@ func (a ABCIResult) Hash() []byte { // ABCIResults wraps the deliver tx results to return a proof type ABCIResults []ABCIResult -// NewResults creates ABCIResults from ResponseDeliverTx -func NewResults(del []*abci.ResponseDeliverTx) ABCIResults { - res := make(ABCIResults, len(del)) - for i, d := range del { +// NewResults creates ABCIResults from the list of ResponseDeliverTx. +func NewResults(responses []*abci.ResponseDeliverTx) ABCIResults { + res := make(ABCIResults, len(responses)) + for i, d := range responses { res[i] = NewResultFromResponse(d) } return res } +// NewResultFromResponse creates ABCIResult from ResponseDeliverTx. func NewResultFromResponse(response *abci.ResponseDeliverTx) ABCIResult { return ABCIResult{ Code: response.Code, diff --git a/types/results_test.go b/types/results_test.go index 009e2693..8cbe319f 100644 --- a/types/results_test.go +++ b/types/results_test.go @@ -5,6 +5,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + abci "github.com/tendermint/tendermint/abci/types" ) func TestABCIResults(t *testing.T) { @@ -41,3 +42,14 @@ func TestABCIResults(t *testing.T) { assert.True(t, valid, "%d", i) } } + +func TestABCIBytes(t *testing.T) { + results := NewResults([]*abci.ResponseDeliverTx{ + {Code: 0, Data: []byte{}}, + {Code: 0, Data: []byte("one")}, + {Code: 14, Data: nil}, + {Code: 14, Data: []byte("foo")}, + {Code: 14, Data: []byte("bar")}, + }) + assert.NotNil(t, results.Bytes()) +} diff --git a/types/tx_test.go b/types/tx_test.go index 67df5c5f..df7a7449 100644 --- a/types/tx_test.go +++ b/types/tx_test.go @@ -24,21 +24,32 @@ func randInt(low, high int) int { } func TestTxIndex(t *testing.T) { - assert := assert.New(t) for i := 0; i < 20; i++ { txs := makeTxs(15, 60) for j := 0; j < len(txs); j++ { tx := txs[j] idx := txs.Index(tx) - assert.Equal(j, idx) + assert.Equal(t, j, idx) } - assert.Equal(-1, txs.Index(nil)) - assert.Equal(-1, txs.Index(Tx("foodnwkf"))) + assert.Equal(t, -1, txs.Index(nil)) + assert.Equal(t, -1, txs.Index(Tx("foodnwkf"))) + } +} + +func TestTxIndexByHash(t *testing.T) { + for i := 0; i < 20; i++ { + txs := makeTxs(15, 60) + for j := 0; j < len(txs); j++ { + tx := txs[j] + idx := txs.IndexByHash(tx.Hash()) + assert.Equal(t, j, idx) + } + assert.Equal(t, -1, txs.IndexByHash(nil)) + assert.Equal(t, -1, txs.IndexByHash(Tx("foodnwkf").Hash())) } } func TestValidTxProof(t *testing.T) { - assert := assert.New(t) cases := []struct { txs Txs }{ @@ -58,21 +69,21 @@ func TestValidTxProof(t *testing.T) { leaf := txs[i] leafHash := leaf.Hash() proof := txs.Proof(i) - assert.Equal(i, proof.Index, "%d: %d", h, i) - assert.Equal(len(txs), proof.Total, "%d: %d", h, i) - assert.EqualValues(root, proof.RootHash, "%d: %d", h, i) - assert.EqualValues(leaf, proof.Data, "%d: %d", h, i) - assert.EqualValues(leafHash, proof.LeafHash(), "%d: %d", h, i) - assert.Nil(proof.Validate(root), "%d: %d", h, i) - assert.NotNil(proof.Validate([]byte("foobar")), "%d: %d", h, i) + assert.Equal(t, i, proof.Index, "%d: %d", h, i) + assert.Equal(t, len(txs), proof.Total, "%d: %d", h, i) + assert.EqualValues(t, root, proof.RootHash, "%d: %d", h, i) + assert.EqualValues(t, leaf, proof.Data, "%d: %d", h, i) + assert.EqualValues(t, leafHash, proof.LeafHash(), "%d: %d", h, i) + assert.Nil(t, proof.Validate(root), "%d: %d", h, i) + assert.NotNil(t, proof.Validate([]byte("foobar")), "%d: %d", h, i) // read-write must also work var p2 TxProof bin, err := cdc.MarshalBinary(proof) - assert.Nil(err) + assert.Nil(t, err) err = cdc.UnmarshalBinary(bin, &p2) - if assert.Nil(err, "%d: %d: %+v", h, i, err) { - assert.Nil(p2.Validate(root), "%d: %d", h, i) + if assert.Nil(t, err, "%d: %d: %+v", h, i, err) { + assert.Nil(t, p2.Validate(root), "%d: %d", h, i) } } } @@ -86,8 +97,6 @@ func TestTxProofUnchangable(t *testing.T) { } func testTxProofUnchangable(t *testing.T) { - assert := assert.New(t) - // make some proof txs := makeTxs(randInt(2, 100), randInt(16, 128)) root := txs.Hash() @@ -95,9 +104,9 @@ func testTxProofUnchangable(t *testing.T) { proof := txs.Proof(i) // make sure it is valid to start with - assert.Nil(proof.Validate(root)) + assert.Nil(t, proof.Validate(root)) bin, err := cdc.MarshalBinary(proof) - assert.Nil(err) + assert.Nil(t, err) // try mutating the data and make sure nothing breaks for j := 0; j < 500; j++ { From ff8ddee7084726a28c769013e90a47adf1300bde Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Thu, 12 Jul 2018 13:22:08 +0400 Subject: [PATCH 13/17] rename privval#GetAddress and GetPubKey to Address and PubKey --- cmd/tendermint/commands/init.go | 2 +- cmd/tendermint/commands/show_validator.go | 3 +- cmd/tendermint/commands/testnet.go | 2 +- consensus/common_test.go | 8 ++-- consensus/reactor_test.go | 14 +++--- consensus/replay_test.go | 6 +-- consensus/state.go | 14 +++--- consensus/state_test.go | 18 ++++---- consensus/types/height_vote_set_test.go | 2 +- node/node.go | 10 ++--- privval/priv_validator.go | 26 +++++------ privval/priv_validator_test.go | 26 +++++------ privval/socket.go | 10 ++--- privval/socket_test.go | 8 ++-- scripts/wire2amino.go | 6 +-- types/evidence_test.go | 4 +- types/priv_validator.go | 12 ++--- types/proposal_test.go | 4 +- types/protobuf_test.go | 4 +- types/test_util.go | 2 +- types/validator.go | 3 +- types/vote_set_test.go | 54 +++++++++++------------ types/vote_test.go | 2 +- 23 files changed, 121 insertions(+), 119 deletions(-) diff --git a/cmd/tendermint/commands/init.go b/cmd/tendermint/commands/init.go index a44c73eb..5d7d849e 100644 --- a/cmd/tendermint/commands/init.go +++ b/cmd/tendermint/commands/init.go @@ -57,7 +57,7 @@ func initFilesWithConfig(config *cfg.Config) error { ConsensusParams: types.DefaultConsensusParams(), } genDoc.Validators = []types.GenesisValidator{{ - PubKey: pv.GetPubKey(), + PubKey: pv.PubKey(), Power: 10, }} diff --git a/cmd/tendermint/commands/show_validator.go b/cmd/tendermint/commands/show_validator.go index 54765164..4bf1f611 100644 --- a/cmd/tendermint/commands/show_validator.go +++ b/cmd/tendermint/commands/show_validator.go @@ -17,6 +17,7 @@ var ShowValidatorCmd = &cobra.Command{ func showValidator(cmd *cobra.Command, args []string) { privValidator := privval.LoadOrGenFilePV(config.PrivValidatorFile()) - pubKeyJSONBytes, _ := cdc.MarshalJSON(privValidator.GetPubKey()) + pubKeyJSONBytes, _ := cdc.MarshalJSON(privValidator.PubKey()) fmt.Println(string(pubKeyJSONBytes)) } + diff --git a/cmd/tendermint/commands/testnet.go b/cmd/tendermint/commands/testnet.go index f7639fb2..4981c2da 100644 --- a/cmd/tendermint/commands/testnet.go +++ b/cmd/tendermint/commands/testnet.go @@ -91,7 +91,7 @@ func testnetFiles(cmd *cobra.Command, args []string) error { pvFile := filepath.Join(nodeDir, config.BaseConfig.PrivValidator) pv := privval.LoadFilePV(pvFile) genVals[i] = types.GenesisValidator{ - PubKey: pv.GetPubKey(), + PubKey: pv.PubKey(), Power: 1, Name: nodeDirName, } diff --git a/consensus/common_test.go b/consensus/common_test.go index 2df226ba..ef4f0bcd 100644 --- a/consensus/common_test.go +++ b/consensus/common_test.go @@ -72,7 +72,7 @@ func NewValidatorStub(privValidator types.PrivValidator, valIndex int) *validato func (vs *validatorStub) signVote(voteType byte, hash []byte, header types.PartSetHeader) (*types.Vote, error) { vote := &types.Vote{ ValidatorIndex: vs.Index, - ValidatorAddress: vs.PrivValidator.GetAddress(), + ValidatorAddress: vs.PrivValidator.Address(), Height: vs.Height, Round: vs.Round, Timestamp: time.Now().UTC(), @@ -150,7 +150,7 @@ func signAddVotes(to *ConsensusState, voteType byte, hash []byte, header types.P func validatePrevote(t *testing.T, cs *ConsensusState, round int, privVal *validatorStub, blockHash []byte) { prevotes := cs.Votes.Prevotes(round) var vote *types.Vote - if vote = prevotes.GetByAddress(privVal.GetAddress()); vote == nil { + if vote = prevotes.GetByAddress(privVal.Address()); vote == nil { panic("Failed to find prevote from validator") } if blockHash == nil { @@ -167,7 +167,7 @@ func validatePrevote(t *testing.T, cs *ConsensusState, round int, privVal *valid func validateLastPrecommit(t *testing.T, cs *ConsensusState, privVal *validatorStub, blockHash []byte) { votes := cs.LastCommit var vote *types.Vote - if vote = votes.GetByAddress(privVal.GetAddress()); vote == nil { + if vote = votes.GetByAddress(privVal.Address()); vote == nil { panic("Failed to find precommit from validator") } if !bytes.Equal(vote.BlockID.Hash, blockHash) { @@ -178,7 +178,7 @@ func validateLastPrecommit(t *testing.T, cs *ConsensusState, privVal *validatorS func validatePrecommit(t *testing.T, cs *ConsensusState, thisRound, lockRound int, privVal *validatorStub, votedBlockHash, lockedBlockHash []byte) { precommits := cs.Votes.Precommits(thisRound) var vote *types.Vote - if vote = precommits.GetByAddress(privVal.GetAddress()); vote == nil { + if vote = precommits.GetByAddress(privVal.Address()); vote == nil { panic("Failed to find precommit from validator") } diff --git a/consensus/reactor_test.go b/consensus/reactor_test.go index 9e2aa0a0..b8ee9dbe 100644 --- a/consensus/reactor_test.go +++ b/consensus/reactor_test.go @@ -242,7 +242,7 @@ func TestReactorVotingPowerChange(t *testing.T) { // map of active validators activeVals := make(map[string]struct{}) for i := 0; i < nVals; i++ { - activeVals[string(css[i].privValidator.GetAddress())] = struct{}{} + activeVals[string(css[i].privValidator.Address())] = struct{}{} } // wait till everyone makes block 1 @@ -253,7 +253,7 @@ func TestReactorVotingPowerChange(t *testing.T) { //--------------------------------------------------------------------------- logger.Debug("---------------------------- Testing changing the voting power of one validator a few times") - val1PubKey := css[0].privValidator.GetPubKey() + val1PubKey := css[0].privValidator.PubKey() val1PubKeyABCI := types.TM2PB.PubKey(val1PubKey) updateValidatorTx := kvstore.MakeValSetChangeTx(val1PubKeyABCI, 25) previousTotalVotingPower := css[0].GetRoundState().LastValidators.TotalVotingPower() @@ -305,7 +305,7 @@ func TestReactorValidatorSetChanges(t *testing.T) { // map of active validators activeVals := make(map[string]struct{}) for i := 0; i < nVals; i++ { - activeVals[string(css[i].privValidator.GetAddress())] = struct{}{} + activeVals[string(css[i].privValidator.Address())] = struct{}{} } // wait till everyone makes block 1 @@ -316,7 +316,7 @@ func TestReactorValidatorSetChanges(t *testing.T) { //--------------------------------------------------------------------------- logger.Info("---------------------------- Testing adding one validator") - newValidatorPubKey1 := css[nVals].privValidator.GetPubKey() + newValidatorPubKey1 := css[nVals].privValidator.PubKey() valPubKey1ABCI := types.TM2PB.PubKey(newValidatorPubKey1) newValidatorTx1 := kvstore.MakeValSetChangeTx(valPubKey1ABCI, testMinPower) @@ -343,7 +343,7 @@ func TestReactorValidatorSetChanges(t *testing.T) { //--------------------------------------------------------------------------- logger.Info("---------------------------- Testing changing the voting power of one validator") - updateValidatorPubKey1 := css[nVals].privValidator.GetPubKey() + updateValidatorPubKey1 := css[nVals].privValidator.PubKey() updatePubKey1ABCI := types.TM2PB.PubKey(updateValidatorPubKey1) updateValidatorTx1 := kvstore.MakeValSetChangeTx(updatePubKey1ABCI, 25) previousTotalVotingPower := css[nVals].GetRoundState().LastValidators.TotalVotingPower() @@ -360,11 +360,11 @@ func TestReactorValidatorSetChanges(t *testing.T) { //--------------------------------------------------------------------------- logger.Info("---------------------------- Testing adding two validators at once") - newValidatorPubKey2 := css[nVals+1].privValidator.GetPubKey() + newValidatorPubKey2 := css[nVals+1].privValidator.PubKey() newVal2ABCI := types.TM2PB.PubKey(newValidatorPubKey2) newValidatorTx2 := kvstore.MakeValSetChangeTx(newVal2ABCI, testMinPower) - newValidatorPubKey3 := css[nVals+2].privValidator.GetPubKey() + newValidatorPubKey3 := css[nVals+2].privValidator.PubKey() newVal3ABCI := types.TM2PB.PubKey(newValidatorPubKey3) newValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, testMinPower) diff --git a/consensus/replay_test.go b/consensus/replay_test.go index da526d24..afa868e2 100644 --- a/consensus/replay_test.go +++ b/consensus/replay_test.go @@ -347,7 +347,7 @@ func testHandshakeReplay(t *testing.T, nBlocks int, mode uint) { t.Fatalf(err.Error()) } - stateDB, state, store := stateAndStore(config, privVal.GetPubKey()) + stateDB, state, store := stateAndStore(config, privVal.PubKey()) store.chain = chain store.commits = commits @@ -362,7 +362,7 @@ func testHandshakeReplay(t *testing.T, nBlocks int, mode uint) { // run nBlocks against a new client to build up the app state. // use a throwaway tendermint state proxyApp := proxy.NewAppConns(clientCreator2, nil) - stateDB, state, _ := stateAndStore(config, privVal.GetPubKey()) + stateDB, state, _ := stateAndStore(config, privVal.PubKey()) buildAppStateFromChain(proxyApp, stateDB, state, chain, nBlocks, mode) } @@ -646,7 +646,7 @@ func TestInitChainUpdateValidators(t *testing.T) { config := ResetConfig("proxy_test_") privVal := privval.LoadFilePV(config.PrivValidatorFile()) - stateDB, state, store := stateAndStore(config, privVal.GetPubKey()) + stateDB, state, store := stateAndStore(config, privVal.PubKey()) oldValAddr := state.Validators.Validators[0].Address diff --git a/consensus/state.go b/consensus/state.go index e4b360e0..ac188a20 100644 --- a/consensus/state.go +++ b/consensus/state.go @@ -768,7 +768,7 @@ func (cs *ConsensusState) needProofBlock(height int64) bool { func (cs *ConsensusState) proposalHeartbeat(height int64, round int) { counter := 0 - addr := cs.privValidator.GetAddress() + addr := cs.privValidator.Address() valIndex, _ := cs.Validators.GetByAddress(addr) chainID := cs.state.ChainID for { @@ -827,8 +827,8 @@ func (cs *ConsensusState) enterPropose(height int64, round int) { } // if not a validator, we're done - if !cs.Validators.HasAddress(cs.privValidator.GetAddress()) { - logger.Debug("This node is not a validator", "addr", cs.privValidator.GetAddress(), "vals", cs.Validators) + if !cs.Validators.HasAddress(cs.privValidator.Address()) { + logger.Debug("This node is not a validator", "addr", cs.privValidator.Address(), "vals", cs.Validators) return } logger.Debug("This node is a validator") @@ -842,7 +842,7 @@ func (cs *ConsensusState) enterPropose(height int64, round int) { } func (cs *ConsensusState) isProposer() bool { - return bytes.Equal(cs.Validators.GetProposer().Address, cs.privValidator.GetAddress()) + return bytes.Equal(cs.Validators.GetProposer().Address, cs.privValidator.Address()) } func (cs *ConsensusState) defaultDecideProposal(height int64, round int) { @@ -1463,7 +1463,7 @@ func (cs *ConsensusState) tryAddVote(vote *types.Vote, peerID p2p.ID) error { if err == ErrVoteHeightMismatch { return err } else if voteErr, ok := err.(*types.ErrVoteConflictingVotes); ok { - if bytes.Equal(vote.ValidatorAddress, cs.privValidator.GetAddress()) { + if bytes.Equal(vote.ValidatorAddress, cs.privValidator.Address()) { cs.Logger.Error("Found conflicting vote from ourselves. Did you unsafe_reset a validator?", "height", vote.Height, "round", vote.Round, "type", vote.Type) return err } @@ -1620,7 +1620,7 @@ func (cs *ConsensusState) addVote(vote *types.Vote, peerID p2p.ID) (added bool, } func (cs *ConsensusState) signVote(type_ byte, hash []byte, header types.PartSetHeader) (*types.Vote, error) { - addr := cs.privValidator.GetAddress() + addr := cs.privValidator.Address() valIndex, _ := cs.Validators.GetByAddress(addr) vote := &types.Vote{ ValidatorAddress: addr, @@ -1638,7 +1638,7 @@ func (cs *ConsensusState) signVote(type_ byte, hash []byte, header types.PartSet // sign the vote and publish on internalMsgQueue func (cs *ConsensusState) signAddVote(type_ byte, hash []byte, header types.PartSetHeader) *types.Vote { // if we don't have a key or we're not in the validator set, do nothing - if cs.privValidator == nil || !cs.Validators.HasAddress(cs.privValidator.GetAddress()) { + if cs.privValidator == nil || !cs.Validators.HasAddress(cs.privValidator.Address()) { return nil } vote, err := cs.signVote(type_, hash, header) diff --git a/consensus/state_test.go b/consensus/state_test.go index 6a14e17b..96d97c4e 100644 --- a/consensus/state_test.go +++ b/consensus/state_test.go @@ -69,7 +69,7 @@ func TestStateProposerSelection0(t *testing.T) { // lets commit a block and ensure proposer for the next height is correct prop := cs1.GetRoundState().Validators.GetProposer() - if !bytes.Equal(prop.Address, cs1.privValidator.GetAddress()) { + if !bytes.Equal(prop.Address, cs1.privValidator.Address()) { t.Fatalf("expected proposer to be validator %d. Got %X", 0, prop.Address) } @@ -83,7 +83,7 @@ func TestStateProposerSelection0(t *testing.T) { <-newRoundCh prop = cs1.GetRoundState().Validators.GetProposer() - if !bytes.Equal(prop.Address, vss[1].GetAddress()) { + if !bytes.Equal(prop.Address, vss[1].Address()) { panic(cmn.Fmt("expected proposer to be validator %d. Got %X", 1, prop.Address)) } } @@ -104,7 +104,7 @@ func TestStateProposerSelection2(t *testing.T) { // everyone just votes nil. we get a new proposer each round for i := 0; i < len(vss); i++ { prop := cs1.GetRoundState().Validators.GetProposer() - if !bytes.Equal(prop.Address, vss[(i+2)%len(vss)].GetAddress()) { + if !bytes.Equal(prop.Address, vss[(i+2)%len(vss)].Address()) { panic(cmn.Fmt("expected proposer to be validator %d. Got %X", (i+2)%len(vss), prop.Address)) } @@ -629,7 +629,7 @@ func TestStateLockPOLUnlock(t *testing.T) { timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) unlockCh := subscribe(cs1.eventBus, types.EventQueryUnlock) - voteCh := subscribeToVoter(cs1, cs1.privValidator.GetAddress()) + voteCh := subscribeToVoter(cs1, cs1.privValidator.Address()) // everything done from perspective of cs1 @@ -725,7 +725,7 @@ func TestStateLockPOLSafety1(t *testing.T) { timeoutProposeCh := subscribe(cs1.eventBus, types.EventQueryTimeoutPropose) timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) - voteCh := subscribeToVoter(cs1, cs1.privValidator.GetAddress()) + voteCh := subscribeToVoter(cs1, cs1.privValidator.Address()) // start round and wait for propose and prevote startTestRound(cs1, cs1.Height, 0) @@ -849,7 +849,7 @@ func TestStateLockPOLSafety2(t *testing.T) { timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) unlockCh := subscribe(cs1.eventBus, types.EventQueryUnlock) - voteCh := subscribeToVoter(cs1, cs1.privValidator.GetAddress()) + voteCh := subscribeToVoter(cs1, cs1.privValidator.Address()) // the block for R0: gets polkad but we miss it // (even though we signed it, shhh) @@ -945,7 +945,7 @@ func TestStateSlashingPrevotes(t *testing.T) { proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) - voteCh := subscribeToVoter(cs1, cs1.privValidator.GetAddress()) + voteCh := subscribeToVoter(cs1, cs1.privValidator.Address()) // start round and wait for propose and prevote startTestRound(cs1, cs1.Height, 0) @@ -980,7 +980,7 @@ func TestStateSlashingPrecommits(t *testing.T) { proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) - voteCh := subscribeToVoter(cs1, cs1.privValidator.GetAddress()) + voteCh := subscribeToVoter(cs1, cs1.privValidator.Address()) // start round and wait for propose and prevote startTestRound(cs1, cs1.Height, 0) @@ -1027,7 +1027,7 @@ func TestStateHalt1(t *testing.T) { timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) newBlockCh := subscribe(cs1.eventBus, types.EventQueryNewBlock) - voteCh := subscribeToVoter(cs1, cs1.privValidator.GetAddress()) + voteCh := subscribeToVoter(cs1, cs1.privValidator.Address()) // start round and wait for propose and prevote startTestRound(cs1, cs1.Height, 0) diff --git a/consensus/types/height_vote_set_test.go b/consensus/types/height_vote_set_test.go index 0de65600..03e40d0b 100644 --- a/consensus/types/height_vote_set_test.go +++ b/consensus/types/height_vote_set_test.go @@ -51,7 +51,7 @@ func TestPeerCatchupRounds(t *testing.T) { func makeVoteHR(t *testing.T, height int64, round int, privVals []types.PrivValidator, valIndex int) *types.Vote { privVal := privVals[valIndex] vote := &types.Vote{ - ValidatorAddress: privVal.GetAddress(), + ValidatorAddress: privVal.Address(), ValidatorIndex: valIndex, Height: height, Round: round, diff --git a/node/node.go b/node/node.go index 9f6428ec..d2ef1db2 100644 --- a/node/node.go +++ b/node/node.go @@ -217,16 +217,16 @@ func NewNode(config *cfg.Config, fastSync := config.FastSync if state.Validators.Size() == 1 { addr, _ := state.Validators.GetByIndex(0) - if bytes.Equal(privValidator.GetAddress(), addr) { + if bytes.Equal(privValidator.Address(), addr) { fastSync = false } } // Log whether this node is a validator or an observer - if state.Validators.HasAddress(privValidator.GetAddress()) { - consensusLogger.Info("This node is a validator", "addr", privValidator.GetAddress(), "pubKey", privValidator.GetPubKey()) + if state.Validators.HasAddress(privValidator.Address()) { + consensusLogger.Info("This node is a validator", "addr", privValidator.Address(), "pubKey", privValidator.PubKey()) } else { - consensusLogger.Info("This node is not a validator", "addr", privValidator.GetAddress(), "pubKey", privValidator.GetPubKey()) + consensusLogger.Info("This node is not a validator", "addr", privValidator.Address(), "pubKey", privValidator.PubKey()) } // metrics @@ -537,7 +537,7 @@ func (n *Node) ConfigureRPC() { rpccore.SetMempool(n.mempoolReactor.Mempool) rpccore.SetEvidencePool(n.evidencePool) rpccore.SetSwitch(n.sw) - rpccore.SetPubKey(n.privValidator.GetPubKey()) + rpccore.SetPubKey(n.privValidator.PubKey()) rpccore.SetGenesisDoc(n.genesisDoc) rpccore.SetAddrBook(n.addrBook) rpccore.SetProxyAppQuery(n.proxyApp.Query()) diff --git a/privval/priv_validator.go b/privval/priv_validator.go index 1e85bf7b..f4b9de64 100644 --- a/privval/priv_validator.go +++ b/privval/priv_validator.go @@ -37,8 +37,8 @@ func voteToStep(vote *types.Vote) int8 { // to prevent double signing. // NOTE: the directory containing the pv.filePath must already exist. type FilePV struct { - Address types.Address `json:"address"` - PubKey crypto.PubKey `json:"pub_key"` + Address_ types.Address `json:"address"` + PubKey_ crypto.PubKey `json:"pub_key"` LastHeight int64 `json:"last_height"` LastRound int `json:"last_round"` LastStep int8 `json:"last_step"` @@ -52,16 +52,16 @@ type FilePV struct { mtx sync.Mutex } -// GetAddress returns the address of the validator. +// Address returns the address of the validator. // Implements PrivValidator. -func (pv *FilePV) GetAddress() types.Address { - return pv.Address +func (pv *FilePV) Address() types.Address { + return pv.Address_ } -// GetPubKey returns the public key of the validator. +// PubKey returns the public key of the validator. // Implements PrivValidator. -func (pv *FilePV) GetPubKey() crypto.PubKey { - return pv.PubKey +func (pv *FilePV) PubKey() crypto.PubKey { + return pv.PubKey_ } // GenFilePV generates a new validator with randomly generated private key @@ -69,8 +69,8 @@ func (pv *FilePV) GetPubKey() crypto.PubKey { func GenFilePV(filePath string) *FilePV { privKey := crypto.GenPrivKeyEd25519() return &FilePV{ - Address: privKey.PubKey().Address(), - PubKey: privKey.PubKey(), + Address_: privKey.PubKey().Address(), + PubKey_: privKey.PubKey(), PrivKey: privKey, LastStep: stepNone, filePath: filePath, @@ -92,8 +92,8 @@ func LoadFilePV(filePath string) *FilePV { } // overwrite pubkey and address for convenience - pv.PubKey = pv.PrivKey.PubKey() - pv.Address = pv.PubKey.Address() + pv.PubKey_ = pv.PrivKey.PubKey() + pv.Address_ = pv.PubKey_.Address() pv.filePath = filePath return pv @@ -301,7 +301,7 @@ func (pv *FilePV) SignHeartbeat(chainID string, heartbeat *types.Heartbeat) erro // String returns a string representation of the FilePV. func (pv *FilePV) String() string { - return fmt.Sprintf("PrivValidator{%v LH:%v, LR:%v, LS:%v}", pv.GetAddress(), pv.LastHeight, pv.LastRound, pv.LastStep) + return fmt.Sprintf("PrivValidator{%v LH:%v, LR:%v, LS:%v}", pv.Address(), pv.LastHeight, pv.LastRound, pv.LastStep) } //------------------------------------- diff --git a/privval/priv_validator_test.go b/privval/priv_validator_test.go index 5889c0d6..5411e17a 100644 --- a/privval/priv_validator_test.go +++ b/privval/priv_validator_test.go @@ -10,8 +10,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/types" cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/types" ) func TestGenLoadValidator(t *testing.T) { @@ -23,10 +23,10 @@ func TestGenLoadValidator(t *testing.T) { height := int64(100) privVal.LastHeight = height privVal.Save() - addr := privVal.GetAddress() + addr := privVal.Address() privVal = LoadFilePV(tempFilePath) - assert.Equal(addr, privVal.GetAddress(), "expected privval addr to be the same") + assert.Equal(addr, privVal.Address(), "expected privval addr to be the same") assert.Equal(height, privVal.LastHeight, "expected privval.LastHeight to have been saved") } @@ -38,9 +38,9 @@ func TestLoadOrGenValidator(t *testing.T) { t.Error(err) } privVal := LoadOrGenFilePV(tempFilePath) - addr := privVal.GetAddress() + addr := privVal.Address() privVal = LoadOrGenFilePV(tempFilePath) - assert.Equal(addr, privVal.GetAddress(), "expected privval addr to be the same") + assert.Equal(addr, privVal.Address(), "expected privval addr to be the same") } func TestUnmarshalValidator(t *testing.T) { @@ -77,8 +77,8 @@ func TestUnmarshalValidator(t *testing.T) { require.Nil(err, "%+v", err) // make sure the values match - assert.EqualValues(addr, val.GetAddress()) - assert.EqualValues(pubKey, val.GetPubKey()) + assert.EqualValues(addr, val.Address()) + assert.EqualValues(pubKey, val.PubKey()) assert.EqualValues(privKey, val.PrivKey) // export it and make sure it is the same @@ -99,7 +99,7 @@ func TestSignVote(t *testing.T) { voteType := types.VoteTypePrevote // sign a vote for first time - vote := newVote(privVal.Address, 0, height, round, voteType, block1) + vote := newVote(privVal.Address(), 0, height, round, voteType, block1) err := privVal.SignVote("mychainid", vote) assert.NoError(err, "expected no error signing vote") @@ -109,10 +109,10 @@ func TestSignVote(t *testing.T) { // now try some bad votes cases := []*types.Vote{ - newVote(privVal.Address, 0, height, round-1, voteType, block1), // round regression - newVote(privVal.Address, 0, height-1, round, voteType, block1), // height regression - newVote(privVal.Address, 0, height-2, round+4, voteType, block1), // height regression and different round - newVote(privVal.Address, 0, height, round, voteType, block2), // different block + newVote(privVal.Address(), 0, height, round-1, voteType, block1), // round regression + newVote(privVal.Address(), 0, height-1, round, voteType, block1), // height regression + newVote(privVal.Address(), 0, height-2, round+4, voteType, block1), // height regression and different round + newVote(privVal.Address(), 0, height, round, voteType, block2), // different block } for _, c := range cases { @@ -201,7 +201,7 @@ func TestDifferByTimestamp(t *testing.T) { { voteType := types.VoteTypePrevote blockID := types.BlockID{[]byte{1, 2, 3}, types.PartSetHeader{}} - vote := newVote(privVal.Address, 0, height, round, voteType, blockID) + vote := newVote(privVal.Address(), 0, height, round, voteType, blockID) err := privVal.SignVote("mychainid", vote) assert.NoError(t, err, "expected no error signing vote") diff --git a/privval/socket.go b/privval/socket.go index 1e8a3807..76525d63 100644 --- a/privval/socket.go +++ b/privval/socket.go @@ -103,8 +103,8 @@ func NewSocketPV( return sc } -// GetAddress implements PrivValidator. -func (sc *SocketPV) GetAddress() types.Address { +// Address implements PrivValidator. +func (sc *SocketPV) Address() types.Address { addr, err := sc.getAddress() if err != nil { panic(err) @@ -123,8 +123,8 @@ func (sc *SocketPV) getAddress() (cmn.HexBytes, error) { return p.Address(), nil } -// GetPubKey implements PrivValidator. -func (sc *SocketPV) GetPubKey() crypto.PubKey { +// PubKey implements PrivValidator. +func (sc *SocketPV) PubKey() crypto.PubKey { pubKey, err := sc.getPubKey() if err != nil { panic(err) @@ -459,7 +459,7 @@ func (rs *RemoteSigner) handleConnection(conn net.Conn) { switch r := req.(type) { case *PubKeyMsg: var p crypto.PubKey - p = rs.privVal.GetPubKey() + p = rs.privVal.PubKey() res = &PubKeyMsg{p} case *SignVoteMsg: err = rs.privVal.SignVote(rs.chainID, r.Vote) diff --git a/privval/socket_test.go b/privval/socket_test.go index 7bcacd6e..9b7973b3 100644 --- a/privval/socket_test.go +++ b/privval/socket_test.go @@ -25,7 +25,7 @@ func TestSocketPVAddress(t *testing.T) { defer sc.Stop() defer rs.Stop() - serverAddr := rs.privVal.GetAddress() + serverAddr := rs.privVal.Address() clientAddr, err := sc.getAddress() require.NoError(t, err) @@ -33,7 +33,7 @@ func TestSocketPVAddress(t *testing.T) { assert.Equal(t, serverAddr, clientAddr) // TODO(xla): Remove when PrivValidator2 replaced PrivValidator. - assert.Equal(t, serverAddr, sc.GetAddress()) + assert.Equal(t, serverAddr, sc.Address()) } @@ -48,12 +48,12 @@ func TestSocketPVPubKey(t *testing.T) { clientKey, err := sc.getPubKey() require.NoError(t, err) - privKey := rs.privVal.GetPubKey() + privKey := rs.privVal.PubKey() assert.Equal(t, privKey, clientKey) // TODO(xla): Remove when PrivValidator2 replaced PrivValidator. - assert.Equal(t, privKey, sc.GetPubKey()) + assert.Equal(t, privKey, sc.PubKey()) } func TestSocketPVProposal(t *testing.T) { diff --git a/scripts/wire2amino.go b/scripts/wire2amino.go index 4933260e..8c210165 100644 --- a/scripts/wire2amino.go +++ b/scripts/wire2amino.go @@ -8,7 +8,7 @@ import ( "path/filepath" "time" - "github.com/tendermint/go-amino" + amino "github.com/tendermint/go-amino" crypto "github.com/tendermint/tendermint/crypto" cmn "github.com/tendermint/tendermint/libs/common" @@ -84,8 +84,8 @@ func convertPrivVal(cdc *amino.Codec, jsonBytes []byte) ([]byte, error) { copy(pubKey[:], privVal.PubKey.Data) privValNew := privval.FilePV{ - Address: pubKey.Address(), - PubKey: pubKey, + Address_: pubKey.Address(), + PubKey_: pubKey, LastHeight: privVal.LastHeight, LastRound: privVal.LastRound, LastStep: privVal.LastStep, diff --git a/types/evidence_test.go b/types/evidence_test.go index 54eba01c..3c4b1a7a 100644 --- a/types/evidence_test.go +++ b/types/evidence_test.go @@ -14,7 +14,7 @@ type voteData struct { func makeVote(val PrivValidator, chainID string, valIndex int, height int64, round, step int, blockID BlockID) *Vote { v := &Vote{ - ValidatorAddress: val.GetAddress(), + ValidatorAddress: val.Address(), ValidatorIndex: valIndex, Height: height, Round: round, @@ -59,7 +59,7 @@ func TestEvidence(t *testing.T) { {vote1, badVote, false}, // signed by wrong key } - pubKey := val.GetPubKey() + pubKey := val.PubKey() for _, c := range cases { ev := &DuplicateVoteEvidence{ VoteA: c.vote1, diff --git a/types/priv_validator.go b/types/priv_validator.go index 85db65a4..44640aee 100644 --- a/types/priv_validator.go +++ b/types/priv_validator.go @@ -10,8 +10,8 @@ import ( // PrivValidator defines the functionality of a local Tendermint validator // that signs votes, proposals, and heartbeats, and never double signs. type PrivValidator interface { - GetAddress() Address // redundant since .PubKey().Address() - GetPubKey() crypto.PubKey + Address() Address // redundant since .PubKey().Address() + PubKey() crypto.PubKey SignVote(chainID string, vote *Vote) error SignProposal(chainID string, proposal *Proposal) error @@ -28,7 +28,7 @@ func (pvs PrivValidatorsByAddress) Len() int { } func (pvs PrivValidatorsByAddress) Less(i, j int) bool { - return bytes.Compare(pvs[i].GetAddress(), pvs[j].GetAddress()) == -1 + return bytes.Compare(pvs[i].Address(), pvs[j].Address()) == -1 } func (pvs PrivValidatorsByAddress) Swap(i, j int) { @@ -51,12 +51,12 @@ func NewMockPV() *MockPV { } // Implements PrivValidator. -func (pv *MockPV) GetAddress() Address { +func (pv *MockPV) Address() Address { return pv.privKey.PubKey().Address() } // Implements PrivValidator. -func (pv *MockPV) GetPubKey() crypto.PubKey { +func (pv *MockPV) PubKey() crypto.PubKey { return pv.privKey.PubKey() } @@ -94,7 +94,7 @@ func (pv *MockPV) SignHeartbeat(chainID string, heartbeat *Heartbeat) error { // String returns a string representation of the MockPV. func (pv *MockPV) String() string { - return fmt.Sprintf("MockPV{%v}", pv.GetAddress()) + return fmt.Sprintf("MockPV{%v}", pv.Address()) } // XXX: Implement. diff --git a/types/proposal_test.go b/types/proposal_test.go index 8aef870f..9ad51fbc 100644 --- a/types/proposal_test.go +++ b/types/proposal_test.go @@ -47,7 +47,7 @@ func TestProposalString(t *testing.T) { func TestProposalVerifySignature(t *testing.T) { privVal := NewMockPV() - pubKey := privVal.GetPubKey() + pubKey := privVal.PubKey() prop := NewProposal(4, 2, PartSetHeader{777, []byte("proper")}, 2, BlockID{}) signBytes := prop.SignBytes("test_chain_id") @@ -94,7 +94,7 @@ func BenchmarkProposalVerifySignature(b *testing.B) { privVal := NewMockPV() err := privVal.SignProposal("test_chain_id", testProposal) require.Nil(b, err) - pubKey := privVal.GetPubKey() + pubKey := privVal.PubKey() for i := 0; i < b.N; i++ { pubKey.VerifyBytes(testProposal.SignBytes("test_chain_id"), testProposal.Signature) diff --git a/types/protobuf_test.go b/types/protobuf_test.go index ce61fa54..a8abe28b 100644 --- a/types/protobuf_test.go +++ b/types/protobuf_test.go @@ -89,13 +89,13 @@ func TestABCIEvidence(t *testing.T) { blockID2 := makeBlockID("blockhash2", 1000, "partshash") const chainID = "mychain" ev := &DuplicateVoteEvidence{ - PubKey: val.GetPubKey(), + PubKey: val.PubKey(), VoteA: makeVote(val, chainID, 0, 10, 2, 1, blockID), VoteB: makeVote(val, chainID, 0, 10, 2, 1, blockID2), } abciEv := TM2PB.Evidence( ev, - NewValidatorSet([]*Validator{NewValidator(val.GetPubKey(), 10)}), + NewValidatorSet([]*Validator{NewValidator(val.PubKey(), 10)}), time.Now(), ) diff --git a/types/test_util.go b/types/test_util.go index f21c2831..c7e3071b 100644 --- a/types/test_util.go +++ b/types/test_util.go @@ -10,7 +10,7 @@ func MakeCommit(blockID BlockID, height int64, round int, for i := 0; i < len(validators); i++ { vote := &Vote{ - ValidatorAddress: validators[i].GetAddress(), + ValidatorAddress: validators[i].Address(), ValidatorIndex: i, Height: height, Round: round, diff --git a/types/validator.go b/types/validator.go index e43acf09..e7998521 100644 --- a/types/validator.go +++ b/types/validator.go @@ -93,6 +93,7 @@ func RandValidator(randPower bool, minPower int64) (*Validator, PrivValidator) { if randPower { votePower += int64(cmn.RandUint32()) } - val := NewValidator(privVal.GetPubKey(), votePower) + val := NewValidator(privVal.PubKey(), votePower) return val, privVal } + diff --git a/types/vote_set_test.go b/types/vote_set_test.go index 32ceb7b1..0d23d519 100644 --- a/types/vote_set_test.go +++ b/types/vote_set_test.go @@ -66,7 +66,7 @@ func TestAddVote(t *testing.T) { // t.Logf(">> %v", voteSet) - if voteSet.GetByAddress(val0.GetAddress()) != nil { + if voteSet.GetByAddress(val0.Address()) != nil { t.Errorf("Expected GetByAddress(val0.Address) to be nil") } if voteSet.BitArray().GetIndex(0) { @@ -78,7 +78,7 @@ func TestAddVote(t *testing.T) { } vote := &Vote{ - ValidatorAddress: val0.GetAddress(), + ValidatorAddress: val0.Address(), ValidatorIndex: 0, // since privValidators are in order Height: height, Round: round, @@ -91,7 +91,7 @@ func TestAddVote(t *testing.T) { t.Error(err) } - if voteSet.GetByAddress(val0.GetAddress()) == nil { + if voteSet.GetByAddress(val0.Address()) == nil { t.Errorf("Expected GetByAddress(val0.Address) to be present") } if !voteSet.BitArray().GetIndex(0) { @@ -118,7 +118,7 @@ func Test2_3Majority(t *testing.T) { } // 6 out of 10 voted for nil. for i := 0; i < 6; i++ { - vote := withValidator(voteProto, privValidators[i].GetAddress(), i) + vote := withValidator(voteProto, privValidators[i].Address(), i) _, err := signAddVote(privValidators[i], vote, voteSet) if err != nil { t.Error(err) @@ -131,7 +131,7 @@ func Test2_3Majority(t *testing.T) { // 7th validator voted for some blockhash { - vote := withValidator(voteProto, privValidators[6].GetAddress(), 6) + vote := withValidator(voteProto, privValidators[6].Address(), 6) _, err := signAddVote(privValidators[6], withBlockHash(vote, cmn.RandBytes(32)), voteSet) if err != nil { t.Error(err) @@ -144,7 +144,7 @@ func Test2_3Majority(t *testing.T) { // 8th validator voted for nil. { - vote := withValidator(voteProto, privValidators[7].GetAddress(), 7) + vote := withValidator(voteProto, privValidators[7].Address(), 7) _, err := signAddVote(privValidators[7], vote, voteSet) if err != nil { t.Error(err) @@ -176,7 +176,7 @@ func Test2_3MajorityRedux(t *testing.T) { // 66 out of 100 voted for nil. for i := 0; i < 66; i++ { - vote := withValidator(voteProto, privValidators[i].GetAddress(), i) + vote := withValidator(voteProto, privValidators[i].Address(), i) _, err := signAddVote(privValidators[i], vote, voteSet) if err != nil { t.Error(err) @@ -189,7 +189,7 @@ func Test2_3MajorityRedux(t *testing.T) { // 67th validator voted for nil { - vote := withValidator(voteProto, privValidators[66].GetAddress(), 66) + vote := withValidator(voteProto, privValidators[66].Address(), 66) _, err := signAddVote(privValidators[66], withBlockHash(vote, nil), voteSet) if err != nil { t.Error(err) @@ -202,7 +202,7 @@ func Test2_3MajorityRedux(t *testing.T) { // 68th validator voted for a different BlockParts PartSetHeader { - vote := withValidator(voteProto, privValidators[67].GetAddress(), 67) + vote := withValidator(voteProto, privValidators[67].Address(), 67) blockPartsHeader := PartSetHeader{blockPartsTotal, crypto.CRandBytes(32)} _, err := signAddVote(privValidators[67], withBlockPartsHeader(vote, blockPartsHeader), voteSet) if err != nil { @@ -216,7 +216,7 @@ func Test2_3MajorityRedux(t *testing.T) { // 69th validator voted for different BlockParts Total { - vote := withValidator(voteProto, privValidators[68].GetAddress(), 68) + vote := withValidator(voteProto, privValidators[68].Address(), 68) blockPartsHeader := PartSetHeader{blockPartsTotal + 1, blockPartsHeader.Hash} _, err := signAddVote(privValidators[68], withBlockPartsHeader(vote, blockPartsHeader), voteSet) if err != nil { @@ -230,7 +230,7 @@ func Test2_3MajorityRedux(t *testing.T) { // 70th validator voted for different BlockHash { - vote := withValidator(voteProto, privValidators[69].GetAddress(), 69) + vote := withValidator(voteProto, privValidators[69].Address(), 69) _, err := signAddVote(privValidators[69], withBlockHash(vote, cmn.RandBytes(32)), voteSet) if err != nil { t.Error(err) @@ -243,7 +243,7 @@ func Test2_3MajorityRedux(t *testing.T) { // 71st validator voted for the right BlockHash & BlockPartsHeader { - vote := withValidator(voteProto, privValidators[70].GetAddress(), 70) + vote := withValidator(voteProto, privValidators[70].Address(), 70) _, err := signAddVote(privValidators[70], vote, voteSet) if err != nil { t.Error(err) @@ -271,7 +271,7 @@ func TestBadVotes(t *testing.T) { // val0 votes for nil. { - vote := withValidator(voteProto, privValidators[0].GetAddress(), 0) + vote := withValidator(voteProto, privValidators[0].Address(), 0) added, err := signAddVote(privValidators[0], vote, voteSet) if !added || err != nil { t.Errorf("Expected VoteSet.Add to succeed") @@ -280,7 +280,7 @@ func TestBadVotes(t *testing.T) { // val0 votes again for some block. { - vote := withValidator(voteProto, privValidators[0].GetAddress(), 0) + vote := withValidator(voteProto, privValidators[0].Address(), 0) added, err := signAddVote(privValidators[0], withBlockHash(vote, cmn.RandBytes(32)), voteSet) if added || err == nil { t.Errorf("Expected VoteSet.Add to fail, conflicting vote.") @@ -289,7 +289,7 @@ func TestBadVotes(t *testing.T) { // val1 votes on another height { - vote := withValidator(voteProto, privValidators[1].GetAddress(), 1) + vote := withValidator(voteProto, privValidators[1].Address(), 1) added, err := signAddVote(privValidators[1], withHeight(vote, height+1), voteSet) if added || err == nil { t.Errorf("Expected VoteSet.Add to fail, wrong height") @@ -298,7 +298,7 @@ func TestBadVotes(t *testing.T) { // val2 votes on another round { - vote := withValidator(voteProto, privValidators[2].GetAddress(), 2) + vote := withValidator(voteProto, privValidators[2].Address(), 2) added, err := signAddVote(privValidators[2], withRound(vote, round+1), voteSet) if added || err == nil { t.Errorf("Expected VoteSet.Add to fail, wrong round") @@ -307,7 +307,7 @@ func TestBadVotes(t *testing.T) { // val3 votes of another type. { - vote := withValidator(voteProto, privValidators[3].GetAddress(), 3) + vote := withValidator(voteProto, privValidators[3].Address(), 3) added, err := signAddVote(privValidators[3], withType(vote, VoteTypePrecommit), voteSet) if added || err == nil { t.Errorf("Expected VoteSet.Add to fail, wrong type") @@ -333,7 +333,7 @@ func TestConflicts(t *testing.T) { // val0 votes for nil. { - vote := withValidator(voteProto, privValidators[0].GetAddress(), 0) + vote := withValidator(voteProto, privValidators[0].Address(), 0) added, err := signAddVote(privValidators[0], vote, voteSet) if !added || err != nil { t.Errorf("Expected VoteSet.Add to succeed") @@ -342,7 +342,7 @@ func TestConflicts(t *testing.T) { // val0 votes again for blockHash1. { - vote := withValidator(voteProto, privValidators[0].GetAddress(), 0) + vote := withValidator(voteProto, privValidators[0].Address(), 0) added, err := signAddVote(privValidators[0], withBlockHash(vote, blockHash1), voteSet) if added { t.Errorf("Expected VoteSet.Add to fail, conflicting vote.") @@ -357,7 +357,7 @@ func TestConflicts(t *testing.T) { // val0 votes again for blockHash1. { - vote := withValidator(voteProto, privValidators[0].GetAddress(), 0) + vote := withValidator(voteProto, privValidators[0].Address(), 0) added, err := signAddVote(privValidators[0], withBlockHash(vote, blockHash1), voteSet) if !added { t.Errorf("Expected VoteSet.Add to succeed, called SetPeerMaj23().") @@ -372,7 +372,7 @@ func TestConflicts(t *testing.T) { // val0 votes again for blockHash1. { - vote := withValidator(voteProto, privValidators[0].GetAddress(), 0) + vote := withValidator(voteProto, privValidators[0].Address(), 0) added, err := signAddVote(privValidators[0], withBlockHash(vote, blockHash2), voteSet) if added { t.Errorf("Expected VoteSet.Add to fail, duplicate SetPeerMaj23() from peerA") @@ -384,7 +384,7 @@ func TestConflicts(t *testing.T) { // val1 votes for blockHash1. { - vote := withValidator(voteProto, privValidators[1].GetAddress(), 1) + vote := withValidator(voteProto, privValidators[1].Address(), 1) added, err := signAddVote(privValidators[1], withBlockHash(vote, blockHash1), voteSet) if !added || err != nil { t.Errorf("Expected VoteSet.Add to succeed") @@ -401,7 +401,7 @@ func TestConflicts(t *testing.T) { // val2 votes for blockHash2. { - vote := withValidator(voteProto, privValidators[2].GetAddress(), 2) + vote := withValidator(voteProto, privValidators[2].Address(), 2) added, err := signAddVote(privValidators[2], withBlockHash(vote, blockHash2), voteSet) if !added || err != nil { t.Errorf("Expected VoteSet.Add to succeed") @@ -421,7 +421,7 @@ func TestConflicts(t *testing.T) { // val2 votes for blockHash1. { - vote := withValidator(voteProto, privValidators[2].GetAddress(), 2) + vote := withValidator(voteProto, privValidators[2].Address(), 2) added, err := signAddVote(privValidators[2], withBlockHash(vote, blockHash1), voteSet) if !added { t.Errorf("Expected VoteSet.Add to succeed") @@ -462,7 +462,7 @@ func TestMakeCommit(t *testing.T) { // 6 out of 10 voted for some block. for i := 0; i < 6; i++ { - vote := withValidator(voteProto, privValidators[i].GetAddress(), i) + vote := withValidator(voteProto, privValidators[i].Address(), i) _, err := signAddVote(privValidators[i], vote, voteSet) if err != nil { t.Error(err) @@ -474,7 +474,7 @@ func TestMakeCommit(t *testing.T) { // 7th voted for some other block. { - vote := withValidator(voteProto, privValidators[6].GetAddress(), 6) + vote := withValidator(voteProto, privValidators[6].Address(), 6) vote = withBlockHash(vote, cmn.RandBytes(32)) vote = withBlockPartsHeader(vote, PartSetHeader{123, cmn.RandBytes(32)}) @@ -486,7 +486,7 @@ func TestMakeCommit(t *testing.T) { // The 8th voted like everyone else. { - vote := withValidator(voteProto, privValidators[7].GetAddress(), 7) + vote := withValidator(voteProto, privValidators[7].Address(), 7) _, err := signAddVote(privValidators[7], vote, voteSet) if err != nil { t.Error(err) diff --git a/types/vote_test.go b/types/vote_test.go index cbb22aaa..6364fa9d 100644 --- a/types/vote_test.go +++ b/types/vote_test.go @@ -72,7 +72,7 @@ func TestVoteString(t *testing.T) { func TestVoteVerifySignature(t *testing.T) { privVal := NewMockPV() - pubKey := privVal.GetPubKey() + pubKey := privVal.PubKey() vote := examplePrecommit() signBytes := vote.SignBytes("test_chain_id") From 17e1df0cbda5a629fabe211b07618e4943d9c09e Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Thu, 12 Jul 2018 18:32:58 +0400 Subject: [PATCH 14/17] test validator set more thoroughly Refs #693 --- types/validator_set.go | 5 ++-- types/validator_set_test.go | 54 +++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 2 deletions(-) diff --git a/types/validator_set.go b/types/validator_set.go index 191f8b42..25355e72 100644 --- a/types/validator_set.go +++ b/types/validator_set.go @@ -39,14 +39,15 @@ func NewValidatorSet(vals []*Validator) *ValidatorSet { Validators: validators, } - if vals != nil { + if vals != nil && len(vals) > 0 { vs.IncrementAccum(1) } return vs } -// incrementAccum and update the proposer +// IncrementAccum increments accum of each validator and updates the +// proposer. Panics if validator set is empty. func (valSet *ValidatorSet) IncrementAccum(times int) { // Add VotingPower * times to each validator and order into heap. validatorsHeap := cmn.NewHeap() diff --git a/types/validator_set_test.go b/types/validator_set_test.go index 61f4dada..eebcca4d 100644 --- a/types/validator_set_test.go +++ b/types/validator_set_test.go @@ -14,6 +14,60 @@ import ( cmn "github.com/tendermint/tendermint/libs/common" ) +func TestValidatorSetBasic(t *testing.T) { + for _, vset := range []*ValidatorSet{NewValidatorSet([]*Validator{}), NewValidatorSet(nil)} { + assert.Panics(t, func() { vset.IncrementAccum(1) }) + + assert.EqualValues(t, vset, vset.Copy()) + assert.False(t, vset.HasAddress([]byte("some val"))) + idx, val := vset.GetByAddress([]byte("some val")) + assert.Equal(t, -1, idx) + assert.Nil(t, val) + addr, val := vset.GetByIndex(-100) + assert.Nil(t, addr) + assert.Nil(t, val) + addr, val = vset.GetByIndex(0) + assert.Nil(t, addr) + assert.Nil(t, val) + addr, val = vset.GetByIndex(100) + assert.Nil(t, addr) + assert.Nil(t, val) + assert.Zero(t, vset.Size()) + assert.Equal(t, int64(0), vset.TotalVotingPower()) + assert.Nil(t, vset.GetProposer()) + assert.Nil(t, vset.Hash()) + + // add + val = randValidator_() + assert.True(t, vset.Add(val)) + assert.True(t, vset.HasAddress(val.Address)) + idx, val2 := vset.GetByAddress(val.Address) + assert.Equal(t, 0, idx) + assert.Equal(t, val, val2) + addr, val2 = vset.GetByIndex(0) + assert.Equal(t, []byte(val.Address), addr) + assert.Equal(t, val, val2) + assert.Equal(t, 1, vset.Size()) + assert.Equal(t, val.VotingPower, vset.TotalVotingPower()) + assert.Equal(t, val, vset.GetProposer()) + assert.NotNil(t, vset.Hash()) + assert.NotPanics(t, func() { vset.IncrementAccum(1) }) + + // update + assert.False(t, vset.Update(randValidator_())) + val.VotingPower = 100 + assert.True(t, vset.Update(val)) + + // remove + val2, removed := vset.Remove(randValidator_().Address) + assert.Nil(t, val2) + assert.False(t, removed) + val2, removed = vset.Remove(val.Address) + assert.Equal(t, val.Address, val2.Address) + assert.True(t, removed) + } +} + func TestCopy(t *testing.T) { vset := randValidatorSet(10) vsetHash := vset.Hash() From d103aaf53fbe3b56677be6decb5f04918c30070f Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Thu, 12 Jul 2018 18:50:32 +0400 Subject: [PATCH 15/17] add test for Vote#Verify remove test for String (very brittle) --- types/vote_test.go | 46 +++++++++++++++++++++++----------------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/types/vote_test.go b/types/vote_test.go index 6364fa9d..0b8c2a1e 100644 --- a/types/vote_test.go +++ b/types/vote_test.go @@ -4,7 +4,9 @@ import ( "testing" "time" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/tendermint/tendermint/crypto" ) func examplePrevote() *Vote { @@ -50,29 +52,9 @@ func TestVoteSignable(t *testing.T) { } } -func TestVoteString(t *testing.T) { - tc := []struct { - name string - in string - out string - }{ - {"Precommit", examplePrecommit().String(), `Vote{56789:616464720000 12345/02/2(Precommit) 686173680000 @ 2017-12-25T03:00:01.234Z}`}, - {"Prevote", examplePrevote().String(), `Vote{56789:616464720000 12345/02/1(Prevote) 686173680000 @ 2017-12-25T03:00:01.234Z}`}, - } - - for _, tt := range tc { - tt := tt - t.Run(tt.name, func(st *testing.T) { - if tt.in != tt.out { - t.Errorf("Got unexpected string for Proposal. Expected:\n%v\nGot:\n%v", tt.in, tt.out) - } - }) - } -} - func TestVoteVerifySignature(t *testing.T) { privVal := NewMockPV() - pubKey := privVal.PubKey() + pubkey := privVal.PubKey() vote := examplePrecommit() signBytes := vote.SignBytes("test_chain_id") @@ -82,7 +64,7 @@ func TestVoteVerifySignature(t *testing.T) { require.NoError(t, err) // verify the same vote - valid := pubKey.VerifyBytes(vote.SignBytes("test_chain_id"), vote.Signature) + valid := pubkey.VerifyBytes(vote.SignBytes("test_chain_id"), vote.Signature) require.True(t, valid) // serialize, deserialize and verify again.... @@ -95,7 +77,7 @@ func TestVoteVerifySignature(t *testing.T) { // verify the transmitted vote newSignBytes := precommit.SignBytes("test_chain_id") require.Equal(t, string(signBytes), string(newSignBytes)) - valid = pubKey.VerifyBytes(newSignBytes, precommit.Signature) + valid = pubkey.VerifyBytes(newSignBytes, precommit.Signature) require.True(t, valid) } @@ -119,3 +101,21 @@ func TestIsVoteTypeValid(t *testing.T) { }) } } + +func TestVoteVerify(t *testing.T) { + privVal := NewMockPV() + pubkey := privVal.PubKey() + + vote := examplePrevote() + vote.ValidatorAddress = pubkey.Address() + + err := vote.Verify("test_chain_id", crypto.GenPrivKeyEd25519().PubKey()) + if assert.Error(t, err) { + assert.Equal(t, ErrVoteInvalidValidatorAddress, err) + } + + err = vote.Verify("test_chain_id", pubkey) + if assert.Error(t, err) { + assert.Equal(t, ErrVoteInvalidSignature, err) + } +} From 6a85aecfb749d59e07b9b8027a9a1bcc6b5378c6 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Thu, 12 Jul 2018 22:37:03 +0400 Subject: [PATCH 16/17] fix linter issues --- libs/pubsub/query/query.peg.go | 1 + types/validator_set.go | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/libs/pubsub/query/query.peg.go b/libs/pubsub/query/query.peg.go index c3ac726b..c1cc60aa 100644 --- a/libs/pubsub/query/query.peg.go +++ b/libs/pubsub/query/query.peg.go @@ -1,3 +1,4 @@ +// nolint package query //go:generate peg -inline -switch query.peg diff --git a/types/validator_set.go b/types/validator_set.go index 25355e72..60fc2d83 100644 --- a/types/validator_set.go +++ b/types/validator_set.go @@ -39,7 +39,7 @@ func NewValidatorSet(vals []*Validator) *ValidatorSet { Validators: validators, } - if vals != nil && len(vals) > 0 { + if len(vals) > 0 { vs.IncrementAccum(1) } From 3ffda994c2d34a5824824479ab711e4d9f80c1b8 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Thu, 12 Jul 2018 22:38:15 +0400 Subject: [PATCH 17/17] Revert "rename privval#GetAddress and GetPubKey to Address and PubKey" This reverts commit 58d0c8de89bcc6c081c5b33683c2d0a4e1f83eef. --- cmd/tendermint/commands/init.go | 2 +- cmd/tendermint/commands/show_validator.go | 3 +- cmd/tendermint/commands/testnet.go | 2 +- consensus/common_test.go | 8 ++-- consensus/reactor_test.go | 14 +++--- consensus/replay_test.go | 6 +-- consensus/state.go | 14 +++--- consensus/state_test.go | 18 ++++---- consensus/types/height_vote_set_test.go | 2 +- node/node.go | 10 ++--- privval/priv_validator.go | 26 +++++------ privval/priv_validator_test.go | 26 +++++------ privval/socket.go | 10 ++--- privval/socket_test.go | 8 ++-- scripts/wire2amino.go | 6 +-- types/evidence_test.go | 4 +- types/priv_validator.go | 12 ++--- types/proposal_test.go | 4 +- types/protobuf_test.go | 4 +- types/test_util.go | 2 +- types/validator.go | 3 +- types/vote_set_test.go | 54 +++++++++++------------ types/vote_test.go | 4 +- 23 files changed, 120 insertions(+), 122 deletions(-) diff --git a/cmd/tendermint/commands/init.go b/cmd/tendermint/commands/init.go index 5d7d849e..a44c73eb 100644 --- a/cmd/tendermint/commands/init.go +++ b/cmd/tendermint/commands/init.go @@ -57,7 +57,7 @@ func initFilesWithConfig(config *cfg.Config) error { ConsensusParams: types.DefaultConsensusParams(), } genDoc.Validators = []types.GenesisValidator{{ - PubKey: pv.PubKey(), + PubKey: pv.GetPubKey(), Power: 10, }} diff --git a/cmd/tendermint/commands/show_validator.go b/cmd/tendermint/commands/show_validator.go index 4bf1f611..54765164 100644 --- a/cmd/tendermint/commands/show_validator.go +++ b/cmd/tendermint/commands/show_validator.go @@ -17,7 +17,6 @@ var ShowValidatorCmd = &cobra.Command{ func showValidator(cmd *cobra.Command, args []string) { privValidator := privval.LoadOrGenFilePV(config.PrivValidatorFile()) - pubKeyJSONBytes, _ := cdc.MarshalJSON(privValidator.PubKey()) + pubKeyJSONBytes, _ := cdc.MarshalJSON(privValidator.GetPubKey()) fmt.Println(string(pubKeyJSONBytes)) } - diff --git a/cmd/tendermint/commands/testnet.go b/cmd/tendermint/commands/testnet.go index 4981c2da..f7639fb2 100644 --- a/cmd/tendermint/commands/testnet.go +++ b/cmd/tendermint/commands/testnet.go @@ -91,7 +91,7 @@ func testnetFiles(cmd *cobra.Command, args []string) error { pvFile := filepath.Join(nodeDir, config.BaseConfig.PrivValidator) pv := privval.LoadFilePV(pvFile) genVals[i] = types.GenesisValidator{ - PubKey: pv.PubKey(), + PubKey: pv.GetPubKey(), Power: 1, Name: nodeDirName, } diff --git a/consensus/common_test.go b/consensus/common_test.go index ef4f0bcd..2df226ba 100644 --- a/consensus/common_test.go +++ b/consensus/common_test.go @@ -72,7 +72,7 @@ func NewValidatorStub(privValidator types.PrivValidator, valIndex int) *validato func (vs *validatorStub) signVote(voteType byte, hash []byte, header types.PartSetHeader) (*types.Vote, error) { vote := &types.Vote{ ValidatorIndex: vs.Index, - ValidatorAddress: vs.PrivValidator.Address(), + ValidatorAddress: vs.PrivValidator.GetAddress(), Height: vs.Height, Round: vs.Round, Timestamp: time.Now().UTC(), @@ -150,7 +150,7 @@ func signAddVotes(to *ConsensusState, voteType byte, hash []byte, header types.P func validatePrevote(t *testing.T, cs *ConsensusState, round int, privVal *validatorStub, blockHash []byte) { prevotes := cs.Votes.Prevotes(round) var vote *types.Vote - if vote = prevotes.GetByAddress(privVal.Address()); vote == nil { + if vote = prevotes.GetByAddress(privVal.GetAddress()); vote == nil { panic("Failed to find prevote from validator") } if blockHash == nil { @@ -167,7 +167,7 @@ func validatePrevote(t *testing.T, cs *ConsensusState, round int, privVal *valid func validateLastPrecommit(t *testing.T, cs *ConsensusState, privVal *validatorStub, blockHash []byte) { votes := cs.LastCommit var vote *types.Vote - if vote = votes.GetByAddress(privVal.Address()); vote == nil { + if vote = votes.GetByAddress(privVal.GetAddress()); vote == nil { panic("Failed to find precommit from validator") } if !bytes.Equal(vote.BlockID.Hash, blockHash) { @@ -178,7 +178,7 @@ func validateLastPrecommit(t *testing.T, cs *ConsensusState, privVal *validatorS func validatePrecommit(t *testing.T, cs *ConsensusState, thisRound, lockRound int, privVal *validatorStub, votedBlockHash, lockedBlockHash []byte) { precommits := cs.Votes.Precommits(thisRound) var vote *types.Vote - if vote = precommits.GetByAddress(privVal.Address()); vote == nil { + if vote = precommits.GetByAddress(privVal.GetAddress()); vote == nil { panic("Failed to find precommit from validator") } diff --git a/consensus/reactor_test.go b/consensus/reactor_test.go index b8ee9dbe..9e2aa0a0 100644 --- a/consensus/reactor_test.go +++ b/consensus/reactor_test.go @@ -242,7 +242,7 @@ func TestReactorVotingPowerChange(t *testing.T) { // map of active validators activeVals := make(map[string]struct{}) for i := 0; i < nVals; i++ { - activeVals[string(css[i].privValidator.Address())] = struct{}{} + activeVals[string(css[i].privValidator.GetAddress())] = struct{}{} } // wait till everyone makes block 1 @@ -253,7 +253,7 @@ func TestReactorVotingPowerChange(t *testing.T) { //--------------------------------------------------------------------------- logger.Debug("---------------------------- Testing changing the voting power of one validator a few times") - val1PubKey := css[0].privValidator.PubKey() + val1PubKey := css[0].privValidator.GetPubKey() val1PubKeyABCI := types.TM2PB.PubKey(val1PubKey) updateValidatorTx := kvstore.MakeValSetChangeTx(val1PubKeyABCI, 25) previousTotalVotingPower := css[0].GetRoundState().LastValidators.TotalVotingPower() @@ -305,7 +305,7 @@ func TestReactorValidatorSetChanges(t *testing.T) { // map of active validators activeVals := make(map[string]struct{}) for i := 0; i < nVals; i++ { - activeVals[string(css[i].privValidator.Address())] = struct{}{} + activeVals[string(css[i].privValidator.GetAddress())] = struct{}{} } // wait till everyone makes block 1 @@ -316,7 +316,7 @@ func TestReactorValidatorSetChanges(t *testing.T) { //--------------------------------------------------------------------------- logger.Info("---------------------------- Testing adding one validator") - newValidatorPubKey1 := css[nVals].privValidator.PubKey() + newValidatorPubKey1 := css[nVals].privValidator.GetPubKey() valPubKey1ABCI := types.TM2PB.PubKey(newValidatorPubKey1) newValidatorTx1 := kvstore.MakeValSetChangeTx(valPubKey1ABCI, testMinPower) @@ -343,7 +343,7 @@ func TestReactorValidatorSetChanges(t *testing.T) { //--------------------------------------------------------------------------- logger.Info("---------------------------- Testing changing the voting power of one validator") - updateValidatorPubKey1 := css[nVals].privValidator.PubKey() + updateValidatorPubKey1 := css[nVals].privValidator.GetPubKey() updatePubKey1ABCI := types.TM2PB.PubKey(updateValidatorPubKey1) updateValidatorTx1 := kvstore.MakeValSetChangeTx(updatePubKey1ABCI, 25) previousTotalVotingPower := css[nVals].GetRoundState().LastValidators.TotalVotingPower() @@ -360,11 +360,11 @@ func TestReactorValidatorSetChanges(t *testing.T) { //--------------------------------------------------------------------------- logger.Info("---------------------------- Testing adding two validators at once") - newValidatorPubKey2 := css[nVals+1].privValidator.PubKey() + newValidatorPubKey2 := css[nVals+1].privValidator.GetPubKey() newVal2ABCI := types.TM2PB.PubKey(newValidatorPubKey2) newValidatorTx2 := kvstore.MakeValSetChangeTx(newVal2ABCI, testMinPower) - newValidatorPubKey3 := css[nVals+2].privValidator.PubKey() + newValidatorPubKey3 := css[nVals+2].privValidator.GetPubKey() newVal3ABCI := types.TM2PB.PubKey(newValidatorPubKey3) newValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, testMinPower) diff --git a/consensus/replay_test.go b/consensus/replay_test.go index afa868e2..da526d24 100644 --- a/consensus/replay_test.go +++ b/consensus/replay_test.go @@ -347,7 +347,7 @@ func testHandshakeReplay(t *testing.T, nBlocks int, mode uint) { t.Fatalf(err.Error()) } - stateDB, state, store := stateAndStore(config, privVal.PubKey()) + stateDB, state, store := stateAndStore(config, privVal.GetPubKey()) store.chain = chain store.commits = commits @@ -362,7 +362,7 @@ func testHandshakeReplay(t *testing.T, nBlocks int, mode uint) { // run nBlocks against a new client to build up the app state. // use a throwaway tendermint state proxyApp := proxy.NewAppConns(clientCreator2, nil) - stateDB, state, _ := stateAndStore(config, privVal.PubKey()) + stateDB, state, _ := stateAndStore(config, privVal.GetPubKey()) buildAppStateFromChain(proxyApp, stateDB, state, chain, nBlocks, mode) } @@ -646,7 +646,7 @@ func TestInitChainUpdateValidators(t *testing.T) { config := ResetConfig("proxy_test_") privVal := privval.LoadFilePV(config.PrivValidatorFile()) - stateDB, state, store := stateAndStore(config, privVal.PubKey()) + stateDB, state, store := stateAndStore(config, privVal.GetPubKey()) oldValAddr := state.Validators.Validators[0].Address diff --git a/consensus/state.go b/consensus/state.go index ac188a20..e4b360e0 100644 --- a/consensus/state.go +++ b/consensus/state.go @@ -768,7 +768,7 @@ func (cs *ConsensusState) needProofBlock(height int64) bool { func (cs *ConsensusState) proposalHeartbeat(height int64, round int) { counter := 0 - addr := cs.privValidator.Address() + addr := cs.privValidator.GetAddress() valIndex, _ := cs.Validators.GetByAddress(addr) chainID := cs.state.ChainID for { @@ -827,8 +827,8 @@ func (cs *ConsensusState) enterPropose(height int64, round int) { } // if not a validator, we're done - if !cs.Validators.HasAddress(cs.privValidator.Address()) { - logger.Debug("This node is not a validator", "addr", cs.privValidator.Address(), "vals", cs.Validators) + if !cs.Validators.HasAddress(cs.privValidator.GetAddress()) { + logger.Debug("This node is not a validator", "addr", cs.privValidator.GetAddress(), "vals", cs.Validators) return } logger.Debug("This node is a validator") @@ -842,7 +842,7 @@ func (cs *ConsensusState) enterPropose(height int64, round int) { } func (cs *ConsensusState) isProposer() bool { - return bytes.Equal(cs.Validators.GetProposer().Address, cs.privValidator.Address()) + return bytes.Equal(cs.Validators.GetProposer().Address, cs.privValidator.GetAddress()) } func (cs *ConsensusState) defaultDecideProposal(height int64, round int) { @@ -1463,7 +1463,7 @@ func (cs *ConsensusState) tryAddVote(vote *types.Vote, peerID p2p.ID) error { if err == ErrVoteHeightMismatch { return err } else if voteErr, ok := err.(*types.ErrVoteConflictingVotes); ok { - if bytes.Equal(vote.ValidatorAddress, cs.privValidator.Address()) { + if bytes.Equal(vote.ValidatorAddress, cs.privValidator.GetAddress()) { cs.Logger.Error("Found conflicting vote from ourselves. Did you unsafe_reset a validator?", "height", vote.Height, "round", vote.Round, "type", vote.Type) return err } @@ -1620,7 +1620,7 @@ func (cs *ConsensusState) addVote(vote *types.Vote, peerID p2p.ID) (added bool, } func (cs *ConsensusState) signVote(type_ byte, hash []byte, header types.PartSetHeader) (*types.Vote, error) { - addr := cs.privValidator.Address() + addr := cs.privValidator.GetAddress() valIndex, _ := cs.Validators.GetByAddress(addr) vote := &types.Vote{ ValidatorAddress: addr, @@ -1638,7 +1638,7 @@ func (cs *ConsensusState) signVote(type_ byte, hash []byte, header types.PartSet // sign the vote and publish on internalMsgQueue func (cs *ConsensusState) signAddVote(type_ byte, hash []byte, header types.PartSetHeader) *types.Vote { // if we don't have a key or we're not in the validator set, do nothing - if cs.privValidator == nil || !cs.Validators.HasAddress(cs.privValidator.Address()) { + if cs.privValidator == nil || !cs.Validators.HasAddress(cs.privValidator.GetAddress()) { return nil } vote, err := cs.signVote(type_, hash, header) diff --git a/consensus/state_test.go b/consensus/state_test.go index 96d97c4e..6a14e17b 100644 --- a/consensus/state_test.go +++ b/consensus/state_test.go @@ -69,7 +69,7 @@ func TestStateProposerSelection0(t *testing.T) { // lets commit a block and ensure proposer for the next height is correct prop := cs1.GetRoundState().Validators.GetProposer() - if !bytes.Equal(prop.Address, cs1.privValidator.Address()) { + if !bytes.Equal(prop.Address, cs1.privValidator.GetAddress()) { t.Fatalf("expected proposer to be validator %d. Got %X", 0, prop.Address) } @@ -83,7 +83,7 @@ func TestStateProposerSelection0(t *testing.T) { <-newRoundCh prop = cs1.GetRoundState().Validators.GetProposer() - if !bytes.Equal(prop.Address, vss[1].Address()) { + if !bytes.Equal(prop.Address, vss[1].GetAddress()) { panic(cmn.Fmt("expected proposer to be validator %d. Got %X", 1, prop.Address)) } } @@ -104,7 +104,7 @@ func TestStateProposerSelection2(t *testing.T) { // everyone just votes nil. we get a new proposer each round for i := 0; i < len(vss); i++ { prop := cs1.GetRoundState().Validators.GetProposer() - if !bytes.Equal(prop.Address, vss[(i+2)%len(vss)].Address()) { + if !bytes.Equal(prop.Address, vss[(i+2)%len(vss)].GetAddress()) { panic(cmn.Fmt("expected proposer to be validator %d. Got %X", (i+2)%len(vss), prop.Address)) } @@ -629,7 +629,7 @@ func TestStateLockPOLUnlock(t *testing.T) { timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) unlockCh := subscribe(cs1.eventBus, types.EventQueryUnlock) - voteCh := subscribeToVoter(cs1, cs1.privValidator.Address()) + voteCh := subscribeToVoter(cs1, cs1.privValidator.GetAddress()) // everything done from perspective of cs1 @@ -725,7 +725,7 @@ func TestStateLockPOLSafety1(t *testing.T) { timeoutProposeCh := subscribe(cs1.eventBus, types.EventQueryTimeoutPropose) timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) - voteCh := subscribeToVoter(cs1, cs1.privValidator.Address()) + voteCh := subscribeToVoter(cs1, cs1.privValidator.GetAddress()) // start round and wait for propose and prevote startTestRound(cs1, cs1.Height, 0) @@ -849,7 +849,7 @@ func TestStateLockPOLSafety2(t *testing.T) { timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) unlockCh := subscribe(cs1.eventBus, types.EventQueryUnlock) - voteCh := subscribeToVoter(cs1, cs1.privValidator.Address()) + voteCh := subscribeToVoter(cs1, cs1.privValidator.GetAddress()) // the block for R0: gets polkad but we miss it // (even though we signed it, shhh) @@ -945,7 +945,7 @@ func TestStateSlashingPrevotes(t *testing.T) { proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) - voteCh := subscribeToVoter(cs1, cs1.privValidator.Address()) + voteCh := subscribeToVoter(cs1, cs1.privValidator.GetAddress()) // start round and wait for propose and prevote startTestRound(cs1, cs1.Height, 0) @@ -980,7 +980,7 @@ func TestStateSlashingPrecommits(t *testing.T) { proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) - voteCh := subscribeToVoter(cs1, cs1.privValidator.Address()) + voteCh := subscribeToVoter(cs1, cs1.privValidator.GetAddress()) // start round and wait for propose and prevote startTestRound(cs1, cs1.Height, 0) @@ -1027,7 +1027,7 @@ func TestStateHalt1(t *testing.T) { timeoutWaitCh := subscribe(cs1.eventBus, types.EventQueryTimeoutWait) newRoundCh := subscribe(cs1.eventBus, types.EventQueryNewRound) newBlockCh := subscribe(cs1.eventBus, types.EventQueryNewBlock) - voteCh := subscribeToVoter(cs1, cs1.privValidator.Address()) + voteCh := subscribeToVoter(cs1, cs1.privValidator.GetAddress()) // start round and wait for propose and prevote startTestRound(cs1, cs1.Height, 0) diff --git a/consensus/types/height_vote_set_test.go b/consensus/types/height_vote_set_test.go index 03e40d0b..0de65600 100644 --- a/consensus/types/height_vote_set_test.go +++ b/consensus/types/height_vote_set_test.go @@ -51,7 +51,7 @@ func TestPeerCatchupRounds(t *testing.T) { func makeVoteHR(t *testing.T, height int64, round int, privVals []types.PrivValidator, valIndex int) *types.Vote { privVal := privVals[valIndex] vote := &types.Vote{ - ValidatorAddress: privVal.Address(), + ValidatorAddress: privVal.GetAddress(), ValidatorIndex: valIndex, Height: height, Round: round, diff --git a/node/node.go b/node/node.go index d2ef1db2..9f6428ec 100644 --- a/node/node.go +++ b/node/node.go @@ -217,16 +217,16 @@ func NewNode(config *cfg.Config, fastSync := config.FastSync if state.Validators.Size() == 1 { addr, _ := state.Validators.GetByIndex(0) - if bytes.Equal(privValidator.Address(), addr) { + if bytes.Equal(privValidator.GetAddress(), addr) { fastSync = false } } // Log whether this node is a validator or an observer - if state.Validators.HasAddress(privValidator.Address()) { - consensusLogger.Info("This node is a validator", "addr", privValidator.Address(), "pubKey", privValidator.PubKey()) + if state.Validators.HasAddress(privValidator.GetAddress()) { + consensusLogger.Info("This node is a validator", "addr", privValidator.GetAddress(), "pubKey", privValidator.GetPubKey()) } else { - consensusLogger.Info("This node is not a validator", "addr", privValidator.Address(), "pubKey", privValidator.PubKey()) + consensusLogger.Info("This node is not a validator", "addr", privValidator.GetAddress(), "pubKey", privValidator.GetPubKey()) } // metrics @@ -537,7 +537,7 @@ func (n *Node) ConfigureRPC() { rpccore.SetMempool(n.mempoolReactor.Mempool) rpccore.SetEvidencePool(n.evidencePool) rpccore.SetSwitch(n.sw) - rpccore.SetPubKey(n.privValidator.PubKey()) + rpccore.SetPubKey(n.privValidator.GetPubKey()) rpccore.SetGenesisDoc(n.genesisDoc) rpccore.SetAddrBook(n.addrBook) rpccore.SetProxyAppQuery(n.proxyApp.Query()) diff --git a/privval/priv_validator.go b/privval/priv_validator.go index f4b9de64..1e85bf7b 100644 --- a/privval/priv_validator.go +++ b/privval/priv_validator.go @@ -37,8 +37,8 @@ func voteToStep(vote *types.Vote) int8 { // to prevent double signing. // NOTE: the directory containing the pv.filePath must already exist. type FilePV struct { - Address_ types.Address `json:"address"` - PubKey_ crypto.PubKey `json:"pub_key"` + Address types.Address `json:"address"` + PubKey crypto.PubKey `json:"pub_key"` LastHeight int64 `json:"last_height"` LastRound int `json:"last_round"` LastStep int8 `json:"last_step"` @@ -52,16 +52,16 @@ type FilePV struct { mtx sync.Mutex } -// Address returns the address of the validator. +// GetAddress returns the address of the validator. // Implements PrivValidator. -func (pv *FilePV) Address() types.Address { - return pv.Address_ +func (pv *FilePV) GetAddress() types.Address { + return pv.Address } -// PubKey returns the public key of the validator. +// GetPubKey returns the public key of the validator. // Implements PrivValidator. -func (pv *FilePV) PubKey() crypto.PubKey { - return pv.PubKey_ +func (pv *FilePV) GetPubKey() crypto.PubKey { + return pv.PubKey } // GenFilePV generates a new validator with randomly generated private key @@ -69,8 +69,8 @@ func (pv *FilePV) PubKey() crypto.PubKey { func GenFilePV(filePath string) *FilePV { privKey := crypto.GenPrivKeyEd25519() return &FilePV{ - Address_: privKey.PubKey().Address(), - PubKey_: privKey.PubKey(), + Address: privKey.PubKey().Address(), + PubKey: privKey.PubKey(), PrivKey: privKey, LastStep: stepNone, filePath: filePath, @@ -92,8 +92,8 @@ func LoadFilePV(filePath string) *FilePV { } // overwrite pubkey and address for convenience - pv.PubKey_ = pv.PrivKey.PubKey() - pv.Address_ = pv.PubKey_.Address() + pv.PubKey = pv.PrivKey.PubKey() + pv.Address = pv.PubKey.Address() pv.filePath = filePath return pv @@ -301,7 +301,7 @@ func (pv *FilePV) SignHeartbeat(chainID string, heartbeat *types.Heartbeat) erro // String returns a string representation of the FilePV. func (pv *FilePV) String() string { - return fmt.Sprintf("PrivValidator{%v LH:%v, LR:%v, LS:%v}", pv.Address(), pv.LastHeight, pv.LastRound, pv.LastStep) + return fmt.Sprintf("PrivValidator{%v LH:%v, LR:%v, LS:%v}", pv.GetAddress(), pv.LastHeight, pv.LastRound, pv.LastStep) } //------------------------------------- diff --git a/privval/priv_validator_test.go b/privval/priv_validator_test.go index 5411e17a..5889c0d6 100644 --- a/privval/priv_validator_test.go +++ b/privval/priv_validator_test.go @@ -10,8 +10,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto" - cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/types" + cmn "github.com/tendermint/tendermint/libs/common" ) func TestGenLoadValidator(t *testing.T) { @@ -23,10 +23,10 @@ func TestGenLoadValidator(t *testing.T) { height := int64(100) privVal.LastHeight = height privVal.Save() - addr := privVal.Address() + addr := privVal.GetAddress() privVal = LoadFilePV(tempFilePath) - assert.Equal(addr, privVal.Address(), "expected privval addr to be the same") + assert.Equal(addr, privVal.GetAddress(), "expected privval addr to be the same") assert.Equal(height, privVal.LastHeight, "expected privval.LastHeight to have been saved") } @@ -38,9 +38,9 @@ func TestLoadOrGenValidator(t *testing.T) { t.Error(err) } privVal := LoadOrGenFilePV(tempFilePath) - addr := privVal.Address() + addr := privVal.GetAddress() privVal = LoadOrGenFilePV(tempFilePath) - assert.Equal(addr, privVal.Address(), "expected privval addr to be the same") + assert.Equal(addr, privVal.GetAddress(), "expected privval addr to be the same") } func TestUnmarshalValidator(t *testing.T) { @@ -77,8 +77,8 @@ func TestUnmarshalValidator(t *testing.T) { require.Nil(err, "%+v", err) // make sure the values match - assert.EqualValues(addr, val.Address()) - assert.EqualValues(pubKey, val.PubKey()) + assert.EqualValues(addr, val.GetAddress()) + assert.EqualValues(pubKey, val.GetPubKey()) assert.EqualValues(privKey, val.PrivKey) // export it and make sure it is the same @@ -99,7 +99,7 @@ func TestSignVote(t *testing.T) { voteType := types.VoteTypePrevote // sign a vote for first time - vote := newVote(privVal.Address(), 0, height, round, voteType, block1) + vote := newVote(privVal.Address, 0, height, round, voteType, block1) err := privVal.SignVote("mychainid", vote) assert.NoError(err, "expected no error signing vote") @@ -109,10 +109,10 @@ func TestSignVote(t *testing.T) { // now try some bad votes cases := []*types.Vote{ - newVote(privVal.Address(), 0, height, round-1, voteType, block1), // round regression - newVote(privVal.Address(), 0, height-1, round, voteType, block1), // height regression - newVote(privVal.Address(), 0, height-2, round+4, voteType, block1), // height regression and different round - newVote(privVal.Address(), 0, height, round, voteType, block2), // different block + newVote(privVal.Address, 0, height, round-1, voteType, block1), // round regression + newVote(privVal.Address, 0, height-1, round, voteType, block1), // height regression + newVote(privVal.Address, 0, height-2, round+4, voteType, block1), // height regression and different round + newVote(privVal.Address, 0, height, round, voteType, block2), // different block } for _, c := range cases { @@ -201,7 +201,7 @@ func TestDifferByTimestamp(t *testing.T) { { voteType := types.VoteTypePrevote blockID := types.BlockID{[]byte{1, 2, 3}, types.PartSetHeader{}} - vote := newVote(privVal.Address(), 0, height, round, voteType, blockID) + vote := newVote(privVal.Address, 0, height, round, voteType, blockID) err := privVal.SignVote("mychainid", vote) assert.NoError(t, err, "expected no error signing vote") diff --git a/privval/socket.go b/privval/socket.go index 76525d63..1e8a3807 100644 --- a/privval/socket.go +++ b/privval/socket.go @@ -103,8 +103,8 @@ func NewSocketPV( return sc } -// Address implements PrivValidator. -func (sc *SocketPV) Address() types.Address { +// GetAddress implements PrivValidator. +func (sc *SocketPV) GetAddress() types.Address { addr, err := sc.getAddress() if err != nil { panic(err) @@ -123,8 +123,8 @@ func (sc *SocketPV) getAddress() (cmn.HexBytes, error) { return p.Address(), nil } -// PubKey implements PrivValidator. -func (sc *SocketPV) PubKey() crypto.PubKey { +// GetPubKey implements PrivValidator. +func (sc *SocketPV) GetPubKey() crypto.PubKey { pubKey, err := sc.getPubKey() if err != nil { panic(err) @@ -459,7 +459,7 @@ func (rs *RemoteSigner) handleConnection(conn net.Conn) { switch r := req.(type) { case *PubKeyMsg: var p crypto.PubKey - p = rs.privVal.PubKey() + p = rs.privVal.GetPubKey() res = &PubKeyMsg{p} case *SignVoteMsg: err = rs.privVal.SignVote(rs.chainID, r.Vote) diff --git a/privval/socket_test.go b/privval/socket_test.go index 9b7973b3..7bcacd6e 100644 --- a/privval/socket_test.go +++ b/privval/socket_test.go @@ -25,7 +25,7 @@ func TestSocketPVAddress(t *testing.T) { defer sc.Stop() defer rs.Stop() - serverAddr := rs.privVal.Address() + serverAddr := rs.privVal.GetAddress() clientAddr, err := sc.getAddress() require.NoError(t, err) @@ -33,7 +33,7 @@ func TestSocketPVAddress(t *testing.T) { assert.Equal(t, serverAddr, clientAddr) // TODO(xla): Remove when PrivValidator2 replaced PrivValidator. - assert.Equal(t, serverAddr, sc.Address()) + assert.Equal(t, serverAddr, sc.GetAddress()) } @@ -48,12 +48,12 @@ func TestSocketPVPubKey(t *testing.T) { clientKey, err := sc.getPubKey() require.NoError(t, err) - privKey := rs.privVal.PubKey() + privKey := rs.privVal.GetPubKey() assert.Equal(t, privKey, clientKey) // TODO(xla): Remove when PrivValidator2 replaced PrivValidator. - assert.Equal(t, privKey, sc.PubKey()) + assert.Equal(t, privKey, sc.GetPubKey()) } func TestSocketPVProposal(t *testing.T) { diff --git a/scripts/wire2amino.go b/scripts/wire2amino.go index 8c210165..4933260e 100644 --- a/scripts/wire2amino.go +++ b/scripts/wire2amino.go @@ -8,7 +8,7 @@ import ( "path/filepath" "time" - amino "github.com/tendermint/go-amino" + "github.com/tendermint/go-amino" crypto "github.com/tendermint/tendermint/crypto" cmn "github.com/tendermint/tendermint/libs/common" @@ -84,8 +84,8 @@ func convertPrivVal(cdc *amino.Codec, jsonBytes []byte) ([]byte, error) { copy(pubKey[:], privVal.PubKey.Data) privValNew := privval.FilePV{ - Address_: pubKey.Address(), - PubKey_: pubKey, + Address: pubKey.Address(), + PubKey: pubKey, LastHeight: privVal.LastHeight, LastRound: privVal.LastRound, LastStep: privVal.LastStep, diff --git a/types/evidence_test.go b/types/evidence_test.go index 3c4b1a7a..54eba01c 100644 --- a/types/evidence_test.go +++ b/types/evidence_test.go @@ -14,7 +14,7 @@ type voteData struct { func makeVote(val PrivValidator, chainID string, valIndex int, height int64, round, step int, blockID BlockID) *Vote { v := &Vote{ - ValidatorAddress: val.Address(), + ValidatorAddress: val.GetAddress(), ValidatorIndex: valIndex, Height: height, Round: round, @@ -59,7 +59,7 @@ func TestEvidence(t *testing.T) { {vote1, badVote, false}, // signed by wrong key } - pubKey := val.PubKey() + pubKey := val.GetPubKey() for _, c := range cases { ev := &DuplicateVoteEvidence{ VoteA: c.vote1, diff --git a/types/priv_validator.go b/types/priv_validator.go index 44640aee..85db65a4 100644 --- a/types/priv_validator.go +++ b/types/priv_validator.go @@ -10,8 +10,8 @@ import ( // PrivValidator defines the functionality of a local Tendermint validator // that signs votes, proposals, and heartbeats, and never double signs. type PrivValidator interface { - Address() Address // redundant since .PubKey().Address() - PubKey() crypto.PubKey + GetAddress() Address // redundant since .PubKey().Address() + GetPubKey() crypto.PubKey SignVote(chainID string, vote *Vote) error SignProposal(chainID string, proposal *Proposal) error @@ -28,7 +28,7 @@ func (pvs PrivValidatorsByAddress) Len() int { } func (pvs PrivValidatorsByAddress) Less(i, j int) bool { - return bytes.Compare(pvs[i].Address(), pvs[j].Address()) == -1 + return bytes.Compare(pvs[i].GetAddress(), pvs[j].GetAddress()) == -1 } func (pvs PrivValidatorsByAddress) Swap(i, j int) { @@ -51,12 +51,12 @@ func NewMockPV() *MockPV { } // Implements PrivValidator. -func (pv *MockPV) Address() Address { +func (pv *MockPV) GetAddress() Address { return pv.privKey.PubKey().Address() } // Implements PrivValidator. -func (pv *MockPV) PubKey() crypto.PubKey { +func (pv *MockPV) GetPubKey() crypto.PubKey { return pv.privKey.PubKey() } @@ -94,7 +94,7 @@ func (pv *MockPV) SignHeartbeat(chainID string, heartbeat *Heartbeat) error { // String returns a string representation of the MockPV. func (pv *MockPV) String() string { - return fmt.Sprintf("MockPV{%v}", pv.Address()) + return fmt.Sprintf("MockPV{%v}", pv.GetAddress()) } // XXX: Implement. diff --git a/types/proposal_test.go b/types/proposal_test.go index 9ad51fbc..8aef870f 100644 --- a/types/proposal_test.go +++ b/types/proposal_test.go @@ -47,7 +47,7 @@ func TestProposalString(t *testing.T) { func TestProposalVerifySignature(t *testing.T) { privVal := NewMockPV() - pubKey := privVal.PubKey() + pubKey := privVal.GetPubKey() prop := NewProposal(4, 2, PartSetHeader{777, []byte("proper")}, 2, BlockID{}) signBytes := prop.SignBytes("test_chain_id") @@ -94,7 +94,7 @@ func BenchmarkProposalVerifySignature(b *testing.B) { privVal := NewMockPV() err := privVal.SignProposal("test_chain_id", testProposal) require.Nil(b, err) - pubKey := privVal.PubKey() + pubKey := privVal.GetPubKey() for i := 0; i < b.N; i++ { pubKey.VerifyBytes(testProposal.SignBytes("test_chain_id"), testProposal.Signature) diff --git a/types/protobuf_test.go b/types/protobuf_test.go index a8abe28b..ce61fa54 100644 --- a/types/protobuf_test.go +++ b/types/protobuf_test.go @@ -89,13 +89,13 @@ func TestABCIEvidence(t *testing.T) { blockID2 := makeBlockID("blockhash2", 1000, "partshash") const chainID = "mychain" ev := &DuplicateVoteEvidence{ - PubKey: val.PubKey(), + PubKey: val.GetPubKey(), VoteA: makeVote(val, chainID, 0, 10, 2, 1, blockID), VoteB: makeVote(val, chainID, 0, 10, 2, 1, blockID2), } abciEv := TM2PB.Evidence( ev, - NewValidatorSet([]*Validator{NewValidator(val.PubKey(), 10)}), + NewValidatorSet([]*Validator{NewValidator(val.GetPubKey(), 10)}), time.Now(), ) diff --git a/types/test_util.go b/types/test_util.go index c7e3071b..f21c2831 100644 --- a/types/test_util.go +++ b/types/test_util.go @@ -10,7 +10,7 @@ func MakeCommit(blockID BlockID, height int64, round int, for i := 0; i < len(validators); i++ { vote := &Vote{ - ValidatorAddress: validators[i].Address(), + ValidatorAddress: validators[i].GetAddress(), ValidatorIndex: i, Height: height, Round: round, diff --git a/types/validator.go b/types/validator.go index e7998521..e43acf09 100644 --- a/types/validator.go +++ b/types/validator.go @@ -93,7 +93,6 @@ func RandValidator(randPower bool, minPower int64) (*Validator, PrivValidator) { if randPower { votePower += int64(cmn.RandUint32()) } - val := NewValidator(privVal.PubKey(), votePower) + val := NewValidator(privVal.GetPubKey(), votePower) return val, privVal } - diff --git a/types/vote_set_test.go b/types/vote_set_test.go index 0d23d519..32ceb7b1 100644 --- a/types/vote_set_test.go +++ b/types/vote_set_test.go @@ -66,7 +66,7 @@ func TestAddVote(t *testing.T) { // t.Logf(">> %v", voteSet) - if voteSet.GetByAddress(val0.Address()) != nil { + if voteSet.GetByAddress(val0.GetAddress()) != nil { t.Errorf("Expected GetByAddress(val0.Address) to be nil") } if voteSet.BitArray().GetIndex(0) { @@ -78,7 +78,7 @@ func TestAddVote(t *testing.T) { } vote := &Vote{ - ValidatorAddress: val0.Address(), + ValidatorAddress: val0.GetAddress(), ValidatorIndex: 0, // since privValidators are in order Height: height, Round: round, @@ -91,7 +91,7 @@ func TestAddVote(t *testing.T) { t.Error(err) } - if voteSet.GetByAddress(val0.Address()) == nil { + if voteSet.GetByAddress(val0.GetAddress()) == nil { t.Errorf("Expected GetByAddress(val0.Address) to be present") } if !voteSet.BitArray().GetIndex(0) { @@ -118,7 +118,7 @@ func Test2_3Majority(t *testing.T) { } // 6 out of 10 voted for nil. for i := 0; i < 6; i++ { - vote := withValidator(voteProto, privValidators[i].Address(), i) + vote := withValidator(voteProto, privValidators[i].GetAddress(), i) _, err := signAddVote(privValidators[i], vote, voteSet) if err != nil { t.Error(err) @@ -131,7 +131,7 @@ func Test2_3Majority(t *testing.T) { // 7th validator voted for some blockhash { - vote := withValidator(voteProto, privValidators[6].Address(), 6) + vote := withValidator(voteProto, privValidators[6].GetAddress(), 6) _, err := signAddVote(privValidators[6], withBlockHash(vote, cmn.RandBytes(32)), voteSet) if err != nil { t.Error(err) @@ -144,7 +144,7 @@ func Test2_3Majority(t *testing.T) { // 8th validator voted for nil. { - vote := withValidator(voteProto, privValidators[7].Address(), 7) + vote := withValidator(voteProto, privValidators[7].GetAddress(), 7) _, err := signAddVote(privValidators[7], vote, voteSet) if err != nil { t.Error(err) @@ -176,7 +176,7 @@ func Test2_3MajorityRedux(t *testing.T) { // 66 out of 100 voted for nil. for i := 0; i < 66; i++ { - vote := withValidator(voteProto, privValidators[i].Address(), i) + vote := withValidator(voteProto, privValidators[i].GetAddress(), i) _, err := signAddVote(privValidators[i], vote, voteSet) if err != nil { t.Error(err) @@ -189,7 +189,7 @@ func Test2_3MajorityRedux(t *testing.T) { // 67th validator voted for nil { - vote := withValidator(voteProto, privValidators[66].Address(), 66) + vote := withValidator(voteProto, privValidators[66].GetAddress(), 66) _, err := signAddVote(privValidators[66], withBlockHash(vote, nil), voteSet) if err != nil { t.Error(err) @@ -202,7 +202,7 @@ func Test2_3MajorityRedux(t *testing.T) { // 68th validator voted for a different BlockParts PartSetHeader { - vote := withValidator(voteProto, privValidators[67].Address(), 67) + vote := withValidator(voteProto, privValidators[67].GetAddress(), 67) blockPartsHeader := PartSetHeader{blockPartsTotal, crypto.CRandBytes(32)} _, err := signAddVote(privValidators[67], withBlockPartsHeader(vote, blockPartsHeader), voteSet) if err != nil { @@ -216,7 +216,7 @@ func Test2_3MajorityRedux(t *testing.T) { // 69th validator voted for different BlockParts Total { - vote := withValidator(voteProto, privValidators[68].Address(), 68) + vote := withValidator(voteProto, privValidators[68].GetAddress(), 68) blockPartsHeader := PartSetHeader{blockPartsTotal + 1, blockPartsHeader.Hash} _, err := signAddVote(privValidators[68], withBlockPartsHeader(vote, blockPartsHeader), voteSet) if err != nil { @@ -230,7 +230,7 @@ func Test2_3MajorityRedux(t *testing.T) { // 70th validator voted for different BlockHash { - vote := withValidator(voteProto, privValidators[69].Address(), 69) + vote := withValidator(voteProto, privValidators[69].GetAddress(), 69) _, err := signAddVote(privValidators[69], withBlockHash(vote, cmn.RandBytes(32)), voteSet) if err != nil { t.Error(err) @@ -243,7 +243,7 @@ func Test2_3MajorityRedux(t *testing.T) { // 71st validator voted for the right BlockHash & BlockPartsHeader { - vote := withValidator(voteProto, privValidators[70].Address(), 70) + vote := withValidator(voteProto, privValidators[70].GetAddress(), 70) _, err := signAddVote(privValidators[70], vote, voteSet) if err != nil { t.Error(err) @@ -271,7 +271,7 @@ func TestBadVotes(t *testing.T) { // val0 votes for nil. { - vote := withValidator(voteProto, privValidators[0].Address(), 0) + vote := withValidator(voteProto, privValidators[0].GetAddress(), 0) added, err := signAddVote(privValidators[0], vote, voteSet) if !added || err != nil { t.Errorf("Expected VoteSet.Add to succeed") @@ -280,7 +280,7 @@ func TestBadVotes(t *testing.T) { // val0 votes again for some block. { - vote := withValidator(voteProto, privValidators[0].Address(), 0) + vote := withValidator(voteProto, privValidators[0].GetAddress(), 0) added, err := signAddVote(privValidators[0], withBlockHash(vote, cmn.RandBytes(32)), voteSet) if added || err == nil { t.Errorf("Expected VoteSet.Add to fail, conflicting vote.") @@ -289,7 +289,7 @@ func TestBadVotes(t *testing.T) { // val1 votes on another height { - vote := withValidator(voteProto, privValidators[1].Address(), 1) + vote := withValidator(voteProto, privValidators[1].GetAddress(), 1) added, err := signAddVote(privValidators[1], withHeight(vote, height+1), voteSet) if added || err == nil { t.Errorf("Expected VoteSet.Add to fail, wrong height") @@ -298,7 +298,7 @@ func TestBadVotes(t *testing.T) { // val2 votes on another round { - vote := withValidator(voteProto, privValidators[2].Address(), 2) + vote := withValidator(voteProto, privValidators[2].GetAddress(), 2) added, err := signAddVote(privValidators[2], withRound(vote, round+1), voteSet) if added || err == nil { t.Errorf("Expected VoteSet.Add to fail, wrong round") @@ -307,7 +307,7 @@ func TestBadVotes(t *testing.T) { // val3 votes of another type. { - vote := withValidator(voteProto, privValidators[3].Address(), 3) + vote := withValidator(voteProto, privValidators[3].GetAddress(), 3) added, err := signAddVote(privValidators[3], withType(vote, VoteTypePrecommit), voteSet) if added || err == nil { t.Errorf("Expected VoteSet.Add to fail, wrong type") @@ -333,7 +333,7 @@ func TestConflicts(t *testing.T) { // val0 votes for nil. { - vote := withValidator(voteProto, privValidators[0].Address(), 0) + vote := withValidator(voteProto, privValidators[0].GetAddress(), 0) added, err := signAddVote(privValidators[0], vote, voteSet) if !added || err != nil { t.Errorf("Expected VoteSet.Add to succeed") @@ -342,7 +342,7 @@ func TestConflicts(t *testing.T) { // val0 votes again for blockHash1. { - vote := withValidator(voteProto, privValidators[0].Address(), 0) + vote := withValidator(voteProto, privValidators[0].GetAddress(), 0) added, err := signAddVote(privValidators[0], withBlockHash(vote, blockHash1), voteSet) if added { t.Errorf("Expected VoteSet.Add to fail, conflicting vote.") @@ -357,7 +357,7 @@ func TestConflicts(t *testing.T) { // val0 votes again for blockHash1. { - vote := withValidator(voteProto, privValidators[0].Address(), 0) + vote := withValidator(voteProto, privValidators[0].GetAddress(), 0) added, err := signAddVote(privValidators[0], withBlockHash(vote, blockHash1), voteSet) if !added { t.Errorf("Expected VoteSet.Add to succeed, called SetPeerMaj23().") @@ -372,7 +372,7 @@ func TestConflicts(t *testing.T) { // val0 votes again for blockHash1. { - vote := withValidator(voteProto, privValidators[0].Address(), 0) + vote := withValidator(voteProto, privValidators[0].GetAddress(), 0) added, err := signAddVote(privValidators[0], withBlockHash(vote, blockHash2), voteSet) if added { t.Errorf("Expected VoteSet.Add to fail, duplicate SetPeerMaj23() from peerA") @@ -384,7 +384,7 @@ func TestConflicts(t *testing.T) { // val1 votes for blockHash1. { - vote := withValidator(voteProto, privValidators[1].Address(), 1) + vote := withValidator(voteProto, privValidators[1].GetAddress(), 1) added, err := signAddVote(privValidators[1], withBlockHash(vote, blockHash1), voteSet) if !added || err != nil { t.Errorf("Expected VoteSet.Add to succeed") @@ -401,7 +401,7 @@ func TestConflicts(t *testing.T) { // val2 votes for blockHash2. { - vote := withValidator(voteProto, privValidators[2].Address(), 2) + vote := withValidator(voteProto, privValidators[2].GetAddress(), 2) added, err := signAddVote(privValidators[2], withBlockHash(vote, blockHash2), voteSet) if !added || err != nil { t.Errorf("Expected VoteSet.Add to succeed") @@ -421,7 +421,7 @@ func TestConflicts(t *testing.T) { // val2 votes for blockHash1. { - vote := withValidator(voteProto, privValidators[2].Address(), 2) + vote := withValidator(voteProto, privValidators[2].GetAddress(), 2) added, err := signAddVote(privValidators[2], withBlockHash(vote, blockHash1), voteSet) if !added { t.Errorf("Expected VoteSet.Add to succeed") @@ -462,7 +462,7 @@ func TestMakeCommit(t *testing.T) { // 6 out of 10 voted for some block. for i := 0; i < 6; i++ { - vote := withValidator(voteProto, privValidators[i].Address(), i) + vote := withValidator(voteProto, privValidators[i].GetAddress(), i) _, err := signAddVote(privValidators[i], vote, voteSet) if err != nil { t.Error(err) @@ -474,7 +474,7 @@ func TestMakeCommit(t *testing.T) { // 7th voted for some other block. { - vote := withValidator(voteProto, privValidators[6].Address(), 6) + vote := withValidator(voteProto, privValidators[6].GetAddress(), 6) vote = withBlockHash(vote, cmn.RandBytes(32)) vote = withBlockPartsHeader(vote, PartSetHeader{123, cmn.RandBytes(32)}) @@ -486,7 +486,7 @@ func TestMakeCommit(t *testing.T) { // The 8th voted like everyone else. { - vote := withValidator(voteProto, privValidators[7].Address(), 7) + vote := withValidator(voteProto, privValidators[7].GetAddress(), 7) _, err := signAddVote(privValidators[7], vote, voteSet) if err != nil { t.Error(err) diff --git a/types/vote_test.go b/types/vote_test.go index 0b8c2a1e..c9e725ec 100644 --- a/types/vote_test.go +++ b/types/vote_test.go @@ -54,7 +54,7 @@ func TestVoteSignable(t *testing.T) { func TestVoteVerifySignature(t *testing.T) { privVal := NewMockPV() - pubkey := privVal.PubKey() + pubkey := privVal.GetPubKey() vote := examplePrecommit() signBytes := vote.SignBytes("test_chain_id") @@ -104,7 +104,7 @@ func TestIsVoteTypeValid(t *testing.T) { func TestVoteVerify(t *testing.T) { privVal := NewMockPV() - pubkey := privVal.PubKey() + pubkey := privVal.GetPubKey() vote := examplePrevote() vote.ValidatorAddress = pubkey.Address()