Browse Source

change use of errors.Wrap to fmt.Errorf with %w verb

Closes #4603

Commands used (VIM):

```
:args `rg -l errors.Wrap`
:argdo normal @q | update
```

where q is a macros rewriting the `errors.Wrap` to `fmt.Errorf`.
pull/4826/head
Anton Kaliaev 4 years ago
committed by GitHub
parent
commit
b7b721c484
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
90 changed files with 321 additions and 391 deletions
  1. +4
    -4
      blockchain/v0/reactor_test.go
  2. +3
    -4
      blockchain/v1/reactor_test.go
  3. +5
    -5
      blockchain/v2/reactor_test.go
  4. +3
    -3
      cmd/tendermint/commands/debug/dump.go
  5. +2
    -3
      cmd/tendermint/commands/debug/io.go
  6. +3
    -3
      cmd/tendermint/commands/debug/kill.go
  7. +5
    -7
      cmd/tendermint/commands/debug/util.go
  8. +1
    -2
      cmd/tendermint/commands/init.go
  9. +3
    -3
      cmd/tendermint/commands/lite.go
  10. +3
    -4
      cmd/tendermint/commands/run_node.go
  11. +2
    -3
      cmd/tendermint/commands/show_validator.go
  12. +1
    -2
      cmd/tendermint/commands/testnet.go
  13. +1
    -2
      consensus/common_test.go
  14. +3
    -4
      consensus/reactor.go
  15. +1
    -1
      consensus/reactor_test.go
  16. +2
    -2
      consensus/replay_file.go
  17. +3
    -4
      consensus/state.go
  18. +1
    -3
      consensus/wal.go
  19. +5
    -7
      consensus/wal_generator.go
  20. +8
    -8
      crypto/merkle/proof.go
  21. +3
    -4
      crypto/merkle/proof_key_path.go
  22. +4
    -6
      crypto/merkle/proof_simple_value.go
  23. +4
    -3
      crypto/merkle/proof_test.go
  24. +6
    -7
      crypto/merkle/simple_proof.go
  25. +13
    -13
      docs/guides/go-built-in.md
  26. +2
    -3
      libs/async/async.go
  27. +2
    -2
      libs/async/async_test.go
  28. +5
    -4
      libs/bech32/bech32.go
  29. +2
    -3
      libs/cli/flags/log_level.go
  30. +6
    -3
      libs/cli/setup.go
  31. +7
    -7
      libs/cli/setup_test.go
  32. +3
    -3
      libs/pubsub/pubsub.go
  33. +4
    -6
      libs/pubsub/query/query.go
  34. +1
    -1
      libs/tempfile/tempfile.go
  35. +1
    -1
      libs/tempfile/tempfile_test.go
  36. +1
    -2
      lite2/client.go
  37. +2
    -3
      lite2/proxy/proxy.go
  38. +3
    -4
      lite2/store/db/db.go
  39. +3
    -3
      lite2/trust_options.go
  40. +11
    -11
      lite2/verifier.go
  41. +1
    -2
      mempool/errors.go
  42. +1
    -1
      mempool/reactor_test.go
  43. +10
    -10
      node/node.go
  44. +2
    -3
      p2p/conn/connection.go
  45. +3
    -2
      p2p/conn/secret_connection.go
  46. +2
    -3
      p2p/netaddress.go
  47. +3
    -4
      p2p/peer_test.go
  48. +3
    -4
      p2p/pex/pex_reactor.go
  49. +3
    -5
      p2p/switch.go
  50. +1
    -3
      p2p/test_util.go
  51. +1
    -2
      p2p/transport.go
  52. +3
    -5
      privval/signer_client.go
  53. +5
    -7
      privval/signer_endpoint.go
  54. +1
    -2
      privval/socket_dialers.go
  55. +1
    -2
      privval/socket_dialers_test.go
  56. +5
    -5
      privval/utils.go
  57. +3
    -2
      privval/utils_test.go
  58. +2
    -3
      proxy/client.go
  59. +4
    -4
      rpc/client/helpers.go
  60. +3
    -4
      rpc/client/http/http.go
  61. +4
    -5
      rpc/client/local/local.go
  62. +1
    -2
      rpc/client/mock/abci_test.go
  63. +2
    -4
      rpc/core/events.go
  64. +2
    -3
      rpc/core/mempool.go
  65. +1
    -2
      rpc/core/net.go
  66. +1
    -2
      rpc/core/tx.go
  67. +13
    -13
      rpc/lib/client/decode.go
  68. +9
    -10
      rpc/lib/client/http_json_client.go
  69. +4
    -5
      rpc/lib/client/http_uri_client.go
  70. +1
    -2
      rpc/lib/client/ws_client.go
  71. +6
    -8
      rpc/lib/server/http_json_handler.go
  72. +7
    -8
      rpc/lib/server/http_params.go
  73. +3
    -3
      rpc/lib/server/http_server.go
  74. +3
    -4
      rpc/lib/server/http_uri_handler.go
  75. +2
    -3
      rpc/lib/server/rpc_func.go
  76. +2
    -3
      rpc/lib/server/ws_handler.go
  77. +1
    -3
      rpc/lib/types/types.go
  78. +2
    -3
      rpc/lib/types/types_test.go
  79. +4
    -6
      state/txindex/kv/kv.go
  80. +6
    -8
      store/store.go
  81. +1
    -2
      store/store_test.go
  82. +1
    -2
      types/block.go
  83. +2
    -3
      types/block_meta.go
  84. +3
    -4
      types/evidence.go
  85. +6
    -7
      types/genesis.go
  86. +11
    -11
      types/params.go
  87. +4
    -5
      types/part_set.go
  88. +3
    -4
      types/test_util.go
  89. +5
    -7
      types/validator_set.go
  90. +12
    -13
      types/vote_set.go

+ 4
- 4
blockchain/v0/reactor_test.go View File

