diff --git a/CHANGELOG.md b/CHANGELOG.md index 9fa63bad7693..19c315607ca5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## 0.15.0 (TBD) + +BREAKING CHANGES + +* Remove go-wire, use go-amino + ## 0.14.0 (April 9, 2018) BREAKING CHANGES: diff --git a/Gopkg.lock b/Gopkg.lock index 4f545a61485b..bb083c8ace55 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -274,6 +274,12 @@ ] revision = "d8387025d2b9d158cf4efb07e7ebf814bcce2057" +[[projects]] + name = "github.com/tendermint/go-amino" + packages = ["."] + revision = "42246108ff925a457fb709475070a03dfd3e2b5c" + version = "0.9.6" + [[projects]] name = "github.com/tendermint/go-crypto" packages = [ @@ -283,17 +289,13 @@ "keys/words", "keys/words/wordlist" ] - revision = "c3e19f3ea26f5c3357e0bcbb799b0761ef923755" - version = "v0.5.0" + revision = "915416979bf70efa4bcbf1c6cd5d64c5fff9fc19" + version = "v0.6.2" [[projects]] name = "github.com/tendermint/go-wire" - packages = [ - ".", - "data" - ] + packages = ["."] revision = "fa721242b042ecd4c6ed1a934ee740db4f74e45c" - source = "github.com/tendermint/go-amino" version = "v0.7.3" [[projects]] @@ -338,11 +340,10 @@ "state/txindex/null", "types", "types/priv_validator", - "version", - "wire" + "version" ] - revision = "4930b61a381b9fb9bc530eb5deb56ea6429a1c3a" - version = "v0.18.0" + revision = "dcd00b0e688f133b9634aee513f8bf856e659356" + version = "v0.19.0-rc4" [[projects]] name = "github.com/tendermint/tmlibs" @@ -458,6 +459,6 @@ [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "669e58d0c4eb48e506f1abc66119c2f21b6600d4e08e8875ac83567b5c721565" + inputs-digest = "ad499422ee60cf89fd9d61e232e33d0a17f7b43e0ff7aff0c0a22949901096e8" solver-name = "gps-cdcl" solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml index e66037a437a1..59119b1fe8f8 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -53,29 +53,28 @@ version = "~1.2.1" [[constraint]] - version = "~0.10.2" name = "github.com/tendermint/abci" + version = "~0.10.3" [[constraint]] - version = "~0.5.0" name = "github.com/tendermint/go-crypto" + version = "~0.6.2" [[constraint]] - version = "~0.7.3" - source = "github.com/tendermint/go-amino" - name = "github.com/tendermint/go-wire" + name = "github.com/tendermint/go-amino" + version = "~0.9.6" [[constraint]] - version = "~0.7.0" name = "github.com/tendermint/iavl" + version = "~0.7.0" [[constraint]] - version = "~0.18.0" name = "github.com/tendermint/tendermint" + version = "0.19.0-rc4" -[[override]] - version = "~0.8.1" +[[constraint]] name = "github.com/tendermint/tmlibs" + version = "~0.8.1" [prune] go-tests = true diff --git a/baseapp/baseapp_test.go b/baseapp/baseapp_test.go index 1658c591d679..29b224c468dd 100644 --- a/baseapp/baseapp_test.go +++ b/baseapp/baseapp_test.go @@ -432,7 +432,7 @@ func makePubKey(secret string) crypto.PubKey { func makePrivKey(secret string) crypto.PrivKey { privKey := crypto.GenPrivKeyEd25519FromSecret([]byte(secret)) - return privKey.Wrap() + return privKey } func secret(index int) string { diff --git a/client/lcd/helpers.go b/client/lcd/helpers.go index 71278fca33ae..64814a5fcf11 100644 --- a/client/lcd/helpers.go +++ b/client/lcd/helpers.go @@ -7,6 +7,7 @@ import ( "os" "path/filepath" "strings" + "time" cmn "github.com/tendermint/tmlibs/common" @@ -21,11 +22,15 @@ func waitForRPC() { laddr := GetConfig().RPC.ListenAddress fmt.Println("LADDR", laddr) client := rpcclient.NewJSONRPCClient(laddr) + ctypes.RegisterAmino(client.Codec()) result := new(ctypes.ResultStatus) for { _, err := client.Call("status", map[string]interface{}{}, result) if err == nil { return + } else { + fmt.Println("error", err) + time.Sleep(time.Millisecond) } } } diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index 48cc35a8e6c3..fe38b18d8fb4 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -25,6 +25,7 @@ import ( ctypes "github.com/tendermint/tendermint/rpc/core/types" tmrpc "github.com/tendermint/tendermint/rpc/lib/server" tmtypes "github.com/tendermint/tendermint/types" + pvm "github.com/tendermint/tendermint/types/priv_validator" "github.com/tendermint/tmlibs/cli" dbm "github.com/tendermint/tmlibs/db" "github.com/tendermint/tmlibs/log" @@ -34,8 +35,6 @@ import ( bapp "github.com/cosmos/cosmos-sdk/examples/basecoin/app" btypes "github.com/cosmos/cosmos-sdk/examples/basecoin/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" - "github.com/cosmos/cosmos-sdk/x/auth" ) var ( @@ -89,7 +88,7 @@ func TestKeys(t *testing.T) { res, body = request(t, port, "GET", "/keys", nil) require.Equal(t, http.StatusOK, res.StatusCode, body) var m [2]keys.KeyOutput - err = json.Unmarshal([]byte(body), &m) + err = cdc.UnmarshalJSON([]byte(body), &m) require.Nil(t, err) assert.Equal(t, m[0].Name, name, "Did not serve keys name correctly") @@ -102,7 +101,7 @@ func TestKeys(t *testing.T) { res, body = request(t, port, "GET", keyEndpoint, nil) require.Equal(t, http.StatusOK, res.StatusCode, body) var m2 keys.KeyOutput - err = json.Unmarshal([]byte(body), &m2) + err = cdc.UnmarshalJSON([]byte(body), &m2) require.Nil(t, err) assert.Equal(t, newName, m2.Name, "Did not serve keys name correctly") @@ -142,7 +141,7 @@ func TestNodeStatus(t *testing.T) { require.Equal(t, http.StatusOK, res.StatusCode, body) var nodeInfo p2p.NodeInfo - err := json.Unmarshal([]byte(body), &nodeInfo) + err := cdc.UnmarshalJSON([]byte(body), &nodeInfo) require.Nil(t, err, "Couldn't parse node info") assert.NotEqual(t, p2p.NodeInfo{}, nodeInfo, "res: %v", res) @@ -165,7 +164,7 @@ func TestBlock(t *testing.T) { res, body := request(t, port, "GET", "/blocks/latest", nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - err := json.Unmarshal([]byte(body), &resultBlock) + err := cdc.UnmarshalJSON([]byte(body), &resultBlock) require.Nil(t, err, "Couldn't parse block") assert.NotEqual(t, ctypes.ResultBlock{}, resultBlock) @@ -193,7 +192,7 @@ func TestValidators(t *testing.T) { res, body := request(t, port, "GET", "/validatorsets/latest", nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - err := json.Unmarshal([]byte(body), &resultVals) + err := cdc.UnmarshalJSON([]byte(body), &resultVals) require.Nil(t, err, "Couldn't parse validatorset") assert.NotEqual(t, ctypes.ResultValidators{}, resultVals) @@ -203,7 +202,7 @@ func TestValidators(t *testing.T) { res, body = request(t, port, "GET", "/validatorsets/1", nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - err = json.Unmarshal([]byte(body), &resultVals) + err = cdc.UnmarshalJSON([]byte(body), &resultVals) require.Nil(t, err, "Couldn't parse validatorset") assert.NotEqual(t, ctypes.ResultValidators{}, resultVals) @@ -220,6 +219,9 @@ func TestCoinSend(t *testing.T) { res, body := request(t, port, "GET", "/accounts/8FA6AB57AD6870F6B5B2E57735F38F2F30E73CB6", nil) require.Equal(t, http.StatusNoContent, res.StatusCode, body) + acc := getAccount(t, sendAddr) + initialBalance := acc.GetCoins() + // create TX receiveAddr, resultTx := doSend(t, port, seed) waitForHeight(resultTx.Height + 1) @@ -229,24 +231,15 @@ func TestCoinSend(t *testing.T) { assert.Equal(t, uint32(0), resultTx.DeliverTx.Code) // query sender - res, body = request(t, port, "GET", "/accounts/"+sendAddr, nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var m auth.BaseAccount - err := json.Unmarshal([]byte(body), &m) - require.Nil(t, err) - coins := m.Coins + acc = getAccount(t, sendAddr) + coins := acc.GetCoins() mycoins := coins[0] assert.Equal(t, coinDenom, mycoins.Denom) - assert.Equal(t, coinAmount-1, mycoins.Amount) + assert.Equal(t, initialBalance[0].Amount-1, mycoins.Amount) // query receiver - res, body = request(t, port, "GET", "/accounts/"+receiveAddr, nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - err = json.Unmarshal([]byte(body), &m) - require.Nil(t, err) - coins = m.Coins + acc = getAccount(t, receiveAddr) + coins = acc.GetCoins() mycoins = coins[0] assert.Equal(t, coinDenom, mycoins.Denom) assert.Equal(t, int64(1), mycoins.Amount) @@ -254,6 +247,9 @@ func TestCoinSend(t *testing.T) { func TestIBCTransfer(t *testing.T) { + acc := getAccount(t, sendAddr) + initialBalance := acc.GetCoins() + // create TX resultTx := doIBCTransfer(t, port, seed) @@ -264,16 +260,11 @@ func TestIBCTransfer(t *testing.T) { assert.Equal(t, uint32(0), resultTx.DeliverTx.Code) // query sender - res, body := request(t, port, "GET", "/accounts/"+sendAddr, nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var m auth.BaseAccount - err := json.Unmarshal([]byte(body), &m) - require.Nil(t, err) - coins := m.Coins + acc = getAccount(t, sendAddr) + coins := acc.GetCoins() mycoins := coins[0] assert.Equal(t, coinDenom, mycoins.Denom) - assert.Equal(t, coinAmount-2, mycoins.Amount) + assert.Equal(t, initialBalance[0].Amount-1, mycoins.Amount) // TODO: query ibc egress packet state } @@ -339,9 +330,9 @@ func startTMAndLCD() (*nm.Node, net.Listener, error) { config.Consensus.SkipTimeoutCommit = false logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) - logger = log.NewFilter(logger, log.AllowError()) + // logger = log.NewFilter(logger, log.AllowError()) privValidatorFile := config.PrivValidatorFile() - privVal := tmtypes.LoadOrGenPrivValidatorFS(privValidatorFile) + privVal := pvm.LoadOrGenFilePV(privValidatorFile) dbs := map[string]dbm.DB{ "main": dbm.NewMemDB(), "acc": dbm.NewMemDB(), @@ -349,6 +340,7 @@ func startTMAndLCD() (*nm.Node, net.Listener, error) { "staking": dbm.NewMemDB(), } app := bapp.NewBasecoinApp(logger, dbs) + cdc = bapp.MakeCodec() // XXX genesisFile := config.GenesisFile() genDoc, err := tmtypes.GenesisDocFromFile(genesisFile) @@ -372,8 +364,6 @@ func startTMAndLCD() (*nm.Node, net.Listener, error) { } genDoc.AppStateJSON = stateBytes - cdc := wire.NewCodec() - // LCD listen address port = fmt.Sprintf("%d", 17377) // XXX listenAddr := fmt.Sprintf("tcp://localhost:%s", port) // XXX @@ -386,7 +376,7 @@ func startTMAndLCD() (*nm.Node, net.Listener, error) { if err != nil { return nil, nil, err } - lcd, err := startLCD(cdc, logger, listenAddr) + lcd, err := startLCD(logger, listenAddr) if err != nil { return nil, nil, err } @@ -425,7 +415,7 @@ func startTM(cfg *tmcfg.Config, logger log.Logger, genDoc *tmtypes.GenesisDoc, p } // start the LCD. note this blocks! -func startLCD(cdc *wire.Codec, logger log.Logger, listenAddr string) (net.Listener, error) { +func startLCD(logger log.Logger, listenAddr string) (net.Listener, error) { handler := createHandler(cdc) return tmrpc.StartHTTPServer(listenAddr, handler, logger) } @@ -447,6 +437,16 @@ func request(t *testing.T, port, method, path string, payload []byte) (*http.Res return res, string(output) } +func getAccount(t *testing.T, sendAddr string) sdk.Account { + // get the account to get the sequence + res, body := request(t, port, "GET", "/accounts/"+sendAddr, nil) + require.Equal(t, http.StatusOK, res.StatusCode, body) + var acc sdk.Account + err := cdc.UnmarshalJSON([]byte(body), &acc) + require.Nil(t, err) + return acc +} + func doSend(t *testing.T, port, seed string) (receiveAddr string, resultTx ctypes.ResultBroadcastTxCommit) { // create receive address @@ -455,20 +455,15 @@ func doSend(t *testing.T, port, seed string) (receiveAddr string, resultTx ctype require.Nil(t, err) receiveAddr = receiveInfo.PubKey.Address().String() - // get the account to get the sequence - res, body := request(t, port, "GET", "/accounts/"+sendAddr, nil) - // require.Equal(t, http.StatusOK, res.StatusCode, body) - acc := auth.BaseAccount{} - err = json.Unmarshal([]byte(body), &acc) - require.Nil(t, err) - sequence := acc.Sequence + acc := getAccount(t, sendAddr) + sequence := acc.GetSequence() // send jsonStr := []byte(fmt.Sprintf(`{ "name":"%s", "password":"%s", "sequence":%d, "amount":[{ "denom": "%s", "amount": 1 }] }`, name, password, sequence, coinDenom)) - res, body = request(t, port, "POST", "/accounts/"+receiveAddr+"/send", jsonStr) + res, body := request(t, port, "POST", "/accounts/"+receiveAddr+"/send", jsonStr) require.Equal(t, http.StatusOK, res.StatusCode, body) - err = json.Unmarshal([]byte(body), &resultTx) + err = cdc.UnmarshalJSON([]byte(body), &resultTx) require.Nil(t, err) return receiveAddr, resultTx @@ -483,19 +478,15 @@ func doIBCTransfer(t *testing.T, port, seed string) (resultTx ctypes.ResultBroad receiveAddr := receiveInfo.PubKey.Address().String() // get the account to get the sequence - res, body := request(t, port, "GET", "/accounts/"+sendAddr, nil) - // require.Equal(t, http.StatusOK, res.StatusCode, body) - acc := auth.BaseAccount{} - err = json.Unmarshal([]byte(body), &acc) - require.Nil(t, err) - sequence := acc.Sequence + acc := getAccount(t, sendAddr) + sequence := acc.GetSequence() // send jsonStr := []byte(fmt.Sprintf(`{ "name":"%s", "password":"%s", "sequence":%d, "amount":[{ "denom": "%s", "amount": 1 }] }`, name, password, sequence, coinDenom)) - res, body = request(t, port, "POST", "/ibc/testchain/"+receiveAddr+"/send", jsonStr) + res, body := request(t, port, "POST", "/ibc/testchain/"+receiveAddr+"/send", jsonStr) require.Equal(t, http.StatusOK, res.StatusCode, body) - err = json.Unmarshal([]byte(body), &resultTx) + err = cdc.UnmarshalJSON([]byte(body), &resultTx) require.Nil(t, err) return resultTx @@ -517,7 +508,7 @@ func waitForHeight(height int64) { } res.Body.Close() - err = json.Unmarshal([]byte(body), &resultBlock) + err = cdc.UnmarshalJSON([]byte(body), &resultBlock) if err != nil { fmt.Println("RES", res) fmt.Println("BODY", string(body)) @@ -537,8 +528,6 @@ func waitForStart() { for { time.Sleep(time.Second) - var resultBlock ctypes.ResultBlock - url := fmt.Sprintf("http://localhost:%v%v", port, "/blocks/latest") res, err := http.Get(url) if err != nil { @@ -557,7 +546,8 @@ func waitForStart() { } res.Body.Close() - err = json.Unmarshal([]byte(body), &resultBlock) + resultBlock := new(ctypes.ResultBlock) + err = cdc.UnmarshalJSON([]byte(body), &resultBlock) if err != nil { fmt.Println("RES", res) fmt.Println("BODY", string(body)) diff --git a/client/lcd/wire.go b/client/lcd/wire.go new file mode 100644 index 000000000000..f146e102ed00 --- /dev/null +++ b/client/lcd/wire.go @@ -0,0 +1,12 @@ +package lcd + +import ( + amino "github.com/tendermint/go-amino" + ctypes "github.com/tendermint/tendermint/rpc/core/types" +) + +var cdc = amino.NewCodec() + +func init() { + ctypes.RegisterAmino(cdc) +} diff --git a/client/rpc/block.go b/client/rpc/block.go index f42a15bc2e98..6333befde912 100644 --- a/client/rpc/block.go +++ b/client/rpc/block.go @@ -1,7 +1,6 @@ package rpc import ( - "encoding/json" "fmt" "net/http" "strconv" @@ -49,7 +48,7 @@ func getBlock(height *int64) ([]byte, error) { // TODO move maarshalling into cmd/rest functions // output, err := tmwire.MarshalJSON(res) - output, err := json.MarshalIndent(res, "", " ") + output, err := cdc.MarshalJSON(res) if err != nil { return nil, err } diff --git a/client/rpc/status.go b/client/rpc/status.go index 8ea8a5ad6aef..13325761ef98 100644 --- a/client/rpc/status.go +++ b/client/rpc/status.go @@ -1,13 +1,11 @@ package rpc import ( - "encoding/json" "fmt" "net/http" "strconv" "github.com/spf13/cobra" - wire "github.com/tendermint/go-wire" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" @@ -41,8 +39,8 @@ func printNodeStatus(cmd *cobra.Command, args []string) error { return err } - output, err := wire.MarshalJSON(status) - // output, err := json.MarshalIndent(res, " ", "") + output, err := cdc.MarshalJSON(status) + // output, err := cdc.MarshalJSONIndent(res, " ", "") if err != nil { return err } @@ -62,7 +60,7 @@ func NodeInfoRequestHandler(w http.ResponseWriter, r *http.Request) { } nodeInfo := status.NodeInfo - output, err := json.MarshalIndent(nodeInfo, "", " ") + output, err := cdc.MarshalJSON(nodeInfo) if err != nil { w.WriteHeader(500) w.Write([]byte(err.Error())) diff --git a/client/rpc/validators.go b/client/rpc/validators.go index 9bf1505dbf24..cdaf3be939e3 100644 --- a/client/rpc/validators.go +++ b/client/rpc/validators.go @@ -1,7 +1,6 @@ package rpc import ( - "encoding/json" "fmt" "net/http" "strconv" @@ -37,7 +36,7 @@ func GetValidators(height *int64) ([]byte, error) { return nil, err } - output, err := json.MarshalIndent(res, "", " ") + output, err := cdc.MarshalJSON(res) if err != nil { return nil, err } diff --git a/client/rpc/wire.go b/client/rpc/wire.go new file mode 100644 index 000000000000..841366fef16b --- /dev/null +++ b/client/rpc/wire.go @@ -0,0 +1,12 @@ +package rpc + +import ( + amino "github.com/tendermint/go-amino" + ctypes "github.com/tendermint/tendermint/rpc/core/types" +) + +var cdc = amino.NewCodec() + +func init() { + ctypes.RegisterAmino(cdc) +} diff --git a/docs/apps.md b/docs/apps.md index 76434791c2dd..29fb905cba51 100644 --- a/docs/apps.md +++ b/docs/apps.md @@ -40,7 +40,7 @@ Basecoin implements a `BaseApp` state machine using the `x/auth` and `x/bank` ex which define how transaction signers are authenticated and how coins are transferred. It should also use `x/ibc` and probably a simple staking extension. -Basecoin and the native `x` extensions use go-wire for all serialization needs, +Basecoin and the native `x` extensions use go-amino for all serialization needs, including for transactions and accounts. ## Your Cosmos App @@ -62,7 +62,7 @@ Ethermint is a new implementation of `BaseApp` that does not depend on Basecoin. Instead of `cosmos-sdk/x/` it has its own `ethermint/x` based on `go-ethereum`. Ethermint uses a Patricia store for its accounts, and an IAVL store for IBC. -It has `x/ante`, which is quite similar to Basecoin's but uses RLP instead of go-wire. +It has `x/ante`, which is quite similar to Basecoin's but uses RLP instead of go-amino. Instead of `x/bank`, it has `x/eth`, which defines the single Ethereum transaction type and all the semantics of the Ethereum state machine. diff --git a/docs/guide.md b/docs/guide.md index 5c31d2e27165..12a9b534cb3b 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -168,8 +168,8 @@ into a `Tx`: type TxDecoder func(txBytes []byte) (Tx, error) ``` -In `Basecoin`, we use the Tendermint wire format and the `go-wire` library for -encoding and decoding all message types. The `go-wire` library has the nice +In `Basecoin`, we use the Tendermint wire format and the `go-amino` library for +encoding and decoding all message types. The `go-amino` library has the nice property that it can unmarshal into interface types, but it requires the relevant types to be registered ahead of type. Registration happens on a `Codec` object, so as not to taint the global name space. @@ -186,7 +186,7 @@ cdc.RegisterConcrete(bank.IssueMsg{}, "cosmos-sdk/IssueMsg", nil) Note how each concrete type is given a name - these name determine the type's unique "prefix bytes" during encoding. A registered type will always use the same prefix-bytes, regardless of what interface it is satisfying. For more -details, see the [go-wire documentation](https://github.com/tendermint/go-wire/blob/develop). +details, see the [go-amino documentation](https://github.com/tendermint/go-amino/blob/develop). ## MultiStore diff --git a/docs/sdk/glossary.rst b/docs/sdk/glossary.rst index 1480e7b38cd1..faf682da4590 100644 --- a/docs/sdk/glossary.rst +++ b/docs/sdk/glossary.rst @@ -18,8 +18,7 @@ store), and it must have a deterministic action. The transaction is the main piece of one request. We currently make heavy use of -`go-wire `__ and -`data `__ to +`go-amino `__ to provide binary and json encodings and decodings for ``struct`` or interface\ ``objects. Here, encoding and decoding operations are designed to operate with interfaces nested any amount times (like an onion!). There is one public``\ TxMapper\` in the basecoin root package, and all modules can register their own @@ -162,13 +161,13 @@ also implements the ``Handler`` interface. We then register a list of modules with the dispatcher. Every module has a unique ``Name()``, which is used for isolating its state space. We use this same name for routing transactions. Each transaction implementation must be registed with -go-wire via ``TxMapper``, so we just look at the registered name of this +go-amino via ``TxMapper``, so we just look at the registered name of this transaction, which should be of the form ``/xxx``. The dispatcher grabs the appropriate module name from the tx name and routes it if the module is present. This all seems like a bit of magic, but really we're just making use of -go-wire magic that we are already using, rather than add another layer. +go-amino magic that we are already using, rather than add another layer. For all the transactions to be properly routed, the only thing you need to remember is to use the following pattern: diff --git a/docs/sdk/overview.rst b/docs/sdk/overview.rst index 9e79dd04ff7c..1356d7dc1db7 100644 --- a/docs/sdk/overview.rst +++ b/docs/sdk/overview.rst @@ -278,8 +278,8 @@ into a ``Tx``: type TxDecoder func(txBytes []byte) (Tx, error) -In ``Basecoin``, we use the Tendermint wire format and the ``go-wire`` library for -encoding and decoding all message types. The ``go-wire`` library has the nice +In ``Basecoin``, we use the Tendermint wire format and the ``go-amino`` library for +encoding and decoding all message types. The ``go-amino`` library has the nice property that it can unmarshal into interface types, but it requires the relevant types to be registered ahead of type. Registration happens on a ``Codec`` object, so as not to taint the global name space. @@ -296,7 +296,7 @@ types: Note how each concrete type is given a name - these name determine the type's unique "prefix bytes" during encoding. A registered type will always use the same prefix-bytes, regardless of what interface it is satisfying. For more -details, see the `go-wire documentation `__. +details, see the `go-amino documentation `__. MultiStore diff --git a/examples/basecoin/app/app.go b/examples/basecoin/app/app.go index caae1684660c..15a4f1f193db 100644 --- a/examples/basecoin/app/app.go +++ b/examples/basecoin/app/app.go @@ -4,7 +4,6 @@ import ( "encoding/json" abci "github.com/tendermint/abci/types" - oldwire "github.com/tendermint/go-wire" cmn "github.com/tendermint/tmlibs/common" dbm "github.com/tendermint/tmlibs/db" "github.com/tendermint/tmlibs/log" @@ -40,23 +39,28 @@ type BasecoinApp struct { } func NewBasecoinApp(logger log.Logger, dbs map[string]dbm.DB) *BasecoinApp { - // create your application object + + // Create app-level codec for txs and accounts. + var cdc = MakeCodec() + + // Create your application object. var app = &BasecoinApp{ BaseApp: bam.NewBaseApp(appName, logger, dbs["main"]), - cdc: MakeCodec(), + cdc: cdc, capKeyMainStore: sdk.NewKVStoreKey("main"), capKeyAccountStore: sdk.NewKVStoreKey("acc"), capKeyIBCStore: sdk.NewKVStoreKey("ibc"), capKeyStakingStore: sdk.NewKVStoreKey("stake"), } - // define the accountMapper - app.accountMapper = auth.NewAccountMapperSealed( + // Define the accountMapper. + app.accountMapper = auth.NewAccountMapper( + cdc, app.capKeyMainStore, // target store &types.AppAccount{}, // prototype - ) + ).Seal() - // add handlers + // Add handlers. coinKeeper := bank.NewCoinKeeper(app.accountMapper) ibcMapper := ibc.NewIBCMapper(app.cdc, app.capKeyIBCStore) stakeKeeper := simplestake.NewKeeper(app.capKeyStakingStore, coinKeeper) @@ -65,7 +69,7 @@ func NewBasecoinApp(logger log.Logger, dbs map[string]dbm.DB) *BasecoinApp { AddRoute("ibc", ibc.NewHandler(ibcMapper, coinKeeper)). AddRoute("simplestake", simplestake.NewHandler(stakeKeeper)) - // initialize BaseApp + // Initialize BaseApp. app.SetTxDecoder(app.txDecoder) app.SetInitChainer(app.initChainer) app.MountStoreWithDB(app.capKeyMainStore, sdk.StoreTypeIAVL, dbs["main"]) @@ -83,42 +87,30 @@ func NewBasecoinApp(logger log.Logger, dbs map[string]dbm.DB) *BasecoinApp { return app } -// custom tx codec -// TODO: use new go-wire +// Custom tx codec func MakeCodec() *wire.Codec { - const msgTypeSend = 0x1 - const msgTypeIssue = 0x2 - const msgTypeQuiz = 0x3 - const msgTypeSetTrend = 0x4 - const msgTypeIBCTransferMsg = 0x5 - const msgTypeIBCReceiveMsg = 0x6 - const msgTypeBondMsg = 0x7 - const msgTypeUnbondMsg = 0x8 - var _ = oldwire.RegisterInterface( - struct{ sdk.Msg }{}, - oldwire.ConcreteType{bank.SendMsg{}, msgTypeSend}, - oldwire.ConcreteType{bank.IssueMsg{}, msgTypeIssue}, - oldwire.ConcreteType{ibc.IBCTransferMsg{}, msgTypeIBCTransferMsg}, - oldwire.ConcreteType{ibc.IBCReceiveMsg{}, msgTypeIBCReceiveMsg}, - oldwire.ConcreteType{simplestake.BondMsg{}, msgTypeBondMsg}, - oldwire.ConcreteType{simplestake.UnbondMsg{}, msgTypeUnbondMsg}, - ) - - const accTypeApp = 0x1 - var _ = oldwire.RegisterInterface( - struct{ sdk.Account }{}, - oldwire.ConcreteType{&types.AppAccount{}, accTypeApp}, - ) - cdc := wire.NewCodec() - - // cdc.RegisterInterface((*sdk.Msg)(nil), nil) - // bank.RegisterWire(cdc) // Register bank.[SendMsg,IssueMsg] types. - // crypto.RegisterWire(cdc) // Register crypto.[PubKey,PrivKey,Signature] types. - // ibc.RegisterWire(cdc) // Register ibc.[IBCTransferMsg, IBCReceiveMsg] types. + var cdc = wire.NewCodec() + + // Register Msgs + cdc.RegisterInterface((*sdk.Msg)(nil), nil) + cdc.RegisterConcrete(bank.SendMsg{}, "basecoin/Send", nil) + cdc.RegisterConcrete(bank.IssueMsg{}, "basecoin/Issue", nil) + cdc.RegisterConcrete(ibc.IBCTransferMsg{}, "basecoin/IBCTransferMsg", nil) + cdc.RegisterConcrete(ibc.IBCReceiveMsg{}, "basecoin/IBCReceiveMsg", nil) + cdc.RegisterConcrete(simplestake.BondMsg{}, "basecoin/BondMsg", nil) + cdc.RegisterConcrete(simplestake.UnbondMsg{}, "basecoin/UnbondMsg", nil) + + // Register AppAccount + cdc.RegisterInterface((*sdk.Account)(nil), nil) + cdc.RegisterConcrete(&types.AppAccount{}, "basecoin/Account", nil) + + // Register crypto. + wire.RegisterCrypto(cdc) + return cdc } -// custom logic for transaction decoding +// Custom logic for transaction decoding func (app *BasecoinApp) txDecoder(txBytes []byte) (sdk.Tx, sdk.Error) { var tx = sdk.StdTx{} @@ -127,7 +119,7 @@ func (app *BasecoinApp) txDecoder(txBytes []byte) (sdk.Tx, sdk.Error) { } // StdTx.Msg is an interface. The concrete types - // are registered by MakeTxCodec in bank.RegisterWire. + // are registered by MakeTxCodec in bank.RegisterAmino. err := app.cdc.UnmarshalBinary(txBytes, &tx) if err != nil { return nil, sdk.ErrTxDecode("").TraceCause(err, "") @@ -135,7 +127,7 @@ func (app *BasecoinApp) txDecoder(txBytes []byte) (sdk.Tx, sdk.Error) { return tx, nil } -// custom logic for basecoin initialization +// Custom logic for basecoin initialization func (app *BasecoinApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { stateJSON := req.AppStateBytes diff --git a/examples/basecoin/app/app_test.go b/examples/basecoin/app/app_test.go index 65aff3af99fc..41c1a6f17112 100644 --- a/examples/basecoin/app/app_test.go +++ b/examples/basecoin/app/app_test.go @@ -349,10 +349,9 @@ func TestQuizMsg(t *testing.T) { // Construct genesis state // Construct some genesis bytes to reflect basecoin/types/AppAccount - coins := sdk.Coins{} baseAcc := auth.BaseAccount{ Address: addr1, - Coins: coins, + Coins: nil, } acc1 := &types.AppAccount{baseAcc, "foobart"} diff --git a/examples/basecoin/types/account.go b/examples/basecoin/types/account.go index 35b37c7b2f4f..b9b735a27fcd 100644 --- a/examples/basecoin/types/account.go +++ b/examples/basecoin/types/account.go @@ -12,7 +12,7 @@ var _ sdk.Account = (*AppAccount)(nil) // extending auth.BaseAccount with custom fields. // // This is compatible with the stock auth.AccountStore, since -// auth.AccountStore uses the flexible go-wire library. +// auth.AccountStore uses the flexible go-amino library. type AppAccount struct { auth.BaseAccount Name string `json:"name"` diff --git a/examples/democoin/app/app.go b/examples/democoin/app/app.go index 2ee79bd5bf47..ad6fd7865d52 100644 --- a/examples/democoin/app/app.go +++ b/examples/democoin/app/app.go @@ -4,7 +4,6 @@ import ( "encoding/json" abci "github.com/tendermint/abci/types" - oldwire "github.com/tendermint/go-wire" cmn "github.com/tendermint/tmlibs/common" dbm "github.com/tendermint/tmlibs/db" "github.com/tendermint/tmlibs/log" @@ -44,10 +43,14 @@ type DemocoinApp struct { } func NewDemocoinApp(logger log.Logger, dbs map[string]dbm.DB) *DemocoinApp { - // create your application object + + // Create app-level codec for txs and accounts. + var cdc = MakeCodec() + + // Create your application object. var app = &DemocoinApp{ BaseApp: bam.NewBaseApp(appName, logger, dbs["main"]), - cdc: MakeCodec(), + cdc: cdc, capKeyMainStore: sdk.NewKVStoreKey("main"), capKeyAccountStore: sdk.NewKVStoreKey("acc"), capKeyPowStore: sdk.NewKVStoreKey("pow"), @@ -55,13 +58,14 @@ func NewDemocoinApp(logger log.Logger, dbs map[string]dbm.DB) *DemocoinApp { capKeyStakingStore: sdk.NewKVStoreKey("stake"), } - // define the accountMapper - app.accountMapper = auth.NewAccountMapperSealed( + // Define the accountMapper. + app.accountMapper = auth.NewAccountMapper( + cdc, app.capKeyMainStore, // target store &types.AppAccount{}, // prototype - ) + ).Seal() - // add handlers + // Add handlers. coinKeeper := bank.NewCoinKeeper(app.accountMapper) coolKeeper := cool.NewKeeper(app.capKeyMainStore, coinKeeper) powKeeper := pow.NewKeeper(app.capKeyPowStore, pow.NewPowConfig("pow", int64(1)), coinKeeper) @@ -75,7 +79,7 @@ func NewDemocoinApp(logger log.Logger, dbs map[string]dbm.DB) *DemocoinApp { AddRoute("ibc", ibc.NewHandler(ibcMapper, coinKeeper)). AddRoute("simplestake", simplestake.NewHandler(stakeKeeper)) - // initialize BaseApp + // Initialize BaseApp. app.SetTxDecoder(app.txDecoder) app.SetInitChainer(app.initChainerFn(coolKeeper, powKeeper)) app.MountStoreWithDB(app.capKeyMainStore, sdk.StoreTypeIAVL, dbs["main"]) @@ -95,41 +99,28 @@ func NewDemocoinApp(logger log.Logger, dbs map[string]dbm.DB) *DemocoinApp { } // custom tx codec -// TODO: use new go-wire func MakeCodec() *wire.Codec { - const msgTypeSend = 0x1 - const msgTypeIssue = 0x2 - const msgTypeQuiz = 0x3 - const msgTypeSetTrend = 0x4 - const msgTypeMine = 0x5 - const msgTypeIBCTransferMsg = 0x6 - const msgTypeIBCReceiveMsg = 0x7 - const msgTypeBondMsg = 0x8 - const msgTypeUnbondMsg = 0x9 - var _ = oldwire.RegisterInterface( - struct{ sdk.Msg }{}, - oldwire.ConcreteType{bank.SendMsg{}, msgTypeSend}, - oldwire.ConcreteType{bank.IssueMsg{}, msgTypeIssue}, - oldwire.ConcreteType{cool.QuizMsg{}, msgTypeQuiz}, - oldwire.ConcreteType{cool.SetTrendMsg{}, msgTypeSetTrend}, - oldwire.ConcreteType{pow.MineMsg{}, msgTypeMine}, - oldwire.ConcreteType{ibc.IBCTransferMsg{}, msgTypeIBCTransferMsg}, - oldwire.ConcreteType{ibc.IBCReceiveMsg{}, msgTypeIBCReceiveMsg}, - oldwire.ConcreteType{simplestake.BondMsg{}, msgTypeBondMsg}, - oldwire.ConcreteType{simplestake.UnbondMsg{}, msgTypeUnbondMsg}, - ) - - const accTypeApp = 0x1 - var _ = oldwire.RegisterInterface( - struct{ sdk.Account }{}, - oldwire.ConcreteType{&types.AppAccount{}, accTypeApp}, - ) - cdc := wire.NewCodec() - - // cdc.RegisterInterface((*sdk.Msg)(nil), nil) - // bank.RegisterWire(cdc) // Register bank.[SendMsg,IssueMsg] types. - // crypto.RegisterWire(cdc) // Register crypto.[PubKey,PrivKey,Signature] types. - // ibc.RegisterWire(cdc) // Register ibc.[IBCTransferMsg, IBCReceiveMsg] types. + var cdc = wire.NewCodec() + + // Register Msgs + cdc.RegisterInterface((*sdk.Msg)(nil), nil) + cdc.RegisterConcrete(bank.SendMsg{}, "democoin/Send", nil) + cdc.RegisterConcrete(bank.IssueMsg{}, "democoin/Issue", nil) + cdc.RegisterConcrete(cool.QuizMsg{}, "democoin/Quiz", nil) + cdc.RegisterConcrete(cool.SetTrendMsg{}, "democoin/SetTrend", nil) + cdc.RegisterConcrete(pow.MineMsg{}, "democoin/Mine", nil) + cdc.RegisterConcrete(ibc.IBCTransferMsg{}, "democoin/IBCTransferMsg", nil) + cdc.RegisterConcrete(ibc.IBCReceiveMsg{}, "democoin/IBCReceiveMsg", nil) + cdc.RegisterConcrete(simplestake.BondMsg{}, "democoin/BondMsg", nil) + cdc.RegisterConcrete(simplestake.UnbondMsg{}, "democoin/UnbondMsg", nil) + + // Register AppAccount + cdc.RegisterInterface((*sdk.Account)(nil), nil) + cdc.RegisterConcrete(&types.AppAccount{}, "democoin/Account", nil) + + // Register crypto. + wire.RegisterCrypto(cdc) + return cdc } diff --git a/examples/democoin/app/app_test.go b/examples/democoin/app/app_test.go index 1cc56bd6bf7f..7047f5d28b99 100644 --- a/examples/democoin/app/app_test.go +++ b/examples/democoin/app/app_test.go @@ -106,8 +106,7 @@ func TestMsgs(t *testing.T) { }}) // just marshal/unmarshal! - cdc := MakeCodec() - txBytes, err := cdc.MarshalBinary(tx) + txBytes, err := bapp.cdc.MarshalBinary(tx) require.NoError(t, err, "i: %v", i) // Run a Check @@ -245,10 +244,9 @@ func TestMineMsg(t *testing.T) { // Construct genesis state // Construct some genesis bytes to reflect democoin/types/AppAccount - coins := sdk.Coins{} baseAcc := auth.BaseAccount{ Address: addr1, - Coins: coins, + Coins: nil, } acc1 := &types.AppAccount{baseAcc, "foobart"} @@ -297,10 +295,9 @@ func TestQuizMsg(t *testing.T) { // Construct genesis state // Construct some genesis bytes to reflect democoin/types/AppAccount - coins := sdk.Coins{} baseAcc := auth.BaseAccount{ Address: addr1, - Coins: coins, + Coins: nil, } acc1 := &types.AppAccount{baseAcc, "foobart"} diff --git a/examples/democoin/types/account.go b/examples/democoin/types/account.go index b5d5a0d0343b..d90525f1dd4e 100644 --- a/examples/democoin/types/account.go +++ b/examples/democoin/types/account.go @@ -15,7 +15,7 @@ var _ sdk.Account = (*AppAccount)(nil) // extending auth.BaseAccount with custom fields. // // This is compatible with the stock auth.AccountStore, since -// auth.AccountStore uses the flexible go-wire library. +// auth.AccountStore uses the flexible go-amino library. type AppAccount struct { auth.BaseAccount Name string `json:"name"` diff --git a/examples/democoin/x/pow/handler_test.go b/examples/democoin/x/pow/handler_test.go index 2de2853713ba..a05932780164 100644 --- a/examples/democoin/x/pow/handler_test.go +++ b/examples/democoin/x/pow/handler_test.go @@ -8,14 +8,17 @@ import ( abci "github.com/tendermint/abci/types" sdk "github.com/cosmos/cosmos-sdk/types" + wire "github.com/cosmos/cosmos-sdk/wire" auth "github.com/cosmos/cosmos-sdk/x/auth" bank "github.com/cosmos/cosmos-sdk/x/bank" ) func TestPowHandler(t *testing.T) { ms, capKey := setupMultiStore() + cdc := wire.NewCodec() + auth.RegisterBaseAccount(cdc) - am := auth.NewAccountMapper(capKey, &auth.BaseAccount{}) + am := auth.NewAccountMapper(cdc, capKey, &auth.BaseAccount{}) ctx := sdk.NewContext(ms, abci.Header{}, false, nil) config := NewPowConfig("pow", int64(1)) ck := bank.NewCoinKeeper(am) diff --git a/examples/democoin/x/pow/keeper_test.go b/examples/democoin/x/pow/keeper_test.go index 6e0d526496e9..cb3492a862f5 100644 --- a/examples/democoin/x/pow/keeper_test.go +++ b/examples/democoin/x/pow/keeper_test.go @@ -10,6 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/store" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/wire" auth "github.com/cosmos/cosmos-sdk/x/auth" bank "github.com/cosmos/cosmos-sdk/x/bank" ) @@ -27,8 +28,10 @@ func setupMultiStore() (sdk.MultiStore, *sdk.KVStoreKey) { func TestPowKeeperGetSet(t *testing.T) { ms, capKey := setupMultiStore() + cdc := wire.NewCodec() + auth.RegisterBaseAccount(cdc) - am := auth.NewAccountMapper(capKey, &auth.BaseAccount{}) + am := auth.NewAccountMapper(cdc, capKey, &auth.BaseAccount{}) ctx := sdk.NewContext(ms, abci.Header{}, false, nil) config := NewPowConfig("pow", int64(1)) ck := bank.NewCoinKeeper(am) diff --git a/server/init.go b/server/init.go index 688bc38e3791..09d97338e895 100644 --- a/server/init.go +++ b/server/init.go @@ -13,6 +13,7 @@ import ( cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/p2p" tmtypes "github.com/tendermint/tendermint/types" + pvm "github.com/tendermint/tendermint/types/priv_validator" cmn "github.com/tendermint/tmlibs/common" dbm "github.com/tendermint/tmlibs/db" ) @@ -109,12 +110,12 @@ func (c initCmd) run(cmd *cobra.Command, args []string) error { func (c initCmd) initTendermintFiles(config *cfg.Config, info *testnetInformation) error { // private validator privValFile := config.PrivValidatorFile() - var privValidator *tmtypes.PrivValidatorFS + var privValidator *pvm.FilePV if cmn.FileExists(privValFile) { - privValidator = tmtypes.LoadPrivValidatorFS(privValFile) + privValidator = pvm.LoadFilePV(privValFile) c.context.Logger.Info("Found private validator", "path", privValFile) } else { - privValidator = tmtypes.GenPrivValidatorFS(privValFile) + privValidator = pvm.GenFilePV(privValFile) privValidator.Save() c.context.Logger.Info("Generated private validator", "path", privValFile) } diff --git a/server/start.go b/server/start.go index 6aee5d316cfd..a4ff9852e5b3 100644 --- a/server/start.go +++ b/server/start.go @@ -11,7 +11,7 @@ import ( tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands" "github.com/tendermint/tendermint/node" "github.com/tendermint/tendermint/proxy" - "github.com/tendermint/tendermint/types" + pvm "github.com/tendermint/tendermint/types/priv_validator" cmn "github.com/tendermint/tmlibs/common" "github.com/tendermint/tmlibs/log" ) @@ -95,7 +95,7 @@ func (s startCmd) startInProcess() error { // Create & start tendermint node n, err := node.NewNode(cfg, - types.LoadOrGenPrivValidatorFS(cfg.PrivValidatorFile()), + pvm.LoadOrGenFilePV(cfg.PrivValidatorFile()), proxy.NewLocalClientCreator(app), node.DefaultGenesisDocProviderFunc(cfg), node.DefaultDBProvider, diff --git a/server/tm_cmds.go b/server/tm_cmds.go index 3e0aefa941b2..2a9b680e56fa 100644 --- a/server/tm_cmds.go +++ b/server/tm_cmds.go @@ -5,10 +5,9 @@ import ( "github.com/spf13/cobra" - "github.com/tendermint/go-wire/data" tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands" "github.com/tendermint/tendermint/p2p" - "github.com/tendermint/tendermint/types" + pvm "github.com/tendermint/tendermint/types/priv_validator" ) // ShowNodeIDCmd - ported from Tendermint, dump node ID to stdout @@ -53,8 +52,8 @@ type showValidator struct { func (s showValidator) run(cmd *cobra.Command, args []string) error { cfg := s.context.Config - privValidator := types.LoadOrGenPrivValidatorFS(cfg.PrivValidatorFile()) - pubKeyJSONBytes, err := data.ToJSON(privValidator.PubKey) + privValidator := pvm.LoadOrGenFilePV(cfg.PrivValidatorFile()) + pubKeyJSONBytes, err := cdc.MarshalJSON(privValidator.PubKey) if err != nil { return err } diff --git a/server/wire.go b/server/wire.go new file mode 100644 index 000000000000..261e7cfe1ec3 --- /dev/null +++ b/server/wire.go @@ -0,0 +1,12 @@ +package server + +import ( + "github.com/cosmos/cosmos-sdk/wire" +) + +var cdc *wire.Codec + +func init() { + cdc = wire.NewCodec() + wire.RegisterCrypto(cdc) +} diff --git a/types/coin.go b/types/coin.go index ab7d863c15f1..8a80bee22638 100644 --- a/types/coin.go +++ b/types/coin.go @@ -110,7 +110,7 @@ func (coins Coins) IsValid() bool { // Plus combines two sets of coins // CONTRACT: Plus will never return Coins where one Coin has a 0 amount. func (coins Coins) Plus(coinsB Coins) Coins { - sum := []Coin{} + sum := ([]Coin)(nil) indexA, indexB := 0, 0 lenA, lenB := len(coins), len(coinsB) for { diff --git a/types/coin_test.go b/types/coin_test.go index 19929e8c7922..eb9f5e087efd 100644 --- a/types/coin_test.go +++ b/types/coin_test.go @@ -201,8 +201,8 @@ func TestPlusCoins(t *testing.T) { }{ {Coins{{"A", 1}, {"B", 1}}, Coins{{"A", 1}, {"B", 1}}, Coins{{"A", 2}, {"B", 2}}}, {Coins{{"A", 0}, {"B", 1}}, Coins{{"A", 0}, {"B", 0}}, Coins{{"B", 1}}}, - {Coins{{"A", 0}, {"B", 0}}, Coins{{"A", 0}, {"B", 0}}, Coins{}}, - {Coins{{"A", 1}, {"B", 0}}, Coins{{"A", -1}, {"B", 0}}, Coins{}}, + {Coins{{"A", 0}, {"B", 0}}, Coins{{"A", 0}, {"B", 0}}, Coins(nil)}, + {Coins{{"A", 1}, {"B", 0}}, Coins{{"A", -1}, {"B", 0}}, Coins(nil)}, {Coins{{"A", -1}, {"B", 0}}, Coins{{"A", 0}, {"B", 0}}, Coins{{"A", -1}}}, } diff --git a/version/version.go b/version/version.go index fccd2bbb1459..e5e3b6611c12 100644 --- a/version/version.go +++ b/version/version.go @@ -6,10 +6,10 @@ package version // TODO improve const Maj = "0" -const Min = "14" +const Min = "15" const Fix = "0" -const Version = "0.14.0" +const Version = "0.15.0-rc1" // GitCommit set by build flags var GitCommit = "" diff --git a/wire/wire.go b/wire/wire.go index e53d5e195b2e..9c366b6fb869 100644 --- a/wire/wire.go +++ b/wire/wire.go @@ -1,55 +1,17 @@ package wire import ( - "bytes" - "reflect" - - "github.com/tendermint/go-wire" + "github.com/tendermint/go-amino" + "github.com/tendermint/go-crypto" ) -type Codec struct{} +type Codec = amino.Codec func NewCodec() *Codec { - return &Codec{} -} - -func (cdc *Codec) MarshalBinary(o interface{}) ([]byte, error) { - w, n, err := new(bytes.Buffer), new(int), new(error) - wire.WriteBinary(o, w, n, err) - return w.Bytes(), *err -} - -func (cdc *Codec) UnmarshalBinary(bz []byte, o interface{}) error { - r, n, err := bytes.NewBuffer(bz), new(int), new(error) - - rv := reflect.ValueOf(o) - if rv.Kind() == reflect.Ptr { - wire.ReadBinaryPtr(o, r, len(bz), n, err) - } else { - wire.ReadBinary(o, r, len(bz), n, err) - } - return *err + cdc := amino.NewCodec() + return cdc } -func (cdc *Codec) MarshalJSON(o interface{}) ([]byte, error) { - w, n, err := new(bytes.Buffer), new(int), new(error) - wire.WriteJSON(o, w, n, err) - return w.Bytes(), *err -} - -func (cdc *Codec) UnmarshalJSON(bz []byte, o interface{}) (err error) { - - rv := reflect.ValueOf(o) - if rv.Kind() == reflect.Ptr { - wire.ReadJSONPtr(o, bz, &err) - } else { - wire.ReadJSON(o, bz, &err) - } - return err -} - -//---------------------------------------------- - func RegisterCrypto(cdc *Codec) { - // TODO + crypto.RegisterAmino(cdc) } diff --git a/x/auth/ante.go b/x/auth/ante.go index a5ab83bcbefa..6801769a45c7 100644 --- a/x/auth/ante.go +++ b/x/auth/ante.go @@ -118,9 +118,9 @@ func processSig( // If pubkey is not known for account, // set it from the StdSignature. pubKey := acc.GetPubKey() - if pubKey.Empty() { + if pubKey == nil { pubKey = sig.PubKey - if pubKey.Empty() { + if pubKey == nil { return nil, sdk.ErrInvalidPubKey("PubKey not found").Result() } if !bytes.Equal(pubKey.Address(), addr) { diff --git a/x/auth/ante_test.go b/x/auth/ante_test.go index fd94145dde0b..2f90701e65b3 100644 --- a/x/auth/ante_test.go +++ b/x/auth/ante_test.go @@ -3,11 +3,13 @@ package auth import ( "testing" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" abci "github.com/tendermint/abci/types" crypto "github.com/tendermint/go-crypto" + + sdk "github.com/cosmos/cosmos-sdk/types" + wire "github.com/cosmos/cosmos-sdk/wire" ) func newTestMsg(addrs ...sdk.Address) *sdk.TestMsg { @@ -31,7 +33,7 @@ func newCoins() sdk.Coins { func privAndAddr() (crypto.PrivKey, sdk.Address) { priv := crypto.GenPrivKeyEd25519() addr := priv.PubKey().Address() - return priv.Wrap(), addr + return priv, addr } // run the tx through the anteHandler and ensure its valid @@ -67,7 +69,9 @@ func newTestTxWithSignBytes(msg sdk.Msg, privs []crypto.PrivKey, seqs []int64, f func TestAnteHandlerSigErrors(t *testing.T) { // setup ms, capKey := setupMultiStore() - mapper := NewAccountMapper(capKey, &BaseAccount{}) + cdc := wire.NewCodec() + RegisterBaseAccount(cdc) + mapper := NewAccountMapper(cdc, capKey, &BaseAccount{}) anteHandler := NewAnteHandler(mapper) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, nil) @@ -106,7 +110,9 @@ func TestAnteHandlerSigErrors(t *testing.T) { func TestAnteHandlerSequences(t *testing.T) { // setup ms, capKey := setupMultiStore() - mapper := NewAccountMapper(capKey, &BaseAccount{}) + cdc := wire.NewCodec() + RegisterBaseAccount(cdc) + mapper := NewAccountMapper(cdc, capKey, &BaseAccount{}) anteHandler := NewAnteHandler(mapper) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, nil) @@ -170,7 +176,9 @@ func TestAnteHandlerSequences(t *testing.T) { func TestAnteHandlerFees(t *testing.T) { // setup ms, capKey := setupMultiStore() - mapper := NewAccountMapper(capKey, &BaseAccount{}) + cdc := wire.NewCodec() + RegisterBaseAccount(cdc) + mapper := NewAccountMapper(cdc, capKey, &BaseAccount{}) anteHandler := NewAnteHandler(mapper) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, nil) @@ -205,7 +213,9 @@ func TestAnteHandlerFees(t *testing.T) { func TestAnteHandlerBadSignBytes(t *testing.T) { // setup ms, capKey := setupMultiStore() - mapper := NewAccountMapper(capKey, &BaseAccount{}) + cdc := wire.NewCodec() + RegisterBaseAccount(cdc) + mapper := NewAccountMapper(cdc, capKey, &BaseAccount{}) anteHandler := NewAnteHandler(mapper) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, nil) @@ -278,7 +288,9 @@ func TestAnteHandlerBadSignBytes(t *testing.T) { func TestAnteHandlerSetPubKey(t *testing.T) { // setup ms, capKey := setupMultiStore() - mapper := NewAccountMapper(capKey, &BaseAccount{}) + cdc := wire.NewCodec() + RegisterBaseAccount(cdc) + mapper := NewAccountMapper(cdc, capKey, &BaseAccount{}) anteHandler := NewAnteHandler(mapper) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, nil) @@ -310,16 +322,16 @@ func TestAnteHandlerSetPubKey(t *testing.T) { msg = newTestMsg(addr2) tx = newTestTx(ctx, msg, privs, seqs, fee) sigs := tx.GetSignatures() - sigs[0].PubKey = crypto.PubKey{} + sigs[0].PubKey = nil checkInvalidTx(t, anteHandler, ctx, tx, sdk.CodeInvalidPubKey) acc2 = mapper.GetAccount(ctx, addr2) - assert.True(t, acc2.GetPubKey().Empty()) + assert.Nil(t, acc2.GetPubKey()) // test invalid signature and public key tx = newTestTx(ctx, msg, privs, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, sdk.CodeInvalidPubKey) acc2 = mapper.GetAccount(ctx, addr2) - assert.True(t, acc2.GetPubKey().Empty()) + assert.Nil(t, acc2.GetPubKey()) } diff --git a/x/auth/baseaccount.go b/x/auth/baseaccount.go index 23123f9949c9..a5f33c81d190 100644 --- a/x/auth/baseaccount.go +++ b/x/auth/baseaccount.go @@ -61,7 +61,7 @@ func (acc BaseAccount) GetPubKey() crypto.PubKey { // Implements sdk.Account. func (acc *BaseAccount) SetPubKey(pubKey crypto.PubKey) error { - if !acc.PubKey.Empty() { + if acc.PubKey != nil { return errors.New("cannot override BaseAccount pubkey") } acc.PubKey = pubKey @@ -93,7 +93,9 @@ func (acc *BaseAccount) SetSequence(seq int64) error { //---------------------------------------- // Wire -func RegisterWireBaseAccount(cdc *wire.Codec) { - // Register crypto.[PubKey,PrivKey,Signature] types. +// Most users shouldn't use this, but this comes handy for tests. +func RegisterBaseAccount(cdc *wire.Codec) { + cdc.RegisterInterface((*sdk.Account)(nil), nil) + cdc.RegisterConcrete(&BaseAccount{}, "cosmos-sdk/BaseAccount", nil) wire.RegisterCrypto(cdc) } diff --git a/x/auth/baseaccount_test.go b/x/auth/baseaccount_test.go index b2f5b54ae28a..24b3e3673ce6 100644 --- a/x/auth/baseaccount_test.go +++ b/x/auth/baseaccount_test.go @@ -15,7 +15,7 @@ func keyPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.Address) { key := crypto.GenPrivKeyEd25519() pub := key.PubKey() addr := pub.Address() - return key.Wrap(), pub, addr + return key, pub, addr } func TestBaseAccountAddressPubKey(t *testing.T) { @@ -25,7 +25,7 @@ func TestBaseAccountAddressPubKey(t *testing.T) { // check the address (set) and pubkey (not set) assert.EqualValues(t, addr1, acc.GetAddress()) - assert.EqualValues(t, crypto.PubKey{}, acc.GetPubKey()) + assert.EqualValues(t, nil, acc.GetPubKey()) // can't override address err := acc.SetAddress(addr2) diff --git a/x/auth/commands/account.go b/x/auth/commands/account.go index b87b957699e8..734285202ce1 100644 --- a/x/auth/commands/account.go +++ b/x/auth/commands/account.go @@ -11,7 +11,6 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/wire" - "github.com/cosmos/cosmos-sdk/x/auth" ) // GetAccountCmd for the auth.BaseAccount type @@ -20,9 +19,9 @@ func GetAccountCmdDefault(storeName string, cdc *wire.Codec) *cobra.Command { } func GetAccountDecoder(cdc *wire.Codec) sdk.AccountDecoder { - return func(accBytes []byte) (sdk.Account, error) { - acct := new(auth.BaseAccount) - err := cdc.UnmarshalBinary(accBytes, &acct) + return func(accBytes []byte) (acct sdk.Account, err error) { + // acct := new(auth.BaseAccount) + err = cdc.UnmarshalBinaryBare(accBytes, &acct) if err != nil { panic(err) } diff --git a/x/auth/mapper.go b/x/auth/mapper.go index 13fe9a844593..7bc23aee1021 100644 --- a/x/auth/mapper.go +++ b/x/auth/mapper.go @@ -1,12 +1,9 @@ package auth import ( - "bytes" "fmt" "reflect" - oldwire "github.com/tendermint/go-wire" - sdk "github.com/cosmos/cosmos-sdk/types" wire "github.com/cosmos/cosmos-sdk/wire" ) @@ -16,7 +13,7 @@ var _ sdk.AccountMapper = (*sealedAccountMapper)(nil) // Implements sdk.AccountMapper. // This AccountMapper encodes/decodes accounts using the -// go-wire (binary) encoding/decoding library. +// go-amino (binary) encoding/decoding library. type accountMapper struct { // The (unexposed) key used to access the store from the Context. @@ -30,9 +27,8 @@ type accountMapper struct { } // NewAccountMapper returns a new sdk.AccountMapper that -// uses go-wire to (binary) encode and decode concrete sdk.Accounts. -func NewAccountMapper(key sdk.StoreKey, proto sdk.Account) accountMapper { - cdc := wire.NewCodec() +// uses go-amino to (binary) encode and decode concrete sdk.Accounts. +func NewAccountMapper(cdc *wire.Codec, key sdk.StoreKey, proto sdk.Account) accountMapper { return accountMapper{ key: key, proto: proto, @@ -40,21 +36,7 @@ func NewAccountMapper(key sdk.StoreKey, proto sdk.Account) accountMapper { } } -// Create and return a sealed account mapper -func NewAccountMapperSealed(key sdk.StoreKey, proto sdk.Account) sealedAccountMapper { - cdc := wire.NewCodec() - am := accountMapper{ - key: key, - proto: proto, - cdc: cdc, - } - RegisterWireBaseAccount(cdc) - - // make accountMapper's WireCodec() inaccessible, return - return am.Seal() -} - -// Returns the go-wire codec. You may need to register interfaces +// Returns the go-amino codec. You may need to register interfaces // and concrete types here, if your app's sdk.Account // implementation includes interface fields. // NOTE: It is not secure to expose the codec, so check out @@ -103,7 +85,7 @@ type sealedAccountMapper struct { } // There's no way for external modules to mutate the -// sam.accountMapper.ctx from here, even with reflection. +// sam.accountMapper.cdc from here, even with reflection. func (sam sealedAccountMapper) WireCodec() *wire.Codec { panic("accountMapper is sealed") } @@ -111,22 +93,6 @@ func (sam sealedAccountMapper) WireCodec() *wire.Codec { //---------------------------------------- // misc. -// NOTE: currently unused -func (am accountMapper) clonePrototypePtr() interface{} { - protoRt := reflect.TypeOf(am.proto) - if protoRt.Kind() == reflect.Ptr { - protoErt := protoRt.Elem() - if protoErt.Kind() != reflect.Struct { - panic("accountMapper requires a struct proto sdk.Account, or a pointer to one") - } - protoRv := reflect.New(protoErt) - return protoRv.Interface() - } else { - protoRv := reflect.New(protoRt) - return protoRv.Interface() - } -} - // Creates a new struct (or pointer to struct) from am.proto. func (am accountMapper) clonePrototype() sdk.Account { protoRt := reflect.TypeOf(am.proto) @@ -152,34 +118,17 @@ func (am accountMapper) clonePrototype() sdk.Account { } func (am accountMapper) encodeAccount(acc sdk.Account) []byte { - bz, err := am.cdc.MarshalBinary(acc) + bz, err := am.cdc.MarshalBinaryBare(acc) if err != nil { panic(err) } return bz } -func (am accountMapper) decodeAccount(bz []byte) sdk.Account { - // ... old go-wire ... - r, n, err := bytes.NewBuffer(bz), new(int), new(error) - accI := oldwire.ReadBinary(struct{ sdk.Account }{}, r, len(bz), n, err) - if *err != nil { - panic(*err) +func (am accountMapper) decodeAccount(bz []byte) (acc sdk.Account) { + err := am.cdc.UnmarshalBinaryBare(bz, &acc) + if err != nil { + panic(err) } - - acc := accI.(struct{ sdk.Account }).Account - return acc - - /* - accPtr := am.clonePrototypePtr() - err := am.cdc.UnmarshalBinary(bz, accPtr) - if err != nil { - panic(err) - } - if reflect.ValueOf(am.proto).Kind() == reflect.Ptr { - return reflect.ValueOf(accPtr).Interface().(sdk.Account) - } else { - return reflect.ValueOf(accPtr).Elem().Interface().(sdk.Account) - } - */ + return } diff --git a/x/auth/mapper_test.go b/x/auth/mapper_test.go index 4ac96c381055..030207db2c1d 100644 --- a/x/auth/mapper_test.go +++ b/x/auth/mapper_test.go @@ -6,12 +6,11 @@ import ( "github.com/stretchr/testify/assert" abci "github.com/tendermint/abci/types" - crypto "github.com/tendermint/go-crypto" - oldwire "github.com/tendermint/go-wire" dbm "github.com/tendermint/tmlibs/db" "github.com/cosmos/cosmos-sdk/store" sdk "github.com/cosmos/cosmos-sdk/types" + wire "github.com/cosmos/cosmos-sdk/wire" ) func setupMultiStore() (sdk.MultiStore, *sdk.KVStoreKey) { @@ -20,22 +19,17 @@ func setupMultiStore() (sdk.MultiStore, *sdk.KVStoreKey) { ms := store.NewCommitMultiStore(db) ms.MountStoreWithDB(capKey, sdk.StoreTypeIAVL, db) ms.LoadLatestVersion() - - // wire registration while we're at it ... TODO - var _ = oldwire.RegisterInterface( - struct{ sdk.Account }{}, - oldwire.ConcreteType{&BaseAccount{}, 0x1}, - ) - return ms, capKey } func TestAccountMapperGetSet(t *testing.T) { ms, capKey := setupMultiStore() + cdc := wire.NewCodec() + RegisterBaseAccount(cdc) // make context and mapper ctx := sdk.NewContext(ms, abci.Header{}, false, nil) - mapper := NewAccountMapper(capKey, &BaseAccount{}) + mapper := NewAccountMapper(cdc, capKey, &BaseAccount{}) addr := sdk.Address([]byte("some-address")) @@ -47,7 +41,7 @@ func TestAccountMapperGetSet(t *testing.T) { acc = mapper.NewAccountWithAddress(ctx, addr) assert.NotNil(t, acc) assert.Equal(t, addr, acc.GetAddress()) - assert.EqualValues(t, crypto.PubKey{}, acc.GetPubKey()) + assert.EqualValues(t, nil, acc.GetPubKey()) assert.EqualValues(t, 0, acc.GetSequence()) // NewAccount doesn't call Set, so it's still nil @@ -66,16 +60,14 @@ func TestAccountMapperGetSet(t *testing.T) { func TestAccountMapperSealed(t *testing.T) { _, capKey := setupMultiStore() + cdc := wire.NewCodec() + RegisterBaseAccount(cdc) // normal mapper exposes the wire codec - mapper := NewAccountMapper(capKey, &BaseAccount{}) + mapper := NewAccountMapper(cdc, capKey, &BaseAccount{}) assert.NotNil(t, mapper.WireCodec()) // seal mapper, should panic when we try to get the codec mapperSealed := mapper.Seal() assert.Panics(t, func() { mapperSealed.WireCodec() }) - - // another way to get a sealed mapper - mapperSealed = NewAccountMapperSealed(capKey, &BaseAccount{}) - assert.Panics(t, func() { mapperSealed.WireCodec() }) } diff --git a/x/auth/rest/query.go b/x/auth/rest/query.go index 5430a77ff249..c401fe47f5e7 100644 --- a/x/auth/rest/query.go +++ b/x/auth/rest/query.go @@ -2,7 +2,6 @@ package rest import ( "encoding/hex" - "encoding/json" "fmt" "net/http" @@ -56,7 +55,7 @@ func QueryAccountRequestHandler(storeName string, cdc *wire.Codec, decoder sdk.A } // print out whole account - output, err := json.MarshalIndent(account, "", " ") + output, err := cdc.MarshalJSON(account) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Could't marshall query result. Error: %s", err.Error()))) diff --git a/x/ibc/ibc_test.go b/x/ibc/ibc_test.go index 1e04311479a9..db172a5caf9d 100644 --- a/x/ibc/ibc_test.go +++ b/x/ibc/ibc_test.go @@ -7,7 +7,6 @@ import ( abci "github.com/tendermint/abci/types" "github.com/tendermint/go-crypto" - oldwire "github.com/tendermint/go-wire" dbm "github.com/tendermint/tmlibs/db" "github.com/cosmos/cosmos-sdk/store" @@ -33,39 +32,25 @@ func newAddress() crypto.Address { } func getCoins(ck bank.CoinKeeper, ctx sdk.Context, addr crypto.Address) (sdk.Coins, sdk.Error) { - zero := sdk.Coins{} + zero := sdk.Coins(nil) return ck.AddCoins(ctx, addr, zero) } -// custom tx codec -// TODO: use new go-wire func makeCodec() *wire.Codec { + var cdc = wire.NewCodec() + + // Register Msgs + cdc.RegisterInterface((*sdk.Msg)(nil), nil) + cdc.RegisterConcrete(bank.SendMsg{}, "test/ibc/Send", nil) + cdc.RegisterConcrete(bank.IssueMsg{}, "test/ibc/Issue", nil) + cdc.RegisterConcrete(IBCTransferMsg{}, "test/ibc/IBCTransferMsg", nil) + cdc.RegisterConcrete(IBCReceiveMsg{}, "test/ibc/IBCReceiveMsg", nil) + + // Register AppAccount + cdc.RegisterInterface((*sdk.Account)(nil), nil) + cdc.RegisterConcrete(&auth.BaseAccount{}, "test/ibc/Account", nil) + wire.RegisterCrypto(cdc) - const msgTypeSend = 0x1 - const msgTypeIssue = 0x2 - const msgTypeQuiz = 0x3 - const msgTypeSetTrend = 0x4 - const msgTypeIBCTransferMsg = 0x5 - const msgTypeIBCReceiveMsg = 0x6 - var _ = oldwire.RegisterInterface( - struct{ sdk.Msg }{}, - oldwire.ConcreteType{bank.SendMsg{}, msgTypeSend}, - oldwire.ConcreteType{bank.IssueMsg{}, msgTypeIssue}, - oldwire.ConcreteType{IBCTransferMsg{}, msgTypeIBCTransferMsg}, - oldwire.ConcreteType{IBCReceiveMsg{}, msgTypeIBCReceiveMsg}, - ) - - const accTypeApp = 0x1 - var _ = oldwire.RegisterInterface( - struct{ sdk.Account }{}, - oldwire.ConcreteType{&auth.BaseAccount{}, accTypeApp}, - ) - cdc := wire.NewCodec() - - // cdc.RegisterInterface((*sdk.Msg)(nil), nil) - // bank.RegisterWire(cdc) // Register bank.[SendMsg,IssueMsg] types. - // crypto.RegisterWire(cdc) // Register crypto.[PubKey,PrivKey,Signature] types. - // ibc.RegisterWire(cdc) // Register ibc.[IBCTransferMsg, IBCReceiveMsg] types. return cdc } @@ -75,13 +60,13 @@ func TestIBC(t *testing.T) { key := sdk.NewKVStoreKey("ibc") ctx := defaultContext(key) - am := auth.NewAccountMapper(key, &auth.BaseAccount{}) + am := auth.NewAccountMapper(cdc, key, &auth.BaseAccount{}) ck := bank.NewCoinKeeper(am) src := newAddress() dest := newAddress() chainid := "ibcchain" - zero := sdk.Coins{} + zero := sdk.Coins(nil) mycoins := sdk.Coins{sdk.Coin{"mycoin", 10}} coins, err := ck.AddCoins(ctx, src, mycoins) diff --git a/x/ibc/rest/transfer.go b/x/ibc/rest/transfer.go index fceac55677fe..1317730e7f29 100644 --- a/x/ibc/rest/transfer.go +++ b/x/ibc/rest/transfer.go @@ -2,7 +2,6 @@ package rest import ( "encoding/hex" - "encoding/json" "io/ioutil" "net/http" @@ -43,7 +42,7 @@ func TransferRequestHandler(cdc *wire.Codec, kb keys.Keybase) func(http.Response w.Write([]byte(err.Error())) return } - err = json.Unmarshal(body, &m) + err = cdc.UnmarshalJSON(body, &m) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(err.Error())) @@ -86,7 +85,7 @@ func TransferRequestHandler(cdc *wire.Codec, kb keys.Keybase) func(http.Response return } - output, err := json.MarshalIndent(res, "", " ") + output, err := cdc.MarshalJSON(res) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) diff --git a/x/simplestake/commands/commands.go b/x/simplestake/commands/commands.go index ce89801d8822..b2a057beeda5 100644 --- a/x/simplestake/commands/commands.go +++ b/x/simplestake/commands/commands.go @@ -77,7 +77,7 @@ func (co commander) bondTxCmd(cmd *cobra.Command, args []string) error { var pubKeyEd crypto.PubKeyEd25519 copy(pubKeyEd[:], rawPubKey) - msg := simplestake.NewBondMsg(from, stake, pubKeyEd.Wrap()) + msg := simplestake.NewBondMsg(from, stake, pubKeyEd) return co.sendMsg(msg) } diff --git a/x/simplestake/keeper.go b/x/simplestake/keeper.go index e5892f3e2370..7dcdbc20fdf2 100644 --- a/x/simplestake/keeper.go +++ b/x/simplestake/keeper.go @@ -21,6 +21,7 @@ type Keeper struct { func NewKeeper(key sdk.StoreKey, coinKeeper bank.CoinKeeper) Keeper { cdc := wire.NewCodec() + wire.RegisterCrypto(cdc) return Keeper{ key: key, cdc: cdc, @@ -83,7 +84,7 @@ func (k Keeper) Bond(ctx sdk.Context, addr sdk.Address, pubKey crypto.PubKey, st func (k Keeper) Unbond(ctx sdk.Context, addr sdk.Address) (crypto.PubKey, int64, sdk.Error) { bi := k.getBondInfo(ctx, addr) if bi.isEmpty() { - return crypto.PubKey{}, 0, ErrInvalidUnbond() + return nil, 0, ErrInvalidUnbond() } k.deleteBondInfo(ctx, addr) @@ -121,7 +122,7 @@ func (k Keeper) bondWithoutCoins(ctx sdk.Context, addr sdk.Address, pubKey crypt func (k Keeper) unbondWithoutCoins(ctx sdk.Context, addr sdk.Address) (crypto.PubKey, int64, sdk.Error) { bi := k.getBondInfo(ctx, addr) if bi.isEmpty() { - return crypto.PubKey{}, 0, ErrInvalidUnbond() + return nil, 0, ErrInvalidUnbond() } k.deleteBondInfo(ctx, addr) diff --git a/x/simplestake/keeper_test.go b/x/simplestake/keeper_test.go index 9f26155901fa..7f9a120b9624 100644 --- a/x/simplestake/keeper_test.go +++ b/x/simplestake/keeper_test.go @@ -13,6 +13,7 @@ import ( "github.com/cosmos/cosmos-sdk/store" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank" ) @@ -55,10 +56,12 @@ func TestKeeperGetSet(t *testing.T) { func TestBonding(t *testing.T) { ms, authKey, capKey := setupMultiStore() + cdc := wire.NewCodec() + auth.RegisterBaseAccount(cdc) ctx := sdk.NewContext(ms, abci.Header{}, false, nil) - accountMapper := auth.NewAccountMapper(authKey, &auth.BaseAccount{}) + accountMapper := auth.NewAccountMapper(cdc, authKey, &auth.BaseAccount{}) coinKeeper := bank.NewCoinKeeper(accountMapper) stakeKeeper := NewKeeper(capKey, coinKeeper) addr := sdk.Address([]byte("some-address")) diff --git a/x/simplestake/msgs.go b/x/simplestake/msgs.go index 2ab0e1bad2eb..9f41334842e2 100644 --- a/x/simplestake/msgs.go +++ b/x/simplestake/msgs.go @@ -34,7 +34,7 @@ func (msg BondMsg) ValidateBasic() sdk.Error { return ErrEmptyStake() } - if msg.PubKey.Empty() { + if msg.PubKey == nil { return sdk.ErrInvalidPubKey("BondMsg.PubKey must not be empty") } diff --git a/x/stake/commands/tx.go b/x/stake/commands/tx.go index d1dec6dce990..d1a399e19ce5 100644 --- a/x/stake/commands/tx.go +++ b/x/stake/commands/tx.go @@ -250,6 +250,6 @@ func GetPubKey(pubKeyStr string) (pk crypto.PubKey, err error) { } var pkEd crypto.PubKeyEd25519 copy(pkEd[:], pkBytes[:]) - pk = pkEd.Wrap() + pk = pkEd return } diff --git a/x/stake/test_common.go b/x/stake/test_common.go index 285364a5d93f..395a5bce0165 100644 --- a/x/stake/test_common.go +++ b/x/stake/test_common.go @@ -8,7 +8,6 @@ import ( abci "github.com/tendermint/abci/types" crypto "github.com/tendermint/go-crypto" - oldwire "github.com/tendermint/go-wire" dbm "github.com/tendermint/tmlibs/db" "github.com/cosmos/cosmos-sdk/store" @@ -84,36 +83,22 @@ func subspace(prefix []byte) (start, end []byte) { return prefix, end } -// custom tx codec -// TODO: use new go-wire func makeTestCodec() *wire.Codec { + var cdc = wire.NewCodec() + + // Register Msgs + cdc.RegisterInterface((*sdk.Msg)(nil), nil) + cdc.RegisterConcrete(bank.SendMsg{}, "test/stake/Send", nil) + cdc.RegisterConcrete(bank.IssueMsg{}, "test/stake/Issue", nil) + cdc.RegisterConcrete(MsgDeclareCandidacy{}, "test/stake/DeclareCandidacy", nil) + cdc.RegisterConcrete(MsgEditCandidacy{}, "test/stake/EditCandidacy", nil) + cdc.RegisterConcrete(MsgUnbond{}, "test/stake/Unbond", nil) + + // Register AppAccount + cdc.RegisterInterface((*sdk.Account)(nil), nil) + cdc.RegisterConcrete(&auth.BaseAccount{}, "test/stake/Account", nil) + wire.RegisterCrypto(cdc) - const msgTypeSend = 0x1 - const msgTypeIssue = 0x2 - const msgTypeDeclareCandidacy = 0x3 - const msgTypeEditCandidacy = 0x4 - const msgTypeDelegate = 0x5 - const msgTypeUnbond = 0x6 - var _ = oldwire.RegisterInterface( - struct{ sdk.Msg }{}, - oldwire.ConcreteType{bank.SendMsg{}, msgTypeSend}, - oldwire.ConcreteType{bank.IssueMsg{}, msgTypeIssue}, - oldwire.ConcreteType{MsgDeclareCandidacy{}, msgTypeDeclareCandidacy}, - oldwire.ConcreteType{MsgEditCandidacy{}, msgTypeEditCandidacy}, - oldwire.ConcreteType{MsgDelegate{}, msgTypeDelegate}, - oldwire.ConcreteType{MsgUnbond{}, msgTypeUnbond}, - ) - - const accTypeApp = 0x1 - var _ = oldwire.RegisterInterface( - struct{ sdk.Account }{}, - oldwire.ConcreteType{&auth.BaseAccount{}, accTypeApp}, - ) - cdc := wire.NewCodec() - - // cdc.RegisterInterface((*sdk.Msg)(nil), nil) - // bank.RegisterWire(cdc) // Register bank.[SendMsg,IssueMsg] types. - // crypto.RegisterWire(cdc) // Register crypto.[PubKey,PrivKey,Signature] types. return cdc } @@ -141,10 +126,11 @@ func createTestInput(t *testing.T, isCheckTx bool, initCoins int64) (sdk.Context ctx := sdk.NewContext(ms, abci.Header{ChainID: "foochainid"}, isCheckTx, nil) cdc := makeTestCodec() - accountMapper := auth.NewAccountMapperSealed( + accountMapper := auth.NewAccountMapper( + cdc, // amino codec keyMain, // target store &auth.BaseAccount{}, // prototype - ) + ).Seal() ck := bank.NewCoinKeeper(accountMapper) keeper := NewKeeper(ctx, cdc, keyStake, ck) keeper.setPool(ctx, initialPool()) @@ -168,7 +154,7 @@ func newPubKey(pk string) (res crypto.PubKey) { //res, err = crypto.PubKeyFromBytes(pkBytes) var pkEd crypto.PubKeyEd25519 copy(pkEd[:], pkBytes[:]) - return pkEd.Wrap() + return pkEd } // for incode address generation