Browse Source

gocritic (1/2) (#3836)

Add gocritic as a linter

    The linting is not complete, but should i complete in this PR or in a following.

    23 files have been touched so it may be better to do in a following PR


Commits:

* Add gocritic to linting

- Added gocritic to linting

Signed-off-by: Marko Baricevic <marbar3778@yahoo.com>

* gocritic

* pr comments

* remove switch in cmdBatch
pull/3854/head
Marko 5 years ago
committed by Anton Kaliaev
parent
commit
41bf54a906
23 changed files with 89 additions and 123 deletions
  1. +13
    -37
      abci/cmd/abci-cli/abci-cli.go
  2. +1
    -2
      abci/example/kvstore/persistent_kvstore.go
  3. +4
    -3
      abci/server/socket_server.go
  4. +1
    -1
      cmd/tendermint/commands/root_test.go
  5. +2
    -2
      consensus/mempool_test.go
  6. +6
    -6
      consensus/reactor_test.go
  7. +2
    -4
      consensus/replay.go
  8. +2
    -4
      consensus/replay_file.go
  9. +2
    -4
      consensus/state.go
  10. +18
    -18
      consensus/state_test.go
  11. +2
    -2
      crypto/ed25519/ed25519.go
  12. +2
    -2
      crypto/internal/benchmarking/bench.go
  13. +1
    -0
      crypto/secp256k1/internal/secp256k1/curve.go
  14. +1
    -1
      libs/cli/helper.go
  15. +3
    -5
      libs/common/random_test.go
  16. +4
    -3
      libs/common/string.go
  17. +4
    -4
      mempool/reactor_test.go
  18. +1
    -1
      p2p/node_info_test.go
  19. +3
    -3
      p2p/pex/addrbook.go
  20. +4
    -6
      rpc/lib/server/handlers.go
  21. +9
    -9
      state/state_test.go
  22. +2
    -4
      types/genesis.go
  23. +2
    -2
      types/validator_set.go

+ 13
- 37
abci/cmd/abci-cli/abci-cli.go View File

@ -174,9 +174,7 @@ where example.file looks something like:
info
`,
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
return cmdBatch(cmd, args)
},
RunE: cmdBatch,
}
var consoleCmd = &cobra.Command{
@ -189,9 +187,7 @@ without opening a new connection each time
`,
Args: cobra.ExactArgs(0),
ValidArgs: []string{"echo", "info", "set_option", "deliver_tx", "check_tx", "commit", "query"},
RunE: func(cmd *cobra.Command, args []string) error {
return cmdConsole(cmd, args)
},
RunE: cmdConsole,
}
var echoCmd = &cobra.Command{
@ -199,27 +195,21 @@ var echoCmd = &cobra.Command{
Short: "have the application echo a message",
Long: "have the application echo a message",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return cmdEcho(cmd, args)
},
RunE: cmdEcho,
}
var infoCmd = &cobra.Command{
Use: "info",
Short: "get some info about the application",
Long: "get some info about the application",
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
return cmdInfo(cmd, args)
},
RunE: cmdInfo,
}
var setOptionCmd = &cobra.Command{
Use: "set_option",
Short: "set an option on the application",
Long: "set an option on the application",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
return cmdSetOption(cmd, args)
},
RunE: cmdSetOption,
}
var deliverTxCmd = &cobra.Command{
@ -227,9 +217,7 @@ var deliverTxCmd = &cobra.Command{
Short: "deliver a new transaction to the application",
Long: "deliver a new transaction to the application",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return cmdDeliverTx(cmd, args)
},
RunE: cmdDeliverTx,
}
var checkTxCmd = &cobra.Command{
@ -237,9 +225,7 @@ var checkTxCmd = &cobra.Command{
Short: "validate a transaction",
Long: "validate a transaction",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return cmdCheckTx(cmd, args)
},
RunE: cmdCheckTx,
}
var commitCmd = &cobra.Command{
@ -247,9 +233,7 @@ var commitCmd = &cobra.Command{
Short: "commit the application state and return the Merkle root hash",
Long: "commit the application state and return the Merkle root hash",
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
return cmdCommit(cmd, args)
},
RunE: cmdCommit,
}
var versionCmd = &cobra.Command{
@ -268,9 +252,7 @@ var queryCmd = &cobra.Command{
Short: "query the application state",
Long: "query the application state",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return cmdQuery(cmd, args)
},
RunE: cmdQuery,
}
var counterCmd = &cobra.Command{
@ -278,9 +260,7 @@ var counterCmd = &cobra.Command{
Short: "ABCI demo example",
Long: "ABCI demo example",
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
return cmdCounter(cmd, args)
},
RunE: cmdCounter,
}
var kvstoreCmd = &cobra.Command{
@ -288,9 +268,7 @@ var kvstoreCmd = &cobra.Command{
Short: "ABCI demo example",
Long: "ABCI demo example",
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
return cmdKVStore(cmd, args)
},
RunE: cmdKVStore,
}
var testCmd = &cobra.Command{
@ -298,9 +276,7 @@ var testCmd = &cobra.Command{
Short: "run integration tests",
Long: "run integration tests",
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
return cmdTest(cmd, args)
},
RunE: cmdTest,
}
// Generates new Args array based off of previous call args to maintain flag persistence
@ -419,7 +395,7 @@ func muxOnCommands(cmd *cobra.Command, pArgs []string) error {
}
// otherwise, we need to skip the next one too
i += 1
i++
continue
}


