Browse Source

Merge pull request #145 from tendermint/types-makeover

Types makeover
pull/1780/head
Ethan Buchman 7 years ago
committed by GitHub
parent
commit
d9d5e35ca5
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
30 changed files with 483 additions and 662 deletions
  1. +1
    -0
      .gitignore
  2. +8
    -2
      CHANGELOG.md
  3. +5
    -4
      Makefile
  4. +3
    -1
      client/grpc_client.go
  5. +1
    -1
      client/socket_client.go
  6. +46
    -33
      cmd/abci-cli/abci-cli.go
  7. +9
    -0
      example/code/code.go
  8. +9
    -8
      example/counter/counter.go
  9. +4
    -3
      example/dummy/dummy.go
  10. +14
    -11
      example/dummy/dummy_test.go
  11. +9
    -8
      example/dummy/persistent_dummy.go
  12. +9
    -7
      example/example_test.go
  13. +27
    -23
      glide.lock
  14. +4
    -1
      glide.yaml
  15. +1
    -0
      server/grpc_server.go
  16. +2
    -2
      tests/client_server_test.go
  17. +3
    -3
      tests/test_app/app.go
  18. +9
    -8
      tests/test_app/main.go
  19. +5
    -0
      tests/test_app/test.sh
  20. +2
    -2
      tests/test_cli/ex2.abci.out
  21. +1
    -1
      tests/test_cli/test.sh
  22. +4
    -4
      types/base_app.go
  23. +0
    -37
      types/code.go
  24. +0
    -12
      types/code_test.go
  25. +1
    -1
      types/messages.go
  26. +55
    -0
      types/protoreplace/protoreplace.go
  27. +14
    -42
      types/result.go
  28. +15
    -17
      types/result_test.go
  29. +210
    -379
      types/types.pb.go
  30. +12
    -52
      types/types.proto

+ 1
- 0
.gitignore View File

@ -1,2 +1,3 @@
vendor vendor
.glide .glide
types/types.pb.go

+ 8
- 2
CHANGELOG.md View File

@ -4,15 +4,21 @@
BREAKING CHANGES: BREAKING CHANGES:
- [client] all XxxSync methods now return (ResponseXxx, error) - [client] all XxxSync methods now return (ResponseXxx, error)
- [types] Application: all methods now take RequestXxx and return (ResponseXxx, error).
- [types] all methods on Application interface now take RequestXxx and return (ResponseXxx, error).
- Except `CheckTx`/`DeliverTx`, which takes a `tx []byte` argument. - Except `CheckTx`/`DeliverTx`, which takes a `tx []byte` argument.
- Except `Commit`, which takes no arguments. - Except `Commit`, which takes no arguments.
- [types] removed Result
- [types] removed Result and ResultQuery
- [types] removed CodeType - only `0 == OK` is defined here, everything else is left to convention at the application level
- [types] switched to using `gogo/protobuf` for code generation
- [types] use `customtype` feature of `gogo/protobuf` to replace `[]byte` with `data.Bytes` in all generated types :)
- this eliminates the need for additional types like ResultQuery
- [abci-cli] codes are printed as their number instead of a message, except for `code == 0`, which is still printed as `OK`
FEATURES: FEATURES:
- [types] added Tags field to ResponseDeliverTx - [types] added Tags field to ResponseDeliverTx
- [types] added Gas and Fee fields to ResponseCheckTx - [types] added Gas and Fee fields to ResponseCheckTx
- [dummy] DeliverTx returns tags - [dummy] DeliverTx returns tags
- [abci-cli] added `log_level` flag to control the logger
## 0.7.1 (November 14, 2017) ## 0.7.1 (November 14, 2017)


+ 5
- 4
Makefile View File

