Merge pull request #814 from cosmos/jae/aminoify

aminoification
This commit is contained in:
Ethan Buchman 2018-04-09 17:27:45 +03:00 committed by GitHub
commit 86fb891215
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
47 changed files with 325 additions and 419 deletions

View File

@ -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:

25
Gopkg.lock generated
View File

@ -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

View File

@ -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

View File

@ -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 {

View File

@ -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)
}
}
}

View File

@ -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))

12
client/lcd/wire.go Normal file
View File

@ -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)
}

View File

@ -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
}

View File

@ -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()))

View File

@ -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
}

12
client/rpc/wire.go Normal file
View File

@ -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)
}

View File

@ -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.

View File

@ -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

View File

@ -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 <https://github.com/tendermint/go-wire>`__ and
`data <https://github.com/tendermint/go-wire/tree/master/data>`__ to
`go-amino <https://github.com/tendermint/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 ``<module name>/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:

View File

@ -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 <https://github.com/tendermint/go-wire/tree/develop>`__.
details, see the `go-amino documentation <https://github.com/tendermint/go-amino/tree/develop>`__.
MultiStore

View File

@ -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},
)
var cdc = wire.NewCodec()
const accTypeApp = 0x1
var _ = oldwire.RegisterInterface(
struct{ sdk.Account }{},
oldwire.ConcreteType{&types.AppAccount{}, accTypeApp},
)
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)
// 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
}
// 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

View File

@ -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"}

View File

@ -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"`

View File

@ -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},
)
var cdc = wire.NewCodec()
const accTypeApp = 0x1
var _ = oldwire.RegisterInterface(
struct{ sdk.Account }{},
oldwire.ConcreteType{&types.AppAccount{}, accTypeApp},
)
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)
// 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
}

View File

@ -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"}

View File

@ -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"`

View File

@ -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)

View File

@ -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)

View File

@ -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)
}

View File

@ -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,

View File

@ -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
}

12
server/wire.go Normal file
View File

@ -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)
}

View File

@ -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 {

View File

@ -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}}},
}

View File

@ -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 = ""

View File

@ -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{}
cdc := amino.NewCodec()
return cdc
}
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
}
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)
}

View File

@ -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) {

View File

@ -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())
}

View File

@ -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)
}

View File

@ -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)

View File

@ -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)
}

View File

@ -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
}

View File

@ -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() })
}

View File

@ -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())))

View File

@ -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()
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},
)
// 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)
const accTypeApp = 0x1
var _ = oldwire.RegisterInterface(
struct{ sdk.Account }{},
oldwire.ConcreteType{&auth.BaseAccount{}, accTypeApp},
)
cdc := wire.NewCodec()
// Register AppAccount
cdc.RegisterInterface((*sdk.Account)(nil), nil)
cdc.RegisterConcrete(&auth.BaseAccount{}, "test/ibc/Account", nil)
wire.RegisterCrypto(cdc)
// 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)

View File

@ -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()))

View File

@ -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)
}

View File

@ -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)

View File

@ -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"))

View File

@ -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")
}

View File

@ -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
}

View File

@ -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()
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},
)
// 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)
const accTypeApp = 0x1
var _ = oldwire.RegisterInterface(
struct{ sdk.Account }{},
oldwire.ConcreteType{&auth.BaseAccount{}, accTypeApp},
)
cdc := wire.NewCodec()
// Register AppAccount
cdc.RegisterInterface((*sdk.Account)(nil), nil)
cdc.RegisterConcrete(&auth.BaseAccount{}, "test/stake/Account", nil)
wire.RegisterCrypto(cdc)
// 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