+ 1
- 2
abci/example/kvstore/persistent_kvstore.go View File

@ -121,8 +121,7 @@ func (app *PersistentKVStoreApplication) BeginBlock(req types.RequestBeginBlock)
app.ValUpdates = make([]types.ValidatorUpdate, 0)
for _, ev := range req.ByzantineValidators {
switch ev.Type {
case tmtypes.ABCIEvidenceTypeDuplicateVote:
if ev.Type == tmtypes.ABCIEvidenceTypeDuplicateVote {
// decrease voting power by 1
if ev.TotalVotingPower == 0 {
continue


+ 4
- 3
abci/server/socket_server.go View File

@ -127,11 +127,12 @@ func (s *SocketServer) acceptConnectionsRoutine() {
func (s *SocketServer) waitForClose(closeConn chan error, connID int) {
err := <-closeConn
if err == io.EOF {
switch {
case err == io.EOF:
s.Logger.Error("Connection was closed by client")
} else if err != nil {
case err != nil:
s.Logger.Error("Connection error", "error", err)
} else {
default:
// never happens
s.Logger.Error("Connection was closed.")
}


+ 1
- 1
cmd/tendermint/commands/root_test.go View File

@ -165,7 +165,7 @@ func TestRootConfig(t *testing.T) {
func WriteConfigVals(dir string, vals map[string]string) error {
data := ""
for k, v := range vals {
data = data + fmt.Sprintf("%s = \"%s\"\n", k, v)
data += fmt.Sprintf("%s = \"%s\"\n", k, v)
}
cfile := filepath.Join(dir, "config.toml")
return ioutil.WriteFile(cfile, []byte(data), 0666)


+ 2
- 2
consensus/mempool_test.go View File

@ -82,14 +82,14 @@ func TestMempoolProgressInHigherRound(t *testing.T) {
ensureNewRound(newRoundCh, height, round) // first round at first height
ensureNewEventOnChannel(newBlockCh) // first block gets committed
height = height + 1 // moving to the next height
height++ // moving to the next height
round = 0
ensureNewRound(newRoundCh, height, round) // first round at next height
deliverTxsRange(cs, 0, 1) // we deliver txs, but dont set a proposal so we get the next round
ensureNewTimeout(timeoutCh, height, round, cs.config.TimeoutPropose.Nanoseconds())
round = round + 1 // moving to the next round
round++ // moving to the next round
ensureNewRound(newRoundCh, height, round) // wait for the next round
ensureNewEventOnChannel(newBlockCh) // now we can commit the block
}


+ 6
- 6
consensus/reactor_test.go View File

@ -31,15 +31,15 @@ import (
//----------------------------------------------
// in-process testnets
func startConsensusNet(t *testing.T, css []*ConsensusState, N int) (
func startConsensusNet(t *testing.T, css []*ConsensusState, n int) (
[]*ConsensusReactor,
[]types.Subscription,
[]*types.EventBus,
) {
reactors := make([]*ConsensusReactor, N)
reactors := make([]*ConsensusReactor, n)
blocksSubs := make([]types.Subscription, 0)
eventBuses := make([]*types.EventBus, N)
for i := 0; i < N; i++ {
eventBuses := make([]*types.EventBus, n)
for i := 0; i < n; i++ {
/*logger, err := tmflags.ParseLogLevel("consensus:info,*:error", logger, "info")
if err != nil { t.Fatal(err)}*/
reactors[i] = NewConsensusReactor(css[i], true) // so we dont start the consensus states
@ -58,7 +58,7 @@ func startConsensusNet(t *testing.T, css []*ConsensusState, N int) (
}
}
// make connected switches and start all reactors
p2p.MakeConnectedSwitches(config.P2P, N, func(i int, s *p2p.Switch) *p2p.Switch {
p2p.MakeConnectedSwitches(config.P2P, n, func(i int, s *p2p.Switch) *p2p.Switch {
s.AddReactor("CONSENSUS", reactors[i])
s.SetLogger(reactors[i].conS.Logger.With("module", "p2p"))
return s
@ -68,7 +68,7 @@ func startConsensusNet(t *testing.T, css []*ConsensusState, N int) (
// If we started the state machines before everyone was connected,
// we'd block when the cs fires NewBlockEvent and the peers are trying to start their reactors
// TODO: is this still true with new pubsub?
for i := 0; i < N; i++ {
for i := 0; i < n; i++ {
s := reactors[i].conS.GetState()
reactors[i].SwitchToConsensus(s, 0)
}


+ 2
- 4
consensus/replay.go View File

@ -320,11 +320,9 @@ func (h *Handshaker) ReplayBlocks(
}
state.Validators = types.NewValidatorSet(vals)
state.NextValidators = types.NewValidatorSet(vals)
} else {
} else if len(h.genDoc.Validators) == 0 {
// If validator set is not set in genesis and still empty after InitChain, exit.
if len(h.genDoc.Validators) == 0 {
return nil, fmt.Errorf("validator set is nil in genesis and still empty after InitChain")
}
return nil, fmt.Errorf("validator set is nil in genesis and still empty after InitChain")
}
if res.ConsensusParams != nil {


+ 2
- 4
consensus/replay_file.go View File

@ -231,10 +231,8 @@ func (pb *playback) replayConsoleLoop() int {
fmt.Println("back takes an integer argument")
} else if i > pb.count {
fmt.Printf("argument to back must not be larger than the current count (%d)\n", pb.count)
} else {
if err := pb.replayReset(i, newStepSub); err != nil {
pb.cs.Logger.Error("Replay reset error", "err", err)
}
} else if err := pb.replayReset(i, newStepSub); err != nil {
pb.cs.Logger.Error("Replay reset error", "err", err)
}
}


+ 2
- 4
consensus/state.go View File

@ -924,10 +924,8 @@ func (cs *ConsensusState) defaultDecideProposal(height int64, round int) {
}
cs.Logger.Info("Signed proposal", "height", height, "round", round, "proposal", proposal)
cs.Logger.Debug(fmt.Sprintf("Signed proposal block: %v", block))
} else {
if !cs.replayMode {
cs.Logger.Error("enterPropose: Error signing proposal", "height", height, "round", round, "err", err)
}
} else if !cs.replayMode {
cs.Logger.Error("enterPropose: Error signing proposal", "height", height, "round", round, "err", err)
}
}


+ 18
- 18
consensus/state_test.go View File

@ -181,7 +181,7 @@ func TestStateBadProposal(t *testing.T) {
propBlock, _ := cs1.createProposalBlock() //changeProposer(t, cs1, vs2)
// make the second validator the proposer by incrementing round
round = round + 1
round++
incrementRound(vss[1:]...)
// make the block bad by tampering with statehash
@ -374,7 +374,7 @@ func TestStateLockNoPOL(t *testing.T) {
///
round = round + 1 // moving to the next round
round++ // moving to the next round
ensureNewRound(newRoundCh, height, round)
t.Log("#### ONTO ROUND 1")
/*
@ -418,7 +418,7 @@ func TestStateLockNoPOL(t *testing.T) {
// then we enterPrecommitWait and timeout into NewRound
ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds())
round = round + 1 // entering new round
round++ // entering new round
ensureNewRound(newRoundCh, height, round)
t.Log("#### ONTO ROUND 2")
/*
@ -460,7 +460,7 @@ func TestStateLockNoPOL(t *testing.T) {
incrementRound(vs2)
round = round + 1 // entering new round
round++ // entering new round
ensureNewRound(newRoundCh, height, round)
t.Log("#### ONTO ROUND 3")
/*
@ -544,7 +544,7 @@ func TestStateLockPOLRelock(t *testing.T) {
// timeout to new round
ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds())
round = round + 1 // moving to the next round
round++ // moving to the next round
//XXX: this isnt guaranteed to get there before the timeoutPropose ...
if err := cs1.SetProposalAndBlock(prop, propBlock, propBlockParts, "some peer"); err != nil {
t.Fatal(err)
@ -635,7 +635,7 @@ func TestStateLockPOLUnlock(t *testing.T) {
lockedBlockHash := rs.LockedBlock.Hash()
incrementRound(vs2, vs3, vs4)
round = round + 1 // moving to the next round
round++ // moving to the next round
ensureNewRound(newRoundCh, height, round)
t.Log("#### ONTO ROUND 1")
@ -718,7 +718,7 @@ func TestStateLockPOLSafety1(t *testing.T) {
incrementRound(vs2, vs3, vs4)
round = round + 1 // moving to the next round
round++ // moving to the next round
ensureNewRound(newRoundCh, height, round)
//XXX: this isnt guaranteed to get there before the timeoutPropose ...
@ -755,7 +755,7 @@ func TestStateLockPOLSafety1(t *testing.T) {
ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds())
incrementRound(vs2, vs3, vs4)
round = round + 1 // moving to the next round
round++ // moving to the next round
ensureNewRound(newRoundCh, height, round)
@ -821,7 +821,7 @@ func TestStateLockPOLSafety2(t *testing.T) {
incrementRound(vs2, vs3, vs4)
round = round + 1 // moving to the next round
round++ // moving to the next round
t.Log("### ONTO Round 1")
// jump in at round 1
startTestRound(cs1, height, round)
@ -850,7 +850,7 @@ func TestStateLockPOLSafety2(t *testing.T) {
// timeout of precommit wait to new round
ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds())
round = round + 1 // moving to the next round
round++ // moving to the next round
// in round 2 we see the polkad block from round 0
newProp := types.NewProposal(height, round, 0, propBlockID0)
if err := vs3.SignProposal(config.ChainID(), newProp); err != nil {
@ -920,7 +920,7 @@ func TestProposeValidBlock(t *testing.T) {
ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds())
incrementRound(vs2, vs3, vs4)
round = round + 1 // moving to the next round
round++ // moving to the next round
ensureNewRound(newRoundCh, height, round)
@ -945,14 +945,14 @@ func TestProposeValidBlock(t *testing.T) {
signAddVotes(cs1, types.PrecommitType, nil, types.PartSetHeader{}, vs2, vs3, vs4)
round = round + 2 // moving to the next round
round += 2 // moving to the next round
ensureNewRound(newRoundCh, height, round)
t.Log("### ONTO ROUND 3")
ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds())
round = round + 1 // moving to the next round
round++ // moving to the next round
ensureNewRound(newRoundCh, height, round)
@ -1044,7 +1044,7 @@ func TestSetValidBlockOnDelayedProposal(t *testing.T) {
voteCh := subscribeToVoter(cs1, addr)
proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal)
round = round + 1 // move to round in which P0 is not proposer
round++ // move to round in which P0 is not proposer
incrementRound(vs2, vs3, vs4)
startTestRound(cs1, cs1.Height, round)
@ -1123,7 +1123,7 @@ func TestWaitingTimeoutProposeOnNewRound(t *testing.T) {
incrementRound(vss[1:]...)
signAddVotes(cs1, types.PrevoteType, nil, types.PartSetHeader{}, vs2, vs3, vs4)
round = round + 1 // moving to the next round
round++ // moving to the next round
ensureNewRound(newRoundCh, height, round)
rs := cs1.GetRoundState()
@ -1157,7 +1157,7 @@ func TestRoundSkipOnNilPolkaFromHigherRound(t *testing.T) {
incrementRound(vss[1:]...)
signAddVotes(cs1, types.PrecommitType, nil, types.PartSetHeader{}, vs2, vs3, vs4)
round = round + 1 // moving to the next round
round++ // moving to the next round
ensureNewRound(newRoundCh, height, round)
ensurePrecommit(voteCh, height, round)
@ -1165,7 +1165,7 @@ func TestRoundSkipOnNilPolkaFromHigherRound(t *testing.T) {
ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds())
round = round + 1 // moving to the next round
round++ // moving to the next round
ensureNewRound(newRoundCh, height, round)
}
@ -1511,7 +1511,7 @@ func TestStateHalt1(t *testing.T) {
// timeout to new round
ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds())
round = round + 1 // moving to the next round
round++ // moving to the next round
ensureNewRound(newRoundCh, height, round)
rs = cs1.GetRoundState()


+ 2
- 2
crypto/ed25519/ed25519.go View File

@ -54,7 +54,7 @@ func (privKey PrivKeyEd25519) Bytes() []byte {
// incorrect signature.
func (privKey PrivKeyEd25519) Sign(msg []byte) ([]byte, error) {
signatureBytes := ed25519.Sign(privKey[:], msg)
return signatureBytes[:], nil
return signatureBytes, nil
}
// PubKey gets the corresponding public key from the private key.
@ -100,7 +100,7 @@ func GenPrivKey() PrivKeyEd25519 {
// genPrivKey generates a new ed25519 private key using the provided reader.
func genPrivKey(rand io.Reader) PrivKeyEd25519 {
seed := make([]byte, 32)
_, err := io.ReadFull(rand, seed[:])
_, err := io.ReadFull(rand, seed)
if err != nil {
panic(err)
}


+ 2
- 2
crypto/internal/benchmarking/bench.go View File

@ -24,10 +24,10 @@ func (zeroReader) Read(buf []byte) (int, error) {
// BenchmarkKeyGeneration benchmarks the given key generation algorithm using
// a dummy reader.
func BenchmarkKeyGeneration(b *testing.B, GenerateKey func(reader io.Reader) crypto.PrivKey) {
func BenchmarkKeyGeneration(b *testing.B, generateKey func(reader io.Reader) crypto.PrivKey) {
var zero zeroReader
for i := 0; i < b.N; i++ {
GenerateKey(zero)
generateKey(zero)
}
}


+ 1
- 0
crypto/secp256k1/internal/secp256k1/curve.go View File

@ -30,6 +30,7 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// nolint:gocritic
package secp256k1
import (


+ 1
- 1
libs/cli/helper.go View File

@ -14,7 +14,7 @@ import (
func WriteConfigVals(dir string, vals map[string]string) error {
data := ""
for k, v := range vals {
data = data + fmt.Sprintf("%s = \"%s\"\n", k, v)
data += fmt.Sprintf("%s = \"%s\"\n", k, v)
}
cfile := filepath.Join(dir, "config.toml")
return ioutil.WriteFile(cfile, []byte(data), 0666)


+ 3
- 5
libs/common/random_test.go View File

@ -45,11 +45,9 @@ func TestDeterminism(t *testing.T) {
output := testThemAll()
if i == 0 {
firstOutput = output
} else {
if firstOutput != output {
t.Errorf("Run #%d's output was different from first run.\nfirst: %v\nlast: %v",
i, firstOutput, output)
}
} else if firstOutput != output {
t.Errorf("Run #%d's output was different from first run.\nfirst: %v\nlast: %v",
i, firstOutput, output)
}
}
}


+ 4
- 3
libs/common/string.go View File

@ -51,11 +51,12 @@ func IsASCIIText(s string) bool {
func ASCIITrim(s string) string {
r := make([]byte, 0, len(s))
for _, b := range []byte(s) {
if b == 32 {
switch {
case b == 32:
continue // skip space
} else if 32 < b && b <= 126 {
case 32 < b && b <= 126:
r = append(r, b)
} else {
default:
panic(fmt.Sprintf("non-ASCII (non-tab) char 0x%X", b))
}
}


+ 4
- 4
mempool/reactor_test.go View File

@ -42,10 +42,10 @@ func mempoolLogger() log.Logger {
}
// connect N mempool reactors through N switches
func makeAndConnectReactors(config *cfg.Config, N int) []*Reactor {
reactors := make([]*Reactor, N)
func makeAndConnectReactors(config *cfg.Config, n int) []*Reactor {
reactors := make([]*Reactor, n)
logger := mempoolLogger()
for i := 0; i < N; i++ {
for i := 0; i < n; i++ {
app := kvstore.NewKVStoreApplication()
cc := proxy.NewLocalClientCreator(app)
mempool, cleanup := newMempoolWithApp(cc)
@ -55,7 +55,7 @@ func makeAndConnectReactors(config *cfg.Config, N int) []*Reactor {
reactors[i].SetLogger(logger.With("validator", i))
}
p2p.MakeConnectedSwitches(config.P2P, N, func(i int, s *p2p.Switch) *p2p.Switch {
p2p.MakeConnectedSwitches(config.P2P, n, func(i int, s *p2p.Switch) *p2p.Switch {
s.AddReactor("MEMPOOL", reactors[i])
return s


+ 1
- 1
p2p/node_info_test.go View File

@ -19,7 +19,7 @@ func TestNodeInfoValidate(t *testing.T) {
channels[i] = byte(i)
}
dupChannels := make([]byte, 5)
copy(dupChannels[:], channels[:5])
copy(dupChannels, channels[:5])
dupChannels = append(dupChannels, testCh)
nonAscii := "¢§µ"


+ 3
- 3
p2p/pex/addrbook.go View File

@ -178,11 +178,11 @@ func (a *addrBook) OurAddress(addr *p2p.NetAddress) bool {
return ok
}
func (a *addrBook) AddPrivateIDs(IDs []string) {
func (a *addrBook) AddPrivateIDs(ids []string) {
a.mtx.Lock()
defer a.mtx.Unlock()
for _, id := range IDs {
for _, id := range ids {
a.privateIDs[p2p.ID(id)] = struct{}{}
}
}
@ -643,7 +643,7 @@ func (a *addrBook) randomPickAddresses(bucketType byte, num int) []*p2p.NetAddre
}
total := 0
for _, bucket := range buckets {
total = total + len(bucket)
total += len(bucket)
}
addresses := make([]*knownAddress, 0, total)
for _, bucket := range buckets {


+ 4
- 6
rpc/lib/server/handlers.go View File

@ -735,12 +735,10 @@ func (wsc *wsConnection) writeRoutine() {
jsonBytes, err := json.MarshalIndent(msg, "", " ")
if err != nil {
wsc.Logger.Error("Failed to marshal RPCResponse to JSON", "err", err)
} else {
if err = wsc.writeMessageWithDeadline(websocket.TextMessage, jsonBytes); err != nil {
wsc.Logger.Error("Failed to write response", "err", err)
wsc.Stop()
return
}
} else if err = wsc.writeMessageWithDeadline(websocket.TextMessage, jsonBytes); err != nil {
wsc.Logger.Error("Failed to write response", "err", err)
wsc.Stop()
return
}
case <-wsc.Quit():
return


+ 9
- 9
state/state_test.go View File

@ -440,13 +440,13 @@ func TestProposerPriorityDoesNotGetResetToZero(t *testing.T) {
// 3. Center - with avg, resulting val2:-61, val1:62
avg := big.NewInt(0).Add(big.NewInt(wantVal1Prio), big.NewInt(wantVal2Prio))
avg.Div(avg, big.NewInt(2))
wantVal2Prio = wantVal2Prio - avg.Int64() // -61
wantVal1Prio = wantVal1Prio - avg.Int64() // 62
wantVal2Prio -= avg.Int64() // -61
wantVal1Prio -= avg.Int64() // 62
// 4. Steps from IncrementProposerPriority
wantVal1Prio = wantVal1Prio + val1VotingPower // 72
wantVal2Prio = wantVal2Prio + val2VotingPower // 39
wantVal1Prio = wantVal1Prio - totalPowerAfter // -38 as val1 is proposer
wantVal1Prio += val1VotingPower // 72
wantVal2Prio += val2VotingPower // 39
wantVal1Prio -= totalPowerAfter // -38 as val1 is proposer
assert.Equal(t, wantVal1Prio, updatedVal1.ProposerPriority)
assert.Equal(t, wantVal2Prio, addedVal2.ProposerPriority)
@ -563,9 +563,9 @@ func TestProposerPriorityProposerAlternates(t *testing.T) {
expectedVal2Prio := v2PrioWhenAddedVal2 - avg.Int64() // -11
expectedVal1Prio := oldVal1.ProposerPriority - avg.Int64() // 11
// 4. Increment
expectedVal2Prio = expectedVal2Prio + val2VotingPower // -11 + 10 = -1
expectedVal1Prio = expectedVal1Prio + val1VotingPower // 11 + 10 == 21
expectedVal1Prio = expectedVal1Prio - totalPower // 1, val1 proposer
expectedVal2Prio += val2VotingPower // -11 + 10 = -1
expectedVal1Prio += val1VotingPower // 11 + 10 == 21
expectedVal1Prio -= totalPower // 1, val1 proposer
assert.EqualValues(t, expectedVal1Prio, updatedVal1.ProposerPriority)
assert.EqualValues(t, expectedVal2Prio, updatedVal2.ProposerPriority, "unexpected proposer priority for validator: %v", updatedVal2)
@ -589,7 +589,7 @@ func TestProposerPriorityProposerAlternates(t *testing.T) {
// Increment
expectedVal2Prio2 := expectedVal2Prio + val2VotingPower // -1 + 10 = 9
expectedVal1Prio2 := expectedVal1Prio + val1VotingPower // 1 + 10 == 11
expectedVal1Prio2 = expectedVal1Prio2 - totalPower // -9, val1 proposer
expectedVal1Prio2 -= totalPower // -9, val1 proposer
assert.EqualValues(t, expectedVal1Prio2, updatedVal1.ProposerPriority, "unexpected proposer priority for validator: %v", updatedVal2)
assert.EqualValues(t, expectedVal2Prio2, updatedVal2.ProposerPriority, "unexpected proposer priority for validator: %v", updatedVal2)


+ 2
- 4
types/genesis.go View File

@ -72,10 +72,8 @@ func (genDoc *GenesisDoc) ValidateAndComplete() error {
if genDoc.ConsensusParams == nil {
genDoc.ConsensusParams = DefaultConsensusParams()
} else {
if err := genDoc.ConsensusParams.Validate(); err != nil {
return err
}
} else if err := genDoc.ConsensusParams.Validate(); err != nil {
return err
}
for i, v := range genDoc.Validators {


+ 2
- 2
types/validator_set.go View File

@ -121,7 +121,7 @@ func (vals *ValidatorSet) RescalePriorities(diffMax int64) {
ratio := (diff + diffMax - 1) / diffMax
if diff > diffMax {
for _, val := range vals.Validators {
val.ProposerPriority = val.ProposerPriority / ratio
val.ProposerPriority /= ratio
}
}
}
@ -525,7 +525,7 @@ func (vals *ValidatorSet) applyRemovals(deletes []*Validator) {
// The 'allowDeletes' flag is set to false by NewValidatorSet() and to true by UpdateWithChangeSet().
func (vals *ValidatorSet) updateWithChangeSet(changes []*Validator, allowDeletes bool) error {
if len(changes) <= 0 {
if len(changes) == 0 {
return nil
}


Loading…
Cancel
Save