Merge branch 'develop' into cwgoes/a-random-walk-down-proof-of-stake

This commit is contained in:
Christopher Goes 2018-07-11 00:59:30 +02:00
commit a33229380b
138 changed files with 1616 additions and 1404 deletions

View File

@ -13,26 +13,22 @@ BREAKING CHANGES
* Default ports changed from 466xx to 266xx
* Amino JSON uses type names instead of prefix bytes
* ED25519 addresses are the first 20-bytes of the SHA256 of the raw 32-byte
pubkey
pubkey (Instead of RIPEMD160)
* go-crypto, abci, tmlibs have been merged into Tendermint
* The keys sub-module is now in the SDK
* Various other fixes
* [auth] Signers of a transaction now only sign over their own account and sequence number
* [auth] Removed MsgChangePubKey
* [auth] Removed MsgChangePubKey
* [auth] Removed SetPubKey from account mapper
* [auth] AltBytes renamed to Memo, now a string, max 100 characters, costs a bit of gas
* [baseapp] NewBaseApp now takes option functions as parameters
* [types] `GetMsg()` -> `GetMsgs()` as txs wrap many messages
* [types] Removed GetMemo from Tx (it is still on StdTx)
* [types] renamed rational.Evaluate to rational.Round{Int64, Int}
* [types] Renamed `sdk.Address` to `sdk.AccAddress`/`sdk.ValAddress`
* [types] `sdk.AccAddress`/`sdk.ValAddress` natively marshals to Bech32 in String, Sprintf (when used with `%s`), and MarshalJSON
* [keys] Keybase and Ledger support from go-crypto merged into the SDK in the `crypto` folder
* [cli] Rearranged commands under subcommands
* [x/gov] Gov module REST endpoints changed to be more RESTful
* [x/stake] Remove Tick and add EndBlocker
* [x/stake] Introduce concept of unbonding for delegations and validators
* `gaiacli stake unbond` replaced with `gaiacli stake begin-unbonding`
* Introduced:
* `gaiacli stake complete-unbonding`
* `gaiacli stake begin-redelegation`
* `gaiacli stake complete-redelegation`
* [x/slashing] Update slashing for unbonding period
* Slash according to power at time of infraction instead of power at
time of discovery
@ -40,25 +36,38 @@ BREAKING CHANGES
to an infraction, slash them proportional to their stake at the time
* Add REST endpoint to unrevoke a validator previously revoked for downtime
* Add REST endpoint to retrieve liveness signing information for a validator
* [types] renamed rational.Evaluate to rational.Round{Int64, Int}
* [x/stake] Remove Tick and add EndBlocker
* [x/stake] most index keys nolonger hold a value - inputs are rearranged to form the desired key
* [lcd] Switch key creation output to return bech32
* [x/stake] store-value for delegation, validator, ubd, and red do not hold duplicate information contained store-key
* [gaiad] genesis transactions now use bech32 addresses / pubkeys
* [x/stake] Introduce concept of unbonding for delegations and validators
* `gaiacli stake unbond` replaced with `gaiacli stake begin-unbonding`
* Introduced:
* `gaiacli stake complete-unbonding`
* `gaiacli stake begin-redelegation`
* `gaiacli stake complete-redelegation`
* [lcd] Switch key creation output to return bech32
* [lcd] Removed shorthand CLI flags (`a`, `c`, `n`, `o`)
* [gaiad] genesis transactions now use bech32 addresses / pubkeys
DEPRECATED
* [cli] Deprecate `--name` flag in commands that send txs, in favor of `--from`
* [cli] Deprecated `--name` flag in commands that send txs, in favor of `--from`
FEATURES
* [gaiacli] You can now attach a simple text-only memo to any transaction, with the `--memo` flag
* [lcd] Queried TXs now include the tx hash to identify each tx
* [mockapp] CompleteSetup() no longer takes a testing parameter
* [x/gov] Implemented MVP
* Supported proposal types: just binary (pass/fail) TextProposals for now
* Proposals need deposits to be votable; deposits are burned if proposal fails
* Delegators delegate votes to validator by default but can override (for their stake)
* Add benchmarks for signing and delivering a block with a single bank transaction
* [gaiacli] Ledger support added
- You can now use a Ledger with `gaiacli --ledger` for all key-related commands
- Ledger keys can be named and tracked locally in the key DB
* [gaiacli] You can now attach a simple text-only memo to any transaction, with the `--memo` flag
* [gaiacli] added the following flags for commands that post transactions to the chain:
* async -- send the tx without waiting for a tendermint response
* json -- return the output in json format for increased readability
* print-response -- return the tx response. (includes fields like gas cost)
* [lcd] Queried TXs now include the tx hash to identify each tx
* [mockapp] CompleteSetup() no longer takes a testing parameter
* [x/bank] Add benchmarks for signing and delivering a block with a single bank transaction
* Run with `cd x/bank && go test --bench=.`
* [tools] make get_tools installs tendermint's linter, and gometalinter
* [tools] Switch gometalinter to the stable version
@ -70,26 +79,22 @@ FEATURES
* ineffassign
* errcheck
* unparam
* [tools] Add `make format` command to automate fixing misspell and gofmt errors.
* gocyclo
* [tools] Added `make format` command to automate fixing misspell and gofmt errors.
* [server] Default config now creates a profiler at port 6060, and increase p2p send/recv rates
* [tests] Add WaitForNextNBlocksTM helper method
* [types] Switches internal representation of Int/Uint/Rat to use pointers
* [types] Added MinInt and MinUint functions
* [gaiad] `unsafe_reset_all` now resets addrbook.json
* [democoin] add x/oracle, x/assoc
* [gaiacli] Ledger support added
- You can now use a Ledger with `gaiacli --ledger` for all key-related commands
- Ledger keys can be named and tracked locally in the key DB
* [testing] created a randomized testing framework.
* [tests] created a randomized testing framework.
- Currently bank has limited functionality in the framework
- Auth has its invariants checked within the framework
* [gaiacli] added the following flags for commands that post transactions to the chain:
* async -- send the tx without waiting for a tendermint response
* json -- return the output in json format for increased readability
* print-response -- return the tx response. (includes fields like gas cost)
* [tests] Add WaitForNextNBlocksTM helper method
* [keys] New keys now have 24 word recovery keys, for heightened security
IMPROVEMENTS
* bank module uses go-wire codec instead of 'encoding/json'
* auth module uses go-wire codec instead of 'encoding/json'
* [x/bank] Now uses go-wire codec instead of 'encoding/json'
* [x/auth] Now uses go-wire codec instead of 'encoding/json'
* revised use of endblock and beginblock
* [stake] module reorganized to include `types` and `keeper` package
* [stake] keeper always loads the store (instead passing around which doesn't really boost efficiency)
@ -99,30 +104,36 @@ IMPROVEMENTS
* [keys] improve error message when deleting non-existent key
* [gaiacli] improve error messages on `send` and `account` commands
* added contributing guidelines
* [docs] Added commands for governance CLI on testnet README
BUG FIXES
* [x/slashing] \#1510 Unrevoked validators cannot un-revoke themselves
* [x/stake] \#1513 Validators slashed to zero power are unbonded and removed from the store
* [x/stake] \#1567 Validators decreased in power but not unbonded are now updated in Tendermint
* [x/stake] error strings lower case
* [x/stake] pool loose tokens now accounts for unbonding and unbonding tokens not associated with any validator
* [x/stake] fix revoke bytes ordering (was putting revoked candidates at the top of the list)
* [x/stake] bond count was counting revoked validators as bonded, fixed
* [gaia] Added self delegation for validators in the genesis creation
* [lcd] tests now don't depend on raw json text
* [stake] error strings lower case
* [stake] pool loose tokens now accounts for unbonding and unbonding tokens not associated with any validator
* \#1259 - fix bug where certain tests that could have a nil pointer in defer
* \#1052 - Make all now works
* Retry on HTTP request failure in CLI tests, add option to retry tests in Makefile
* Fixed bug where chain ID wasn't passed properly in x/bank REST handler, removed Viper hack from ante handler
* Fixed bug where `democli account` didn't decode the account data correctly
* \#1343 - fixed unnecessary parallelism in CI
* \#1367 - set ChainID in InitChain
* \#1353 - CLI: Show pool shares fractions in human-readable format
* \#1258 - printing big.rat's can no longer overflow int64
* \#872 - recovery phrases no longer all end in `abandon`
* \#887 - limit the size of rationals that can be passed in from user input
* \#1052 - Make all now works
* \#1258 - printing big.rat's can no longer overflow int64
* \#1259 - fix bug where certain tests that could have a nil pointer in defer
* \#1343 - fixed unnecessary parallelism in CI
* \#1353 - CLI: Show pool shares fractions in human-readable format
* \#1367 - set ChainID in InitChain
* \#1461 - CLI tests now no longer reset your local environment data
* \#1505 - `gaiacli stake validator` no longer panics if validator doesn't exist
* [x/stake] fix revoke bytes ordering (was putting revoked candidates at the top of the list)
* [x/stake] bond count was counting revoked validators as bonded, fixed
* \#1565 - fix cliff validator persisting when validator set shrinks from max
* \#1287 - prevent zero power validators at genesis
* [x/stake] fix bug when unbonding/redelegating using `--shares-percent`
* \#1010 - two validators can't bond with the same pubkey anymore
## 0.19.0

View File

@ -73,7 +73,8 @@ var _ abci.Application = (*BaseApp)(nil)
// Create and name new BaseApp
// NOTE: The db is used to store the version number for now.
func NewBaseApp(name string, cdc *wire.Codec, logger log.Logger, db dbm.DB) *BaseApp {
// Accepts variable number of option functions, which act on the BaseApp to set configuration choices
func NewBaseApp(name string, cdc *wire.Codec, logger log.Logger, db dbm.DB, options ...func(*BaseApp)) *BaseApp {
app := &BaseApp{
Logger: logger,
name: name,
@ -86,6 +87,9 @@ func NewBaseApp(name string, cdc *wire.Codec, logger log.Logger, db dbm.DB) *Bas
}
// Register the undefined & root codespaces, which should not be used by any modules
app.codespacer.RegisterOrPanic(sdk.CodespaceRoot)
for _, option := range options {
option(app)
}
return app
}
@ -204,36 +208,6 @@ func (app *BaseApp) initFromStore(mainKey sdk.StoreKey) error {
return errors.New("baseapp expects MultiStore with 'main' KVStore")
}
// XXX: Do we really need the header? What does it have that we want
// here that's not already in the CommitID ? If an app wants to have it,
// they can do so in their BeginBlocker. If we force it in baseapp,
// then either we force the AppHash to change with every block (since the header
// will be in the merkle store) or we can't write the state and the header to the
// db atomically without doing some surgery on the store interfaces ...
// if we've committed before, we expect <dbHeaderKey> to exist in the db
/*
var lastCommitID = app.cms.LastCommitID()
var header abci.Header
if !lastCommitID.IsZero() {
headerBytes := app.db.Get(dbHeaderKey)
if len(headerBytes) == 0 {
errStr := fmt.Sprintf("Version > 0 but missing key %s", dbHeaderKey)
return errors.New(errStr)
}
err := proto.Unmarshal(headerBytes, &header)
if err != nil {
return errors.Wrap(err, "failed to parse Header")
}
lastVersion := lastCommitID.Version
if header.Height != lastVersion {
errStr := fmt.Sprintf("expected db://%s.Height %v but got %v", dbHeaderKey, lastVersion, header.Height)
return errors.New(errStr)
}
}
*/
return nil
}
@ -324,16 +298,39 @@ func (app *BaseApp) FilterPeerByPubKey(info string) abci.ResponseQuery {
return abci.ResponseQuery{}
}
// Implements ABCI.
// Delegates to CommitMultiStore if it implements Queryable
func (app *BaseApp) Query(req abci.RequestQuery) (res abci.ResponseQuery) {
path := strings.Split(req.Path, "/")
func splitPath(requestPath string) (path []string) {
path = strings.Split(requestPath, "/")
// first element is empty string
if len(path) > 0 && path[0] == "" {
path = path[1:]
}
return path
}
// Implements ABCI.
// Delegates to CommitMultiStore if it implements Queryable
func (app *BaseApp) Query(req abci.RequestQuery) (res abci.ResponseQuery) {
path := splitPath(req.Path)
if len(path) == 0 {
msg := "no query path provided"
return sdk.ErrUnknownRequest(msg).QueryResult()
}
switch path[0] {
// "/app" prefix for special application queries
if len(path) >= 2 && path[0] == "app" {
case "app":
return handleQueryApp(app, path, req)
case "store":
return handleQueryStore(app, path, req)
case "p2p":
return handleQueryP2P(app, path, req)
}
msg := "unknown query path"
return sdk.ErrUnknownRequest(msg).QueryResult()
}
func handleQueryApp(app *BaseApp, path []string, req abci.RequestQuery) (res abci.ResponseQuery) {
if len(path) >= 2 {
var result sdk.Result
switch path[1] {
case "simulate":
@ -358,18 +355,24 @@ func (app *BaseApp) Query(req abci.RequestQuery) (res abci.ResponseQuery) {
Value: value,
}
}
msg := "Expected second parameter to be either simulate or version, neither was present"
return sdk.ErrUnknownRequest(msg).QueryResult()
}
func handleQueryStore(app *BaseApp, path []string, req abci.RequestQuery) (res abci.ResponseQuery) {
// "/store" prefix for store queries
if len(path) >= 1 && path[0] == "store" {
queryable, ok := app.cms.(sdk.Queryable)
if !ok {
msg := "multistore doesn't support queries"
return sdk.ErrUnknownRequest(msg).QueryResult()
}
req.Path = "/" + strings.Join(path[1:], "/")
return queryable.Query(req)
queryable, ok := app.cms.(sdk.Queryable)
if !ok {
msg := "multistore doesn't support queries"
return sdk.ErrUnknownRequest(msg).QueryResult()
}
req.Path = "/" + strings.Join(path[1:], "/")
return queryable.Query(req)
}
func handleQueryP2P(app *BaseApp, path []string, req abci.RequestQuery) (res abci.ResponseQuery) {
// "/p2p" prefix for p2p queries
if len(path) >= 4 && path[0] == "p2p" {
if len(path) >= 4 {
if path[1] == "filter" {
if path[2] == "addr" {
return app.FilterPeerByAddrPort(path[3])
@ -379,9 +382,13 @@ func (app *BaseApp) Query(req abci.RequestQuery) (res abci.ResponseQuery) {
// NOTE: this changed in tendermint and we didn't notice...
return app.FilterPeerByPubKey(path[3])
}
} else {
msg := "Expected second parameter to be filter"
return sdk.ErrUnknownRequest(msg).QueryResult()
}
}
msg := "unknown query path"
msg := "Expected path is p2p filter <addr|pubkey> <parameter>"
return sdk.ErrUnknownRequest(msg).QueryResult()
}
@ -457,52 +464,11 @@ func (app *BaseApp) DeliverTx(txBytes []byte) (res abci.ResponseDeliverTx) {
}
}
// nolint - Mostly for testing
func (app *BaseApp) Check(tx sdk.Tx) (result sdk.Result) {
return app.runTx(runTxModeCheck, nil, tx)
}
// nolint - full tx execution
func (app *BaseApp) Simulate(tx sdk.Tx) (result sdk.Result) {
return app.runTx(runTxModeSimulate, nil, tx)
}
// nolint
func (app *BaseApp) Deliver(tx sdk.Tx) (result sdk.Result) {
return app.runTx(runTxModeDeliver, nil, tx)
}
// txBytes may be nil in some cases, eg. in tests.
// Also, in the future we may support "internal" transactions.
func (app *BaseApp) runTx(mode runTxMode, txBytes []byte, tx sdk.Tx) (result sdk.Result) {
//NOTE: GasWanted should be returned by the AnteHandler.
// GasUsed is determined by the GasMeter.
// We need access to the context to get the gas meter so
// we initialize upfront
var gasWanted int64
ctx := app.getContextForAnte(mode, txBytes)
// Handle any panics.
defer func() {
if r := recover(); r != nil {
switch rType := r.(type) {
case sdk.ErrorOutOfGas:
log := fmt.Sprintf("out of gas in location: %v", rType.Descriptor)
result = sdk.ErrOutOfGas(log).Result()
default:
log := fmt.Sprintf("recovered: %v\nstack:\n%v", r, string(debug.Stack()))
result = sdk.ErrInternal(log).Result()
}
}
result.GasWanted = gasWanted
result.GasUsed = ctx.GasMeter().GasConsumed()
}()
// Get the Msg.
var msgs = tx.GetMsgs()
// Basic validator for msgs
func validateBasicTxMsgs(msgs []sdk.Msg) sdk.Error {
if msgs == nil || len(msgs) == 0 {
// TODO: probably shouldn't be ErrInternal. Maybe new ErrInvalidMessage, or ?
return sdk.ErrInternal("Tx.GetMsgs() must return at least one message in list").Result()
return sdk.ErrInternal("Tx.GetMsgs() must return at least one message in list")
}
for _, msg := range msgs {
@ -510,34 +476,32 @@ func (app *BaseApp) runTx(mode runTxMode, txBytes []byte, tx sdk.Tx) (result sdk
err := msg.ValidateBasic()
if err != nil {
err = err.WithDefaultCodespace(sdk.CodespaceRoot)
return err.Result()
return err
}
}
// Run the ante handler.
if app.anteHandler != nil {
newCtx, anteResult, abort := app.anteHandler(ctx, tx)
if abort {
return anteResult
}
if !newCtx.IsZero() {
ctx = newCtx
}
gasWanted = anteResult.GasWanted
}
return nil
}
// Get the correct cache
var msCache sdk.CacheMultiStore
func (app *BaseApp) getContextForAnte(mode runTxMode, txBytes []byte) (ctx sdk.Context) {
// Get the context
if mode == runTxModeCheck || mode == runTxModeSimulate {
// CacheWrap app.checkState.ms in case it fails.
msCache = app.checkState.CacheMultiStore()
ctx = ctx.WithMultiStore(msCache)
ctx = app.checkState.ctx.WithTxBytes(txBytes)
} else {
// CacheWrap app.deliverState.ms in case it fails.
msCache = app.deliverState.CacheMultiStore()
ctx = ctx.WithMultiStore(msCache)
ctx = app.deliverState.ctx.WithTxBytes(txBytes)
ctx = ctx.WithSigningValidators(app.signedValidators)
}
// Simulate a DeliverTx for gas calculation
if mode == runTxModeSimulate {
ctx = ctx.WithIsCheckTx(false)
}
return
}
// Iterates through msgs and executes them
func (app *BaseApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg) (result sdk.Result) {
// accumulate results
logs := make([]string, 0, len(msgs))
var data []byte // NOTE: we just append them all (?!)
@ -573,39 +537,84 @@ func (app *BaseApp) runTx(mode runTxMode, txBytes []byte, tx sdk.Tx) (result sdk
// Set the final gas values.
result = sdk.Result{
Code: code,
Data: data,
Log: strings.Join(logs, "\n"),
GasWanted: gasWanted,
GasUsed: ctx.GasMeter().GasConsumed(),
Code: code,
Data: data,
Log: strings.Join(logs, "\n"),
GasUsed: ctx.GasMeter().GasConsumed(),
// TODO: FeeAmount/FeeDenom
Tags: tags,
}
return result
}
// Returns deliverState if app is in runTxModeDeliver, otherwhise returns checkstate
func getState(app *BaseApp, mode runTxMode) *state {
if mode == runTxModeCheck || mode == runTxModeSimulate {
return app.checkState
}
return app.deliverState
}
// txBytes may be nil in some cases, eg. in tests.
// Also, in the future we may support "internal" transactions.
func (app *BaseApp) runTx(mode runTxMode, txBytes []byte, tx sdk.Tx) (result sdk.Result) {
//NOTE: GasWanted should be returned by the AnteHandler.
// GasUsed is determined by the GasMeter.
// We need access to the context to get the gas meter so
// we initialize upfront
var gasWanted int64
ctx := app.getContextForAnte(mode, txBytes)
// Handle any panics.
defer func() {
if r := recover(); r != nil {
switch rType := r.(type) {
case sdk.ErrorOutOfGas:
log := fmt.Sprintf("out of gas in location: %v", rType.Descriptor)
result = sdk.ErrOutOfGas(log).Result()
default:
log := fmt.Sprintf("recovered: %v\nstack:\n%v", r, string(debug.Stack()))
result = sdk.ErrInternal(log).Result()
}
}
result.GasWanted = gasWanted
result.GasUsed = ctx.GasMeter().GasConsumed()
}()
// Get the Msg.
var msgs = tx.GetMsgs()
err := validateBasicTxMsgs(msgs)
if err != nil {
return err.Result()
}
// Run the ante handler.
if app.anteHandler != nil {
newCtx, anteResult, abort := app.anteHandler(ctx, tx)
if abort {
return anteResult
}
if !newCtx.IsZero() {
ctx = newCtx
}
gasWanted = result.GasWanted
}
// CacheWrap the state in case it fails.
msCache := getState(app, mode).CacheMultiStore()
ctx = ctx.WithMultiStore(msCache)
result = app.runMsgs(ctx, msgs)
result.GasWanted = gasWanted
// Only update state if all messages pass and we're not in a simulation.
if result.IsOK() && mode != runTxModeSimulate {
msCache.Write()
}
return result
}
func (app *BaseApp) getContextForAnte(mode runTxMode, txBytes []byte) sdk.Context {
var ctx sdk.Context
// Get the context.
if mode == runTxModeCheck || mode == runTxModeSimulate {
ctx = app.checkState.ctx.WithTxBytes(txBytes)
} else {
ctx = app.deliverState.ctx.WithTxBytes(txBytes)
ctx = ctx.WithSigningValidators(app.signedValidators)
}
// Simulate a DeliverTx for gas calculation.
if mode == runTxModeSimulate {
ctx = ctx.WithIsCheckTx(false)
}
return ctx
return
}
// Implements ABCI

View File

@ -139,6 +139,21 @@ func testLoadVersionHelper(t *testing.T, app *BaseApp, expectedHeight int64, exp
require.Equal(t, expectedID, lastID)
}
func TestOptionFunction(t *testing.T) {
logger := defaultLogger()
db := dbm.NewMemDB()
codec := wire.NewCodec()
registerTestCodec(codec)
bap := NewBaseApp("starting name", codec, logger, db, testChangeNameHelper("new name"))
require.Equal(t, bap.name, "new name", "BaseApp should have had name changed via option function")
}
func testChangeNameHelper(name string) func(*BaseApp) {
return func(bap *BaseApp) {
bap.name = name
}
}
// Test that the app hash is static
// TODO: https://github.com/cosmos/cosmos-sdk/issues/520
/*func TestStaticAppHash(t *testing.T) {
@ -285,9 +300,9 @@ type msgCounter struct {
}
// Implements Msg
func (msg msgCounter) Type() string { return typeMsgCounter }
func (msg msgCounter) GetSignBytes() []byte { return nil }
func (msg msgCounter) GetSigners() []sdk.Address { return nil }
func (msg msgCounter) Type() string { return typeMsgCounter }
func (msg msgCounter) GetSignBytes() []byte { return nil }
func (msg msgCounter) GetSigners() []sdk.AccAddress { return nil }
func (msg msgCounter) ValidateBasic() sdk.Error {
if msg.Counter >= 0 {
return nil
@ -323,9 +338,9 @@ type msgCounter2 struct {
}
// Implements Msg
func (msg msgCounter2) Type() string { return typeMsgCounter2 }
func (msg msgCounter2) GetSignBytes() []byte { return nil }
func (msg msgCounter2) GetSigners() []sdk.Address { return nil }
func (msg msgCounter2) Type() string { return typeMsgCounter2 }
func (msg msgCounter2) GetSignBytes() []byte { return nil }
func (msg msgCounter2) GetSigners() []sdk.AccAddress { return nil }
func (msg msgCounter2) ValidateBasic() sdk.Error {
if msg.Counter >= 0 {
return nil

View File

@ -1,11 +1,27 @@
package baseapp
import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/tendermint/tendermint/abci/server"
abci "github.com/tendermint/tendermint/abci/types"
cmn "github.com/tendermint/tendermint/libs/common"
)
// nolint - Mostly for testing
func (app *BaseApp) Check(tx sdk.Tx) (result sdk.Result) {
return app.runTx(runTxModeCheck, nil, tx)
}
// nolint - full tx execution
func (app *BaseApp) Simulate(tx sdk.Tx) (result sdk.Result) {
return app.runTx(runTxModeSimulate, nil, tx)
}
// nolint
func (app *BaseApp) Deliver(tx sdk.Tx) (result sdk.Result) {
return app.runTx(runTxModeDeliver, nil, tx)
}
// RunForever - BasecoinApp execution and cleanup
func RunForever(app abci.Application) {

View File

@ -109,7 +109,7 @@ func (ctx CoreContext) queryStore(key cmn.HexBytes, storeName, endPath string) (
}
// Get the from address from the name flag
func (ctx CoreContext) GetFromAddress() (from sdk.Address, err error) {
func (ctx CoreContext) GetFromAddress() (from sdk.AccAddress, err error) {
keybase, err := keys.GetKeyBase()
if err != nil {
@ -126,7 +126,7 @@ func (ctx CoreContext) GetFromAddress() (from sdk.Address, err error) {
return nil, errors.Errorf("no key for: %s", name)
}
return info.GetPubKey().Address(), nil
return sdk.AccAddress(info.GetPubKey().Address()), nil
}
// sign and build the transaction from the msg

View File

@ -46,6 +46,8 @@ phrase, otherwise, a new key will be generated.`,
return cmd
}
// nolint: gocyclo
// TODO remove the above when addressing #1446
func runAddCmd(cmd *cobra.Command, args []string) error {
var kb keys.Keybase
var err error
@ -219,14 +221,14 @@ func AddNewKeyRequestHandler(w http.ResponseWriter, r *http.Request) {
keyOutput.Seed = mnemonic
output, err := json.MarshalIndent(keyOutput, "", " ")
bz, err := json.Marshal(keyOutput)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
w.Write(output)
w.Write(bz)
}
// function to just a new seed to display in the UI before actually persisting it in the keybase

View File

@ -48,11 +48,11 @@ func SetKeyBase(kb keys.Keybase) {
// used for outputting keys.Info over REST
type KeyOutput struct {
Name string `json:"name"`
Type string `json:"type"`
Address string `json:"address"`
PubKey string `json:"pub_key"`
Seed string `json:"seed,omitempty"`
Name string `json:"name"`
Type string `json:"type"`
Address sdk.AccAddress `json:"address"`
PubKey string `json:"pub_key"`
Seed string `json:"seed,omitempty"`
}
// create a list of KeyOutput in bech32 format
@ -70,10 +70,7 @@ func Bech32KeysOutput(infos []keys.Info) ([]KeyOutput, error) {
// create a KeyOutput in bech32 format
func Bech32KeyOutput(info keys.Info) (KeyOutput, error) {
bechAccount, err := sdk.Bech32ifyAcc(sdk.Address(info.GetPubKey().Address().Bytes()))
if err != nil {
return KeyOutput{}, err
}
account := sdk.AccAddress(info.GetPubKey().Address().Bytes())
bechPubKey, err := sdk.Bech32ifyAccPub(info.GetPubKey())
if err != nil {
return KeyOutput{}, err
@ -81,7 +78,7 @@ func Bech32KeyOutput(info keys.Info) (KeyOutput, error) {
return KeyOutput{
Name: info.GetName(),
Type: info.GetType(),
Address: bechAccount,
Address: account,
PubKey: bechPubKey,
}, nil
}

View File

@ -36,7 +36,7 @@ func init() {
func TestKeys(t *testing.T) {
name, password := "test", "1234567890"
addr, seed := CreateAddr(t, "test", password, GetKB(t))
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.Address{addr})
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr})
defer cleanup()
// get seed
@ -60,8 +60,8 @@ func TestKeys(t *testing.T) {
err = wire.Cdc.UnmarshalJSON([]byte(body), &resp)
require.Nil(t, err, body)
addr2Bech32 := resp.Address
_, err = sdk.GetAccAddressBech32(addr2Bech32)
addr2Bech32 := resp.Address.String()
_, err = sdk.AccAddressFromBech32(addr2Bech32)
require.NoError(t, err, "Failed to return a correct bech32 address")
// existing keys
@ -71,12 +71,12 @@ func TestKeys(t *testing.T) {
err = cdc.UnmarshalJSON([]byte(body), &m)
require.Nil(t, err)
addrBech32 := sdk.MustBech32ifyAcc(addr)
addrBech32 := addr.String()
require.Equal(t, name, m[0].Name, "Did not serve keys name correctly")
require.Equal(t, addrBech32, m[0].Address, "Did not serve keys Address correctly")
require.Equal(t, addrBech32, m[0].Address.String(), "Did not serve keys Address correctly")
require.Equal(t, newName, m[1].Name, "Did not serve keys name correctly")
require.Equal(t, addr2Bech32, m[1].Address, "Did not serve keys Address correctly")
require.Equal(t, addr2Bech32, m[1].Address.String(), "Did not serve keys Address correctly")
// select key
keyEndpoint := fmt.Sprintf("/keys/%s", newName)
@ -87,7 +87,7 @@ func TestKeys(t *testing.T) {
require.Nil(t, err)
require.Equal(t, newName, m2.Name, "Did not serve keys name correctly")
require.Equal(t, addr2Bech32, m2.Address, "Did not serve keys Address correctly")
require.Equal(t, addr2Bech32, m2.Address.String(), "Did not serve keys Address correctly")
// update key
jsonStr = []byte(fmt.Sprintf(`{
@ -109,7 +109,7 @@ func TestKeys(t *testing.T) {
}
func TestVersion(t *testing.T) {
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.Address{})
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{})
defer cleanup()
// node info
@ -132,7 +132,7 @@ func TestVersion(t *testing.T) {
}
func TestNodeStatus(t *testing.T) {
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.Address{})
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{})
defer cleanup()
// node info
@ -154,7 +154,7 @@ func TestNodeStatus(t *testing.T) {
}
func TestBlock(t *testing.T) {
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.Address{})
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{})
defer cleanup()
var resultBlock ctypes.ResultBlock
@ -184,7 +184,7 @@ func TestBlock(t *testing.T) {
}
func TestValidators(t *testing.T) {
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.Address{})
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{})
defer cleanup()
var resultVals rpc.ResultValidatorsOutput
@ -197,7 +197,7 @@ func TestValidators(t *testing.T) {
require.NotEqual(t, rpc.ResultValidatorsOutput{}, resultVals)
require.Contains(t, resultVals.Validators[0].Address, "cosmosvaladdr")
require.Contains(t, resultVals.Validators[0].Address.String(), "cosmosvaladdr")
require.Contains(t, resultVals.Validators[0].PubKey, "cosmosvalpub")
// --
@ -219,15 +219,15 @@ func TestValidators(t *testing.T) {
func TestCoinSend(t *testing.T) {
name, password := "test", "1234567890"
addr, seed := CreateAddr(t, "test", password, GetKB(t))
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.Address{addr})
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr})
defer cleanup()
bz, err := hex.DecodeString("8FA6AB57AD6870F6B5B2E57735F38F2F30E73CB6")
require.NoError(t, err)
someFakeAddr := sdk.MustBech32ifyAcc(bz)
someFakeAddr := sdk.AccAddress(bz)
// query empty
res, body := Request(t, port, "GET", "/accounts/"+someFakeAddr, nil)
res, body := Request(t, port, "GET", fmt.Sprintf("/accounts/%s", someFakeAddr), nil)
require.Equal(t, http.StatusNoContent, res.StatusCode, body)
acc := getAccount(t, port, addr)
@ -261,7 +261,7 @@ func TestCoinSend(t *testing.T) {
func TestIBCTransfer(t *testing.T) {
name, password := "test", "1234567890"
addr, seed := CreateAddr(t, "test", password, GetKB(t))
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.Address{addr})
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr})
defer cleanup()
acc := getAccount(t, port, addr)
@ -290,7 +290,7 @@ func TestIBCTransfer(t *testing.T) {
func TestTxs(t *testing.T) {
name, password := "test", "1234567890"
addr, seed := CreateAddr(t, "test", password, GetKB(t))
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.Address{addr})
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr})
defer cleanup()
// query wrong
@ -334,8 +334,7 @@ func TestTxs(t *testing.T) {
// query sender
// also tests url decoding
addrBech := sdk.MustBech32ifyAcc(addr)
res, body = Request(t, port, "GET", "/txs?tag=sender_bech32=%27"+addrBech+"%27", nil)
res, body = Request(t, port, "GET", fmt.Sprintf("/txs?tag=sender_bech32=%%27%s%%27", addr), nil)
require.Equal(t, http.StatusOK, res.StatusCode, body)
err = cdc.UnmarshalJSON([]byte(body), &indexedTxs)
@ -344,8 +343,7 @@ func TestTxs(t *testing.T) {
require.Equal(t, resultTx.Height, indexedTxs[0].Height)
// query recipient
receiveAddrBech := sdk.MustBech32ifyAcc(receiveAddr)
res, body = Request(t, port, "GET", fmt.Sprintf("/txs?tag=recipient_bech32='%s'", receiveAddrBech), nil)
res, body = Request(t, port, "GET", fmt.Sprintf("/txs?tag=recipient_bech32='%s'", receiveAddr), nil)
require.Equal(t, http.StatusOK, res.StatusCode, body)
err = cdc.UnmarshalJSON([]byte(body), &indexedTxs)
@ -355,7 +353,7 @@ func TestTxs(t *testing.T) {
}
func TestValidatorsQuery(t *testing.T) {
cleanup, pks, port := InitializeTestLCD(t, 2, []sdk.Address{})
cleanup, pks, port := InitializeTestLCD(t, 2, []sdk.AccAddress{})
defer cleanup()
require.Equal(t, 2, len(pks))
@ -379,10 +377,10 @@ func TestValidatorsQuery(t *testing.T) {
func TestBonding(t *testing.T) {
name, password, denom := "test", "1234567890", "steak"
addr, seed := CreateAddr(t, "test", password, GetKB(t))
cleanup, pks, port := InitializeTestLCD(t, 1, []sdk.Address{addr})
cleanup, pks, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr})
defer cleanup()
validator1Owner := pks[0].Address()
validator1Owner := sdk.AccAddress(pks[0].Address())
// create bond TX
resultTx := doDelegate(t, port, seed, name, password, addr, validator1Owner)
@ -429,7 +427,7 @@ func TestBonding(t *testing.T) {
func TestSubmitProposal(t *testing.T) {
name, password := "test", "1234567890"
addr, seed := CreateAddr(t, "test", password, GetKB(t))
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.Address{addr})
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr})
defer cleanup()
// create SubmitProposal TX
@ -451,7 +449,7 @@ func TestSubmitProposal(t *testing.T) {
func TestDeposit(t *testing.T) {
name, password := "test", "1234567890"
addr, seed := CreateAddr(t, "test", password, GetKB(t))
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.Address{addr})
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr})
defer cleanup()
// create SubmitProposal TX
@ -485,7 +483,7 @@ func TestDeposit(t *testing.T) {
func TestVote(t *testing.T) {
name, password := "test", "1234567890"
addr, seed := CreateAddr(t, "test", password, GetKB(t))
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.Address{addr})
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr})
defer cleanup()
// create SubmitProposal TX
@ -523,13 +521,13 @@ func TestVote(t *testing.T) {
func TestUnrevoke(t *testing.T) {
_, password := "test", "1234567890"
addr, _ := CreateAddr(t, "test", password, GetKB(t))
cleanup, pks, port := InitializeTestLCD(t, 1, []sdk.Address{addr})
cleanup, pks, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr})
defer cleanup()
// XXX: any less than this and it fails
tests.WaitForHeight(3, port)
signingInfo := getSigningInfo(t, port, pks[0].Address())
signingInfo := getSigningInfo(t, port, sdk.ValAddress(pks[0].Address()))
tests.WaitForHeight(4, port)
require.Equal(t, true, signingInfo.IndexOffset > 0)
require.Equal(t, int64(0), signingInfo.JailedUntil)
@ -541,7 +539,7 @@ func TestProposalsQuery(t *testing.T) {
name2, password2 := "test2", "1234567890"
addr, seed := CreateAddr(t, "test", password1, GetKB(t))
addr2, seed2 := CreateAddr(t, "test2", password2, GetKB(t))
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.Address{addr, addr2})
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr, addr2})
defer cleanup()
// Addr1 proposes (and deposits) proposals #1 and #2
@ -607,9 +605,8 @@ func TestProposalsQuery(t *testing.T) {
//_____________________________________________________________________________
// get the account to get the sequence
func getAccount(t *testing.T, port string, addr sdk.Address) auth.Account {
addrBech32 := sdk.MustBech32ifyAcc(addr)
res, body := Request(t, port, "GET", "/accounts/"+addrBech32, nil)
func getAccount(t *testing.T, port string, addr sdk.AccAddress) auth.Account {
res, body := Request(t, port, "GET", fmt.Sprintf("/accounts/%s", addr), nil)
require.Equal(t, http.StatusOK, res.StatusCode, body)
var acc auth.Account
err := cdc.UnmarshalJSON([]byte(body), &acc)
@ -617,14 +614,13 @@ func getAccount(t *testing.T, port string, addr sdk.Address) auth.Account {
return acc
}
func doSend(t *testing.T, port, seed, name, password string, addr sdk.Address) (receiveAddr sdk.Address, resultTx ctypes.ResultBroadcastTxCommit) {
func doSend(t *testing.T, port, seed, name, password string, addr sdk.AccAddress) (receiveAddr sdk.AccAddress, resultTx ctypes.ResultBroadcastTxCommit) {
// create receive address
kb := client.MockKeyBase()
receiveInfo, _, err := kb.CreateMnemonic("receive_address", cryptoKeys.English, "1234567890", cryptoKeys.SigningAlgo("secp256k1"))
require.Nil(t, err)
receiveAddr = receiveInfo.GetPubKey().Address()
receiveAddrBech := sdk.MustBech32ifyAcc(receiveAddr)
receiveAddr = sdk.AccAddress(receiveInfo.GetPubKey().Address())
acc := getAccount(t, port, addr)
accnum := acc.GetAccountNumber()
@ -646,7 +642,7 @@ func doSend(t *testing.T, port, seed, name, password string, addr sdk.Address) (
"amount":[%s],
"chain_id":"%s"
}`, name, password, accnum, sequence, coinbz, chainID))
res, body := Request(t, port, "POST", "/accounts/"+receiveAddrBech+"/send", jsonStr)
res, body := Request(t, port, "POST", fmt.Sprintf("/accounts/%s/send", receiveAddr), jsonStr)
require.Equal(t, http.StatusOK, res.StatusCode, body)
err = cdc.UnmarshalJSON([]byte(body), &resultTx)
@ -655,13 +651,12 @@ func doSend(t *testing.T, port, seed, name, password string, addr sdk.Address) (
return receiveAddr, resultTx
}
func doIBCTransfer(t *testing.T, port, seed, name, password string, addr sdk.Address) (resultTx ctypes.ResultBroadcastTxCommit) {
func doIBCTransfer(t *testing.T, port, seed, name, password string, addr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) {
// create receive address
kb := client.MockKeyBase()
receiveInfo, _, err := kb.CreateMnemonic("receive_address", cryptoKeys.English, "1234567890", cryptoKeys.SigningAlgo("secp256k1"))
require.Nil(t, err)
receiveAddr := receiveInfo.GetPubKey().Address()
receiveAddrBech := sdk.MustBech32ifyAcc(receiveAddr)
receiveAddr := sdk.AccAddress(receiveInfo.GetPubKey().Address())
chainID := viper.GetString(client.FlagChainID)
@ -685,7 +680,7 @@ func doIBCTransfer(t *testing.T, port, seed, name, password string, addr sdk.Add
}
]
}`, name, password, accnum, sequence, chainID, "steak"))
res, body := Request(t, port, "POST", "/ibc/testchain/"+receiveAddrBech+"/send", jsonStr)
res, body := Request(t, port, "POST", fmt.Sprintf("/ibc/testchain/%s/send", receiveAddr), jsonStr)
require.Equal(t, http.StatusOK, res.StatusCode, body)
err = cdc.UnmarshalJSON([]byte(body), &resultTx)
@ -694,9 +689,8 @@ func doIBCTransfer(t *testing.T, port, seed, name, password string, addr sdk.Add
return resultTx
}
func getSigningInfo(t *testing.T, port string, validatorAddr sdk.Address) slashing.ValidatorSigningInfo {
validatorAddrBech := sdk.MustBech32ifyVal(validatorAddr)
res, body := Request(t, port, "GET", "/slashing/signing_info/"+validatorAddrBech, nil)
func getSigningInfo(t *testing.T, port string, validatorAddr sdk.ValAddress) slashing.ValidatorSigningInfo {
res, body := Request(t, port, "GET", fmt.Sprintf("/slashing/signing_info/%s", validatorAddr), nil)
require.Equal(t, http.StatusOK, res.StatusCode, body)
var signingInfo slashing.ValidatorSigningInfo
err := cdc.UnmarshalJSON([]byte(body), &signingInfo)
@ -704,13 +698,10 @@ func getSigningInfo(t *testing.T, port string, validatorAddr sdk.Address) slashi
return signingInfo
}
func getDelegation(t *testing.T, port string, delegatorAddr, validatorAddr sdk.Address) stake.Delegation {
delegatorAddrBech := sdk.MustBech32ifyAcc(delegatorAddr)
validatorAddrBech := sdk.MustBech32ifyVal(validatorAddr)
func getDelegation(t *testing.T, port string, delegatorAddr, validatorAddr sdk.AccAddress) stake.Delegation {
// get the account to get the sequence
res, body := Request(t, port, "GET", "/stake/"+delegatorAddrBech+"/delegation/"+validatorAddrBech, nil)
res, body := Request(t, port, "GET", fmt.Sprintf("/stake/%s/delegation/%s", delegatorAddr, validatorAddr), nil)
require.Equal(t, http.StatusOK, res.StatusCode, body)
var bond stake.Delegation
err := cdc.UnmarshalJSON([]byte(body), &bond)
@ -718,15 +709,12 @@ func getDelegation(t *testing.T, port string, delegatorAddr, validatorAddr sdk.A
return bond
}
func doDelegate(t *testing.T, port, seed, name, password string, delegatorAddr, validatorAddr sdk.Address) (resultTx ctypes.ResultBroadcastTxCommit) {
func doDelegate(t *testing.T, port, seed, name, password string, delegatorAddr, validatorAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) {
// get the account to get the sequence
acc := getAccount(t, port, delegatorAddr)
accnum := acc.GetAccountNumber()
sequence := acc.GetSequence()
delegatorAddrBech := sdk.MustBech32ifyAcc(delegatorAddr)
validatorAddrBech := sdk.MustBech32ifyVal(validatorAddr)
chainID := viper.GetString(client.FlagChainID)
// send
@ -748,7 +736,7 @@ func doDelegate(t *testing.T, port, seed, name, password string, delegatorAddr,
"complete_unbondings": [],
"begin_redelegates": [],
"complete_redelegates": []
}`, name, password, accnum, sequence, chainID, delegatorAddrBech, validatorAddrBech, "steak"))
}`, name, password, accnum, sequence, chainID, delegatorAddr, validatorAddr, "steak"))
res, body := Request(t, port, "POST", "/stake/delegations", jsonStr)
require.Equal(t, http.StatusOK, res.StatusCode, body)
@ -760,16 +748,13 @@ func doDelegate(t *testing.T, port, seed, name, password string, delegatorAddr,
}
func doBeginUnbonding(t *testing.T, port, seed, name, password string,
delegatorAddr, validatorAddr sdk.Address) (resultTx ctypes.ResultBroadcastTxCommit) {
delegatorAddr, validatorAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) {
// get the account to get the sequence
acc := getAccount(t, port, delegatorAddr)
accnum := acc.GetAccountNumber()
sequence := acc.GetSequence()
delegatorAddrBech := sdk.MustBech32ifyAcc(delegatorAddr)
validatorAddrBech := sdk.MustBech32ifyVal(validatorAddr)
chainID := viper.GetString(client.FlagChainID)
// send
@ -791,7 +776,7 @@ func doBeginUnbonding(t *testing.T, port, seed, name, password string,
"complete_unbondings": [],
"begin_redelegates": [],
"complete_redelegates": []
}`, name, password, accnum, sequence, chainID, delegatorAddrBech, validatorAddrBech))
}`, name, password, accnum, sequence, chainID, delegatorAddr, validatorAddr))
res, body := Request(t, port, "POST", "/stake/delegations", jsonStr)
require.Equal(t, http.StatusOK, res.StatusCode, body)
@ -803,17 +788,13 @@ func doBeginUnbonding(t *testing.T, port, seed, name, password string,
}
func doBeginRedelegation(t *testing.T, port, seed, name, password string,
delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.Address) (resultTx ctypes.ResultBroadcastTxCommit) {
delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) {
// get the account to get the sequence
acc := getAccount(t, port, delegatorAddr)
accnum := acc.GetAccountNumber()
sequence := acc.GetSequence()
delegatorAddrBech := sdk.MustBech32ifyAcc(delegatorAddr)
validatorSrcAddrBech := sdk.MustBech32ifyVal(validatorSrcAddr)
validatorDstAddrBech := sdk.MustBech32ifyVal(validatorDstAddr)
chainID := viper.GetString(client.FlagChainID)
// send
@ -836,7 +817,7 @@ func doBeginRedelegation(t *testing.T, port, seed, name, password string,
}
],
"complete_redelegates": []
}`, name, password, accnum, sequence, chainID, delegatorAddrBech, validatorSrcAddrBech, validatorDstAddrBech))
}`, name, password, accnum, sequence, chainID, delegatorAddr, validatorSrcAddr, validatorDstAddr))
res, body := Request(t, port, "POST", "/stake/delegations", jsonStr)
require.Equal(t, http.StatusOK, res.StatusCode, body)
@ -866,9 +847,8 @@ func getProposal(t *testing.T, port string, proposalID int64) gov.ProposalRest {
return proposal
}
func getDeposit(t *testing.T, port string, proposalID int64, depositerAddr sdk.Address) gov.DepositRest {
bechDepositerAddr := sdk.MustBech32ifyAcc(depositerAddr)
res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals/%d/deposits/%s", proposalID, bechDepositerAddr), nil)
func getDeposit(t *testing.T, port string, proposalID int64, depositerAddr sdk.AccAddress) gov.DepositRest {
res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals/%d/deposits/%s", proposalID, depositerAddr), nil)
require.Equal(t, http.StatusOK, res.StatusCode, body)
var deposit gov.DepositRest
err := cdc.UnmarshalJSON([]byte(body), &deposit)
@ -876,9 +856,8 @@ func getDeposit(t *testing.T, port string, proposalID int64, depositerAddr sdk.A
return deposit
}
func getVote(t *testing.T, port string, proposalID int64, voterAddr sdk.Address) gov.VoteRest {
bechVoterAddr := sdk.MustBech32ifyAcc(voterAddr)
res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals/%d/votes/%s", proposalID, bechVoterAddr), nil)
func getVote(t *testing.T, port string, proposalID int64, voterAddr sdk.AccAddress) gov.VoteRest {
res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals/%d/votes/%s", proposalID, voterAddr), nil)
require.Equal(t, http.StatusOK, res.StatusCode, body)
var vote gov.VoteRest
err := cdc.UnmarshalJSON([]byte(body), &vote)
@ -896,10 +875,8 @@ func getProposalsAll(t *testing.T, port string) []gov.ProposalRest {
return proposals
}
func getProposalsFilterDepositer(t *testing.T, port string, depositerAddr sdk.Address) []gov.ProposalRest {
bechDepositerAddr := sdk.MustBech32ifyAcc(depositerAddr)
res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals?depositer=%s", bechDepositerAddr), nil)
func getProposalsFilterDepositer(t *testing.T, port string, depositerAddr sdk.AccAddress) []gov.ProposalRest {
res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals?depositer=%s", depositerAddr), nil)
require.Equal(t, http.StatusOK, res.StatusCode, body)
var proposals []gov.ProposalRest
@ -908,10 +885,8 @@ func getProposalsFilterDepositer(t *testing.T, port string, depositerAddr sdk.Ad
return proposals
}
func getProposalsFilterVoter(t *testing.T, port string, voterAddr sdk.Address) []gov.ProposalRest {
bechVoterAddr := sdk.MustBech32ifyAcc(voterAddr)
res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals?voter=%s", bechVoterAddr), nil)
func getProposalsFilterVoter(t *testing.T, port string, voterAddr sdk.AccAddress) []gov.ProposalRest {
res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals?voter=%s", voterAddr), nil)
require.Equal(t, http.StatusOK, res.StatusCode, body)
var proposals []gov.ProposalRest
@ -920,11 +895,8 @@ func getProposalsFilterVoter(t *testing.T, port string, voterAddr sdk.Address) [
return proposals
}
func getProposalsFilterVoterDepositer(t *testing.T, port string, voterAddr sdk.Address, depositerAddr sdk.Address) []gov.ProposalRest {
bechVoterAddr := sdk.MustBech32ifyAcc(voterAddr)
bechDepositerAddr := sdk.MustBech32ifyAcc(depositerAddr)
res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals?depositer=%s&voter=%s", bechDepositerAddr, bechVoterAddr), nil)
func getProposalsFilterVoterDepositer(t *testing.T, port string, voterAddr, depositerAddr sdk.AccAddress) []gov.ProposalRest {
res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals?depositer=%s&voter=%s", depositerAddr, voterAddr), nil)
require.Equal(t, http.StatusOK, res.StatusCode, body)
var proposals []gov.ProposalRest
@ -933,7 +905,7 @@ func getProposalsFilterVoterDepositer(t *testing.T, port string, voterAddr sdk.A
return proposals
}
func doSubmitProposal(t *testing.T, port, seed, name, password string, proposerAddr sdk.Address) (resultTx ctypes.ResultBroadcastTxCommit) {
func doSubmitProposal(t *testing.T, port, seed, name, password string, proposerAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) {
// get the account to get the sequence
acc := getAccount(t, port, proposerAddr)
accnum := acc.GetAccountNumber()
@ -941,8 +913,6 @@ func doSubmitProposal(t *testing.T, port, seed, name, password string, proposerA
chainID := viper.GetString(client.FlagChainID)
bechProposerAddr := sdk.MustBech32ifyAcc(proposerAddr)
// submitproposal
jsonStr := []byte(fmt.Sprintf(`{
"title": "Test",
@ -958,7 +928,7 @@ func doSubmitProposal(t *testing.T, port, seed, name, password string, proposerA
"sequence":"%d",
"gas":"100000"
}
}`, bechProposerAddr, name, password, chainID, accnum, sequence))
}`, proposerAddr, name, password, chainID, accnum, sequence))
res, body := Request(t, port, "POST", "/gov/proposals", jsonStr)
require.Equal(t, http.StatusOK, res.StatusCode, body)
@ -969,7 +939,7 @@ func doSubmitProposal(t *testing.T, port, seed, name, password string, proposerA
return results
}
func doDeposit(t *testing.T, port, seed, name, password string, proposerAddr sdk.Address, proposalID int64) (resultTx ctypes.ResultBroadcastTxCommit) {
func doDeposit(t *testing.T, port, seed, name, password string, proposerAddr sdk.AccAddress, proposalID int64) (resultTx ctypes.ResultBroadcastTxCommit) {
// get the account to get the sequence
acc := getAccount(t, port, proposerAddr)
accnum := acc.GetAccountNumber()
@ -977,8 +947,6 @@ func doDeposit(t *testing.T, port, seed, name, password string, proposerAddr sdk
chainID := viper.GetString(client.FlagChainID)
bechProposerAddr := sdk.MustBech32ifyAcc(proposerAddr)
// deposit on proposal
jsonStr := []byte(fmt.Sprintf(`{
"depositer": "%s",
@ -991,7 +959,7 @@ func doDeposit(t *testing.T, port, seed, name, password string, proposerAddr sdk
"sequence": "%d",
"gas":"100000"
}
}`, bechProposerAddr, name, password, chainID, accnum, sequence))
}`, proposerAddr, name, password, chainID, accnum, sequence))
res, body := Request(t, port, "POST", fmt.Sprintf("/gov/proposals/%d/deposits", proposalID), jsonStr)
require.Equal(t, http.StatusOK, res.StatusCode, body)
@ -1002,7 +970,7 @@ func doDeposit(t *testing.T, port, seed, name, password string, proposerAddr sdk
return results
}
func doVote(t *testing.T, port, seed, name, password string, proposerAddr sdk.Address, proposalID int64) (resultTx ctypes.ResultBroadcastTxCommit) {
func doVote(t *testing.T, port, seed, name, password string, proposerAddr sdk.AccAddress, proposalID int64) (resultTx ctypes.ResultBroadcastTxCommit) {
// get the account to get the sequence
acc := getAccount(t, port, proposerAddr)
accnum := acc.GetAccountNumber()
@ -1010,8 +978,6 @@ func doVote(t *testing.T, port, seed, name, password string, proposerAddr sdk.Ad
chainID := viper.GetString(client.FlagChainID)
bechProposerAddr := sdk.MustBech32ifyAcc(proposerAddr)
// vote on proposal
jsonStr := []byte(fmt.Sprintf(`{
"voter": "%s",
@ -1024,7 +990,7 @@ func doVote(t *testing.T, port, seed, name, password string, proposerAddr sdk.Ad
"sequence": "%d",
"gas":"100000"
}
}`, bechProposerAddr, name, password, chainID, accnum, sequence))
}`, proposerAddr, name, password, chainID, accnum, sequence))
res, body := Request(t, port, "POST", fmt.Sprintf("/gov/proposals/%d/votes", proposalID), jsonStr)
fmt.Println(res)
require.Equal(t, http.StatusOK, res.StatusCode, body)

View File

@ -80,19 +80,19 @@ func GetKB(t *testing.T) crkeys.Keybase {
}
// add an address to the store return name and password
func CreateAddr(t *testing.T, name, password string, kb crkeys.Keybase) (addr sdk.Address, seed string) {
func CreateAddr(t *testing.T, name, password string, kb crkeys.Keybase) (addr sdk.AccAddress, seed string) {
var info crkeys.Info
var err error
info, seed, err = kb.CreateMnemonic(name, crkeys.English, password, crkeys.Secp256k1)
require.NoError(t, err)
addr = info.GetPubKey().Address()
addr = sdk.AccAddress(info.GetPubKey().Address())
return
}
// strt TM and the LCD in process, listening on their respective sockets
// nValidators = number of validators
// initAddrs = accounts to initialize with some steaks
func InitializeTestLCD(t *testing.T, nValidators int, initAddrs []sdk.Address) (cleanup func(), validatorsPKs []crypto.PubKey, port string) {
func InitializeTestLCD(t *testing.T, nValidators int, initAddrs []sdk.AccAddress) (cleanup func(), validatorsPKs []crypto.PubKey, port string) {
config := GetConfig()
config.Consensus.TimeoutCommit = 100
@ -132,7 +132,7 @@ func InitializeTestLCD(t *testing.T, nValidators int, initAddrs []sdk.Address) (
for _, gdValidator := range genDoc.Validators {
pk := gdValidator.PubKey
validatorsPKs = append(validatorsPKs, pk) // append keys for output
appGenTx, _, _, err := gapp.GaiaAppGenTxNF(cdc, pk, sdk.MustBech32ifyAcc(pk.Address()), "test_val1")
appGenTx, _, _, err := gapp.GaiaAppGenTxNF(cdc, pk, sdk.AccAddress(pk.Address()), "test_val1")
require.NoError(t, err)
appGenTxs = append(appGenTxs, appGenTx)
}

View File

@ -32,10 +32,10 @@ func ValidatorCommand() *cobra.Command {
// Validator output in bech32 format
type ValidatorOutput struct {
Address string `json:"address"` // in bech32
PubKey string `json:"pub_key"` // in bech32
Accum int64 `json:"accum"`
VotingPower int64 `json:"voting_power"`
Address sdk.ValAddress `json:"address"` // in bech32
PubKey string `json:"pub_key"` // in bech32
Accum int64 `json:"accum"`
VotingPower int64 `json:"voting_power"`
}
// Validators at a certain height output in bech32 format
@ -45,17 +45,13 @@ type ResultValidatorsOutput struct {
}
func bech32ValidatorOutput(validator *tmtypes.Validator) (ValidatorOutput, error) {
bechAddress, err := sdk.Bech32ifyVal(validator.Address)
if err != nil {
return ValidatorOutput{}, err
}
bechValPubkey, err := sdk.Bech32ifyValPub(validator.PubKey)
if err != nil {
return ValidatorOutput{}, err
}
return ValidatorOutput{
Address: bechAddress,
Address: sdk.ValAddress(validator.Address),
PubKey: bechValPubkey,
Accum: validator.Accum,
VotingPower: validator.VotingPower,

View File

@ -124,7 +124,7 @@ func SearchTxRequestHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.Han
return
}
tag = strings.TrimRight(key, "_bech32") + "='" + sdk.Address(bz).String() + "'"
tag = strings.TrimRight(key, "_bech32") + "='" + sdk.AccAddress(bz).String() + "'"
}
txs, err := searchTxs(ctx, cdc, []string{tag})

View File

@ -164,7 +164,11 @@ func (app *GaiaApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci
}
// load the initial stake information
stake.InitGenesis(ctx, app.stakeKeeper, genesisState.StakeData)
err = stake.InitGenesis(ctx, app.stakeKeeper, genesisState.StakeData)
if err != nil {
panic(err) // TODO https://github.com/cosmos/cosmos-sdk/issues/468
// return sdk.ErrGenesisParse("").TraceCause(err, "")
}
gov.InitGenesis(ctx, app.govKeeper, gov.DefaultGenesisState())

View File

@ -30,20 +30,20 @@ type GenesisState struct {
// GenesisAccount doesn't need pubkey or sequence
type GenesisAccount struct {
Address string `json:"address"`
Coins sdk.Coins `json:"coins"`
Address sdk.AccAddress `json:"address"`
Coins sdk.Coins `json:"coins"`
}
func NewGenesisAccount(acc *auth.BaseAccount) GenesisAccount {
return GenesisAccount{
Address: sdk.MustBech32ifyAcc(acc.Address),
Address: acc.Address,
Coins: acc.Coins,
}
}
func NewGenesisAccountI(acc auth.Account) GenesisAccount {
return GenesisAccount{
Address: sdk.MustBech32ifyAcc(acc.GetAddress()),
Address: acc.GetAddress(),
Coins: acc.GetCoins(),
}
}
@ -51,7 +51,7 @@ func NewGenesisAccountI(acc auth.Account) GenesisAccount {
// convert GenesisAccount to auth.BaseAccount
func (ga *GenesisAccount) ToAccount() (acc *auth.BaseAccount) {
return &auth.BaseAccount{
Address: sdk.MustGetAccAddressBech32(ga.Address),
Address: ga.Address,
Coins: ga.Coins.Sort(),
}
}
@ -76,9 +76,9 @@ func GaiaAppInit() server.AppInit {
// simple genesis tx
type GaiaGenTx struct {
Name string `json:"name"`
Address string `json:"address"`
PubKey string `json:"pub_key"`
Name string `json:"name"`
Address sdk.AccAddress `json:"address"`
PubKey string `json:"pub_key"`
}
// Generate a gaia genesis transaction with flags
@ -88,7 +88,7 @@ func GaiaAppGenTx(cdc *wire.Codec, pk crypto.PubKey, genTxConfig config.GenTx) (
return nil, nil, tmtypes.GenesisValidator{}, errors.New("Must specify --name (validator moniker)")
}
var addr string
var addr sdk.AccAddress
var secret string
addr, secret, err = server.GenerateSaveCoinKey(genTxConfig.CliRoot, genTxConfig.Name, "1234567890", genTxConfig.Overwrite)
if err != nil {
@ -108,7 +108,7 @@ func GaiaAppGenTx(cdc *wire.Codec, pk crypto.PubKey, genTxConfig config.GenTx) (
}
// Generate a gaia genesis transaction without flags
func GaiaAppGenTxNF(cdc *wire.Codec, pk crypto.PubKey, addr string, name string) (
func GaiaAppGenTxNF(cdc *wire.Codec, pk crypto.PubKey, addr sdk.AccAddress, name string) (
appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) {
var bz []byte
@ -153,7 +153,7 @@ func GaiaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState
}
// create the genesis account, give'm few steaks and a buncha token with there name
accAuth := auth.NewBaseAccountWithAddress(sdk.MustGetAccAddressBech32(genTx.Address))
accAuth := auth.NewBaseAccountWithAddress(genTx.Address)
accAuth.Coins = sdk.Coins{
{genTx.Name + "Token", sdk.NewInt(1000)},
{"steak", sdk.NewInt(freeFermionsAcc)},
@ -165,7 +165,7 @@ func GaiaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState
// add the validator
if len(genTx.Name) > 0 {
desc := stake.NewDescription(genTx.Name, "", "", "")
validator := stake.NewValidator(sdk.MustGetAccAddressBech32(genTx.Address),
validator := stake.NewValidator(genTx.Address,
sdk.MustGetAccPubKeyBech32(genTx.PubKey), desc)
stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens + freeFermionVal // increase the supply

View File

@ -11,7 +11,7 @@ import (
func TestToAccount(t *testing.T) {
priv := crypto.GenPrivKeyEd25519()
addr := sdk.Address(priv.PubKey().Address())
addr := sdk.AccAddress(priv.PubKey().Address())
authAcc := auth.NewBaseAccountWithAddress(addr)
genAcc := NewGenesisAccount(&authAcc)
require.Equal(t, authAcc, *genAcc.ToAccount())

View File

@ -52,37 +52,35 @@ func TestGaiaCLISend(t *testing.T) {
tests.WaitForNextHeightTM(port)
fooAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show foo --output=json --home=%s", gaiacliHome))
fooCech := sdk.MustBech32ifyAcc(fooAddr)
barAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show bar --output=json --home=%s", gaiacliHome))
barCech := sdk.MustBech32ifyAcc(barAddr)
fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooCech, flags))
fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags))
require.Equal(t, int64(50), fooAcc.GetCoins().AmountOf("steak").Int64())
executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%v --from=foo", flags, barCech), pass)
executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%s --from=foo", flags, barAddr), pass)
tests.WaitForNextHeightTM(port)
barAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", barCech, flags))
barAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", barAddr, flags))
require.Equal(t, int64(10), barAcc.GetCoins().AmountOf("steak").Int64())
fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooCech, flags))
fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags))
require.Equal(t, int64(40), fooAcc.GetCoins().AmountOf("steak").Int64())
// test autosequencing
executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%v --from=foo", flags, barCech), pass)
executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%s --from=foo", flags, barAddr), pass)
tests.WaitForNextHeightTM(port)
barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", barCech, flags))
barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", barAddr, flags))
require.Equal(t, int64(20), barAcc.GetCoins().AmountOf("steak").Int64())
fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooCech, flags))
fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags))
require.Equal(t, int64(30), fooAcc.GetCoins().AmountOf("steak").Int64())
// test memo
executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%v --from=foo --memo 'testmemo'", flags, barCech), pass)
executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%s --from=foo --memo 'testmemo'", flags, barAddr), pass)
tests.WaitForNextHeightTM(port)
barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", barCech, flags))
barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", barAddr, flags))
require.Equal(t, int64(30), barAcc.GetCoins().AmountOf("steak").Int64())
fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooCech, flags))
fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags))
require.Equal(t, int64(20), fooAcc.GetCoins().AmountOf("steak").Int64())
}
@ -106,42 +104,40 @@ func TestGaiaCLICreateValidator(t *testing.T) {
tests.WaitForNextHeightTM(port)
fooAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show foo --output=json --home=%s", gaiacliHome))
fooCech := sdk.MustBech32ifyAcc(fooAddr)
barAddr, barPubKey := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show bar --output=json --home=%s", gaiacliHome))
barCech := sdk.MustBech32ifyAcc(barAddr)
barCeshPubKey := sdk.MustBech32ifyValPub(barPubKey)
executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%v --from=foo", flags, barCech), pass)
executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%s --from=foo", flags, barAddr), pass)
tests.WaitForNextHeightTM(port)
barAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", barCech, flags))
barAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", barAddr, flags))
require.Equal(t, int64(10), barAcc.GetCoins().AmountOf("steak").Int64())
fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooCech, flags))
fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags))
require.Equal(t, int64(40), fooAcc.GetCoins().AmountOf("steak").Int64())
// create validator
cvStr := fmt.Sprintf("gaiacli stake create-validator %v", flags)
cvStr += fmt.Sprintf(" --from=%v", "bar")
cvStr += fmt.Sprintf(" --address-validator=%v", barCech)
cvStr += fmt.Sprintf(" --pubkey=%v", barCeshPubKey)
cvStr += fmt.Sprintf(" --from=%s", "bar")
cvStr += fmt.Sprintf(" --address-validator=%s", barAddr)
cvStr += fmt.Sprintf(" --pubkey=%s", barCeshPubKey)
cvStr += fmt.Sprintf(" --amount=%v", "2steak")
cvStr += fmt.Sprintf(" --moniker=%v", "bar-vally")
executeWrite(t, cvStr, pass)
tests.WaitForNextHeightTM(port)
barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", barCech, flags))
barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", barAddr, flags))
require.Equal(t, int64(8), barAcc.GetCoins().AmountOf("steak").Int64(), "%v", barAcc)
validator := executeGetValidator(t, fmt.Sprintf("gaiacli stake validator %v --output=json %v", barCech, flags))
validator := executeGetValidator(t, fmt.Sprintf("gaiacli stake validator %s --output=json %v", barAddr, flags))
require.Equal(t, validator.Owner, barAddr)
require.Equal(t, "2/1", validator.PoolShares.Amount.String())
// unbond a single share
unbondStr := fmt.Sprintf("gaiacli stake unbond begin %v", flags)
unbondStr += fmt.Sprintf(" --from=%v", "bar")
unbondStr += fmt.Sprintf(" --address-validator=%v", barCech)
unbondStr += fmt.Sprintf(" --address-delegator=%v", barCech)
unbondStr += fmt.Sprintf(" --from=%s", "bar")
unbondStr += fmt.Sprintf(" --address-validator=%s", barAddr)
unbondStr += fmt.Sprintf(" --address-delegator=%s", barAddr)
unbondStr += fmt.Sprintf(" --shares-amount=%v", "1")
success := executeWrite(t, unbondStr, pass)
@ -152,7 +148,7 @@ func TestGaiaCLICreateValidator(t *testing.T) {
barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", barCech, flags))
require.Equal(t, int64(9), barAcc.GetCoins().AmountOf("steak").Int64(), "%v", barAcc)
*/
validator = executeGetValidator(t, fmt.Sprintf("gaiacli stake validator %v --output=json %v", barCech, flags))
validator = executeGetValidator(t, fmt.Sprintf("gaiacli stake validator %s --output=json %v", barAddr, flags))
require.Equal(t, "1/1", validator.PoolShares.Amount.String())
}
@ -176,34 +172,33 @@ func TestGaiaCLISubmitProposal(t *testing.T) {
tests.WaitForNextHeightTM(port)
fooAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show foo --output=json --home=%s", gaiacliHome))
fooCech := sdk.MustBech32ifyAcc(fooAddr)
fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooCech, flags))
fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags))
require.Equal(t, int64(50), fooAcc.GetCoins().AmountOf("steak").Int64())
executeWrite(t, fmt.Sprintf("gaiacli gov submit-proposal %v --proposer=%v --deposit=5steak --type=Text --title=Test --description=test --from=foo", flags, fooCech), pass)
executeWrite(t, fmt.Sprintf("gaiacli gov submit-proposal %v --proposer=%s --deposit=5steak --type=Text --title=Test --description=test --from=foo", flags, fooAddr), pass)
tests.WaitForNextHeightTM(port)
fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooCech, flags))
fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags))
require.Equal(t, int64(45), fooAcc.GetCoins().AmountOf("steak").Int64())
proposal1 := executeGetProposal(t, fmt.Sprintf("gaiacli gov query-proposal --proposalID=1 --output=json %v", flags))
require.Equal(t, int64(1), proposal1.ProposalID)
require.Equal(t, gov.StatusToString(gov.StatusDepositPeriod), proposal1.Status)
executeWrite(t, fmt.Sprintf("gaiacli gov deposit %v --depositer=%v --deposit=10steak --proposalID=1 --from=foo", flags, fooCech), pass)
executeWrite(t, fmt.Sprintf("gaiacli gov deposit %v --depositer=%s --deposit=10steak --proposalID=1 --from=foo", flags, fooAddr), pass)
tests.WaitForNextHeightTM(port)
fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooCech, flags))
fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags))
require.Equal(t, int64(35), fooAcc.GetCoins().AmountOf("steak").Int64())
proposal1 = executeGetProposal(t, fmt.Sprintf("gaiacli gov query-proposal --proposalID=1 --output=json %v", flags))
require.Equal(t, int64(1), proposal1.ProposalID)
require.Equal(t, gov.StatusToString(gov.StatusVotingPeriod), proposal1.Status)
executeWrite(t, fmt.Sprintf("gaiacli gov vote %v --proposalID=1 --voter=%v --option=Yes --from=foo", flags, fooCech), pass)
executeWrite(t, fmt.Sprintf("gaiacli gov vote %v --proposalID=1 --voter=%s --option=Yes --from=foo", flags, fooAddr), pass)
tests.WaitForNextHeightTM(port)
vote := executeGetVote(t, fmt.Sprintf("gaiacli gov query-vote --proposalID=1 --voter=%v --output=json %v", fooCech, flags))
vote := executeGetVote(t, fmt.Sprintf("gaiacli gov query-vote --proposalID=1 --voter=%s --output=json %v", fooAddr, flags))
require.Equal(t, int64(1), vote.ProposalID)
require.Equal(t, gov.VoteOptionToString(gov.OptionYes), vote.Option)
}
@ -259,18 +254,15 @@ func executeInit(t *testing.T, cmdStr string) (chainID string) {
return
}
func executeGetAddrPK(t *testing.T, cmdStr string) (sdk.Address, crypto.PubKey) {
func executeGetAddrPK(t *testing.T, cmdStr string) (sdk.AccAddress, crypto.PubKey) {
out := tests.ExecuteT(t, cmdStr)
var ko keys.KeyOutput
keys.UnmarshalJSON([]byte(out), &ko)
address, err := sdk.GetAccAddressBech32(ko.Address)
require.NoError(t, err)
pk, err := sdk.GetAccPubKeyBech32(ko.PubKey)
require.NoError(t, err)
return address, pk
return ko.Address, pk
}
func executeGetAccount(t *testing.T, cmdStr string) auth.BaseAccount {

View File

@ -228,8 +228,7 @@ func (app *GaiaApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci
var genesisState gaia.GenesisState
err := app.cdc.UnmarshalJSON(stateJSON, &genesisState)
if err != nil {
panic(err) // TODO https://github.com/cosmos/cosmos-sdk/issues/468
// return sdk.ErrGenesisParse("").TraceCause(err, "")
panic(err) // TODO https://github.com/cosmos/cosmos-sdk/issues/468 // return sdk.ErrGenesisParse("").TraceCause(err, "")
}
// load the accounts
@ -239,7 +238,10 @@ func (app *GaiaApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci
}
// load the initial stake information
stake.InitGenesis(ctx, app.stakeKeeper, genesisState.StakeData)
return abci.ResponseInitChain{}
err = stake.InitGenesis(ctx, app.stakeKeeper, genesisState.StakeData)
if err != nil {
panic(err) // TODO https://github.com/cosmos/cosmos-sdk/issues/468 // return sdk.ErrGenesisParse("").TraceCause(err, "")
}
return abci.ResponseInitChain{}
}

View File

@ -151,17 +151,17 @@ func runAddrCmd(cmd *cobra.Command, args []string) error {
}
addrString := args[0]
var addr sdk.Address
var addr []byte
// try hex, then bech32
var err error
addr, err = hex.DecodeString(addrString)
if err != nil {
var err2 error
addr, err2 = sdk.GetAccAddressBech32(addrString)
addr, err2 = sdk.AccAddressFromBech32(addrString)
if err2 != nil {
var err3 error
addr, err3 = sdk.GetValAddressBech32(addrString)
addr, err3 = sdk.ValAddressFromBech32(addrString)
if err3 != nil {
return fmt.Errorf(`Expected hex or bech32. Got errors:
@ -174,14 +174,9 @@ func runAddrCmd(cmd *cobra.Command, args []string) error {
}
}
accAddr, err := sdk.Bech32ifyAcc(addr)
if err != nil {
return err
}
valAddr, err := sdk.Bech32ifyVal(addr)
if err != nil {
return err
}
accAddr := sdk.AccAddress(addr)
valAddr := sdk.ValAddress(addr)
fmt.Println("Address:", addr)
fmt.Println("Bech32 Acc:", accAddr)
fmt.Println("Bech32 Val:", valAddr)

View File

@ -310,11 +310,11 @@ WantedBy=multi-user.target
## Delegating to a Validator
On the upcoming mainnet, you can delegate `atom` to a validator. These [delegators](https://cosmos.network/resources/delegators) can receive part of the validator's fee revenue. Read more about the [Cosmos Token Model](https://github.com/cosmos/cosmos/raw/master/Cosmos_Token_Model.pdf).
On the upcoming mainnet, you can delegate `Atom` to a validator. These [delegators](https://cosmos.network/resources/delegators) can receive part of the validator's fee revenue. Read more about the [Cosmos Token Model](https://github.com/cosmos/cosmos/raw/master/Cosmos_Token_Model.pdf).
### Bond Tokens
On the testnet, we delegate `steak` instead of `atom`. Here's how you can bond tokens to a testnet validator:
On the testnet, we delegate `steak` instead of `Atom`. Here's how you can bond tokens to a testnet validator:
```bash
gaiacli stake delegate \
@ -353,6 +353,90 @@ gaiacli stake delegation \
--chain-id=gaia-6002
```
## Governance
Governance is the process from which users in the Cosmos Hub can come to consensus on software upgrades, parameters of the mainnet or on custom text proposals. This is done through voting on proposals, which will be submitted by `Atom` holders on the mainnet.
Some considerations about the voting process:
- Voting is done by bonded `Atom` holders on a 1 bonded `Atom` 1 vote basis
- Delegators inherit the vote of their validator if they don't vote
- **Validators MUST vote on every proposal**. If a validator does not vote on a proposal, they will be **partially slashed**
- Votes are tallied at the end of the voting period (2 weeks on mainnet). Each address can vote multiple times to update its `Option` value (paying the transaction fee each time), only the last casted vote will count as valid
- Voters can choose between options `Yes`, `No`, `NoWithVeto` and `Abstain`
At the end of the voting period, a proposal is accepted if `(YesVotes/(YesVotes+NoVotes+NoWithVetoVotes))>1/2` and `(NoWithVetoVotes/(YesVotes+NoVotes+NoWithVetoVotes))<1/3`. It is rejected otherwise
For more information about the governance process and how it works, please check out the Governance module [specification](https://github.com/cosmos/cosmos-sdk/tree/develop/docs/spec/governance).
### Create a Governance proposal
In order to create a governance proposal, you must submit an initial deposit along with the proposal details:
- `title`: Title of the proposal
- `description`: Description of the proposal
- `type`: Type of proposal. Must be of value _Text_ (types _SoftwareUpgrade_ and _ParameterChange_ not supported yet).
```bash
gaiacli gov submit-proposal \
--title=<title> \
--description=<description> \
--type=<Text/ParameterChange/SoftwareUpgrade> \
--proposer=<account_cosmosaccaddr> \
--deposit=<40steak> \
--from=<name> \
--chain-id=gaia-7000
```
### Increase deposit
In order for a proposal to be broadcasted to the network, the amount deposited must be above a `minDeposit` value (default: `10 steak`). If the proposal you previously created didn't meet this requirement, you can still increase the total amount deposited to activate it. Once the minimum deposit is reached, the proposal enters voting period:
```bash
gaiacli gov deposit \
--proposalID=<proposal_id> \
--depositer=<account_cosmosaccaddr> \
--deposit=<200steak> \
--from=<name> \
--chain-id=gaia-7000
```
> _NOTE_: Proposals that don't meet this requirement will be deleted after `MaxDepositPeriod` is reached.
#### Query proposal
Once created, you can now query information of the proposal:
```bash
gaiacli gov query-proposal \
--proposalID=<proposal_id> \
--chain-id=gaia-7000
```
### Vote on a proposal
After a proposal's deposit reaches the `MinDeposit` value, the voting period opens. Bonded `Atom` holders can then cast vote on it:
```bash
gaiacli gov vote \
--proposalID=<proposal_id> \
--voter=<account_cosmosaccaddr> \
--option=<Yes/No/NoWithVeto/Abstain> \
--from=<name> \
--chain-id=gaia-7000
```
#### Query vote
Check the vote with the option you just submitted:
```bash
gaiacli gov query-vote \
--proposalID=<proposal_id> \
--voter=<account_cosmosaccaddr> \
--chain-id=gaia-7000
```
## Other Operations
### Send Tokens
@ -365,7 +449,7 @@ gaiacli send \
--to=<destination_cosmosaccaddr>
```
> _*Note:*_ The `--amount` flag accepts the format `--amount=<value|coin_name>`.
> _*NOTE:*_ The `--amount` flag accepts the format `--amount=<value|coin_name>`.
Now, view the updated balances of the origin and destination accounts:

View File

@ -30,7 +30,7 @@ type Msg interface {
// Signers returns the addrs of signers that must sign.
// CONTRACT: All signatures must be present to be valid.
// CONTRACT: Returns addrs in some deterministic order.
GetSigners() []Address
GetSigners() []AccAddress
}
```
@ -43,8 +43,8 @@ For instance, take the simple token sending message type from app1.go:
```go
// MsgSend to send coins from Input to Output
type MsgSend struct {
From sdk.Address `json:"from"`
To sdk.Address `json:"to"`
From sdk.AccAddress `json:"from"`
To sdk.AccAddress `json:"to"`
Amount sdk.Coins `json:"amount"`
}
@ -65,8 +65,8 @@ func (msg MsgSend) GetSignBytes() []byte {
}
// Implements Msg. Return the signer.
func (msg MsgSend) GetSigners() []sdk.Address {
return []sdk.Address{msg.From}
func (msg MsgSend) GetSigners() []sdk.AccAddress {
return []sdk.AccAddress{msg.From}
}
```
@ -277,7 +277,7 @@ Coins](https://godoc.org/github.com/cosmos/cosmos-sdk/types#Coins).
Now we're ready to handle the two parts of the MsgSend:
```go
func handleFrom(store sdk.KVStore, from sdk.Address, amt sdk.Coins) sdk.Result {
func handleFrom(store sdk.KVStore, from sdk.AccAddress, amt sdk.Coins) sdk.Result {
// Get sender account from the store.
accBytes := store.Get(from)
if accBytes == nil {
@ -315,7 +315,7 @@ func handleFrom(store sdk.KVStore, from sdk.Address, amt sdk.Coins) sdk.Result {
return sdk.Result{}
}
func handleTo(store sdk.KVStore, to sdk.Address, amt sdk.Coins) sdk.Result {
func handleTo(store sdk.KVStore, to sdk.AccAddress, amt sdk.Coins) sdk.Result {
// Add msg amount to receiver account
accBytes := store.Get(to)
var acc appAccount

View File

@ -22,8 +22,8 @@ Let's introduce a new message type for issuing coins:
// MsgIssue to allow a registered issuer
// to issue new coins.
type MsgIssue struct {
Issuer sdk.Address
Receiver sdk.Address
Issuer sdk.AccAddress
Receiver sdk.AccAddress
Coin sdk.Coin
}
@ -71,7 +71,7 @@ func handleMsgIssue(keyIssue *sdk.KVStoreKey, keyAcc *sdk.KVStoreKey) sdk.Handle
}
}
func handleIssuer(store sdk.KVStore, issuer sdk.Address, coin sdk.Coin) sdk.Result {
func handleIssuer(store sdk.KVStore, issuer sdk.AccAddress, coin sdk.Coin) sdk.Result {
// the issuer address is stored directly under the coin denomination
denom := []byte(coin.Denom)
infoBytes := store.Get(denom)
@ -95,7 +95,7 @@ func handleIssuer(store sdk.KVStore, issuer sdk.Address, coin sdk.Coin) sdk.Resu
// coinInfo stores meta data about a coin
type coinInfo struct {
Issuer sdk.Address `json:"issuer"`
Issuer sdk.AccAddress `json:"issuer"`
}
```

View File

@ -46,8 +46,8 @@ The `Account` interface captures this account model with getters and setters:
// Account is a standard account using a sequence number for replay protection
// and a pubkey for authentication.
type Account interface {
GetAddress() sdk.Address
SetAddress(sdk.Address) error // errors if already set.
GetAddress() sdk.AccAddress
SetAddress(sdk.AccAddress) error // errors if already set.
GetPubKey() crypto.PubKey // can return nil.
SetPubKey(crypto.PubKey) error
@ -76,11 +76,11 @@ The default implementation of `Account` is the `BaseAccount`:
// Extend this by embedding this in your AppAccount.
// See the examples/basecoin/types/account.go for an example.
type BaseAccount struct {
Address sdk.Address `json:"address"`
Coins sdk.Coins `json:"coins"`
PubKey crypto.PubKey `json:"public_key"`
AccountNumber int64 `json:"account_number"`
Sequence int64 `json:"sequence"`
Address sdk.AccAddress `json:"address"`
Coins sdk.Coins `json:"coins"`
PubKey crypto.PubKey `json:"public_key"`
AccountNumber int64 `json:"account_number"`
Sequence int64 `json:"sequence"`
}
```
@ -260,7 +260,7 @@ The PubKey is required for signature verification, but it is only required in
the StdSignature once. From that point on, it will be stored in the account.
The fee is paid by the first address returned by `msg.GetSigners()` for the first `Msg`,
as provided by the `FeePayer(tx Tx) sdk.Address` function.
as provided by the `FeePayer(tx Tx) sdk.AccAddress` function.
## CoinKeeper

View File

@ -51,13 +51,13 @@ var _ sdk.Msg = MsgSend{}
// MsgSend to send coins from Input to Output
type MsgSend struct {
From sdk.Address `json:"from"`
To sdk.Address `json:"to"`
Amount sdk.Coins `json:"amount"`
From sdk.AccAddress `json:"from"`
To sdk.AccAddress `json:"to"`
Amount sdk.Coins `json:"amount"`
}
// NewMsgSend
func NewMsgSend(from, to sdk.Address, amt sdk.Coins) MsgSend {
func NewMsgSend(from, to sdk.AccAddress, amt sdk.Coins) MsgSend {
return MsgSend{from, to, amt}
}
@ -89,8 +89,8 @@ func (msg MsgSend) GetSignBytes() []byte {
}
// Implements Msg. Return the signer.
func (msg MsgSend) GetSigners() []sdk.Address {
return []sdk.Address{msg.From}
func (msg MsgSend) GetSigners() []sdk.AccAddress {
return []sdk.AccAddress{msg.From}
}
// Returns the sdk.Tags for the message
@ -136,7 +136,7 @@ func handleMsgSend(key *sdk.KVStoreKey) sdk.Handler {
}
// Convenience Handlers
func handleFrom(store sdk.KVStore, from sdk.Address, amt sdk.Coins) sdk.Result {
func handleFrom(store sdk.KVStore, from sdk.AccAddress, amt sdk.Coins) sdk.Result {
// Get sender account from the store.
accBytes := store.Get(from)
if accBytes == nil {
@ -174,7 +174,7 @@ func handleFrom(store sdk.KVStore, from sdk.Address, amt sdk.Coins) sdk.Result {
return sdk.Result{}
}
func handleTo(store sdk.KVStore, to sdk.Address, amt sdk.Coins) sdk.Result {
func handleTo(store sdk.KVStore, to sdk.AccAddress, amt sdk.Coins) sdk.Result {
// Add msg amount to receiver account
accBytes := store.Get(to)
var acc appAccount

View File

@ -68,8 +68,8 @@ func NewApp2(logger log.Logger, db dbm.DB) *bapp.BaseApp {
// MsgIssue to allow a registered issuer
// to issue new coins.
type MsgIssue struct {
Issuer sdk.Address
Receiver sdk.Address
Issuer sdk.AccAddress
Receiver sdk.AccAddress
Coin sdk.Coin
}
@ -104,8 +104,8 @@ func (msg MsgIssue) GetSignBytes() []byte {
}
// Implements Msg. Return the signer.
func (msg MsgIssue) GetSigners() []sdk.Address {
return []sdk.Address{msg.Issuer}
func (msg MsgIssue) GetSigners() []sdk.AccAddress {
return []sdk.AccAddress{msg.Issuer}
}
// Returns the sdk.Tags for the message
@ -146,7 +146,7 @@ func handleMsgIssue(keyIssue *sdk.KVStoreKey, keyAcc *sdk.KVStoreKey) sdk.Handle
}
}
func handleIssuer(store sdk.KVStore, issuer sdk.Address, coin sdk.Coin) sdk.Result {
func handleIssuer(store sdk.KVStore, issuer sdk.AccAddress, coin sdk.Coin) sdk.Result {
// the issuer address is stored directly under the coin denomination
denom := []byte(coin.Denom)
infoBytes := store.Get(denom)
@ -170,7 +170,7 @@ func handleIssuer(store sdk.KVStore, issuer sdk.Address, coin sdk.Coin) sdk.Resu
// coinInfo stores meta data about a coin
type coinInfo struct {
Issuer sdk.Address `json:"issuer"`
Issuer sdk.AccAddress `json:"issuer"`
}
//------------------------------------------------------------------

View File

@ -61,8 +61,8 @@ type GenesisState struct {
// GenesisAccount doesn't need pubkey or sequence
type GenesisAccount struct {
Address sdk.Address `json:"address"`
Coins sdk.Coins `json:"coins"`
Address sdk.AccAddress `json:"address"`
Coins sdk.Coins `json:"coins"`
}
// Converts GenesisAccount to auth.BaseAccount for storage in account store

View File

@ -43,7 +43,7 @@ func TestGenesis(t *testing.T) {
// construct a pubkey and an address for the test account
pubkey := crypto.GenPrivKeyEd25519().PubKey()
addr := pubkey.Address()
addr := sdk.AccAddress(pubkey.Address())
// construct some test coins
coins, err := sdk.ParseCoins("77foocoin,99barcoin")

View File

@ -54,9 +54,9 @@ type GenesisState struct {
// GenesisAccount reflects a genesis account the application expects in it's
// genesis state.
type GenesisAccount struct {
Name string `json:"name"`
Address sdk.Address `json:"address"`
Coins sdk.Coins `json:"coins"`
Name string `json:"name"`
Address sdk.AccAddress `json:"address"`
Coins sdk.Coins `json:"coins"`
}
// NewGenesisAccount returns a reference to a new GenesisAccount given an

View File

@ -47,7 +47,7 @@ func TestGenesis(t *testing.T) {
// Construct some genesis bytes to reflect democoin/types/AppAccount
pk := crypto.GenPrivKeyEd25519().PubKey()
addr := pk.Address()
addr := sdk.AccAddress(pk.Address())
coins, err := sdk.ParseCoins("77foocoin,99barcoin")
require.Nil(t, err)
baseAcc := auth.BaseAccount{

View File

@ -9,7 +9,7 @@ import (
// Validator implements sdk.Validator
type Validator struct {
Address sdk.Address
Address sdk.AccAddress
Power sdk.Rat
}
@ -19,7 +19,7 @@ func (v Validator) GetStatus() sdk.BondStatus {
}
// Implements sdk.Validator
func (v Validator) GetOwner() sdk.Address {
func (v Validator) GetOwner() sdk.AccAddress {
return v.Address
}
@ -73,7 +73,7 @@ func (vs *ValidatorSet) IterateValidatorsBonded(ctx sdk.Context, fn func(index i
}
// Validator implements sdk.ValidatorSet
func (vs *ValidatorSet) Validator(ctx sdk.Context, addr sdk.Address) sdk.Validator {
func (vs *ValidatorSet) Validator(ctx sdk.Context, addr sdk.AccAddress) sdk.Validator {
for _, val := range vs.Validators {
if bytes.Equal(val.Address, addr) {
return val
@ -97,7 +97,7 @@ func (vs *ValidatorSet) AddValidator(val Validator) {
}
// Helper function for removing exsting validator
func (vs *ValidatorSet) RemoveValidator(addr sdk.Address) {
func (vs *ValidatorSet) RemoveValidator(addr sdk.AccAddress) {
pos := -1
for i, val := range vs.Validators {
if bytes.Equal(val.Address, addr) {

View File

@ -51,9 +51,9 @@ type GenesisState struct {
// GenesisAccount doesn't need pubkey or sequence
type GenesisAccount struct {
Name string `json:"name"`
Address sdk.Address `json:"address"`
Coins sdk.Coins `json:"coins"`
Name string `json:"name"`
Address sdk.AccAddress `json:"address"`
Coins sdk.Coins `json:"coins"`
}
func NewGenesisAccount(aa *AppAccount) *GenesisAccount {

View File

@ -37,7 +37,7 @@ func NewValidatorSet(cdc *wire.Codec, key sdk.KVStoreGetter, valset sdk.Validato
}
// Implements sdk.ValidatorSet
func (valset ValidatorSet) Validator(ctx sdk.Context, addr sdk.Address) (res sdk.Validator) {
func (valset ValidatorSet) Validator(ctx sdk.Context, addr sdk.AccAddress) (res sdk.Validator) {
store := valset.key.KVStore(ctx)
base := store.Get(GetBaseKey(addr))
res = valset.ValidatorSet.Validator(ctx, base)
@ -47,23 +47,23 @@ func (valset ValidatorSet) Validator(ctx sdk.Context, addr sdk.Address) (res sdk
return
}
// GetBaseKey :: sdk.Address -> sdk.Address
func GetBaseKey(addr sdk.Address) []byte {
// GetBaseKey :: sdk.AccAddress -> sdk.AccAddress
func GetBaseKey(addr sdk.AccAddress) []byte {
return append([]byte{0x00}, addr...)
}
// GetAssocPrefix :: sdk.Address -> (sdk.Address -> byte)
func GetAssocPrefix(base sdk.Address) []byte {
// GetAssocPrefix :: sdk.AccAddress -> (sdk.AccAddress -> byte)
func GetAssocPrefix(base sdk.AccAddress) []byte {
return append([]byte{0x01}, base...)
}
// GetAssocKey :: (sdk.Address, sdk.Address) -> byte
func GetAssocKey(base sdk.Address, assoc sdk.Address) []byte {
// GetAssocKey :: (sdk.AccAddress, sdk.AccAddress) -> byte
func GetAssocKey(base sdk.AccAddress, assoc sdk.AccAddress) []byte {
return append(append([]byte{0x01}, base...), assoc...)
}
// Associate associates new address with validator address
func (valset ValidatorSet) Associate(ctx sdk.Context, base sdk.Address, assoc sdk.Address) bool {
func (valset ValidatorSet) Associate(ctx sdk.Context, base sdk.AccAddress, assoc sdk.AccAddress) bool {
if len(base) != valset.addrLen || len(assoc) != valset.addrLen {
return false
}
@ -78,7 +78,7 @@ func (valset ValidatorSet) Associate(ctx sdk.Context, base sdk.Address, assoc sd
}
// Dissociate removes association between addresses
func (valset ValidatorSet) Dissociate(ctx sdk.Context, base sdk.Address, assoc sdk.Address) bool {
func (valset ValidatorSet) Dissociate(ctx sdk.Context, base sdk.AccAddress, assoc sdk.AccAddress) bool {
if len(base) != valset.addrLen || len(assoc) != valset.addrLen {
return false
}
@ -93,9 +93,9 @@ func (valset ValidatorSet) Dissociate(ctx sdk.Context, base sdk.Address, assoc s
}
// Associations returns all associated addresses with a validator
func (valset ValidatorSet) Associations(ctx sdk.Context, base sdk.Address) (res []sdk.Address) {
func (valset ValidatorSet) Associations(ctx sdk.Context, base sdk.AccAddress) (res []sdk.AccAddress) {
store := valset.key.KVStore(ctx)
res = make([]sdk.Address, valset.maxAssoc)
res = make([]sdk.AccAddress, valset.maxAssoc)
iter := sdk.KVStorePrefixIterator(store, GetAssocPrefix(base))
i := 0
for ; iter.Valid(); iter.Next() {

View File

@ -15,7 +15,7 @@ import (
var (
priv1 = crypto.GenPrivKeyEd25519()
pubKey = priv1.PubKey()
addr1 = pubKey.Address()
addr1 = sdk.AccAddress(pubKey.Address())
quizMsg1 = MsgQuiz{
Sender: addr1,

View File

@ -11,7 +11,7 @@ import (
// a really cool msg type, these fields are can be entirely arbitrary and
// custom to your message
type MsgSetTrend struct {
Sender sdk.Address
Sender sdk.AccAddress
Cool string
}
@ -21,7 +21,7 @@ type Genesis struct {
}
// new cool message
func NewMsgSetTrend(sender sdk.Address, cool string) MsgSetTrend {
func NewMsgSetTrend(sender sdk.AccAddress, cool string) MsgSetTrend {
return MsgSetTrend{
Sender: sender,
Cool: cool,
@ -32,8 +32,8 @@ func NewMsgSetTrend(sender sdk.Address, cool string) MsgSetTrend {
var _ sdk.Msg = MsgSetTrend{}
// nolint
func (msg MsgSetTrend) Type() string { return "cool" }
func (msg MsgSetTrend) GetSigners() []sdk.Address { return []sdk.Address{msg.Sender} }
func (msg MsgSetTrend) Type() string { return "cool" }
func (msg MsgSetTrend) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Sender} }
func (msg MsgSetTrend) String() string {
return fmt.Sprintf("MsgSetTrend{Sender: %v, Cool: %v}", msg.Sender, msg.Cool)
}
@ -66,12 +66,12 @@ func (msg MsgSetTrend) GetSignBytes() []byte {
// A message type to quiz how cool you are. these fields are can be entirely
// arbitrary and custom to your message
type MsgQuiz struct {
Sender sdk.Address
Sender sdk.AccAddress
CoolAnswer string
}
// New cool message
func NewMsgQuiz(sender sdk.Address, coolerthancool string) MsgQuiz {
func NewMsgQuiz(sender sdk.AccAddress, coolerthancool string) MsgQuiz {
return MsgQuiz{
Sender: sender,
CoolAnswer: coolerthancool,
@ -82,8 +82,8 @@ func NewMsgQuiz(sender sdk.Address, coolerthancool string) MsgQuiz {
var _ sdk.Msg = MsgQuiz{}
// nolint
func (msg MsgQuiz) Type() string { return "cool" }
func (msg MsgQuiz) GetSigners() []sdk.Address { return []sdk.Address{msg.Sender} }
func (msg MsgQuiz) Type() string { return "cool" }
func (msg MsgQuiz) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Sender} }
func (msg MsgQuiz) String() string {
return fmt.Sprintf("MsgQuiz{Sender: %v, CoolAnswer: %v}", msg.Sender, msg.CoolAnswer)
}

View File

@ -16,7 +16,7 @@ const (
// Error constructors
// ErrNotValidator called when the signer of a Msg is not a validator
func ErrNotValidator(codespace sdk.CodespaceType, address sdk.Address) sdk.Error {
func ErrNotValidator(codespace sdk.CodespaceType, address sdk.AccAddress) sdk.Error {
return sdk.NewError(codespace, CodeNotValidator, address.String())
}

View File

@ -84,14 +84,14 @@ func (keeper Keeper) setInfo(ctx sdk.Context, p Payload, info Info) {
store.Set(key, bz)
}
func (keeper Keeper) sign(ctx sdk.Context, p Payload, signer sdk.Address) {
func (keeper Keeper) sign(ctx sdk.Context, p Payload, signer sdk.AccAddress) {
store := keeper.key.KVStore(ctx)
key := GetSignKey(p, signer, keeper.cdc)
store.Set(key, signer)
}
func (keeper Keeper) signed(ctx sdk.Context, p Payload, signer sdk.Address) bool {
func (keeper Keeper) signed(ctx sdk.Context, p Payload, signer sdk.AccAddress) bool {
store := keeper.key.KVStore(ctx)
key := GetSignKey(p, signer, keeper.cdc)

View File

@ -18,6 +18,6 @@ func GetSignPrefix(p Payload, cdc *wire.Codec) []byte {
}
// GetSignKey returns the key for sign
func GetSignKey(p Payload, signer sdk.Address, cdc *wire.Codec) []byte {
func GetSignKey(p Payload, signer sdk.AccAddress, cdc *wire.Codec) []byte {
return append(GetSignPrefix(p, cdc), signer...)
}

View File

@ -9,7 +9,7 @@ import (
// Msg - struct for voting on payloads
type Msg struct {
Payload
Signer sdk.Address
Signer sdk.AccAddress
}
// GetSignBytes implements sdk.Msg
@ -22,8 +22,8 @@ func (msg Msg) GetSignBytes() []byte {
}
// GetSigners implements sdk.Msg
func (msg Msg) GetSigners() []sdk.Address {
return []sdk.Address{msg.Signer}
func (msg Msg) GetSigners() []sdk.AccAddress {
return []sdk.AccAddress{msg.Signer}
}
// Payload defines inner data for actual execution

View File

@ -16,7 +16,7 @@ import (
var (
priv1 = crypto.GenPrivKeyEd25519()
addr1 = priv1.PubKey().Address()
addr1 = sdk.AccAddress(priv1.PubKey().Address())
)
// initialize the mock application for this module

View File

@ -27,7 +27,7 @@ func TestPowHandler(t *testing.T) {
handler := keeper.Handler
addr := sdk.Address([]byte("sender"))
addr := sdk.AccAddress([]byte("sender"))
count := uint64(1)
difficulty := uint64(2)

View File

@ -124,7 +124,7 @@ func (k Keeper) CheckValid(ctx sdk.Context, difficulty uint64, count uint64) (ui
}
// Add some coins for a POW well done
func (k Keeper) ApplyValid(ctx sdk.Context, sender sdk.Address, newDifficulty uint64, newCount uint64) sdk.Error {
func (k Keeper) ApplyValid(ctx sdk.Context, sender sdk.AccAddress, newDifficulty uint64, newCount uint64) sdk.Error {
_, _, ckErr := k.ck.AddCoins(ctx, sender, []sdk.Coin{sdk.NewCoin(k.config.Denomination, k.config.Reward)})
if ckErr != nil {
return ckErr

View File

@ -10,12 +10,12 @@ import (
)
// generate the mine message
func GenerateMsgMine(sender sdk.Address, count uint64, difficulty uint64) MsgMine {
func GenerateMsgMine(sender sdk.AccAddress, count uint64, difficulty uint64) MsgMine {
nonce, hash := mine(sender, count, difficulty)
return NewMsgMine(sender, difficulty, count, nonce, hash)
}
func hash(sender sdk.Address, count uint64, nonce uint64) []byte {
func hash(sender sdk.AccAddress, count uint64, nonce uint64) []byte {
var bytes []byte
bytes = append(bytes, []byte(sender)...)
countBytes := strconv.FormatUint(count, 16)
@ -30,7 +30,7 @@ func hash(sender sdk.Address, count uint64, nonce uint64) []byte {
return ret[:16]
}
func mine(sender sdk.Address, count uint64, difficulty uint64) (uint64, []byte) {
func mine(sender sdk.AccAddress, count uint64, difficulty uint64) (uint64, []byte) {
target := math.MaxUint64 / difficulty
for nonce := uint64(0); ; nonce++ {
hash := hash(sender, count, nonce)

View File

@ -15,26 +15,26 @@ import (
// MsgMine - mine some coins with PoW
type MsgMine struct {
Sender sdk.Address `json:"sender"`
Difficulty uint64 `json:"difficulty"`
Count uint64 `json:"count"`
Nonce uint64 `json:"nonce"`
Proof []byte `json:"proof"`
Sender sdk.AccAddress `json:"sender"`
Difficulty uint64 `json:"difficulty"`
Count uint64 `json:"count"`
Nonce uint64 `json:"nonce"`
Proof []byte `json:"proof"`
}
// enforce the msg type at compile time
var _ sdk.Msg = MsgMine{}
// NewMsgMine - construct mine message
func NewMsgMine(sender sdk.Address, difficulty uint64, count uint64, nonce uint64, proof []byte) MsgMine {
func NewMsgMine(sender sdk.AccAddress, difficulty uint64, count uint64, nonce uint64, proof []byte) MsgMine {
return MsgMine{sender, difficulty, count, nonce, proof}
}
// nolint
func (msg MsgMine) Type() string { return "pow" }
func (msg MsgMine) GetSigners() []sdk.Address { return []sdk.Address{msg.Sender} }
func (msg MsgMine) Type() string { return "pow" }
func (msg MsgMine) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Sender} }
func (msg MsgMine) String() string {
return fmt.Sprintf("MsgMine{Sender: %v, Difficulty: %d, Count: %d, Nonce: %d, Proof: %s}", msg.Sender, msg.Difficulty, msg.Count, msg.Nonce, msg.Proof)
return fmt.Sprintf("MsgMine{Sender: %s, Difficulty: %d, Count: %d, Nonce: %d, Proof: %s}", msg.Sender, msg.Difficulty, msg.Count, msg.Nonce, msg.Proof)
}
// validate the mine message

View File

@ -10,21 +10,21 @@ import (
)
func TestNewMsgMine(t *testing.T) {
addr := sdk.Address([]byte("sender"))
addr := sdk.AccAddress([]byte("sender"))
msg := MsgMine{addr, 0, 0, 0, []byte("")}
equiv := NewMsgMine(addr, 0, 0, 0, []byte(""))
require.Equal(t, msg, equiv, "%s != %s", msg, equiv)
}
func TestMsgMineType(t *testing.T) {
addr := sdk.Address([]byte("sender"))
addr := sdk.AccAddress([]byte("sender"))
msg := MsgMine{addr, 0, 0, 0, []byte("")}
require.Equal(t, msg.Type(), "pow")
}
func TestMsgMineValidation(t *testing.T) {
addr := sdk.Address([]byte("sender"))
otherAddr := sdk.Address([]byte("another"))
addr := sdk.AccAddress([]byte("sender"))
otherAddr := sdk.AccAddress([]byte("another"))
count := uint64(0)
for difficulty := uint64(1); difficulty < 1000; difficulty += 100 {
@ -52,21 +52,21 @@ func TestMsgMineValidation(t *testing.T) {
}
func TestMsgMineString(t *testing.T) {
addr := sdk.Address([]byte("sender"))
addr := sdk.AccAddress([]byte("sender"))
msg := MsgMine{addr, 0, 0, 0, []byte("abc")}
res := msg.String()
require.Equal(t, res, "MsgMine{Sender: 73656E646572, Difficulty: 0, Count: 0, Nonce: 0, Proof: abc}")
require.Equal(t, res, "MsgMine{Sender: cosmosaccaddr1wdjkuer9wg4wml9c, Difficulty: 0, Count: 0, Nonce: 0, Proof: abc}")
}
func TestMsgMineGetSignBytes(t *testing.T) {
addr := sdk.Address([]byte("sender"))
addr := sdk.AccAddress([]byte("sender"))
msg := MsgMine{addr, 1, 1, 1, []byte("abc")}
res := msg.GetSignBytes()
require.Equal(t, string(res), `{"count":1,"difficulty":1,"nonce":1,"proof":"YWJj","sender":"73656E646572"}`)
require.Equal(t, string(res), `{"count":1,"difficulty":1,"nonce":1,"proof":"YWJj","sender":"cosmosaccaddr1wdjkuer9wg4wml9c"}`)
}
func TestMsgMineGetSigners(t *testing.T) {
addr := sdk.Address([]byte("sender"))
addr := sdk.AccAddress([]byte("sender"))
msg := MsgMine{addr, 1, 1, 1, []byte("abc")}
res := msg.GetSigners()
require.Equal(t, fmt.Sprintf("%v", res), "[73656E646572]")

View File

@ -32,7 +32,7 @@ func NewKeeper(key sdk.StoreKey, coinKeeper bank.Keeper, codespace sdk.Codespace
}
}
func (k Keeper) getBondInfo(ctx sdk.Context, addr sdk.Address) bondInfo {
func (k Keeper) getBondInfo(ctx sdk.Context, addr sdk.AccAddress) bondInfo {
store := ctx.KVStore(k.key)
bz := store.Get(addr)
if bz == nil {
@ -46,7 +46,7 @@ func (k Keeper) getBondInfo(ctx sdk.Context, addr sdk.Address) bondInfo {
return bi
}
func (k Keeper) setBondInfo(ctx sdk.Context, addr sdk.Address, bi bondInfo) {
func (k Keeper) setBondInfo(ctx sdk.Context, addr sdk.AccAddress, bi bondInfo) {
store := ctx.KVStore(k.key)
bz, err := k.cdc.MarshalBinary(bi)
if err != nil {
@ -55,13 +55,13 @@ func (k Keeper) setBondInfo(ctx sdk.Context, addr sdk.Address, bi bondInfo) {
store.Set(addr, bz)
}
func (k Keeper) deleteBondInfo(ctx sdk.Context, addr sdk.Address) {
func (k Keeper) deleteBondInfo(ctx sdk.Context, addr sdk.AccAddress) {
store := ctx.KVStore(k.key)
store.Delete(addr)
}
// register a bond with the keeper
func (k Keeper) Bond(ctx sdk.Context, addr sdk.Address, pubKey crypto.PubKey, stake sdk.Coin) (int64, sdk.Error) {
func (k Keeper) Bond(ctx sdk.Context, addr sdk.AccAddress, pubKey crypto.PubKey, stake sdk.Coin) (int64, sdk.Error) {
if stake.Denom != stakingToken {
return 0, ErrIncorrectStakingToken(k.codespace)
}
@ -86,7 +86,7 @@ func (k Keeper) Bond(ctx sdk.Context, addr sdk.Address, pubKey crypto.PubKey, st
}
// register an unbond with the keeper
func (k Keeper) Unbond(ctx sdk.Context, addr sdk.Address) (crypto.PubKey, int64, sdk.Error) {
func (k Keeper) Unbond(ctx sdk.Context, addr sdk.AccAddress) (crypto.PubKey, int64, sdk.Error) {
bi := k.getBondInfo(ctx, addr)
if bi.isEmpty() {
return nil, 0, ErrInvalidUnbond(k.codespace)
@ -105,7 +105,7 @@ func (k Keeper) Unbond(ctx sdk.Context, addr sdk.Address) (crypto.PubKey, int64,
// FOR TESTING PURPOSES -------------------------------------------------
func (k Keeper) bondWithoutCoins(ctx sdk.Context, addr sdk.Address, pubKey crypto.PubKey, stake sdk.Coin) (int64, sdk.Error) {
func (k Keeper) bondWithoutCoins(ctx sdk.Context, addr sdk.AccAddress, pubKey crypto.PubKey, stake sdk.Coin) (int64, sdk.Error) {
if stake.Denom != stakingToken {
return 0, ErrIncorrectStakingToken(k.codespace)
}
@ -124,7 +124,7 @@ func (k Keeper) bondWithoutCoins(ctx sdk.Context, addr sdk.Address, pubKey crypt
return bi.Power, nil
}
func (k Keeper) unbondWithoutCoins(ctx sdk.Context, addr sdk.Address) (crypto.PubKey, int64, sdk.Error) {
func (k Keeper) unbondWithoutCoins(ctx sdk.Context, addr sdk.AccAddress) (crypto.PubKey, int64, sdk.Error) {
bi := k.getBondInfo(ctx, addr)
if bi.isEmpty() {
return nil, 0, ErrInvalidUnbond(k.codespace)

View File

@ -38,7 +38,7 @@ func TestKeeperGetSet(t *testing.T) {
accountMapper := auth.NewAccountMapper(cdc, authKey, &auth.BaseAccount{})
stakeKeeper := NewKeeper(capKey, bank.NewKeeper(accountMapper), DefaultCodespace)
ctx := sdk.NewContext(ms, abci.Header{}, false, log.NewNopLogger())
addr := sdk.Address([]byte("some-address"))
addr := sdk.AccAddress([]byte("some-address"))
bi := stakeKeeper.getBondInfo(ctx, addr)
require.Equal(t, bi, bondInfo{})
@ -68,7 +68,7 @@ func TestBonding(t *testing.T) {
accountMapper := auth.NewAccountMapper(cdc, authKey, &auth.BaseAccount{})
coinKeeper := bank.NewKeeper(accountMapper)
stakeKeeper := NewKeeper(capKey, coinKeeper, DefaultCodespace)
addr := sdk.Address([]byte("some-address"))
addr := sdk.AccAddress([]byte("some-address"))
privKey := crypto.GenPrivKeyEd25519()
pubKey := privKey.PubKey()

View File

@ -12,12 +12,12 @@ import (
// simple bond message
type MsgBond struct {
Address sdk.Address `json:"address"`
Stake sdk.Coin `json:"coins"`
PubKey crypto.PubKey `json:"pub_key"`
Address sdk.AccAddress `json:"address"`
Stake sdk.Coin `json:"coins"`
PubKey crypto.PubKey `json:"pub_key"`
}
func NewMsgBond(addr sdk.Address, stake sdk.Coin, pubKey crypto.PubKey) MsgBond {
func NewMsgBond(addr sdk.AccAddress, stake sdk.Coin, pubKey crypto.PubKey) MsgBond {
return MsgBond{
Address: addr,
Stake: stake,
@ -26,8 +26,8 @@ func NewMsgBond(addr sdk.Address, stake sdk.Coin, pubKey crypto.PubKey) MsgBond
}
//nolint
func (msg MsgBond) Type() string { return moduleName } //TODO update "stake/createvalidator"
func (msg MsgBond) GetSigners() []sdk.Address { return []sdk.Address{msg.Address} }
func (msg MsgBond) Type() string { return moduleName } //TODO update "stake/createvalidator"
func (msg MsgBond) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Address} }
// basic validation of the bond message
func (msg MsgBond) ValidateBasic() sdk.Error {
@ -55,19 +55,19 @@ func (msg MsgBond) GetSignBytes() []byte {
// simple unbond message
type MsgUnbond struct {
Address sdk.Address `json:"address"`
Address sdk.AccAddress `json:"address"`
}
func NewMsgUnbond(addr sdk.Address) MsgUnbond {
func NewMsgUnbond(addr sdk.AccAddress) MsgUnbond {
return MsgUnbond{
Address: addr,
}
}
//nolint
func (msg MsgUnbond) Type() string { return moduleName } //TODO update "stake/createvalidator"
func (msg MsgUnbond) GetSigners() []sdk.Address { return []sdk.Address{msg.Address} }
func (msg MsgUnbond) ValidateBasic() sdk.Error { return nil }
func (msg MsgUnbond) Type() string { return moduleName } //TODO update "stake/createvalidator"
func (msg MsgUnbond) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Address} }
func (msg MsgUnbond) ValidateBasic() sdk.Error { return nil }
// get unbond message sign bytes
func (msg MsgUnbond) GetSignBytes() []byte {

View File

@ -16,8 +16,8 @@ func TestBondMsgValidation(t *testing.T) {
valid bool
msgBond MsgBond
}{
{true, NewMsgBond(sdk.Address{}, sdk.NewCoin("mycoin", 5), privKey.PubKey())},
{false, NewMsgBond(sdk.Address{}, sdk.NewCoin("mycoin", 0), privKey.PubKey())},
{true, NewMsgBond(sdk.AccAddress{}, sdk.NewCoin("mycoin", 5), privKey.PubKey())},
{false, NewMsgBond(sdk.AccAddress{}, sdk.NewCoin("mycoin", 0), privKey.PubKey())},
}
for i, tc := range cases {

View File

@ -35,7 +35,7 @@ func (tx kvstoreTx) ValidateBasic() sdk.Error {
return nil
}
func (tx kvstoreTx) GetSigners() []sdk.Address {
func (tx kvstoreTx) GetSigners() []sdk.AccAddress {
return nil
}

View File

@ -376,22 +376,22 @@ var DefaultAppInit = AppInit{
// simple genesis tx
type SimpleGenTx struct {
Addr string `json:"addr"`
Addr sdk.AccAddress `json:"addr"`
}
// Generate a genesis transaction
func SimpleAppGenTx(cdc *wire.Codec, pk crypto.PubKey, genTxConfig serverconfig.GenTx) (
appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) {
var bech32Addr string
var addr sdk.AccAddress
var secret string
bech32Addr, secret, err = GenerateCoinKey()
addr, secret, err = GenerateCoinKey()
if err != nil {
return
}
var bz []byte
simpleGenTx := SimpleGenTx{bech32Addr}
simpleGenTx := SimpleGenTx{addr}
bz, err = cdc.MarshalJSON(simpleGenTx)
if err != nil {
return
@ -444,7 +444,7 @@ func SimpleAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (appState j
// GenerateCoinKey returns the address of a public key, along with the secret
// phrase to recover the private key.
func GenerateCoinKey() (string, string, error) {
func GenerateCoinKey() (sdk.AccAddress, string, error) {
// construct an in-memory key store
keybase := keys.New(
@ -454,35 +454,35 @@ func GenerateCoinKey() (string, string, error) {
// generate a private key, with recovery phrase
info, secret, err := keybase.CreateMnemonic("name", keys.English, "pass", keys.Secp256k1)
if err != nil {
return "", "", err
return sdk.AccAddress([]byte{}), "", err
}
addr := info.GetPubKey().Address()
return sdk.MustBech32ifyAcc(sdk.Address(addr)), secret, nil
return sdk.AccAddress(addr), secret, nil
}
// GenerateSaveCoinKey returns the address of a public key, along with the secret
// phrase to recover the private key.
func GenerateSaveCoinKey(clientRoot, keyName, keyPass string, overwrite bool) (string, string, error) {
func GenerateSaveCoinKey(clientRoot, keyName, keyPass string, overwrite bool) (sdk.AccAddress, string, error) {
// get the keystore from the client
keybase, err := clkeys.GetKeyBaseFromDir(clientRoot)
if err != nil {
return "", "", err
return sdk.AccAddress([]byte{}), "", err
}
// ensure no overwrite
if !overwrite {
_, err := keybase.Get(keyName)
if err == nil {
return "", "", errors.New("key already exists, overwrite is disabled")
return sdk.AccAddress([]byte{}), "", errors.New("key already exists, overwrite is disabled")
}
}
// generate a private key, with recovery phrase
info, secret, err := keybase.CreateMnemonic(keyName, keys.English, keyPass, keys.Secp256k1)
if err != nil {
return "", "", err
return sdk.AccAddress([]byte{}), "", err
}
addr := info.GetPubKey().Address()
return sdk.MustBech32ifyAcc(sdk.Address(addr)), secret, nil
return sdk.AccAddress(addr), secret, nil
}

View File

@ -48,7 +48,7 @@ func (tx kvstoreTx) ValidateBasic() sdk.Error {
return nil
}
func (tx kvstoreTx) GetSigners() []sdk.Address {
func (tx kvstoreTx) GetSigners() []sdk.AccAddress {
return nil
}

View File

@ -60,10 +60,11 @@ Example:
}
func testnetWithConfig(config *cfg.Config, cdc *wire.Codec, appInit AppInit) error {
outDir := viper.GetString(outputDir)
numValidators := viper.GetInt(nValidators)
// Generate private key, node ID, initial transaction
for i := 0; i < viper.GetInt(nValidators); i++ {
for i := 0; i < numValidators; i++ {
nodeDirName := fmt.Sprintf("%s%d", viper.GetString(nodeDirPrefix), i)
nodeDir := filepath.Join(outDir, nodeDirName, "gaiad")
clientDir := filepath.Join(outDir, nodeDirName, "gaiacli")
@ -83,18 +84,9 @@ func testnetWithConfig(config *cfg.Config, cdc *wire.Codec, appInit AppInit) err
}
config.Moniker = nodeDirName
ip := viper.GetString(startingIPAddress)
if len(ip) == 0 {
ip, err = externalIP()
if err != nil {
return err
}
} else {
ip, err = calculateIP(ip, i)
if err != nil {
return err
}
ip, err := getIP(i)
if err != nil {
return err
}
genTxConfig := gc.GenTx{
@ -112,35 +104,22 @@ func testnetWithConfig(config *cfg.Config, cdc *wire.Codec, appInit AppInit) err
// Save private key seed words
name := fmt.Sprintf("%v.json", "key_seed")
writePath := filepath.Join(clientDir)
file := filepath.Join(writePath, name)
err = cmn.EnsureDir(writePath, 0700)
if err != nil {
return err
}
err = cmn.WriteFile(file, cliPrint, 0600)
err = writeFile(name, clientDir, cliPrint)
if err != nil {
return err
}
// Gather gentxs folder
name = fmt.Sprintf("%v.json", nodeDirName)
writePath = filepath.Join(gentxsDir)
file = filepath.Join(writePath, name)
err = cmn.EnsureDir(writePath, 0700)
err = writeFile(name, gentxsDir, genTxFile)
if err != nil {
return err
}
err = cmn.WriteFile(file, genTxFile, 0644)
if err != nil {
return err
}
}
// Generate genesis.json and config.toml
chainID := "chain-" + cmn.RandStr(6)
for i := 0; i < viper.GetInt(nValidators); i++ {
for i := 0; i < numValidators; i++ {
nodeDirName := fmt.Sprintf("%s%d", viper.GetString(nodeDirPrefix), i)
nodeDir := filepath.Join(outDir, nodeDirName, "gaiad")
@ -165,6 +144,36 @@ func testnetWithConfig(config *cfg.Config, cdc *wire.Codec, appInit AppInit) err
return nil
}
func getIP(i int) (ip string, err error) {
ip = viper.GetString(startingIPAddress)
if len(ip) == 0 {
ip, err = externalIP()
if err != nil {
return "", err
}
} else {
ip, err = calculateIP(ip, i)
if err != nil {
return "", err
}
}
return ip, nil
}
func writeFile(name string, dir string, contents []byte) error {
writePath := filepath.Join(dir)
file := filepath.Join(writePath, name)
err := cmn.EnsureDir(writePath, 0700)
if err != nil {
return err
}
err = cmn.WriteFile(file, contents, 0600)
if err != nil {
return err
}
return nil
}
func calculateIP(ip string, i int) (string, error) {
ipv4 := net.ParseIP(ip).To4()
if ipv4 == nil {

View File

@ -149,24 +149,15 @@ func externalIP() (string, error) {
return "", err
}
for _, iface := range ifaces {
if iface.Flags&net.FlagUp == 0 {
continue // interface down
}
if iface.Flags&net.FlagLoopback != 0 {
continue // loopback interface
if skipInterface(iface) {
continue
}
addrs, err := iface.Addrs()
if err != nil {
return "", err
}
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
ip := addrToIP(addr)
if ip == nil || ip.IsLoopback() {
continue
}
@ -179,3 +170,24 @@ func externalIP() (string, error) {
}
return "", errors.New("are you connected to the network?")
}
func skipInterface(iface net.Interface) bool {
if iface.Flags&net.FlagUp == 0 {
return true // interface down
}
if iface.Flags&net.FlagLoopback != 0 {
return true // loopback interface
}
return false
}
func addrToIP(addr net.Addr) net.IP {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
return ip
}

View File

@ -153,6 +153,20 @@ func (st *iavlStore) ReverseIterator(start, end []byte) Iterator {
return newIAVLIterator(st.tree.Tree(), start, end, false)
}
// Handle gatest the latest height, if height is 0
func getHeight(tree *iavl.VersionedTree, req abci.RequestQuery) int64 {
height := req.Height
if height == 0 {
latest := tree.Version64()
if tree.VersionExists(latest - 1) {
height = latest - 1
} else {
height = latest
}
}
return height
}
// Query implements ABCI interface, allows queries
//
// by default we will return from (latest height -1),
@ -167,24 +181,17 @@ func (st *iavlStore) Query(req abci.RequestQuery) (res abci.ResponseQuery) {
}
tree := st.tree
height := req.Height
if height == 0 {
latest := tree.Version64()
if tree.VersionExists(latest - 1) {
height = latest - 1
} else {
height = latest
}
}
// store the height we chose in the response
res.Height = height
// store the height we chose in the response, with 0 being changed to the
// latest height
res.Height = getHeight(tree, req)
switch req.Path {
case "/store", "/key": // Get by key
key := req.Data // Data holds the key bytes
res.Key = key
if req.Prove {
value, proof, err := tree.GetVersionedWithProof(key, height)
value, proof, err := tree.GetVersionedWithProof(key, res.Height)
if err != nil {
res.Log = err.Error()
break
@ -198,7 +205,7 @@ func (st *iavlStore) Query(req abci.RequestQuery) (res abci.ResponseQuery) {
}
res.Proof = p
} else {
_, res.Value = tree.GetVersioned(key, height)
_, res.Value = tree.GetVersioned(key, res.Height)
}
case "/subspace":
subspace := req.Data

View File

@ -12,6 +12,7 @@ INEFFASSIGN = github.com/gordonklaus/ineffassign
MISSPELL = github.com/client9/misspell/cmd/misspell
ERRCHECK = github.com/kisielk/errcheck
UNPARAM = mvdan.cc/unparam
GOCYCLO = github.com/alecthomas/gocyclo
DEP_CHECK := $(shell command -v dep 2> /dev/null)
GOLINT_CHECK := $(shell command -v golint 2> /dev/null)
@ -21,6 +22,7 @@ INEFFASSIGN_CHECK := $(shell command -v ineffassign 2> /dev/null)
MISSPELL_CHECK := $(shell command -v misspell 2> /dev/null)
ERRCHECK_CHECK := $(shell command -v errcheck 2> /dev/null)
UNPARAM_CHECK := $(shell command -v unparam 2> /dev/null)
GOCYCLO_CHECK := $(shell command -v gocyclo 2> /dev/null)
check_tools:
ifndef DEP_CHECK
@ -63,6 +65,11 @@ ifndef UNPARAM_CHECK
else
@echo "Found unparam in path."
endif
ifndef GOCYCLO_CHECK
@echo "No gocyclo in path. Install with 'make get_tools'."
else
@echo "Found gocyclo in path."
endif
get_tools:
ifdef DEP_CHECK
@ -113,6 +120,12 @@ else
@echo "Installing unparam"
go get -v $(UNPARAM)
endif
ifdef GOYCLO_CHECK
@echo "goyclo is already installed. Run 'make update_tools' to update."
else
@echo "Installing goyclo"
go get -v $(GOCYCLO)
endif
update_tools:
@echo "Updating dep"
@ -131,6 +144,8 @@ update_tools:
go get -u -v $(ERRCHECK)
@echo "Updating unparam"
go get -u -v $(UNPARAM)
@echo "Updating goyclo"
go get -u -v $(GOCYCLO)
# To avoid unintended conflicts with file names, always add to .PHONY
# unless there is a reason not to.

View File

@ -2,7 +2,8 @@
"Linters": {
"vet": "go tool vet -composites=false :PATH:LINE:MESSAGE"
},
"Enable": ["golint", "vet", "ineffassign", "unparam", "unconvert", "misspell"],
"Enable": ["golint", "vet", "ineffassign", "unparam", "unconvert", "misspell", "gocyclo"],
"Deadline": "500s",
"Vendor": true
"Vendor": true,
"Cyclo": 11
}

View File

@ -2,18 +2,15 @@ package types
import (
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/libs/bech32"
cmn "github.com/tendermint/tendermint/libs/common"
)
//Address is a go crypto-style Address
type Address = cmn.HexBytes
// nolint
// Bech32 prefixes
const (
// expected address length
AddrLen = 20
@ -25,18 +22,172 @@ const (
Bech32PrefixValPub = "cosmosvalpub"
)
// Bech32ifyAcc takes Address and returns the bech32 encoded string
func Bech32ifyAcc(addr Address) (string, error) {
return bech32.ConvertAndEncode(Bech32PrefixAccAddr, addr.Bytes())
//__________________________________________________________
// AccAddress a wrapper around bytes meant to represent an account address
// When marshaled to a string or json, it uses bech32
type AccAddress []byte
// create an AccAddress from a hex string
func AccAddressFromHex(address string) (addr AccAddress, err error) {
if len(address) == 0 {
return addr, errors.New("decoding bech32 address failed: must provide an address")
}
bz, err := hex.DecodeString(address)
if err != nil {
return nil, err
}
return AccAddress(bz), nil
}
// MustBech32ifyAcc panics on bech32-encoding failure
func MustBech32ifyAcc(addr Address) string {
enc, err := Bech32ifyAcc(addr)
// create an AccAddress from a bech32 string
func AccAddressFromBech32(address string) (addr AccAddress, err error) {
bz, err := GetFromBech32(address, Bech32PrefixAccAddr)
if err != nil {
return nil, err
}
return AccAddress(bz), nil
}
// Marshal needed for protobuf compatibility
func (bz AccAddress) Marshal() ([]byte, error) {
return bz, nil
}
// Unmarshal needed for protobuf compatibility
func (bz *AccAddress) Unmarshal(data []byte) error {
*bz = data
return nil
}
// Marshals to JSON using Bech32
func (bz AccAddress) MarshalJSON() ([]byte, error) {
return json.Marshal(bz.String())
}
// Unmarshals from JSON assuming Bech32 encoding
func (bz *AccAddress) UnmarshalJSON(data []byte) error {
var s string
err := json.Unmarshal(data, &s)
if err != nil {
return nil
}
bz2, err := AccAddressFromBech32(s)
if err != nil {
return err
}
*bz = bz2
return nil
}
// Allow it to fulfill various interfaces in light-client, etc...
func (bz AccAddress) Bytes() []byte {
return bz
}
func (bz AccAddress) String() string {
bech32Addr, err := bech32.ConvertAndEncode(Bech32PrefixAccAddr, bz.Bytes())
if err != nil {
panic(err)
}
return enc
return bech32Addr
}
// For Printf / Sprintf, returns bech32 when using %s
func (bz AccAddress) Format(s fmt.State, verb rune) {
switch verb {
case 's':
s.Write([]byte(fmt.Sprintf("%s", bz.String())))
case 'p':
s.Write([]byte(fmt.Sprintf("%p", bz)))
default:
s.Write([]byte(fmt.Sprintf("%X", []byte(bz))))
}
}
//__________________________________________________________
// AccAddress a wrapper around bytes meant to represent a validator address
// (from over ABCI). When marshaled to a string or json, it uses bech32
type ValAddress []byte
// create a ValAddress from a hex string
func ValAddressFromHex(address string) (addr ValAddress, err error) {
if len(address) == 0 {
return addr, errors.New("decoding bech32 address failed: must provide an address")
}
bz, err := hex.DecodeString(address)
if err != nil {
return nil, err
}
return ValAddress(bz), nil
}
// create a ValAddress from a bech32 string
func ValAddressFromBech32(address string) (addr ValAddress, err error) {
bz, err := GetFromBech32(address, Bech32PrefixValAddr)
if err != nil {
return nil, err
}
return ValAddress(bz), nil
}
// Marshal needed for protobuf compatibility
func (bz ValAddress) Marshal() ([]byte, error) {
return bz, nil
}
// Unmarshal needed for protobuf compatibility
func (bz *ValAddress) Unmarshal(data []byte) error {
*bz = data
return nil
}
// Marshals to JSON using Bech32
func (bz ValAddress) MarshalJSON() ([]byte, error) {
return json.Marshal(bz.String())
}
// Unmarshals from JSON assuming Bech32 encoding
func (bz *ValAddress) UnmarshalJSON(data []byte) error {
var s string
err := json.Unmarshal(data, &s)
if err != nil {
return nil
}
bz2, err := ValAddressFromBech32(s)
if err != nil {
return err
}
*bz = bz2
return nil
}
// Allow it to fulfill various interfaces in light-client, etc...
func (bz ValAddress) Bytes() []byte {
return bz
}
func (bz ValAddress) String() string {
bech32Addr, err := bech32.ConvertAndEncode(Bech32PrefixValAddr, bz.Bytes())
if err != nil {
panic(err)
}
return bech32Addr
}
// For Printf / Sprintf, returns bech32 when using %s
func (bz ValAddress) Format(s fmt.State, verb rune) {
switch verb {
case 's':
s.Write([]byte(fmt.Sprintf("%s", bz.String())))
case 'p':
s.Write([]byte(fmt.Sprintf("%p", bz)))
default:
s.Write([]byte(fmt.Sprintf("%X", []byte(bz))))
}
}
// Bech32ifyAccPub takes AccountPubKey and returns the bech32 encoded string
@ -53,26 +204,12 @@ func MustBech32ifyAccPub(pub crypto.PubKey) string {
return enc
}
// Bech32ifyVal returns the bech32 encoded string for a validator address
func Bech32ifyVal(addr Address) (string, error) {
return bech32.ConvertAndEncode(Bech32PrefixValAddr, addr.Bytes())
}
// MustBech32ifyVal panics on bech32-encoding failure
func MustBech32ifyVal(addr Address) string {
enc, err := Bech32ifyVal(addr)
if err != nil {
panic(err)
}
return enc
}
// Bech32ifyValPub returns the bech32 encoded string for a validator pubkey
func Bech32ifyValPub(pub crypto.PubKey) (string, error) {
return bech32.ConvertAndEncode(Bech32PrefixValPub, pub.Bytes())
}
// MustBech32ifyValPub pancis on bech32-encoding failure
// MustBech32ifyValPub panics on bech32-encoding failure
func MustBech32ifyValPub(pub crypto.PubKey) string {
enc, err := Bech32ifyValPub(pub)
if err != nil {
@ -81,36 +218,6 @@ func MustBech32ifyValPub(pub crypto.PubKey) string {
return enc
}
// create an Address from a string
func GetAccAddressHex(address string) (addr Address, err error) {
if len(address) == 0 {
return addr, errors.New("decoding bech32 address failed: must provide an address")
}
bz, err := hex.DecodeString(address)
if err != nil {
return nil, err
}
return Address(bz), nil
}
// create an Address from a string
func GetAccAddressBech32(address string) (addr Address, err error) {
bz, err := GetFromBech32(address, Bech32PrefixAccAddr)
if err != nil {
return nil, err
}
return Address(bz), nil
}
// create an Address from a string, panics on error
func MustGetAccAddressBech32(address string) (addr Address) {
addr, err := GetAccAddressBech32(address)
if err != nil {
panic(err)
}
return addr
}
// create a Pubkey from a string
func GetAccPubKeyBech32(address string) (pk crypto.PubKey, err error) {
bz, err := GetFromBech32(address, Bech32PrefixAccPub)
@ -135,36 +242,6 @@ func MustGetAccPubKeyBech32(address string) (pk crypto.PubKey) {
return pk
}
// create an Address from a hex string
func GetValAddressHex(address string) (addr Address, err error) {
if len(address) == 0 {
return addr, errors.New("decoding bech32 address failed: must provide an address")
}
bz, err := hex.DecodeString(address)
if err != nil {
return nil, err
}
return Address(bz), nil
}
// create an Address from a bech32 string
func GetValAddressBech32(address string) (addr Address, err error) {
bz, err := GetFromBech32(address, Bech32PrefixValAddr)
if err != nil {
return nil, err
}
return Address(bz), nil
}
// create an Address from a string, panics on error
func MustGetValAddressBech32(address string) (addr Address) {
addr, err := GetValAddressBech32(address)
if err != nil {
panic(err)
}
return addr
}
// decode a validator public key into a PubKey
func GetValPubKeyBech32(pubkey string) (pk crypto.PubKey, err error) {
bz, err := GetFromBech32(pubkey, Bech32PrefixValPub)

View File

@ -66,6 +66,7 @@ const (
)
// NOTE: Don't stringer this, we'll put better messages in later.
// nolint: gocyclo
func CodeToDefaultMsg(code CodeType) string {
switch code {
case CodeInternal:

View File

@ -37,6 +37,13 @@ func mod(i *big.Int, i2 *big.Int) *big.Int { return new(big.Int).Mod(i, i2) }
func neg(i *big.Int) *big.Int { return new(big.Int).Neg(i) }
func min(i *big.Int, i2 *big.Int) *big.Int {
if i.Cmp(i2) == 1 {
return new(big.Int).Set(i2)
}
return new(big.Int).Set(i)
}
// MarshalAmino for custom encoding scheme
func marshalAmino(i *big.Int) (string, error) {
bz, err := i.MarshalText()
@ -227,6 +234,11 @@ func (i Int) Neg() (res Int) {
return Int{neg(i.i)}
}
// Return the minimum of the ints
func MinInt(i1, i2 Int) Int {
return Int{min(i1.BigInt(), i2.BigInt())}
}
func (i Int) String() string {
return i.i.String()
}
@ -419,6 +431,11 @@ func (i Uint) DivRaw(i2 uint64) Uint {
return i.Div(NewUint(i2))
}
// Return the minimum of the Uints
func MinUint(i1, i2 Uint) Uint {
return Uint{min(i1.BigInt(), i2.BigInt())}
}
// MarshalAmino defines custom encoding scheme
func (i Uint) MarshalAmino() (string, error) {
if i.i == nil { // Necessary since default Uint initialization has i.i as nil

View File

@ -37,6 +37,30 @@ func NewRat(Numerator int64, Denominator ...int64) Rat {
}
}
func getNumeratorDenominator(str []string, prec int) (numerator string, denom int64, err Error) {
switch len(str) {
case 1:
if len(str[0]) == 0 {
return "", 0, ErrUnknownRequest("not a decimal string")
}
numerator = str[0]
return numerator, 1, nil
case 2:
if len(str[0]) == 0 || len(str[1]) == 0 {
return "", 0, ErrUnknownRequest("not a decimal string")
}
if len(str[1]) > prec {
return "", 0, ErrUnknownRequest("string has too many decimals")
}
numerator = str[0] + str[1]
len := int64(len(str[1]))
denom = new(big.Int).Exp(big.NewInt(10), big.NewInt(len), nil).Int64()
return numerator, denom, nil
default:
return "", 0, ErrUnknownRequest("not a decimal string")
}
}
// create a rational from decimal string or integer string
// precision is the number of values after the decimal point which should be read
func NewRatFromDecimal(decimalStr string, prec int) (f Rat, err Error) {
@ -53,26 +77,9 @@ func NewRatFromDecimal(decimalStr string, prec int) (f Rat, err Error) {
str := strings.Split(decimalStr, ".")
var numStr string
var denom int64 = 1
switch len(str) {
case 1:
if len(str[0]) == 0 {
return f, ErrUnknownRequest("not a decimal string")
}
numStr = str[0]
case 2:
if len(str[0]) == 0 || len(str[1]) == 0 {
return f, ErrUnknownRequest("not a decimal string")
}
if len(str[1]) > prec {
return f, ErrUnknownRequest("string has too many decimals")
}
numStr = str[0] + str[1]
len := int64(len(str[1]))
denom = new(big.Int).Exp(big.NewInt(10), big.NewInt(len), nil).Int64()
default:
return f, ErrUnknownRequest("not a decimal string")
numStr, denom, err := getNumeratorDenominator(str, prec)
if err != nil {
return f, err
}
num, errConv := strconv.Atoi(numStr)

View File

@ -35,7 +35,7 @@ type Validator interface {
GetRevoked() bool // whether the validator is revoked
GetMoniker() string // moniker of the validator
GetStatus() BondStatus // status of the validator
GetOwner() Address // owner address to receive/return validators coins
GetOwner() AccAddress // owner AccAddress to receive/return validators coins
GetPubKey() crypto.PubKey // validation pubkey
GetPower() Rat // validation power
GetDelegatorShares() Rat // Total out standing delegator shares
@ -52,16 +52,16 @@ func ABCIValidator(v Validator) abci.Validator {
// properties for the set of all validators
type ValidatorSet interface {
// iterate through validator by owner-address, execute func for each validator
// iterate through validator by owner-AccAddress, execute func for each validator
IterateValidators(Context,
func(index int64, validator Validator) (stop bool))
// iterate through bonded validator by pubkey-address, execute func for each validator
// iterate through bonded validator by pubkey-AccAddress, execute func for each validator
IterateValidatorsBonded(Context,
func(index int64, validator Validator) (stop bool))
Validator(Context, Address) Validator // get a particular validator by owner address
TotalPower(Context) Rat // total power of the validator set
Validator(Context, AccAddress) Validator // get a particular validator by owner AccAddress
TotalPower(Context) Rat // total power of the validator set
// slash the validator and delegators of the validator, specifying offence height, offence power, and slash fraction
Slash(Context, crypto.PubKey, int64, int64, Rat)
@ -73,17 +73,17 @@ type ValidatorSet interface {
// delegation bond for a delegated proof of stake system
type Delegation interface {
GetDelegator() Address // delegator address for the bond
GetValidator() Address // validator owner address for the bond
GetBondShares() Rat // amount of validator's shares
GetDelegator() AccAddress // delegator AccAddress for the bond
GetValidator() AccAddress // validator owner AccAddress for the bond
GetBondShares() Rat // amount of validator's shares
}
// properties for the set of all delegations for a particular
type DelegationSet interface {
GetValidatorSet() ValidatorSet // validator set for which delegation set is based upon
// iterate through all delegations from one delegator by validator-address,
// iterate through all delegations from one delegator by validator-AccAddress,
// execute func for each validator
IterateDelegations(ctx Context, delegator Address,
IterateDelegations(ctx Context, delegator AccAddress,
fn func(index int64, delegation Delegation) (stop bool))
}

View File

@ -21,7 +21,7 @@ type Msg interface {
// Signers returns the addrs of signers that must sign.
// CONTRACT: All signatures must be present to be valid.
// CONTRACT: Returns addrs in some deterministic order.
GetSigners() []Address
GetSigners() []AccAddress
}
//__________________________________________________________
@ -44,10 +44,10 @@ var _ Msg = (*TestMsg)(nil)
// msg type for testing
type TestMsg struct {
signers []Address
signers []AccAddress
}
func NewTestMsg(addrs ...Address) *TestMsg {
func NewTestMsg(addrs ...AccAddress) *TestMsg {
return &TestMsg{
signers: addrs,
}
@ -63,6 +63,6 @@ func (msg *TestMsg) GetSignBytes() []byte {
return MustSortJSON(bz)
}
func (msg *TestMsg) ValidateBasic() Error { return nil }
func (msg *TestMsg) GetSigners() []Address {
func (msg *TestMsg) GetSigners() []AccAddress {
return msg.signers
}

View File

@ -11,8 +11,8 @@ import (
// Account is a standard account using a sequence number for replay protection
// and a pubkey for authentication.
type Account interface {
GetAddress() sdk.Address
SetAddress(sdk.Address) error // errors if already set.
GetAddress() sdk.AccAddress
SetAddress(sdk.AccAddress) error // errors if already set.
GetPubKey() crypto.PubKey // can return nil.
SetPubKey(crypto.PubKey) error
@ -39,26 +39,26 @@ var _ Account = (*BaseAccount)(nil)
// Extend this by embedding this in your AppAccount.
// See the examples/basecoin/types/account.go for an example.
type BaseAccount struct {
Address sdk.Address `json:"address"`
Coins sdk.Coins `json:"coins"`
PubKey crypto.PubKey `json:"public_key"`
AccountNumber int64 `json:"account_number"`
Sequence int64 `json:"sequence"`
Address sdk.AccAddress `json:"address"`
Coins sdk.Coins `json:"coins"`
PubKey crypto.PubKey `json:"public_key"`
AccountNumber int64 `json:"account_number"`
Sequence int64 `json:"sequence"`
}
func NewBaseAccountWithAddress(addr sdk.Address) BaseAccount {
func NewBaseAccountWithAddress(addr sdk.AccAddress) BaseAccount {
return BaseAccount{
Address: addr,
}
}
// Implements sdk.Account.
func (acc BaseAccount) GetAddress() sdk.Address {
func (acc BaseAccount) GetAddress() sdk.AccAddress {
return acc.Address
}
// Implements sdk.Account.
func (acc *BaseAccount) SetAddress(addr sdk.Address) error {
func (acc *BaseAccount) SetAddress(addr sdk.AccAddress) error {
if len(acc.Address) != 0 {
return errors.New("cannot override BaseAccount address")
}

View File

@ -11,10 +11,10 @@ import (
wire "github.com/cosmos/cosmos-sdk/wire"
)
func keyPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.Address) {
func keyPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.AccAddress) {
key := crypto.GenPrivKeyEd25519()
pub := key.PubKey()
addr := pub.Address()
addr := sdk.AccAddress(pub.Address())
return key, pub, addr
}

View File

@ -29,45 +29,26 @@ func NewAnteHandler(am AccountMapper, fck FeeCollectionKeeper) sdk.AnteHandler {
return ctx, sdk.ErrInternal("tx must be StdTx").Result(), true
}
// Assert that there are signatures.
var sigs = stdTx.GetSignatures()
if len(sigs) == 0 {
return ctx,
sdk.ErrUnauthorized("no signers").Result(),
true
err := validateBasic(stdTx)
if err != nil {
return ctx, err.Result(), true
}
memo := stdTx.GetMemo()
if len(memo) > maxMemoCharacters {
return ctx,
sdk.ErrMemoTooLarge(fmt.Sprintf("maximum number of characters is %d but received %d characters", maxMemoCharacters, len(memo))).Result(),
true
}
sigs := stdTx.GetSignatures()
signerAddrs := stdTx.GetSigners()
msgs := tx.GetMsgs()
// set the gas meter
ctx = ctx.WithGasMeter(sdk.NewGasMeter(stdTx.Fee.Gas))
// charge gas for the memo
ctx.GasMeter().ConsumeGas(memoCostPerByte*sdk.Gas(len(memo)), "memo")
msgs := tx.GetMsgs()
// Assert that number of signatures is correct.
var signerAddrs = stdTx.GetSigners()
if len(sigs) != len(signerAddrs) {
return ctx,
sdk.ErrUnauthorized("wrong number of signers").Result(),
true
}
ctx.GasMeter().ConsumeGas(memoCostPerByte*sdk.Gas(len(stdTx.GetMemo())), "memo")
// Get the sign bytes (requires all account & sequence numbers and the fee)
sequences := make([]int64, len(signerAddrs))
for i := 0; i < len(signerAddrs); i++ {
sequences := make([]int64, len(sigs))
accNums := make([]int64, len(sigs))
for i := 0; i < len(sigs); i++ {
sequences[i] = sigs[i].Sequence
}
accNums := make([]int64, len(signerAddrs))
for i := 0; i < len(signerAddrs); i++ {
accNums[i] = sigs[i].AccountNumber
}
fee := stdTx.Fee
@ -88,16 +69,15 @@ func NewAnteHandler(am AccountMapper, fck FeeCollectionKeeper) sdk.AnteHandler {
}
// first sig pays the fees
if i == 0 {
// TODO: min fee
if !fee.Amount.IsZero() {
ctx.GasMeter().ConsumeGas(deductFeesCost, "deductFees")
signerAcc, res = deductFees(signerAcc, fee)
if !res.IsOK() {
return ctx, res, true
}
fck.addCollectedFees(ctx, fee.Amount)
// TODO: Add min fees
// Can this function be moved outside of the loop?
if i == 0 && !fee.Amount.IsZero() {
ctx.GasMeter().ConsumeGas(deductFeesCost, "deductFees")
signerAcc, res = deductFees(signerAcc, fee)
if !res.IsOK() {
return ctx, res, true
}
fck.addCollectedFees(ctx, fee.Amount)
}
// Save the account.
@ -114,11 +94,34 @@ func NewAnteHandler(am AccountMapper, fck FeeCollectionKeeper) sdk.AnteHandler {
}
}
// Validate the transaction based on things that don't depend on the context
func validateBasic(tx StdTx) (err sdk.Error) {
// Assert that there are signatures.
sigs := tx.GetSignatures()
if len(sigs) == 0 {
return sdk.ErrUnauthorized("no signers")
}
// Assert that number of signatures is correct.
var signerAddrs = tx.GetSigners()
if len(sigs) != len(signerAddrs) {
return sdk.ErrUnauthorized("wrong number of signers")
}
memo := tx.GetMemo()
if len(memo) > maxMemoCharacters {
return sdk.ErrMemoTooLarge(
fmt.Sprintf("maximum number of characters is %d but received %d characters",
maxMemoCharacters, len(memo)))
}
return nil
}
// verify the signature and increment the sequence.
// if the account doesn't have a pubkey, set it.
func processSig(
ctx sdk.Context, am AccountMapper,
addr sdk.Address, sig StdSignature, signBytes []byte) (
addr sdk.AccAddress, sig StdSignature, signBytes []byte) (
acc Account, res sdk.Result) {
// Get the account.

View File

@ -13,7 +13,7 @@ import (
wire "github.com/cosmos/cosmos-sdk/wire"
)
func newTestMsg(addrs ...sdk.Address) *sdk.TestMsg {
func newTestMsg(addrs ...sdk.AccAddress) *sdk.TestMsg {
return sdk.NewTestMsg(addrs...)
}
@ -31,9 +31,9 @@ func newCoins() sdk.Coins {
}
// generate a priv key and return it with its address
func privAndAddr() (crypto.PrivKey, sdk.Address) {
func privAndAddr() (crypto.PrivKey, sdk.AccAddress) {
priv := crypto.GenPrivKeyEd25519()
addr := priv.PubKey().Address()
addr := sdk.AccAddress(priv.PubKey().Address())
return priv, addr
}
@ -135,7 +135,7 @@ func TestAnteHandlerSigErrors(t *testing.T) {
tx = newTestTx(ctx, msgs, privs, accNums, seqs, fee)
// tx.GetSigners returns addresses in correct order: addr1, addr2, addr3
expectedSigners := []sdk.Address{addr1, addr2, addr3}
expectedSigners := []sdk.AccAddress{addr1, addr2, addr3}
stdTx := tx.(StdTx)
require.Equal(t, expectedSigners, stdTx.GetSigners())

View File

@ -41,7 +41,7 @@ func GetAccountCmd(storeName string, cdc *wire.Codec, decoder auth.AccountDecode
// find the key to look up the account
addr := args[0]
key, err := sdk.GetAccAddressBech32(addr)
key, err := sdk.AccAddressFromBech32(addr)
if err != nil {
return err
}

View File

@ -27,7 +27,7 @@ func QueryAccountRequestHandlerFn(storeName string, cdc *wire.Codec, decoder aut
vars := mux.Vars(r)
bech32addr := vars["address"]
addr, err := sdk.GetAccAddressBech32(bech32addr)
addr, err := sdk.AccAddressFromBech32(bech32addr)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))

View File

@ -37,7 +37,7 @@ func NewAccountMapper(cdc *wire.Codec, key sdk.StoreKey, proto Account) AccountM
}
// Implaements sdk.AccountMapper.
func (am AccountMapper) NewAccountWithAddress(ctx sdk.Context, addr sdk.Address) Account {
func (am AccountMapper) NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) Account {
acc := am.clonePrototype()
err := acc.SetAddress(addr)
if err != nil {
@ -63,12 +63,12 @@ func (am AccountMapper) NewAccount(ctx sdk.Context, acc Account) Account {
}
// Turn an address to key used to get it from the account store
func AddressStoreKey(addr sdk.Address) []byte {
func AddressStoreKey(addr sdk.AccAddress) []byte {
return append([]byte("account:"), addr.Bytes()...)
}
// Implements sdk.AccountMapper.
func (am AccountMapper) GetAccount(ctx sdk.Context, addr sdk.Address) Account {
func (am AccountMapper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) Account {
store := ctx.KVStore(am.key)
bz := store.Get(AddressStoreKey(addr))
if bz == nil {
@ -104,7 +104,7 @@ func (am AccountMapper) IterateAccounts(ctx sdk.Context, process func(Account) (
}
// Returns the PubKey of the account at address
func (am AccountMapper) GetPubKey(ctx sdk.Context, addr sdk.Address) (crypto.PubKey, sdk.Error) {
func (am AccountMapper) GetPubKey(ctx sdk.Context, addr sdk.AccAddress) (crypto.PubKey, sdk.Error) {
acc := am.GetAccount(ctx, addr)
if acc == nil {
return nil, sdk.ErrUnknownAddress(addr.String())
@ -113,7 +113,7 @@ func (am AccountMapper) GetPubKey(ctx sdk.Context, addr sdk.Address) (crypto.Pub
}
// Returns the Sequence of the account at address
func (am AccountMapper) GetSequence(ctx sdk.Context, addr sdk.Address) (int64, sdk.Error) {
func (am AccountMapper) GetSequence(ctx sdk.Context, addr sdk.AccAddress) (int64, sdk.Error) {
acc := am.GetAccount(ctx, addr)
if acc == nil {
return 0, sdk.ErrUnknownAddress(addr.String())
@ -121,7 +121,7 @@ func (am AccountMapper) GetSequence(ctx sdk.Context, addr sdk.Address) (int64, s
return acc.GetSequence(), nil
}
func (am AccountMapper) setSequence(ctx sdk.Context, addr sdk.Address, newSequence int64) sdk.Error {
func (am AccountMapper) setSequence(ctx sdk.Context, addr sdk.AccAddress, newSequence int64) sdk.Error {
acc := am.GetAccount(ctx, addr)
if acc == nil {
return sdk.ErrUnknownAddress(addr.String())

View File

@ -34,7 +34,7 @@ func TestAccountMapperGetSet(t *testing.T) {
ctx := sdk.NewContext(ms, abci.Header{}, false, log.NewNopLogger())
mapper := NewAccountMapper(cdc, capKey, &BaseAccount{})
addr := sdk.Address([]byte("some-address"))
addr := sdk.AccAddress([]byte("some-address"))
// no account before its created
acc := mapper.GetAccount(ctx, addr)

View File

@ -35,9 +35,9 @@ func (tx StdTx) GetMsgs() []sdk.Msg { return tx.Msgs }
// They are accumulated from the GetSigners method for each Msg
// in the order they appear in tx.GetMsgs().
// Duplicate addresses will be omitted.
func (tx StdTx) GetSigners() []sdk.Address {
func (tx StdTx) GetSigners() []sdk.AccAddress {
seen := map[string]bool{}
var signers []sdk.Address
var signers []sdk.AccAddress
for _, msg := range tx.GetMsgs() {
for _, addr := range msg.GetSigners() {
if !seen[addr.String()] {
@ -65,7 +65,7 @@ func (tx StdTx) GetSignatures() []StdSignature { return tx.Signatures }
// FeePayer returns the address responsible for paying the fees
// for the transactions. It's the first address returned by msg.GetSigners().
// If GetSigners() is empty, this panics.
func FeePayer(tx sdk.Tx) sdk.Address {
func FeePayer(tx sdk.Tx) sdk.AccAddress {
return tx.GetMsgs()[0].GetSigners()[0]
}

View File

@ -13,7 +13,7 @@ import (
func TestStdTx(t *testing.T) {
priv := crypto.GenPrivKeyEd25519()
addr := priv.PubKey().Address()
addr := sdk.AccAddress(priv.PubKey().Address())
msgs := []sdk.Msg{sdk.NewTestMsg(addr)}
fee := newStdFee()
sigs := []StdSignature{}
@ -28,7 +28,7 @@ func TestStdTx(t *testing.T) {
func TestStdSignBytes(t *testing.T) {
priv := crypto.GenPrivKeyEd25519()
addr := priv.PubKey().Address()
addr := sdk.AccAddress(priv.PubKey().Address())
msgs := []sdk.Msg{sdk.NewTestMsg(addr)}
fee := newStdFee()
signMsg := StdSignMsg{

View File

@ -18,12 +18,12 @@ import (
// test bank module in a mock application
var (
priv1 = crypto.GenPrivKeyEd25519()
addr1 = priv1.PubKey().Address()
addr1 = sdk.AccAddress(priv1.PubKey().Address())
priv2 = crypto.GenPrivKeyEd25519()
addr2 = priv2.PubKey().Address()
addr3 = crypto.GenPrivKeyEd25519().PubKey().Address()
addr2 = sdk.AccAddress(priv2.PubKey().Address())
addr3 = sdk.AccAddress(crypto.GenPrivKeyEd25519().PubKey().Address())
priv4 = crypto.GenPrivKeyEd25519()
addr4 = priv4.PubKey().Address()
addr4 = sdk.AccAddress(priv4.PubKey().Address())
coins = sdk.Coins{sdk.NewCoin("foocoin", 10)}
halfCoins = sdk.Coins{sdk.NewCoin("foocoin", 5)}
manyCoins = sdk.Coins{sdk.NewCoin("foocoin", 1), sdk.NewCoin("barcoin", 1)}

View File

@ -1,7 +1,7 @@
package cli
import (
"errors"
"github.com/pkg/errors"
"github.com/cosmos/cosmos-sdk/client/context"
sdk "github.com/cosmos/cosmos-sdk/types"
@ -37,16 +37,14 @@ func SendTxCmd(cdc *wire.Codec) *cobra.Command {
return err
}
bech32From := sdk.MustBech32ifyAcc(from)
// Check if account was found
if fromAcc == nil {
return errors.New("No account with address " + bech32From +
" was found in the state.\nAre you sure there has been a transaction involving it?")
return errors.Errorf("No account with address %s was found in the state.\nAre you sure there has been a transaction involving it?", from)
}
toStr := viper.GetString(flagTo)
to, err := sdk.GetAccAddressBech32(toStr)
to, err := sdk.AccAddressFromBech32(toStr)
if err != nil {
return err
}
@ -63,8 +61,7 @@ func SendTxCmd(cdc *wire.Codec) *cobra.Command {
return err
}
if !account.GetCoins().IsGTE(coins) {
return errors.New("Address " + bech32From +
" doesn't have enough coins to pay for this transaction.")
return errors.Errorf("Address %s doesn't have enough coins to pay for this transaction.", from)
}
// build and sign the transaction, then broadcast to Tendermint

View File

@ -44,7 +44,7 @@ func SendRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreCont
vars := mux.Vars(r)
bech32addr := vars["address"]
address, err := sdk.GetAccAddressBech32(bech32addr)
to, err := sdk.AccAddressFromBech32(bech32addr)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
@ -72,15 +72,8 @@ func SendRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreCont
return
}
to, err := sdk.GetAccAddressHex(address.String())
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
// build message
msg := client.BuildMsg(info.GetPubKey().Address(), to, m.Amount)
msg := client.BuildMsg(sdk.AccAddress(info.GetPubKey().Address()), to, m.Amount)
if err != nil { // XXX rechecking same error ?
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))

View File

@ -6,7 +6,7 @@ import (
)
// build the sendTx msg
func BuildMsg(from sdk.Address, to sdk.Address, coins sdk.Coins) sdk.Msg {
func BuildMsg(from sdk.AccAddress, to sdk.AccAddress, coins sdk.Coins) sdk.Msg {
input := bank.NewInput(from, coins)
output := bank.NewOutput(to, coins)
msg := bank.NewMsgSend([]bank.Input{input}, []bank.Output{output})

View File

@ -26,32 +26,32 @@ func NewKeeper(am auth.AccountMapper) Keeper {
}
// GetCoins returns the coins at the addr.
func (keeper Keeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {
func (keeper Keeper) GetCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins {
return getCoins(ctx, keeper.am, addr)
}
// SetCoins sets the coins at the addr.
func (keeper Keeper) SetCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) sdk.Error {
func (keeper Keeper) SetCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) sdk.Error {
return setCoins(ctx, keeper.am, addr, amt)
}
// HasCoins returns whether or not an account has at least amt coins.
func (keeper Keeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool {
func (keeper Keeper) HasCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) bool {
return hasCoins(ctx, keeper.am, addr, amt)
}
// SubtractCoins subtracts amt from the coins at the addr.
func (keeper Keeper) SubtractCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Tags, sdk.Error) {
func (keeper Keeper) SubtractCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) (sdk.Coins, sdk.Tags, sdk.Error) {
return subtractCoins(ctx, keeper.am, addr, amt)
}
// AddCoins adds amt to the coins at the addr.
func (keeper Keeper) AddCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Tags, sdk.Error) {
func (keeper Keeper) AddCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) (sdk.Coins, sdk.Tags, sdk.Error) {
return addCoins(ctx, keeper.am, addr, amt)
}
// SendCoins moves coins from one account to another
func (keeper Keeper) SendCoins(ctx sdk.Context, fromAddr sdk.Address, toAddr sdk.Address, amt sdk.Coins) (sdk.Tags, sdk.Error) {
func (keeper Keeper) SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) (sdk.Tags, sdk.Error) {
return sendCoins(ctx, keeper.am, fromAddr, toAddr, amt)
}
@ -73,17 +73,17 @@ func NewSendKeeper(am auth.AccountMapper) SendKeeper {
}
// GetCoins returns the coins at the addr.
func (keeper SendKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {
func (keeper SendKeeper) GetCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins {
return getCoins(ctx, keeper.am, addr)
}
// HasCoins returns whether or not an account has at least amt coins.
func (keeper SendKeeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool {
func (keeper SendKeeper) HasCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) bool {
return hasCoins(ctx, keeper.am, addr, amt)
}
// SendCoins moves coins from one account to another
func (keeper SendKeeper) SendCoins(ctx sdk.Context, fromAddr sdk.Address, toAddr sdk.Address, amt sdk.Coins) (sdk.Tags, sdk.Error) {
func (keeper SendKeeper) SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) (sdk.Tags, sdk.Error) {
return sendCoins(ctx, keeper.am, fromAddr, toAddr, amt)
}
@ -105,18 +105,18 @@ func NewViewKeeper(am auth.AccountMapper) ViewKeeper {
}
// GetCoins returns the coins at the addr.
func (keeper ViewKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {
func (keeper ViewKeeper) GetCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins {
return getCoins(ctx, keeper.am, addr)
}
// HasCoins returns whether or not an account has at least amt coins.
func (keeper ViewKeeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool {
func (keeper ViewKeeper) HasCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) bool {
return hasCoins(ctx, keeper.am, addr, amt)
}
//______________________________________________________________________________________________
func getCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.Address) sdk.Coins {
func getCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.AccAddress) sdk.Coins {
ctx.GasMeter().ConsumeGas(costGetCoins, "getCoins")
acc := am.GetAccount(ctx, addr)
if acc == nil {
@ -125,7 +125,7 @@ func getCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.Address) sdk.Coin
return acc.GetCoins()
}
func setCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.Address, amt sdk.Coins) sdk.Error {
func setCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.AccAddress, amt sdk.Coins) sdk.Error {
ctx.GasMeter().ConsumeGas(costSetCoins, "setCoins")
acc := am.GetAccount(ctx, addr)
if acc == nil {
@ -141,13 +141,13 @@ func setCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.Address, amt sdk.
}
// HasCoins returns whether or not an account has at least amt coins.
func hasCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.Address, amt sdk.Coins) bool {
func hasCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.AccAddress, amt sdk.Coins) bool {
ctx.GasMeter().ConsumeGas(costHasCoins, "hasCoins")
return getCoins(ctx, am, addr).IsGTE(amt)
}
// SubtractCoins subtracts amt from the coins at the addr.
func subtractCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Tags, sdk.Error) {
func subtractCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.AccAddress, amt sdk.Coins) (sdk.Coins, sdk.Tags, sdk.Error) {
ctx.GasMeter().ConsumeGas(costSubtractCoins, "subtractCoins")
oldCoins := getCoins(ctx, am, addr)
newCoins := oldCoins.Minus(amt)
@ -160,7 +160,7 @@ func subtractCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.Address, amt
}
// AddCoins adds amt to the coins at the addr.
func addCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Tags, sdk.Error) {
func addCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.AccAddress, amt sdk.Coins) (sdk.Coins, sdk.Tags, sdk.Error) {
ctx.GasMeter().ConsumeGas(costAddCoins, "addCoins")
oldCoins := getCoins(ctx, am, addr)
newCoins := oldCoins.Plus(amt)
@ -174,7 +174,7 @@ func addCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.Address, amt sdk.
// SendCoins moves coins from one account to another
// NOTE: Make sure to revert state changes from tx on error
func sendCoins(ctx sdk.Context, am auth.AccountMapper, fromAddr sdk.Address, toAddr sdk.Address, amt sdk.Coins) (sdk.Tags, sdk.Error) {
func sendCoins(ctx sdk.Context, am auth.AccountMapper, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) (sdk.Tags, sdk.Error) {
_, subTags, err := subtractCoins(ctx, am, fromAddr, amt)
if err != nil {
return nil, err

View File

@ -36,9 +36,9 @@ func TestKeeper(t *testing.T) {
accountMapper := auth.NewAccountMapper(cdc, authKey, &auth.BaseAccount{})
coinKeeper := NewKeeper(accountMapper)
addr := sdk.Address([]byte("addr1"))
addr2 := sdk.Address([]byte("addr2"))
addr3 := sdk.Address([]byte("addr3"))
addr := sdk.AccAddress([]byte("addr1"))
addr2 := sdk.AccAddress([]byte("addr2"))
addr3 := sdk.AccAddress([]byte("addr3"))
acc := accountMapper.NewAccountWithAddress(ctx, addr)
// Test GetCoins/SetCoins
@ -122,9 +122,9 @@ func TestSendKeeper(t *testing.T) {
coinKeeper := NewKeeper(accountMapper)
sendKeeper := NewSendKeeper(accountMapper)
addr := sdk.Address([]byte("addr1"))
addr2 := sdk.Address([]byte("addr2"))
addr3 := sdk.Address([]byte("addr3"))
addr := sdk.AccAddress([]byte("addr1"))
addr2 := sdk.AccAddress([]byte("addr2"))
addr3 := sdk.AccAddress([]byte("addr3"))
acc := accountMapper.NewAccountWithAddress(ctx, addr)
// Test GetCoins/SetCoins
@ -191,7 +191,7 @@ func TestViewKeeper(t *testing.T) {
coinKeeper := NewKeeper(accountMapper)
viewKeeper := NewViewKeeper(accountMapper)
addr := sdk.Address([]byte("addr1"))
addr := sdk.AccAddress([]byte("addr1"))
acc := accountMapper.NewAccountWithAddress(ctx, addr)
// Test GetCoins/SetCoins

View File

@ -76,8 +76,8 @@ func (msg MsgSend) GetSignBytes() []byte {
}
// Implements Msg.
func (msg MsgSend) GetSigners() []sdk.Address {
addrs := make([]sdk.Address, len(msg.Inputs))
func (msg MsgSend) GetSigners() []sdk.AccAddress {
addrs := make([]sdk.AccAddress, len(msg.Inputs))
for i, in := range msg.Inputs {
addrs[i] = in.Address
}
@ -89,14 +89,14 @@ func (msg MsgSend) GetSigners() []sdk.Address {
// MsgIssue - high level transaction of the coin module
type MsgIssue struct {
Banker sdk.Address `json:"banker"`
Outputs []Output `json:"outputs"`
Banker sdk.AccAddress `json:"banker"`
Outputs []Output `json:"outputs"`
}
var _ sdk.Msg = MsgIssue{}
// NewMsgIssue - construct arbitrary multi-in, multi-out send msg.
func NewMsgIssue(banker sdk.Address, out []Output) MsgIssue {
func NewMsgIssue(banker sdk.AccAddress, out []Output) MsgIssue {
return MsgIssue{Banker: banker, Outputs: out}
}
@ -124,10 +124,10 @@ func (msg MsgIssue) GetSignBytes() []byte {
outputs = append(outputs, output.GetSignBytes())
}
b, err := msgCdc.MarshalJSON(struct {
Banker string `json:"banker"`
Banker sdk.AccAddress `json:"banker"`
Outputs []json.RawMessage `json:"outputs"`
}{
Banker: sdk.MustBech32ifyAcc(msg.Banker),
Banker: msg.Banker,
Outputs: outputs,
})
if err != nil {
@ -137,8 +137,8 @@ func (msg MsgIssue) GetSignBytes() []byte {
}
// Implements Msg.
func (msg MsgIssue) GetSigners() []sdk.Address {
return []sdk.Address{msg.Banker}
func (msg MsgIssue) GetSigners() []sdk.AccAddress {
return []sdk.AccAddress{msg.Banker}
}
//----------------------------------------
@ -146,19 +146,13 @@ func (msg MsgIssue) GetSigners() []sdk.Address {
// Transaction Input
type Input struct {
Address sdk.Address `json:"address"`
Coins sdk.Coins `json:"coins"`
Address sdk.AccAddress `json:"address"`
Coins sdk.Coins `json:"coins"`
}
// Return bytes to sign for Input
func (in Input) GetSignBytes() []byte {
bin, err := msgCdc.MarshalJSON(struct {
Address string `json:"address"`
Coins sdk.Coins `json:"coins"`
}{
Address: sdk.MustBech32ifyAcc(in.Address),
Coins: in.Coins,
})
bin, err := msgCdc.MarshalJSON(in)
if err != nil {
panic(err)
}
@ -180,7 +174,7 @@ func (in Input) ValidateBasic() sdk.Error {
}
// NewInput - create a transaction input, used with MsgSend
func NewInput(addr sdk.Address, coins sdk.Coins) Input {
func NewInput(addr sdk.AccAddress, coins sdk.Coins) Input {
input := Input{
Address: addr,
Coins: coins,
@ -193,19 +187,13 @@ func NewInput(addr sdk.Address, coins sdk.Coins) Input {
// Transaction Output
type Output struct {
Address sdk.Address `json:"address"`
Coins sdk.Coins `json:"coins"`
Address sdk.AccAddress `json:"address"`
Coins sdk.Coins `json:"coins"`
}
// Return bytes to sign for Output
func (out Output) GetSignBytes() []byte {
bin, err := msgCdc.MarshalJSON(struct {
Address string `json:"address"`
Coins sdk.Coins `json:"coins"`
}{
Address: sdk.MustBech32ifyAcc(out.Address),
Coins: out.Coins,
})
bin, err := msgCdc.MarshalJSON(out)
if err != nil {
panic(err)
}
@ -227,7 +215,7 @@ func (out Output) ValidateBasic() sdk.Error {
}
// NewOutput - create a transaction output, used with MsgSend
func NewOutput(addr sdk.Address, coins sdk.Coins) Output {
func NewOutput(addr sdk.AccAddress, coins sdk.Coins) Output {
output := Output{
Address: addr,
Coins: coins,

View File

@ -13,8 +13,8 @@ func TestNewMsgSend(t *testing.T) {}
func TestMsgSendType(t *testing.T) {
// Construct a MsgSend
addr1 := sdk.Address([]byte("input"))
addr2 := sdk.Address([]byte("output"))
addr1 := sdk.AccAddress([]byte("input"))
addr2 := sdk.AccAddress([]byte("output"))
coins := sdk.Coins{sdk.NewCoin("atom", 10)}
var msg = MsgSend{
Inputs: []Input{NewInput(addr1, coins)},
@ -26,12 +26,12 @@ func TestMsgSendType(t *testing.T) {
}
func TestInputValidation(t *testing.T) {
addr1 := sdk.Address([]byte{1, 2})
addr2 := sdk.Address([]byte{7, 8})
addr1 := sdk.AccAddress([]byte{1, 2})
addr2 := sdk.AccAddress([]byte{7, 8})
someCoins := sdk.Coins{sdk.NewCoin("atom", 123)}
multiCoins := sdk.Coins{sdk.NewCoin("atom", 123), sdk.NewCoin("eth", 20)}
var emptyAddr sdk.Address
var emptyAddr sdk.AccAddress
emptyCoins := sdk.Coins{}
emptyCoins2 := sdk.Coins{sdk.NewCoin("eth", 0)}
someEmptyCoins := sdk.Coins{sdk.NewCoin("eth", 10), sdk.NewCoin("atom", 0)}
@ -68,12 +68,12 @@ func TestInputValidation(t *testing.T) {
}
func TestOutputValidation(t *testing.T) {
addr1 := sdk.Address([]byte{1, 2})
addr2 := sdk.Address([]byte{7, 8})
addr1 := sdk.AccAddress([]byte{1, 2})
addr2 := sdk.AccAddress([]byte{7, 8})
someCoins := sdk.Coins{sdk.NewCoin("atom", 123)}
multiCoins := sdk.Coins{sdk.NewCoin("atom", 123), sdk.NewCoin("eth", 20)}
var emptyAddr sdk.Address
var emptyAddr sdk.AccAddress
emptyCoins := sdk.Coins{}
emptyCoins2 := sdk.Coins{sdk.NewCoin("eth", 0)}
someEmptyCoins := sdk.Coins{sdk.NewCoin("eth", 10), sdk.NewCoin("atom", 0)}
@ -110,8 +110,8 @@ func TestOutputValidation(t *testing.T) {
}
func TestMsgSendValidation(t *testing.T) {
addr1 := sdk.Address([]byte{1, 2})
addr2 := sdk.Address([]byte{7, 8})
addr1 := sdk.AccAddress([]byte{1, 2})
addr2 := sdk.AccAddress([]byte{7, 8})
atom123 := sdk.Coins{sdk.NewCoin("atom", 123)}
atom124 := sdk.Coins{sdk.NewCoin("atom", 124)}
eth123 := sdk.Coins{sdk.NewCoin("eth", 123)}
@ -124,7 +124,7 @@ func TestMsgSendValidation(t *testing.T) {
output3 := NewOutput(addr2, eth123)
outputMulti := NewOutput(addr2, atom123eth123)
var emptyAddr sdk.Address
var emptyAddr sdk.AccAddress
cases := []struct {
valid bool
@ -178,8 +178,8 @@ func TestMsgSendValidation(t *testing.T) {
}
func TestMsgSendGetSignBytes(t *testing.T) {
addr1 := sdk.Address([]byte("input"))
addr2 := sdk.Address([]byte("output"))
addr1 := sdk.AccAddress([]byte("input"))
addr2 := sdk.AccAddress([]byte("output"))
coins := sdk.Coins{sdk.NewCoin("atom", 10)}
var msg = MsgSend{
Inputs: []Input{NewInput(addr1, coins)},
@ -194,9 +194,9 @@ func TestMsgSendGetSignBytes(t *testing.T) {
func TestMsgSendGetSigners(t *testing.T) {
var msg = MsgSend{
Inputs: []Input{
NewInput(sdk.Address([]byte("input1")), nil),
NewInput(sdk.Address([]byte("input2")), nil),
NewInput(sdk.Address([]byte("input3")), nil),
NewInput(sdk.AccAddress([]byte("input1")), nil),
NewInput(sdk.AccAddress([]byte("input2")), nil),
NewInput(sdk.AccAddress([]byte("input3")), nil),
},
}
res := msg.GetSigners()
@ -207,7 +207,7 @@ func TestMsgSendGetSigners(t *testing.T) {
/*
// what to do w/ this test?
func TestMsgSendSigners(t *testing.T) {
signers := []sdk.Address{
signers := []sdk.AccAddress{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
@ -233,10 +233,10 @@ func TestNewMsgIssue(t *testing.T) {
func TestMsgIssueType(t *testing.T) {
// Construct an MsgIssue
addr := sdk.Address([]byte("loan-from-bank"))
addr := sdk.AccAddress([]byte("loan-from-bank"))
coins := sdk.Coins{sdk.NewCoin("atom", 10)}
var msg = MsgIssue{
Banker: sdk.Address([]byte("input")),
Banker: sdk.AccAddress([]byte("input")),
Outputs: []Output{NewOutput(addr, coins)},
}
@ -249,10 +249,10 @@ func TestMsgIssueValidation(t *testing.T) {
}
func TestMsgIssueGetSignBytes(t *testing.T) {
addr := sdk.Address([]byte("loan-from-bank"))
addr := sdk.AccAddress([]byte("loan-from-bank"))
coins := sdk.Coins{sdk.NewCoin("atom", 10)}
var msg = MsgIssue{
Banker: sdk.Address([]byte("input")),
Banker: sdk.AccAddress([]byte("input")),
Outputs: []Output{NewOutput(addr, coins)},
}
res := msg.GetSignBytes()
@ -263,7 +263,7 @@ func TestMsgIssueGetSignBytes(t *testing.T) {
func TestMsgIssueGetSigners(t *testing.T) {
var msg = MsgIssue{
Banker: sdk.Address([]byte("onlyone")),
Banker: sdk.AccAddress([]byte("onlyone")),
}
res := msg.GetSigners()
require.Equal(t, fmt.Sprintf("%v", res), "[6F6E6C796F6E65]")

View File

@ -58,7 +58,7 @@ func TotalCoinsInvariant(t *testing.T, app *mock.App, log string) {
// accounts already exist.
func TestAndRunSingleInputMsgSend(t *testing.T, r *rand.Rand, app *mock.App, ctx sdk.Context, keys []crypto.PrivKey, log string) (action string, err sdk.Error) {
fromKey := keys[r.Intn(len(keys))]
fromAddr := fromKey.PubKey().Address()
fromAddr := sdk.AccAddress(fromKey.PubKey().Address())
toKey := keys[r.Intn(len(keys))]
// Disallow sending money to yourself
for {
@ -67,7 +67,7 @@ func TestAndRunSingleInputMsgSend(t *testing.T, r *rand.Rand, app *mock.App, ctx
}
toKey = keys[r.Intn(len(keys))]
}
toAddr := toKey.PubKey().Address()
toAddr := sdk.AccAddress(toKey.PubKey().Address())
initFromCoins := app.AccountMapper.GetAccount(ctx, fromAddr).GetCoins()
denomIndex := r.Intn(len(initFromCoins))

View File

@ -38,7 +38,7 @@ func GetCmdSubmitProposal(cdc *wire.Codec) *cobra.Command {
initialDeposit := viper.GetString(flagDeposit)
// get the from address from the name flag
from, err := sdk.GetAccAddressBech32(viper.GetString(flagProposer))
from, err := sdk.AccAddressFromBech32(viper.GetString(flagProposer))
if err != nil {
return err
}
@ -90,7 +90,7 @@ func GetCmdDeposit(cdc *wire.Codec) *cobra.Command {
Short: "deposit tokens for activing proposal",
RunE: func(cmd *cobra.Command, args []string) error {
// get the from address from the name flag
depositer, err := sdk.GetAccAddressBech32(viper.GetString(flagDepositer))
depositer, err := sdk.AccAddressFromBech32(viper.GetString(flagDepositer))
if err != nil {
return err
}
@ -136,7 +136,7 @@ func GetCmdVote(cdc *wire.Codec) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
bechVoter := viper.GetString(flagVoter)
voter, err := sdk.GetAccAddressBech32(bechVoter)
voter, err := sdk.AccAddressFromBech32(bechVoter)
if err != nil {
return err
}
@ -218,7 +218,7 @@ func GetCmdQueryVote(storeName string, cdc *wire.Codec) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
proposalID := viper.GetInt64(flagProposalID)
voterAddr, err := sdk.GetAccAddressBech32(viper.GetString(flagVoter))
voterAddr, err := sdk.AccAddressFromBech32(viper.GetString(flagVoter))
if err != nil {
return err
}

View File

@ -68,7 +68,7 @@ func postProposalHandlerFn(cdc *wire.Codec, ctx context.CoreContext) http.Handle
return
}
proposer, err := sdk.GetAccAddressBech32(req.Proposer)
proposer, err := sdk.AccAddressFromBech32(req.Proposer)
if err != nil {
writeErr(&w, http.StatusBadRequest, err.Error())
return
@ -122,7 +122,7 @@ func depositHandlerFn(cdc *wire.Codec, ctx context.CoreContext) http.HandlerFunc
return
}
depositer, err := sdk.GetAccAddressBech32(req.Depositer)
depositer, err := sdk.AccAddressFromBech32(req.Depositer)
if err != nil {
writeErr(&w, http.StatusBadRequest, err.Error())
return
@ -170,7 +170,7 @@ func voteHandlerFn(cdc *wire.Codec, ctx context.CoreContext) http.HandlerFunc {
return
}
voter, err := sdk.GetAccAddressBech32(req.Voter)
voter, err := sdk.AccAddressFromBech32(req.Voter)
if err != nil {
writeErr(&w, http.StatusBadRequest, err.Error())
return
@ -264,7 +264,7 @@ func queryDepositHandlerFn(cdc *wire.Codec) http.HandlerFunc {
return
}
depositerAddr, err := sdk.GetAccAddressBech32(bechDepositerAddr)
depositerAddr, err := sdk.AccAddressFromBech32(bechDepositerAddr)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
err := errors.Errorf("'%s' needs to be bech32 encoded", RestDepositer)
@ -330,7 +330,7 @@ func queryVoteHandlerFn(cdc *wire.Codec) http.HandlerFunc {
return
}
voterAddr, err := sdk.GetAccAddressBech32(bechVoterAddr)
voterAddr, err := sdk.AccAddressFromBech32(bechVoterAddr)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
err := errors.Errorf("'%s' needs to be bech32 encoded", RestVoter)
@ -369,17 +369,19 @@ func queryVoteHandlerFn(cdc *wire.Codec) http.HandlerFunc {
}
}
// nolint: gocyclo
// todo: Split this functionality into helper functions to remove the above
func queryProposalsWithParameterFn(cdc *wire.Codec) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
bechVoterAddr := r.URL.Query().Get(RestVoter)
bechDepositerAddr := r.URL.Query().Get(RestDepositer)
var err error
var voterAddr sdk.Address
var depositerAddr sdk.Address
var voterAddr sdk.AccAddress
var depositerAddr sdk.AccAddress
if len(bechVoterAddr) != 0 {
voterAddr, err = sdk.GetAccAddressBech32(bechVoterAddr)
voterAddr, err = sdk.AccAddressFromBech32(bechVoterAddr)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
err := errors.Errorf("'%s' needs to be bech32 encoded", RestVoter)
@ -389,7 +391,7 @@ func queryProposalsWithParameterFn(cdc *wire.Codec) http.HandlerFunc {
}
if len(bechDepositerAddr) != 0 {
depositerAddr, err = sdk.GetAccAddressBech32(bechDepositerAddr)
depositerAddr, err = sdk.AccAddressFromBech32(bechDepositerAddr)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
err := errors.Errorf("'%s' needs to be bech32 encoded", RestDepositer)

View File

@ -18,16 +18,16 @@ const (
// Vote
type Vote struct {
Voter sdk.Address `json:"voter"` // address of the voter
ProposalID int64 `json:"proposal_id"` // proposalID of the proposal
Option VoteOption `json:"option"` // option from OptionSet chosen by the voter
Voter sdk.AccAddress `json:"voter"` // address of the voter
ProposalID int64 `json:"proposal_id"` // proposalID of the proposal
Option VoteOption `json:"option"` // option from OptionSet chosen by the voter
}
// Deposit
type Deposit struct {
Depositer sdk.Address `json:"depositer"` // Address of the depositer
ProposalID int64 `json:"proposal_id"` // proposalID of the proposal
Amount sdk.Coins `json:"amount"` // Deposit amount
Depositer sdk.AccAddress `json:"depositer"` // Address of the depositer
ProposalID int64 `json:"proposal_id"` // proposalID of the proposal
Amount sdk.Coins `json:"amount"` // Deposit amount
}
// ProposalTypeToString for pretty prints of ProposalType
@ -77,16 +77,15 @@ func StringToVoteOption(str string) (VoteOption, sdk.Error) {
// Rest Deposits
type DepositRest struct {
Depositer string `json:"voter"` // address of the voter
ProposalID int64 `json:"proposal_id"` // proposalID of the proposal
Amount sdk.Coins `json:"option"`
Depositer sdk.AccAddress `json:"depositer"` // address of the depositer
ProposalID int64 `json:"proposal_id"` // proposalID of the proposal
Amount sdk.Coins `json:"option"`
}
// Turn any Deposit to a DepositRest
func DepositToRest(deposit Deposit) DepositRest {
bechAddr := sdk.MustBech32ifyAcc(deposit.Depositer)
return DepositRest{
Depositer: bechAddr,
Depositer: deposit.Depositer,
ProposalID: deposit.ProposalID,
Amount: deposit.Amount,
}
@ -94,16 +93,15 @@ func DepositToRest(deposit Deposit) DepositRest {
// Rest Votes
type VoteRest struct {
Voter string `json:"voter"` // address of the voter
ProposalID int64 `json:"proposal_id"` // proposalID of the proposal
Option string `json:"option"`
Voter sdk.AccAddress `json:"voter"` // address of the voter
ProposalID int64 `json:"proposal_id"` // proposalID of the proposal
Option string `json:"option"`
}
// Turn any Vote to a VoteRest
func VoteToRest(vote Vote) VoteRest {
bechAddr, _ := sdk.Bech32ifyAcc(vote.Voter)
return VoteRest{
Voter: bechAddr,
Voter: vote.Voter,
ProposalID: vote.ProposalID,
Option: VoteOptionToString(vote.Option),
}

View File

@ -41,9 +41,8 @@ func ErrAlreadyFinishedProposal(codespace sdk.CodespaceType, proposalID int64) s
return sdk.NewError(codespace, CodeAlreadyFinishedProposal, fmt.Sprintf("Proposal %d has already passed its voting period", proposalID))
}
func ErrAddressNotStaked(codespace sdk.CodespaceType, address sdk.Address) sdk.Error {
bechAddr, _ := sdk.Bech32ifyAcc(address)
return sdk.NewError(codespace, CodeAddressNotStaked, fmt.Sprintf("Address %s is not staked and is thus ineligible to vote", bechAddr))
func ErrAddressNotStaked(codespace sdk.CodespaceType, address sdk.AccAddress) sdk.Error {
return sdk.NewError(codespace, CodeAddressNotStaked, fmt.Sprintf("Address %s is not staked and is thus ineligible to vote", address))
}
func ErrInvalidTitle(codespace sdk.CodespaceType, title string) sdk.Error {

View File

@ -93,7 +93,7 @@ func handleMsgVote(ctx sdk.Context, keeper Keeper, msg MsgVote) sdk.Result {
}
// Called every block, process inflation, update validator set
func EndBlocker(ctx sdk.Context, keeper Keeper) (tags sdk.Tags, nonVotingVals []sdk.Address) {
func EndBlocker(ctx sdk.Context, keeper Keeper) (tags sdk.Tags, nonVotingVals []sdk.AccAddress) {
tags = sdk.NewTags()

View File

@ -156,7 +156,7 @@ func (keeper Keeper) GetTallyingProcedure() TallyingProcedure {
// Votes
// Adds a vote on a specific proposal
func (keeper Keeper) AddVote(ctx sdk.Context, proposalID int64, voterAddr sdk.Address, option VoteOption) sdk.Error {
func (keeper Keeper) AddVote(ctx sdk.Context, proposalID int64, voterAddr sdk.AccAddress, option VoteOption) sdk.Error {
proposal := keeper.GetProposal(ctx, proposalID)
if proposal == nil {
return ErrUnknownProposal(keeper.codespace, proposalID)
@ -180,7 +180,7 @@ func (keeper Keeper) AddVote(ctx sdk.Context, proposalID int64, voterAddr sdk.Ad
}
// Gets the vote of a specific voter on a specific proposal
func (keeper Keeper) GetVote(ctx sdk.Context, proposalID int64, voterAddr sdk.Address) (Vote, bool) {
func (keeper Keeper) GetVote(ctx sdk.Context, proposalID int64, voterAddr sdk.AccAddress) (Vote, bool) {
store := ctx.KVStore(keeper.storeKey)
bz := store.Get(KeyVote(proposalID, voterAddr))
if bz == nil {
@ -191,7 +191,7 @@ func (keeper Keeper) GetVote(ctx sdk.Context, proposalID int64, voterAddr sdk.Ad
return vote, true
}
func (keeper Keeper) setVote(ctx sdk.Context, proposalID int64, voterAddr sdk.Address, vote Vote) {
func (keeper Keeper) setVote(ctx sdk.Context, proposalID int64, voterAddr sdk.AccAddress, vote Vote) {
store := ctx.KVStore(keeper.storeKey)
bz := keeper.cdc.MustMarshalBinary(vote)
store.Set(KeyVote(proposalID, voterAddr), bz)
@ -203,7 +203,7 @@ func (keeper Keeper) GetVotes(ctx sdk.Context, proposalID int64) sdk.Iterator {
return sdk.KVStorePrefixIterator(store, KeyVotesSubspace(proposalID))
}
func (keeper Keeper) deleteVote(ctx sdk.Context, proposalID int64, voterAddr sdk.Address) {
func (keeper Keeper) deleteVote(ctx sdk.Context, proposalID int64, voterAddr sdk.AccAddress) {
store := ctx.KVStore(keeper.storeKey)
store.Delete(KeyVote(proposalID, voterAddr))
}
@ -212,7 +212,7 @@ func (keeper Keeper) deleteVote(ctx sdk.Context, proposalID int64, voterAddr sdk
// Deposits
// Gets the deposit of a specific depositer on a specific proposal
func (keeper Keeper) GetDeposit(ctx sdk.Context, proposalID int64, depositerAddr sdk.Address) (Deposit, bool) {
func (keeper Keeper) GetDeposit(ctx sdk.Context, proposalID int64, depositerAddr sdk.AccAddress) (Deposit, bool) {
store := ctx.KVStore(keeper.storeKey)
bz := store.Get(KeyDeposit(proposalID, depositerAddr))
if bz == nil {
@ -223,7 +223,7 @@ func (keeper Keeper) GetDeposit(ctx sdk.Context, proposalID int64, depositerAddr
return deposit, true
}
func (keeper Keeper) setDeposit(ctx sdk.Context, proposalID int64, depositerAddr sdk.Address, deposit Deposit) {
func (keeper Keeper) setDeposit(ctx sdk.Context, proposalID int64, depositerAddr sdk.AccAddress, deposit Deposit) {
store := ctx.KVStore(keeper.storeKey)
bz := keeper.cdc.MustMarshalBinary(deposit)
store.Set(KeyDeposit(proposalID, depositerAddr), bz)
@ -231,7 +231,7 @@ func (keeper Keeper) setDeposit(ctx sdk.Context, proposalID int64, depositerAddr
// Adds or updates a deposit of a specific depositer on a specific proposal
// Activates voting period when appropriate
func (keeper Keeper) AddDeposit(ctx sdk.Context, proposalID int64, depositerAddr sdk.Address, depositAmount sdk.Coins) (sdk.Error, bool) {
func (keeper Keeper) AddDeposit(ctx sdk.Context, proposalID int64, depositerAddr sdk.AccAddress, depositAmount sdk.Coins) (sdk.Error, bool) {
// Checks to see if proposal exists
proposal := keeper.GetProposal(ctx, proposalID)
if proposal == nil {

View File

@ -21,12 +21,12 @@ func KeyProposal(proposalID int64) []byte {
}
// Key for getting a specific deposit from the store
func KeyDeposit(proposalID int64, depositerAddr sdk.Address) []byte {
func KeyDeposit(proposalID int64, depositerAddr sdk.AccAddress) []byte {
return []byte(fmt.Sprintf("deposits:%d:%d", proposalID, depositerAddr))
}
// Key for getting a specific vote from the store
func KeyVote(proposalID int64, voterAddr sdk.Address) []byte {
func KeyVote(proposalID int64, voterAddr sdk.AccAddress) []byte {
return []byte(fmt.Sprintf("votes:%d:%d", proposalID, voterAddr))
}

View File

@ -12,14 +12,14 @@ const MsgType = "gov"
//-----------------------------------------------------------
// MsgSubmitProposal
type MsgSubmitProposal struct {
Title string // Title of the proposal
Description string // Description of the proposal
ProposalType ProposalKind // Type of proposal. Initial set {PlainTextProposal, SoftwareUpgradeProposal}
Proposer sdk.Address // Address of the proposer
InitialDeposit sdk.Coins // Initial deposit paid by sender. Must be strictly positive.
Title string // Title of the proposal
Description string // Description of the proposal
ProposalType ProposalKind // Type of proposal. Initial set {PlainTextProposal, SoftwareUpgradeProposal}
Proposer sdk.AccAddress // Address of the proposer
InitialDeposit sdk.Coins // Initial deposit paid by sender. Must be strictly positive.
}
func NewMsgSubmitProposal(title string, description string, proposalType ProposalKind, proposer sdk.Address, initialDeposit sdk.Coins) MsgSubmitProposal {
func NewMsgSubmitProposal(title string, description string, proposalType ProposalKind, proposer sdk.AccAddress, initialDeposit sdk.Coins) MsgSubmitProposal {
return MsgSubmitProposal{
Title: title,
Description: description,
@ -67,16 +67,16 @@ func (msg MsgSubmitProposal) Get(key interface{}) (value interface{}) {
// Implements Msg.
func (msg MsgSubmitProposal) GetSignBytes() []byte {
b, err := msgCdc.MarshalJSON(struct {
Title string `json:"title"`
Description string `json:"description"`
ProposalType string `json:"proposal_type"`
Proposer string `json:"proposer"`
InitialDeposit sdk.Coins `json:"deposit"`
Title string `json:"title"`
Description string `json:"description"`
ProposalType string `json:"proposal_type"`
Proposer sdk.AccAddress `json:"proposer"`
InitialDeposit sdk.Coins `json:"deposit"`
}{
Title: msg.Title,
Description: msg.Description,
ProposalType: ProposalTypeToString(msg.ProposalType),
Proposer: sdk.MustBech32ifyVal(msg.Proposer),
Proposer: msg.Proposer,
InitialDeposit: msg.InitialDeposit,
})
if err != nil {
@ -86,19 +86,19 @@ func (msg MsgSubmitProposal) GetSignBytes() []byte {
}
// Implements Msg.
func (msg MsgSubmitProposal) GetSigners() []sdk.Address {
return []sdk.Address{msg.Proposer}
func (msg MsgSubmitProposal) GetSigners() []sdk.AccAddress {
return []sdk.AccAddress{msg.Proposer}
}
//-----------------------------------------------------------
// MsgDeposit
type MsgDeposit struct {
ProposalID int64 `json:"proposalID"` // ID of the proposal
Depositer sdk.Address `json:"depositer"` // Address of the depositer
Amount sdk.Coins `json:"amount"` // Coins to add to the proposal's deposit
ProposalID int64 `json:"proposalID"` // ID of the proposal
Depositer sdk.AccAddress `json:"depositer"` // Address of the depositer
Amount sdk.Coins `json:"amount"` // Coins to add to the proposal's deposit
}
func NewMsgDeposit(depositer sdk.Address, proposalID int64, amount sdk.Coins) MsgDeposit {
func NewMsgDeposit(depositer sdk.AccAddress, proposalID int64, amount sdk.Coins) MsgDeposit {
return MsgDeposit{
ProposalID: proposalID,
Depositer: depositer,
@ -138,12 +138,12 @@ func (msg MsgDeposit) Get(key interface{}) (value interface{}) {
// Implements Msg.
func (msg MsgDeposit) GetSignBytes() []byte {
b, err := msgCdc.MarshalJSON(struct {
ProposalID int64 `json:"proposalID"`
Depositer string `json:"proposer"`
Amount sdk.Coins `json:"deposit"`
ProposalID int64 `json:"proposalID"`
Depositer sdk.AccAddress `json:"proposer"`
Amount sdk.Coins `json:"deposit"`
}{
ProposalID: msg.ProposalID,
Depositer: sdk.MustBech32ifyVal(msg.Depositer),
Depositer: msg.Depositer,
Amount: msg.Amount,
})
if err != nil {
@ -153,19 +153,19 @@ func (msg MsgDeposit) GetSignBytes() []byte {
}
// Implements Msg.
func (msg MsgDeposit) GetSigners() []sdk.Address {
return []sdk.Address{msg.Depositer}
func (msg MsgDeposit) GetSigners() []sdk.AccAddress {
return []sdk.AccAddress{msg.Depositer}
}
//-----------------------------------------------------------
// MsgVote
type MsgVote struct {
ProposalID int64 // proposalID of the proposal
Voter sdk.Address // address of the voter
Option VoteOption // option from OptionSet chosen by the voter
ProposalID int64 // proposalID of the proposal
Voter sdk.AccAddress // address of the voter
Option VoteOption // option from OptionSet chosen by the voter
}
func NewMsgVote(voter sdk.Address, proposalID int64, option VoteOption) MsgVote {
func NewMsgVote(voter sdk.AccAddress, proposalID int64, option VoteOption) MsgVote {
return MsgVote{
ProposalID: proposalID,
Voter: voter,
@ -202,12 +202,12 @@ func (msg MsgVote) Get(key interface{}) (value interface{}) {
// Implements Msg.
func (msg MsgVote) GetSignBytes() []byte {
b, err := msgCdc.MarshalJSON(struct {
ProposalID int64 `json:"proposalID"`
Voter string `json:"voter"`
Option string `json:"option"`
ProposalID int64 `json:"proposalID"`
Voter sdk.AccAddress `json:"voter"`
Option string `json:"option"`
}{
ProposalID: msg.ProposalID,
Voter: sdk.MustBech32ifyVal(msg.Voter),
Voter: msg.Voter,
Option: VoteOptionToString(msg.Option),
})
if err != nil {
@ -217,6 +217,6 @@ func (msg MsgVote) GetSignBytes() []byte {
}
// Implements Msg.
func (msg MsgVote) GetSigners() []sdk.Address {
return []sdk.Address{msg.Voter}
func (msg MsgVote) GetSigners() []sdk.AccAddress {
return []sdk.AccAddress{msg.Voter}
}

View File

@ -23,7 +23,7 @@ func TestMsgSubmitProposal(t *testing.T) {
tests := []struct {
title, description string
proposalType byte
proposerAddr sdk.Address
proposerAddr sdk.AccAddress
initialDeposit sdk.Coins
expectPass bool
}{
@ -33,7 +33,7 @@ func TestMsgSubmitProposal(t *testing.T) {
{"Test Proposal", "the purpose of this proposal is to test", ProposalTypeParameterChange, addrs[0], coinsPos, true},
{"Test Proposal", "the purpose of this proposal is to test", ProposalTypeSoftwareUpgrade, addrs[0], coinsPos, true},
{"Test Proposal", "the purpose of this proposal is to test", 0x05, addrs[0], coinsPos, false},
{"Test Proposal", "the purpose of this proposal is to test", ProposalTypeText, sdk.Address{}, coinsPos, false},
{"Test Proposal", "the purpose of this proposal is to test", ProposalTypeText, sdk.AccAddress{}, coinsPos, false},
{"Test Proposal", "the purpose of this proposal is to test", ProposalTypeText, addrs[0], coinsZero, true},
{"Test Proposal", "the purpose of this proposal is to test", ProposalTypeText, addrs[0], coinsNeg, false},
{"Test Proposal", "the purpose of this proposal is to test", ProposalTypeText, addrs[0], coinsMulti, true},
@ -54,13 +54,13 @@ func TestMsgDeposit(t *testing.T) {
_, addrs, _, _ := mock.CreateGenAccounts(1, sdk.Coins{})
tests := []struct {
proposalID int64
depositerAddr sdk.Address
depositerAddr sdk.AccAddress
depositAmount sdk.Coins
expectPass bool
}{
{0, addrs[0], coinsPos, true},
{-1, addrs[0], coinsPos, false},
{1, sdk.Address{}, coinsPos, false},
{1, sdk.AccAddress{}, coinsPos, false},
{1, addrs[0], coinsZero, true},
{1, addrs[0], coinsNeg, false},
{1, addrs[0], coinsMulti, true},
@ -81,13 +81,13 @@ func TestMsgVote(t *testing.T) {
_, addrs, _, _ := mock.CreateGenAccounts(1, sdk.Coins{})
tests := []struct {
proposalID int64
voterAddr sdk.Address
voterAddr sdk.AccAddress
option VoteOption
expectPass bool
}{
{0, addrs[0], OptionYes, true},
{-1, addrs[0], OptionYes, false},
{0, sdk.Address{}, OptionYes, false},
{0, sdk.AccAddress{}, OptionYes, false},
{0, addrs[0], OptionNo, true},
{0, addrs[0], OptionNoWithVeto, true},
{0, addrs[0], OptionAbstain, true},

View File

@ -6,14 +6,14 @@ import (
// validatorGovInfo used for tallying
type validatorGovInfo struct {
Address sdk.Address // sdk.Address of the validator owner
Power sdk.Rat // Power of a Validator
DelegatorShares sdk.Rat // Total outstanding delegator shares
Minus sdk.Rat // Minus of validator, used to compute validator's voting power
Vote VoteOption // Vote of the validator
Address sdk.AccAddress // sdk.AccAddress of the validator owner
Power sdk.Rat // Power of a Validator
DelegatorShares sdk.Rat // Total outstanding delegator shares
Minus sdk.Rat // Minus of validator, used to compute validator's voting power
Vote VoteOption // Vote of the validator
}
func tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, nonVoting []sdk.Address) {
func tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, nonVoting []sdk.AccAddress) {
results := make(map[VoteOption]sdk.Rat)
results[OptionYes] = sdk.ZeroRat()
results[OptionAbstain] = sdk.ZeroRat()
@ -67,7 +67,7 @@ func tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, nonV
votesIterator.Close()
// Iterate over the validators again to tally their voting power and see who didn't vote
nonVoting = []sdk.Address{}
nonVoting = []sdk.AccAddress{}
for _, val := range currValidators {
if val.Vote == OptionEmpty {
nonVoting = append(nonVoting, val.Address)

View File

@ -18,7 +18,7 @@ import (
)
// initialize the mock application for this module
func getMockApp(t *testing.T, numGenAccs int) (*mock.App, Keeper, stake.Keeper, []sdk.Address, []crypto.PubKey, []crypto.PrivKey) {
func getMockApp(t *testing.T, numGenAccs int) (*mock.App, Keeper, stake.Keeper, []sdk.AccAddress, []crypto.PubKey, []crypto.PrivKey) {
mapp := mock.NewApp()
stake.RegisterWire(mapp.Cdc)
@ -61,14 +61,17 @@ func getInitChainer(mapp *mock.App, keeper Keeper, stakeKeeper stake.Keeper) sdk
stakeGenesis := stake.DefaultGenesisState()
stakeGenesis.Pool.LooseTokens = 100000
stake.InitGenesis(ctx, stakeKeeper, stakeGenesis)
err := stake.InitGenesis(ctx, stakeKeeper, stakeGenesis)
if err != nil {
panic(err)
}
InitGenesis(ctx, keeper, DefaultGenesisState())
return abci.ResponseInitChain{}
}
}
// Sorts Addresses
func SortAddresses(addrs []sdk.Address) {
func SortAddresses(addrs []sdk.AccAddress) {
var byteAddrs [][]byte
for _, addr := range addrs {
byteAddrs = append(byteAddrs, addr.Bytes())

View File

@ -35,7 +35,7 @@ func TestIBCMsgs(t *testing.T) {
destChain := "dest-chain"
priv1 := crypto.GenPrivKeyEd25519()
addr1 := priv1.PubKey().Address()
addr1 := sdk.AccAddress(priv1.PubKey().Address())
coins := sdk.Coins{sdk.NewCoin("foocoin", 10)}
var emptyCoins sdk.Coins

View File

@ -56,7 +56,7 @@ func IBCTransferCmd(cdc *wire.Codec) *cobra.Command {
return cmd
}
func buildMsg(from sdk.Address) (sdk.Msg, error) {
func buildMsg(from sdk.AccAddress) (sdk.Msg, error) {
amount := viper.GetString(flagAmount)
coins, err := sdk.ParseCoins(amount)
if err != nil {
@ -68,7 +68,7 @@ func buildMsg(from sdk.Address) (sdk.Msg, error) {
if err != nil {
return nil, err
}
to := sdk.Address(bz)
to := sdk.AccAddress(bz)
packet := ibc.NewIBCPacket(from, to, coins, viper.GetString(client.FlagChainID),
viper.GetString(flagChain))

View File

@ -27,7 +27,7 @@ const (
type relayCommander struct {
cdc *wire.Codec
address sdk.Address
address sdk.AccAddress
decoder auth.AccountDecoder
mainStore string
ibcStore string
@ -86,6 +86,8 @@ func (c relayCommander) runIBCRelay(cmd *cobra.Command, args []string) {
c.loop(fromChainID, fromChainNode, toChainID, toChainNode)
}
// This is nolinted as someone is in the process of refactoring this to remove the goto
// nolint: gocyclo
func (c relayCommander) loop(fromChainID, fromChainNode, toChainID,
toChainNode string) {

View File

@ -1,7 +1,6 @@
package rest
import (
"encoding/hex"
"io/ioutil"
"net/http"
@ -39,7 +38,7 @@ func TransferRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.Core
destChainID := vars["destchain"]
bech32addr := vars["address"]
address, err := sdk.GetAccAddressBech32(bech32addr)
to, err := sdk.AccAddressFromBech32(bech32addr)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
@ -67,16 +66,8 @@ func TransferRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.Core
return
}
bz, err := hex.DecodeString(address.String())
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
to := sdk.Address(bz)
// build message
packet := ibc.NewIBCPacket(info.GetPubKey().Address(), to, m.Amount, m.SrcChainID, destChainID)
packet := ibc.NewIBCPacket(sdk.AccAddress(info.GetPubKey().Address()), to, m.Amount, m.SrcChainID, destChainID)
msg := ibc.IBCTransferMsg{packet}
// add gas to context

View File

@ -28,11 +28,11 @@ func defaultContext(key sdk.StoreKey) sdk.Context {
return ctx
}
func newAddress() crypto.Address {
return crypto.GenPrivKeyEd25519().PubKey().Address()
func newAddress() sdk.AccAddress {
return sdk.AccAddress(crypto.GenPrivKeyEd25519().PubKey().Address())
}
func getCoins(ck bank.Keeper, ctx sdk.Context, addr crypto.Address) (sdk.Coins, sdk.Error) {
func getCoins(ck bank.Keeper, ctx sdk.Context, addr sdk.AccAddress) (sdk.Coins, sdk.Error) {
zero := sdk.Coins(nil)
coins, _, err := ck.AddCoins(ctx, addr, zero)
return coins, err

View File

@ -22,14 +22,14 @@ func init() {
// IBCPacket defines a piece of data that can be send between two separate
// blockchains.
type IBCPacket struct {
SrcAddr sdk.Address
DestAddr sdk.Address
SrcAddr sdk.AccAddress
DestAddr sdk.AccAddress
Coins sdk.Coins
SrcChain string
DestChain string
}
func NewIBCPacket(srcAddr sdk.Address, destAddr sdk.Address, coins sdk.Coins,
func NewIBCPacket(srcAddr sdk.AccAddress, destAddr sdk.AccAddress, coins sdk.Coins,
srcChain string, destChain string) IBCPacket {
return IBCPacket{
@ -43,19 +43,7 @@ func NewIBCPacket(srcAddr sdk.Address, destAddr sdk.Address, coins sdk.Coins,
//nolint
func (p IBCPacket) GetSignBytes() []byte {
b, err := msgCdc.MarshalJSON(struct {
SrcAddr string
DestAddr string
Coins sdk.Coins
SrcChain string
DestChain string
}{
SrcAddr: sdk.MustBech32ifyAcc(p.SrcAddr),
DestAddr: sdk.MustBech32ifyAcc(p.DestAddr),
Coins: p.Coins,
SrcChain: p.SrcChain,
DestChain: p.DestChain,
})
b, err := msgCdc.MarshalJSON(p)
if err != nil {
panic(err)
}
@ -86,7 +74,7 @@ type IBCTransferMsg struct {
func (msg IBCTransferMsg) Type() string { return "ibc" }
// x/bank/tx.go MsgSend.GetSigners()
func (msg IBCTransferMsg) GetSigners() []sdk.Address { return []sdk.Address{msg.SrcAddr} }
func (msg IBCTransferMsg) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.SrcAddr} }
// get the sign bytes for ibc transfer message
func (msg IBCTransferMsg) GetSignBytes() []byte {
@ -106,7 +94,7 @@ func (msg IBCTransferMsg) ValidateBasic() sdk.Error {
// to the destination chain.
type IBCReceiveMsg struct {
IBCPacket
Relayer sdk.Address
Relayer sdk.AccAddress
Sequence int64
}
@ -115,17 +103,17 @@ func (msg IBCReceiveMsg) Type() string { return "ibc" }
func (msg IBCReceiveMsg) ValidateBasic() sdk.Error { return msg.IBCPacket.ValidateBasic() }
// x/bank/tx.go MsgSend.GetSigners()
func (msg IBCReceiveMsg) GetSigners() []sdk.Address { return []sdk.Address{msg.Relayer} }
func (msg IBCReceiveMsg) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Relayer} }
// get the sign bytes for ibc receive message
func (msg IBCReceiveMsg) GetSignBytes() []byte {
b, err := msgCdc.MarshalJSON(struct {
IBCPacket json.RawMessage
Relayer string
Relayer sdk.AccAddress
Sequence int64
}{
IBCPacket: json.RawMessage(msg.IBCPacket.GetSignBytes()),
Relayer: sdk.MustBech32ifyAcc(msg.Relayer),
Relayer: msg.Relayer,
Sequence: msg.Sequence,
})
if err != nil {

View File

@ -67,7 +67,7 @@ func TestIBCTransferMsgValidation(t *testing.T) {
func TestIBCReceiveMsg(t *testing.T) {
packet := constructIBCPacket(true)
msg := IBCReceiveMsg{packet, sdk.Address([]byte("relayer")), 0}
msg := IBCReceiveMsg{packet, sdk.AccAddress([]byte("relayer")), 0}
require.Equal(t, msg.Type(), "ibc")
}
@ -80,8 +80,8 @@ func TestIBCReceiveMsgValidation(t *testing.T) {
valid bool
msg IBCReceiveMsg
}{
{true, IBCReceiveMsg{validPacket, sdk.Address([]byte("relayer")), 0}},
{false, IBCReceiveMsg{invalidPacket, sdk.Address([]byte("relayer")), 0}},
{true, IBCReceiveMsg{validPacket, sdk.AccAddress([]byte("relayer")), 0}},
{false, IBCReceiveMsg{invalidPacket, sdk.AccAddress([]byte("relayer")), 0}},
}
for i, tc := range cases {
@ -98,8 +98,8 @@ func TestIBCReceiveMsgValidation(t *testing.T) {
// Helpers
func constructIBCPacket(valid bool) IBCPacket {
srcAddr := sdk.Address([]byte("source"))
destAddr := sdk.Address([]byte("destination"))
srcAddr := sdk.AccAddress([]byte("source"))
destAddr := sdk.AccAddress([]byte("destination"))
coins := sdk.Coins{sdk.NewCoin("atom", 10)}
srcChain := "source-chain"
destChain := "dest-chain"

View File

@ -95,11 +95,11 @@ func (app *App) InitChainer(ctx sdk.Context, _ abci.RequestInitChain) abci.Respo
// CreateGenAccounts generates genesis accounts loaded with coins, and returns
// their addresses, pubkeys, and privkeys.
func CreateGenAccounts(numAccs int, genCoins sdk.Coins) (genAccs []auth.Account, addrs []sdk.Address, pubKeys []crypto.PubKey, privKeys []crypto.PrivKey) {
func CreateGenAccounts(numAccs int, genCoins sdk.Coins) (genAccs []auth.Account, addrs []sdk.AccAddress, pubKeys []crypto.PubKey, privKeys []crypto.PrivKey) {
for i := 0; i < numAccs; i++ {
privKey := crypto.GenPrivKeyEd25519()
pubKey := privKey.PubKey()
addr := pubKey.Address()
addr := sdk.AccAddress(pubKey.Address())
genAcc := &auth.BaseAccount{
Address: addr,
@ -166,19 +166,19 @@ func GeneratePrivKeys(n int) (keys []crypto.PrivKey) {
// GeneratePrivKeyAddressPairs generates a total of n private key, address
// pairs.
func GeneratePrivKeyAddressPairs(n int) (keys []crypto.PrivKey, addrs []sdk.Address) {
func GeneratePrivKeyAddressPairs(n int) (keys []crypto.PrivKey, addrs []sdk.AccAddress) {
keys = make([]crypto.PrivKey, n, n)
addrs = make([]sdk.Address, n, n)
addrs = make([]sdk.AccAddress, n, n)
for i := 0; i < n; i++ {
keys[i] = crypto.GenPrivKeyEd25519()
addrs[i] = keys[i].PubKey().Address()
addrs[i] = sdk.AccAddress(keys[i].PubKey().Address())
}
return
}
// RandomSetGenesis set genesis accounts with random coin values using the
// provided addresses and coin denominations.
func RandomSetGenesis(r *rand.Rand, app *App, addrs []sdk.Address, denoms []string) {
func RandomSetGenesis(r *rand.Rand, app *App, addrs []sdk.AccAddress, denoms []string) {
accts := make([]auth.Account, len(addrs), len(addrs))
randCoinIntervals := []BigInterval{
{sdk.NewIntWithDecimal(1, 0), sdk.NewIntWithDecimal(1, 1)},

View File

@ -19,7 +19,7 @@ var (
// testMsg is a mock transaction that has a validation which can fail.
type testMsg struct {
signers []sdk.Address
signers []sdk.AccAddress
positiveNum int64
}
@ -27,7 +27,7 @@ func (tx testMsg) Type() string { return msgType }
func (tx testMsg) GetMsg() sdk.Msg { return tx }
func (tx testMsg) GetMemo() string { return "" }
func (tx testMsg) GetSignBytes() []byte { return nil }
func (tx testMsg) GetSigners() []sdk.Address { return tx.signers }
func (tx testMsg) GetSigners() []sdk.AccAddress { return tx.signers }
func (tx testMsg) GetSignatures() []auth.StdSignature { return nil }
func (tx testMsg) ValidateBasic() sdk.Error {
if tx.positiveNum >= 0 {
@ -53,7 +53,7 @@ func TestCheckAndDeliverGenTx(t *testing.T) {
SetGenesis(mApp, accs)
ctxCheck := mApp.BaseApp.NewContext(true, abci.Header{})
msg := testMsg{signers: []sdk.Address{addrs[0]}, positiveNum: 1}
msg := testMsg{signers: []sdk.AccAddress{addrs[0]}, positiveNum: 1}
acct := mApp.AccountMapper.GetAccount(ctxCheck, addrs[0])
require.Equal(t, accs[0], acct.(*auth.BaseAccount))
@ -86,14 +86,14 @@ func TestCheckGenTx(t *testing.T) {
SetGenesis(mApp, accs)
msg1 := testMsg{signers: []sdk.Address{addrs[0]}, positiveNum: 1}
msg1 := testMsg{signers: []sdk.AccAddress{addrs[0]}, positiveNum: 1}
CheckGenTx(
t, mApp.BaseApp, []sdk.Msg{msg1},
[]int64{accs[0].GetAccountNumber()}, []int64{accs[0].GetSequence()},
true, privKeys[0],
)
msg2 := testMsg{signers: []sdk.Address{addrs[0]}, positiveNum: -1}
msg2 := testMsg{signers: []sdk.AccAddress{addrs[0]}, positiveNum: -1}
CheckGenTx(
t, mApp.BaseApp, []sdk.Msg{msg2},
[]int64{accs[0].GetAccountNumber()}, []int64{accs[0].GetSequence()},

View File

@ -64,6 +64,7 @@ func (app *App) RandomizedTestingFromSeed(
}
}
// SimpleRandomizedTestingFromSeed
func (app *App) SimpleRandomizedTestingFromSeed(
t *testing.T, seed int64, ops []TestAndRunMsg, setups []RandSetup,
invariants []Invariant, numKeys int, numBlocks int, blockSize int,

Some files were not shown because too many files have changed in this diff Show More