@ -2,7 +2,9 @@ GOTOOLS = \
github.com/mitchellh/gox \ github.com/mitchellh/gox \
github.com/Masterminds/glide \ github.com/Masterminds/glide \
github.com/alecthomas/gometalinter \ github.com/alecthomas/gometalinter \
github.com/ckaznocha/protoc-gen-lint
github.com/ckaznocha/protoc-gen-lint \
github.com/gogo/protobuf/protoc-gen-gogo \
github.com/gogo/protobuf/gogoproto
all: install test all: install test
@ -17,13 +19,12 @@ install_protoc:
make install && \ make install && \
cd .. && \ cd .. && \
rm -rf protobuf-3.4.1 rm -rf protobuf-3.4.1
go get github.com/golang/protobuf/protoc-gen-go
protoc: protoc:
## On "error while loading shared libraries: libprotobuf.so.14: cannot open shared object file: No such file or directory" ## On "error while loading shared libraries: libprotobuf.so.14: cannot open shared object file: No such file or directory"
## ldconfig (may require sudo) ## ldconfig (may require sudo)
## https://stackoverflow.com/a/25518702 ## https://stackoverflow.com/a/25518702
protoc --go_out=plugins=grpc:. types/*.proto
protoc -I=. -I=${GOPATH}/src -I=${GOPATH}/src/github.com/gogo/protobuf/protobuf --gogo_out=plugins=grpc:. types/*.proto
install: install:
@ go install ./cmd/... @ go install ./cmd/...
@ -74,7 +75,6 @@ metalinter_test:
gometalinter --vendor --deadline=600s --disable-all \ gometalinter --vendor --deadline=600s --disable-all \
--enable=maligned \ --enable=maligned \
--enable=deadcode \ --enable=deadcode \
--enable=gas \
--enable=goconst \ --enable=goconst \
--enable=goimports \ --enable=goimports \
--enable=gosimple \ --enable=gosimple \
@ -90,6 +90,7 @@ metalinter_test:
--enable=vetshadow \ --enable=vetshadow \
./... ./...
#--enable=gas \
#--enable=dupl \ #--enable=dupl \
#--enable=errcheck \ #--enable=errcheck \
#--enable=gocyclo \ #--enable=gocyclo \


+ 3
- 1
client/grpc_client.go View File

@ -60,6 +60,7 @@ RETRY_LOOP:
continue RETRY_LOOP continue RETRY_LOOP
} }
cli.Logger.Info("Dialed server. Waiting for echo.", "addr", cli.addr)
client := types.NewABCIApplicationClient(conn) client := types.NewABCIApplicationClient(conn)
ENSURE_CONNECTED: ENSURE_CONNECTED:
@ -68,6 +69,7 @@ RETRY_LOOP:
if err == nil { if err == nil {
break ENSURE_CONNECTED break ENSURE_CONNECTED
} }
cli.Logger.Error("Echo failed", "err", err)
time.Sleep(time.Second * echoRetryIntervalSeconds) time.Sleep(time.Second * echoRetryIntervalSeconds)
} }
@ -104,7 +106,7 @@ func (cli *grpcClient) StopForError(err error) {
func (cli *grpcClient) Error() error { func (cli *grpcClient) Error() error {
cli.mtx.Lock() cli.mtx.Lock()
defer cli.mtx.Unlock() defer cli.mtx.Unlock()
return errors.Wrap(cli.err, types.HumanCode(types.CodeType_InternalError))
return errors.Wrap(cli.err, "grpc client error")
} }
// Set listener for all responses // Set listener for all responses


+ 1
- 1
client/socket_client.go View File

@ -111,7 +111,7 @@ func (cli *socketClient) StopForError(err error) {
func (cli *socketClient) Error() error { func (cli *socketClient) Error() error {
cli.mtx.Lock() cli.mtx.Lock()
defer cli.mtx.Unlock() defer cli.mtx.Unlock()
return errors.Wrap(cli.err, types.HumanCode(types.CodeType_InternalError))
return errors.Wrap(cli.err, "socket client error")
} }
// Set listener for all responses // Set listener for all responses


+ 46
- 33
cmd/abci-cli/abci-cli.go View File

@ -10,46 +10,32 @@ import (
"os/exec" "os/exec"
"strings" "strings"
"github.com/spf13/cobra"
cmn "github.com/tendermint/tmlibs/common"
"github.com/tendermint/tmlibs/log"
abcicli "github.com/tendermint/abci/client" abcicli "github.com/tendermint/abci/client"
"github.com/tendermint/abci/example/counter" "github.com/tendermint/abci/example/counter"
"github.com/tendermint/abci/example/dummy" "github.com/tendermint/abci/example/dummy"
"github.com/tendermint/abci/server" "github.com/tendermint/abci/server"
"github.com/tendermint/abci/types" "github.com/tendermint/abci/types"
"github.com/tendermint/abci/version" "github.com/tendermint/abci/version"
cmn "github.com/tendermint/tmlibs/common"
"github.com/tendermint/tmlibs/log"
"github.com/spf13/cobra"
) )
// Structure for data passed to print response.
type response struct {
// generic abci response
Data []byte
Code types.CodeType
Log string
Query *queryResponse
}
type queryResponse struct {
Key []byte
Value []byte
Height uint64
Proof []byte
}
// client is a global variable so it can be reused by the console // client is a global variable so it can be reused by the console
var client abcicli.Client
var logger log.Logger
var (
client abcicli.Client
logger log.Logger
)
// flags // flags
var ( var (
// global // global
address string
abci string
verbose bool
address string
abci string
verbose bool // for the println output
logLevel string // for the logger
// query // query
path string path string
@ -79,7 +65,11 @@ var RootCmd = &cobra.Command{
} }
if logger == nil { if logger == nil {
logger = log.NewFilter(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), log.AllowError())
allowLevel, err := log.AllowLevel(logLevel)
if err != nil {
return err
}
logger = log.NewFilter(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), allowLevel)
} }
if client == nil { if client == nil {
var err error var err error
@ -88,7 +78,7 @@ var RootCmd = &cobra.Command{
return err return err
} }
client.SetLogger(logger.With("module", "abci-client")) client.SetLogger(logger.With("module", "abci-client"))
if _, err := client.Start(); err != nil {
if err := client.Start(); err != nil {
return err return err
} }
} }
@ -96,6 +86,23 @@ var RootCmd = &cobra.Command{
}, },
} }
// Structure for data passed to print response.
type response struct {
// generic abci response
Data []byte
Code uint32
Log string
Query *queryResponse
}
type queryResponse struct {
Key []byte
Value []byte
Height uint64
Proof []byte
}
func Execute() error { func Execute() error {
addGlobalFlags() addGlobalFlags()
addCommands() addCommands()
@ -103,9 +110,10 @@ func Execute() error {
} }
func addGlobalFlags() { func addGlobalFlags() {
RootCmd.PersistentFlags().StringVarP(&address, "address", "", "tcp://127.0.0.1:46658", "Address of application socket")
RootCmd.PersistentFlags().StringVarP(&address, "address", "", "tcp://0.0.0.0:46658", "Address of application socket")
RootCmd.PersistentFlags().StringVarP(&abci, "abci", "", "socket", "Either socket or grpc") RootCmd.PersistentFlags().StringVarP(&abci, "abci", "", "socket", "Either socket or grpc")
RootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "Print the command and results as if it were a console session") RootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "Print the command and results as if it were a console session")
RootCmd.PersistentFlags().StringVarP(&logLevel, "log_level", "", "debug", "Set the logger level")
} }
func addQueryFlags() { func addQueryFlags() {
@ -457,7 +465,7 @@ func cmdCounter(cmd *cobra.Command, args []string) error {
return err return err
} }
srv.SetLogger(logger.With("module", "abci-server")) srv.SetLogger(logger.With("module", "abci-server"))
if _, err := srv.Start(); err != nil {
if err := srv.Start(); err != nil {
return err return err
} }
@ -487,7 +495,7 @@ func cmdDummy(cmd *cobra.Command, args []string) error {
return err return err
} }
srv.SetLogger(logger.With("module", "abci-server")) srv.SetLogger(logger.With("module", "abci-server"))
if _, err := srv.Start(); err != nil {
if err := srv.Start(); err != nil {
return err return err
} }
@ -508,7 +516,12 @@ func printResponse(cmd *cobra.Command, args []string, rsp response) {
} }
// Always print the status code. // Always print the status code.
fmt.Printf("-> code: %s\n", rsp.Code.String())
if rsp.Code == types.CodeTypeOK {
fmt.Printf("-> code: OK\n")
} else {
fmt.Printf("-> code: %d\n", rsp.Code)
}
if len(rsp.Data) != 0 { if len(rsp.Data) != 0 {
// Do no print this line when using the commit command // Do no print this line when using the commit command


+ 9
- 0
example/code/code.go View File

@ -0,0 +1,9 @@
package code
// Return codes for the examples
const (
CodeTypeOK uint32 = 0
CodeTypeEncodingError uint32 = 1
CodeTypeBadNonce uint32 = 2
CodeTypeUnauthorized uint32 = 3
)

+ 9
- 8
example/counter/counter.go View File

@ -4,6 +4,7 @@ import (
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"github.com/tendermint/abci/example/code"
"github.com/tendermint/abci/types" "github.com/tendermint/abci/types"
cmn "github.com/tendermint/tmlibs/common" cmn "github.com/tendermint/tmlibs/common"
) )
@ -36,7 +37,7 @@ func (app *CounterApplication) DeliverTx(tx []byte) types.ResponseDeliverTx {
if app.serial { if app.serial {
if len(tx) > 8 { if len(tx) > 8 {
return types.ResponseDeliverTx{ return types.ResponseDeliverTx{
Code: types.CodeType_EncodingError,
Code: code.CodeTypeEncodingError,
Log: fmt.Sprintf("Max tx size is 8 bytes, got %d", len(tx))} Log: fmt.Sprintf("Max tx size is 8 bytes, got %d", len(tx))}
} }
tx8 := make([]byte, 8) tx8 := make([]byte, 8)
@ -44,19 +45,19 @@ func (app *CounterApplication) DeliverTx(tx []byte) types.ResponseDeliverTx {
txValue := binary.BigEndian.Uint64(tx8) txValue := binary.BigEndian.Uint64(tx8)
if txValue != uint64(app.txCount) { if txValue != uint64(app.txCount) {
return types.ResponseDeliverTx{ return types.ResponseDeliverTx{
Code: types.CodeType_BadNonce,
Code: code.CodeTypeBadNonce,
Log: fmt.Sprintf("Invalid nonce. Expected %v, got %v", app.txCount, txValue)} Log: fmt.Sprintf("Invalid nonce. Expected %v, got %v", app.txCount, txValue)}
} }
} }
app.txCount++ app.txCount++
return types.ResponseDeliverTx{Code: types.CodeType_OK}
return types.ResponseDeliverTx{Code: code.CodeTypeOK}
} }
func (app *CounterApplication) CheckTx(tx []byte) types.ResponseCheckTx { func (app *CounterApplication) CheckTx(tx []byte) types.ResponseCheckTx {
if app.serial { if app.serial {
if len(tx) > 8 { if len(tx) > 8 {
return types.ResponseCheckTx{ return types.ResponseCheckTx{
Code: types.CodeType_EncodingError,
Code: code.CodeTypeEncodingError,
Log: fmt.Sprintf("Max tx size is 8 bytes, got %d", len(tx))} Log: fmt.Sprintf("Max tx size is 8 bytes, got %d", len(tx))}
} }
tx8 := make([]byte, 8) tx8 := make([]byte, 8)
@ -64,21 +65,21 @@ func (app *CounterApplication) CheckTx(tx []byte) types.ResponseCheckTx {
txValue := binary.BigEndian.Uint64(tx8) txValue := binary.BigEndian.Uint64(tx8)
if txValue < uint64(app.txCount) { if txValue < uint64(app.txCount) {
return types.ResponseCheckTx{ return types.ResponseCheckTx{
Code: types.CodeType_BadNonce,
Code: code.CodeTypeBadNonce,
Log: fmt.Sprintf("Invalid nonce. Expected >= %v, got %v", app.txCount, txValue)} Log: fmt.Sprintf("Invalid nonce. Expected >= %v, got %v", app.txCount, txValue)}
} }
} }
return types.ResponseCheckTx{Code: types.CodeType_OK}
return types.ResponseCheckTx{Code: code.CodeTypeOK}
} }
func (app *CounterApplication) Commit() (resp types.ResponseCommit) { func (app *CounterApplication) Commit() (resp types.ResponseCommit) {
app.hashCount++ app.hashCount++
if app.txCount == 0 { if app.txCount == 0 {
return types.ResponseCommit{Code: types.CodeType_OK}
return types.ResponseCommit{Code: code.CodeTypeOK}
} }
hash := make([]byte, 8) hash := make([]byte, 8)
binary.BigEndian.PutUint64(hash, uint64(app.txCount)) binary.BigEndian.PutUint64(hash, uint64(app.txCount))
return types.ResponseCommit{Code: types.CodeType_OK, Data: hash}
return types.ResponseCommit{Code: code.CodeTypeOK, Data: hash}
} }
func (app *CounterApplication) Query(reqQuery types.RequestQuery) types.ResponseQuery { func (app *CounterApplication) Query(reqQuery types.RequestQuery) types.ResponseQuery {


+ 4
- 3
example/dummy/dummy.go View File

@ -4,6 +4,7 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"github.com/tendermint/abci/example/code"
"github.com/tendermint/abci/types" "github.com/tendermint/abci/types"
wire "github.com/tendermint/go-wire" wire "github.com/tendermint/go-wire"
"github.com/tendermint/iavl" "github.com/tendermint/iavl"
@ -42,11 +43,11 @@ func (app *DummyApplication) DeliverTx(tx []byte) types.ResponseDeliverTx {
{Key: "app.creator", ValueType: types.KVPair_STRING, ValueString: "jae"}, {Key: "app.creator", ValueType: types.KVPair_STRING, ValueString: "jae"},
{Key: "app.key", ValueType: types.KVPair_STRING, ValueString: string(key)}, {Key: "app.key", ValueType: types.KVPair_STRING, ValueString: string(key)},
} }
return types.ResponseDeliverTx{Code: types.CodeType_OK, Tags: tags}
return types.ResponseDeliverTx{Code: code.CodeTypeOK, Tags: tags}
} }
func (app *DummyApplication) CheckTx(tx []byte) types.ResponseCheckTx { func (app *DummyApplication) CheckTx(tx []byte) types.ResponseCheckTx {
return types.ResponseCheckTx{Code: types.CodeType_OK}
return types.ResponseCheckTx{Code: code.CodeTypeOK}
} }
func (app *DummyApplication) Commit() types.ResponseCommit { func (app *DummyApplication) Commit() types.ResponseCommit {
@ -64,7 +65,7 @@ func (app *DummyApplication) Commit() types.ResponseCommit {
} }
} }
return types.ResponseCommit{Code: types.CodeType_OK, Data: hash}
return types.ResponseCommit{Code: code.CodeTypeOK, Data: hash}
} }
func (app *DummyApplication) Query(reqQuery types.RequestQuery) (resQuery types.ResponseQuery) { func (app *DummyApplication) Query(reqQuery types.RequestQuery) (resQuery types.ResponseQuery) {


+ 14
- 11
example/dummy/dummy_test.go View File

@ -7,12 +7,15 @@ import (
"testing" "testing"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
abcicli "github.com/tendermint/abci/client"
abciserver "github.com/tendermint/abci/server"
"github.com/tendermint/abci/types"
"github.com/tendermint/iavl" "github.com/tendermint/iavl"
cmn "github.com/tendermint/tmlibs/common" cmn "github.com/tendermint/tmlibs/common"
"github.com/tendermint/tmlibs/log" "github.com/tendermint/tmlibs/log"
abcicli "github.com/tendermint/abci/client"
"github.com/tendermint/abci/example/code"
abciserver "github.com/tendermint/abci/server"
"github.com/tendermint/abci/types"
) )
func testDummy(t *testing.T, app types.Application, tx []byte, key, value string) { func testDummy(t *testing.T, app types.Application, tx []byte, key, value string) {
@ -27,7 +30,7 @@ func testDummy(t *testing.T, app types.Application, tx []byte, key, value string
Path: "/store", Path: "/store",
Data: []byte(key), Data: []byte(key),
}) })
require.Equal(t, types.CodeType_OK, resQuery.Code)
require.Equal(t, code.CodeTypeOK, resQuery.Code)
require.Equal(t, value, string(resQuery.Value)) require.Equal(t, value, string(resQuery.Value))
// make sure proof is fine // make sure proof is fine
@ -36,7 +39,7 @@ func testDummy(t *testing.T, app types.Application, tx []byte, key, value string
Data: []byte(key), Data: []byte(key),
Prove: true, Prove: true,
}) })
require.Equal(t, types.CodeType_OK, resQuery.Code)
require.EqualValues(t, code.CodeTypeOK, resQuery.Code)
require.Equal(t, value, string(resQuery.Value)) require.Equal(t, value, string(resQuery.Value))
proof, err := iavl.ReadKeyExistsProof(resQuery.Proof) proof, err := iavl.ReadKeyExistsProof(resQuery.Proof)
require.Nil(t, err) require.Nil(t, err)
@ -212,14 +215,14 @@ func makeSocketClientServer(app types.Application, name string) (abcicli.Client,
server := abciserver.NewSocketServer(socket, app) server := abciserver.NewSocketServer(socket, app)
server.SetLogger(logger.With("module", "abci-server")) server.SetLogger(logger.With("module", "abci-server"))
if _, err := server.Start(); err != nil {
if err := server.Start(); err != nil {
return nil, nil, err return nil, nil, err
} }
// Connect to the socket // Connect to the socket
client := abcicli.NewSocketClient(socket, false) client := abcicli.NewSocketClient(socket, false)
client.SetLogger(logger.With("module", "abci-client")) client.SetLogger(logger.With("module", "abci-client"))
if _, err := client.Start(); err != nil {
if err := client.Start(); err != nil {
server.Stop() server.Stop()
return nil, nil, err return nil, nil, err
} }
@ -235,13 +238,13 @@ func makeGRPCClientServer(app types.Application, name string) (abcicli.Client, c
gapp := types.NewGRPCApplication(app) gapp := types.NewGRPCApplication(app)
server := abciserver.NewGRPCServer(socket, gapp) server := abciserver.NewGRPCServer(socket, gapp)
server.SetLogger(logger.With("module", "abci-server")) server.SetLogger(logger.With("module", "abci-server"))
if _, err := server.Start(); err != nil {
if err := server.Start(); err != nil {
return nil, nil, err return nil, nil, err
} }
client := abcicli.NewGRPCClient(socket, true) client := abcicli.NewGRPCClient(socket, true)
client.SetLogger(logger.With("module", "abci-client")) client.SetLogger(logger.With("module", "abci-client"))
if _, err := client.Start(); err != nil {
if err := client.Start(); err != nil {
server.Stop() server.Stop()
return nil, nil, err return nil, nil, err
} }
@ -295,7 +298,7 @@ func testClient(t *testing.T, app abcicli.Client, tx []byte, key, value string)
Data: []byte(key), Data: []byte(key),
}) })
require.Nil(t, err) require.Nil(t, err)
require.Equal(t, types.CodeType_OK, resQuery.Code)
require.Equal(t, code.CodeTypeOK, resQuery.Code)
require.Equal(t, value, string(resQuery.Value)) require.Equal(t, value, string(resQuery.Value))
// make sure proof is fine // make sure proof is fine
@ -305,7 +308,7 @@ func testClient(t *testing.T, app abcicli.Client, tx []byte, key, value string)
Prove: true, Prove: true,
}) })
require.Nil(t, err) require.Nil(t, err)
require.Equal(t, types.CodeType_OK, resQuery.Code)
require.Equal(t, code.CodeTypeOK, resQuery.Code)
require.Equal(t, value, string(resQuery.Value)) require.Equal(t, value, string(resQuery.Value))
proof, err := iavl.ReadKeyExistsProof(resQuery.Proof) proof, err := iavl.ReadKeyExistsProof(resQuery.Proof)
require.Nil(t, err) require.Nil(t, err)


+ 9
- 8
example/dummy/persistent_dummy.go View File

@ -7,6 +7,7 @@ import (
"strconv" "strconv"
"strings" "strings"
"github.com/tendermint/abci/example/code"
"github.com/tendermint/abci/types" "github.com/tendermint/abci/types"
crypto "github.com/tendermint/go-crypto" crypto "github.com/tendermint/go-crypto"
"github.com/tendermint/iavl" "github.com/tendermint/iavl"
@ -96,7 +97,7 @@ func (app *PersistentDummyApplication) Commit() types.ResponseCommit {
} }
app.logger.Info("Commit block", "height", height, "root", appHash) app.logger.Info("Commit block", "height", height, "root", appHash)
return types.ResponseCommit{Code: types.CodeType_OK, Data: appHash}
return types.ResponseCommit{Code: code.CodeTypeOK, Data: appHash}
} }
func (app *PersistentDummyApplication) Query(reqQuery types.RequestQuery) types.ResponseQuery { func (app *PersistentDummyApplication) Query(reqQuery types.RequestQuery) types.ResponseQuery {
@ -160,7 +161,7 @@ func (app *PersistentDummyApplication) execValidatorTx(tx []byte) types.Response
pubKeyAndPower := strings.Split(string(tx), "/") pubKeyAndPower := strings.Split(string(tx), "/")
if len(pubKeyAndPower) != 2 { if len(pubKeyAndPower) != 2 {
return types.ResponseDeliverTx{ return types.ResponseDeliverTx{
Code: types.CodeType_EncodingError,
Code: code.CodeTypeEncodingError,
Log: fmt.Sprintf("Expected 'pubkey/power'. Got %v", pubKeyAndPower)} Log: fmt.Sprintf("Expected 'pubkey/power'. Got %v", pubKeyAndPower)}
} }
pubkeyS, powerS := pubKeyAndPower[0], pubKeyAndPower[1] pubkeyS, powerS := pubKeyAndPower[0], pubKeyAndPower[1]
@ -169,13 +170,13 @@ func (app *PersistentDummyApplication) execValidatorTx(tx []byte) types.Response
pubkey, err := hex.DecodeString(pubkeyS) pubkey, err := hex.DecodeString(pubkeyS)
if err != nil { if err != nil {
return types.ResponseDeliverTx{ return types.ResponseDeliverTx{
Code: types.CodeType_EncodingError,
Code: code.CodeTypeEncodingError,
Log: fmt.Sprintf("Pubkey (%s) is invalid hex", pubkeyS)} Log: fmt.Sprintf("Pubkey (%s) is invalid hex", pubkeyS)}
} }
_, err = crypto.PubKeyFromBytes(pubkey) _, err = crypto.PubKeyFromBytes(pubkey)
if err != nil { if err != nil {
return types.ResponseDeliverTx{ return types.ResponseDeliverTx{
Code: types.CodeType_EncodingError,
Code: code.CodeTypeEncodingError,
Log: fmt.Sprintf("Pubkey (%X) is invalid go-crypto encoded", pubkey)} Log: fmt.Sprintf("Pubkey (%X) is invalid go-crypto encoded", pubkey)}
} }
@ -183,7 +184,7 @@ func (app *PersistentDummyApplication) execValidatorTx(tx []byte) types.Response
power, err := strconv.Atoi(powerS) power, err := strconv.Atoi(powerS)
if err != nil { if err != nil {
return types.ResponseDeliverTx{ return types.ResponseDeliverTx{
Code: types.CodeType_EncodingError,
Code: code.CodeTypeEncodingError,
Log: fmt.Sprintf("Power (%s) is not an int", powerS)} Log: fmt.Sprintf("Power (%s) is not an int", powerS)}
} }
@ -198,7 +199,7 @@ func (app *PersistentDummyApplication) updateValidator(v *types.Validator) types
// remove validator // remove validator
if !app.app.state.Has(key) { if !app.app.state.Has(key) {
return types.ResponseDeliverTx{ return types.ResponseDeliverTx{
Code: types.CodeType_Unauthorized,
Code: code.CodeTypeUnauthorized,
Log: fmt.Sprintf("Cannot remove non-existent validator %X", key)} Log: fmt.Sprintf("Cannot remove non-existent validator %X", key)}
} }
app.app.state.Remove(key) app.app.state.Remove(key)
@ -207,7 +208,7 @@ func (app *PersistentDummyApplication) updateValidator(v *types.Validator) types
value := bytes.NewBuffer(make([]byte, 0)) value := bytes.NewBuffer(make([]byte, 0))
if err := types.WriteMessage(v, value); err != nil { if err := types.WriteMessage(v, value); err != nil {
return types.ResponseDeliverTx{ return types.ResponseDeliverTx{
Code: types.CodeType_InternalError,
Code: code.CodeTypeEncodingError,
Log: fmt.Sprintf("Error encoding validator: %v", err)} Log: fmt.Sprintf("Error encoding validator: %v", err)}
} }
app.app.state.Set(key, value.Bytes()) app.app.state.Set(key, value.Bytes())
@ -216,5 +217,5 @@ func (app *PersistentDummyApplication) updateValidator(v *types.Validator) types
// we only update the changes array if we successfully updated the tree // we only update the changes array if we successfully updated the tree
app.changes = append(app.changes, v) app.changes = append(app.changes, v)
return types.ResponseDeliverTx{Code: types.CodeType_OK}
return types.ResponseDeliverTx{Code: code.CodeTypeOK}
} }

+ 9
- 7
example/example_test.go View File

@ -11,12 +11,14 @@ import (
"golang.org/x/net/context" "golang.org/x/net/context"
cmn "github.com/tendermint/tmlibs/common"
"github.com/tendermint/tmlibs/log"
abcicli "github.com/tendermint/abci/client" abcicli "github.com/tendermint/abci/client"
"github.com/tendermint/abci/example/code"
"github.com/tendermint/abci/example/dummy" "github.com/tendermint/abci/example/dummy"
abciserver "github.com/tendermint/abci/server" abciserver "github.com/tendermint/abci/server"
"github.com/tendermint/abci/types" "github.com/tendermint/abci/types"
cmn "github.com/tendermint/tmlibs/common"
"github.com/tendermint/tmlibs/log"
) )
func TestDummy(t *testing.T) { func TestDummy(t *testing.T) {
@ -40,7 +42,7 @@ func testStream(t *testing.T, app types.Application) {
// Start the listener // Start the listener
server := abciserver.NewSocketServer("unix://test.sock", app) server := abciserver.NewSocketServer("unix://test.sock", app)
server.SetLogger(log.TestingLogger().With("module", "abci-server")) server.SetLogger(log.TestingLogger().With("module", "abci-server"))
if _, err := server.Start(); err != nil {
if err := server.Start(); err != nil {
t.Fatalf("Error starting socket server: %v", err.Error()) t.Fatalf("Error starting socket server: %v", err.Error())
} }
defer server.Stop() defer server.Stop()
@ -48,7 +50,7 @@ func testStream(t *testing.T, app types.Application) {
// Connect to the socket // Connect to the socket
client := abcicli.NewSocketClient("unix://test.sock", false) client := abcicli.NewSocketClient("unix://test.sock", false)
client.SetLogger(log.TestingLogger().With("module", "abci-client")) client.SetLogger(log.TestingLogger().With("module", "abci-client"))
if _, err := client.Start(); err != nil {
if err := client.Start(); err != nil {
t.Fatalf("Error starting socket client: %v", err.Error()) t.Fatalf("Error starting socket client: %v", err.Error())
} }
defer client.Stop() defer client.Stop()
@ -60,7 +62,7 @@ func testStream(t *testing.T, app types.Application) {
switch r := res.Value.(type) { switch r := res.Value.(type) {
case *types.Response_DeliverTx: case *types.Response_DeliverTx:
counter++ counter++
if r.DeliverTx.Code != types.CodeType_OK {
if r.DeliverTx.Code != code.CodeTypeOK {
t.Error("DeliverTx failed with ret_code", r.DeliverTx.Code) t.Error("DeliverTx failed with ret_code", r.DeliverTx.Code)
} }
if counter > numDeliverTxs { if counter > numDeliverTxs {
@ -113,7 +115,7 @@ func testGRPCSync(t *testing.T, app *types.GRPCApplication) {
// Start the listener // Start the listener
server := abciserver.NewGRPCServer("unix://test.sock", app) server := abciserver.NewGRPCServer("unix://test.sock", app)
server.SetLogger(log.TestingLogger().With("module", "abci-server")) server.SetLogger(log.TestingLogger().With("module", "abci-server"))
if _, err := server.Start(); err != nil {
if err := server.Start(); err != nil {
t.Fatalf("Error starting GRPC server: %v", err.Error()) t.Fatalf("Error starting GRPC server: %v", err.Error())
} }
defer server.Stop() defer server.Stop()
@ -135,7 +137,7 @@ func testGRPCSync(t *testing.T, app *types.GRPCApplication) {
t.Fatalf("Error in GRPC DeliverTx: %v", err.Error()) t.Fatalf("Error in GRPC DeliverTx: %v", err.Error())
} }
counter++ counter++
if response.Code != types.CodeType_OK {
if response.Code != code.CodeTypeOK {
t.Error("DeliverTx failed with ret_code", response.Code) t.Error("DeliverTx failed with ret_code", response.Code)
} }
if counter > numDeliverTxs { if counter > numDeliverTxs {


+ 27
- 23
glide.lock View File

@ -1,14 +1,12 @@
hash: 5501ab3d7136aa8fb425c995d45221849b33aefab76c5d2c192e721dad28da38
updated: 2017-11-14T18:23:41.2024073Z
hash: 6cb2c869c8ce7d9e43b1e8930b9b1bc974ebb3d36d4b704fc78b77efba956a13
updated: 2017-11-30T17:08:29.176515576-05:00
imports: imports:
- name: github.com/btcsuite/btcd - name: github.com/btcsuite/btcd
version: b8df516b4b267acf2de46be593a9d948d1d2c420
version: 2e60448ffcc6bf78332d1fe590260095f554dd78
subpackages: subpackages:
- btcec - btcec
- name: github.com/btcsuite/fastsha256
version: 637e656429416087660c84436a2a035d69d54e2e
- name: github.com/go-kit/kit - name: github.com/go-kit/kit
version: d67bb4c202e3b91377d1079b110a6c9ce23ab2f8
version: e3b2152e0063c5f05efea89ecbe297852af2a92d
subpackages: subpackages:
- log - log
- log/level - log/level
@ -16,15 +14,21 @@ imports:
- name: github.com/go-logfmt/logfmt - name: github.com/go-logfmt/logfmt
version: 390ab7935ee28ec6b286364bba9b4dd6410cb3d5 version: 390ab7935ee28ec6b286364bba9b4dd6410cb3d5
- name: github.com/go-playground/locales - name: github.com/go-playground/locales
version: 1e5f1161c6416a5ff48840eb8724a394e48cc534
version: e4cbcb5d0652150d40ad0646651076b6bd2be4f6
subpackages: subpackages:
- currency - currency
- name: github.com/go-playground/universal-translator - name: github.com/go-playground/universal-translator
version: 71201497bace774495daed26a3874fd339e0b538 version: 71201497bace774495daed26a3874fd339e0b538
- name: github.com/go-stack/stack - name: github.com/go-stack/stack
version: 100eb0c0a9c5b306ca2fb4f165df21d80ada4b82
version: 259ab82a6cad3992b4e21ff5cac294ccb06474bc
- name: github.com/gogo/protobuf
version: 342cbe0a04158f6dcb03ca0079991a51a4248c02
subpackages:
- gogoproto
- proto
- protoc-gen-gogo/descriptor
- name: github.com/golang/protobuf - name: github.com/golang/protobuf
version: 1643683e1b54a9e88ad26d98f81400c8c9d9f4f9
version: 1e59b77b52bf8e4b449a57e6f79f21226d571845
subpackages: subpackages:
- proto - proto
- ptypes - ptypes
@ -40,13 +44,13 @@ imports:
- name: github.com/kr/logfmt - name: github.com/kr/logfmt
version: b84e30acd515aadc4b783ad4ff83aff3299bdfe0 version: b84e30acd515aadc4b783ad4ff83aff3299bdfe0
- name: github.com/pkg/errors - name: github.com/pkg/errors
version: 645ef00459ed84a119197bfb8d8205042c6df63d
version: f15c970de5b76fac0b59abb32d62c17cc7bed265
- name: github.com/spf13/cobra - name: github.com/spf13/cobra
version: 7b2c5ac9fc04fc5efafb60700713d4fa609b777b version: 7b2c5ac9fc04fc5efafb60700713d4fa609b777b
- name: github.com/spf13/pflag - name: github.com/spf13/pflag
version: 80fe0fb4eba54167e2ccae1c6c950e72abf61b73
version: 4c012f6dcd9546820e378d0bdda4d8fc772cdfea
- name: github.com/syndtr/goleveldb - name: github.com/syndtr/goleveldb
version: 8c81ea47d4c41a385645e133e15510fc6a2a74b4
version: adf24ef3f94bd13ec4163060b21a5678f22b429b
subpackages: subpackages:
- leveldb - leveldb
- leveldb/cache - leveldb/cache
@ -61,27 +65,27 @@ imports:
- leveldb/table - leveldb/table
- leveldb/util - leveldb/util
- name: github.com/tendermint/ed25519 - name: github.com/tendermint/ed25519
version: 1f52c6f8b8a5c7908aff4497c186af344b428925
version: d8387025d2b9d158cf4efb07e7ebf814bcce2057
subpackages: subpackages:
- edwards25519 - edwards25519
- extra25519 - extra25519
- name: github.com/tendermint/go-crypto - name: github.com/tendermint/go-crypto
version: b4f04f196cd719660e43b91202cd60d9a95b1837 version: b4f04f196cd719660e43b91202cd60d9a95b1837
- name: github.com/tendermint/go-wire - name: github.com/tendermint/go-wire
version: 1c96861c03231361546944d883d99593b2e6b408
version: 5ab49b4c6ad674da6b81442911cf713ef0afb544
subpackages: subpackages:
- data - data
- name: github.com/tendermint/iavl - name: github.com/tendermint/iavl
version: 595f3dcd5b6cd4a292e90757ae6d367fd7a6e653 version: 595f3dcd5b6cd4a292e90757ae6d367fd7a6e653
- name: github.com/tendermint/tmlibs - name: github.com/tendermint/tmlibs
version: 2442a0a698d271d5cf5d6a8e7c1db20335e959c1
version: 21fb7819891997c96838308b4eba5a50b07ff03f
subpackages: subpackages:
- common - common
- db - db
- log - log
- process - process
- name: golang.org/x/crypto - name: golang.org/x/crypto
version: c7af5bf2638a1164f2eb5467c39c6cffbd13a02e
version: 94eea52f7b742c7cbe0b03b22f0c4c8631ece122
subpackages: subpackages:
- nacl/secretbox - nacl/secretbox
- openpgp/armor - openpgp/armor
@ -90,7 +94,7 @@ imports:
- ripemd160 - ripemd160
- salsa20/salsa - salsa20/salsa
- name: golang.org/x/net - name: golang.org/x/net
version: cd69bc3fc700721b709c3a59e16e24c67b58f6ff
version: a8b9294777976932365dabb6640cf1468d95c70f
subpackages: subpackages:
- context - context
- http2 - http2
@ -100,18 +104,18 @@ imports:
- lex/httplex - lex/httplex
- trace - trace
- name: golang.org/x/text - name: golang.org/x/text
version: 470f45bf29f4147d6fbd7dfd0a02a848e49f5bf4
version: 75cc3cad82b5f47d3fb229ddda8c5167da14f294
subpackages: subpackages:
- secure/bidirule - secure/bidirule
- transform - transform
- unicode/bidi - unicode/bidi
- unicode/norm - unicode/norm
- name: google.golang.org/genproto - name: google.golang.org/genproto
version: f676e0f3ac6395ff1a529ae59a6670878a8371a6
version: 7f0da29060c682909f650ad8ed4e515bd74fa12a
subpackages: subpackages:
- googleapis/rpc/status - googleapis/rpc/status
- name: google.golang.org/grpc - name: google.golang.org/grpc
version: f7bf885db0b7479a537ec317c6e48ce53145f3db
version: 401e0e00e4bb830a10496d64cd95e068c5bf50de
subpackages: subpackages:
- balancer - balancer
- codes - codes
@ -130,10 +134,10 @@ imports:
- tap - tap
- transport - transport
- name: gopkg.in/go-playground/validator.v9 - name: gopkg.in/go-playground/validator.v9
version: 6d8c18553ea1ac493d049edd6f102f52e618f085
version: 61caf9d3038e1af346dbf5c2e16f6678e1548364
testImports: testImports:
- name: github.com/davecgh/go-spew - name: github.com/davecgh/go-spew
version: 6d212800a42e8ab5c146b8ace3490ee17e5225f9
version: 04cdfd42973bb9c8589fd6a731800cf222fde1a9
subpackages: subpackages:
- spew - spew
- name: github.com/pmezard/go-difflib - name: github.com/pmezard/go-difflib
@ -141,7 +145,7 @@ testImports:
subpackages: subpackages:
- difflib - difflib
- name: github.com/stretchr/testify - name: github.com/stretchr/testify
version: 69483b4bd14f5845b5a1e55bca19e954e827f1d0
version: 2aa2c176b9dab406a6970f6a55f513e8a8c8b18f
subpackages: subpackages:
- assert - assert
- require - require

+ 4
- 1
glide.yaml View File

@ -1,9 +1,11 @@
package: github.com/tendermint/abci package: github.com/tendermint/abci
import: import:
- package: github.com/golang/protobuf
- package: github.com/gogo/protobuf
version: v0.5
subpackages: subpackages:
- proto - proto
- package: github.com/spf13/cobra - package: github.com/spf13/cobra
version: v0.0.1
- package: github.com/tendermint/go-crypto - package: github.com/tendermint/go-crypto
version: develop version: develop
- package: github.com/tendermint/go-wire - package: github.com/tendermint/go-wire
@ -23,6 +25,7 @@ import:
subpackages: subpackages:
- context - context
- package: google.golang.org/grpc - package: google.golang.org/grpc
version: v1.7.3
testImport: testImport:
- package: github.com/stretchr/testify - package: github.com/stretchr/testify
subpackages: subpackages:


+ 1
- 0
server/grpc_server.go View File

@ -42,6 +42,7 @@ func (s *GRPCServer) OnStart() error {
if err != nil { if err != nil {
return err return err
} }
s.Logger.Info("Listening", "proto", s.proto, "addr", s.addr)
s.listener = ln s.listener = ln
s.server = grpc.NewServer() s.server = grpc.NewServer()
types.RegisterABCIApplicationServer(s.server, s.app) types.RegisterABCIApplicationServer(s.server, s.app)


+ 2
- 2
tests/client_server_test.go View File

@ -17,11 +17,11 @@ func TestClientServerNoAddrPrefix(t *testing.T) {
server, err := abciserver.NewServer(addr, transport, app) server, err := abciserver.NewServer(addr, transport, app)
assert.NoError(t, err, "expected no error on NewServer") assert.NoError(t, err, "expected no error on NewServer")
_, err = server.Start()
err = server.Start()
assert.NoError(t, err, "expected no error on server.Start") assert.NoError(t, err, "expected no error on server.Start")
client, err := abciclient.NewClient(addr, transport, true) client, err := abciclient.NewClient(addr, transport, true)
assert.NoError(t, err, "expected no error on NewClient") assert.NoError(t, err, "expected no error on NewClient")
_, err = client.Start()
err = client.Start()
assert.NoError(t, err, "expected no error on client.Start") assert.NoError(t, err, "expected no error on client.Start")
} }

+ 3
- 3
tests/test_app/app.go View File

@ -18,7 +18,7 @@ func startClient(abciType string) abcicli.Client {
} }
logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout))
client.SetLogger(logger.With("module", "abcicli")) client.SetLogger(logger.With("module", "abcicli"))
if _, err := client.Start(); err != nil {
if err := client.Start(); err != nil {
panicf("connecting to abci_app: %v", err.Error()) panicf("connecting to abci_app: %v", err.Error())
} }
@ -45,7 +45,7 @@ func commit(client abcicli.Client, hashExp []byte) {
} }
} }
func deliverTx(client abcicli.Client, txBytes []byte, codeExp types.CodeType, dataExp []byte) {
func deliverTx(client abcicli.Client, txBytes []byte, codeExp uint32, dataExp []byte) {
res, err := client.DeliverTxSync(txBytes) res, err := client.DeliverTxSync(txBytes)
if err != nil { if err != nil {
panicf("client error: %v", err) panicf("client error: %v", err)
@ -58,7 +58,7 @@ func deliverTx(client abcicli.Client, txBytes []byte, codeExp types.CodeType, da
} }
} }
/*func checkTx(client abcicli.Client, txBytes []byte, codeExp types.CodeType, dataExp []byte) {
/*func checkTx(client abcicli.Client, txBytes []byte, codeExp uint32, dataExp []byte) {
res, err := client.CheckTxSync(txBytes) res, err := client.CheckTxSync(txBytes)
if err != nil { if err != nil {
panicf("client error: %v", err) panicf("client error: %v", err)


+ 9
- 8
tests/test_app/main.go View File

@ -7,6 +7,7 @@ import (
"os/exec" "os/exec"
"time" "time"
"github.com/tendermint/abci/example/code"
"github.com/tendermint/abci/types" "github.com/tendermint/abci/types"
) )
@ -69,15 +70,15 @@ func testCounter() {
setOption(client, "serial", "on") setOption(client, "serial", "on")
commit(client, nil) commit(client, nil)
deliverTx(client, []byte("abc"), types.CodeType_BadNonce, nil)
deliverTx(client, []byte("abc"), code.CodeTypeBadNonce, nil)
commit(client, nil) commit(client, nil)
deliverTx(client, []byte{0x00}, types.CodeType_OK, nil)
deliverTx(client, []byte{0x00}, types.CodeTypeOK, nil)
commit(client, []byte{0, 0, 0, 0, 0, 0, 0, 1}) commit(client, []byte{0, 0, 0, 0, 0, 0, 0, 1})
deliverTx(client, []byte{0x00}, types.CodeType_BadNonce, nil)
deliverTx(client, []byte{0x01}, types.CodeType_OK, nil)
deliverTx(client, []byte{0x00, 0x02}, types.CodeType_OK, nil)
deliverTx(client, []byte{0x00, 0x03}, types.CodeType_OK, nil)
deliverTx(client, []byte{0x00, 0x00, 0x04}, types.CodeType_OK, nil)
deliverTx(client, []byte{0x00, 0x00, 0x06}, types.CodeType_BadNonce, nil)
deliverTx(client, []byte{0x00}, code.CodeTypeBadNonce, nil)
deliverTx(client, []byte{0x01}, types.CodeTypeOK, nil)
deliverTx(client, []byte{0x00, 0x02}, types.CodeTypeOK, nil)
deliverTx(client, []byte{0x00, 0x03}, types.CodeTypeOK, nil)
deliverTx(client, []byte{0x00, 0x00, 0x04}, types.CodeTypeOK, nil)
deliverTx(client, []byte{0x00, 0x00, 0x06}, code.CodeTypeBadNonce, nil)
commit(client, []byte{0, 0, 0, 0, 0, 0, 0, 5}) commit(client, []byte{0, 0, 0, 0, 0, 0, 0, 5})
} }

+ 5
- 0
tests/test_app/test.sh View File

@ -11,11 +11,16 @@ DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
# Change into that dir because we expect that. # Change into that dir because we expect that.
cd "$DIR" cd "$DIR"
echo "RUN COUNTER OVER SOCKET"
# test golang counter # test golang counter
ABCI_APP="counter" go run ./*.go ABCI_APP="counter" go run ./*.go
echo "----------------------"
echo "RUN COUNTER OVER GRPC"
# test golang counter via grpc # test golang counter via grpc
ABCI_APP="counter --abci=grpc" ABCI="grpc" go run ./*.go ABCI_APP="counter --abci=grpc" ABCI="grpc" go run ./*.go
echo "----------------------"
# test nodejs counter # test nodejs counter
# TODO: fix node app # TODO: fix node app


+ 2
- 2
tests/test_cli/ex2.abci.out View File

@ -11,14 +11,14 @@
-> code: OK -> code: OK
> check_tx 0x00 > check_tx 0x00
-> code: BadNonce
-> code: 2
-> log: Invalid nonce. Expected >= 1, got 0 -> log: Invalid nonce. Expected >= 1, got 0
> deliver_tx 0x01 > deliver_tx 0x01
-> code: OK -> code: OK
> deliver_tx 0x04 > deliver_tx 0x04
-> code: BadNonce
-> code: 2
-> log: Invalid nonce. Expected 2, got 4 -> log: Invalid nonce. Expected 2, got 4
> info > info


+ 1
- 1
tests/test_cli/test.sh View File

@ -17,7 +17,7 @@ function testExample() {
echo "Example $N: $APP" echo "Example $N: $APP"
$APP &> /dev/null & $APP &> /dev/null &
sleep 2 sleep 2
abci-cli --verbose batch < "$INPUT" > "${INPUT}.out.new"
abci-cli --log_level=error --verbose batch < "$INPUT" > "${INPUT}.out.new"
killall "$3" killall "$3"
pre=$(shasum < "${INPUT}.out") pre=$(shasum < "${INPUT}.out")


+ 4
- 4
types/base_app.go View File

@ -16,19 +16,19 @@ func (BaseApplication) SetOption(req RequestSetOption) ResponseSetOption {
} }
func (BaseApplication) DeliverTx(tx []byte) ResponseDeliverTx { func (BaseApplication) DeliverTx(tx []byte) ResponseDeliverTx {
return ResponseDeliverTx{Code: CodeType_OK}
return ResponseDeliverTx{Code: CodeTypeOK}
} }
func (BaseApplication) CheckTx(tx []byte) ResponseCheckTx { func (BaseApplication) CheckTx(tx []byte) ResponseCheckTx {
return ResponseCheckTx{Code: CodeType_OK}
return ResponseCheckTx{Code: CodeTypeOK}
} }
func (BaseApplication) Commit() ResponseCommit { func (BaseApplication) Commit() ResponseCommit {
return ResponseCommit{Code: CodeType_OK, Data: []byte("nil")}
return ResponseCommit{Code: CodeTypeOK}
} }
func (BaseApplication) Query(req RequestQuery) ResponseQuery { func (BaseApplication) Query(req RequestQuery) ResponseQuery {
return ResponseQuery{Code: CodeType_OK}
return ResponseQuery{Code: CodeTypeOK}
} }
func (BaseApplication) InitChain(req RequestInitChain) ResponseInitChain { func (BaseApplication) InitChain(req RequestInitChain) ResponseInitChain {


+ 0
- 37
types/code.go View File

@ -1,37 +0,0 @@
package types
var (
code2string = map[CodeType]string{
CodeType_InternalError: "Internal error",
CodeType_EncodingError: "Encoding error",
CodeType_BadNonce: "Error bad nonce",
CodeType_Unauthorized: "Unauthorized",
CodeType_InsufficientFunds: "Insufficient funds",
CodeType_UnknownRequest: "Unknown request",
CodeType_BaseDuplicateAddress: "Error (base) duplicate address",
CodeType_BaseEncodingError: "Error (base) encoding error",
CodeType_BaseInsufficientFees: "Error (base) insufficient fees",
CodeType_BaseInsufficientFunds: "Error (base) insufficient funds",
CodeType_BaseInsufficientGasPrice: "Error (base) insufficient gas price",
CodeType_BaseInvalidInput: "Error (base) invalid input",
CodeType_BaseInvalidOutput: "Error (base) invalid output",
CodeType_BaseInvalidPubKey: "Error (base) invalid pubkey",
CodeType_BaseInvalidSequence: "Error (base) invalid sequence",
CodeType_BaseInvalidSignature: "Error (base) invalid signature",
CodeType_BaseUnknownAddress: "Error (base) unknown address",
CodeType_BaseUnknownPlugin: "Error (base) unknown plugin",
CodeType_BaseUnknownPubKey: "Error (base) unknown pubkey",
}
)
func (c CodeType) IsOK() bool { return c == CodeType_OK }
// HumanCode transforms code into a more humane format, such as "Internal error" instead of 0.
func HumanCode(code CodeType) string {
s, ok := code2string[code]
if !ok {
return "Unknown code"
}
return s
}

+ 0
- 12
types/code_test.go View File

@ -1,12 +0,0 @@
package types
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestHumanCode(t *testing.T) {
assert.Equal(t, "Internal error", HumanCode(CodeType_InternalError))
assert.Equal(t, "Unknown code", HumanCode(-1))
}

+ 1
- 1
types/messages.go View File

@ -3,7 +3,7 @@ package types
import ( import (
"io" "io"
"github.com/golang/protobuf/proto"
"github.com/gogo/protobuf/proto"
wire "github.com/tendermint/go-wire" wire "github.com/tendermint/go-wire"
) )


+ 55
- 0
types/protoreplace/protoreplace.go View File

@ -0,0 +1,55 @@
package main
// +build ignore
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"os/exec"
"regexp"
"strings"
)
// This script replaces most `[]byte` with `data.Bytes` in a `.pb.go` file.
// It was written before we realized we could use `gogo/protobuf` to achieve
// this more natively. So it's here for safe keeping in case we ever need to
// abandon `gogo/protobuf`.
func main() {
bytePattern := regexp.MustCompile("[[][]]byte")
const oldPath = "types/types.pb.go"
const tmpPath = "types/types.pb.new"
content, err := ioutil.ReadFile(oldPath)
if err != nil {
panic("cannot read " + oldPath)
os.Exit(1)
}
lines := bytes.Split(content, []byte("\n"))
outFile, _ := os.Create(tmpPath)
wroteImport := false
for _, line_bytes := range lines {
line := string(line_bytes)
gotPackageLine := strings.HasPrefix(line, "package ")
writeImportTime := strings.HasPrefix(line, "import ")
containsDescriptor := strings.Contains(line, "Descriptor")
containsByteArray := strings.Contains(line, "[]byte")
if containsByteArray && !containsDescriptor {
line = string(bytePattern.ReplaceAll([]byte(line), []byte("data.Bytes")))
}
if writeImportTime && !wroteImport {
wroteImport = true
fmt.Fprintf(outFile, "import \"github.com/tendermint/go-wire/data\"\n")
}
if gotPackageLine {
fmt.Fprintf(outFile, "%s\n", "//nolint: gas")
}
fmt.Fprintf(outFile, "%s\n", line)
}
outFile.Close()
os.Remove(oldPath)
os.Rename(tmpPath, oldPath)
exec.Command("goimports", "-w", oldPath)
}

+ 14
- 42
types/result.go View File

@ -2,13 +2,15 @@ package types
import ( import (
"fmt" "fmt"
)
"github.com/tendermint/go-wire/data"
const (
CodeTypeOK uint32 = 0
) )
// IsErr returns true if Code is something other than OK. // IsErr returns true if Code is something other than OK.
func (r ResponseCheckTx) IsErr() bool { func (r ResponseCheckTx) IsErr() bool {
return r.Code != CodeType_OK
return r.Code != CodeTypeOK
} }
// Error implements error interface by formatting response as string. // Error implements error interface by formatting response as string.
@ -18,7 +20,7 @@ func (r ResponseCheckTx) Error() string {
// IsErr returns true if Code is something other than OK. // IsErr returns true if Code is something other than OK.
func (r ResponseDeliverTx) IsErr() bool { func (r ResponseDeliverTx) IsErr() bool {
return r.Code != CodeType_OK
return r.Code != CodeTypeOK
} }
// Error implements error interface by formatting response as string. // Error implements error interface by formatting response as string.
@ -28,7 +30,7 @@ func (r ResponseDeliverTx) Error() string {
// IsErr returns true if Code is something other than OK. // IsErr returns true if Code is something other than OK.
func (r ResponseCommit) IsErr() bool { func (r ResponseCommit) IsErr() bool {
return r.Code != CodeType_OK
return r.Code != CodeTypeOK
} }
// Error implements error interface by formatting response as string. // Error implements error interface by formatting response as string.
@ -36,46 +38,16 @@ func (r ResponseCommit) Error() string {
return fmtError(r.Code, r.Log) return fmtError(r.Code, r.Log)
} }
func fmtError(code CodeType, log string) string {
codeAsStr, ok := code2string[code]
if ok {
return fmt.Sprintf("%s (%d): %s", codeAsStr, code, log)
} else {
return fmt.Sprintf("Unknown error (%d): %s", code, log)
}
}
// ResultQuery is a wrapper around ResponseQuery using data.Bytes instead of
// raw byte slices.
type ResultQuery struct {
Code CodeType `json:"code"`
Index int64 `json:"index"`
Key data.Bytes `json:"key"`
Value data.Bytes `json:"value"`
Proof data.Bytes `json:"proof"`
Height uint64 `json:"height"`
Log string `json:"log"`
}
// Result converts response query to ResultQuery.
func (r *ResponseQuery) Result() *ResultQuery {
return &ResultQuery{
Code: r.Code,
Index: r.Index,
Key: r.Key,
Value: r.Value,
Proof: r.Proof,
Height: r.Height,
Log: r.Log,
}
}
// IsErr returns true if Code is something other than OK. // IsErr returns true if Code is something other than OK.
func (r *ResultQuery) IsErr() bool {
return r.Code != CodeType_OK
func (r ResponseQuery) IsErr() bool {
return r.Code != CodeTypeOK
} }
// Error implements error interface by formatting result as string.
func (r *ResultQuery) Error() string {
// Error implements error interface by formatting response as string.
func (r ResponseQuery) Error() string {
return fmtError(r.Code, r.Log) return fmtError(r.Code, r.Log)
} }
func fmtError(code uint32, log string) string {
return fmt.Sprintf("Error code (%d): %s", code, log)
}

+ 15
- 17
types/result_test.go View File

@ -6,71 +6,69 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func TestResultQuery(t *testing.T) {
orig := &ResponseQuery{
Code: CodeType_OK,
func TestResponseQuery(t *testing.T) {
res := ResponseQuery{
Code: CodeTypeOK,
Index: 0, Index: 0,
Key: []byte("hello"), Key: []byte("hello"),
Value: []byte("world"), Value: []byte("world"),
Height: 1, Height: 1,
} }
res := orig.Result()
assert.False(t, res.IsErr()) assert.False(t, res.IsErr())
orig = &ResponseQuery{
Code: CodeType_BadNonce,
res = ResponseQuery{
Code: 1,
Index: 0, Index: 0,
Key: []byte("hello"), Key: []byte("hello"),
Value: []byte("world"), Value: []byte("world"),
Height: 1, Height: 1,
Log: "bad", Log: "bad",
} }
res = orig.Result()
assert.True(t, res.IsErr()) assert.True(t, res.IsErr())
assert.Equal(t, "Error bad nonce (3): bad", res.Error())
assert.Equal(t, "Error code (1): bad", res.Error())
} }
func TestResponseDeliverTx(t *testing.T) { func TestResponseDeliverTx(t *testing.T) {
res := ResponseDeliverTx{ res := ResponseDeliverTx{
Code: CodeType_OK,
Code: CodeTypeOK,
Data: []byte("Victor Mancha"), Data: []byte("Victor Mancha"),
} }
assert.False(t, res.IsErr()) assert.False(t, res.IsErr())
res = ResponseDeliverTx{ res = ResponseDeliverTx{
Code: CodeType_InternalError,
Code: 1,
Log: "bad", Log: "bad",
} }
assert.True(t, res.IsErr()) assert.True(t, res.IsErr())
assert.Equal(t, "Internal error (1): bad", res.Error())
assert.Equal(t, "Error code (1): bad", res.Error())
} }
func TestResponseCheckTx(t *testing.T) { func TestResponseCheckTx(t *testing.T) {
res := ResponseCheckTx{ res := ResponseCheckTx{
Code: CodeType_OK,
Code: CodeTypeOK,
Data: []byte("Talos"), Data: []byte("Talos"),
} }
assert.False(t, res.IsErr()) assert.False(t, res.IsErr())
res = ResponseCheckTx{ res = ResponseCheckTx{
Code: CodeType_InternalError,
Code: 1,
Log: "bad", Log: "bad",
} }
assert.True(t, res.IsErr()) assert.True(t, res.IsErr())
assert.Equal(t, "Internal error (1): bad", res.Error())
assert.Equal(t, "Error code (1): bad", res.Error())
} }
func TestResponseCommit(t *testing.T) { func TestResponseCommit(t *testing.T) {
res := ResponseCommit{ res := ResponseCommit{
Code: CodeType_OK,
Code: CodeTypeOK,
Data: []byte("Old Lace"), Data: []byte("Old Lace"),
} }
assert.False(t, res.IsErr()) assert.False(t, res.IsErr())
res = ResponseCommit{ res = ResponseCommit{
Code: CodeType_Unauthorized,
Code: 1,
Log: "bad", Log: "bad",
} }
assert.True(t, res.IsErr()) assert.True(t, res.IsErr())
assert.Equal(t, "Unauthorized (4): bad", res.Error())
assert.Equal(t, "Error code (1): bad", res.Error())
} }

+ 210
- 379
types/types.pb.go
File diff suppressed because it is too large
View File


+ 12
- 52
types/types.proto View File

@ -1,50 +1,10 @@
syntax = "proto3"; syntax = "proto3";
package types; package types;
// This file is copied from http://github.com/tendermint/abci
import "github.com/gogo/protobuf/gogoproto/gogo.proto";
//----------------------------------------
// Code types
enum CodeType {
OK = 0;
// General response codes, 0 ~ 99
InternalError = 1;
EncodingError = 2;
BadNonce = 3;
Unauthorized = 4;
InsufficientFunds = 5;
UnknownRequest = 6;
// Reserved for basecoin, 100 ~ 199
BaseDuplicateAddress = 101;
BaseEncodingError = 102;
BaseInsufficientFees = 103;
BaseInsufficientFunds = 104;
BaseInsufficientGasPrice = 105;
BaseInvalidInput = 106;
BaseInvalidOutput = 107;
BaseInvalidPubKey = 108;
BaseInvalidSequence = 109;
BaseInvalidSignature = 110;
BaseUnknownAddress = 111;
BaseUnknownPubKey = 112;
BaseUnknownPlugin = 113;
// Reserved for governance, 200 ~ 299
GovUnknownEntity = 201;
GovUnknownGroup = 202;
GovUnknownProposal = 203;
GovDuplicateGroup = 204;
GovDuplicateMember = 205;
GovDuplicateProposal = 206;
GovDuplicateVote = 207;
GovInvalidMember = 208;
GovInvalidVote = 209;
GovInvalidVotingPower = 210;
}
// This file is copied from http://github.com/tendermint/abci
//---------------------------------------- //----------------------------------------
// Request types // Request types
@ -156,33 +116,33 @@ message ResponseSetOption{
} }
message ResponseDeliverTx{ message ResponseDeliverTx{
CodeType code = 1;
bytes data = 2;
uint32 code = 1;
bytes data = 2 [(gogoproto.customtype) = "github.com/tendermint/go-wire/data.Bytes", (gogoproto.nullable) = false];
string log = 3; string log = 3;
repeated KVPair tags = 4; repeated KVPair tags = 4;
} }
message ResponseCheckTx{ message ResponseCheckTx{
CodeType code = 1;
bytes data = 2;
uint32 code = 1;
bytes data = 2 [(gogoproto.customtype) = "github.com/tendermint/go-wire/data.Bytes", (gogoproto.nullable) = false];
string log = 3; string log = 3;
uint64 gas = 4; uint64 gas = 4;
uint64 fee = 5; uint64 fee = 5;
} }
message ResponseQuery{ message ResponseQuery{
CodeType code = 1;
uint32 code = 1;
int64 index = 2; int64 index = 2;
bytes key = 3;
bytes value = 4;
bytes proof = 5;
bytes key = 3 [(gogoproto.customtype) = "github.com/tendermint/go-wire/data.Bytes", (gogoproto.nullable) = false];
bytes value = 4 [(gogoproto.customtype) = "github.com/tendermint/go-wire/data.Bytes", (gogoproto.nullable) = false];
bytes proof = 5 [(gogoproto.customtype) = "github.com/tendermint/go-wire/data.Bytes", (gogoproto.nullable) = false];
uint64 height = 6; uint64 height = 6;
string log = 7; string log = 7;
} }
message ResponseCommit{ message ResponseCommit{
CodeType code = 1;
bytes data = 2;
uint32 code = 1;
bytes data = 2 [(gogoproto.customtype) = "github.com/tendermint/go-wire/data.Bytes", (gogoproto.nullable) = false];
string log = 3; string log = 3;
} }


Loading…
Cancel
Save