From 2756be5a5930071a1e03aeea33f0b820066648ea Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Fri, 10 Aug 2018 00:25:57 -0500 Subject: [PATCH] libs: Remove usage of custom Fmt, in favor of fmt.Sprintf (#2199) * libs: Remove usage of custom Fmt, in favor of fmt.Sprintf Closes #2193 * Fix bug that was masked by custom Fmt! --- CHANGELOG_PENDING.md | 1 + Gopkg.lock | 5 +- abci/example/counter/counter.go | 11 ++- abci/example/kvstore/kvstore_test.go | 5 +- abci/example/kvstore/persistent_kvstore.go | 3 +- benchmarks/simu/counter.go | 2 +- blockchain/pool.go | 6 +- blockchain/reactor.go | 14 ++-- blockchain/store.go | 8 +-- cmd/tendermint/commands/gen_node_key.go | 2 +- cmd/tendermint/commands/init.go | 5 +- .../commands/reset_priv_validator.go | 2 +- cmd/tendermint/commands/testnet.go | 12 ++-- consensus/byzantine_test.go | 7 +- consensus/common_test.go | 4 +- consensus/mempool_test.go | 7 +- consensus/reactor.go | 16 ++--- consensus/reactor_test.go | 2 +- consensus/replay.go | 4 +- consensus/replay_file.go | 12 ++-- consensus/replay_test.go | 14 ++-- consensus/state.go | 68 +++++++++---------- consensus/state_test.go | 7 +- consensus/types/height_vote_set.go | 6 +- consensus/types/height_vote_set_test.go | 4 +- consensus/types/peer_round_state.go | 2 +- consensus/types/round_state.go | 2 +- consensus/version.go | 6 +- consensus/wal.go | 6 +- consensus/wal_generator.go | 8 +-- consensus/wal_test.go | 8 +-- crypto/merkle/simple_tree_test.go | 3 +- crypto/xsalsa20symmetric/symmetric.go | 5 +- docs/app-dev/app-development.md | 2 +- evidence/pool_test.go | 2 +- evidence/store.go | 2 +- evidence/store_test.go | 2 +- libs/autofile/group.go | 4 +- libs/common/bit_array_test.go | 3 +- libs/common/colors.go | 2 +- libs/common/errors.go | 14 ++-- libs/common/os.go | 4 +- libs/common/random.go | 2 +- libs/common/service.go | 12 ++-- libs/common/string.go | 8 --- libs/db/backend_test.go | 6 +- libs/db/c_level_db_test.go | 4 +- libs/db/go_level_db_test.go | 2 +- lite/provider.go | 2 +- lite/provider_test.go | 4 +- lite/proxy/verifier.go | 4 +- mempool/mempool.go | 2 +- mempool/mempool_test.go | 3 +- node/node.go | 18 ++--- p2p/base_reactor.go | 2 +- p2p/conn/connection.go | 6 +- p2p/listener.go | 2 +- p2p/netaddress.go | 2 +- p2p/peer.go | 2 +- p2p/peer_set_test.go | 3 +- p2p/pex/addrbook.go | 15 ++-- p2p/pex/file.go | 5 +- p2p/test_util.go | 4 +- p2p/trust/store.go | 3 +- p2p/upnp/probe.go | 25 ++++--- privval/priv_validator.go | 4 +- proxy/app_conn_test.go | 9 +-- rpc/client/event_test.go | 2 +- rpc/client/httpclient.go | 2 +- rpc/client/interface.go | 2 +- rpc/client/mock/abci.go | 2 +- rpc/client/mock/abci_test.go | 2 +- rpc/client/mock/client.go | 2 +- rpc/client/mock/status_test.go | 2 +- rpc/core/mempool.go | 2 +- rpc/core/pipe.go | 4 +- rpc/lib/client/ws_client.go | 2 +- rpc/lib/server/handlers_test.go | 2 +- rpc/lib/server/http_server.go | 2 +- rpc/lib/test/main.go | 2 +- state/errors.go | 20 +++--- state/state_test.go | 8 +-- state/store.go | 14 ++-- state/validation.go | 2 +- types/genesis.go | 3 +- types/proto3_test.go | 8 +-- types/protobuf_test.go | 6 +- types/validator_set_test.go | 5 +- 88 files changed, 270 insertions(+), 275 deletions(-) diff --git a/CHANGELOG_PENDING.md b/CHANGELOG_PENDING.md index 84848754c..2939381b2 100644 --- a/CHANGELOG_PENDING.md +++ b/CHANGELOG_PENDING.md @@ -9,6 +9,7 @@ BREAKING CHANGES: top-level - [abci] Added address of the original proposer of the block to Header. - [abci] Change ABCI Header to match Tendermint exactly +- [libs] Remove cmn.Fmt, in favor of fmt.Sprintf FEATURES: diff --git a/Gopkg.lock b/Gopkg.lock index 36d6f0df9..ff5cbcfe1 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -244,7 +244,7 @@ [[projects]] branch = "master" - digest = "1:63b68062b8968092eb86bedc4e68894bd096ea6b24920faca8b9dcf451f54bb5" + digest = "1:dad2e5a2153ee7a6c9ab8fc13673a16ee4fb64434a7da980965a3741b0c981a3" name = "github.com/prometheus/common" packages = [ "expfmt", @@ -426,7 +426,7 @@ [[projects]] branch = "master" - digest = "1:bb0fe59917bdd5b89f49b9a8b26e5f465e325d9223b3a8e32254314bdf51e0f1" + digest = "1:70656e26ab4a96e683a21d677630edb5239a3d60b2d54bdc861c808ab5aa42c7" name = "golang.org/x/sys" packages = [ "cpu", @@ -527,6 +527,7 @@ "github.com/gogo/protobuf/gogoproto", "github.com/gogo/protobuf/jsonpb", "github.com/gogo/protobuf/proto", + "github.com/gogo/protobuf/types", "github.com/golang/protobuf/proto", "github.com/golang/protobuf/ptypes/timestamp", "github.com/gorilla/websocket", diff --git a/abci/example/counter/counter.go b/abci/example/counter/counter.go index 857e82baf..a77e7821f 100644 --- a/abci/example/counter/counter.go +++ b/abci/example/counter/counter.go @@ -6,7 +6,6 @@ import ( "github.com/tendermint/tendermint/abci/example/code" "github.com/tendermint/tendermint/abci/types" - cmn "github.com/tendermint/tendermint/libs/common" ) type CounterApplication struct { @@ -22,7 +21,7 @@ func NewCounterApplication(serial bool) *CounterApplication { } func (app *CounterApplication) Info(req types.RequestInfo) types.ResponseInfo { - return types.ResponseInfo{Data: cmn.Fmt("{\"hashes\":%v,\"txs\":%v}", app.hashCount, app.txCount)} + return types.ResponseInfo{Data: fmt.Sprintf("{\"hashes\":%v,\"txs\":%v}", app.hashCount, app.txCount)} } func (app *CounterApplication) SetOption(req types.RequestSetOption) types.ResponseSetOption { @@ -34,7 +33,7 @@ func (app *CounterApplication) SetOption(req types.RequestSetOption) types.Respo TODO Panic and have the ABCI server pass an exception. The client can call SetOptionSync() and get an `error`. return types.ResponseSetOption{ - Error: cmn.Fmt("Unknown key (%s) or value (%s)", key, value), + Error: fmt.Sprintf("Unknown key (%s) or value (%s)", key, value), } */ return types.ResponseSetOption{} @@ -95,10 +94,10 @@ func (app *CounterApplication) Commit() (resp types.ResponseCommit) { func (app *CounterApplication) Query(reqQuery types.RequestQuery) types.ResponseQuery { switch reqQuery.Path { case "hash": - return types.ResponseQuery{Value: []byte(cmn.Fmt("%v", app.hashCount))} + return types.ResponseQuery{Value: []byte(fmt.Sprintf("%v", app.hashCount))} case "tx": - return types.ResponseQuery{Value: []byte(cmn.Fmt("%v", app.txCount))} + return types.ResponseQuery{Value: []byte(fmt.Sprintf("%v", app.txCount))} default: - return types.ResponseQuery{Log: cmn.Fmt("Invalid query path. Expected hash or tx, got %v", reqQuery.Path)} + return types.ResponseQuery{Log: fmt.Sprintf("Invalid query path. Expected hash or tx, got %v", reqQuery.Path)} } } diff --git a/abci/example/kvstore/kvstore_test.go b/abci/example/kvstore/kvstore_test.go index 6ef5a08f9..33e67aaad 100644 --- a/abci/example/kvstore/kvstore_test.go +++ b/abci/example/kvstore/kvstore_test.go @@ -2,6 +2,7 @@ package kvstore import ( "bytes" + "fmt" "io/ioutil" "sort" "testing" @@ -207,7 +208,7 @@ func valsEqual(t *testing.T, vals1, vals2 []types.Validator) { func makeSocketClientServer(app types.Application, name string) (abcicli.Client, cmn.Service, error) { // Start the listener - socket := cmn.Fmt("unix://%s.sock", name) + socket := fmt.Sprintf("unix://%s.sock", name) logger := log.TestingLogger() server := abciserver.NewSocketServer(socket, app) @@ -229,7 +230,7 @@ func makeSocketClientServer(app types.Application, name string) (abcicli.Client, func makeGRPCClientServer(app types.Application, name string) (abcicli.Client, cmn.Service, error) { // Start the listener - socket := cmn.Fmt("unix://%s.sock", name) + socket := fmt.Sprintf("unix://%s.sock", name) logger := log.TestingLogger() gapp := types.NewGRPCApplication(app) diff --git a/abci/example/kvstore/persistent_kvstore.go b/abci/example/kvstore/persistent_kvstore.go index 12ccbab78..b8a2299a6 100644 --- a/abci/example/kvstore/persistent_kvstore.go +++ b/abci/example/kvstore/persistent_kvstore.go @@ -9,7 +9,6 @@ import ( "github.com/tendermint/tendermint/abci/example/code" "github.com/tendermint/tendermint/abci/types" - cmn "github.com/tendermint/tendermint/libs/common" dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/libs/log" ) @@ -130,7 +129,7 @@ func (app *PersistentKVStoreApplication) Validators() (validators []types.Valida } func MakeValSetChangeTx(pubkey types.PubKey, power int64) []byte { - return []byte(cmn.Fmt("val:%X/%d", pubkey.Data, power)) + return []byte(fmt.Sprintf("val:%X/%d", pubkey.Data, power)) } func isValidatorTx(tx []byte) bool { diff --git a/benchmarks/simu/counter.go b/benchmarks/simu/counter.go index b7d2c4d63..c24eddf8a 100644 --- a/benchmarks/simu/counter.go +++ b/benchmarks/simu/counter.go @@ -6,8 +6,8 @@ import ( "fmt" "time" - rpcclient "github.com/tendermint/tendermint/rpc/lib/client" cmn "github.com/tendermint/tendermint/libs/common" + rpcclient "github.com/tendermint/tendermint/rpc/lib/client" ) func main() { diff --git a/blockchain/pool.go b/blockchain/pool.go index a881c7cb7..c7864a646 100644 --- a/blockchain/pool.go +++ b/blockchain/pool.go @@ -365,10 +365,10 @@ func (pool *BlockPool) debug() string { nextHeight := pool.height + pool.requestersLen() for h := pool.height; h < nextHeight; h++ { if pool.requesters[h] == nil { - str += cmn.Fmt("H(%v):X ", h) + str += fmt.Sprintf("H(%v):X ", h) } else { - str += cmn.Fmt("H(%v):", h) - str += cmn.Fmt("B?(%v) ", pool.requesters[h].block != nil) + str += fmt.Sprintf("H(%v):", h) + str += fmt.Sprintf("B?(%v) ", pool.requesters[h].block != nil) } } return str diff --git a/blockchain/reactor.go b/blockchain/reactor.go index f00df50c3..d480eacaf 100644 --- a/blockchain/reactor.go +++ b/blockchain/reactor.go @@ -201,7 +201,7 @@ func (bcR *BlockchainReactor) Receive(chID byte, src p2p.Peer, msgBytes []byte) // Got a peer status. Unverified. bcR.pool.SetPeerHeight(src.ID(), msg.Height) default: - bcR.Logger.Error(cmn.Fmt("Unknown message type %v", reflect.TypeOf(msg))) + bcR.Logger.Error(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg))) } } @@ -321,7 +321,7 @@ FOR_LOOP: state, err = bcR.blockExec.ApplyBlock(state, firstID, first) if err != nil { // TODO This is bad, are we zombie? - cmn.PanicQ(cmn.Fmt("Failed to process committed block (%d:%X): %v", + cmn.PanicQ(fmt.Sprintf("Failed to process committed block (%d:%X): %v", first.Height, first.Hash(), err)) } blocksSynced++ @@ -378,7 +378,7 @@ type bcBlockRequestMessage struct { } func (m *bcBlockRequestMessage) String() string { - return cmn.Fmt("[bcBlockRequestMessage %v]", m.Height) + return fmt.Sprintf("[bcBlockRequestMessage %v]", m.Height) } type bcNoBlockResponseMessage struct { @@ -386,7 +386,7 @@ type bcNoBlockResponseMessage struct { } func (brm *bcNoBlockResponseMessage) String() string { - return cmn.Fmt("[bcNoBlockResponseMessage %d]", brm.Height) + return fmt.Sprintf("[bcNoBlockResponseMessage %d]", brm.Height) } //------------------------------------- @@ -396,7 +396,7 @@ type bcBlockResponseMessage struct { } func (m *bcBlockResponseMessage) String() string { - return cmn.Fmt("[bcBlockResponseMessage %v]", m.Block.Height) + return fmt.Sprintf("[bcBlockResponseMessage %v]", m.Block.Height) } //------------------------------------- @@ -406,7 +406,7 @@ type bcStatusRequestMessage struct { } func (m *bcStatusRequestMessage) String() string { - return cmn.Fmt("[bcStatusRequestMessage %v]", m.Height) + return fmt.Sprintf("[bcStatusRequestMessage %v]", m.Height) } //------------------------------------- @@ -416,5 +416,5 @@ type bcStatusResponseMessage struct { } func (m *bcStatusResponseMessage) String() string { - return cmn.Fmt("[bcStatusResponseMessage %v]", m.Height) + return fmt.Sprintf("[bcStatusResponseMessage %v]", m.Height) } diff --git a/blockchain/store.go b/blockchain/store.go index f02d4facb..fa9ee5189 100644 --- a/blockchain/store.go +++ b/blockchain/store.go @@ -148,10 +148,10 @@ func (bs *BlockStore) SaveBlock(block *types.Block, blockParts *types.PartSet, s } height := block.Height if g, w := height, bs.Height()+1; g != w { - cmn.PanicSanity(cmn.Fmt("BlockStore can only save contiguous blocks. Wanted %v, got %v", w, g)) + cmn.PanicSanity(fmt.Sprintf("BlockStore can only save contiguous blocks. Wanted %v, got %v", w, g)) } if !blockParts.IsComplete() { - cmn.PanicSanity(cmn.Fmt("BlockStore can only save complete block part sets")) + cmn.PanicSanity(fmt.Sprintf("BlockStore can only save complete block part sets")) } // Save block meta @@ -188,7 +188,7 @@ func (bs *BlockStore) SaveBlock(block *types.Block, blockParts *types.PartSet, s func (bs *BlockStore) saveBlockPart(height int64, index int, part *types.Part) { if height != bs.Height()+1 { - cmn.PanicSanity(cmn.Fmt("BlockStore can only save contiguous blocks. Wanted %v, got %v", bs.Height()+1, height)) + cmn.PanicSanity(fmt.Sprintf("BlockStore can only save contiguous blocks. Wanted %v, got %v", bs.Height()+1, height)) } partBytes := cdc.MustMarshalBinaryBare(part) bs.db.Set(calcBlockPartKey(height, index), partBytes) @@ -224,7 +224,7 @@ type BlockStoreStateJSON struct { func (bsj BlockStoreStateJSON) Save(db dbm.DB) { bytes, err := cdc.MarshalJSON(bsj) if err != nil { - cmn.PanicSanity(cmn.Fmt("Could not marshal state bytes: %v", err)) + cmn.PanicSanity(fmt.Sprintf("Could not marshal state bytes: %v", err)) } db.SetSync(blockStoreKey, bytes) } diff --git a/cmd/tendermint/commands/gen_node_key.go b/cmd/tendermint/commands/gen_node_key.go index 7aedcd0dc..38dc5c66d 100644 --- a/cmd/tendermint/commands/gen_node_key.go +++ b/cmd/tendermint/commands/gen_node_key.go @@ -5,8 +5,8 @@ import ( "github.com/spf13/cobra" - "github.com/tendermint/tendermint/p2p" cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/p2p" ) // GenNodeKeyCmd allows the generation of a node key. It prints node's ID to diff --git a/cmd/tendermint/commands/init.go b/cmd/tendermint/commands/init.go index a44c73ebf..d39a27dac 100644 --- a/cmd/tendermint/commands/init.go +++ b/cmd/tendermint/commands/init.go @@ -1,15 +1,16 @@ package commands import ( + "fmt" "time" "github.com/spf13/cobra" cfg "github.com/tendermint/tendermint/config" + cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/privval" "github.com/tendermint/tendermint/types" - cmn "github.com/tendermint/tendermint/libs/common" ) // InitFilesCmd initialises a fresh Tendermint Core instance. @@ -52,7 +53,7 @@ func initFilesWithConfig(config *cfg.Config) error { logger.Info("Found genesis file", "path", genFile) } else { genDoc := types.GenesisDoc{ - ChainID: cmn.Fmt("test-chain-%v", cmn.RandStr(6)), + ChainID: fmt.Sprintf("test-chain-%v", cmn.RandStr(6)), GenesisTime: time.Now(), ConsensusParams: types.DefaultConsensusParams(), } diff --git a/cmd/tendermint/commands/reset_priv_validator.go b/cmd/tendermint/commands/reset_priv_validator.go index ef0ba3019..53d347129 100644 --- a/cmd/tendermint/commands/reset_priv_validator.go +++ b/cmd/tendermint/commands/reset_priv_validator.go @@ -5,8 +5,8 @@ import ( "github.com/spf13/cobra" - "github.com/tendermint/tendermint/privval" "github.com/tendermint/tendermint/libs/log" + "github.com/tendermint/tendermint/privval" ) // ResetAllCmd removes the database of this Tendermint core diff --git a/cmd/tendermint/commands/testnet.go b/cmd/tendermint/commands/testnet.go index f7639fb27..69fbe1f69 100644 --- a/cmd/tendermint/commands/testnet.go +++ b/cmd/tendermint/commands/testnet.go @@ -11,10 +11,10 @@ import ( "github.com/spf13/cobra" cfg "github.com/tendermint/tendermint/config" + cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/privval" "github.com/tendermint/tendermint/types" - cmn "github.com/tendermint/tendermint/libs/common" ) var ( @@ -76,7 +76,7 @@ func testnetFiles(cmd *cobra.Command, args []string) error { genVals := make([]types.GenesisValidator, nValidators) for i := 0; i < nValidators; i++ { - nodeDirName := cmn.Fmt("%s%d", nodeDirPrefix, i) + nodeDirName := fmt.Sprintf("%s%d", nodeDirPrefix, i) nodeDir := filepath.Join(outputDir, nodeDirName) config.SetRoot(nodeDir) @@ -98,7 +98,7 @@ func testnetFiles(cmd *cobra.Command, args []string) error { } for i := 0; i < nNonValidators; i++ { - nodeDir := filepath.Join(outputDir, cmn.Fmt("%s%d", nodeDirPrefix, i+nValidators)) + nodeDir := filepath.Join(outputDir, fmt.Sprintf("%s%d", nodeDirPrefix, i+nValidators)) config.SetRoot(nodeDir) err := os.MkdirAll(filepath.Join(nodeDir, "config"), nodeDirPerm) @@ -119,7 +119,7 @@ func testnetFiles(cmd *cobra.Command, args []string) error { // Write genesis file. for i := 0; i < nValidators+nNonValidators; i++ { - nodeDir := filepath.Join(outputDir, cmn.Fmt("%s%d", nodeDirPrefix, i)) + nodeDir := filepath.Join(outputDir, fmt.Sprintf("%s%d", nodeDirPrefix, i)) if err := genDoc.SaveAs(filepath.Join(nodeDir, config.BaseConfig.Genesis)); err != nil { _ = os.RemoveAll(outputDir) return err @@ -159,7 +159,7 @@ func hostnameOrIP(i int) string { func populatePersistentPeersInConfigAndWriteIt(config *cfg.Config) error { persistentPeers := make([]string, nValidators+nNonValidators) for i := 0; i < nValidators+nNonValidators; i++ { - nodeDir := filepath.Join(outputDir, cmn.Fmt("%s%d", nodeDirPrefix, i)) + nodeDir := filepath.Join(outputDir, fmt.Sprintf("%s%d", nodeDirPrefix, i)) config.SetRoot(nodeDir) nodeKey, err := p2p.LoadNodeKey(config.NodeKeyFile()) if err != nil { @@ -170,7 +170,7 @@ func populatePersistentPeersInConfigAndWriteIt(config *cfg.Config) error { persistentPeersList := strings.Join(persistentPeers, ",") for i := 0; i < nValidators+nNonValidators; i++ { - nodeDir := filepath.Join(outputDir, cmn.Fmt("%s%d", nodeDirPrefix, i)) + nodeDir := filepath.Join(outputDir, fmt.Sprintf("%s%d", nodeDirPrefix, i)) config.SetRoot(nodeDir) config.P2P.PersistentPeers = persistentPeersList config.P2P.AddrBookStrict = false diff --git a/consensus/byzantine_test.go b/consensus/byzantine_test.go index 5360a92c9..0aba77432 100644 --- a/consensus/byzantine_test.go +++ b/consensus/byzantine_test.go @@ -2,14 +2,15 @@ package consensus import ( "context" + "fmt" "sync" "testing" "time" "github.com/stretchr/testify/require" + cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/types" - cmn "github.com/tendermint/tendermint/libs/common" ) func init() { @@ -156,8 +157,8 @@ func TestByzantine(t *testing.T) { case <-done: case <-tick.C: for i, reactor := range reactors { - t.Log(cmn.Fmt("Consensus Reactor %v", i)) - t.Log(cmn.Fmt("%v", reactor)) + t.Log(fmt.Sprintf("Consensus Reactor %v", i)) + t.Log(fmt.Sprintf("%v", reactor)) } t.Fatalf("Timed out waiting for all validators to commit first block") } diff --git a/consensus/common_test.go b/consensus/common_test.go index f4855992d..818946184 100644 --- a/consensus/common_test.go +++ b/consensus/common_test.go @@ -348,7 +348,7 @@ func randConsensusNet(nValidators int, testName string, tickerFunc func() Timeou for i := 0; i < nValidators; i++ { stateDB := dbm.NewMemDB() // each state needs its own db state, _ := sm.LoadStateFromDBOrGenesisDoc(stateDB, genDoc) - thisConfig := ResetConfig(cmn.Fmt("%s_%d", testName, i)) + thisConfig := ResetConfig(fmt.Sprintf("%s_%d", testName, i)) for _, opt := range configOpts { opt(thisConfig) } @@ -372,7 +372,7 @@ func randConsensusNetWithPeers(nValidators, nPeers int, testName string, tickerF for i := 0; i < nPeers; i++ { stateDB := dbm.NewMemDB() // each state needs its own db state, _ := sm.LoadStateFromDBOrGenesisDoc(stateDB, genDoc) - thisConfig := ResetConfig(cmn.Fmt("%s_%d", testName, i)) + thisConfig := ResetConfig(fmt.Sprintf("%s_%d", testName, i)) ensureDir(path.Dir(thisConfig.Consensus.WalFile()), 0700) // dir for wal var privVal types.PrivValidator if i < nValidators { diff --git a/consensus/mempool_test.go b/consensus/mempool_test.go index a811de731..c905f50bb 100644 --- a/consensus/mempool_test.go +++ b/consensus/mempool_test.go @@ -10,7 +10,6 @@ import ( "github.com/tendermint/tendermint/abci/example/code" abci "github.com/tendermint/tendermint/abci/types" - cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/types" ) @@ -89,7 +88,7 @@ func deliverTxsRange(cs *ConsensusState, start, end int) { binary.BigEndian.PutUint64(txBytes, uint64(i)) err := cs.mempool.CheckTx(txBytes, nil) if err != nil { - panic(cmn.Fmt("Error after CheckTx: %v", err)) + panic(fmt.Sprintf("Error after CheckTx: %v", err)) } } } @@ -126,7 +125,7 @@ func TestMempoolRmBadTx(t *testing.T) { binary.BigEndian.PutUint64(txBytes, uint64(0)) resDeliver := app.DeliverTx(txBytes) - assert.False(t, resDeliver.IsErr(), cmn.Fmt("expected no error. got %v", resDeliver)) + assert.False(t, resDeliver.IsErr(), fmt.Sprintf("expected no error. got %v", resDeliver)) resCommit := app.Commit() assert.True(t, len(resCommit.Data) > 0) @@ -190,7 +189,7 @@ func NewCounterApplication() *CounterApplication { } func (app *CounterApplication) Info(req abci.RequestInfo) abci.ResponseInfo { - return abci.ResponseInfo{Data: cmn.Fmt("txs:%v", app.txCount)} + return abci.ResponseInfo{Data: fmt.Sprintf("txs:%v", app.txCount)} } func (app *CounterApplication) DeliverTx(tx []byte) abci.ResponseDeliverTx { diff --git a/consensus/reactor.go b/consensus/reactor.go index 58ff42ae2..885571854 100644 --- a/consensus/reactor.go +++ b/consensus/reactor.go @@ -241,7 +241,7 @@ func (conR *ConsensusReactor) Receive(chID byte, src p2p.Peer, msgBytes []byte) "height", hb.Height, "round", hb.Round, "sequence", hb.Sequence, "valIdx", hb.ValidatorIndex, "valAddr", hb.ValidatorAddress) default: - conR.Logger.Error(cmn.Fmt("Unknown message type %v", reflect.TypeOf(msg))) + conR.Logger.Error(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg))) } case DataChannel: @@ -262,7 +262,7 @@ func (conR *ConsensusReactor) Receive(chID byte, src p2p.Peer, msgBytes []byte) } conR.conS.peerMsgQueue <- msgInfo{msg, src.ID()} default: - conR.Logger.Error(cmn.Fmt("Unknown message type %v", reflect.TypeOf(msg))) + conR.Logger.Error(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg))) } case VoteChannel: @@ -287,7 +287,7 @@ func (conR *ConsensusReactor) Receive(chID byte, src p2p.Peer, msgBytes []byte) default: // don't punish (leave room for soft upgrades) - conR.Logger.Error(cmn.Fmt("Unknown message type %v", reflect.TypeOf(msg))) + conR.Logger.Error(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg))) } case VoteSetBitsChannel: @@ -319,11 +319,11 @@ func (conR *ConsensusReactor) Receive(chID byte, src p2p.Peer, msgBytes []byte) } default: // don't punish (leave room for soft upgrades) - conR.Logger.Error(cmn.Fmt("Unknown message type %v", reflect.TypeOf(msg))) + conR.Logger.Error(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg))) } default: - conR.Logger.Error(cmn.Fmt("Unknown chId %X", chID)) + conR.Logger.Error(fmt.Sprintf("Unknown chId %X", chID)) } if err != nil { @@ -482,7 +482,7 @@ OUTER_LOOP: if prs.ProposalBlockParts == nil { blockMeta := conR.conS.blockStore.LoadBlockMeta(prs.Height) if blockMeta == nil { - cmn.PanicCrisis(cmn.Fmt("Failed to load block %d when blockStore is at %d", + cmn.PanicCrisis(fmt.Sprintf("Failed to load block %d when blockStore is at %d", prs.Height, conR.conS.blockStore.Height())) } ps.InitProposalBlockParts(blockMeta.BlockID.PartsHeader) @@ -1034,7 +1034,7 @@ func (ps *PeerState) ensureCatchupCommitRound(height int64, round int, numValida NOTE: This is wrong, 'round' could change. e.g. if orig round is not the same as block LastCommit round. if ps.CatchupCommitRound != -1 && ps.CatchupCommitRound != round { - cmn.PanicSanity(cmn.Fmt("Conflicting CatchupCommitRound. Height: %v, Orig: %v, New: %v", height, ps.CatchupCommitRound, round)) + cmn.PanicSanity(fmt.Sprintf("Conflicting CatchupCommitRound. Height: %v, Orig: %v, New: %v", height, ps.CatchupCommitRound, round)) } */ if ps.PRS.CatchupCommitRound == round { @@ -1138,7 +1138,7 @@ func (ps *PeerState) SetHasVote(vote *types.Vote) { } func (ps *PeerState) setHasVote(height int64, round int, type_ byte, index int) { - logger := ps.logger.With("peerH/R", cmn.Fmt("%d/%d", ps.PRS.Height, ps.PRS.Round), "H/R", cmn.Fmt("%d/%d", height, round)) + logger := ps.logger.With("peerH/R", fmt.Sprintf("%d/%d", ps.PRS.Height, ps.PRS.Round), "H/R", fmt.Sprintf("%d/%d", height, round)) logger.Debug("setHasVote", "type", type_, "index", index) // NOTE: some may be nil BitArrays -> no side effects. diff --git a/consensus/reactor_test.go b/consensus/reactor_test.go index a3d284d98..35502fb1c 100644 --- a/consensus/reactor_test.go +++ b/consensus/reactor_test.go @@ -115,7 +115,7 @@ func TestReactorWithEvidence(t *testing.T) { for i := 0; i < nValidators; i++ { stateDB := dbm.NewMemDB() // each state needs its own db state, _ := sm.LoadStateFromDBOrGenesisDoc(stateDB, genDoc) - thisConfig := ResetConfig(cmn.Fmt("%s_%d", testName, i)) + thisConfig := ResetConfig(fmt.Sprintf("%s_%d", testName, i)) ensureDir(path.Dir(thisConfig.Consensus.WalFile()), 0700) // dir for wal app := appFunc() vals := types.TM2PB.Validators(state.Validators) diff --git a/consensus/replay.go b/consensus/replay.go index 25859a768..cff8344be 100644 --- a/consensus/replay.go +++ b/consensus/replay.go @@ -304,11 +304,11 @@ func (h *Handshaker) ReplayBlocks(state sm.State, appHash []byte, appBlockHeight } else if storeBlockHeight < stateBlockHeight { // the state should never be ahead of the store (this is under tendermint's control) - cmn.PanicSanity(cmn.Fmt("StateBlockHeight (%d) > StoreBlockHeight (%d)", stateBlockHeight, storeBlockHeight)) + cmn.PanicSanity(fmt.Sprintf("StateBlockHeight (%d) > StoreBlockHeight (%d)", stateBlockHeight, storeBlockHeight)) } else if storeBlockHeight > stateBlockHeight+1 { // store should be at most one ahead of the state (this is under tendermint's control) - cmn.PanicSanity(cmn.Fmt("StoreBlockHeight (%d) > StateBlockHeight + 1 (%d)", storeBlockHeight, stateBlockHeight+1)) + cmn.PanicSanity(fmt.Sprintf("StoreBlockHeight (%d) > StateBlockHeight + 1 (%d)", storeBlockHeight, stateBlockHeight+1)) } var err error diff --git a/consensus/replay_file.go b/consensus/replay_file.go index 0c0b0dcb1..e4b9f0196 100644 --- a/consensus/replay_file.go +++ b/consensus/replay_file.go @@ -13,12 +13,12 @@ import ( bc "github.com/tendermint/tendermint/blockchain" cfg "github.com/tendermint/tendermint/config" - "github.com/tendermint/tendermint/proxy" - sm "github.com/tendermint/tendermint/state" - "github.com/tendermint/tendermint/types" cmn "github.com/tendermint/tendermint/libs/common" dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/libs/log" + "github.com/tendermint/tendermint/proxy" + sm "github.com/tendermint/tendermint/state" + "github.com/tendermint/tendermint/types" ) const ( @@ -34,7 +34,7 @@ func RunReplayFile(config cfg.BaseConfig, csConfig *cfg.ConsensusConfig, console consensusState := newConsensusStateForReplay(config, csConfig) if err := consensusState.ReplayFile(csConfig.WalFile(), console); err != nil { - cmn.Exit(cmn.Fmt("Error during consensus replay: %v", err)) + cmn.Exit(fmt.Sprintf("Error during consensus replay: %v", err)) } } @@ -302,12 +302,12 @@ func newConsensusStateForReplay(config cfg.BaseConfig, csConfig *cfg.ConsensusCo NewHandshaker(stateDB, state, blockStore, gdoc)) err = proxyApp.Start() if err != nil { - cmn.Exit(cmn.Fmt("Error starting proxy app conns: %v", err)) + cmn.Exit(fmt.Sprintf("Error starting proxy app conns: %v", err)) } eventBus := types.NewEventBus() if err := eventBus.Start(); err != nil { - cmn.Exit(cmn.Fmt("Failed to start event bus: %v", err)) + cmn.Exit(fmt.Sprintf("Failed to start event bus: %v", err)) } mempool, evpool := sm.MockMempool{}, sm.MockEvidencePool{} diff --git a/consensus/replay_test.go b/consensus/replay_test.go index fa0ec0408..c74a1ae9d 100644 --- a/consensus/replay_test.go +++ b/consensus/replay_test.go @@ -3,7 +3,6 @@ package consensus import ( "bytes" "context" - "errors" "fmt" "io" "io/ioutil" @@ -20,15 +19,14 @@ import ( abci "github.com/tendermint/tendermint/abci/types" crypto "github.com/tendermint/tendermint/crypto" auto "github.com/tendermint/tendermint/libs/autofile" - cmn "github.com/tendermint/tendermint/libs/common" dbm "github.com/tendermint/tendermint/libs/db" cfg "github.com/tendermint/tendermint/config" + "github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/privval" "github.com/tendermint/tendermint/proxy" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" - "github.com/tendermint/tendermint/libs/log" ) var consensusReplayConfig *cfg.Config @@ -494,7 +492,7 @@ func makeBlockchainFromWAL(wal WAL) ([]*types.Block, []*types.Commit, error) { return nil, nil, err } if !found { - return nil, nil, errors.New(cmn.Fmt("WAL does not contain height %d.", 1)) + return nil, nil, fmt.Errorf("WAL does not contain height %d.", 1) } defer gr.Close() // nolint: errcheck @@ -531,11 +529,11 @@ func makeBlockchainFromWAL(wal WAL) ([]*types.Block, []*types.Commit, error) { panic(err) } if block.Height != height+1 { - panic(cmn.Fmt("read bad block from wal. got height %d, expected %d", block.Height, height+1)) + panic(fmt.Sprintf("read bad block from wal. got height %d, expected %d", block.Height, height+1)) } commitHeight := thisBlockCommit.Precommits[0].Height if commitHeight != height+1 { - panic(cmn.Fmt("commit doesnt match. got height %d, expected %d", commitHeight, height+1)) + panic(fmt.Sprintf("commit doesnt match. got height %d, expected %d", commitHeight, height+1)) } blocks = append(blocks, block) commits = append(commits, thisBlockCommit) @@ -564,11 +562,11 @@ func makeBlockchainFromWAL(wal WAL) ([]*types.Block, []*types.Commit, error) { panic(err) } if block.Height != height+1 { - panic(cmn.Fmt("read bad block from wal. got height %d, expected %d", block.Height, height+1)) + panic(fmt.Sprintf("read bad block from wal. got height %d, expected %d", block.Height, height+1)) } commitHeight := thisBlockCommit.Precommits[0].Height if commitHeight != height+1 { - panic(cmn.Fmt("commit doesnt match. got height %d, expected %d", commitHeight, height+1)) + panic(fmt.Sprintf("commit doesnt match. got height %d, expected %d", commitHeight, height+1)) } blocks = append(blocks, block) commits = append(commits, thisBlockCommit) diff --git a/consensus/state.go b/consensus/state.go index a5ade13cc..debe94dad 100644 --- a/consensus/state.go +++ b/consensus/state.go @@ -186,7 +186,7 @@ func WithMetrics(metrics *Metrics) CSOption { // String returns a string. func (cs *ConsensusState) String() string { // better not to access shared variables - return cmn.Fmt("ConsensusState") //(H:%v R:%v S:%v", cs.Height, cs.Round, cs.Step) + return fmt.Sprintf("ConsensusState") //(H:%v R:%v S:%v", cs.Height, cs.Round, cs.Step) } // GetState returns a copy of the chain state. @@ -459,7 +459,7 @@ func (cs *ConsensusState) reconstructLastCommit(state sm.State) { } added, err := lastPrecommits.AddVote(precommit) if !added || err != nil { - cmn.PanicCrisis(cmn.Fmt("Failed to reconstruct LastCommit: %v", err)) + cmn.PanicCrisis(fmt.Sprintf("Failed to reconstruct LastCommit: %v", err)) } } if !lastPrecommits.HasTwoThirdsMajority() { @@ -472,13 +472,13 @@ func (cs *ConsensusState) reconstructLastCommit(state sm.State) { // The round becomes 0 and cs.Step becomes cstypes.RoundStepNewHeight. func (cs *ConsensusState) updateToState(state sm.State) { if cs.CommitRound > -1 && 0 < cs.Height && cs.Height != state.LastBlockHeight { - cmn.PanicSanity(cmn.Fmt("updateToState() expected state height of %v but found %v", + cmn.PanicSanity(fmt.Sprintf("updateToState() expected state height of %v but found %v", cs.Height, state.LastBlockHeight)) } if !cs.state.IsEmpty() && cs.state.LastBlockHeight+1 != cs.Height { // This might happen when someone else is mutating cs.state. // Someone forgot to pass in state.Copy() somewhere?! - cmn.PanicSanity(cmn.Fmt("Inconsistent cs.state.LastBlockHeight+1 %v vs cs.Height %v", + cmn.PanicSanity(fmt.Sprintf("Inconsistent cs.state.LastBlockHeight+1 %v vs cs.Height %v", cs.state.LastBlockHeight+1, cs.Height)) } @@ -698,7 +698,7 @@ func (cs *ConsensusState) handleTimeout(ti timeoutInfo, rs cstypes.RoundState) { cs.eventBus.PublishEventTimeoutWait(cs.RoundStateEvent()) cs.enterNewRound(ti.Height, ti.Round+1) default: - panic(cmn.Fmt("Invalid timeout step: %v", ti.Step)) + panic(fmt.Sprintf("Invalid timeout step: %v", ti.Step)) } } @@ -724,7 +724,7 @@ func (cs *ConsensusState) enterNewRound(height int64, round int) { logger := cs.Logger.With("height", height, "round", round) if cs.Height != height || round < cs.Round || (cs.Round == round && cs.Step != cstypes.RoundStepNewHeight) { - logger.Debug(cmn.Fmt("enterNewRound(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + logger.Debug(fmt.Sprintf("enterNewRound(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) return } @@ -732,7 +732,7 @@ func (cs *ConsensusState) enterNewRound(height int64, round int) { logger.Info("Need to set a buffer and log message here for sanity.", "startTime", cs.StartTime, "now", now) } - logger.Info(cmn.Fmt("enterNewRound(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + logger.Info(fmt.Sprintf("enterNewRound(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) // Increment validators if necessary validators := cs.Validators @@ -819,10 +819,10 @@ func (cs *ConsensusState) enterPropose(height int64, round int) { logger := cs.Logger.With("height", height, "round", round) if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPropose <= cs.Step) { - logger.Debug(cmn.Fmt("enterPropose(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + logger.Debug(fmt.Sprintf("enterPropose(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) return } - logger.Info(cmn.Fmt("enterPropose(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + logger.Info(fmt.Sprintf("enterPropose(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) defer func() { // Done enterPropose: @@ -902,7 +902,7 @@ func (cs *ConsensusState) defaultDecideProposal(height int64, round int) { cs.sendInternalMessage(msgInfo{&BlockPartMessage{cs.Height, cs.Round, part}, ""}) } cs.Logger.Info("Signed proposal", "height", height, "round", round, "proposal", proposal) - cs.Logger.Debug(cmn.Fmt("Signed proposal block: %v", block)) + 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) @@ -961,7 +961,7 @@ func (cs *ConsensusState) createProposalBlock() (block *types.Block, blockParts // Otherwise vote nil. func (cs *ConsensusState) enterPrevote(height int64, round int) { if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPrevote <= cs.Step) { - cs.Logger.Debug(cmn.Fmt("enterPrevote(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + cs.Logger.Debug(fmt.Sprintf("enterPrevote(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) return } @@ -979,7 +979,7 @@ func (cs *ConsensusState) enterPrevote(height int64, round int) { // TODO: catchup event? } - cs.Logger.Info(cmn.Fmt("enterPrevote(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + cs.Logger.Info(fmt.Sprintf("enterPrevote(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) // Sign and broadcast vote as necessary cs.doPrevote(height, round) @@ -1025,13 +1025,13 @@ func (cs *ConsensusState) enterPrevoteWait(height int64, round int) { logger := cs.Logger.With("height", height, "round", round) if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPrevoteWait <= cs.Step) { - logger.Debug(cmn.Fmt("enterPrevoteWait(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + logger.Debug(fmt.Sprintf("enterPrevoteWait(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) return } if !cs.Votes.Prevotes(round).HasTwoThirdsAny() { - cmn.PanicSanity(cmn.Fmt("enterPrevoteWait(%v/%v), but Prevotes does not have any +2/3 votes", height, round)) + cmn.PanicSanity(fmt.Sprintf("enterPrevoteWait(%v/%v), but Prevotes does not have any +2/3 votes", height, round)) } - logger.Info(cmn.Fmt("enterPrevoteWait(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + logger.Info(fmt.Sprintf("enterPrevoteWait(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) defer func() { // Done enterPrevoteWait: @@ -1053,11 +1053,11 @@ func (cs *ConsensusState) enterPrecommit(height int64, round int) { logger := cs.Logger.With("height", height, "round", round) if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPrecommit <= cs.Step) { - logger.Debug(cmn.Fmt("enterPrecommit(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + logger.Debug(fmt.Sprintf("enterPrecommit(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) return } - logger.Info(cmn.Fmt("enterPrecommit(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + logger.Info(fmt.Sprintf("enterPrecommit(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) defer func() { // Done enterPrecommit: @@ -1085,7 +1085,7 @@ func (cs *ConsensusState) enterPrecommit(height int64, round int) { // the latest POLRound should be this round. polRound, _ := cs.Votes.POLInfo() if polRound < round { - cmn.PanicSanity(cmn.Fmt("This POLRound should be %v but got %", round, polRound)) + cmn.PanicSanity(fmt.Sprintf("This POLRound should be %v but got %v", round, polRound)) } // +2/3 prevoted nil. Unlock and precommit nil. @@ -1119,7 +1119,7 @@ func (cs *ConsensusState) enterPrecommit(height int64, round int) { logger.Info("enterPrecommit: +2/3 prevoted proposal block. Locking", "hash", blockID.Hash) // Validate the block. if err := cs.blockExec.ValidateBlock(cs.state, cs.ProposalBlock); err != nil { - cmn.PanicConsensus(cmn.Fmt("enterPrecommit: +2/3 prevoted for an invalid block: %v", err)) + cmn.PanicConsensus(fmt.Sprintf("enterPrecommit: +2/3 prevoted for an invalid block: %v", err)) } cs.LockedRound = round cs.LockedBlock = cs.ProposalBlock @@ -1149,13 +1149,13 @@ func (cs *ConsensusState) enterPrecommitWait(height int64, round int) { logger := cs.Logger.With("height", height, "round", round) if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPrecommitWait <= cs.Step) { - logger.Debug(cmn.Fmt("enterPrecommitWait(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + logger.Debug(fmt.Sprintf("enterPrecommitWait(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) return } if !cs.Votes.Precommits(round).HasTwoThirdsAny() { - cmn.PanicSanity(cmn.Fmt("enterPrecommitWait(%v/%v), but Precommits does not have any +2/3 votes", height, round)) + cmn.PanicSanity(fmt.Sprintf("enterPrecommitWait(%v/%v), but Precommits does not have any +2/3 votes", height, round)) } - logger.Info(cmn.Fmt("enterPrecommitWait(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + logger.Info(fmt.Sprintf("enterPrecommitWait(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) defer func() { // Done enterPrecommitWait: @@ -1173,10 +1173,10 @@ func (cs *ConsensusState) enterCommit(height int64, commitRound int) { logger := cs.Logger.With("height", height, "commitRound", commitRound) if cs.Height != height || cstypes.RoundStepCommit <= cs.Step { - logger.Debug(cmn.Fmt("enterCommit(%v/%v): Invalid args. Current step: %v/%v/%v", height, commitRound, cs.Height, cs.Round, cs.Step)) + logger.Debug(fmt.Sprintf("enterCommit(%v/%v): Invalid args. Current step: %v/%v/%v", height, commitRound, cs.Height, cs.Round, cs.Step)) return } - logger.Info(cmn.Fmt("enterCommit(%v/%v). Current: %v/%v/%v", height, commitRound, cs.Height, cs.Round, cs.Step)) + logger.Info(fmt.Sprintf("enterCommit(%v/%v). Current: %v/%v/%v", height, commitRound, cs.Height, cs.Round, cs.Step)) defer func() { // Done enterCommit: @@ -1223,7 +1223,7 @@ func (cs *ConsensusState) tryFinalizeCommit(height int64) { logger := cs.Logger.With("height", height) if cs.Height != height { - cmn.PanicSanity(cmn.Fmt("tryFinalizeCommit() cs.Height: %v vs height: %v", cs.Height, height)) + cmn.PanicSanity(fmt.Sprintf("tryFinalizeCommit() cs.Height: %v vs height: %v", cs.Height, height)) } blockID, ok := cs.Votes.Precommits(cs.CommitRound).TwoThirdsMajority() @@ -1245,7 +1245,7 @@ func (cs *ConsensusState) tryFinalizeCommit(height int64) { // Increment height and goto cstypes.RoundStepNewHeight func (cs *ConsensusState) finalizeCommit(height int64) { if cs.Height != height || cs.Step != cstypes.RoundStepCommit { - cs.Logger.Debug(cmn.Fmt("finalizeCommit(%v): Invalid args. Current step: %v/%v/%v", height, cs.Height, cs.Round, cs.Step)) + cs.Logger.Debug(fmt.Sprintf("finalizeCommit(%v): Invalid args. Current step: %v/%v/%v", height, cs.Height, cs.Round, cs.Step)) return } @@ -1253,21 +1253,21 @@ func (cs *ConsensusState) finalizeCommit(height int64) { block, blockParts := cs.ProposalBlock, cs.ProposalBlockParts if !ok { - cmn.PanicSanity(cmn.Fmt("Cannot finalizeCommit, commit does not have two thirds majority")) + cmn.PanicSanity(fmt.Sprintf("Cannot finalizeCommit, commit does not have two thirds majority")) } if !blockParts.HasHeader(blockID.PartsHeader) { - cmn.PanicSanity(cmn.Fmt("Expected ProposalBlockParts header to be commit header")) + cmn.PanicSanity(fmt.Sprintf("Expected ProposalBlockParts header to be commit header")) } if !block.HashesTo(blockID.Hash) { - cmn.PanicSanity(cmn.Fmt("Cannot finalizeCommit, ProposalBlock does not hash to commit hash")) + cmn.PanicSanity(fmt.Sprintf("Cannot finalizeCommit, ProposalBlock does not hash to commit hash")) } if err := cs.blockExec.ValidateBlock(cs.state, block); err != nil { - cmn.PanicConsensus(cmn.Fmt("+2/3 committed an invalid block: %v", err)) + cmn.PanicConsensus(fmt.Sprintf("+2/3 committed an invalid block: %v", err)) } - cs.Logger.Info(cmn.Fmt("Finalizing commit of block with %d txs", block.NumTxs), + cs.Logger.Info(fmt.Sprintf("Finalizing commit of block with %d txs", block.NumTxs), "height", block.Height, "hash", block.Hash(), "root", block.AppHash) - cs.Logger.Info(cmn.Fmt("%v", block)) + cs.Logger.Info(fmt.Sprintf("%v", block)) fail.Fail() // XXX @@ -1519,7 +1519,7 @@ func (cs *ConsensusState) addVote(vote *types.Vote, peerID p2p.ID) (added bool, return added, err } - cs.Logger.Info(cmn.Fmt("Added to lastPrecommits: %v", cs.LastCommit.StringShort())) + cs.Logger.Info(fmt.Sprintf("Added to lastPrecommits: %v", cs.LastCommit.StringShort())) cs.eventBus.PublishEventVote(types.EventDataVote{vote}) cs.evsw.FireEvent(types.EventVote, vote) @@ -1635,7 +1635,7 @@ func (cs *ConsensusState) addVote(vote *types.Vote, peerID p2p.ID) (added bool, cs.enterPrecommitWait(height, vote.Round) } default: - panic(cmn.Fmt("Unexpected vote type %X", vote.Type)) // go-wire should prevent this. + panic(fmt.Sprintf("Unexpected vote type %X", vote.Type)) // go-wire should prevent this. } return diff --git a/consensus/state_test.go b/consensus/state_test.go index d943be87e..14cd0593e 100644 --- a/consensus/state_test.go +++ b/consensus/state_test.go @@ -8,7 +8,6 @@ import ( "time" cstypes "github.com/tendermint/tendermint/consensus/types" - cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/log" tmpubsub "github.com/tendermint/tendermint/libs/pubsub" "github.com/tendermint/tendermint/types" @@ -84,7 +83,7 @@ func TestStateProposerSelection0(t *testing.T) { prop = cs1.GetRoundState().Validators.GetProposer() if !bytes.Equal(prop.Address, vss[1].GetAddress()) { - panic(cmn.Fmt("expected proposer to be validator %d. Got %X", 1, prop.Address)) + panic(fmt.Sprintf("expected proposer to be validator %d. Got %X", 1, prop.Address)) } } @@ -106,7 +105,7 @@ func TestStateProposerSelection2(t *testing.T) { prop := cs1.GetRoundState().Validators.GetProposer() correctProposer := vss[(i+2)%len(vss)].GetAddress() if !bytes.Equal(prop.Address, correctProposer) { - panic(cmn.Fmt("expected RoundState.Validators.GetProposer() to be validator %d. Got %X", (i+2)%len(vss), prop.Address)) + panic(fmt.Sprintf("expected RoundState.Validators.GetProposer() to be validator %d. Got %X", (i+2)%len(vss), prop.Address)) } rs := cs1.GetRoundState() @@ -445,7 +444,7 @@ func TestStateLockNoPOL(t *testing.T) { // now we're on a new round and are the proposer if !bytes.Equal(rs.ProposalBlock.Hash(), rs.LockedBlock.Hash()) { - panic(cmn.Fmt("Expected proposal block to be locked block. Got %v, Expected %v", rs.ProposalBlock, rs.LockedBlock)) + panic(fmt.Sprintf("Expected proposal block to be locked block. Got %v, Expected %v", rs.ProposalBlock, rs.LockedBlock)) } <-voteCh // prevote diff --git a/consensus/types/height_vote_set.go b/consensus/types/height_vote_set.go index 70a38668f..1c8ac67cb 100644 --- a/consensus/types/height_vote_set.go +++ b/consensus/types/height_vote_set.go @@ -6,9 +6,9 @@ import ( "strings" "sync" + cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/types" - cmn "github.com/tendermint/tendermint/libs/common" ) type RoundVoteSet struct { @@ -169,7 +169,7 @@ func (hvs *HeightVoteSet) getVoteSet(round int, type_ byte) *types.VoteSet { case types.VoteTypePrecommit: return rvs.Precommits default: - cmn.PanicSanity(cmn.Fmt("Unexpected vote type %X", type_)) + cmn.PanicSanity(fmt.Sprintf("Unexpected vote type %X", type_)) return nil } } @@ -219,7 +219,7 @@ func (hvs *HeightVoteSet) StringIndented(indent string) string { voteSetString = roundVoteSet.Precommits.StringShort() vsStrings = append(vsStrings, voteSetString) } - return cmn.Fmt(`HeightVoteSet{H:%v R:0~%v + return fmt.Sprintf(`HeightVoteSet{H:%v R:0~%v %s %v %s}`, hvs.height, hvs.round, diff --git a/consensus/types/height_vote_set_test.go b/consensus/types/height_vote_set_test.go index 0de656000..77b5bfcb2 100644 --- a/consensus/types/height_vote_set_test.go +++ b/consensus/types/height_vote_set_test.go @@ -1,12 +1,12 @@ package types import ( + "fmt" "testing" "time" cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/types" - cmn "github.com/tendermint/tendermint/libs/common" ) var config *cfg.Config // NOTE: must be reset for each _test.go file @@ -62,7 +62,7 @@ func makeVoteHR(t *testing.T, height int64, round int, privVals []types.PrivVali chainID := config.ChainID() err := privVal.SignVote(chainID, vote) if err != nil { - panic(cmn.Fmt("Error signing vote: %v", err)) + panic(fmt.Sprintf("Error signing vote: %v", err)) return nil } return vote diff --git a/consensus/types/peer_round_state.go b/consensus/types/peer_round_state.go index 7a5d69b8e..e42395bc3 100644 --- a/consensus/types/peer_round_state.go +++ b/consensus/types/peer_round_state.go @@ -4,8 +4,8 @@ import ( "fmt" "time" - "github.com/tendermint/tendermint/types" cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/types" ) //----------------------------------------------------------------------------- diff --git a/consensus/types/round_state.go b/consensus/types/round_state.go index cca560ccf..c22880c2b 100644 --- a/consensus/types/round_state.go +++ b/consensus/types/round_state.go @@ -5,8 +5,8 @@ import ( "fmt" "time" - "github.com/tendermint/tendermint/types" cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/types" ) //----------------------------------------------------------------------------- diff --git a/consensus/version.go b/consensus/version.go index 5c74a16db..c04d2ac7d 100644 --- a/consensus/version.go +++ b/consensus/version.go @@ -1,8 +1,6 @@ package consensus -import ( - cmn "github.com/tendermint/tendermint/libs/common" -) +import "fmt" // kind of arbitrary var Spec = "1" // async @@ -10,4 +8,4 @@ var Major = "0" // var Minor = "2" // replay refactor var Revision = "2" // validation -> commit -var Version = cmn.Fmt("v%s/%s.%s.%s", Spec, Major, Minor, Revision) +var Version = fmt.Sprintf("v%s/%s.%s.%s", Spec, Major, Minor, Revision) diff --git a/consensus/wal.go b/consensus/wal.go index 8c4c10bc7..5c22bb930 100644 --- a/consensus/wal.go +++ b/consensus/wal.go @@ -11,9 +11,9 @@ import ( "github.com/pkg/errors" amino "github.com/tendermint/go-amino" - "github.com/tendermint/tendermint/types" auto "github.com/tendermint/tendermint/libs/autofile" cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/types" ) const ( @@ -120,7 +120,7 @@ func (wal *baseWAL) Write(msg WALMessage) { // Write the wal message if err := wal.enc.Encode(&TimedWALMessage{time.Now(), msg}); err != nil { - panic(cmn.Fmt("Error writing msg to consensus wal: %v \n\nMessage: %v", err, msg)) + panic(fmt.Sprintf("Error writing msg to consensus wal: %v \n\nMessage: %v", err, msg)) } } @@ -134,7 +134,7 @@ func (wal *baseWAL) WriteSync(msg WALMessage) { wal.Write(msg) if err := wal.group.Flush(); err != nil { - panic(cmn.Fmt("Error flushing consensus wal buf to file. Error: %v \n", err)) + panic(fmt.Sprintf("Error flushing consensus wal buf to file. Error: %v \n", err)) } } diff --git a/consensus/wal_generator.go b/consensus/wal_generator.go index f3a365809..6d889aa6f 100644 --- a/consensus/wal_generator.go +++ b/consensus/wal_generator.go @@ -13,14 +13,14 @@ import ( "github.com/tendermint/tendermint/abci/example/kvstore" bc "github.com/tendermint/tendermint/blockchain" cfg "github.com/tendermint/tendermint/config" - "github.com/tendermint/tendermint/privval" - "github.com/tendermint/tendermint/proxy" - sm "github.com/tendermint/tendermint/state" - "github.com/tendermint/tendermint/types" auto "github.com/tendermint/tendermint/libs/autofile" cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/libs/log" + "github.com/tendermint/tendermint/privval" + "github.com/tendermint/tendermint/proxy" + sm "github.com/tendermint/tendermint/state" + "github.com/tendermint/tendermint/types" ) // WALWithNBlocks generates a consensus WAL. It does this by spining up a diff --git a/consensus/wal_test.go b/consensus/wal_test.go index 3ecb4fe8f..9a101bb73 100644 --- a/consensus/wal_test.go +++ b/consensus/wal_test.go @@ -3,13 +3,13 @@ package consensus import ( "bytes" "crypto/rand" + "fmt" // "sync" "testing" "time" "github.com/tendermint/tendermint/consensus/types" tmtypes "github.com/tendermint/tendermint/types" - cmn "github.com/tendermint/tendermint/libs/common" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -54,8 +54,8 @@ func TestWALSearchForEndHeight(t *testing.T) { h := int64(3) gr, found, err := wal.SearchForEndHeight(h, &WALSearchOptions{}) - assert.NoError(t, err, cmn.Fmt("expected not to err on height %d", h)) - assert.True(t, found, cmn.Fmt("expected to find end height for %d", h)) + assert.NoError(t, err, fmt.Sprintf("expected not to err on height %d", h)) + assert.True(t, found, fmt.Sprintf("expected to find end height for %d", h)) assert.NotNil(t, gr, "expected group not to be nil") defer gr.Close() @@ -64,7 +64,7 @@ func TestWALSearchForEndHeight(t *testing.T) { assert.NoError(t, err, "expected to decode a message") rs, ok := msg.Msg.(tmtypes.EventDataRoundState) assert.True(t, ok, "expected message of type EventDataRoundState") - assert.Equal(t, rs.Height, h+1, cmn.Fmt("wrong height")) + assert.Equal(t, rs.Height, h+1, fmt.Sprintf("wrong height")) } /* diff --git a/crypto/merkle/simple_tree_test.go b/crypto/merkle/simple_tree_test.go index 488e0c907..e2dccd3b3 100644 --- a/crypto/merkle/simple_tree_test.go +++ b/crypto/merkle/simple_tree_test.go @@ -6,8 +6,9 @@ import ( cmn "github.com/tendermint/tendermint/libs/common" . "github.com/tendermint/tendermint/libs/test" - "github.com/tendermint/tendermint/crypto/tmhash" "testing" + + "github.com/tendermint/tendermint/crypto/tmhash" ) type testItem []byte diff --git a/crypto/xsalsa20symmetric/symmetric.go b/crypto/xsalsa20symmetric/symmetric.go index d2369675d..aa33ee14a 100644 --- a/crypto/xsalsa20symmetric/symmetric.go +++ b/crypto/xsalsa20symmetric/symmetric.go @@ -2,6 +2,7 @@ package xsalsa20symmetric import ( "errors" + "fmt" "github.com/tendermint/tendermint/crypto" cmn "github.com/tendermint/tendermint/libs/common" @@ -18,7 +19,7 @@ const secretLen = 32 // NOTE: call crypto.MixEntropy() first. func EncryptSymmetric(plaintext []byte, secret []byte) (ciphertext []byte) { if len(secret) != secretLen { - cmn.PanicSanity(cmn.Fmt("Secret must be 32 bytes long, got len %v", len(secret))) + cmn.PanicSanity(fmt.Sprintf("Secret must be 32 bytes long, got len %v", len(secret))) } nonce := crypto.CRandBytes(nonceLen) nonceArr := [nonceLen]byte{} @@ -35,7 +36,7 @@ func EncryptSymmetric(plaintext []byte, secret []byte) (ciphertext []byte) { // The ciphertext is (secretbox.Overhead + 24) bytes longer than the plaintext. func DecryptSymmetric(ciphertext []byte, secret []byte) (plaintext []byte, err error) { if len(secret) != secretLen { - cmn.PanicSanity(cmn.Fmt("Secret must be 32 bytes long, got len %v", len(secret))) + cmn.PanicSanity(fmt.Sprintf("Secret must be 32 bytes long, got len %v", len(secret))) } if len(ciphertext) <= secretbox.Overhead+nonceLen { return nil, errors.New("Ciphertext is too short") diff --git a/docs/app-dev/app-development.md b/docs/app-dev/app-development.md index d3f22362b..6c2ae9aba 100644 --- a/docs/app-dev/app-development.md +++ b/docs/app-dev/app-development.md @@ -502,7 +502,7 @@ In go: ``` func (app *KVStoreApplication) Info(req types.RequestInfo) (resInfo types.ResponseInfo) { - return types.ResponseInfo{Data: cmn.Fmt("{\"size\":%v}", app.state.Size())} + return types.ResponseInfo{Data: fmt.Sprintf("{\"size\":%v}", app.state.Size())} } ``` diff --git a/evidence/pool_test.go b/evidence/pool_test.go index 7c9f2c215..a38be0ab2 100644 --- a/evidence/pool_test.go +++ b/evidence/pool_test.go @@ -7,9 +7,9 @@ import ( "github.com/stretchr/testify/assert" + dbm "github.com/tendermint/tendermint/libs/db" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" - dbm "github.com/tendermint/tendermint/libs/db" ) var mockState = sm.State{} diff --git a/evidence/store.go b/evidence/store.go index 20b37bdb2..ba2e0afdd 100644 --- a/evidence/store.go +++ b/evidence/store.go @@ -3,8 +3,8 @@ package evidence import ( "fmt" - "github.com/tendermint/tendermint/types" dbm "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/types" ) /* diff --git a/evidence/store_test.go b/evidence/store_test.go index 30dc1c4d5..1eb5b7f6a 100644 --- a/evidence/store_test.go +++ b/evidence/store_test.go @@ -4,8 +4,8 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/tendermint/tendermint/types" dbm "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/types" ) //------------------------------------------- diff --git a/libs/autofile/group.go b/libs/autofile/group.go index e747f04dd..4e35d68d7 100644 --- a/libs/autofile/group.go +++ b/libs/autofile/group.go @@ -724,11 +724,11 @@ func (gr *GroupReader) SetIndex(index int) error { func MakeSimpleSearchFunc(prefix string, target int) SearchFunc { return func(line string) (int, error) { if !strings.HasPrefix(line, prefix) { - return -1, errors.New(cmn.Fmt("Marker line did not have prefix: %v", prefix)) + return -1, fmt.Errorf("Marker line did not have prefix: %v", prefix) } i, err := strconv.Atoi(line[len(prefix):]) if err != nil { - return -1, errors.New(cmn.Fmt("Failed to parse marker line: %v", err.Error())) + return -1, fmt.Errorf("Failed to parse marker line: %v", err.Error()) } if target < i { return 1, nil diff --git a/libs/common/bit_array_test.go b/libs/common/bit_array_test.go index c697ba5de..b1efd3f62 100644 --- a/libs/common/bit_array_test.go +++ b/libs/common/bit_array_test.go @@ -3,6 +3,7 @@ package common import ( "bytes" "encoding/json" + "fmt" "testing" "github.com/stretchr/testify/assert" @@ -149,7 +150,7 @@ func TestBytes(t *testing.T) { bA.SetIndex(0, true) check := func(bA *BitArray, bz []byte) { if !bytes.Equal(bA.Bytes(), bz) { - panic(Fmt("Expected %X but got %X", bz, bA.Bytes())) + panic(fmt.Sprintf("Expected %X but got %X", bz, bA.Bytes())) } } check(bA, []byte{0x01}) diff --git a/libs/common/colors.go b/libs/common/colors.go index 049ce7a50..4837f97b4 100644 --- a/libs/common/colors.go +++ b/libs/common/colors.go @@ -88,7 +88,7 @@ func ColoredBytes(data []byte, textColor, bytesColor func(...interface{}) string if 0x21 <= b && b < 0x7F { s += textColor(string(b)) } else { - s += bytesColor(Fmt("%02X", b)) + s += bytesColor(fmt.Sprintf("%02X", b)) } } return s diff --git a/libs/common/errors.go b/libs/common/errors.go index 5c31b8968..1dc909e89 100644 --- a/libs/common/errors.go +++ b/libs/common/errors.go @@ -10,13 +10,13 @@ import ( func ErrorWrap(cause interface{}, format string, args ...interface{}) Error { if causeCmnError, ok := cause.(*cmnError); ok { - msg := Fmt(format, args...) + msg := fmt.Sprintf(format, args...) return causeCmnError.Stacktrace().Trace(1, msg) } else if cause == nil { return newCmnError(FmtError{format, args}).Stacktrace() } else { // NOTE: causeCmnError is a typed nil here. - msg := Fmt(format, args...) + msg := fmt.Sprintf(format, args...) return newCmnError(cause).Stacktrace().Trace(1, msg) } } @@ -98,7 +98,7 @@ func (err *cmnError) Stacktrace() Error { // Add tracing information with msg. // Set n=0 unless wrapped with some function, then n > 0. func (err *cmnError) Trace(offset int, format string, args ...interface{}) Error { - msg := Fmt(format, args...) + msg := fmt.Sprintf(format, args...) return err.doTrace(msg, offset) } @@ -221,7 +221,7 @@ func (fe FmtError) Format() string { // and some guarantee is not satisfied. // XXX DEPRECATED func PanicSanity(v interface{}) { - panic(Fmt("Panicked on a Sanity Check: %v", v)) + panic(fmt.Sprintf("Panicked on a Sanity Check: %v", v)) } // A panic here means something has gone horribly wrong, in the form of data corruption or @@ -229,18 +229,18 @@ func PanicSanity(v interface{}) { // If they do, it's indicative of a much more serious problem. // XXX DEPRECATED func PanicCrisis(v interface{}) { - panic(Fmt("Panicked on a Crisis: %v", v)) + panic(fmt.Sprintf("Panicked on a Crisis: %v", v)) } // Indicates a failure of consensus. Someone was malicious or something has // gone horribly wrong. These should really boot us into an "emergency-recover" mode // XXX DEPRECATED func PanicConsensus(v interface{}) { - panic(Fmt("Panicked on a Consensus Failure: %v", v)) + panic(fmt.Sprintf("Panicked on a Consensus Failure: %v", v)) } // For those times when we're not sure if we should panic // XXX DEPRECATED func PanicQ(v interface{}) { - panic(Fmt("Panicked questionably: %v", v)) + panic(fmt.Sprintf("Panicked questionably: %v", v)) } diff --git a/libs/common/os.go b/libs/common/os.go index b8419764e..501bb5640 100644 --- a/libs/common/os.go +++ b/libs/common/os.go @@ -106,7 +106,7 @@ func ReadFile(filePath string) ([]byte, error) { func MustReadFile(filePath string) []byte { fileBytes, err := ioutil.ReadFile(filePath) if err != nil { - Exit(Fmt("MustReadFile failed: %v", err)) + Exit(fmt.Sprintf("MustReadFile failed: %v", err)) return nil } return fileBytes @@ -119,7 +119,7 @@ func WriteFile(filePath string, contents []byte, mode os.FileMode) error { func MustWriteFile(filePath string, contents []byte, mode os.FileMode) { err := WriteFile(filePath, contents, mode) if err != nil { - Exit(Fmt("MustWriteFile failed: %v", err)) + Exit(fmt.Sprintf("MustWriteFile failed: %v", err)) } } diff --git a/libs/common/random.go b/libs/common/random.go index 4b0594d0e..2de65945c 100644 --- a/libs/common/random.go +++ b/libs/common/random.go @@ -295,7 +295,7 @@ func (r *Rand) Perm(n int) []int { // NOTE: This relies on the os's random number generator. // For real security, we should salt that with some seed. -// See github.com/tendermint/go-crypto for a more secure reader. +// See github.com/tendermint/tendermint/crypto for a more secure reader. func cRandBytes(numBytes int) []byte { b := make([]byte, numBytes) _, err := crand.Read(b) diff --git a/libs/common/service.go b/libs/common/service.go index b6f166e77..03e392855 100644 --- a/libs/common/service.go +++ b/libs/common/service.go @@ -123,10 +123,10 @@ func (bs *BaseService) SetLogger(l log.Logger) { func (bs *BaseService) Start() error { if atomic.CompareAndSwapUint32(&bs.started, 0, 1) { if atomic.LoadUint32(&bs.stopped) == 1 { - bs.Logger.Error(Fmt("Not starting %v -- already stopped", bs.name), "impl", bs.impl) + bs.Logger.Error(fmt.Sprintf("Not starting %v -- already stopped", bs.name), "impl", bs.impl) return ErrAlreadyStopped } - bs.Logger.Info(Fmt("Starting %v", bs.name), "impl", bs.impl) + bs.Logger.Info(fmt.Sprintf("Starting %v", bs.name), "impl", bs.impl) err := bs.impl.OnStart() if err != nil { // revert flag @@ -135,7 +135,7 @@ func (bs *BaseService) Start() error { } return nil } - bs.Logger.Debug(Fmt("Not starting %v -- already started", bs.name), "impl", bs.impl) + bs.Logger.Debug(fmt.Sprintf("Not starting %v -- already started", bs.name), "impl", bs.impl) return ErrAlreadyStarted } @@ -148,12 +148,12 @@ func (bs *BaseService) OnStart() error { return nil } // channel. An error will be returned if the service is already stopped. func (bs *BaseService) Stop() error { if atomic.CompareAndSwapUint32(&bs.stopped, 0, 1) { - bs.Logger.Info(Fmt("Stopping %v", bs.name), "impl", bs.impl) + bs.Logger.Info(fmt.Sprintf("Stopping %v", bs.name), "impl", bs.impl) bs.impl.OnStop() close(bs.quit) return nil } - bs.Logger.Debug(Fmt("Stopping %v (ignoring: already stopped)", bs.name), "impl", bs.impl) + bs.Logger.Debug(fmt.Sprintf("Stopping %v (ignoring: already stopped)", bs.name), "impl", bs.impl) return ErrAlreadyStopped } @@ -166,7 +166,7 @@ func (bs *BaseService) OnStop() {} // will be returned if the service is running. func (bs *BaseService) Reset() error { if !atomic.CompareAndSwapUint32(&bs.stopped, 1, 0) { - bs.Logger.Debug(Fmt("Can't reset %v. Not stopped", bs.name), "impl", bs.impl) + bs.Logger.Debug(fmt.Sprintf("Can't reset %v. Not stopped", bs.name), "impl", bs.impl) return fmt.Errorf("can't reset running %s", bs.name) } diff --git a/libs/common/string.go b/libs/common/string.go index fac1be6c9..e341b49e8 100644 --- a/libs/common/string.go +++ b/libs/common/string.go @@ -6,14 +6,6 @@ import ( "strings" ) -// Like fmt.Sprintf, but skips formatting if args are empty. -var Fmt = func(format string, a ...interface{}) string { - if len(a) == 0 { - return format - } - return fmt.Sprintf(format, a...) -} - // IsHex returns true for non-empty hex-string prefixed with "0x" func IsHex(s string) bool { if len(s) > 2 && strings.EqualFold(s[:2], "0x") { diff --git a/libs/db/backend_test.go b/libs/db/backend_test.go index b31b4d74a..496f4c410 100644 --- a/libs/db/backend_test.go +++ b/libs/db/backend_test.go @@ -54,7 +54,7 @@ func TestBackendsGetSetDelete(t *testing.T) { } func withDB(t *testing.T, creator dbCreator, fn func(DB)) { - name := cmn.Fmt("test_%x", cmn.RandStr(12)) + name := fmt.Sprintf("test_%x", cmn.RandStr(12)) db, err := creator(name, "") defer cleanupDBDir("", name) assert.Nil(t, err) @@ -143,7 +143,7 @@ func TestBackendsNilKeys(t *testing.T) { } func TestGoLevelDBBackend(t *testing.T) { - name := cmn.Fmt("test_%x", cmn.RandStr(12)) + name := fmt.Sprintf("test_%x", cmn.RandStr(12)) db := NewDB(name, GoLevelDBBackend, "") defer cleanupDBDir("", name) @@ -160,7 +160,7 @@ func TestDBIterator(t *testing.T) { } func testDBIterator(t *testing.T, backend DBBackendType) { - name := cmn.Fmt("test_%x", cmn.RandStr(12)) + name := fmt.Sprintf("test_%x", cmn.RandStr(12)) db := NewDB(name, backend, "") defer cleanupDBDir("", name) diff --git a/libs/db/c_level_db_test.go b/libs/db/c_level_db_test.go index 2d30500dd..d01a85e9d 100644 --- a/libs/db/c_level_db_test.go +++ b/libs/db/c_level_db_test.go @@ -19,7 +19,7 @@ func BenchmarkRandomReadsWrites2(b *testing.B) { for i := 0; i < int(numItems); i++ { internal[int64(i)] = int64(0) } - db, err := NewCLevelDB(cmn.Fmt("test_%x", cmn.RandStr(12)), "") + db, err := NewCLevelDB(fmt.Sprintf("test_%x", cmn.RandStr(12)), "") if err != nil { b.Fatal(err.Error()) return @@ -87,7 +87,7 @@ func bytes2Int64(buf []byte) int64 { */ func TestCLevelDBBackend(t *testing.T) { - name := cmn.Fmt("test_%x", cmn.RandStr(12)) + name := fmt.Sprintf("test_%x", cmn.RandStr(12)) db := NewDB(name, LevelDBBackend, "") defer cleanupDBDir("", name) diff --git a/libs/db/go_level_db_test.go b/libs/db/go_level_db_test.go index 47be216a6..e262fccd3 100644 --- a/libs/db/go_level_db_test.go +++ b/libs/db/go_level_db_test.go @@ -17,7 +17,7 @@ func BenchmarkRandomReadsWrites(b *testing.B) { for i := 0; i < int(numItems); i++ { internal[int64(i)] = int64(0) } - db, err := NewGoLevelDB(cmn.Fmt("test_%x", cmn.RandStr(12)), "") + db, err := NewGoLevelDB(fmt.Sprintf("test_%x", cmn.RandStr(12)), "") if err != nil { b.Fatal(err.Error()) return diff --git a/lite/provider.go b/lite/provider.go index 59e36a673..97e06a06d 100644 --- a/lite/provider.go +++ b/lite/provider.go @@ -1,8 +1,8 @@ package lite import ( - "github.com/tendermint/tendermint/types" log "github.com/tendermint/tendermint/libs/log" + "github.com/tendermint/tendermint/types" ) // Provider provides information for the lite client to sync validators. diff --git a/lite/provider_test.go b/lite/provider_test.go index e55470222..94b467de8 100644 --- a/lite/provider_test.go +++ b/lite/provider_test.go @@ -7,10 +7,10 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - lerr "github.com/tendermint/tendermint/lite/errors" - "github.com/tendermint/tendermint/types" dbm "github.com/tendermint/tendermint/libs/db" log "github.com/tendermint/tendermint/libs/log" + lerr "github.com/tendermint/tendermint/lite/errors" + "github.com/tendermint/tendermint/types" ) // missingProvider doesn't store anything, always a miss. diff --git a/lite/proxy/verifier.go b/lite/proxy/verifier.go index 6686def0d..a93d30c7f 100644 --- a/lite/proxy/verifier.go +++ b/lite/proxy/verifier.go @@ -1,11 +1,11 @@ package proxy import ( - "github.com/tendermint/tendermint/lite" - lclient "github.com/tendermint/tendermint/lite/client" cmn "github.com/tendermint/tendermint/libs/common" dbm "github.com/tendermint/tendermint/libs/db" log "github.com/tendermint/tendermint/libs/log" + "github.com/tendermint/tendermint/lite" + lclient "github.com/tendermint/tendermint/lite/client" ) func NewVerifier(chainID, rootDir string, client lclient.SignStatusClient, logger log.Logger) (*lite.DynamicVerifier, error) { diff --git a/mempool/mempool.go b/mempool/mempool.go index 5acb6f0d8..f03ca4e8b 100644 --- a/mempool/mempool.go +++ b/mempool/mempool.go @@ -312,7 +312,7 @@ func (mem *Mempool) resCbRecheck(req *abci.Request, res *abci.Response) { case *abci.Response_CheckTx: memTx := mem.recheckCursor.Value.(*mempoolTx) if !bytes.Equal(req.GetCheckTx().Tx, memTx.tx) { - cmn.PanicSanity(cmn.Fmt("Unexpected tx response from proxy during recheck\n"+ + cmn.PanicSanity(fmt.Sprintf("Unexpected tx response from proxy during recheck\n"+ "Expected %X, got %X", r.CheckTx.Data, memTx.tx)) } if r.CheckTx.Code == abci.CodeTypeOK { diff --git a/mempool/mempool_test.go b/mempool/mempool_test.go index c0f66051f..e276f11c8 100644 --- a/mempool/mempool_test.go +++ b/mempool/mempool_test.go @@ -14,7 +14,6 @@ import ( "github.com/tendermint/tendermint/abci/example/counter" "github.com/tendermint/tendermint/abci/example/kvstore" abci "github.com/tendermint/tendermint/abci/types" - cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/log" cfg "github.com/tendermint/tendermint/config" @@ -151,7 +150,7 @@ func TestSerialReap(t *testing.T) { reapCheck := func(exp int) { txs := mempool.Reap(-1) - require.Equal(t, len(txs), exp, cmn.Fmt("Expected to reap %v txs but got %v", exp, len(txs))) + require.Equal(t, len(txs), exp, fmt.Sprintf("Expected to reap %v txs but got %v", exp, len(txs))) } updateRange := func(start, end int) { diff --git a/node/node.go b/node/node.go index 0c3396dc6..ce0a22c9b 100644 --- a/node/node.go +++ b/node/node.go @@ -327,7 +327,7 @@ func NewNode(config *cfg.Config, if config.FilterPeers { // NOTE: addr is ip:port sw.SetAddrFilter(func(addr net.Addr) error { - resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/addr/%s", addr.String())}) + resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: fmt.Sprintf("/p2p/filter/addr/%s", addr.String())}) if err != nil { return err } @@ -337,7 +337,7 @@ func NewNode(config *cfg.Config, return nil }) sw.SetIDFilter(func(id p2p.ID) error { - resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/id/%s", id)}) + resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: fmt.Sprintf("/p2p/filter/id/%s", id)}) if err != nil { return err } @@ -683,11 +683,11 @@ func (n *Node) makeNodeInfo(nodeID p2p.ID) p2p.NodeInfo { }, Moniker: n.config.Moniker, Other: []string{ - cmn.Fmt("amino_version=%v", amino.Version), - cmn.Fmt("p2p_version=%v", p2p.Version), - cmn.Fmt("consensus_version=%v", cs.Version), - cmn.Fmt("rpc_version=%v/%v", rpc.Version, rpccore.Version), - cmn.Fmt("tx_index=%v", txIndexerStatus), + fmt.Sprintf("amino_version=%v", amino.Version), + fmt.Sprintf("p2p_version=%v", p2p.Version), + fmt.Sprintf("consensus_version=%v", cs.Version), + fmt.Sprintf("rpc_version=%v/%v", rpc.Version, rpccore.Version), + fmt.Sprintf("tx_index=%v", txIndexerStatus), }, } @@ -696,7 +696,7 @@ func (n *Node) makeNodeInfo(nodeID p2p.ID) p2p.NodeInfo { } rpcListenAddr := n.config.RPC.ListenAddress - nodeInfo.Other = append(nodeInfo.Other, cmn.Fmt("rpc_addr=%v", rpcListenAddr)) + nodeInfo.Other = append(nodeInfo.Other, fmt.Sprintf("rpc_addr=%v", rpcListenAddr)) if !n.sw.IsListening() { return nodeInfo @@ -705,7 +705,7 @@ func (n *Node) makeNodeInfo(nodeID p2p.ID) p2p.NodeInfo { p2pListener := n.sw.Listeners()[0] p2pHost := p2pListener.ExternalAddressHost() p2pPort := p2pListener.ExternalAddress().Port - nodeInfo.ListenAddr = cmn.Fmt("%v:%v", p2pHost, p2pPort) + nodeInfo.ListenAddr = fmt.Sprintf("%v:%v", p2pHost, p2pPort) return nodeInfo } diff --git a/p2p/base_reactor.go b/p2p/base_reactor.go index da1296da0..be65d2f14 100644 --- a/p2p/base_reactor.go +++ b/p2p/base_reactor.go @@ -1,8 +1,8 @@ package p2p import ( - "github.com/tendermint/tendermint/p2p/conn" cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/p2p/conn" ) type Reactor interface { diff --git a/p2p/conn/connection.go b/p2p/conn/connection.go index 9672e0117..bb67eab30 100644 --- a/p2p/conn/connection.go +++ b/p2p/conn/connection.go @@ -257,7 +257,7 @@ func (c *MConnection) Send(chID byte, msgBytes []byte) bool { // Send message to channel. channel, ok := c.channelsIdx[chID] if !ok { - c.Logger.Error(cmn.Fmt("Cannot send bytes, unknown channel %X", chID)) + c.Logger.Error(fmt.Sprintf("Cannot send bytes, unknown channel %X", chID)) return false } @@ -286,7 +286,7 @@ func (c *MConnection) TrySend(chID byte, msgBytes []byte) bool { // Send message to channel. channel, ok := c.channelsIdx[chID] if !ok { - c.Logger.Error(cmn.Fmt("Cannot send bytes, unknown channel %X", chID)) + c.Logger.Error(fmt.Sprintf("Cannot send bytes, unknown channel %X", chID)) return false } @@ -311,7 +311,7 @@ func (c *MConnection) CanSend(chID byte) bool { channel, ok := c.channelsIdx[chID] if !ok { - c.Logger.Error(cmn.Fmt("Unknown channel %X", chID)) + c.Logger.Error(fmt.Sprintf("Unknown channel %X", chID)) return false } return channel.canSend() diff --git a/p2p/listener.go b/p2p/listener.go index d73b3cabf..d0dd3f42a 100644 --- a/p2p/listener.go +++ b/p2p/listener.go @@ -259,7 +259,7 @@ func isIpv6(ip net.IP) bool { func getNaiveExternalAddress(defaultToIPv4 bool, port int, settleForLocal bool, logger log.Logger) *NetAddress { addrs, err := net.InterfaceAddrs() if err != nil { - panic(cmn.Fmt("Could not fetch interface addresses: %v", err)) + panic(fmt.Sprintf("Could not fetch interface addresses: %v", err)) } for _, a := range addrs { diff --git a/p2p/netaddress.go b/p2p/netaddress.go index ebac8cc82..a42f0fdde 100644 --- a/p2p/netaddress.go +++ b/p2p/netaddress.go @@ -44,7 +44,7 @@ func NewNetAddress(id ID, addr net.Addr) *NetAddress { tcpAddr, ok := addr.(*net.TCPAddr) if !ok { if flag.Lookup("test.v") == nil { // normal run - cmn.PanicSanity(cmn.Fmt("Only TCPAddrs are supported. Got: %v", addr)) + cmn.PanicSanity(fmt.Sprintf("Only TCPAddrs are supported. Got: %v", addr)) } else { // in testing netAddr := NewNetAddressIPPort(net.IP("0.0.0.0"), 0) netAddr.ID = id diff --git a/p2p/peer.go b/p2p/peer.go index 4f59fef76..a5f0bbbd8 100644 --- a/p2p/peer.go +++ b/p2p/peer.go @@ -425,7 +425,7 @@ func createMConnection( if reactor == nil { // Note that its ok to panic here as it's caught in the conn._recover, // which does onPeerError. - panic(cmn.Fmt("Unknown channel %X", chID)) + panic(fmt.Sprintf("Unknown channel %X", chID)) } reactor.Receive(chID, p, msgBytes) } diff --git a/p2p/peer_set_test.go b/p2p/peer_set_test.go index 4582ab644..a352cce00 100644 --- a/p2p/peer_set_test.go +++ b/p2p/peer_set_test.go @@ -1,6 +1,7 @@ package p2p import ( + "fmt" "net" "sync" "testing" @@ -21,7 +22,7 @@ func randPeer(ip net.IP) *peer { p := &peer{ nodeInfo: NodeInfo{ ID: nodeKey.ID(), - ListenAddr: cmn.Fmt("%v.%v.%v.%v:26656", cmn.RandInt()%256, cmn.RandInt()%256, cmn.RandInt()%256, cmn.RandInt()%256), + ListenAddr: fmt.Sprintf("%v.%v.%v.%v:26656", cmn.RandInt()%256, cmn.RandInt()%256, cmn.RandInt()%256, cmn.RandInt()%256), }, } diff --git a/p2p/pex/addrbook.go b/p2p/pex/addrbook.go index ad6e0c00b..e0c0e0b9c 100644 --- a/p2p/pex/addrbook.go +++ b/p2p/pex/addrbook.go @@ -7,6 +7,7 @@ package pex import ( "crypto/sha256" "encoding/binary" + "fmt" "math" "net" "sync" @@ -559,11 +560,11 @@ func (a *addrBook) addToNewBucket(ka *knownAddress, bucketIdx int) { func (a *addrBook) addToOldBucket(ka *knownAddress, bucketIdx int) bool { // Sanity check if ka.isNew() { - a.Logger.Error(cmn.Fmt("Cannot add new address to old bucket: %v", ka)) + a.Logger.Error(fmt.Sprintf("Cannot add new address to old bucket: %v", ka)) return false } if len(ka.Buckets) != 0 { - a.Logger.Error(cmn.Fmt("Cannot add already old address to another old bucket: %v", ka)) + a.Logger.Error(fmt.Sprintf("Cannot add already old address to another old bucket: %v", ka)) return false } @@ -594,7 +595,7 @@ func (a *addrBook) addToOldBucket(ka *knownAddress, bucketIdx int) bool { func (a *addrBook) removeFromBucket(ka *knownAddress, bucketType byte, bucketIdx int) { if ka.BucketType != bucketType { - a.Logger.Error(cmn.Fmt("Bucket type mismatch: %v", ka)) + a.Logger.Error(fmt.Sprintf("Bucket type mismatch: %v", ka)) return } bucket := a.getBucket(bucketType, bucketIdx) @@ -690,7 +691,7 @@ func (a *addrBook) expireNew(bucketIdx int) { for addrStr, ka := range a.bucketsNew[bucketIdx] { // If an entry is bad, throw it away if ka.isBad() { - a.Logger.Info(cmn.Fmt("expiring bad address %v", addrStr)) + a.Logger.Info(fmt.Sprintf("expiring bad address %v", addrStr)) a.removeFromBucket(ka, bucketTypeNew, bucketIdx) return } @@ -707,11 +708,11 @@ func (a *addrBook) expireNew(bucketIdx int) { func (a *addrBook) moveToOld(ka *knownAddress) { // Sanity check if ka.isOld() { - a.Logger.Error(cmn.Fmt("Cannot promote address that is already old %v", ka)) + a.Logger.Error(fmt.Sprintf("Cannot promote address that is already old %v", ka)) return } if len(ka.Buckets) == 0 { - a.Logger.Error(cmn.Fmt("Cannot promote address that isn't in any new buckets %v", ka)) + a.Logger.Error(fmt.Sprintf("Cannot promote address that isn't in any new buckets %v", ka)) return } @@ -733,7 +734,7 @@ func (a *addrBook) moveToOld(ka *knownAddress) { // Finally, add our ka to old bucket again. added = a.addToOldBucket(ka, oldBucketIdx) if !added { - a.Logger.Error(cmn.Fmt("Could not re-add ka %v to oldBucketIdx %v", ka, oldBucketIdx)) + a.Logger.Error(fmt.Sprintf("Could not re-add ka %v to oldBucketIdx %v", ka, oldBucketIdx)) } } } diff --git a/p2p/pex/file.go b/p2p/pex/file.go index 3237e1253..33fec0336 100644 --- a/p2p/pex/file.go +++ b/p2p/pex/file.go @@ -2,6 +2,7 @@ package pex import ( "encoding/json" + "fmt" "os" cmn "github.com/tendermint/tendermint/libs/common" @@ -53,14 +54,14 @@ func (a *addrBook) loadFromFile(filePath string) bool { // Load addrBookJSON{} r, err := os.Open(filePath) if err != nil { - cmn.PanicCrisis(cmn.Fmt("Error opening file %s: %v", filePath, err)) + cmn.PanicCrisis(fmt.Sprintf("Error opening file %s: %v", filePath, err)) } defer r.Close() // nolint: errcheck aJSON := &addrBookJSON{} dec := json.NewDecoder(r) err = dec.Decode(aJSON) if err != nil { - cmn.PanicCrisis(cmn.Fmt("Error reading file %s: %v", filePath, err)) + cmn.PanicCrisis(fmt.Sprintf("Error reading file %s: %v", filePath, err)) } // Restore all the fields... diff --git a/p2p/test_util.go b/p2p/test_util.go index fdf9ae764..90bcba4f1 100644 --- a/p2p/test_util.go +++ b/p2p/test_util.go @@ -35,7 +35,7 @@ func CreateRandomPeer(outbound bool) *peer { func CreateRoutableAddr() (addr string, netAddr *NetAddress) { for { var err error - addr = cmn.Fmt("%X@%v.%v.%v.%v:26656", cmn.RandBytes(20), cmn.RandInt()%256, cmn.RandInt()%256, cmn.RandInt()%256, cmn.RandInt()%256) + addr = fmt.Sprintf("%X@%v.%v.%v.%v:26656", cmn.RandBytes(20), cmn.RandInt()%256, cmn.RandInt()%256, cmn.RandInt()%256, cmn.RandInt()%256) netAddr, err = NewNetAddressString(addr) if err != nil { panic(err) @@ -142,7 +142,7 @@ func MakeSwitch(cfg *config.P2PConfig, i int, network, version string, initSwitc sw = initSwitch(i, sw) ni := NodeInfo{ ID: nodeKey.ID(), - Moniker: cmn.Fmt("switch%d", i), + Moniker: fmt.Sprintf("switch%d", i), Network: network, Version: version, ListenAddr: fmt.Sprintf("127.0.0.1:%d", cmn.RandIntn(64512)+1023), diff --git a/p2p/trust/store.go b/p2p/trust/store.go index 31f659a43..d6b4c049d 100644 --- a/p2p/trust/store.go +++ b/p2p/trust/store.go @@ -5,6 +5,7 @@ package trust import ( "encoding/json" + "fmt" "sync" "time" @@ -155,7 +156,7 @@ func (tms *TrustMetricStore) loadFromDB() bool { peers := make(map[string]MetricHistoryJSON) err := json.Unmarshal(bytes, &peers) if err != nil { - cmn.PanicCrisis(cmn.Fmt("Could not unmarshal Trust Metric Store DB data: %v", err)) + cmn.PanicCrisis(fmt.Sprintf("Could not unmarshal Trust Metric Store DB data: %v", err)) } // If history data exists in the file, diff --git a/p2p/upnp/probe.go b/p2p/upnp/probe.go index 2de5e7905..16a537241 100644 --- a/p2p/upnp/probe.go +++ b/p2p/upnp/probe.go @@ -5,7 +5,6 @@ import ( "net" "time" - cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/log" ) @@ -19,19 +18,19 @@ func makeUPNPListener(intPort int, extPort int, logger log.Logger) (NAT, net.Lis if err != nil { return nil, nil, nil, fmt.Errorf("NAT upnp could not be discovered: %v", err) } - logger.Info(cmn.Fmt("ourIP: %v", nat.(*upnpNAT).ourIP)) + logger.Info(fmt.Sprintf("ourIP: %v", nat.(*upnpNAT).ourIP)) ext, err := nat.GetExternalAddress() if err != nil { return nat, nil, nil, fmt.Errorf("External address error: %v", err) } - logger.Info(cmn.Fmt("External address: %v", ext)) + logger.Info(fmt.Sprintf("External address: %v", ext)) port, err := nat.AddPortMapping("tcp", extPort, intPort, "Tendermint UPnP Probe", 0) if err != nil { return nat, nil, ext, fmt.Errorf("Port mapping error: %v", err) } - logger.Info(cmn.Fmt("Port mapping mapped: %v", port)) + logger.Info(fmt.Sprintf("Port mapping mapped: %v", port)) // also run the listener, open for all remote addresses. listener, err := net.Listen("tcp", fmt.Sprintf(":%v", intPort)) @@ -46,17 +45,17 @@ func testHairpin(listener net.Listener, extAddr string, logger log.Logger) (supp go func() { inConn, err := listener.Accept() if err != nil { - logger.Info(cmn.Fmt("Listener.Accept() error: %v", err)) + logger.Info(fmt.Sprintf("Listener.Accept() error: %v", err)) return } - logger.Info(cmn.Fmt("Accepted incoming connection: %v -> %v", inConn.LocalAddr(), inConn.RemoteAddr())) + logger.Info(fmt.Sprintf("Accepted incoming connection: %v -> %v", inConn.LocalAddr(), inConn.RemoteAddr())) buf := make([]byte, 1024) n, err := inConn.Read(buf) if err != nil { - logger.Info(cmn.Fmt("Incoming connection read error: %v", err)) + logger.Info(fmt.Sprintf("Incoming connection read error: %v", err)) return } - logger.Info(cmn.Fmt("Incoming connection read %v bytes: %X", n, buf)) + logger.Info(fmt.Sprintf("Incoming connection read %v bytes: %X", n, buf)) if string(buf) == "test data" { supportsHairpin = true return @@ -66,16 +65,16 @@ func testHairpin(listener net.Listener, extAddr string, logger log.Logger) (supp // Establish outgoing outConn, err := net.Dial("tcp", extAddr) if err != nil { - logger.Info(cmn.Fmt("Outgoing connection dial error: %v", err)) + logger.Info(fmt.Sprintf("Outgoing connection dial error: %v", err)) return } n, err := outConn.Write([]byte("test data")) if err != nil { - logger.Info(cmn.Fmt("Outgoing connection write error: %v", err)) + logger.Info(fmt.Sprintf("Outgoing connection write error: %v", err)) return } - logger.Info(cmn.Fmt("Outgoing connection wrote %v bytes", n)) + logger.Info(fmt.Sprintf("Outgoing connection wrote %v bytes", n)) // Wait for data receipt time.Sleep(1 * time.Second) @@ -96,10 +95,10 @@ func Probe(logger log.Logger) (caps UPNPCapabilities, err error) { // Deferred cleanup defer func() { if err := nat.DeletePortMapping("tcp", intPort, extPort); err != nil { - logger.Error(cmn.Fmt("Port mapping delete error: %v", err)) + logger.Error(fmt.Sprintf("Port mapping delete error: %v", err)) } if err := listener.Close(); err != nil { - logger.Error(cmn.Fmt("Listener closing error: %v", err)) + logger.Error(fmt.Sprintf("Listener closing error: %v", err)) } }() diff --git a/privval/priv_validator.go b/privval/priv_validator.go index a81751a91..83fbb7e40 100644 --- a/privval/priv_validator.go +++ b/privval/priv_validator.go @@ -89,7 +89,7 @@ func LoadFilePV(filePath string) *FilePV { pv := &FilePV{} err = cdc.UnmarshalJSON(pvJSONBytes, &pv) if err != nil { - cmn.Exit(cmn.Fmt("Error reading PrivValidator from %v: %v\n", filePath, err)) + cmn.Exit(fmt.Sprintf("Error reading PrivValidator from %v: %v\n", filePath, err)) } // overwrite pubkey and address for convenience @@ -153,7 +153,7 @@ func (pv *FilePV) SignVote(chainID string, vote *types.Vote) error { pv.mtx.Lock() defer pv.mtx.Unlock() if err := pv.signVote(chainID, vote); err != nil { - return errors.New(cmn.Fmt("Error signing vote: %v", err)) + return fmt.Errorf("Error signing vote: %v", err) } return nil } diff --git a/proxy/app_conn_test.go b/proxy/app_conn_test.go index 44936056a..5eadb032f 100644 --- a/proxy/app_conn_test.go +++ b/proxy/app_conn_test.go @@ -1,6 +1,7 @@ package proxy import ( + "fmt" "strings" "testing" @@ -45,7 +46,7 @@ func (app *appConnTest) InfoSync(req types.RequestInfo) (*types.ResponseInfo, er var SOCKET = "socket" func TestEcho(t *testing.T) { - sockPath := cmn.Fmt("unix:///tmp/echo_%v.sock", cmn.RandStr(6)) + sockPath := fmt.Sprintf("unix:///tmp/echo_%v.sock", cmn.RandStr(6)) clientCreator := NewRemoteClientCreator(sockPath, SOCKET, true) // Start server @@ -70,7 +71,7 @@ func TestEcho(t *testing.T) { t.Log("Connected") for i := 0; i < 1000; i++ { - proxy.EchoAsync(cmn.Fmt("echo-%v", i)) + proxy.EchoAsync(fmt.Sprintf("echo-%v", i)) } if err := proxy.FlushSync(); err != nil { t.Error(err) @@ -79,7 +80,7 @@ func TestEcho(t *testing.T) { func BenchmarkEcho(b *testing.B) { b.StopTimer() // Initialize - sockPath := cmn.Fmt("unix:///tmp/echo_%v.sock", cmn.RandStr(6)) + sockPath := fmt.Sprintf("unix:///tmp/echo_%v.sock", cmn.RandStr(6)) clientCreator := NewRemoteClientCreator(sockPath, SOCKET, true) // Start server @@ -118,7 +119,7 @@ func BenchmarkEcho(b *testing.B) { } func TestInfo(t *testing.T) { - sockPath := cmn.Fmt("unix:///tmp/echo_%v.sock", cmn.RandStr(6)) + sockPath := fmt.Sprintf("unix:///tmp/echo_%v.sock", cmn.RandStr(6)) clientCreator := NewRemoteClientCreator(sockPath, SOCKET, true) // Start server diff --git a/rpc/client/event_test.go b/rpc/client/event_test.go index 79c452fc9..da4625d51 100644 --- a/rpc/client/event_test.go +++ b/rpc/client/event_test.go @@ -8,9 +8,9 @@ import ( "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" + cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/rpc/client" "github.com/tendermint/tendermint/types" - cmn "github.com/tendermint/tendermint/libs/common" ) var waitForEventTimeout = 5 * time.Second diff --git a/rpc/client/httpclient.go b/rpc/client/httpclient.go index 4b85bf01d..a9c64f5da 100644 --- a/rpc/client/httpclient.go +++ b/rpc/client/httpclient.go @@ -7,11 +7,11 @@ import ( "github.com/pkg/errors" amino "github.com/tendermint/go-amino" + cmn "github.com/tendermint/tendermint/libs/common" tmpubsub "github.com/tendermint/tendermint/libs/pubsub" ctypes "github.com/tendermint/tendermint/rpc/core/types" rpcclient "github.com/tendermint/tendermint/rpc/lib/client" "github.com/tendermint/tendermint/types" - cmn "github.com/tendermint/tendermint/libs/common" ) /* diff --git a/rpc/client/interface.go b/rpc/client/interface.go index f939c855b..f34410c5b 100644 --- a/rpc/client/interface.go +++ b/rpc/client/interface.go @@ -21,9 +21,9 @@ implementation. */ import ( + cmn "github.com/tendermint/tendermint/libs/common" ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" - cmn "github.com/tendermint/tendermint/libs/common" ) // ABCIClient groups together the functionality that principally diff --git a/rpc/client/mock/abci.go b/rpc/client/mock/abci.go index 4502c087a..022e4f363 100644 --- a/rpc/client/mock/abci.go +++ b/rpc/client/mock/abci.go @@ -2,11 +2,11 @@ package mock import ( abci "github.com/tendermint/tendermint/abci/types" + cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/rpc/client" ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" "github.com/tendermint/tendermint/version" - cmn "github.com/tendermint/tendermint/libs/common" ) // ABCIApp will send all abci related request to the named app, diff --git a/rpc/client/mock/abci_test.go b/rpc/client/mock/abci_test.go index bcf443cf0..327ec9e7b 100644 --- a/rpc/client/mock/abci_test.go +++ b/rpc/client/mock/abci_test.go @@ -11,11 +11,11 @@ import ( "github.com/tendermint/tendermint/abci/example/kvstore" abci "github.com/tendermint/tendermint/abci/types" + cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/rpc/client" "github.com/tendermint/tendermint/rpc/client/mock" ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" - cmn "github.com/tendermint/tendermint/libs/common" ) func TestABCIMock(t *testing.T) { diff --git a/rpc/client/mock/client.go b/rpc/client/mock/client.go index 955df6277..c57878499 100644 --- a/rpc/client/mock/client.go +++ b/rpc/client/mock/client.go @@ -16,11 +16,11 @@ package mock import ( "reflect" + cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/rpc/client" "github.com/tendermint/tendermint/rpc/core" ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" - cmn "github.com/tendermint/tendermint/libs/common" ) // Client wraps arbitrary implementations of the various interfaces. diff --git a/rpc/client/mock/status_test.go b/rpc/client/mock/status_test.go index 8e3c15061..fa64c6a83 100644 --- a/rpc/client/mock/status_test.go +++ b/rpc/client/mock/status_test.go @@ -6,9 +6,9 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/rpc/client/mock" ctypes "github.com/tendermint/tendermint/rpc/core/types" - cmn "github.com/tendermint/tendermint/libs/common" ) func TestStatus(t *testing.T) { diff --git a/rpc/core/mempool.go b/rpc/core/mempool.go index ecc41ce12..47776d3e4 100644 --- a/rpc/core/mempool.go +++ b/rpc/core/mempool.go @@ -8,9 +8,9 @@ import ( "github.com/pkg/errors" abci "github.com/tendermint/tendermint/abci/types" + cmn "github.com/tendermint/tendermint/libs/common" ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" - cmn "github.com/tendermint/tendermint/libs/common" ) //----------------------------------------------------------------------------- diff --git a/rpc/core/pipe.go b/rpc/core/pipe.go index 0125ffae2..9c162e9e4 100644 --- a/rpc/core/pipe.go +++ b/rpc/core/pipe.go @@ -5,13 +5,13 @@ import ( "github.com/tendermint/tendermint/consensus" crypto "github.com/tendermint/tendermint/crypto" + dbm "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/proxy" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/state/txindex" "github.com/tendermint/tendermint/types" - dbm "github.com/tendermint/tendermint/libs/db" - "github.com/tendermint/tendermint/libs/log" ) const ( diff --git a/rpc/lib/client/ws_client.go b/rpc/lib/client/ws_client.go index 9a07c8676..cff285222 100644 --- a/rpc/lib/client/ws_client.go +++ b/rpc/lib/client/ws_client.go @@ -14,8 +14,8 @@ import ( metrics "github.com/rcrowley/go-metrics" "github.com/tendermint/go-amino" - types "github.com/tendermint/tendermint/rpc/lib/types" cmn "github.com/tendermint/tendermint/libs/common" + types "github.com/tendermint/tendermint/rpc/lib/types" ) const ( diff --git a/rpc/lib/server/handlers_test.go b/rpc/lib/server/handlers_test.go index 3471eb791..6004959ae 100644 --- a/rpc/lib/server/handlers_test.go +++ b/rpc/lib/server/handlers_test.go @@ -14,9 +14,9 @@ import ( "github.com/stretchr/testify/require" amino "github.com/tendermint/go-amino" + "github.com/tendermint/tendermint/libs/log" rs "github.com/tendermint/tendermint/rpc/lib/server" types "github.com/tendermint/tendermint/rpc/lib/types" - "github.com/tendermint/tendermint/libs/log" ) ////////////////////////////////////////////////////////////////////////////// diff --git a/rpc/lib/server/http_server.go b/rpc/lib/server/http_server.go index dd95d823a..ff7173a10 100644 --- a/rpc/lib/server/http_server.go +++ b/rpc/lib/server/http_server.go @@ -14,8 +14,8 @@ import ( "github.com/pkg/errors" "golang.org/x/net/netutil" - types "github.com/tendermint/tendermint/rpc/lib/types" "github.com/tendermint/tendermint/libs/log" + types "github.com/tendermint/tendermint/rpc/lib/types" ) // Config is an RPC server configuration. diff --git a/rpc/lib/test/main.go b/rpc/lib/test/main.go index cb9560e12..544284b9c 100644 --- a/rpc/lib/test/main.go +++ b/rpc/lib/test/main.go @@ -6,9 +6,9 @@ import ( "os" amino "github.com/tendermint/go-amino" - rpcserver "github.com/tendermint/tendermint/rpc/lib/server" cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/log" + rpcserver "github.com/tendermint/tendermint/rpc/lib/server" ) var routes = map[string]*rpcserver.RPCFunc{ diff --git a/state/errors.go b/state/errors.go index d40c7e141..6010ed9bb 100644 --- a/state/errors.go +++ b/state/errors.go @@ -1,8 +1,6 @@ package state -import ( - cmn "github.com/tendermint/tendermint/libs/common" -) +import "fmt" type ( ErrInvalidBlock error @@ -48,32 +46,32 @@ type ( ) func (e ErrUnknownBlock) Error() string { - return cmn.Fmt("Could not find block #%d", e.Height) + return fmt.Sprintf("Could not find block #%d", e.Height) } func (e ErrBlockHashMismatch) Error() string { - return cmn.Fmt("App block hash (%X) does not match core block hash (%X) for height %d", e.AppHash, e.CoreHash, e.Height) + return fmt.Sprintf("App block hash (%X) does not match core block hash (%X) for height %d", e.AppHash, e.CoreHash, e.Height) } func (e ErrAppBlockHeightTooHigh) Error() string { - return cmn.Fmt("App block height (%d) is higher than core (%d)", e.AppHeight, e.CoreHeight) + return fmt.Sprintf("App block height (%d) is higher than core (%d)", e.AppHeight, e.CoreHeight) } func (e ErrLastStateMismatch) Error() string { - return cmn.Fmt("Latest tendermint block (%d) LastAppHash (%X) does not match app's AppHash (%X)", e.Height, e.Core, e.App) + return fmt.Sprintf("Latest tendermint block (%d) LastAppHash (%X) does not match app's AppHash (%X)", e.Height, e.Core, e.App) } func (e ErrStateMismatch) Error() string { - return cmn.Fmt("State after replay does not match saved state. Got ----\n%v\nExpected ----\n%v\n", e.Got, e.Expected) + return fmt.Sprintf("State after replay does not match saved state. Got ----\n%v\nExpected ----\n%v\n", e.Got, e.Expected) } func (e ErrNoValSetForHeight) Error() string { - return cmn.Fmt("Could not find validator set for height #%d", e.Height) + return fmt.Sprintf("Could not find validator set for height #%d", e.Height) } func (e ErrNoConsensusParamsForHeight) Error() string { - return cmn.Fmt("Could not find consensus params for height #%d", e.Height) + return fmt.Sprintf("Could not find consensus params for height #%d", e.Height) } func (e ErrNoABCIResponsesForHeight) Error() string { - return cmn.Fmt("Could not find results for height #%d", e.Height) + return fmt.Sprintf("Could not find results for height #%d", e.Height) } diff --git a/state/state_test.go b/state/state_test.go index 93ae8ca9a..211d5fdc9 100644 --- a/state/state_test.go +++ b/state/state_test.go @@ -40,11 +40,11 @@ func TestStateCopy(t *testing.T) { stateCopy := state.Copy() assert.True(state.Equals(stateCopy), - cmn.Fmt("expected state and its copy to be identical.\ngot: %v\nexpected: %v\n", + fmt.Sprintf("expected state and its copy to be identical.\ngot: %v\nexpected: %v\n", stateCopy, state)) stateCopy.LastBlockHeight++ - assert.False(state.Equals(stateCopy), cmn.Fmt(`expected states to be different. got same + assert.False(state.Equals(stateCopy), fmt.Sprintf(`expected states to be different. got same %v`, state)) } @@ -60,7 +60,7 @@ func TestStateSaveLoad(t *testing.T) { loadedState := LoadState(stateDB) assert.True(state.Equals(loadedState), - cmn.Fmt("expected state and its copy to be identical.\ngot: %v\nexpected: %v\n", + fmt.Sprintf("expected state and its copy to be identical.\ngot: %v\nexpected: %v\n", loadedState, state)) } @@ -86,7 +86,7 @@ func TestABCIResponsesSaveLoad1(t *testing.T) { loadedABCIResponses, err := LoadABCIResponses(stateDB, block.Height) assert.Nil(err) assert.Equal(abciResponses, loadedABCIResponses, - cmn.Fmt("ABCIResponses don't match:\ngot: %v\nexpected: %v\n", + fmt.Sprintf("ABCIResponses don't match:\ngot: %v\nexpected: %v\n", loadedABCIResponses, abciResponses)) } diff --git a/state/store.go b/state/store.go index ea10b27c1..2f90c747e 100644 --- a/state/store.go +++ b/state/store.go @@ -12,15 +12,15 @@ import ( //------------------------------------------------------------------------ func calcValidatorsKey(height int64) []byte { - return []byte(cmn.Fmt("validatorsKey:%v", height)) + return []byte(fmt.Sprintf("validatorsKey:%v", height)) } func calcConsensusParamsKey(height int64) []byte { - return []byte(cmn.Fmt("consensusParamsKey:%v", height)) + return []byte(fmt.Sprintf("consensusParamsKey:%v", height)) } func calcABCIResponsesKey(height int64) []byte { - return []byte(cmn.Fmt("abciResponsesKey:%v", height)) + return []byte(fmt.Sprintf("abciResponsesKey:%v", height)) } // LoadStateFromDBOrGenesisFile loads the most recent state from the database, @@ -71,7 +71,7 @@ func loadState(db dbm.DB, key []byte) (state State) { err := cdc.UnmarshalBinaryBare(buf, &state) if err != nil { // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED - cmn.Exit(cmn.Fmt(`LoadState: Data has been corrupted or its spec has changed: + cmn.Exit(fmt.Sprintf(`LoadState: Data has been corrupted or its spec has changed: %v\n`, err)) } // TODO: ensure that buf is completely read. @@ -144,7 +144,7 @@ func LoadABCIResponses(db dbm.DB, height int64) (*ABCIResponses, error) { err := cdc.UnmarshalBinaryBare(buf, abciResponses) if err != nil { // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED - cmn.Exit(cmn.Fmt(`LoadABCIResponses: Data has been corrupted or its spec has + cmn.Exit(fmt.Sprintf(`LoadABCIResponses: Data has been corrupted or its spec has changed: %v\n`, err)) } // TODO: ensure that buf is completely read. @@ -207,7 +207,7 @@ func loadValidatorsInfo(db dbm.DB, height int64) *ValidatorsInfo { err := cdc.UnmarshalBinaryBare(buf, v) if err != nil { // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED - cmn.Exit(cmn.Fmt(`LoadValidators: Data has been corrupted or its spec has changed: + cmn.Exit(fmt.Sprintf(`LoadValidators: Data has been corrupted or its spec has changed: %v\n`, err)) } // TODO: ensure that buf is completely read. @@ -278,7 +278,7 @@ func loadConsensusParamsInfo(db dbm.DB, height int64) *ConsensusParamsInfo { err := cdc.UnmarshalBinaryBare(buf, paramsInfo) if err != nil { // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED - cmn.Exit(cmn.Fmt(`LoadConsensusParams: Data has been corrupted or its spec has changed: + cmn.Exit(fmt.Sprintf(`LoadConsensusParams: Data has been corrupted or its spec has changed: %v\n`, err)) } // TODO: ensure that buf is completely read. diff --git a/state/validation.go b/state/validation.go index 4686d82b2..5c88d97b4 100644 --- a/state/validation.go +++ b/state/validation.go @@ -5,7 +5,7 @@ import ( "errors" "fmt" - "github.com/tendermint/go-crypto/tmhash" + "github.com/tendermint/tendermint/crypto/tmhash" dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/types" ) diff --git a/types/genesis.go b/types/genesis.go index 220ee0e0e..c4f69980e 100644 --- a/types/genesis.go +++ b/types/genesis.go @@ -2,6 +2,7 @@ package types import ( "encoding/json" + "fmt" "io/ioutil" "time" @@ -107,7 +108,7 @@ func GenesisDocFromFile(genDocFile string) (*GenesisDoc, error) { } genDoc, err := GenesisDocFromJSON(jsonBlob) if err != nil { - return nil, cmn.ErrorWrap(err, cmn.Fmt("Error reading GenesisDoc at %v", genDocFile)) + return nil, cmn.ErrorWrap(err, fmt.Sprintf("Error reading GenesisDoc at %v", genDocFile)) } return genDoc, nil } diff --git a/types/proto3_test.go b/types/proto3_test.go index 50645abf3..c9dfa35a9 100644 --- a/types/proto3_test.go +++ b/types/proto3_test.go @@ -63,10 +63,10 @@ func TestProto3Compatibility(t *testing.T) { assert.Equal(t, ab, pb, "encoding doesn't match") emptyLastBlockPb := proto3.Header{ - ChainID: "cosmos", - Height: 150, - Time: &proto3.Timestamp{Seconds: seconds, Nanos: nanos}, - NumTxs: 7, + ChainID: "cosmos", + Height: 150, + Time: &proto3.Timestamp{Seconds: seconds, Nanos: nanos}, + NumTxs: 7, TotalTxs: 100, LastCommitHash: []byte("commit hash"), DataHash: []byte("data hash"), diff --git a/types/protobuf_test.go b/types/protobuf_test.go index 8c1c39f18..caad5c8f9 100644 --- a/types/protobuf_test.go +++ b/types/protobuf_test.go @@ -111,10 +111,10 @@ func TestABCIEvidence(t *testing.T) { type pubKeyEddie struct{} -func (pubKeyEddie) Address() Address { return []byte{} } -func (pubKeyEddie) Bytes() []byte { return []byte{} } +func (pubKeyEddie) Address() Address { return []byte{} } +func (pubKeyEddie) Bytes() []byte { return []byte{} } func (pubKeyEddie) VerifyBytes(msg []byte, sig []byte) bool { return false } -func (pubKeyEddie) Equals(crypto.PubKey) bool { return false } +func (pubKeyEddie) Equals(crypto.PubKey) bool { return false } func TestABCIValidatorFromPubKeyAndPower(t *testing.T) { pubkey := ed25519.GenPrivKey().PubKey() diff --git a/types/validator_set_test.go b/types/validator_set_test.go index ba5fefa2b..ad9a2b00f 100644 --- a/types/validator_set_test.go +++ b/types/validator_set_test.go @@ -2,6 +2,7 @@ package types import ( "bytes" + "fmt" "math" "strings" "testing" @@ -219,7 +220,7 @@ func TestProposerSelection3(t *testing.T) { got := vset.GetProposer().Address expected := proposerOrder[j%4].Address if !bytes.Equal(got, expected) { - t.Fatalf(cmn.Fmt("vset.Proposer (%X) does not match expected proposer (%X) for (%d, %d)", got, expected, i, j)) + t.Fatalf(fmt.Sprintf("vset.Proposer (%X) does not match expected proposer (%X) for (%d, %d)", got, expected, i, j)) } // serialize, deserialize, check proposer @@ -229,7 +230,7 @@ func TestProposerSelection3(t *testing.T) { computed := vset.GetProposer() // findGetProposer() if i != 0 { if !bytes.Equal(got, computed.Address) { - t.Fatalf(cmn.Fmt("vset.Proposer (%X) does not match computed proposer (%X) for (%d, %d)", got, computed.Address, i, j)) + t.Fatalf(fmt.Sprintf("vset.Proposer (%X) does not match computed proposer (%X) for (%d, %d)", got, computed.Address, i, j)) } }