@ -1,12 +1,12 @@
package v0 package v0
import ( import (
"fmt"
"os" "os"
"sort" "sort"
"testing" "testing"
"time" "time"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
dbm "github.com/tendermint/tm-db" dbm "github.com/tendermint/tm-db"
@ -64,7 +64,7 @@ func newBlockchainReactor(
proxyApp := proxy.NewAppConns(cc) proxyApp := proxy.NewAppConns(cc)
err := proxyApp.Start() err := proxyApp.Start()
if err != nil { if err != nil {
panic(errors.Wrap(err, "error start app"))
panic(fmt.Errorf("error start app: %w", err))
} }
blockDB := dbm.NewMemDB() blockDB := dbm.NewMemDB()
@ -73,7 +73,7 @@ func newBlockchainReactor(
state, err := sm.LoadStateFromDBOrGenesisDoc(stateDB, genDoc) state, err := sm.LoadStateFromDBOrGenesisDoc(stateDB, genDoc)
if err != nil { if err != nil {
panic(errors.Wrap(err, "error constructing state from genesis file"))
panic(fmt.Errorf("error constructing state from genesis file: %w", err))
} }
// Make the BlockchainReactor itself. // Make the BlockchainReactor itself.
@ -114,7 +114,7 @@ func newBlockchainReactor(
state, _, err = blockExec.ApplyBlock(state, blockID, thisBlock) state, _, err = blockExec.ApplyBlock(state, blockID, thisBlock)
if err != nil { if err != nil {
panic(errors.Wrap(err, "error apply block"))
panic(fmt.Errorf("error apply block: %w", err))
} }
blockStore.SaveBlock(thisBlock, thisParts, lastCommit) blockStore.SaveBlock(thisBlock, thisParts, lastCommit)


+ 3
- 4
blockchain/v1/reactor_test.go View File

@ -8,7 +8,6 @@ import (
"testing" "testing"
"time" "time"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@ -94,7 +93,7 @@ func newBlockchainReactor(
proxyApp := proxy.NewAppConns(cc) proxyApp := proxy.NewAppConns(cc)
err := proxyApp.Start() err := proxyApp.Start()
if err != nil { if err != nil {
panic(errors.Wrap(err, "error start app"))
panic(fmt.Errorf("error start app: %w", err))
} }
blockDB := dbm.NewMemDB() blockDB := dbm.NewMemDB()
@ -103,7 +102,7 @@ func newBlockchainReactor(
state, err := sm.LoadStateFromDBOrGenesisDoc(stateDB, genDoc) state, err := sm.LoadStateFromDBOrGenesisDoc(stateDB, genDoc)
if err != nil { if err != nil {
panic(errors.Wrap(err, "error constructing state from genesis file"))
panic(fmt.Errorf("error constructing state from genesis file: %w", err))
} }
// Make the BlockchainReactor itself. // Make the BlockchainReactor itself.
@ -133,7 +132,7 @@ func newBlockchainReactor(
state, _, err = blockExec.ApplyBlock(state, blockID, thisBlock) state, _, err = blockExec.ApplyBlock(state, blockID, thisBlock)
if err != nil { if err != nil {
panic(errors.Wrap(err, "error apply block"))
panic(fmt.Errorf("error apply block: %w", err))
} }
blockStore.SaveBlock(thisBlock, thisParts, lastCommit) blockStore.SaveBlock(thisBlock, thisParts, lastCommit)


+ 5
- 5
blockchain/v2/reactor_test.go View File

@ -1,6 +1,7 @@
package v2 package v2
import ( import (
"fmt"
"net" "net"
"os" "os"
"sort" "sort"
@ -8,7 +9,6 @@ import (
"testing" "testing"
"time" "time"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
dbm "github.com/tendermint/tm-db" dbm "github.com/tendermint/tm-db"
@ -149,7 +149,7 @@ func newTestReactor(p testReactorParams) *BlockchainReactor {
proxyApp := proxy.NewAppConns(cc) proxyApp := proxy.NewAppConns(cc)
err := proxyApp.Start() err := proxyApp.Start()
if err != nil { if err != nil {
panic(errors.Wrap(err, "error start app"))
panic(fmt.Errorf("error start app: %w", err))
} }
db := dbm.NewMemDB() db := dbm.NewMemDB()
appl = sm.NewBlockExecutor(db, p.logger, proxyApp.Consensus(), mock.Mempool{}, sm.MockEvidencePool{}) appl = sm.NewBlockExecutor(db, p.logger, proxyApp.Consensus(), mock.Mempool{}, sm.MockEvidencePool{})
@ -480,7 +480,7 @@ func newReactorStore(
proxyApp := proxy.NewAppConns(cc) proxyApp := proxy.NewAppConns(cc)
err := proxyApp.Start() err := proxyApp.Start()
if err != nil { if err != nil {
panic(errors.Wrap(err, "error start app"))
panic(fmt.Errorf("error start app: %w", err))
} }
stateDB := dbm.NewMemDB() stateDB := dbm.NewMemDB()
@ -488,7 +488,7 @@ func newReactorStore(
state, err := sm.LoadStateFromDBOrGenesisDoc(stateDB, genDoc) state, err := sm.LoadStateFromDBOrGenesisDoc(stateDB, genDoc)
if err != nil { if err != nil {
panic(errors.Wrap(err, "error constructing state from genesis file"))
panic(fmt.Errorf("error constructing state from genesis file: %w", err))
} }
db := dbm.NewMemDB() db := dbm.NewMemDB()
@ -524,7 +524,7 @@ func newReactorStore(
state, _, err = blockExec.ApplyBlock(state, blockID, thisBlock) state, _, err = blockExec.ApplyBlock(state, blockID, thisBlock)
if err != nil { if err != nil {
panic(errors.Wrap(err, "error apply block"))
panic(fmt.Errorf("error apply block: %w", err))
} }
blockStore.SaveBlock(thisBlock, thisParts, lastCommit) blockStore.SaveBlock(thisBlock, thisParts, lastCommit)


+ 3
- 3
cmd/tendermint/commands/debug/dump.go View File

@ -1,13 +1,13 @@
package debug package debug
import ( import (
"errors"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"time" "time"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
@ -55,13 +55,13 @@ func dumpCmdHandler(_ *cobra.Command, args []string) error {
if _, err := os.Stat(outDir); os.IsNotExist(err) { if _, err := os.Stat(outDir); os.IsNotExist(err) {
if err := os.Mkdir(outDir, os.ModePerm); err != nil { if err := os.Mkdir(outDir, os.ModePerm); err != nil {
return errors.Wrap(err, "failed to create output directory")
return fmt.Errorf("failed to create output directory: %w", err)
} }
} }
rpc, err := rpchttp.New(nodeRPCAddr, "/websocket") rpc, err := rpchttp.New(nodeRPCAddr, "/websocket")
if err != nil { if err != nil {
return errors.Wrap(err, "failed to create new http client")
return fmt.Errorf("failed to create new http client: %w", err)
} }
home := viper.GetString(cli.HomeFlag) home := viper.GetString(cli.HomeFlag)


+ 2
- 3
cmd/tendermint/commands/debug/io.go View File

@ -3,14 +3,13 @@ package debug
import ( import (
"archive/zip" "archive/zip"
"encoding/json" "encoding/json"
"fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/pkg/errors"
) )
// zipDir zips all the contents found in src, including both files and // zipDir zips all the contents found in src, including both files and
@ -110,7 +109,7 @@ func copyFile(src, dest string) error {
func writeStateJSONToFile(state interface{}, dir, filename string) error { func writeStateJSONToFile(state interface{}, dir, filename string) error {
stateJSON, err := json.MarshalIndent(state, "", " ") stateJSON, err := json.MarshalIndent(state, "", " ")
if err != nil { if err != nil {
return errors.Wrap(err, "failed to encode state dump")
return fmt.Errorf("failed to encode state dump: %w", err)
} }
return ioutil.WriteFile(path.Join(dir, filename), stateJSON, os.ModePerm) return ioutil.WriteFile(path.Join(dir, filename), stateJSON, os.ModePerm)


+ 3
- 3
cmd/tendermint/commands/debug/kill.go View File

@ -1,6 +1,7 @@
package debug package debug
import ( import (
"errors"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"os" "os"
@ -10,7 +11,6 @@ import (
"syscall" "syscall"
"time" "time"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
@ -46,7 +46,7 @@ func killCmdHandler(cmd *cobra.Command, args []string) error {
rpc, err := rpchttp.New(nodeRPCAddr, "/websocket") rpc, err := rpchttp.New(nodeRPCAddr, "/websocket")
if err != nil { if err != nil {
return errors.Wrap(err, "failed to create new http client")
return fmt.Errorf("failed to create new http client: %w", err)
} }
home := viper.GetString(cli.HomeFlag) home := viper.GetString(cli.HomeFlag)
@ -58,7 +58,7 @@ func killCmdHandler(cmd *cobra.Command, args []string) error {
// relevant files and directories that will be compressed into a file. // relevant files and directories that will be compressed into a file.
tmpDir, err := ioutil.TempDir(os.TempDir(), "tendermint_debug_tmp") tmpDir, err := ioutil.TempDir(os.TempDir(), "tendermint_debug_tmp")
if err != nil { if err != nil {
return errors.Wrap(err, "failed to create temporary directory")
return fmt.Errorf("failed to create temporary directory: %w", err)
} }
defer os.RemoveAll(tmpDir) defer os.RemoveAll(tmpDir)


+ 5
- 7
cmd/tendermint/commands/debug/util.go View File

@ -8,8 +8,6 @@ import (
"path" "path"
"path/filepath" "path/filepath"
"github.com/pkg/errors"
cfg "github.com/tendermint/tendermint/config" cfg "github.com/tendermint/tendermint/config"
rpchttp "github.com/tendermint/tendermint/rpc/client/http" rpchttp "github.com/tendermint/tendermint/rpc/client/http"
) )
@ -19,7 +17,7 @@ import (
func dumpStatus(rpc *rpchttp.HTTP, dir, filename string) error { func dumpStatus(rpc *rpchttp.HTTP, dir, filename string) error {
status, err := rpc.Status() status, err := rpc.Status()
if err != nil { if err != nil {
return errors.Wrap(err, "failed to get node status")
return fmt.Errorf("failed to get node status: %w", err)
} }
return writeStateJSONToFile(status, dir, filename) return writeStateJSONToFile(status, dir, filename)
@ -30,7 +28,7 @@ func dumpStatus(rpc *rpchttp.HTTP, dir, filename string) error {
func dumpNetInfo(rpc *rpchttp.HTTP, dir, filename string) error { func dumpNetInfo(rpc *rpchttp.HTTP, dir, filename string) error {
netInfo, err := rpc.NetInfo() netInfo, err := rpc.NetInfo()
if err != nil { if err != nil {
return errors.Wrap(err, "failed to get node network information")
return fmt.Errorf("failed to get node network information: %w", err)
} }
return writeStateJSONToFile(netInfo, dir, filename) return writeStateJSONToFile(netInfo, dir, filename)
@ -41,7 +39,7 @@ func dumpNetInfo(rpc *rpchttp.HTTP, dir, filename string) error {
func dumpConsensusState(rpc *rpchttp.HTTP, dir, filename string) error { func dumpConsensusState(rpc *rpchttp.HTTP, dir, filename string) error {
consDump, err := rpc.DumpConsensusState() consDump, err := rpc.DumpConsensusState()
if err != nil { if err != nil {
return errors.Wrap(err, "failed to get node consensus dump")
return fmt.Errorf("failed to get node consensus dump: %w", err)
} }
return writeStateJSONToFile(consDump, dir, filename) return writeStateJSONToFile(consDump, dir, filename)
@ -70,13 +68,13 @@ func dumpProfile(dir, addr, profile string, debug int) error {
resp, err := http.Get(endpoint) // nolint: gosec resp, err := http.Get(endpoint) // nolint: gosec
if err != nil { if err != nil {
return errors.Wrapf(err, "failed to query for %s profile", profile)
return fmt.Errorf("failed to query for %s profile: %w", profile, err)
} }
defer resp.Body.Close() defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body) body, err := ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
return errors.Wrapf(err, "failed to read %s profile response body", profile)
return fmt.Errorf("failed to read %s profile response body: %w", profile, err)
} }
return ioutil.WriteFile(path.Join(dir, fmt.Sprintf("%s.out", profile)), body, os.ModePerm) return ioutil.WriteFile(path.Join(dir, fmt.Sprintf("%s.out", profile)), body, os.ModePerm)


+ 1
- 2
cmd/tendermint/commands/init.go View File

@ -3,7 +3,6 @@ package commands
import ( import (
"fmt" "fmt"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
cfg "github.com/tendermint/tendermint/config" cfg "github.com/tendermint/tendermint/config"
@ -64,7 +63,7 @@ func initFilesWithConfig(config *cfg.Config) error {
} }
pubKey, err := pv.GetPubKey() pubKey, err := pv.GetPubKey()
if err != nil { if err != nil {
return errors.Wrap(err, "can't get pubkey")
return fmt.Errorf("can't get pubkey: %w", err)
} }
genDoc.Validators = []types.GenesisValidator{{ genDoc.Validators = []types.GenesisValidator{{
Address: pubKey.Address(), Address: pubKey.Address(),


+ 3
- 3
cmd/tendermint/commands/lite.go View File

@ -1,12 +1,12 @@
package commands package commands
import ( import (
"fmt"
"net/http" "net/http"
"os" "os"
"strings" "strings"
"time" "time"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/tendermint/go-amino" "github.com/tendermint/go-amino"
@ -102,7 +102,7 @@ func runProxy(cmd *cobra.Command, args []string) error {
db, err := dbm.NewGoLevelDB("lite-client-db", home) db, err := dbm.NewGoLevelDB("lite-client-db", home)
if err != nil { if err != nil {
return errors.Wrap(err, "new goleveldb")
return fmt.Errorf("new goleveldb: %w", err)
} }
var c *lite.Client var c *lite.Client
@ -135,7 +135,7 @@ func runProxy(cmd *cobra.Command, args []string) error {
rpcClient, err := rpchttp.New(primaryAddr, "/websocket") rpcClient, err := rpchttp.New(primaryAddr, "/websocket")
if err != nil { if err != nil {
return errors.Wrapf(err, "http client for %s", primaryAddr)
return fmt.Errorf("http client for %s: %w", primaryAddr, err)
} }
p := lproxy.Proxy{ p := lproxy.Proxy{
Addr: listenAddr, Addr: listenAddr,


+ 3
- 4
cmd/tendermint/commands/run_node.go View File

@ -7,7 +7,6 @@ import (
"io" "io"
"os" "os"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
cfg "github.com/tendermint/tendermint/config" cfg "github.com/tendermint/tendermint/config"
@ -138,18 +137,18 @@ func checkGenesisHash(config *cfg.Config) error {
// Calculate SHA-256 hash of the genesis file. // Calculate SHA-256 hash of the genesis file.
f, err := os.Open(config.GenesisFile()) f, err := os.Open(config.GenesisFile())
if err != nil { if err != nil {
return errors.Wrap(err, "can't open genesis file")
return fmt.Errorf("can't open genesis file: %w", err)
} }
defer f.Close() defer f.Close()
h := sha256.New() h := sha256.New()
if _, err := io.Copy(h, f); err != nil { if _, err := io.Copy(h, f); err != nil {
return errors.Wrap(err, "error when hashing genesis file")
return fmt.Errorf("error when hashing genesis file: %w", err)
} }
actualHash := h.Sum(nil) actualHash := h.Sum(nil)
// Compare with the flag. // Compare with the flag.
if !bytes.Equal(genesisHash, actualHash) { if !bytes.Equal(genesisHash, actualHash) {
return errors.Errorf(
return fmt.Errorf(
"--genesis_hash=%X does not match %s hash: %X", "--genesis_hash=%X does not match %s hash: %X",
genesisHash, config.GenesisFile(), actualHash) genesisHash, config.GenesisFile(), actualHash)
} }


+ 2
- 3
cmd/tendermint/commands/show_validator.go View File

@ -3,7 +3,6 @@ package commands
import ( import (
"fmt" "fmt"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
tmos "github.com/tendermint/tendermint/libs/os" tmos "github.com/tendermint/tendermint/libs/os"
@ -27,12 +26,12 @@ func showValidator(cmd *cobra.Command, args []string) error {
pubKey, err := pv.GetPubKey() pubKey, err := pv.GetPubKey()
if err != nil { if err != nil {
return errors.Wrap(err, "can't get pubkey")
return fmt.Errorf("can't get pubkey: %w", err)
} }
bz, err := cdc.MarshalJSON(pubKey) bz, err := cdc.MarshalJSON(pubKey)
if err != nil { if err != nil {
return errors.Wrap(err, "failed to marshal private validator pubkey")
return fmt.Errorf("failed to marshal private validator pubkey: %w", err)
} }
fmt.Println(string(bz)) fmt.Println(string(bz))


+ 1
- 2
cmd/tendermint/commands/testnet.go View File

@ -7,7 +7,6 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
@ -142,7 +141,7 @@ func testnetFiles(cmd *cobra.Command, args []string) error {
pubKey, err := pv.GetPubKey() pubKey, err := pv.GetPubKey()
if err != nil { if err != nil {
return errors.Wrap(err, "can't get pubkey")
return fmt.Errorf("can't get pubkey: %w", err)
} }
genVals[i] = types.GenesisValidator{ genVals[i] = types.GenesisValidator{
Address: pubKey.Address(), Address: pubKey.Address(),


+ 1
- 2
consensus/common_test.go View File

@ -13,7 +13,6 @@ import (
"time" "time"
"github.com/go-kit/kit/log/term" "github.com/go-kit/kit/log/term"
"github.com/pkg/errors"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"path" "path"
@ -92,7 +91,7 @@ func (vs *validatorStub) signVote(
pubKey, err := vs.PrivValidator.GetPubKey() pubKey, err := vs.PrivValidator.GetPubKey()
if err != nil { if err != nil {
return nil, errors.Wrap(err, "can't get pubkey")
return nil, fmt.Errorf("can't get pubkey: %w", err)
} }
vote := &types.Vote{ vote := &types.Vote{


+ 3
- 4
consensus/reactor.go View File

@ -1,13 +1,12 @@
package consensus package consensus
import ( import (
"errors"
"fmt" "fmt"
"reflect" "reflect"
"sync" "sync"
"time" "time"
"github.com/pkg/errors"
amino "github.com/tendermint/go-amino" amino "github.com/tendermint/go-amino"
cstypes "github.com/tendermint/tendermint/consensus/types" cstypes "github.com/tendermint/tendermint/consensus/types"
@ -1469,7 +1468,7 @@ func (m *NewValidBlockMessage) ValidateBasic() error {
m.BlockPartsHeader.Total) m.BlockPartsHeader.Total)
} }
if m.BlockParts.Size() > types.MaxBlockPartsCount { if m.BlockParts.Size() > types.MaxBlockPartsCount {
return errors.Errorf("blockParts bit array is too big: %d, max: %d", m.BlockParts.Size(), types.MaxBlockPartsCount)
return fmt.Errorf("blockParts bit array is too big: %d, max: %d", m.BlockParts.Size(), types.MaxBlockPartsCount)
} }
return nil return nil
} }
@ -1518,7 +1517,7 @@ func (m *ProposalPOLMessage) ValidateBasic() error {
return errors.New("empty ProposalPOL bit array") return errors.New("empty ProposalPOL bit array")
} }
if m.ProposalPOL.Size() > types.MaxVotesCount { if m.ProposalPOL.Size() > types.MaxVotesCount {
return errors.Errorf("ProposalPOL bit array is too big: %d, max: %d", m.ProposalPOL.Size(), types.MaxVotesCount)
return fmt.Errorf("proposalPOL bit array is too big: %d, max: %d", m.ProposalPOL.Size(), types.MaxVotesCount)
} }
return nil return nil
} }


+ 1
- 1
consensus/reactor_test.go View File

@ -773,7 +773,7 @@ func TestProposalPOLMessageValidateBasic(t *testing.T) {
{func(msg *ProposalPOLMessage) { msg.ProposalPOLRound = -1 }, "negative ProposalPOLRound"}, {func(msg *ProposalPOLMessage) { msg.ProposalPOLRound = -1 }, "negative ProposalPOLRound"},
{func(msg *ProposalPOLMessage) { msg.ProposalPOL = bits.NewBitArray(0) }, "empty ProposalPOL bit array"}, {func(msg *ProposalPOLMessage) { msg.ProposalPOL = bits.NewBitArray(0) }, "empty ProposalPOL bit array"},
{func(msg *ProposalPOLMessage) { msg.ProposalPOL = bits.NewBitArray(types.MaxVotesCount + 1) }, {func(msg *ProposalPOLMessage) { msg.ProposalPOL = bits.NewBitArray(types.MaxVotesCount + 1) },
"ProposalPOL bit array is too big: 10001, max: 10000"},
"proposalPOL bit array is too big: 10001, max: 10000"},
} }
for i, tc := range testCases { for i, tc := range testCases {


+ 2
- 2
consensus/replay_file.go View File

@ -3,13 +3,13 @@ package consensus
import ( import (
"bufio" "bufio"
"context" "context"
"errors"
"fmt" "fmt"
"io" "io"
"os" "os"
"strconv" "strconv"
"strings" "strings"
"github.com/pkg/errors"
dbm "github.com/tendermint/tm-db" dbm "github.com/tendermint/tm-db"
cfg "github.com/tendermint/tendermint/config" cfg "github.com/tendermint/tendermint/config"
@ -55,7 +55,7 @@ func (cs *State) ReplayFile(file string, console bool) error {
ctx := context.Background() ctx := context.Background()
newStepSub, err := cs.eventBus.Subscribe(ctx, subscriber, types.EventQueryNewRoundStep) newStepSub, err := cs.eventBus.Subscribe(ctx, subscriber, types.EventQueryNewRoundStep)
if err != nil { if err != nil {
return errors.Errorf("failed to subscribe %s to %v", subscriber, types.EventQueryNewRoundStep)
return fmt.Errorf("failed to subscribe %s to %v", subscriber, types.EventQueryNewRoundStep)
} }
defer cs.eventBus.Unsubscribe(ctx, subscriber, types.EventQueryNewRoundStep) defer cs.eventBus.Unsubscribe(ctx, subscriber, types.EventQueryNewRoundStep)


+ 3
- 4
consensus/state.go View File

@ -2,14 +2,13 @@ package consensus
import ( import (
"bytes" "bytes"
"errors"
"fmt" "fmt"
"reflect" "reflect"
"runtime/debug" "runtime/debug"
"sync" "sync"
"time" "time"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/libs/fail" "github.com/tendermint/tendermint/libs/fail"
"github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/libs/log"
tmos "github.com/tendermint/tendermint/libs/os" tmos "github.com/tendermint/tendermint/libs/os"
@ -1738,7 +1737,7 @@ func (cs *State) tryAddVote(vote *types.Vote, peerID p2p.ID) (bool, error) {
} else if voteErr, ok := err.(*types.ErrVoteConflictingVotes); ok { } else if voteErr, ok := err.(*types.ErrVoteConflictingVotes); ok {
pubKey, err := cs.privValidator.GetPubKey() pubKey, err := cs.privValidator.GetPubKey()
if err != nil { if err != nil {
return false, errors.Wrap(err, "can't get pubkey")
return false, fmt.Errorf("can't get pubkey: %w", err)
} }
if bytes.Equal(vote.ValidatorAddress, pubKey.Address()) { if bytes.Equal(vote.ValidatorAddress, pubKey.Address()) {
@ -1945,7 +1944,7 @@ func (cs *State) signVote(
pubKey, err := cs.privValidator.GetPubKey() pubKey, err := cs.privValidator.GetPubKey()
if err != nil { if err != nil {
return nil, errors.Wrap(err, "can't get pubkey")
return nil, fmt.Errorf("can't get pubkey: %w", err)
} }
addr := pubKey.Address() addr := pubKey.Address()
valIdx, _ := cs.Validators.GetByAddress(addr) valIdx, _ := cs.Validators.GetByAddress(addr)


+ 1
- 3
consensus/wal.go View File

@ -8,8 +8,6 @@ import (
"path/filepath" "path/filepath"
"time" "time"
"github.com/pkg/errors"
amino "github.com/tendermint/go-amino" amino "github.com/tendermint/go-amino"
auto "github.com/tendermint/tendermint/libs/autofile" auto "github.com/tendermint/tendermint/libs/autofile"
@ -97,7 +95,7 @@ var _ WAL = &BaseWAL{}
func NewWAL(walFile string, groupOptions ...func(*auto.Group)) (*BaseWAL, error) { func NewWAL(walFile string, groupOptions ...func(*auto.Group)) (*BaseWAL, error) {
err := tmos.EnsureDir(filepath.Dir(walFile), 0700) err := tmos.EnsureDir(filepath.Dir(walFile), 0700)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "failed to ensure WAL directory is in place")
return nil, fmt.Errorf("failed to ensure WAL directory is in place: %w", err)
} }
group, err := auto.OpenGroup(walFile, groupOptions...) group, err := auto.OpenGroup(walFile, groupOptions...)


+ 5
- 7
consensus/wal_generator.go View File

@ -9,8 +9,6 @@ import (
"testing" "testing"
"time" "time"
"github.com/pkg/errors"
db "github.com/tendermint/tm-db" db "github.com/tendermint/tm-db"
"github.com/tendermint/tendermint/abci/example/kvstore" "github.com/tendermint/tendermint/abci/example/kvstore"
@ -46,13 +44,13 @@ func WALGenerateNBlocks(t *testing.T, wr io.Writer, numBlocks int) (err error) {
privValidator := privval.LoadOrGenFilePV(privValidatorKeyFile, privValidatorStateFile) privValidator := privval.LoadOrGenFilePV(privValidatorKeyFile, privValidatorStateFile)
genDoc, err := types.GenesisDocFromFile(config.GenesisFile()) genDoc, err := types.GenesisDocFromFile(config.GenesisFile())
if err != nil { if err != nil {
return errors.Wrap(err, "failed to read genesis file")
return fmt.Errorf("failed to read genesis file: %w", err)
} }
blockStoreDB := db.NewMemDB() blockStoreDB := db.NewMemDB()
stateDB := blockStoreDB stateDB := blockStoreDB
state, err := sm.MakeGenesisState(genDoc) state, err := sm.MakeGenesisState(genDoc)
if err != nil { if err != nil {
return errors.Wrap(err, "failed to make genesis state")
return fmt.Errorf("failed to make genesis state: %w", err)
} }
state.Version.Consensus.App = kvstore.ProtocolVersion state.Version.Consensus.App = kvstore.ProtocolVersion
sm.SaveState(stateDB, state) sm.SaveState(stateDB, state)
@ -61,14 +59,14 @@ func WALGenerateNBlocks(t *testing.T, wr io.Writer, numBlocks int) (err error) {
proxyApp := proxy.NewAppConns(proxy.NewLocalClientCreator(app)) proxyApp := proxy.NewAppConns(proxy.NewLocalClientCreator(app))
proxyApp.SetLogger(logger.With("module", "proxy")) proxyApp.SetLogger(logger.With("module", "proxy"))
if err := proxyApp.Start(); err != nil { if err := proxyApp.Start(); err != nil {
return errors.Wrap(err, "failed to start proxy app connections")
return fmt.Errorf("failed to start proxy app connections: %w", err)
} }
defer proxyApp.Stop() defer proxyApp.Stop()
eventBus := types.NewEventBus() eventBus := types.NewEventBus()
eventBus.SetLogger(logger.With("module", "events")) eventBus.SetLogger(logger.With("module", "events"))
if err := eventBus.Start(); err != nil { if err := eventBus.Start(); err != nil {
return errors.Wrap(err, "failed to start event bus")
return fmt.Errorf("failed to start event bus: %w", err)
} }
defer eventBus.Stop() defer eventBus.Stop()
mempool := emptyMempool{} mempool := emptyMempool{}
@ -91,7 +89,7 @@ func WALGenerateNBlocks(t *testing.T, wr io.Writer, numBlocks int) (err error) {
consensusState.wal = wal consensusState.wal = wal
if err := consensusState.Start(); err != nil { if err := consensusState.Start(); err != nil {
return errors.Wrap(err, "failed to start consensus state")
return fmt.Errorf("failed to start consensus state: %w", err)
} }
select { select {


+ 8
- 8
crypto/merkle/proof.go View File

@ -2,8 +2,8 @@ package merkle
import ( import (
"bytes" "bytes"
"github.com/pkg/errors"
"errors"
"fmt"
) )
//---------------------------------------- //----------------------------------------
@ -44,11 +44,11 @@ func (poz ProofOperators) Verify(root []byte, keypath string, args [][]byte) (er
key := op.GetKey() key := op.GetKey()
if len(key) != 0 { if len(key) != 0 {
if len(keys) == 0 { if len(keys) == 0 {
return errors.Errorf("key path has insufficient # of parts: expected no more keys but got %+v", string(key))
return fmt.Errorf("key path has insufficient # of parts: expected no more keys but got %+v", string(key))
} }
lastKey := keys[len(keys)-1] lastKey := keys[len(keys)-1]
if !bytes.Equal(lastKey, key) { if !bytes.Equal(lastKey, key) {
return errors.Errorf("key mismatch on operation #%d: expected %+v but got %+v", i, string(lastKey), string(key))
return fmt.Errorf("key mismatch on operation #%d: expected %+v but got %+v", i, string(lastKey), string(key))
} }
keys = keys[:len(keys)-1] keys = keys[:len(keys)-1]
} }
@ -58,7 +58,7 @@ func (poz ProofOperators) Verify(root []byte, keypath string, args [][]byte) (er
} }
} }
if !bytes.Equal(root, args[0]) { if !bytes.Equal(root, args[0]) {
return errors.Errorf("calculated root hash is invalid: expected %+v but got %+v", root, args[0])
return fmt.Errorf("calculated root hash is invalid: expected %+v but got %+v", root, args[0])
} }
if len(keys) != 0 { if len(keys) != 0 {
return errors.New("keypath not consumed all") return errors.New("keypath not consumed all")
@ -92,7 +92,7 @@ func (prt *ProofRuntime) RegisterOpDecoder(typ string, dec OpDecoder) {
func (prt *ProofRuntime) Decode(pop ProofOp) (ProofOperator, error) { func (prt *ProofRuntime) Decode(pop ProofOp) (ProofOperator, error) {
decoder := prt.decoders[pop.Type] decoder := prt.decoders[pop.Type]
if decoder == nil { if decoder == nil {
return nil, errors.Errorf("unrecognized proof type %v", pop.Type)
return nil, fmt.Errorf("unrecognized proof type %v", pop.Type)
} }
return decoder(pop) return decoder(pop)
} }
@ -102,7 +102,7 @@ func (prt *ProofRuntime) DecodeProof(proof *Proof) (ProofOperators, error) {
for _, pop := range proof.Ops { for _, pop := range proof.Ops {
operator, err := prt.Decode(pop) operator, err := prt.Decode(pop)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "decoding a proof operator")
return nil, fmt.Errorf("decoding a proof operator: %w", err)
} }
poz = append(poz, operator) poz = append(poz, operator)
} }
@ -122,7 +122,7 @@ func (prt *ProofRuntime) VerifyAbsence(proof *Proof, root []byte, keypath string
func (prt *ProofRuntime) Verify(proof *Proof, root []byte, keypath string, args [][]byte) (err error) { func (prt *ProofRuntime) Verify(proof *Proof, root []byte, keypath string, args [][]byte) (err error) {
poz, err := prt.DecodeProof(proof) poz, err := prt.DecodeProof(proof)
if err != nil { if err != nil {
return errors.Wrap(err, "decoding proof")
return fmt.Errorf("decoding proof: %w", err)
} }
return poz.Verify(root, keypath, args) return poz.Verify(root, keypath, args)
} }


+ 3
- 4
crypto/merkle/proof_key_path.go View File

@ -2,11 +2,10 @@ package merkle
import ( import (
"encoding/hex" "encoding/hex"
"errors"
"fmt" "fmt"
"net/url" "net/url"
"strings" "strings"
"github.com/pkg/errors"
) )
/* /*
@ -96,13 +95,13 @@ func KeyPathToKeys(path string) (keys [][]byte, err error) {
hexPart := part[2:] hexPart := part[2:]
key, err := hex.DecodeString(hexPart) key, err := hex.DecodeString(hexPart)
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "decoding hex-encoded part #%d: /%s", i, part)
return nil, fmt.Errorf("decoding hex-encoded part #%d: /%s: %w", i, part, err)
} }
keys[i] = key keys[i] = key
} else { } else {
key, err := url.PathUnescape(part) key, err := url.PathUnescape(part)
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "decoding url-encoded part #%d: /%s", i, part)
return nil, fmt.Errorf("decoding url-encoded part #%d: /%s: %w", i, part, err)
} }
keys[i] = []byte(key) // TODO Test this with random bytes, I'm not sure that it works for arbitrary bytes... keys[i] = []byte(key) // TODO Test this with random bytes, I'm not sure that it works for arbitrary bytes...
} }


+ 4
- 6
crypto/merkle/proof_simple_value.go View File

@ -4,8 +4,6 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/crypto/tmhash" "github.com/tendermint/tendermint/crypto/tmhash"
) )
@ -40,12 +38,12 @@ func NewSimpleValueOp(key []byte, proof *SimpleProof) SimpleValueOp {
func SimpleValueOpDecoder(pop ProofOp) (ProofOperator, error) { func SimpleValueOpDecoder(pop ProofOp) (ProofOperator, error) {
if pop.Type != ProofOpSimpleValue { if pop.Type != ProofOpSimpleValue {
return nil, errors.Errorf("unexpected ProofOp.Type; got %v, want %v", pop.Type, ProofOpSimpleValue)
return nil, fmt.Errorf("unexpected ProofOp.Type; got %v, want %v", pop.Type, ProofOpSimpleValue)
} }
var op SimpleValueOp // a bit strange as we'll discard this, but it works. var op SimpleValueOp // a bit strange as we'll discard this, but it works.
err := cdc.UnmarshalBinaryLengthPrefixed(pop.Data, &op) err := cdc.UnmarshalBinaryLengthPrefixed(pop.Data, &op)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "decoding ProofOp.Data into SimpleValueOp")
return nil, fmt.Errorf("decoding ProofOp.Data into SimpleValueOp: %w", err)
} }
return NewSimpleValueOp(pop.Key, op.Proof), nil return NewSimpleValueOp(pop.Key, op.Proof), nil
} }
@ -65,7 +63,7 @@ func (op SimpleValueOp) String() string {
func (op SimpleValueOp) Run(args [][]byte) ([][]byte, error) { func (op SimpleValueOp) Run(args [][]byte) ([][]byte, error) {
if len(args) != 1 { if len(args) != 1 {
return nil, errors.Errorf("expected 1 arg, got %v", len(args))
return nil, fmt.Errorf("expected 1 arg, got %v", len(args))
} }
value := args[0] value := args[0]
hasher := tmhash.New() hasher := tmhash.New()
@ -79,7 +77,7 @@ func (op SimpleValueOp) Run(args [][]byte) ([][]byte, error) {
kvhash := leafHash(bz.Bytes()) kvhash := leafHash(bz.Bytes())
if !bytes.Equal(kvhash, op.Proof.LeafHash) { if !bytes.Equal(kvhash, op.Proof.LeafHash) {
return nil, errors.Errorf("leaf hash mismatch: want %X got %X", op.Proof.LeafHash, kvhash)
return nil, fmt.Errorf("leaf hash mismatch: want %X got %X", op.Proof.LeafHash, kvhash)
} }
return [][]byte{ return [][]byte{


+ 4
- 3
crypto/merkle/proof_test.go View File

@ -1,9 +1,10 @@
package merkle package merkle
import ( import (
"errors"
"fmt"
"testing" "testing"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
amino "github.com/tendermint/go-amino" amino "github.com/tendermint/go-amino"
) )
@ -34,7 +35,7 @@ func DominoOpDecoder(pop ProofOp) (ProofOperator, error) {
var op DominoOp // a bit strange as we'll discard this, but it works. var op DominoOp // a bit strange as we'll discard this, but it works.
err := amino.UnmarshalBinaryLengthPrefixed(pop.Data, &op) err := amino.UnmarshalBinaryLengthPrefixed(pop.Data, &op)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "decoding ProofOp.Data into SimpleValueOp")
return nil, fmt.Errorf("decoding ProofOp.Data into SimpleValueOp: %w", err)
} }
return NewDominoOp(string(pop.Key), op.Input, op.Output), nil return NewDominoOp(string(pop.Key), op.Input, op.Output), nil
} }
@ -53,7 +54,7 @@ func (dop DominoOp) Run(input [][]byte) (output [][]byte, err error) {
return nil, errors.New("expected input of length 1") return nil, errors.New("expected input of length 1")
} }
if string(input[0]) != dop.Input { if string(input[0]) != dop.Input {
return nil, errors.Errorf("expected input %v, got %v",
return nil, fmt.Errorf("expected input %v, got %v",
dop.Input, string(input[0])) dop.Input, string(input[0]))
} }
return [][]byte{[]byte(dop.Output)}, nil return [][]byte{[]byte(dop.Output)}, nil


+ 6
- 7
crypto/merkle/simple_proof.go View File

@ -2,10 +2,9 @@ package merkle
import ( import (
"bytes" "bytes"
"errors"
"fmt" "fmt"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/crypto/tmhash" "github.com/tendermint/tendermint/crypto/tmhash"
) )
@ -58,11 +57,11 @@ func (sp *SimpleProof) Verify(rootHash []byte, leaf []byte) error {
return errors.New("proof index cannot be negative") return errors.New("proof index cannot be negative")
} }
if !bytes.Equal(sp.LeafHash, leafHash) { if !bytes.Equal(sp.LeafHash, leafHash) {
return errors.Errorf("invalid leaf hash: wanted %X got %X", leafHash, sp.LeafHash)
return fmt.Errorf("invalid leaf hash: wanted %X got %X", leafHash, sp.LeafHash)
} }
computedHash := sp.ComputeRootHash() computedHash := sp.ComputeRootHash()
if !bytes.Equal(computedHash, rootHash) { if !bytes.Equal(computedHash, rootHash) {
return errors.Errorf("invalid root hash: wanted %X got %X", rootHash, computedHash)
return fmt.Errorf("invalid root hash: wanted %X got %X", rootHash, computedHash)
} }
return nil return nil
} }
@ -103,14 +102,14 @@ func (sp *SimpleProof) ValidateBasic() error {
return errors.New("negative Index") return errors.New("negative Index")
} }
if len(sp.LeafHash) != tmhash.Size { if len(sp.LeafHash) != tmhash.Size {
return errors.Errorf("expected LeafHash size to be %d, got %d", tmhash.Size, len(sp.LeafHash))
return fmt.Errorf("expected LeafHash size to be %d, got %d", tmhash.Size, len(sp.LeafHash))
} }
if len(sp.Aunts) > MaxAunts { if len(sp.Aunts) > MaxAunts {
return errors.Errorf("expected no more than %d aunts, got %d", MaxAunts, len(sp.Aunts))
return fmt.Errorf("expected no more than %d aunts, got %d", MaxAunts, len(sp.Aunts))
} }
for i, auntHash := range sp.Aunts { for i, auntHash := range sp.Aunts {
if len(auntHash) != tmhash.Size { if len(auntHash) != tmhash.Size {
return errors.Errorf("expected Aunts#%d size to be %d, got %d", i, tmhash.Size, len(auntHash))
return fmt.Errorf("expected Aunts#%d size to be %d, got %d", i, tmhash.Size, len(auntHash))
} }
} }
return nil return nil


+ 13
- 13
docs/guides/go-built-in.md View File

@ -331,6 +331,7 @@ Put the following code into the "main.go" file:
package main package main
import ( import (
"errors"
"flag" "flag"
"fmt" "fmt"
"os" "os"
@ -339,7 +340,6 @@ import (
"syscall" "syscall"
"github.com/dgraph-io/badger" "github.com/dgraph-io/badger"
"github.com/pkg/errors"
"github.com/spf13/viper" "github.com/spf13/viper"
abci "github.com/tendermint/tendermint/abci/types" abci "github.com/tendermint/tendermint/abci/types"
@ -393,13 +393,13 @@ func newTendermint(app abci.Application, configFile string) (*nm.Node, error) {
config.RootDir = filepath.Dir(filepath.Dir(configFile)) config.RootDir = filepath.Dir(filepath.Dir(configFile))
viper.SetConfigFile(configFile) viper.SetConfigFile(configFile)
if err := viper.ReadInConfig(); err != nil { if err := viper.ReadInConfig(); err != nil {
return nil, errors.Wrap(err, "viper failed to read config file")
return nil, fmt.Errorf("viper failed to read config file: %w", err)
} }
if err := viper.Unmarshal(config); err != nil { if err := viper.Unmarshal(config); err != nil {
return nil, errors.Wrap(err, "viper failed to unmarshal config")
return nil, fmt.Errorf("viper failed to unmarshal config: %w", err)
} }
if err := config.ValidateBasic(); err != nil { if err := config.ValidateBasic(); err != nil {
return nil, errors.Wrap(err, "config is invalid")
return nil, fmt.Errorf("config is invalid: %w", err)
} }
// create logger // create logger
@ -407,7 +407,7 @@ func newTendermint(app abci.Application, configFile string) (*nm.Node, error) {
var err error var err error
logger, err = tmflags.ParseLogLevel(config.LogLevel, logger, cfg.DefaultLogLevel()) logger, err = tmflags.ParseLogLevel(config.LogLevel, logger, cfg.DefaultLogLevel())
if err != nil { if err != nil {
return nil, errors.Wrap(err, "failed to parse log level")
return nil, fmt.Errorf("failed to parse log level: %w", err)
} }
// read private validator // read private validator
@ -419,7 +419,7 @@ func newTendermint(app abci.Application, configFile string) (*nm.Node, error) {
// read node key // read node key
nodeKey, err := p2p.LoadNodeKey(config.NodeKeyFile()) nodeKey, err := p2p.LoadNodeKey(config.NodeKeyFile())
if err != nil { if err != nil {
return nil, errors.Wrap(err, "failed to load node's key")
return nil, fmt.Errorf("failed to load node's key: %w", err)
} }
// create node // create node
@ -433,7 +433,7 @@ func newTendermint(app abci.Application, configFile string) (*nm.Node, error) {
nm.DefaultMetricsProvider(config.Instrumentation), nm.DefaultMetricsProvider(config.Instrumentation),
logger) logger)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "failed to create new Tendermint node")
return nil, fmt.Errorf("failed to create new Tendermint node: %w", err)
} }
return node, nil return node, nil
@ -485,7 +485,7 @@ node, err := nm.NewNode(
nm.DefaultMetricsProvider(config.Instrumentation), nm.DefaultMetricsProvider(config.Instrumentation),
logger) logger)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "failed to create new Tendermint node")
return nil, fmt.Errorf("failed to create new Tendermint node: %w", err)
} }
``` ```
@ -503,13 +503,13 @@ config := cfg.DefaultConfig()
config.RootDir = filepath.Dir(filepath.Dir(configFile)) config.RootDir = filepath.Dir(filepath.Dir(configFile))
viper.SetConfigFile(configFile) viper.SetConfigFile(configFile)
if err := viper.ReadInConfig(); err != nil { if err := viper.ReadInConfig(); err != nil {
return nil, errors.Wrap(err, "viper failed to read config file")
return nil, fmt.Errorf("viper failed to read config file: %w", err)
} }
if err := viper.Unmarshal(config); err != nil { if err := viper.Unmarshal(config); err != nil {
return nil, errors.Wrap(err, "viper failed to unmarshal config")
return nil, fmt.Errorf("viper failed to unmarshal config: %w", err)
} }
if err := config.ValidateBasic(); err != nil { if err := config.ValidateBasic(); err != nil {
return nil, errors.Wrap(err, "config is invalid")
return nil, fmt.Errorf("config is invalid: %w", err)
} }
``` ```
@ -530,7 +530,7 @@ pv := privval.LoadFilePV(
```go ```go
nodeKey, err := p2p.LoadNodeKey(config.NodeKeyFile()) nodeKey, err := p2p.LoadNodeKey(config.NodeKeyFile())
if err != nil { if err != nil {
return nil, errors.Wrap(err, "failed to load node's key")
return nil, fmt.Errorf("failed to load node's key: %w", err)
} }
``` ```
@ -543,7 +543,7 @@ logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout))
var err error var err error
logger, err = tmflags.ParseLogLevel(config.LogLevel, logger, cfg.DefaultLogLevel()) logger, err = tmflags.ParseLogLevel(config.LogLevel, logger, cfg.DefaultLogLevel())
if err != nil { if err != nil {
return nil, errors.Wrap(err, "failed to parse log level")
return nil, fmt.Errorf("failed to parse log level: %w", err)
} }
``` ```


+ 2
- 3
libs/async/async.go View File

@ -1,9 +1,8 @@
package async package async
import ( import (
"fmt"
"sync/atomic" "sync/atomic"
"github.com/pkg/errors"
) )
//---------------------------------------- //----------------------------------------
@ -144,7 +143,7 @@ func Parallel(tasks ...Task) (trs *TaskResultSet, ok bool) {
if pnk := recover(); pnk != nil { if pnk := recover(); pnk != nil {
atomic.AddInt32(numPanics, 1) atomic.AddInt32(numPanics, 1)
// Send panic to taskResultCh. // Send panic to taskResultCh.
taskResultCh <- TaskResult{nil, errors.Errorf("panic in task %v", pnk)}
taskResultCh <- TaskResult{nil, fmt.Errorf("panic in task %v", pnk)}
// Closing taskResultCh lets trs.Wait() work. // Closing taskResultCh lets trs.Wait() work.
close(taskResultCh) close(taskResultCh)
// Decrement waitgroup. // Decrement waitgroup.


+ 2
- 2
libs/async/async_test.go View File

@ -1,12 +1,12 @@
package async package async
import ( import (
"errors"
"fmt" "fmt"
"sync/atomic" "sync/atomic"
"testing" "testing"
"time" "time"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -125,7 +125,7 @@ func TestParallelRecover(t *testing.T) {
// Verify task #0, #1, #2. // Verify task #0, #1, #2.
checkResult(t, taskResultSet, 0, 0, nil, nil) checkResult(t, taskResultSet, 0, 0, nil, nil)
checkResult(t, taskResultSet, 1, 1, errors.New("some error"), nil) checkResult(t, taskResultSet, 1, 1, errors.New("some error"), nil)
checkResult(t, taskResultSet, 2, nil, nil, errors.Errorf("panic in task %v", 2).Error())
checkResult(t, taskResultSet, 2, nil, nil, fmt.Errorf("panic in task %v", 2).Error())
} }
// Wait for result // Wait for result


+ 5
- 4
libs/bech32/bech32.go View File

@ -1,15 +1,16 @@
package bech32 package bech32
import ( import (
"fmt"
"github.com/btcsuite/btcutil/bech32" "github.com/btcsuite/btcutil/bech32"
"github.com/pkg/errors"
) )
//ConvertAndEncode converts from a base64 encoded byte string to base32 encoded byte string and then to bech32 //ConvertAndEncode converts from a base64 encoded byte string to base32 encoded byte string and then to bech32
func ConvertAndEncode(hrp string, data []byte) (string, error) { func ConvertAndEncode(hrp string, data []byte) (string, error) {
converted, err := bech32.ConvertBits(data, 8, 5, true) converted, err := bech32.ConvertBits(data, 8, 5, true)
if err != nil { if err != nil {
return "", errors.Wrap(err, "encoding bech32 failed")
return "", fmt.Errorf("encoding bech32 failed: %w", err)
} }
return bech32.Encode(hrp, converted) return bech32.Encode(hrp, converted)
@ -19,11 +20,11 @@ func ConvertAndEncode(hrp string, data []byte) (string, error) {
func DecodeAndConvert(bech string) (string, []byte, error) { func DecodeAndConvert(bech string) (string, []byte, error) {
hrp, data, err := bech32.Decode(bech) hrp, data, err := bech32.Decode(bech)
if err != nil { if err != nil {
return "", nil, errors.Wrap(err, "decoding bech32 failed")
return "", nil, fmt.Errorf("decoding bech32 failed: %w", err)
} }
converted, err := bech32.ConvertBits(data, 5, 8, false) converted, err := bech32.ConvertBits(data, 5, 8, false)
if err != nil { if err != nil {
return "", nil, errors.Wrap(err, "decoding bech32 failed")
return "", nil, fmt.Errorf("decoding bech32 failed: %w", err)
} }
return hrp, converted, nil return hrp, converted, nil
} }

+ 2
- 3
libs/cli/flags/log_level.go View File

@ -1,11 +1,10 @@
package flags package flags
import ( import (
"errors"
"fmt" "fmt"
"strings" "strings"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/libs/log"
) )
@ -51,7 +50,7 @@ func ParseLogLevel(lvl string, logger log.Logger, defaultLogLevelValue string) (
if module == defaultLogLevelKey { if module == defaultLogLevelKey {
option, err = log.AllowLevel(level) option, err = log.AllowLevel(level)
if err != nil { if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("Failed to parse default log level (pair %s, list %s)", item, l))
return nil, fmt.Errorf("failed to parse default log level (pair %s, list %s): %w", item, l, err)
} }
options = append(options, option) options = append(options, option)
isDefaultLogLevelSet = true isDefaultLogLevelSet = true


+ 6
- 3
libs/cli/setup.go View File

@ -4,9 +4,9 @@ import (
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
"runtime"
"strings" "strings"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
) )
@ -89,7 +89,10 @@ func (e Executor) Execute() error {
err := e.Command.Execute() err := e.Command.Execute()
if err != nil { if err != nil {
if viper.GetBool(TraceFlag) { if viper.GetBool(TraceFlag) {
fmt.Fprintf(os.Stderr, "ERROR: %+v\n", err)
const size = 64 << 10
buf := make([]byte, size)
buf = buf[:runtime.Stack(buf, false)]
fmt.Fprintf(os.Stderr, "ERROR: %v\n%s\n", err, buf)
} else { } else {
fmt.Fprintf(os.Stderr, "ERROR: %v\n", err) fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
} }
@ -151,7 +154,7 @@ func validateOutput(cmd *cobra.Command, args []string) error {
switch output { switch output {
case "text", "json": case "text", "json":
default: default:
return errors.Errorf("unsupported output format: %s", output)
return fmt.Errorf("unsupported output format: %s", output)
} }
return nil return nil
} }

+ 7
- 7
libs/cli/setup_test.go View File

@ -7,7 +7,6 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -201,10 +200,10 @@ func TestSetupTrace(t *testing.T) {
long bool long bool
expected string expected string
}{ }{
{nil, nil, false, "Trace flag = false"},
{[]string{"--trace"}, nil, true, "Trace flag = true"},
{nil, nil, false, "trace flag = false"},
{[]string{"--trace"}, nil, true, "trace flag = true"},
{[]string{"--no-such-flag"}, nil, false, "unknown flag: --no-such-flag"}, {[]string{"--no-such-flag"}, nil, false, "unknown flag: --no-such-flag"},
{nil, map[string]string{"DBG_TRACE": "true"}, true, "Trace flag = true"},
{nil, map[string]string{"DBG_TRACE": "true"}, true, "trace flag = true"},
} }
for idx, tc := range cases { for idx, tc := range cases {
@ -213,7 +212,7 @@ func TestSetupTrace(t *testing.T) {
trace := &cobra.Command{ trace := &cobra.Command{
Use: "trace", Use: "trace",
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return errors.Errorf("Trace flag = %t", viper.GetBool(TraceFlag))
return fmt.Errorf("trace flag = %t", viper.GetBool(TraceFlag))
}, },
} }
cmd := PrepareBaseCmd(trace, "DBG", "/qwerty/asdfgh") // some missing dir.. cmd := PrepareBaseCmd(trace, "DBG", "/qwerty/asdfgh") // some missing dir..
@ -228,10 +227,11 @@ func TestSetupTrace(t *testing.T) {
msg := strings.Split(stderr, "\n") msg := strings.Split(stderr, "\n")
desired := fmt.Sprintf("ERROR: %s", tc.expected) desired := fmt.Sprintf("ERROR: %s", tc.expected)
assert.Equal(t, desired, msg[0], i) assert.Equal(t, desired, msg[0], i)
t.Log(msg)
if tc.long && assert.True(t, len(msg) > 2, i) { if tc.long && assert.True(t, len(msg) > 2, i) {
// the next line starts the stack trace... // the next line starts the stack trace...
assert.Contains(t, msg[1], "TestSetupTrace", i)
assert.Contains(t, msg[2], "setup_test.go", i)
assert.Contains(t, stderr, "TestSetupTrace", i)
assert.Contains(t, stderr, "setup_test.go", i)
} }
} }
} }

+ 3
- 3
libs/pubsub/pubsub.go View File

@ -36,10 +36,10 @@ package pubsub
import ( import (
"context" "context"
"errors"
"fmt"
"sync" "sync"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/libs/service" "github.com/tendermint/tendermint/libs/service"
) )
@ -410,7 +410,7 @@ func (state *state) send(msg interface{}, events map[string][]string) error {
match, err := q.Matches(events) match, err := q.Matches(events)
if err != nil { if err != nil {
return errors.Wrapf(err, "failed to match against query %s", q.String())
return fmt.Errorf("failed to match against query %s: %w", q.String(), err)
} }
if match { if match {


+ 4
- 6
libs/pubsub/query/query.go View File

@ -15,8 +15,6 @@ import (
"strconv" "strconv"
"strings" "strings"
"time" "time"
"github.com/pkg/errors"
) )
var ( var (
@ -411,7 +409,7 @@ func matchValue(value string, op Operator, operand reflect.Value) (bool, error)
v, err = time.Parse(DateLayout, value) v, err = time.Parse(DateLayout, value)
} }
if err != nil { if err != nil {
return false, errors.Wrapf(err, "failed to convert value %v from event attribute to time.Time", value)
return false, fmt.Errorf("failed to convert value %v from event attribute to time.Time: %w", value, err)
} }
switch op { switch op {
@ -436,7 +434,7 @@ func matchValue(value string, op Operator, operand reflect.Value) (bool, error)
// try our best to convert value from tags to float64 // try our best to convert value from tags to float64
v, err := strconv.ParseFloat(filteredValue, 64) v, err := strconv.ParseFloat(filteredValue, 64)
if err != nil { if err != nil {
return false, errors.Wrapf(err, "failed to convert value %v from event attribute to float64", filteredValue)
return false, fmt.Errorf("failed to convert value %v from event attribute to float64: %w", filteredValue, err)
} }
switch op { switch op {
@ -462,7 +460,7 @@ func matchValue(value string, op Operator, operand reflect.Value) (bool, error)
if strings.ContainsAny(filteredValue, ".") { if strings.ContainsAny(filteredValue, ".") {
v1, err := strconv.ParseFloat(filteredValue, 64) v1, err := strconv.ParseFloat(filteredValue, 64)
if err != nil { if err != nil {
return false, errors.Wrapf(err, "failed to convert value %v from event attribute to float64", filteredValue)
return false, fmt.Errorf("failed to convert value %v from event attribute to float64: %w", filteredValue, err)
} }
v = int64(v1) v = int64(v1)
@ -471,7 +469,7 @@ func matchValue(value string, op Operator, operand reflect.Value) (bool, error)
// try our best to convert value from tags to int64 // try our best to convert value from tags to int64
v, err = strconv.ParseInt(filteredValue, 10, 64) v, err = strconv.ParseInt(filteredValue, 10, 64)
if err != nil { if err != nil {
return false, errors.Wrapf(err, "failed to convert value %v from event attribute to int64", filteredValue)
return false, fmt.Errorf("failed to convert value %v from event attribute to int64: %w", filteredValue, err)
} }
} }


+ 1
- 1
libs/tempfile/tempfile.go View File

@ -1,7 +1,7 @@
package tempfile package tempfile
import ( import (
fmt "fmt"
"fmt"
"io" "io"
"os" "os"
"path/filepath" "path/filepath"


+ 1
- 1
libs/tempfile/tempfile_test.go View File

@ -4,7 +4,7 @@ package tempfile
import ( import (
"bytes" "bytes"
fmt "fmt"
"fmt"
"io/ioutil" "io/ioutil"
"os" "os"
testing "testing" testing "testing"


+ 1
- 2
lite2/client.go View File

@ -2,13 +2,12 @@ package lite
import ( import (
"bytes" "bytes"
"errors"
"fmt" "fmt"
"math/rand" "math/rand"
"sync" "sync"
"time" "time"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/libs/log"
tmmath "github.com/tendermint/tendermint/libs/math" tmmath "github.com/tendermint/tendermint/libs/math"
"github.com/tendermint/tendermint/lite2/provider" "github.com/tendermint/tendermint/lite2/provider"


+ 2
- 3
lite2/proxy/proxy.go View File

@ -2,11 +2,10 @@ package proxy
import ( import (
"context" "context"
"fmt"
"net" "net"
"net/http" "net/http"
"github.com/pkg/errors"
amino "github.com/tendermint/go-amino" amino "github.com/tendermint/go-amino"
"github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/libs/log"
@ -91,7 +90,7 @@ func (p *Proxy) listen() (net.Listener, *http.ServeMux, error) {
// 3) Start a client. // 3) Start a client.
if !p.Client.IsRunning() { if !p.Client.IsRunning() {
if err := p.Client.Start(); err != nil { if err := p.Client.Start(); err != nil {
return nil, mux, errors.Wrap(err, "Client#Start")
return nil, mux, fmt.Errorf("can't start client: %w", err)
} }
} }


+ 3
- 4
lite2/store/db/db.go View File

@ -7,7 +7,6 @@ import (
"strconv" "strconv"
"sync" "sync"
"github.com/pkg/errors"
"github.com/tendermint/go-amino" "github.com/tendermint/go-amino"
dbm "github.com/tendermint/tm-db" dbm "github.com/tendermint/tm-db"
@ -58,12 +57,12 @@ func (s *dbs) SaveSignedHeaderAndValidatorSet(sh *types.SignedHeader, valSet *ty
shBz, err := s.cdc.MarshalBinaryLengthPrefixed(sh) shBz, err := s.cdc.MarshalBinaryLengthPrefixed(sh)
if err != nil { if err != nil {
return errors.Wrap(err, "marshalling header")
return fmt.Errorf("marshalling header: %w", err)
} }
valSetBz, err := s.cdc.MarshalBinaryLengthPrefixed(valSet) valSetBz, err := s.cdc.MarshalBinaryLengthPrefixed(valSet)
if err != nil { if err != nil {
return errors.Wrap(err, "marshalling validator set")
return fmt.Errorf("marshalling validator set: %w", err)
} }
s.mtx.Lock() s.mtx.Lock()
@ -287,7 +286,7 @@ func (s *dbs) Prune(size uint16) error {
s.size -= uint16(pruned) s.size -= uint16(pruned)
if wErr := s.db.SetSync(sizeKey, marshalSize(s.size)); wErr != nil { if wErr := s.db.SetSync(sizeKey, marshalSize(s.size)); wErr != nil {
return errors.Wrap(wErr, "failed to persist size")
return fmt.Errorf("failed to persist size: %w", wErr)
} }
return nil return nil


+ 3
- 3
lite2/trust_options.go View File

@ -1,10 +1,10 @@
package lite package lite
import ( import (
"errors"
"fmt"
"time" "time"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/crypto/tmhash" "github.com/tendermint/tendermint/crypto/tmhash"
) )
@ -44,7 +44,7 @@ func (opts TrustOptions) ValidateBasic() error {
return errors.New("negative or zero height") return errors.New("negative or zero height")
} }
if len(opts.Hash) != tmhash.Size { if len(opts.Hash) != tmhash.Size {
return errors.Errorf("expected hash size to be %d bytes, got %d bytes",
return fmt.Errorf("expected hash size to be %d bytes, got %d bytes",
tmhash.Size, tmhash.Size,
len(opts.Hash), len(opts.Hash),
) )


+ 11
- 11
lite2/verifier.go View File

@ -2,10 +2,10 @@ package lite
import ( import (
"bytes" "bytes"
"errors"
"fmt"
"time" "time"
"github.com/pkg/errors"
tmmath "github.com/tendermint/tendermint/libs/math" tmmath "github.com/tendermint/tendermint/libs/math"
"github.com/tendermint/tendermint/types" "github.com/tendermint/tendermint/types"
) )
@ -119,7 +119,7 @@ func VerifyAdjacent(
// Check the validator hashes are the same // Check the validator hashes are the same
if !bytes.Equal(untrustedHeader.ValidatorsHash, trustedHeader.NextValidatorsHash) { if !bytes.Equal(untrustedHeader.ValidatorsHash, trustedHeader.NextValidatorsHash) {
err := errors.Errorf("expected old header next validators (%X) to match those from new header (%X)",
err := fmt.Errorf("expected old header next validators (%X) to match those from new header (%X)",
trustedHeader.NextValidatorsHash, trustedHeader.NextValidatorsHash,
untrustedHeader.ValidatorsHash, untrustedHeader.ValidatorsHash,
) )
@ -164,30 +164,30 @@ func verifyNewHeaderAndVals(
maxClockDrift time.Duration) error { maxClockDrift time.Duration) error {
if err := untrustedHeader.ValidateBasic(chainID); err != nil { if err := untrustedHeader.ValidateBasic(chainID); err != nil {
return errors.Wrap(err, "untrustedHeader.ValidateBasic failed")
return fmt.Errorf("untrustedHeader.ValidateBasic failed: %w", err)
} }
if untrustedHeader.Height <= trustedHeader.Height { if untrustedHeader.Height <= trustedHeader.Height {
return errors.Errorf("expected new header height %d to be greater than one of old header %d",
return fmt.Errorf("expected new header height %d to be greater than one of old header %d",
untrustedHeader.Height, untrustedHeader.Height,
trustedHeader.Height) trustedHeader.Height)
} }
if !untrustedHeader.Time.After(trustedHeader.Time) { if !untrustedHeader.Time.After(trustedHeader.Time) {
return errors.Errorf("expected new header time %v to be after old header time %v",
return fmt.Errorf("expected new header time %v to be after old header time %v",
untrustedHeader.Time, untrustedHeader.Time,
trustedHeader.Time) trustedHeader.Time)
} }
if !untrustedHeader.Time.Before(now.Add(maxClockDrift)) { if !untrustedHeader.Time.Before(now.Add(maxClockDrift)) {
return errors.Errorf("new header has a time from the future %v (now: %v; max clock drift: %v)",
return fmt.Errorf("new header has a time from the future %v (now: %v; max clock drift: %v)",
untrustedHeader.Time, untrustedHeader.Time,
now, now,
maxClockDrift) maxClockDrift)
} }
if !bytes.Equal(untrustedHeader.ValidatorsHash, untrustedVals.Hash()) { if !bytes.Equal(untrustedHeader.ValidatorsHash, untrustedVals.Hash()) {
return errors.Errorf("expected new header validators (%X) to match those that were supplied (%X) at height %d",
return fmt.Errorf("expected new header validators (%X) to match those that were supplied (%X) at height %d",
untrustedHeader.ValidatorsHash, untrustedHeader.ValidatorsHash,
untrustedVals.Hash(), untrustedVals.Hash(),
untrustedHeader.Height, untrustedHeader.Height,
@ -204,7 +204,7 @@ func ValidateTrustLevel(lvl tmmath.Fraction) error {
if lvl.Numerator*3 < lvl.Denominator || // < 1/3 if lvl.Numerator*3 < lvl.Denominator || // < 1/3
lvl.Numerator > lvl.Denominator || // > 1 lvl.Numerator > lvl.Denominator || // > 1
lvl.Denominator == 0 { lvl.Denominator == 0 {
return errors.Errorf("trustLevel must be within [1/3, 1], given %v", lvl)
return fmt.Errorf("trustLevel must be within [1/3, 1], given %v", lvl)
} }
return nil return nil
} }
@ -231,14 +231,14 @@ func VerifyBackwards(chainID string, untrustedHeader, trustedHeader *types.Signe
if !untrustedHeader.Time.Before(trustedHeader.Time) { if !untrustedHeader.Time.Before(trustedHeader.Time) {
return ErrInvalidHeader{ return ErrInvalidHeader{
errors.Errorf("expected older header time %v to be before new header time %v",
fmt.Errorf("expected older header time %v to be before new header time %v",
untrustedHeader.Time, untrustedHeader.Time,
trustedHeader.Time)} trustedHeader.Time)}
} }
if !bytes.Equal(untrustedHeader.Hash(), trustedHeader.LastBlockID.Hash) { if !bytes.Equal(untrustedHeader.Hash(), trustedHeader.LastBlockID.Hash) {
return ErrInvalidHeader{ return ErrInvalidHeader{
errors.Errorf("older header hash %X does not match trusted header's last block %X",
fmt.Errorf("older header hash %X does not match trusted header's last block %X",
untrustedHeader.Hash(), untrustedHeader.Hash(),
trustedHeader.LastBlockID.Hash)} trustedHeader.LastBlockID.Hash)}
} }


+ 1
- 2
mempool/errors.go View File

@ -1,9 +1,8 @@
package mempool package mempool
import ( import (
"errors"
"fmt" "fmt"
"github.com/pkg/errors"
) )
var ( var (


+ 1
- 1
mempool/reactor_test.go View File

@ -1,6 +1,7 @@
package mempool package mempool
import ( import (
"errors"
"net" "net"
"sync" "sync"
"testing" "testing"
@ -8,7 +9,6 @@ import (
"github.com/fortytw2/leaktest" "github.com/fortytw2/leaktest"
"github.com/go-kit/kit/log/term" "github.com/go-kit/kit/log/term"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/tendermint/tendermint/abci/example/kvstore" "github.com/tendermint/tendermint/abci/example/kvstore"


+ 10
- 10
node/node.go View File

@ -3,6 +3,7 @@ package node
import ( import (
"bytes" "bytes"
"context" "context"
"errors"
"fmt" "fmt"
"net" "net"
"net/http" "net/http"
@ -10,7 +11,6 @@ import (
"strings" "strings"
"time" "time"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp" "github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/rs/cors" "github.com/rs/cors"
@ -527,14 +527,14 @@ func createAddrBookAndSetOnSwitch(config *cfg.Config, sw *p2p.Switch,
if config.P2P.ExternalAddress != "" { if config.P2P.ExternalAddress != "" {
addr, err := p2p.NewNetAddressString(p2p.IDAddressString(nodeKey.ID(), config.P2P.ExternalAddress)) addr, err := p2p.NewNetAddressString(p2p.IDAddressString(nodeKey.ID(), config.P2P.ExternalAddress))
if err != nil { if err != nil {
return nil, errors.Wrap(err, "p2p.external_address is incorrect")
return nil, fmt.Errorf("p2p.external_address is incorrect: %w", err)
} }
addrBook.AddOurAddress(addr) addrBook.AddOurAddress(addr)
} }
if config.P2P.ListenAddress != "" { if config.P2P.ListenAddress != "" {
addr, err := p2p.NewNetAddressString(p2p.IDAddressString(nodeKey.ID(), config.P2P.ListenAddress)) addr, err := p2p.NewNetAddressString(p2p.IDAddressString(nodeKey.ID(), config.P2P.ListenAddress))
if err != nil { if err != nil {
return nil, errors.Wrap(err, "p2p.laddr is incorrect")
return nil, fmt.Errorf("p2p.laddr is incorrect: %w", err)
} }
addrBook.AddOurAddress(addr) addrBook.AddOurAddress(addr)
} }
@ -666,13 +666,13 @@ func NewNode(config *cfg.Config,
// FIXME: we should start services inside OnStart // FIXME: we should start services inside OnStart
privValidator, err = createAndStartPrivValidatorSocketClient(config.PrivValidatorListenAddr, logger) privValidator, err = createAndStartPrivValidatorSocketClient(config.PrivValidatorListenAddr, logger)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "error with private validator socket client")
return nil, fmt.Errorf("error with private validator socket client: %w", err)
} }
} }
pubKey, err := privValidator.GetPubKey() pubKey, err := privValidator.GetPubKey()
if err != nil { if err != nil {
return nil, errors.Wrap(err, "can't get pubkey")
return nil, fmt.Errorf("can't get pubkey: %w", err)
} }
// Determine whether we should do state and/or fast sync. // Determine whether we should do state and/or fast sync.
@ -724,7 +724,7 @@ func NewNode(config *cfg.Config,
// Make BlockchainReactor. Don't start fast sync if we're doing a state sync first. // Make BlockchainReactor. Don't start fast sync if we're doing a state sync first.
bcReactor, err := createBlockchainReactor(config, state, blockExec, blockStore, fastSync && !stateSync, logger) bcReactor, err := createBlockchainReactor(config, state, blockExec, blockStore, fastSync && !stateSync, logger)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "could not create blockchain reactor")
return nil, fmt.Errorf("could not create blockchain reactor: %w", err)
} }
// Make ConsensusReactor. Don't enable fully if doing a state sync and/or fast sync first. // Make ConsensusReactor. Don't enable fully if doing a state sync and/or fast sync first.
@ -764,17 +764,17 @@ func NewNode(config *cfg.Config,
err = sw.AddPersistentPeers(splitAndTrimEmpty(config.P2P.PersistentPeers, ",", " ")) err = sw.AddPersistentPeers(splitAndTrimEmpty(config.P2P.PersistentPeers, ",", " "))
if err != nil { if err != nil {
return nil, errors.Wrap(err, "could not add peers from persistent_peers field")
return nil, fmt.Errorf("could not add peers from persistent_peers field: %w", err)
} }
err = sw.AddUnconditionalPeerIDs(splitAndTrimEmpty(config.P2P.UnconditionalPeerIDs, ",", " ")) err = sw.AddUnconditionalPeerIDs(splitAndTrimEmpty(config.P2P.UnconditionalPeerIDs, ",", " "))
if err != nil { if err != nil {
return nil, errors.Wrap(err, "could not add peer ids from unconditional_peer_ids field")
return nil, fmt.Errorf("could not add peer ids from unconditional_peer_ids field: %w", err)
} }
addrBook, err := createAddrBookAndSetOnSwitch(config, sw, p2pLogger, nodeKey) addrBook, err := createAddrBookAndSetOnSwitch(config, sw, p2pLogger, nodeKey)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "could not create addrbook")
return nil, fmt.Errorf("could not create addrbook: %w", err)
} }
// Optionally, start the pex reactor // Optionally, start the pex reactor
@ -890,7 +890,7 @@ func (n *Node) OnStart() error {
// Always connect to persistent peers // Always connect to persistent peers
err = n.sw.DialPeersAsync(splitAndTrimEmpty(n.config.P2P.PersistentPeers, ",", " ")) err = n.sw.DialPeersAsync(splitAndTrimEmpty(n.config.P2P.PersistentPeers, ",", " "))
if err != nil { if err != nil {
return errors.Wrap(err, "could not dial peers from persistent_peers field")
return fmt.Errorf("could not dial peers from persistent_peers field: %w", err)
} }
// Run state sync // Run state sync


+ 2
- 3
p2p/conn/connection.go View File

@ -4,6 +4,7 @@ import (
"bufio" "bufio"
"runtime/debug" "runtime/debug"
"errors"
"fmt" "fmt"
"io" "io"
"math" "math"
@ -13,8 +14,6 @@ import (
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/pkg/errors"
amino "github.com/tendermint/go-amino" amino "github.com/tendermint/go-amino"
flow "github.com/tendermint/tendermint/libs/flowrate" flow "github.com/tendermint/tendermint/libs/flowrate"
@ -331,7 +330,7 @@ func (c *MConnection) flush() {
func (c *MConnection) _recover() { func (c *MConnection) _recover() {
if r := recover(); r != nil { if r := recover(); r != nil {
c.Logger.Error("MConnection panicked", "err", r, "stack", string(debug.Stack())) c.Logger.Error("MConnection panicked", "err", r, "stack", string(debug.Stack()))
c.stopForError(errors.Errorf("recovered from panic: %v", r))
c.stopForError(fmt.Errorf("recovered from panic: %v", r))
} }
} }


+ 3
- 2
p2p/conn/secret_connection.go View File

@ -6,6 +6,8 @@ import (
crand "crypto/rand" crand "crypto/rand"
"crypto/sha256" "crypto/sha256"
"encoding/binary" "encoding/binary"
"errors"
"fmt"
"io" "io"
"math" "math"
"net" "net"
@ -14,7 +16,6 @@ import (
"github.com/gtank/merlin" "github.com/gtank/merlin"
pool "github.com/libp2p/go-buffer-pool" pool "github.com/libp2p/go-buffer-pool"
"github.com/pkg/errors"
"golang.org/x/crypto/chacha20poly1305" "golang.org/x/crypto/chacha20poly1305"
"golang.org/x/crypto/curve25519" "golang.org/x/crypto/curve25519"
"golang.org/x/crypto/hkdf" "golang.org/x/crypto/hkdf"
@ -163,7 +164,7 @@ func MakeSecretConnection(conn io.ReadWriteCloser, locPrivKey crypto.PrivKey) (*
remPubKey, remSignature := authSigMsg.Key, authSigMsg.Sig remPubKey, remSignature := authSigMsg.Key, authSigMsg.Sig
if _, ok := remPubKey.(ed25519.PubKeyEd25519); !ok { if _, ok := remPubKey.(ed25519.PubKeyEd25519); !ok {
return nil, errors.Errorf("expected ed25519 pubkey, got %T", remPubKey)
return nil, fmt.Errorf("expected ed25519 pubkey, got %T", remPubKey)
} }
if !remPubKey.VerifyBytes(challenge[:], remSignature) { if !remPubKey.VerifyBytes(challenge[:], remSignature) {
return nil, errors.New("challenge verification failed") return nil, errors.New("challenge verification failed")


+ 2
- 3
p2p/netaddress.go View File

@ -6,14 +6,13 @@ package p2p
import ( import (
"encoding/hex" "encoding/hex"
"errors"
"flag" "flag"
"fmt" "fmt"
"net" "net"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"github.com/pkg/errors"
) )
// NetAddress defines information about a peer on the network // NetAddress defines information about a peer on the network
@ -217,7 +216,7 @@ func (na *NetAddress) Routable() bool {
// address or one that matches the RFC3849 documentation address format. // address or one that matches the RFC3849 documentation address format.
func (na *NetAddress) Valid() error { func (na *NetAddress) Valid() error {
if err := validateID(na.ID); err != nil { if err := validateID(na.ID); err != nil {
return errors.Wrap(err, "invalid ID")
return fmt.Errorf("invalid ID: %w", err)
} }
if na.IP == nil { if na.IP == nil {


+ 3
- 4
p2p/peer_test.go View File

@ -7,7 +7,6 @@ import (
"testing" "testing"
"time" "time"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@ -114,13 +113,13 @@ func testOutboundPeerConn(
var pc peerConn var pc peerConn
conn, err := testDial(addr, config) conn, err := testDial(addr, config)
if err != nil { if err != nil {
return pc, errors.Wrap(err, "Error creating peer")
return pc, fmt.Errorf("error creating peer: %w", err)
} }
pc, err = testPeerConn(conn, config, true, persistent, ourNodePrivKey, addr) pc, err = testPeerConn(conn, config, true, persistent, ourNodePrivKey, addr)
if err != nil { if err != nil {
if cerr := conn.Close(); cerr != nil { if cerr := conn.Close(); cerr != nil {
return pc, errors.Wrap(err, cerr.Error())
return pc, fmt.Errorf("%v: %w", cerr.Error(), err)
} }
return pc, err return pc, err
} }
@ -128,7 +127,7 @@ func testOutboundPeerConn(
// ensure dialed ID matches connection ID // ensure dialed ID matches connection ID
if addr.ID != pc.ID() { if addr.ID != pc.ID() {
if cerr := conn.Close(); cerr != nil { if cerr := conn.Close(); cerr != nil {
return pc, errors.Wrap(err, cerr.Error())
return pc, fmt.Errorf("%v: %w", cerr.Error(), err)
} }
return pc, ErrSwitchAuthenticationFailure{addr, pc.ID()} return pc, ErrSwitchAuthenticationFailure{addr, pc.ID()}
} }


+ 3
- 4
p2p/pex/pex_reactor.go View File

@ -1,13 +1,12 @@
package pex package pex
import ( import (
"errors"
"fmt" "fmt"
"reflect" "reflect"
"sync" "sync"
"time" "time"
"github.com/pkg/errors"
"github.com/tendermint/go-amino" "github.com/tendermint/go-amino"
"github.com/tendermint/tendermint/libs/cmap" "github.com/tendermint/tendermint/libs/cmap"
@ -569,7 +568,7 @@ func (r *Reactor) dialPeer(addr *p2p.NetAddress) error {
default: default:
r.attemptsToDial.Store(addr.DialString(), _attemptsToDial{attempts + 1, time.Now()}) r.attemptsToDial.Store(addr.DialString(), _attemptsToDial{attempts + 1, time.Now()})
} }
return errors.Wrapf(err, "dialing failed (attempts: %d)", attempts+1)
return fmt.Errorf("dialing failed (attempts: %d): %w", attempts+1, err)
} }
// cleanup any history // cleanup any history
@ -604,7 +603,7 @@ func (r *Reactor) checkSeeds() (numOnline int, netAddrs []*p2p.NetAddress, err e
case p2p.ErrNetAddressLookup: case p2p.ErrNetAddressLookup:
r.Logger.Error("Connecting to seed failed", "err", e) r.Logger.Error("Connecting to seed failed", "err", e)
default: default:
return 0, nil, errors.Wrap(e, "seed node configuration has error")
return 0, nil, fmt.Errorf("seed node configuration has error: %w", e)
} }
} }
return numOnline, netAddrs, nil return numOnline, netAddrs, nil


+ 3
- 5
p2p/switch.go View File

@ -6,8 +6,6 @@ import (
"sync" "sync"
"time" "time"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/libs/cmap" "github.com/tendermint/tendermint/libs/cmap"
"github.com/tendermint/tendermint/libs/rand" "github.com/tendermint/tendermint/libs/rand"
@ -226,7 +224,7 @@ func (sw *Switch) OnStart() error {
for _, reactor := range sw.reactors { for _, reactor := range sw.reactors {
err := reactor.Start() err := reactor.Start()
if err != nil { if err != nil {
return errors.Wrapf(err, "failed to start %v", reactor)
return fmt.Errorf("failed to start %v: %w", reactor, err)
} }
} }
@ -443,7 +441,7 @@ type privateAddr interface {
} }
func isPrivateAddr(err error) bool { func isPrivateAddr(err error) bool {
te, ok := errors.Cause(err).(privateAddr)
te, ok := err.(privateAddr)
return ok && te.PrivateAddr() return ok && te.PrivateAddr()
} }
@ -577,7 +575,7 @@ func (sw *Switch) AddUnconditionalPeerIDs(ids []string) error {
for i, id := range ids { for i, id := range ids {
err := validateID(ID(id)) err := validateID(ID(id))
if err != nil { if err != nil {
return errors.Wrapf(err, "wrong ID #%d", i)
return fmt.Errorf("wrong ID #%d: %w", i, err)
} }
sw.unconditionalPeerIDs[ID(id)] = struct{}{} sw.unconditionalPeerIDs[ID(id)] = struct{}{}
} }


+ 1
- 3
p2p/test_util.go View File

@ -5,8 +5,6 @@ import (
"net" "net"
"time" "time"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/crypto/ed25519" "github.com/tendermint/tendermint/crypto/ed25519"
"github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/libs/log"
@ -245,7 +243,7 @@ func testPeerConn(
// Encrypt connection // Encrypt connection
conn, err = upgradeSecretConn(conn, cfg.HandshakeTimeout, ourNodePrivKey) conn, err = upgradeSecretConn(conn, cfg.HandshakeTimeout, ourNodePrivKey)
if err != nil { if err != nil {
return pc, errors.Wrap(err, "Error creating peer")
return pc, fmt.Errorf("error creating peer: %w", err)
} }
// Only the information we already have // Only the information we already have


+ 1
- 2
p2p/transport.go View File

@ -6,7 +6,6 @@ import (
"net" "net"
"time" "time"
"github.com/pkg/errors"
"golang.org/x/net/netutil" "golang.org/x/net/netutil"
"github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto"
@ -288,7 +287,7 @@ func (mt *MultiplexTransport) acceptPeers() {
if r := recover(); r != nil { if r := recover(); r != nil {
err := ErrRejected{ err := ErrRejected{
conn: c, conn: c,
err: errors.Errorf("recovered from panic: %v", r),
err: fmt.Errorf("recovered from panic: %v", r),
isAuthFailure: true, isAuthFailure: true,
} }
select { select {


+ 3
- 5
privval/signer_client.go View File

@ -4,8 +4,6 @@ import (
"fmt" "fmt"
"time" "time"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/types" "github.com/tendermint/tendermint/types"
) )
@ -23,7 +21,7 @@ var _ types.PrivValidator = (*SignerClient)(nil)
func NewSignerClient(endpoint *SignerListenerEndpoint) (*SignerClient, error) { func NewSignerClient(endpoint *SignerListenerEndpoint) (*SignerClient, error) {
if !endpoint.IsRunning() { if !endpoint.IsRunning() {
if err := endpoint.Start(); err != nil { if err := endpoint.Start(); err != nil {
return nil, errors.Wrap(err, "failed to start listener endpoint")
return nil, fmt.Errorf("failed to start listener endpoint: %w", err)
} }
} }
@ -72,13 +70,13 @@ func (sc *SignerClient) GetPubKey() (crypto.PubKey, error) {
response, err := sc.endpoint.SendRequest(&PubKeyRequest{}) response, err := sc.endpoint.SendRequest(&PubKeyRequest{})
if err != nil { if err != nil {
sc.endpoint.Logger.Error("SignerClient::GetPubKey", "err", err) sc.endpoint.Logger.Error("SignerClient::GetPubKey", "err", err)
return nil, errors.Wrap(err, "send")
return nil, fmt.Errorf("send: %w", err)
} }
pubKeyResp, ok := response.(*PubKeyResponse) pubKeyResp, ok := response.(*PubKeyResponse)
if !ok { if !ok {
sc.endpoint.Logger.Error("SignerClient::GetPubKey", "err", "response != PubKeyResponse") sc.endpoint.Logger.Error("SignerClient::GetPubKey", "err", "response != PubKeyResponse")
return nil, errors.Errorf("unexpected response type %T", response)
return nil, fmt.Errorf("unexpected response type %T", response)
} }
if pubKeyResp.Error != nil { if pubKeyResp.Error != nil {


+ 5
- 7
privval/signer_endpoint.go View File

@ -6,8 +6,6 @@ import (
"sync" "sync"
"time" "time"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/libs/service" "github.com/tendermint/tendermint/libs/service"
) )
@ -100,9 +98,9 @@ func (se *signerEndpoint) ReadMessage() (msg SignerMessage, err error) {
_, err = cdc.UnmarshalBinaryLengthPrefixedReader(se.conn, &msg, maxRemoteSignerMsgSize) _, err = cdc.UnmarshalBinaryLengthPrefixedReader(se.conn, &msg, maxRemoteSignerMsgSize)
if _, ok := err.(timeoutError); ok { if _, ok := err.(timeoutError); ok {
if err != nil { if err != nil {
err = errors.Wrap(ErrReadTimeout, err.Error())
err = fmt.Errorf("%v: %w", err, ErrReadTimeout)
} else { } else {
err = errors.Wrap(ErrReadTimeout, "Empty error")
err = fmt.Errorf("empty error: %w", ErrReadTimeout)
} }
se.Logger.Debug("Dropping [read]", "obj", se) se.Logger.Debug("Dropping [read]", "obj", se)
se.dropConnection() se.dropConnection()
@ -117,7 +115,7 @@ func (se *signerEndpoint) WriteMessage(msg SignerMessage) (err error) {
defer se.connMtx.Unlock() defer se.connMtx.Unlock()
if !se.isConnected() { if !se.isConnected() {
return errors.Wrap(ErrNoConnection, "endpoint is not connected")
return fmt.Errorf("endpoint is not connected: %w", ErrNoConnection)
} }
// Reset read deadline // Reset read deadline
@ -130,9 +128,9 @@ func (se *signerEndpoint) WriteMessage(msg SignerMessage) (err error) {
_, err = cdc.MarshalBinaryLengthPrefixedWriter(se.conn, msg) _, err = cdc.MarshalBinaryLengthPrefixedWriter(se.conn, msg)
if _, ok := err.(timeoutError); ok { if _, ok := err.(timeoutError); ok {
if err != nil { if err != nil {
err = errors.Wrap(ErrWriteTimeout, err.Error())
err = fmt.Errorf("%v: %w", err, ErrWriteTimeout)
} else { } else {
err = errors.Wrap(ErrWriteTimeout, "Empty error")
err = fmt.Errorf("empty error: %w", ErrWriteTimeout)
} }
se.dropConnection() se.dropConnection()
} }


+ 1
- 2
privval/socket_dialers.go View File

@ -1,11 +1,10 @@
package privval package privval
import ( import (
"errors"
"net" "net"
"time" "time"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto"
tmnet "github.com/tendermint/tendermint/libs/net" tmnet "github.com/tendermint/tendermint/libs/net"
p2pconn "github.com/tendermint/tendermint/p2p/conn" p2pconn "github.com/tendermint/tendermint/p2p/conn"


+ 1
- 2
privval/socket_dialers_test.go View File

@ -5,7 +5,6 @@ import (
"testing" "testing"
"time" "time"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@ -44,6 +43,6 @@ func TestIsConnTimeoutForWrappedConnTimeouts(t *testing.T) {
dialer := DialTCPFn(tcpAddr, time.Millisecond, ed25519.GenPrivKey()) dialer := DialTCPFn(tcpAddr, time.Millisecond, ed25519.GenPrivKey())
_, err := dialer() _, err := dialer()
assert.Error(t, err) assert.Error(t, err)
err = errors.Wrap(ErrConnectionTimeout, err.Error())
err = fmt.Errorf("%v: %w", err, ErrConnectionTimeout)
assert.True(t, IsConnTimeout(err)) assert.True(t, IsConnTimeout(err))
} }

+ 5
- 5
privval/utils.go View File

@ -1,11 +1,10 @@
package privval package privval
import ( import (
"errors"
"fmt" "fmt"
"net" "net"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/crypto/ed25519" "github.com/tendermint/tendermint/crypto/ed25519"
"github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/libs/log"
tmnet "github.com/tendermint/tendermint/libs/net" tmnet "github.com/tendermint/tendermint/libs/net"
@ -15,10 +14,11 @@ import (
// report that a connection timeout occurred. This detects both fundamental // report that a connection timeout occurred. This detects both fundamental
// network timeouts, as well as ErrConnTimeout errors. // network timeouts, as well as ErrConnTimeout errors.
func IsConnTimeout(err error) bool { func IsConnTimeout(err error) bool {
switch errors.Cause(err).(type) {
case EndpointTimeoutError:
_, ok := errors.Unwrap(err).(timeoutError)
switch {
case errors.As(err, &EndpointTimeoutError{}):
return true return true
case timeoutError:
case ok:
return true return true
default: default:
return false return false


+ 3
- 2
privval/utils_test.go View File

@ -1,13 +1,14 @@
package privval package privval
import ( import (
"errors"
"fmt"
"testing" "testing"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func TestIsConnTimeoutForNonTimeoutErrors(t *testing.T) { func TestIsConnTimeoutForNonTimeoutErrors(t *testing.T) {
assert.False(t, IsConnTimeout(errors.Wrap(ErrDialRetryMax, "max retries exceeded")))
assert.False(t, IsConnTimeout(fmt.Errorf("max retries exceeded: %w", ErrDialRetryMax)))
assert.False(t, IsConnTimeout(errors.New("completely irrelevant error"))) assert.False(t, IsConnTimeout(errors.New("completely irrelevant error")))
} }

+ 2
- 3
proxy/client.go View File

@ -1,10 +1,9 @@
package proxy package proxy
import ( import (
"fmt"
"sync" "sync"
"github.com/pkg/errors"
abcicli "github.com/tendermint/tendermint/abci/client" abcicli "github.com/tendermint/tendermint/abci/client"
"github.com/tendermint/tendermint/abci/example/counter" "github.com/tendermint/tendermint/abci/example/counter"
"github.com/tendermint/tendermint/abci/example/kvstore" "github.com/tendermint/tendermint/abci/example/kvstore"
@ -55,7 +54,7 @@ func NewRemoteClientCreator(addr, transport string, mustConnect bool) ClientCrea
func (r *remoteClientCreator) NewABCIClient() (abcicli.Client, error) { func (r *remoteClientCreator) NewABCIClient() (abcicli.Client, error) {
remoteApp, err := abcicli.NewClient(r.addr, r.transport, r.mustConnect) remoteApp, err := abcicli.NewClient(r.addr, r.transport, r.mustConnect)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "Failed to connect to proxy")
return nil, fmt.Errorf("failed to connect to proxy: %w", err)
} }
return remoteApp, nil return remoteApp, nil
} }


+ 4
- 4
rpc/client/helpers.go View File

@ -2,10 +2,10 @@ package client
import ( import (
"context" "context"
"errors"
"fmt"
"time" "time"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/types" "github.com/tendermint/tendermint/types"
) )
@ -16,7 +16,7 @@ type Waiter func(delta int64) (abort error)
// but you can plug in another one // but you can plug in another one
func DefaultWaitStrategy(delta int64) (abort error) { func DefaultWaitStrategy(delta int64) (abort error) {
if delta > 10 { if delta > 10 {
return errors.Errorf("waiting for %d blocks... aborting", delta)
return fmt.Errorf("waiting for %d blocks... aborting", delta)
} else if delta > 0 { } else if delta > 0 {
// estimate of wait time.... // estimate of wait time....
// wait half a second for the next block (in progress) // wait half a second for the next block (in progress)
@ -64,7 +64,7 @@ func WaitForOneEvent(c EventsClient, evtTyp string, timeout time.Duration) (type
// register for the next event of this type // register for the next event of this type
eventCh, err := c.Subscribe(ctx, subscriber, types.QueryForEvent(evtTyp).String()) eventCh, err := c.Subscribe(ctx, subscriber, types.QueryForEvent(evtTyp).String())
if err != nil { if err != nil {
return nil, errors.Wrap(err, "failed to subscribe")
return nil, fmt.Errorf("failed to subscribe: %w", err)
} }
// make sure to unregister after the test is over // make sure to unregister after the test is over
defer c.UnsubscribeAll(ctx, subscriber) defer c.UnsubscribeAll(ctx, subscriber)


+ 3
- 4
rpc/client/http/http.go View File

@ -2,13 +2,12 @@ package http
import ( import (
"context" "context"
"errors"
"net/http" "net/http"
"strings" "strings"
"sync" "sync"
"time" "time"
"github.com/pkg/errors"
amino "github.com/tendermint/go-amino" amino "github.com/tendermint/go-amino"
"github.com/tendermint/tendermint/libs/bytes" "github.com/tendermint/tendermint/libs/bytes"
@ -308,7 +307,7 @@ func (c *baseRPCClient) ConsensusState() (*ctypes.ResultConsensusState, error) {
result := new(ctypes.ResultConsensusState) result := new(ctypes.ResultConsensusState)
_, err := c.caller.Call("consensus_state", map[string]interface{}{}, result) _, err := c.caller.Call("consensus_state", map[string]interface{}{}, result)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "ConsensusState")
return nil, err
} }
return result, nil return result, nil
} }
@ -402,7 +401,7 @@ func (c *baseRPCClient) Tx(hash []byte, prove bool) (*ctypes.ResultTx, error) {
} }
_, err := c.caller.Call("tx", params, result) _, err := c.caller.Call("tx", params, result)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "Tx")
return nil, err
} }
return result, nil return result, nil
} }


+ 4
- 5
rpc/client/local/local.go View File

@ -2,10 +2,9 @@ package local
import ( import (
"context" "context"
"fmt"
"time" "time"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/libs/bytes" "github.com/tendermint/tendermint/libs/bytes"
"github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/libs/log"
tmpubsub "github.com/tendermint/tendermint/libs/pubsub" tmpubsub "github.com/tendermint/tendermint/libs/pubsub"
@ -177,7 +176,7 @@ func (c *Local) Subscribe(
outCapacity ...int) (out <-chan ctypes.ResultEvent, err error) { outCapacity ...int) (out <-chan ctypes.ResultEvent, err error) {
q, err := tmquery.New(query) q, err := tmquery.New(query)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "failed to parse query")
return nil, fmt.Errorf("failed to parse query: %w", err)
} }
outCap := 1 outCap := 1
@ -192,7 +191,7 @@ func (c *Local) Subscribe(
sub, err = c.EventBus.SubscribeUnbuffered(ctx, subscriber, q) sub, err = c.EventBus.SubscribeUnbuffered(ctx, subscriber, q)
} }
if err != nil { if err != nil {
return nil, errors.Wrap(err, "failed to subscribe")
return nil, fmt.Errorf("failed to subscribe: %w", err)
} }
outc := make(chan ctypes.ResultEvent, outCap) outc := make(chan ctypes.ResultEvent, outCap)
@ -256,7 +255,7 @@ func (c *Local) resubscribe(subscriber string, q tmpubsub.Query) types.Subscript
func (c *Local) Unsubscribe(ctx context.Context, subscriber, query string) error { func (c *Local) Unsubscribe(ctx context.Context, subscriber, query string) error {
q, err := tmquery.New(query) q, err := tmquery.New(query)
if err != nil { if err != nil {
return errors.Wrap(err, "failed to parse query")
return fmt.Errorf("failed to parse query: %w", err)
} }
return c.EventBus.Unsubscribe(ctx, subscriber, q) return c.EventBus.Unsubscribe(ctx, subscriber, q)
} }


+ 1
- 2
rpc/client/mock/abci_test.go View File

@ -1,11 +1,10 @@
package mock_test package mock_test
import ( import (
"errors"
"fmt" "fmt"
"testing" "testing"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"


+ 2
- 4
rpc/core/events.go View File

@ -4,8 +4,6 @@ import (
"context" "context"
"fmt" "fmt"
"github.com/pkg/errors"
tmpubsub "github.com/tendermint/tendermint/libs/pubsub" tmpubsub "github.com/tendermint/tendermint/libs/pubsub"
tmquery "github.com/tendermint/tendermint/libs/pubsub/query" tmquery "github.com/tendermint/tendermint/libs/pubsub/query"
ctypes "github.com/tendermint/tendermint/rpc/core/types" ctypes "github.com/tendermint/tendermint/rpc/core/types"
@ -32,7 +30,7 @@ func Subscribe(ctx *rpctypes.Context, query string) (*ctypes.ResultSubscribe, er
q, err := tmquery.New(query) q, err := tmquery.New(query)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "failed to parse query")
return nil, fmt.Errorf("failed to parse query: %w", err)
} }
subCtx, cancel := context.WithTimeout(ctx.Context(), SubscribeTimeout) subCtx, cancel := context.WithTimeout(ctx.Context(), SubscribeTimeout)
@ -85,7 +83,7 @@ func Unsubscribe(ctx *rpctypes.Context, query string) (*ctypes.ResultUnsubscribe
logger.Info("Unsubscribe from query", "remote", addr, "query", query) logger.Info("Unsubscribe from query", "remote", addr, "query", query)
q, err := tmquery.New(query) q, err := tmquery.New(query)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "failed to parse query")
return nil, fmt.Errorf("failed to parse query: %w", err)
} }
err = eventBus.Unsubscribe(context.Background(), addr, q) err = eventBus.Unsubscribe(context.Background(), addr, q)
if err != nil { if err != nil {


+ 2
- 3
rpc/core/mempool.go View File

@ -2,11 +2,10 @@ package core
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"time" "time"
"github.com/pkg/errors"
abci "github.com/tendermint/tendermint/abci/types" abci "github.com/tendermint/tendermint/abci/types"
mempl "github.com/tendermint/tendermint/mempool" mempl "github.com/tendermint/tendermint/mempool"
ctypes "github.com/tendermint/tendermint/rpc/core/types" ctypes "github.com/tendermint/tendermint/rpc/core/types"
@ -68,7 +67,7 @@ func BroadcastTxCommit(ctx *rpctypes.Context, tx types.Tx) (*ctypes.ResultBroadc
q := types.EventQueryTxFor(tx) q := types.EventQueryTxFor(tx)
deliverTxSub, err := eventBus.Subscribe(subCtx, subscriber, q) deliverTxSub, err := eventBus.Subscribe(subCtx, subscriber, q)
if err != nil { if err != nil {
err = errors.Wrap(err, "failed to subscribe to tx")
err = fmt.Errorf("failed to subscribe to tx: %w", err)
logger.Error("Error on broadcast_tx_commit", "err", err) logger.Error("Error on broadcast_tx_commit", "err", err)
return nil, err return nil, err
} }


+ 1
- 2
rpc/core/net.go View File

@ -1,10 +1,9 @@
package core package core
import ( import (
"errors"
"fmt" "fmt"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/p2p"
ctypes "github.com/tendermint/tendermint/rpc/core/types" ctypes "github.com/tendermint/tendermint/rpc/core/types"
rpctypes "github.com/tendermint/tendermint/rpc/lib/types" rpctypes "github.com/tendermint/tendermint/rpc/lib/types"


+ 1
- 2
rpc/core/tx.go View File

@ -1,11 +1,10 @@
package core package core
import ( import (
"errors"
"fmt" "fmt"
"sort" "sort"
"github.com/pkg/errors"
tmmath "github.com/tendermint/tendermint/libs/math" tmmath "github.com/tendermint/tendermint/libs/math"
tmquery "github.com/tendermint/tendermint/libs/pubsub/query" tmquery "github.com/tendermint/tendermint/libs/pubsub/query"
ctypes "github.com/tendermint/tendermint/rpc/core/types" ctypes "github.com/tendermint/tendermint/rpc/core/types"


+ 13
- 13
rpc/lib/client/decode.go View File

@ -2,8 +2,8 @@ package rpcclient
import ( import (
"encoding/json" "encoding/json"
"github.com/pkg/errors"
"errors"
"fmt"
amino "github.com/tendermint/go-amino" amino "github.com/tendermint/go-amino"
@ -21,7 +21,7 @@ func unmarshalResponseBytes(
// into the correct type. // into the correct type.
response := &types.RPCResponse{} response := &types.RPCResponse{}
if err := json.Unmarshal(responseBytes, response); err != nil { if err := json.Unmarshal(responseBytes, response); err != nil {
return nil, errors.Wrap(err, "error unmarshalling")
return nil, fmt.Errorf("error unmarshalling: %w", err)
} }
if response.Error != nil { if response.Error != nil {
@ -29,12 +29,12 @@ func unmarshalResponseBytes(
} }
if err := validateAndVerifyID(response, expectedID); err != nil { if err := validateAndVerifyID(response, expectedID); err != nil {
return nil, errors.Wrap(err, "wrong ID")
return nil, fmt.Errorf("wrong ID: %w", err)
} }
// Unmarshal the RawMessage into the result. // Unmarshal the RawMessage into the result.
if err := cdc.UnmarshalJSON(response.Result, result); err != nil { if err := cdc.UnmarshalJSON(response.Result, result); err != nil {
return nil, errors.Wrap(err, "error unmarshalling result")
return nil, fmt.Errorf("error unmarshalling result: %w", err)
} }
return result, nil return result, nil
@ -52,14 +52,14 @@ func unmarshalResponseBytesArray(
) )
if err := json.Unmarshal(responseBytes, &responses); err != nil { if err := json.Unmarshal(responseBytes, &responses); err != nil {
return nil, errors.Wrap(err, "error unmarshalling")
return nil, fmt.Errorf("error unmarshalling: %w", err)
} }
// No response error checking here as there may be a mixture of successful // No response error checking here as there may be a mixture of successful
// and unsuccessful responses. // and unsuccessful responses.
if len(results) != len(responses) { if len(results) != len(responses) {
return nil, errors.Errorf(
return nil, fmt.Errorf(
"expected %d result objects into which to inject responses, but got %d", "expected %d result objects into which to inject responses, but got %d",
len(responses), len(responses),
len(results), len(results),
@ -72,16 +72,16 @@ func unmarshalResponseBytesArray(
for i, resp := range responses { for i, resp := range responses {
ids[i], ok = resp.ID.(types.JSONRPCIntID) ids[i], ok = resp.ID.(types.JSONRPCIntID)
if !ok { if !ok {
return nil, errors.Errorf("expected JSONRPCIntID, got %T", resp.ID)
return nil, fmt.Errorf("expected JSONRPCIntID, got %T", resp.ID)
} }
} }
if err := validateResponseIDs(ids, expectedIDs); err != nil { if err := validateResponseIDs(ids, expectedIDs); err != nil {
return nil, errors.Wrap(err, "wrong IDs")
return nil, fmt.Errorf("wrong IDs: %w", err)
} }
for i := 0; i < len(responses); i++ { for i := 0; i < len(responses); i++ {
if err := cdc.UnmarshalJSON(responses[i].Result, results[i]); err != nil { if err := cdc.UnmarshalJSON(responses[i].Result, results[i]); err != nil {
return nil, errors.Wrapf(err, "error unmarshalling #%d result", i)
return nil, fmt.Errorf("error unmarshalling #%d result: %w", i, err)
} }
} }
@ -98,7 +98,7 @@ func validateResponseIDs(ids, expectedIDs []types.JSONRPCIntID) error {
if m[id] { if m[id] {
delete(m, id) delete(m, id)
} else { } else {
return errors.Errorf("unsolicited ID #%d: %v", i, id)
return fmt.Errorf("unsolicited ID #%d: %v", i, id)
} }
} }
@ -112,7 +112,7 @@ func validateAndVerifyID(res *types.RPCResponse, expectedID types.JSONRPCIntID)
return err return err
} }
if expectedID != res.ID.(types.JSONRPCIntID) { // validateResponseID ensured res.ID has the right type if expectedID != res.ID.(types.JSONRPCIntID) { // validateResponseID ensured res.ID has the right type
return errors.Errorf("response ID (%d) does not match request ID (%d)", res.ID, expectedID)
return fmt.Errorf("response ID (%d) does not match request ID (%d)", res.ID, expectedID)
} }
return nil return nil
} }
@ -123,7 +123,7 @@ func validateResponseID(id interface{}) error {
} }
_, ok := id.(types.JSONRPCIntID) _, ok := id.(types.JSONRPCIntID)
if !ok { if !ok {
return errors.Errorf("expected JSONRPCIntID, but got: %T", id)
return fmt.Errorf("expected JSONRPCIntID, but got: %T", id)
} }
return nil return nil
} }

+ 9
- 10
rpc/lib/client/http_json_client.go View File

@ -11,7 +11,6 @@ import (
"strings" "strings"
"sync" "sync"
"github.com/pkg/errors"
amino "github.com/tendermint/go-amino" amino "github.com/tendermint/go-amino"
types "github.com/tendermint/tendermint/rpc/lib/types" types "github.com/tendermint/tendermint/rpc/lib/types"
@ -168,18 +167,18 @@ func (c *JSONRPCClient) Call(method string, params map[string]interface{}, resul
request, err := types.MapToRequest(c.cdc, id, method, params) request, err := types.MapToRequest(c.cdc, id, method, params)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "failed to encode params")
return nil, fmt.Errorf("failed to encode params: %w", err)
} }
requestBytes, err := json.Marshal(request) requestBytes, err := json.Marshal(request)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "failed to marshal request")
return nil, fmt.Errorf("failed to marshal request: %w", err)
} }
requestBuf := bytes.NewBuffer(requestBytes) requestBuf := bytes.NewBuffer(requestBytes)
httpRequest, err := http.NewRequest(http.MethodPost, c.address, requestBuf) httpRequest, err := http.NewRequest(http.MethodPost, c.address, requestBuf)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "Request failed")
return nil, fmt.Errorf("request failed: %w", err)
} }
httpRequest.Header.Set("Content-Type", "text/json") httpRequest.Header.Set("Content-Type", "text/json")
if c.username != "" || c.password != "" { if c.username != "" || c.password != "" {
@ -187,13 +186,13 @@ func (c *JSONRPCClient) Call(method string, params map[string]interface{}, resul
} }
httpResponse, err := c.client.Do(httpRequest) httpResponse, err := c.client.Do(httpRequest)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "Post failed")
return nil, fmt.Errorf("post failed: %w", err)
} }
defer httpResponse.Body.Close() // nolint: errcheck defer httpResponse.Body.Close() // nolint: errcheck
responseBytes, err := ioutil.ReadAll(httpResponse.Body) responseBytes, err := ioutil.ReadAll(httpResponse.Body)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "failed to read response body")
return nil, fmt.Errorf("failed to read response body: %w", err)
} }
return unmarshalResponseBytes(c.cdc, responseBytes, id, result) return unmarshalResponseBytes(c.cdc, responseBytes, id, result)
@ -221,12 +220,12 @@ func (c *JSONRPCClient) sendBatch(requests []*jsonRPCBufferedRequest) ([]interfa
// serialize the array of requests into a single JSON object // serialize the array of requests into a single JSON object
requestBytes, err := json.Marshal(reqs) requestBytes, err := json.Marshal(reqs)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "failed to marshal requests")
return nil, fmt.Errorf("failed to marshal requests: %w", err)
} }
httpRequest, err := http.NewRequest(http.MethodPost, c.address, bytes.NewBuffer(requestBytes)) httpRequest, err := http.NewRequest(http.MethodPost, c.address, bytes.NewBuffer(requestBytes))
if err != nil { if err != nil {
return nil, errors.Wrap(err, "Request failed")
return nil, fmt.Errorf("request failed: %w", err)
} }
httpRequest.Header.Set("Content-Type", "text/json") httpRequest.Header.Set("Content-Type", "text/json")
if c.username != "" || c.password != "" { if c.username != "" || c.password != "" {
@ -234,13 +233,13 @@ func (c *JSONRPCClient) sendBatch(requests []*jsonRPCBufferedRequest) ([]interfa
} }
httpResponse, err := c.client.Do(httpRequest) httpResponse, err := c.client.Do(httpRequest)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "Post failed")
return nil, fmt.Errorf("post failed: %w", err)
} }
defer httpResponse.Body.Close() // nolint: errcheck defer httpResponse.Body.Close() // nolint: errcheck
responseBytes, err := ioutil.ReadAll(httpResponse.Body) responseBytes, err := ioutil.ReadAll(httpResponse.Body)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "failed to read response body")
return nil, fmt.Errorf("failed to read response body: %w", err)
} }
// collect ids to check responses IDs in unmarshalResponseBytesArray // collect ids to check responses IDs in unmarshalResponseBytesArray


+ 4
- 5
rpc/lib/client/http_uri_client.go View File

@ -1,11 +1,10 @@
package rpcclient package rpcclient
import ( import (
"fmt"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"github.com/pkg/errors"
amino "github.com/tendermint/go-amino" amino "github.com/tendermint/go-amino"
types "github.com/tendermint/tendermint/rpc/lib/types" types "github.com/tendermint/tendermint/rpc/lib/types"
@ -60,18 +59,18 @@ func NewURIClient(remote string) (*URIClient, error) {
func (c *URIClient) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) { func (c *URIClient) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) {
values, err := argsToURLValues(c.cdc, params) values, err := argsToURLValues(c.cdc, params)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "failed to encode params")
return nil, fmt.Errorf("failed to encode params: %w", err)
} }
resp, err := c.client.PostForm(c.address+"/"+method, values) resp, err := c.client.PostForm(c.address+"/"+method, values)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "PostForm failed")
return nil, fmt.Errorf("post form failed: %w", err)
} }
defer resp.Body.Close() // nolint: errcheck defer resp.Body.Close() // nolint: errcheck
responseBytes, err := ioutil.ReadAll(resp.Body) responseBytes, err := ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "failed to read response body")
return nil, fmt.Errorf("failed to read response body: %w", err)
} }
return unmarshalResponseBytes(c.cdc, responseBytes, URIClientRequestID, result) return unmarshalResponseBytes(c.cdc, responseBytes, URIClientRequestID, result)


+ 1
- 2
rpc/lib/client/ws_client.go View File

@ -10,7 +10,6 @@ import (
"time" "time"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
"github.com/pkg/errors"
metrics "github.com/rcrowley/go-metrics" metrics "github.com/rcrowley/go-metrics"
amino "github.com/tendermint/go-amino" amino "github.com/tendermint/go-amino"
@ -315,7 +314,7 @@ func (c *WSClient) reconnect() error {
attempt++ attempt++
if attempt > c.maxReconnectAttempts { if attempt > c.maxReconnectAttempts {
return errors.Wrap(err, "reached maximum reconnect attempts")
return fmt.Errorf("reached maximum reconnect attempts: %w", err)
} }
} }
} }


+ 6
- 8
rpc/lib/server/http_json_handler.go View File

@ -9,8 +9,6 @@ import (
"reflect" "reflect"
"sort" "sort"
"github.com/pkg/errors"
amino "github.com/tendermint/go-amino" amino "github.com/tendermint/go-amino"
"github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/libs/log"
@ -30,7 +28,7 @@ func makeJSONRPCHandler(funcMap map[string]*RPCFunc, cdc *amino.Codec, logger lo
w, w,
types.RPCInvalidRequestError( types.RPCInvalidRequestError(
nil, nil,
errors.Wrap(err, "error reading request body"),
fmt.Errorf("error reading request body: %w", err),
), ),
) )
return return
@ -55,7 +53,7 @@ func makeJSONRPCHandler(funcMap map[string]*RPCFunc, cdc *amino.Codec, logger lo
WriteRPCResponseHTTP( WriteRPCResponseHTTP(
w, w,
types.RPCParseError( types.RPCParseError(
errors.Wrap(err, "error unmarshalling request"),
fmt.Errorf("error unmarshalling request: %w", err),
), ),
) )
return return
@ -78,7 +76,7 @@ func makeJSONRPCHandler(funcMap map[string]*RPCFunc, cdc *amino.Codec, logger lo
if len(r.URL.Path) > 1 { if len(r.URL.Path) > 1 {
responses = append( responses = append(
responses, responses,
types.RPCInvalidRequestError(request.ID, errors.Errorf("path %s is invalid", r.URL.Path)),
types.RPCInvalidRequestError(request.ID, fmt.Errorf("path %s is invalid", r.URL.Path)),
) )
continue continue
} }
@ -94,7 +92,7 @@ func makeJSONRPCHandler(funcMap map[string]*RPCFunc, cdc *amino.Codec, logger lo
if err != nil { if err != nil {
responses = append( responses = append(
responses, responses,
types.RPCInvalidParamsError(request.ID, errors.Wrap(err, "error converting json params to arguments")),
types.RPCInvalidParamsError(request.ID, fmt.Errorf("error converting json params to arguments: %w", err)),
) )
continue continue
} }
@ -162,7 +160,7 @@ func arrayParamsToArgs(
) ([]reflect.Value, error) { ) ([]reflect.Value, error) {
if len(rpcFunc.argNames) != len(params) { if len(rpcFunc.argNames) != len(params) {
return nil, errors.Errorf("expected %v parameters (%v), got %v (%v)",
return nil, fmt.Errorf("expected %v parameters (%v), got %v (%v)",
len(rpcFunc.argNames), rpcFunc.argNames, len(params), params) len(rpcFunc.argNames), rpcFunc.argNames, len(params), params)
} }
@ -204,7 +202,7 @@ func jsonParamsToArgs(rpcFunc *RPCFunc, cdc *amino.Codec, raw []byte) ([]reflect
} }
// Otherwise, bad format, we cannot parse // Otherwise, bad format, we cannot parse
return nil, errors.Errorf("unknown type for JSON params: %v. Expected map or array", err)
return nil, fmt.Errorf("unknown type for JSON params: %v. Expected map or array", err)
} }
// writes a list of available rpc endpoints as an html page // writes a list of available rpc endpoints as an html page


+ 7
- 8
rpc/lib/server/http_params.go View File

@ -2,11 +2,10 @@ package rpcserver
import ( import (
"encoding/hex" "encoding/hex"
"fmt"
"net/http" "net/http"
"regexp" "regexp"
"strconv" "strconv"
"github.com/pkg/errors"
) )
var ( var (
@ -41,7 +40,7 @@ func GetParamInt64(r *http.Request, param string) (int64, error) {
s := GetParam(r, param) s := GetParam(r, param)
i, err := strconv.ParseInt(s, 10, 64) i, err := strconv.ParseInt(s, 10, 64)
if err != nil { if err != nil {
return 0, errors.Errorf(param, err.Error())
return 0, fmt.Errorf(param, err.Error())
} }
return i, nil return i, nil
} }
@ -50,7 +49,7 @@ func GetParamInt32(r *http.Request, param string) (int32, error) {
s := GetParam(r, param) s := GetParam(r, param)
i, err := strconv.ParseInt(s, 10, 32) i, err := strconv.ParseInt(s, 10, 32)
if err != nil { if err != nil {
return 0, errors.Errorf(param, err.Error())
return 0, fmt.Errorf(param, err.Error())
} }
return int32(i), nil return int32(i), nil
} }
@ -59,7 +58,7 @@ func GetParamUint64(r *http.Request, param string) (uint64, error) {
s := GetParam(r, param) s := GetParam(r, param)
i, err := strconv.ParseUint(s, 10, 64) i, err := strconv.ParseUint(s, 10, 64)
if err != nil { if err != nil {
return 0, errors.Errorf(param, err.Error())
return 0, fmt.Errorf(param, err.Error())
} }
return i, nil return i, nil
} }
@ -68,7 +67,7 @@ func GetParamUint(r *http.Request, param string) (uint, error) {
s := GetParam(r, param) s := GetParam(r, param)
i, err := strconv.ParseUint(s, 10, 64) i, err := strconv.ParseUint(s, 10, 64)
if err != nil { if err != nil {
return 0, errors.Errorf(param, err.Error())
return 0, fmt.Errorf(param, err.Error())
} }
return uint(i), nil return uint(i), nil
} }
@ -76,7 +75,7 @@ func GetParamUint(r *http.Request, param string) (uint, error) {
func GetParamRegexp(r *http.Request, param string, re *regexp.Regexp) (string, error) { func GetParamRegexp(r *http.Request, param string, re *regexp.Regexp) (string, error) {
s := GetParam(r, param) s := GetParam(r, param)
if !re.MatchString(s) { if !re.MatchString(s) {
return "", errors.Errorf(param, "did not match regular expression %v", re.String())
return "", fmt.Errorf(param, "did not match regular expression %v", re.String())
} }
return s, nil return s, nil
} }
@ -85,7 +84,7 @@ func GetParamFloat64(r *http.Request, param string) (float64, error) {
s := GetParam(r, param) s := GetParam(r, param)
f, err := strconv.ParseFloat(s, 64) f, err := strconv.ParseFloat(s, 64)
if err != nil { if err != nil {
return 0, errors.Errorf(param, err.Error())
return 0, fmt.Errorf(param, err.Error())
} }
return f, nil return f, nil
} }

+ 3
- 3
rpc/lib/server/http_server.go View File

@ -4,6 +4,7 @@ package rpcserver
import ( import (
"bufio" "bufio"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"net" "net"
"net/http" "net/http"
@ -12,7 +13,6 @@ import (
"strings" "strings"
"time" "time"
"github.com/pkg/errors"
"golang.org/x/net/netutil" "golang.org/x/net/netutil"
"github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/libs/log"
@ -241,7 +241,7 @@ func (h maxBytesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
func Listen(addr string, config *Config) (listener net.Listener, err error) { func Listen(addr string, config *Config) (listener net.Listener, err error) {
parts := strings.SplitN(addr, "://", 2) parts := strings.SplitN(addr, "://", 2)
if len(parts) != 2 { if len(parts) != 2 {
return nil, errors.Errorf(
return nil, fmt.Errorf(
"invalid listening address %s (use fully formed addresses, including the tcp:// or unix:// prefix)", "invalid listening address %s (use fully formed addresses, including the tcp:// or unix:// prefix)",
addr, addr,
) )
@ -249,7 +249,7 @@ func Listen(addr string, config *Config) (listener net.Listener, err error) {
proto, addr := parts[0], parts[1] proto, addr := parts[0], parts[1]
listener, err = net.Listen(proto, addr) listener, err = net.Listen(proto, addr)
if err != nil { if err != nil {
return nil, errors.Errorf("failed to listen on %v: %v", addr, err)
return nil, fmt.Errorf("failed to listen on %v: %v", addr, err)
} }
if config.MaxOpenConnections > 0 { if config.MaxOpenConnections > 0 {
listener = netutil.LimitListener(listener, config.MaxOpenConnections) listener = netutil.LimitListener(listener, config.MaxOpenConnections)


+ 3
- 4
rpc/lib/server/http_uri_handler.go View File

@ -2,12 +2,11 @@ package rpcserver
import ( import (
"encoding/hex" "encoding/hex"
"fmt"
"net/http" "net/http"
"reflect" "reflect"
"strings" "strings"
"github.com/pkg/errors"
amino "github.com/tendermint/go-amino" amino "github.com/tendermint/go-amino"
"github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/libs/log"
@ -43,7 +42,7 @@ func makeHTTPHandler(rpcFunc *RPCFunc, cdc *amino.Codec, logger log.Logger) func
w, w,
types.RPCInvalidParamsError( types.RPCInvalidParamsError(
dummyID, dummyID,
errors.Wrap(err, "error converting http params to arguments"),
fmt.Errorf("error converting http params to arguments: %w", err),
), ),
) )
return return
@ -165,7 +164,7 @@ func _nonJSONStringToArg(cdc *amino.Codec, rt reflect.Type, arg string) (reflect
if isHexString { if isHexString {
if !expectingString && !expectingByteSlice { if !expectingString && !expectingByteSlice {
err := errors.Errorf("got a hex string arg, but expected '%s'",
err := fmt.Errorf("got a hex string arg, but expected '%s'",
rt.Kind().String()) rt.Kind().String())
return reflect.ValueOf(nil), false, err return reflect.ValueOf(nil), false, err
} }


+ 2
- 3
rpc/lib/server/rpc_func.go View File

@ -1,12 +1,11 @@
package rpcserver package rpcserver
import ( import (
"fmt"
"net/http" "net/http"
"reflect" "reflect"
"strings" "strings"
"github.com/pkg/errors"
amino "github.com/tendermint/go-amino" amino "github.com/tendermint/go-amino"
"github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/libs/log"
@ -92,7 +91,7 @@ func funcReturnTypes(f interface{}) []reflect.Type {
func unreflectResult(returns []reflect.Value) (interface{}, error) { func unreflectResult(returns []reflect.Value) (interface{}, error) {
errV := returns[1] errV := returns[1]
if errV.Interface() != nil { if errV.Interface() != nil {
return nil, errors.Errorf("%v", errV.Interface())
return nil, fmt.Errorf("%v", errV.Interface())
} }
rv := returns[0] rv := returns[0]
// the result is a registered interface, // the result is a registered interface,


+ 2
- 3
rpc/lib/server/ws_handler.go View File

@ -10,7 +10,6 @@ import (
"time" "time"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
"github.com/pkg/errors"
amino "github.com/tendermint/go-amino" amino "github.com/tendermint/go-amino"
@ -340,7 +339,7 @@ func (wsc *wsConnection) readRoutine() {
var request types.RPCRequest var request types.RPCRequest
err = json.Unmarshal(in, &request) err = json.Unmarshal(in, &request)
if err != nil { if err != nil {
wsc.WriteRPCResponse(types.RPCParseError(errors.Wrap(err, "error unmarshaling request")))
wsc.WriteRPCResponse(types.RPCParseError(fmt.Errorf("error unmarshaling request: %w", err)))
continue continue
} }
@ -367,7 +366,7 @@ func (wsc *wsConnection) readRoutine() {
fnArgs, err := jsonParamsToArgs(rpcFunc, wsc.cdc, request.Params) fnArgs, err := jsonParamsToArgs(rpcFunc, wsc.cdc, request.Params)
if err != nil { if err != nil {
wsc.WriteRPCResponse( wsc.WriteRPCResponse(
types.RPCInternalError(request.ID, errors.Wrap(err, "error converting json params to arguments")),
types.RPCInternalError(request.ID, fmt.Errorf("error converting json params to arguments: %w", err)),
) )
continue continue
} }


+ 1
- 3
rpc/lib/types/types.go View File

@ -8,8 +8,6 @@ import (
"reflect" "reflect"
"strings" "strings"
"github.com/pkg/errors"
amino "github.com/tendermint/go-amino" amino "github.com/tendermint/go-amino"
) )
@ -189,7 +187,7 @@ func NewRPCSuccessResponse(cdc *amino.Codec, id jsonrpcid, res interface{}) RPCR
var js []byte var js []byte
js, err := cdc.MarshalJSON(res) js, err := cdc.MarshalJSON(res)
if err != nil { if err != nil {
return RPCInternalError(id, errors.Wrap(err, "Error marshalling response"))
return RPCInternalError(id, fmt.Errorf("error marshalling response: %w", err))
} }
rawMsg = json.RawMessage(js) rawMsg = json.RawMessage(js)
} }


+ 2
- 3
rpc/lib/types/types_test.go View File

@ -2,11 +2,10 @@ package rpctypes
import ( import (
"encoding/json" "encoding/json"
"testing"
"errors"
"fmt" "fmt"
"testing"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
amino "github.com/tendermint/go-amino" amino "github.com/tendermint/go-amino"
) )


+ 4
- 6
state/txindex/kv/kv.go View File

@ -9,8 +9,6 @@ import (
"strings" "strings"
"time" "time"
"github.com/pkg/errors"
dbm "github.com/tendermint/tm-db" dbm "github.com/tendermint/tm-db"
"github.com/tendermint/tendermint/libs/pubsub/query" "github.com/tendermint/tendermint/libs/pubsub/query"
@ -186,18 +184,18 @@ func (txi *TxIndex) Search(ctx context.Context, q *query.Query) ([]*types.TxResu
// get a list of conditions (like "tx.height > 5") // get a list of conditions (like "tx.height > 5")
conditions, err := q.Conditions() conditions, err := q.Conditions()
if err != nil { if err != nil {
return nil, errors.Wrap(err, "error during parsing conditions from query")
return nil, fmt.Errorf("error during parsing conditions from query: %w", err)
} }
// if there is a hash condition, return the result immediately // if there is a hash condition, return the result immediately
hash, ok, err := lookForHash(conditions) hash, ok, err := lookForHash(conditions)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "error during searching for a hash in the query")
return nil, fmt.Errorf("error during searching for a hash in the query: %w", err)
} else if ok { } else if ok {
res, err := txi.Get(hash) res, err := txi.Get(hash)
switch { switch {
case err != nil: case err != nil:
return []*types.TxResult{}, errors.Wrap(err, "error while retrieving the result")
return []*types.TxResult{}, fmt.Errorf("error while retrieving the result: %w", err)
case res == nil: case res == nil:
return []*types.TxResult{}, nil return []*types.TxResult{}, nil
default: default:
@ -258,7 +256,7 @@ func (txi *TxIndex) Search(ctx context.Context, q *query.Query) ([]*types.TxResu
for _, h := range filteredHashes { for _, h := range filteredHashes {
res, err := txi.Get(h) res, err := txi.Get(h)
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "failed to get Tx{%X}", h)
return nil, fmt.Errorf("failed to get Tx{%X}: %w", h, err)
} }
results = append(results, res) results = append(results, res)


+ 6
- 8
store/store.go View File

@ -5,8 +5,6 @@ import (
"strconv" "strconv"
"sync" "sync"
"github.com/pkg/errors"
db "github.com/tendermint/tm-db" db "github.com/tendermint/tm-db"
dbm "github.com/tendermint/tm-db" dbm "github.com/tendermint/tm-db"
@ -91,7 +89,7 @@ func (bs *BlockStore) LoadBlock(height int64) *types.Block {
if err != nil { if err != nil {
// NOTE: The existence of meta should imply the existence of the // NOTE: The existence of meta should imply the existence of the
// block. So, make sure meta is only saved after blocks are saved. // block. So, make sure meta is only saved after blocks are saved.
panic(errors.Wrap(err, "Error reading block"))
panic(fmt.Sprintf("Error reading block: %v", err))
} }
return block return block
} }
@ -112,7 +110,7 @@ func (bs *BlockStore) LoadBlockByHash(hash []byte) *types.Block {
height, err := strconv.ParseInt(s, 10, 64) height, err := strconv.ParseInt(s, 10, 64)
if err != nil { if err != nil {
panic(errors.Wrapf(err, "failed to extract height from %s", s))
panic(fmt.Sprintf("failed to extract height from %s: %v", s, err))
} }
return bs.LoadBlock(height) return bs.LoadBlock(height)
} }
@ -131,7 +129,7 @@ func (bs *BlockStore) LoadBlockPart(height int64, index int) *types.Part {
} }
err = cdc.UnmarshalBinaryBare(bz, part) err = cdc.UnmarshalBinaryBare(bz, part)
if err != nil { if err != nil {
panic(errors.Wrap(err, "Error reading block part"))
panic(fmt.Sprintf("Error reading block part: %v", err))
} }
return part return part
} }
@ -149,7 +147,7 @@ func (bs *BlockStore) LoadBlockMeta(height int64) *types.BlockMeta {
} }
err = cdc.UnmarshalBinaryBare(bz, blockMeta) err = cdc.UnmarshalBinaryBare(bz, blockMeta)
if err != nil { if err != nil {
panic(errors.Wrap(err, "Error reading block meta"))
panic(fmt.Sprintf("Error reading block meta: %v", err))
} }
return blockMeta return blockMeta
} }
@ -169,7 +167,7 @@ func (bs *BlockStore) LoadBlockCommit(height int64) *types.Commit {
} }
err = cdc.UnmarshalBinaryBare(bz, commit) err = cdc.UnmarshalBinaryBare(bz, commit)
if err != nil { if err != nil {
panic(errors.Wrap(err, "Error reading block commit"))
panic(fmt.Sprintf("Error reading block commit: %v", err))
} }
return commit return commit
} }
@ -188,7 +186,7 @@ func (bs *BlockStore) LoadSeenCommit(height int64) *types.Commit {
} }
err = cdc.UnmarshalBinaryBare(bz, commit) err = cdc.UnmarshalBinaryBare(bz, commit)
if err != nil { if err != nil {
panic(errors.Wrap(err, "Error reading block seen commit"))
panic(fmt.Sprintf("Error reading block seen commit: %v", err))
} }
return commit return commit
} }


+ 1
- 2
store/store_test.go View File

@ -9,7 +9,6 @@ import (
"testing" "testing"
"time" "time"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
db "github.com/tendermint/tm-db" db "github.com/tendermint/tm-db"
@ -58,7 +57,7 @@ func makeStateAndBlockStore(logger log.Logger) (sm.State, *BlockStore, cleanupFu
stateDB := dbm.NewMemDB() stateDB := dbm.NewMemDB()
state, err := sm.LoadStateFromDBOrGenesisFile(stateDB, config.GenesisFile()) state, err := sm.LoadStateFromDBOrGenesisFile(stateDB, config.GenesisFile())
if err != nil { if err != nil {
panic(errors.Wrap(err, "error constructing state from genesis file"))
panic(fmt.Errorf("error constructing state from genesis file: %w", err))
} }
return state, NewBlockStore(blockDB), func() { os.RemoveAll(config.RootDir) } return state, NewBlockStore(blockDB), func() { os.RemoveAll(config.RootDir) }
} }


+ 1
- 2
types/block.go View File

@ -2,13 +2,12 @@ package types
import ( import (
"bytes" "bytes"
"errors"
"fmt" "fmt"
"strings" "strings"
"sync" "sync"
"time" "time"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/crypto/merkle" "github.com/tendermint/tendermint/crypto/merkle"
"github.com/tendermint/tendermint/crypto/tmhash" "github.com/tendermint/tendermint/crypto/tmhash"


+ 2
- 3
types/block_meta.go View File

@ -2,8 +2,7 @@ package types
import ( import (
"bytes" "bytes"
"github.com/pkg/errors"
"fmt"
) )
// BlockMeta contains meta information. // BlockMeta contains meta information.
@ -58,7 +57,7 @@ func (bm *BlockMeta) ValidateBasic() error {
return err return err
} }
if !bytes.Equal(bm.BlockID.Hash, bm.Header.Hash()) { if !bytes.Equal(bm.BlockID.Hash, bm.Header.Hash()) {
return errors.Errorf("expected BlockID#Hash and Header#Hash to be the same, got %X != %X",
return fmt.Errorf("expected BlockID#Hash and Header#Hash to be the same, got %X != %X",
bm.BlockID.Hash, bm.Header.Hash()) bm.BlockID.Hash, bm.Header.Hash())
} }
return nil return nil


+ 3
- 4
types/evidence.go View File

@ -2,12 +2,11 @@ package types
import ( import (
"bytes" "bytes"
"errors"
"fmt" "fmt"
"strings" "strings"
"time" "time"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/crypto/tmhash" "github.com/tendermint/tendermint/crypto/tmhash"
tmmath "github.com/tendermint/tendermint/libs/math" tmmath "github.com/tendermint/tendermint/libs/math"
@ -485,7 +484,7 @@ func (ev ConflictingHeadersEvidence) VerifyComposite(committedHeader *Header, va
// Max validator set size = 100 * 2 = 200 [fork?] // Max validator set size = 100 * 2 = 200 [fork?]
maxNumValidators := valSet.Size() * 2 maxNumValidators := valSet.Size() * 2
if len(alternativeHeader.Commit.Signatures) > maxNumValidators { if len(alternativeHeader.Commit.Signatures) > maxNumValidators {
return errors.Errorf("alt commit contains too many signatures: %d, expected no more than %d",
return fmt.Errorf("alt commit contains too many signatures: %d, expected no more than %d",
len(alternativeHeader.Commit.Signatures), len(alternativeHeader.Commit.Signatures),
maxNumValidators) maxNumValidators)
} }
@ -496,7 +495,7 @@ func (ev ConflictingHeadersEvidence) VerifyComposite(committedHeader *Header, va
alternativeHeader.ChainID, alternativeHeader.ChainID,
alternativeHeader.Commit, alternativeHeader.Commit,
tmmath.Fraction{Numerator: 1, Denominator: 3}); err != nil { tmmath.Fraction{Numerator: 1, Denominator: 3}); err != nil {
return errors.Wrap(err, "alt header does not have 1/3+ of voting power of our validator set")
return fmt.Errorf("alt header does not have 1/3+ of voting power of our validator set: %w", err)
} }
return nil return nil


+ 6
- 7
types/genesis.go View File

@ -3,12 +3,11 @@ package types
import ( import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"time" "time"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto"
tmbytes "github.com/tendermint/tendermint/libs/bytes" tmbytes "github.com/tendermint/tendermint/libs/bytes"
tmos "github.com/tendermint/tendermint/libs/os" tmos "github.com/tendermint/tendermint/libs/os"
@ -70,7 +69,7 @@ func (genDoc *GenesisDoc) ValidateAndComplete() error {
return errors.New("genesis doc must include non-empty chain_id") return errors.New("genesis doc must include non-empty chain_id")
} }
if len(genDoc.ChainID) > MaxChainIDLen { if len(genDoc.ChainID) > MaxChainIDLen {
return errors.Errorf("chain_id in genesis doc is too long (max: %d)", MaxChainIDLen)
return fmt.Errorf("chain_id in genesis doc is too long (max: %d)", MaxChainIDLen)
} }
if genDoc.ConsensusParams == nil { if genDoc.ConsensusParams == nil {
@ -81,10 +80,10 @@ func (genDoc *GenesisDoc) ValidateAndComplete() error {
for i, v := range genDoc.Validators { for i, v := range genDoc.Validators {
if v.Power == 0 { if v.Power == 0 {
return errors.Errorf("the genesis file cannot contain validators with no voting power: %v", v)
return fmt.Errorf("the genesis file cannot contain validators with no voting power: %v", v)
} }
if len(v.Address) > 0 && !bytes.Equal(v.PubKey.Address(), v.Address) { if len(v.Address) > 0 && !bytes.Equal(v.PubKey.Address(), v.Address) {
return errors.Errorf("incorrect address for validator %v in the genesis file, should be %v", v, v.PubKey.Address())
return fmt.Errorf("incorrect address for validator %v in the genesis file, should be %v", v, v.PubKey.Address())
} }
if len(v.Address) == 0 { if len(v.Address) == 0 {
genDoc.Validators[i].Address = v.PubKey.Address() genDoc.Validators[i].Address = v.PubKey.Address()
@ -120,11 +119,11 @@ func GenesisDocFromJSON(jsonBlob []byte) (*GenesisDoc, error) {
func GenesisDocFromFile(genDocFile string) (*GenesisDoc, error) { func GenesisDocFromFile(genDocFile string) (*GenesisDoc, error) {
jsonBlob, err := ioutil.ReadFile(genDocFile) jsonBlob, err := ioutil.ReadFile(genDocFile)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "Couldn't read GenesisDoc file")
return nil, fmt.Errorf("couldn't read GenesisDoc file: %w", err)
} }
genDoc, err := GenesisDocFromJSON(jsonBlob) genDoc, err := GenesisDocFromJSON(jsonBlob)
if err != nil { if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("Error reading GenesisDoc at %v", genDocFile))
return nil, fmt.Errorf("error reading GenesisDoc at %s: %w", genDocFile, err)
} }
return genDoc, nil return genDoc, nil
} }

+ 11
- 11
types/params.go View File

@ -1,10 +1,10 @@
package types package types
import ( import (
"errors"
"fmt"
"time" "time"
"github.com/pkg/errors"
abci "github.com/tendermint/tendermint/abci/types" abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/crypto/tmhash" "github.com/tendermint/tendermint/crypto/tmhash"
tmstrings "github.com/tendermint/tendermint/libs/strings" tmstrings "github.com/tendermint/tendermint/libs/strings"
@ -130,41 +130,41 @@ func (params *ValidatorParams) IsValidPubkeyType(pubkeyType string) bool {
// allowed limits, and returns an error if they are not. // allowed limits, and returns an error if they are not.
func (params *ConsensusParams) Validate() error { func (params *ConsensusParams) Validate() error {
if params.Block.MaxBytes <= 0 { if params.Block.MaxBytes <= 0 {
return errors.Errorf("block.MaxBytes must be greater than 0. Got %d",
return fmt.Errorf("block.MaxBytes must be greater than 0. Got %d",
params.Block.MaxBytes) params.Block.MaxBytes)
} }
if params.Block.MaxBytes > MaxBlockSizeBytes { if params.Block.MaxBytes > MaxBlockSizeBytes {
return errors.Errorf("block.MaxBytes is too big. %d > %d",
return fmt.Errorf("block.MaxBytes is too big. %d > %d",
params.Block.MaxBytes, MaxBlockSizeBytes) params.Block.MaxBytes, MaxBlockSizeBytes)
} }
if params.Block.MaxGas < -1 { if params.Block.MaxGas < -1 {
return errors.Errorf("block.MaxGas must be greater or equal to -1. Got %d",
return fmt.Errorf("block.MaxGas must be greater or equal to -1. Got %d",
params.Block.MaxGas) params.Block.MaxGas)
} }
if params.Block.TimeIotaMs <= 0 { if params.Block.TimeIotaMs <= 0 {
return errors.Errorf("block.TimeIotaMs must be greater than 0. Got %v",
return fmt.Errorf("block.TimeIotaMs must be greater than 0. Got %v",
params.Block.TimeIotaMs) params.Block.TimeIotaMs)
} }
if params.Evidence.MaxAgeNumBlocks <= 0 { if params.Evidence.MaxAgeNumBlocks <= 0 {
return errors.Errorf("evidenceParams.MaxAgeNumBlocks must be greater than 0. Got %d",
return fmt.Errorf("evidenceParams.MaxAgeNumBlocks must be greater than 0. Got %d",
params.Evidence.MaxAgeNumBlocks) params.Evidence.MaxAgeNumBlocks)
} }
if params.Evidence.MaxAgeDuration <= 0 { if params.Evidence.MaxAgeDuration <= 0 {
return errors.Errorf("evidenceParams.MaxAgeDuration must be grater than 0 if provided, Got %v",
return fmt.Errorf("evidenceParams.MaxAgeDuration must be grater than 0 if provided, Got %v",
params.Evidence.MaxAgeDuration) params.Evidence.MaxAgeDuration)
} }
if params.Evidence.MaxNum > MaxEvidencePerBlock { if params.Evidence.MaxNum > MaxEvidencePerBlock {
return errors.Errorf("evidenceParams.MaxNumEvidence is greater than upper bound, %d > %d",
return fmt.Errorf("evidenceParams.MaxNumEvidence is greater than upper bound, %d > %d",
params.Evidence.MaxNum, MaxEvidencePerBlock) params.Evidence.MaxNum, MaxEvidencePerBlock)
} }
if int64(params.Evidence.MaxNum)*MaxEvidenceBytes > params.Block.MaxBytes { if int64(params.Evidence.MaxNum)*MaxEvidenceBytes > params.Block.MaxBytes {
return errors.Errorf("total possible evidence size is bigger than block.MaxBytes, %d > %d",
return fmt.Errorf("total possible evidence size is bigger than block.MaxBytes, %d > %d",
int64(params.Evidence.MaxNum)*MaxEvidenceBytes, params.Block.MaxBytes) int64(params.Evidence.MaxNum)*MaxEvidenceBytes, params.Block.MaxBytes)
} }
@ -176,7 +176,7 @@ func (params *ConsensusParams) Validate() error {
for i := 0; i < len(params.Validator.PubKeyTypes); i++ { for i := 0; i < len(params.Validator.PubKeyTypes); i++ {
keyType := params.Validator.PubKeyTypes[i] keyType := params.Validator.PubKeyTypes[i]
if _, ok := ABCIPubKeyTypesToAminoNames[keyType]; !ok { if _, ok := ABCIPubKeyTypesToAminoNames[keyType]; !ok {
return errors.Errorf("params.Validator.PubKeyTypes[%d], %s, is an unknown pubkey type",
return fmt.Errorf("params.Validator.PubKeyTypes[%d], %s, is an unknown pubkey type",
i, keyType) i, keyType)
} }
} }


+ 4
- 5
types/part_set.go View File

@ -2,12 +2,11 @@ package types
import ( import (
"bytes" "bytes"
"errors"
"fmt" "fmt"
"io" "io"
"sync" "sync"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/crypto/merkle" "github.com/tendermint/tendermint/crypto/merkle"
"github.com/tendermint/tendermint/libs/bits" "github.com/tendermint/tendermint/libs/bits"
tmbytes "github.com/tendermint/tendermint/libs/bytes" tmbytes "github.com/tendermint/tendermint/libs/bytes"
@ -31,10 +30,10 @@ func (part *Part) ValidateBasic() error {
return errors.New("negative Index") return errors.New("negative Index")
} }
if len(part.Bytes) > BlockPartSizeBytes { if len(part.Bytes) > BlockPartSizeBytes {
return errors.Errorf("too big: %d bytes, max: %d", len(part.Bytes), BlockPartSizeBytes)
return fmt.Errorf("too big: %d bytes, max: %d", len(part.Bytes), BlockPartSizeBytes)
} }
if err := part.Proof.ValidateBasic(); err != nil { if err := part.Proof.ValidateBasic(); err != nil {
return errors.Wrap(err, "wrong Proof")
return fmt.Errorf("wrong Proof: %w", err)
} }
return nil return nil
} }
@ -80,7 +79,7 @@ func (psh PartSetHeader) ValidateBasic() error {
} }
// Hash can be empty in case of POLBlockID.PartsHeader in Proposal. // Hash can be empty in case of POLBlockID.PartsHeader in Proposal.
if err := ValidateHash(psh.Hash); err != nil { if err := ValidateHash(psh.Hash); err != nil {
return errors.Wrap(err, "Wrong Hash")
return fmt.Errorf("wrong Hash: %w", err)
} }
return nil return nil
} }


+ 3
- 4
types/test_util.go View File

@ -1,9 +1,8 @@
package types package types
import ( import (
"fmt"
"time" "time"
"github.com/pkg/errors"
) )
func MakeCommit(blockID BlockID, height int64, round int, func MakeCommit(blockID BlockID, height int64, round int,
@ -13,7 +12,7 @@ func MakeCommit(blockID BlockID, height int64, round int,
for i := 0; i < len(validators); i++ { for i := 0; i < len(validators); i++ {
pubKey, err := validators[i].GetPubKey() pubKey, err := validators[i].GetPubKey()
if err != nil { if err != nil {
return nil, errors.Wrap(err, "can't get pubkey")
return nil, fmt.Errorf("can't get pubkey: %w", err)
} }
vote := &Vote{ vote := &Vote{
ValidatorAddress: pubKey.Address(), ValidatorAddress: pubKey.Address(),
@ -52,7 +51,7 @@ func MakeVote(
) (*Vote, error) { ) (*Vote, error) {
pubKey, err := privVal.GetPubKey() pubKey, err := privVal.GetPubKey()
if err != nil { if err != nil {
return nil, errors.Wrap(err, "can't get pubkey")
return nil, fmt.Errorf("can't get pubkey: %w", err)
} }
addr := pubKey.Address() addr := pubKey.Address()
idx, _ := valSet.GetByAddress(addr) idx, _ := valSet.GetByAddress(addr)


+ 5
- 7
types/validator_set.go View File

@ -2,14 +2,13 @@ package types
import ( import (
"bytes" "bytes"
"errors"
"fmt" "fmt"
"math" "math"
"math/big" "math/big"
"sort" "sort"
"strings" "strings"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/crypto/merkle" "github.com/tendermint/tendermint/crypto/merkle"
tmmath "github.com/tendermint/tendermint/libs/math" tmmath "github.com/tendermint/tendermint/libs/math"
) )
@ -751,7 +750,7 @@ func (vals *ValidatorSet) VerifyFutureCommit(newSet *ValidatorSet, chainID strin
// Validate signature. // Validate signature.
voteSignBytes := commit.VoteSignBytes(chainID, idx) voteSignBytes := commit.VoteSignBytes(chainID, idx)
if !val.PubKey.VerifyBytes(voteSignBytes, commitSig.Signature) { if !val.PubKey.VerifyBytes(voteSignBytes, commitSig.Signature) {
return errors.Errorf("wrong signature (#%d): %X", idx, commitSig.Signature)
return fmt.Errorf("wrong signature (#%d): %X", idx, commitSig.Signature)
} }
// Good! // Good!
if blockID.Equals(commitSig.BlockID(commit.BlockID)) { if blockID.Equals(commitSig.BlockID(commit.BlockID)) {
@ -805,14 +804,14 @@ func (vals *ValidatorSet) VerifyCommitTrusting(chainID string, commit *Commit, t
// check for double vote of validator on the same commit // check for double vote of validator on the same commit
if firstIndex, ok := seenVals[valIdx]; ok { if firstIndex, ok := seenVals[valIdx]; ok {
secondIndex := idx secondIndex := idx
return errors.Errorf("double vote from %v (%d and %d)", val, firstIndex, secondIndex)
return fmt.Errorf("double vote from %v (%d and %d)", val, firstIndex, secondIndex)
} }
seenVals[valIdx] = idx seenVals[valIdx] = idx
// Validate signature. // Validate signature.
voteSignBytes := commit.VoteSignBytes(chainID, idx) voteSignBytes := commit.VoteSignBytes(chainID, idx)
if !val.PubKey.VerifyBytes(voteSignBytes, commitSig.Signature) { if !val.PubKey.VerifyBytes(voteSignBytes, commitSig.Signature) {
return errors.Errorf("wrong signature (#%d): %X", idx, commitSig.Signature)
return fmt.Errorf("wrong signature (#%d): %X", idx, commitSig.Signature)
} }
// Good! // Good!
@ -838,8 +837,7 @@ func (vals *ValidatorSet) VerifyCommitTrusting(chainID string, commit *Commit, t
// IsErrNotEnoughVotingPowerSigned returns true if err is // IsErrNotEnoughVotingPowerSigned returns true if err is
// ErrNotEnoughVotingPowerSigned. // ErrNotEnoughVotingPowerSigned.
func IsErrNotEnoughVotingPowerSigned(err error) bool { func IsErrNotEnoughVotingPowerSigned(err error) bool {
_, ok := errors.Cause(err).(ErrNotEnoughVotingPowerSigned)
return ok
return errors.As(err, &ErrNotEnoughVotingPowerSigned{})
} }
// ErrNotEnoughVotingPowerSigned is returned when not enough validators signed // ErrNotEnoughVotingPowerSigned is returned when not enough validators signed


+ 12
- 13
types/vote_set.go View File

@ -6,8 +6,6 @@ import (
"strings" "strings"
"sync" "sync"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/libs/bits" "github.com/tendermint/tendermint/libs/bits"
) )
@ -160,33 +158,34 @@ func (voteSet *VoteSet) addVote(vote *Vote) (added bool, err error) {
// Ensure that validator index was set // Ensure that validator index was set
if valIndex < 0 { if valIndex < 0 {
return false, errors.Wrap(ErrVoteInvalidValidatorIndex, "Index < 0")
return false, fmt.Errorf("index < 0: %w", ErrVoteInvalidValidatorIndex)
} else if len(valAddr) == 0 { } else if len(valAddr) == 0 {
return false, errors.Wrap(ErrVoteInvalidValidatorAddress, "Empty address")
return false, fmt.Errorf("empty address: %w", ErrVoteInvalidValidatorAddress)
} }
// Make sure the step matches. // Make sure the step matches.
if (vote.Height != voteSet.height) || if (vote.Height != voteSet.height) ||
(vote.Round != voteSet.round) || (vote.Round != voteSet.round) ||
(vote.Type != voteSet.signedMsgType) { (vote.Type != voteSet.signedMsgType) {
return false, errors.Wrapf(ErrVoteUnexpectedStep, "Expected %d/%d/%d, but got %d/%d/%d",
return false, fmt.Errorf("expected %d/%d/%d, but got %d/%d/%d: %w",
voteSet.height, voteSet.round, voteSet.signedMsgType, voteSet.height, voteSet.round, voteSet.signedMsgType,
vote.Height, vote.Round, vote.Type)
vote.Height, vote.Round, vote.Type, ErrVoteUnexpectedStep)
} }
// Ensure that signer is a validator. // Ensure that signer is a validator.
lookupAddr, val := voteSet.valSet.GetByIndex(valIndex) lookupAddr, val := voteSet.valSet.GetByIndex(valIndex)
if val == nil { if val == nil {
return false, errors.Wrapf(ErrVoteInvalidValidatorIndex,
"Cannot find validator %d in valSet of size %d", valIndex, voteSet.valSet.Size())
return false, fmt.Errorf(
"cannot find validator %d in valSet of size %d: %w",
valIndex, voteSet.valSet.Size(), ErrVoteInvalidValidatorIndex)
} }
// Ensure that the signer has the right address. // Ensure that the signer has the right address.
if !bytes.Equal(valAddr, lookupAddr) { if !bytes.Equal(valAddr, lookupAddr) {
return false, errors.Wrapf(ErrVoteInvalidValidatorAddress,
return false, fmt.Errorf(
"vote.ValidatorAddress (%X) does not match address (%X) for vote.ValidatorIndex (%d)\n"+ "vote.ValidatorAddress (%X) does not match address (%X) for vote.ValidatorIndex (%d)\n"+
"Ensure the genesis file is correct across all validators.",
valAddr, lookupAddr, valIndex)
"Ensure the genesis file is correct across all validators: %w",
valAddr, lookupAddr, valIndex, ErrVoteInvalidValidatorAddress)
} }
// If we already know of this vote, return false. // If we already know of this vote, return false.
@ -194,12 +193,12 @@ func (voteSet *VoteSet) addVote(vote *Vote) (added bool, err error) {
if bytes.Equal(existing.Signature, vote.Signature) { if bytes.Equal(existing.Signature, vote.Signature) {
return false, nil // duplicate return false, nil // duplicate
} }
return false, errors.Wrapf(ErrVoteNonDeterministicSignature, "Existing vote: %v; New vote: %v", existing, vote)
return false, fmt.Errorf("existing vote: %v; new vote: %v: %w", existing, vote, ErrVoteNonDeterministicSignature)
} }
// Check signature. // Check signature.
if err := vote.Verify(voteSet.chainID, val.PubKey); err != nil { if err := vote.Verify(voteSet.chainID, val.PubKey); err != nil {
return false, errors.Wrapf(err, "Failed to verify vote with ChainID %s and PubKey %s", voteSet.chainID, val.PubKey)
return false, fmt.Errorf("failed to verify vote with ChainID %s and PubKey %s: %w", voteSet.chainID, val.PubKey, err)
} }
// Add vote and get conflicting vote if any. // Add vote and get conflicting vote if any.


Loading…
Cancel
Save