commit
96451b55ff
@ -38,6 +38,7 @@ jobs:
|
||||
command: |
|
||||
export PATH="$GOBIN:$PATH"
|
||||
make install
|
||||
make install_examples
|
||||
- persist_to_workspace:
|
||||
root: /tmp/workspace
|
||||
paths:
|
||||
@ -84,6 +85,22 @@ jobs:
|
||||
export PATH="$GOBIN:$PATH"
|
||||
make test_unit
|
||||
|
||||
test_cli:
|
||||
<<: *defaults
|
||||
parallelism: 1
|
||||
steps:
|
||||
- attach_workspace:
|
||||
at: /tmp/workspace
|
||||
- restore_cache:
|
||||
key: v1-pkg-cache
|
||||
- restore_cache:
|
||||
key: v1-tree-{{ .Environment.CIRCLE_SHA1 }}
|
||||
- run:
|
||||
name: Test cli
|
||||
command: |
|
||||
export PATH="$GOBIN:$PATH"
|
||||
make test_cli
|
||||
|
||||
test_cover:
|
||||
<<: *defaults
|
||||
parallelism: 4
|
||||
@ -137,6 +154,9 @@ workflows:
|
||||
- lint:
|
||||
requires:
|
||||
- setup_dependencies
|
||||
- test_cli:
|
||||
requires:
|
||||
- setup_dependencies
|
||||
- test_unit:
|
||||
requires:
|
||||
- setup_dependencies
|
||||
|
||||
2
.github/PULL_REQUEST_TEMPLATE.md
vendored
2
.github/PULL_REQUEST_TEMPLATE.md
vendored
@ -4,3 +4,5 @@
|
||||
* [ ] Updated all code comments where relevant
|
||||
* [ ] Wrote tests
|
||||
* [ ] Updated CHANGELOG.md
|
||||
* [ ] Updated Basecoin / other examples
|
||||
* [ ] Squashed related commits and prefixed with PR number per [coding standards](https://github.com/tendermint/coding/blob/master/README.md#merging-a-pr)
|
||||
|
||||
5
.gitignore
vendored
5
.gitignore
vendored
@ -19,8 +19,11 @@ baseapp/data/*
|
||||
coverage.txt
|
||||
profile.out
|
||||
|
||||
### Vagrant ###
|
||||
# Vagrant
|
||||
.vagrant/
|
||||
*.box
|
||||
*.log
|
||||
vagrant
|
||||
|
||||
# Graphviz
|
||||
dependency-graph.png
|
||||
328
CHANGELOG.md
328
CHANGELOG.md
@ -1,5 +1,86 @@
|
||||
# Changelog
|
||||
|
||||
BREAKING CHANGES
|
||||
* msg.GetSignBytes() now returns bech32-encoded addresses in all cases
|
||||
|
||||
FEATURES
|
||||
|
||||
IMPROVEMENTS
|
||||
* export command now writes current validator set for Tendermint
|
||||
* [tests] Application module tests now use a mock application
|
||||
|
||||
FIXES
|
||||
* [lcd] Switch to bech32 for addresses on all human readable inputs and outputs
|
||||
* [cli] Added `--gas` flag to specify transaction gas limit
|
||||
|
||||
## 0.18.0
|
||||
|
||||
*June 9, 2018*
|
||||
|
||||
BREAKING CHANGES
|
||||
|
||||
* [stake] candidate -> validator throughout (details in refactor comment)
|
||||
* [stake] delegate-bond -> delegation throughout
|
||||
* [stake] `gaiacli query validator` takes and argument instead of using the `--address-candidate` flag
|
||||
* [stake] introduce `gaiacli query delegations`
|
||||
* [stake] staking refactor
|
||||
* ValidatorsBonded store now take sorted pubKey-address instead of validator owner-address,
|
||||
is sorted like Tendermint by pk's address
|
||||
* store names more understandable
|
||||
* removed temporary ToKick store, just needs a local map!
|
||||
* removed distinction between candidates and validators
|
||||
* everything is now a validator
|
||||
* only validators with a status == bonded are actively validating/receiving rewards
|
||||
* Introduction of Unbonding fields, lowlevel logic throughout (not fully implemented with queue)
|
||||
* Introduction of PoolShares type within validators,
|
||||
replaces three rational fields (BondedShares, UnbondingShares, UnbondedShares
|
||||
* [x/auth] move stuff specific to auth anteHandler to the auth module rather than the types folder. This includes:
|
||||
* StdTx (and its related stuff i.e. StdSignDoc, etc)
|
||||
* StdFee
|
||||
* StdSignature
|
||||
* Account interface
|
||||
* Related to this organization, I also:
|
||||
* [x/auth] got rid of AccountMapper interface (in favor of the struct already in auth module)
|
||||
* [x/auth] removed the FeeHandler function from the AnteHandler, Replaced with FeeKeeper
|
||||
* [x/auth] Removed GetSignatures() from Tx interface (as different Tx styles might use something different than StdSignature)
|
||||
* [store] Removed SubspaceIterator and ReverseSubspaceIterator from KVStore interface and replaced them with helper functions in /types
|
||||
* [cli] rearranged commands under subcommands
|
||||
* [stake] remove Tick and add EndBlocker
|
||||
* Switch to bech32cosmos on all human readable inputs and outputs
|
||||
|
||||
|
||||
FEATURES
|
||||
|
||||
* [x/auth] Added ability to change pubkey to auth module
|
||||
* [baseapp] baseapp now has settable functions for filtering peers by address/port & public key
|
||||
* [sdk] Gas consumption is now measured as transactions are executed
|
||||
* Transactions which run out of gas stop execution and revert state changes
|
||||
* A "simulate" query has been added to determine how much gas a transaction will need
|
||||
* Modules can include their own gas costs for execution of particular message types
|
||||
* [stake] Seperation of fee distribution to a new module
|
||||
* [stake] Creation of a validator/delegation generics in `/types`
|
||||
* [stake] Helper Description of the store in x/stake/store.md
|
||||
* [stake] removed use of caches in the stake keeper
|
||||
* [stake] Added REST API
|
||||
* [Makefile] Added terraform/ansible playbooks to easily create remote testnets on Digital Ocean
|
||||
|
||||
|
||||
BUG FIXES
|
||||
|
||||
* [stake] staking delegator shares exchange rate now relative to equivalent-bonded-tokens the validator has instead of bonded tokens
|
||||
^ this is important for unbonded validators in the power store!
|
||||
* [cli] fixed cli-bash tests
|
||||
* [ci] added cli-bash tests
|
||||
* [basecoin] updated basecoin for stake and slashing
|
||||
* [docs] fixed references to old cli commands
|
||||
* [docs] Downgraded Swagger to v2 for downstream compatibility
|
||||
* auto-sequencing transactions correctly
|
||||
* query sequence via account store
|
||||
* fixed duplicate pub_key in stake.Validator
|
||||
* Auto-sequencing now works correctly
|
||||
* [gaiacli] Fix error message when account isn't found when running gaiacli account
|
||||
|
||||
|
||||
## 0.17.5
|
||||
|
||||
*June 5, 2018*
|
||||
@ -21,7 +102,7 @@ Update to Tendermint v0.19.6 (fix fast-sync halt)
|
||||
|
||||
## 0.17.2
|
||||
|
||||
*May 20, 2018*
|
||||
_May 20, 2018_
|
||||
|
||||
Update to Tendermint v0.19.5 (reduce WAL use, bound the mempool and some rpcs, improve logging)
|
||||
|
||||
@ -34,13 +115,14 @@ Update to Tendermint v0.19.4 (fixes a consensus bug and improves logging)
|
||||
BREAKING CHANGES
|
||||
|
||||
* [stake] MarshalJSON -> MarshalBinary
|
||||
* Queries against the store must be prefixed with the path "/store"
|
||||
|
||||
FEATURES
|
||||
|
||||
* [gaiacli] Support queries for candidates, delegator-bonds
|
||||
* [gaiad] Added `gaiad export` command to export current state to JSON
|
||||
* [x/bank] Tx tags with sender/recipient for indexing & later retrieval
|
||||
* [x/stake] Tx tags with delegator/candidate for delegation & unbonding, and candidate info for declare candidate / edit candidacy
|
||||
* [x/stake] Tx tags with delegator/candidate for delegation & unbonding, and candidate info for declare candidate / edit validator
|
||||
|
||||
IMPROVEMENTS
|
||||
|
||||
@ -56,48 +138,53 @@ BUG FIXES
|
||||
|
||||
* Auto-sequencing now works correctly
|
||||
|
||||
|
||||
## 0.16.0 (May 14th, 2018)
|
||||
|
||||
BREAKING CHANGES
|
||||
|
||||
* Move module REST/CLI packages to x/[module]/client/rest and x/[module]/client/cli
|
||||
* Gaia simple-staking bond and unbond functions replaced
|
||||
* Gaia simple-staking bond and unbond functions replaced
|
||||
* [stake] Delegator bonds now store the height at which they were updated
|
||||
* All module keepers now require a codespace, see basecoin or democoin for usage
|
||||
* Many changes to names throughout
|
||||
* Type as a prefix naming convention applied (ex. BondMsg -> MsgBond)
|
||||
* Many changes to names throughout
|
||||
* Type as a prefix naming convention applied (ex. BondMsg -> MsgBond)
|
||||
* Removed redundancy in names (ex. stake.StakeKeeper -> stake.Keeper)
|
||||
* Removed SealedAccountMapper
|
||||
* gaiad init now requires use of `--name` flag
|
||||
* gaiad init now requires use of `--name` flag
|
||||
* Removed Get from Msg interface
|
||||
* types/rational now extends big.Rat
|
||||
|
||||
FEATURES:
|
||||
|
||||
* Gaia stake commands include, DeclareCandidacy, EditCandidacy, Delegate, Unbond
|
||||
* Gaia stake commands include, CreateValidator, EditValidator, Delegate, Unbond
|
||||
* MountStoreWithDB without providing a custom store works.
|
||||
* Repo is now lint compliant / GoMetaLinter with tendermint-lint integrated into CI
|
||||
* Better key output, pubkey go-amino hex bytes now output by default
|
||||
* gaiad init overhaul
|
||||
* Create genesis transactions with `gaiad init gen-tx`
|
||||
* Create genesis transactions with `gaiad init gen-tx`
|
||||
* New genesis account keys are automatically added to the client keybase (introduce `--client-home` flag)
|
||||
* Initialize with genesis txs using `--gen-txs` flag
|
||||
* Context now has access to the application-configured logger
|
||||
|
||||
* Add (non-proof) subspace query helper functions
|
||||
* Add more staking query functions: candidates, delegator-bonds
|
||||
|
||||
BUG FIXES
|
||||
|
||||
* Gaia now uses stake, ported from github.com/cosmos/gaia
|
||||
|
||||
|
||||
## 0.15.1 (April 29, 2018)
|
||||
|
||||
IMPROVEMENTS:
|
||||
|
||||
* Update Tendermint to v0.19.1 (includes many rpc fixes)
|
||||
|
||||
|
||||
## 0.15.0 (April 29, 2018)
|
||||
|
||||
NOTE: v0.15.0 is a large breaking change that updates the encoding scheme to use
|
||||
[Amino](github.com/tendermint/go-amino).
|
||||
[Amino](github.com/tendermint/go-amino).
|
||||
|
||||
For details on how this changes encoding for public keys and addresses,
|
||||
see the [docs](https://github.com/tendermint/tendermint/blob/v0.19.1/docs/specification/new-spec/encoding.md#public-key-cryptography).
|
||||
@ -115,6 +202,7 @@ FEATURES:
|
||||
* Add FeeHandler to ante handler
|
||||
|
||||
BUG FIXES
|
||||
|
||||
* MountStoreWithDB without providing a custom store works.
|
||||
|
||||
## 0.14.1 (April 9, 2018)
|
||||
@ -143,7 +231,7 @@ FEATURES:
|
||||
BUG FIXES
|
||||
|
||||
* [client] Reuse Tendermint RPC client to avoid excessive open files
|
||||
* [client] Fix setting log level
|
||||
* [client] Fix setting log level
|
||||
* [basecoin] Sort coins in genesis
|
||||
|
||||
## 0.13.1 (April 3, 2018)
|
||||
@ -216,11 +304,12 @@ FEATURES
|
||||
IMPROVEMENTS
|
||||
|
||||
* Lots more tests!
|
||||
* [client/builder] Helpers for forming and signing transactions
|
||||
* [client/builder] Helpers for forming and signing transactions
|
||||
* [types] sdk.Address
|
||||
* [specs] Staking
|
||||
|
||||
BUG FIXES
|
||||
|
||||
* [x/auth] Fix setting pubkey on new account
|
||||
* [x/auth] Require signatures to include the sequences
|
||||
* [baseapp] Dont panic on nil handler
|
||||
@ -281,7 +370,7 @@ BREAKING CHANGES
|
||||
|
||||
* Massive refactor. Basecoin works. Still needs <3
|
||||
|
||||
## 0.8.1
|
||||
## 0.8.1
|
||||
|
||||
* Updates for dependencies
|
||||
|
||||
@ -319,29 +408,30 @@ Make lots of small cli fixes that arose when people were using the tools for
|
||||
the testnet.
|
||||
|
||||
IMPROVEMENTS:
|
||||
- basecoin
|
||||
- `basecoin start` supports all flags that `tendermint node` does, such as
|
||||
`--rpc.laddr`, `--p2p.seeds`, and `--p2p.skip_upnp`
|
||||
- fully supports `--log_level` and `--trace` for logger configuration
|
||||
- merkleeyes no longers spams the logs... unless you want it
|
||||
- Example: `basecoin start --log_level="merkleeyes:info,state:info,*:error"`
|
||||
- Example: `basecoin start --log_level="merkleeyes:debug,state:info,*:error"`
|
||||
- basecli
|
||||
- `basecli init` is more intelligent and only complains if there really was
|
||||
a connected chain, not just random files
|
||||
- support `localhost:46657` or `http://localhost:46657` format for nodes,
|
||||
not just `tcp://localhost:46657`
|
||||
- Add `--genesis` to init to specify chain-id and validator hash
|
||||
- Example: `basecli init --node=localhost:46657 --genesis=$HOME/.basecoin/genesis.json`
|
||||
- `basecli rpc` has a number of methods to easily accept tendermint rpc, and verifies what it can
|
||||
|
||||
* basecoin
|
||||
* `basecoin start` supports all flags that `tendermint node` does, such as
|
||||
`--rpc.laddr`, `--p2p.seeds`, and `--p2p.skip_upnp`
|
||||
* fully supports `--log_level` and `--trace` for logger configuration
|
||||
* merkleeyes no longers spams the logs... unless you want it
|
||||
* Example: `basecoin start --log_level="merkleeyes:info,state:info,*:error"`
|
||||
* Example: `basecoin start --log_level="merkleeyes:debug,state:info,*:error"`
|
||||
* basecli
|
||||
* `basecli init` is more intelligent and only complains if there really was
|
||||
a connected chain, not just random files
|
||||
* support `localhost:46657` or `http://localhost:46657` format for nodes,
|
||||
not just `tcp://localhost:46657`
|
||||
* Add `--genesis` to init to specify chain-id and validator hash
|
||||
* Example: `basecli init --node=localhost:46657 --genesis=$HOME/.basecoin/genesis.json`
|
||||
* `basecli rpc` has a number of methods to easily accept tendermint rpc, and verifies what it can
|
||||
|
||||
BUG FIXES:
|
||||
- basecli
|
||||
- `basecli query account` accepts hex account address with or without `0x`
|
||||
prefix
|
||||
- gives error message when running commands on an unitialized chain, rather
|
||||
than some unintelligable panic
|
||||
|
||||
* basecli
|
||||
* `basecli query account` accepts hex account address with or without `0x`
|
||||
prefix
|
||||
* gives error message when running commands on an unitialized chain, rather
|
||||
than some unintelligable panic
|
||||
|
||||
## 0.6.0 (June 22, 2017)
|
||||
|
||||
@ -349,111 +439,118 @@ Make the basecli command the only way to use client-side, to enforce best
|
||||
security practices. Lots of enhancements to get it up to production quality.
|
||||
|
||||
BREAKING CHANGES:
|
||||
- ./cmd/commands -> ./cmd/basecoin/commands
|
||||
- basecli
|
||||
- `basecli proof state get` -> `basecli query key`
|
||||
- `basecli proof tx get` -> `basecli query tx`
|
||||
- `basecli proof state get --app=account` -> `basecli query account`
|
||||
- use `--chain-id` not `--chainid` for consistency
|
||||
- update to use `--trace` not `--debug` for stack traces on errors
|
||||
- complete overhaul on how tx and query subcommands are added. (see counter or trackomatron for examples)
|
||||
- no longer supports counter app (see new countercli)
|
||||
- basecoin
|
||||
- `basecoin init` takes an argument, an address to allocate funds to in the genesis
|
||||
- removed key2.json
|
||||
- removed all client side functionality from it (use basecli now for proofs)
|
||||
- no tx subcommand
|
||||
- no query subcommand
|
||||
- no account (query) subcommand
|
||||
- a few other random ones...
|
||||
- enhanced relay subcommand
|
||||
- relay start did what relay used to do
|
||||
- relay init registers both chains on one another (to set it up so relay start just works)
|
||||
- docs
|
||||
- removed `example-plugin`, put `counter` inside `docs/guide`
|
||||
- app
|
||||
- Implements ABCI handshake by proxying merkleeyes.Info()
|
||||
|
||||
* ./cmd/commands -> ./cmd/basecoin/commands
|
||||
* basecli
|
||||
* `basecli proof state get` -> `basecli query key`
|
||||
* `basecli proof tx get` -> `basecli query tx`
|
||||
* `basecli proof state get --app=account` -> `basecli query account`
|
||||
* use `--chain-id` not `--chainid` for consistency
|
||||
* update to use `--trace` not `--debug` for stack traces on errors
|
||||
* complete overhaul on how tx and query subcommands are added. (see counter or trackomatron for examples)
|
||||
* no longer supports counter app (see new countercli)
|
||||
* basecoin
|
||||
* `basecoin init` takes an argument, an address to allocate funds to in the genesis
|
||||
* removed key2.json
|
||||
* removed all client side functionality from it (use basecli now for proofs)
|
||||
* no tx subcommand
|
||||
* no query subcommand
|
||||
* no account (query) subcommand
|
||||
* a few other random ones...
|
||||
* enhanced relay subcommand
|
||||
* relay start did what relay used to do
|
||||
* relay init registers both chains on one another (to set it up so relay start just works)
|
||||
* docs
|
||||
* removed `example-plugin`, put `counter` inside `docs/guide`
|
||||
* app
|
||||
* Implements ABCI handshake by proxying merkleeyes.Info()
|
||||
|
||||
IMPROVEMENTS:
|
||||
- `basecoin init` support `--chain-id`
|
||||
- intergrates tendermint 0.10.0 (not the rc-2, but the real thing)
|
||||
- commands return error code (1) on failure for easier script testing
|
||||
- add `reset_all` to basecli, and never delete keys on `init`
|
||||
- new shutil based unit tests, with better coverage of the cli actions
|
||||
- just `make fresh` when things are getting stale ;)
|
||||
|
||||
* `basecoin init` support `--chain-id`
|
||||
* intergrates tendermint 0.10.0 (not the rc-2, but the real thing)
|
||||
* commands return error code (1) on failure for easier script testing
|
||||
* add `reset_all` to basecli, and never delete keys on `init`
|
||||
* new shutil based unit tests, with better coverage of the cli actions
|
||||
* just `make fresh` when things are getting stale ;)
|
||||
|
||||
BUG FIXES:
|
||||
- app: no longer panics on missing app_options in genesis (thanks, anton)
|
||||
- docs: updated all docs... again
|
||||
- ibc: fix panic on getting BlockID from commit without 100% precommits (still a TODO)
|
||||
|
||||
* app: no longer panics on missing app_options in genesis (thanks, anton)
|
||||
* docs: updated all docs... again
|
||||
* ibc: fix panic on getting BlockID from commit without 100% precommits (still a TODO)
|
||||
|
||||
## 0.5.2 (June 2, 2017)
|
||||
|
||||
BUG FIXES:
|
||||
- fix parsing of the log level from Tendermint config (#97)
|
||||
|
||||
* fix parsing of the log level from Tendermint config (#97)
|
||||
|
||||
## 0.5.1 (May 30, 2017)
|
||||
|
||||
BUG FIXES:
|
||||
- fix ibc demo app to use proper tendermint flags, 0.10.0-rc2 compatibility
|
||||
- Make sure all cli uses new json.Marshal not wire.JSONBytes
|
||||
|
||||
* fix ibc demo app to use proper tendermint flags, 0.10.0-rc2 compatibility
|
||||
* Make sure all cli uses new json.Marshal not wire.JSONBytes
|
||||
|
||||
## 0.5.0 (May 27, 2017)
|
||||
|
||||
BREAKING CHANGES:
|
||||
- only those related to the tendermint 0.9 -> 0.10 upgrade
|
||||
|
||||
* only those related to the tendermint 0.9 -> 0.10 upgrade
|
||||
|
||||
IMPROVEMENTS:
|
||||
- basecoin cli
|
||||
- integrates tendermint 0.10.0 and unifies cli (init, unsafe_reset_all, ...)
|
||||
- integrate viper, all command line flags can also be defined in environmental variables or config.toml
|
||||
- genesis file
|
||||
- you can define accounts with either address or pub_key
|
||||
- sorts coins for you, so no silent errors if not in alphabetical order
|
||||
- [light-client](https://github.com/tendermint/light-client) integration
|
||||
- no longer must you trust the node you connect to, prove everything!
|
||||
- new [basecli command](./cmd/basecli/README.md)
|
||||
- integrated [key management](https://github.com/tendermint/go-crypto/blob/master/cmd/README.md), stored encrypted locally
|
||||
- tracks validator set changes and proves everything from one initial validator seed
|
||||
- `basecli proof state` gets complete proofs for any abci state
|
||||
- `basecli proof tx` gets complete proof where a tx was stored in the chain
|
||||
- `basecli proxy` exposes tendermint rpc, but only passes through results after doing complete verification
|
||||
|
||||
* basecoin cli
|
||||
* integrates tendermint 0.10.0 and unifies cli (init, unsafe_reset_all, ...)
|
||||
* integrate viper, all command line flags can also be defined in environmental variables or config.toml
|
||||
* genesis file
|
||||
* you can define accounts with either address or pub_key
|
||||
* sorts coins for you, so no silent errors if not in alphabetical order
|
||||
* [light-client](https://github.com/tendermint/light-client) integration
|
||||
* no longer must you trust the node you connect to, prove everything!
|
||||
* new [basecli command](./cmd/basecli/README.md)
|
||||
* integrated [key management](https://github.com/tendermint/go-crypto/blob/master/cmd/README.md), stored encrypted locally
|
||||
* tracks validator set changes and proves everything from one initial validator seed
|
||||
* `basecli proof state` gets complete proofs for any abci state
|
||||
* `basecli proof tx` gets complete proof where a tx was stored in the chain
|
||||
* `basecli proxy` exposes tendermint rpc, but only passes through results after doing complete verification
|
||||
|
||||
BUG FIXES:
|
||||
- no more silently ignored error with invalid coin names (eg. "17.22foo coin" used to parse as "17 foo", not warning/error)
|
||||
|
||||
* no more silently ignored error with invalid coin names (eg. "17.22foo coin" used to parse as "17 foo", not warning/error)
|
||||
|
||||
## 0.4.1 (April 26, 2017)
|
||||
|
||||
BUG FIXES:
|
||||
|
||||
- Fix bug in `basecoin unsafe_reset_X` where the `priv_validator.json` was not being reset
|
||||
* Fix bug in `basecoin unsafe_reset_X` where the `priv_validator.json` was not being reset
|
||||
|
||||
## 0.4.0 (April 21, 2017)
|
||||
|
||||
BREAKING CHANGES:
|
||||
|
||||
- CLI now uses Cobra, which forced changes to some of the flag names and orderings
|
||||
* CLI now uses Cobra, which forced changes to some of the flag names and orderings
|
||||
|
||||
IMPROVEMENTS:
|
||||
|
||||
- `basecoin init` doesn't generate error if already initialized
|
||||
- Much more testing
|
||||
* `basecoin init` doesn't generate error if already initialized
|
||||
* Much more testing
|
||||
|
||||
## 0.3.1 (March 23, 2017)
|
||||
|
||||
IMPROVEMENTS:
|
||||
|
||||
- CLI returns exit code 1 and logs error before exiting
|
||||
* CLI returns exit code 1 and logs error before exiting
|
||||
|
||||
## 0.3.0 (March 23, 2017)
|
||||
|
||||
BREAKING CHANGES:
|
||||
|
||||
- Remove `--data` flag and use `BCHOME` to set the home directory (defaults to `~/.basecoin`)
|
||||
- Remove `--in-proc` flag and start Tendermint in-process by default (expect Tendermint files in $BCHOME/tendermint).
|
||||
To start just the ABCI app/server, use `basecoin start --without-tendermint`.
|
||||
- Consolidate genesis files so the Basecoin genesis is an object under `app_options` in Tendermint genesis. For instance:
|
||||
* Remove `--data` flag and use `BCHOME` to set the home directory (defaults to `~/.basecoin`)
|
||||
* Remove `--in-proc` flag and start Tendermint in-process by default (expect Tendermint files in $BCHOME/tendermint).
|
||||
To start just the ABCI app/server, use `basecoin start --without-tendermint`.
|
||||
* Consolidate genesis files so the Basecoin genesis is an object under `app_options` in Tendermint genesis. For instance:
|
||||
|
||||
```
|
||||
{
|
||||
@ -497,48 +594,45 @@ We also changed `chainID` to `chain_id` and consolidated to have just one of the
|
||||
|
||||
FEATURES:
|
||||
|
||||
- Introduce `basecoin init` and `basecoin unsafe_reset_all`
|
||||
* Introduce `basecoin init` and `basecoin unsafe_reset_all`
|
||||
|
||||
## 0.2.0 (March 6, 2017)
|
||||
|
||||
BREAKING CHANGES:
|
||||
|
||||
- Update to ABCI v0.4.0 and Tendermint v0.9.0
|
||||
- Coins are specified on the CLI as `Xcoin`, eg. `5gold`
|
||||
- `Cost` is now `Fee`
|
||||
* Update to ABCI v0.4.0 and Tendermint v0.9.0
|
||||
* Coins are specified on the CLI as `Xcoin`, eg. `5gold`
|
||||
* `Cost` is now `Fee`
|
||||
|
||||
FEATURES:
|
||||
|
||||
- CLI for sending transactions and querying the state,
|
||||
designed to be easily extensible as plugins are implemented
|
||||
- Run Basecoin in-process with Tendermint
|
||||
- Add `/account` path in Query
|
||||
- IBC plugin for InterBlockchain Communication
|
||||
- Demo script of IBC between two chains
|
||||
* CLI for sending transactions and querying the state,
|
||||
designed to be easily extensible as plugins are implemented
|
||||
* Run Basecoin in-process with Tendermint
|
||||
* Add `/account` path in Query
|
||||
* IBC plugin for InterBlockchain Communication
|
||||
* Demo script of IBC between two chains
|
||||
|
||||
IMPROVEMENTS:
|
||||
|
||||
- Use new Tendermint `/commit` endpoint for crafting IBC transactions
|
||||
- More unit tests
|
||||
- Use go-crypto S structs and go-data for more standard JSON
|
||||
- Demo uses fewer sleeps
|
||||
* Use new Tendermint `/commit` endpoint for crafting IBC transactions
|
||||
* More unit tests
|
||||
* Use go-crypto S structs and go-data for more standard JSON
|
||||
* Demo uses fewer sleeps
|
||||
|
||||
BUG FIXES:
|
||||
|
||||
- Various little fixes in coin arithmetic
|
||||
- More commit validation in IBC
|
||||
- Return results from transactions
|
||||
* Various little fixes in coin arithmetic
|
||||
* More commit validation in IBC
|
||||
* Return results from transactions
|
||||
|
||||
## PreHistory
|
||||
|
||||
##### January 14-18, 2017
|
||||
|
||||
- Update to Tendermint v0.8.0
|
||||
- Cleanup a bit and release blog post
|
||||
* Update to Tendermint v0.8.0
|
||||
* Cleanup a bit and release blog post
|
||||
|
||||
##### September 22, 2016
|
||||
|
||||
- Basecoin compiles again
|
||||
|
||||
|
||||
|
||||
* Basecoin compiles again
|
||||
|
||||
45
Gopkg.lock
generated
45
Gopkg.lock
generated
@ -13,6 +13,12 @@
|
||||
packages = ["btcec"]
|
||||
revision = "86fed781132ac890ee03e906e4ecd5d6fa180c64"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/btcsuite/btcutil"
|
||||
packages = ["bech32"]
|
||||
revision = "d4cc87b860166d00d6b5b9e0d3b3d71d6088d4d4"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/davecgh/go-spew"
|
||||
packages = ["spew"]
|
||||
@ -250,7 +256,7 @@
|
||||
"leveldb/table",
|
||||
"leveldb/util"
|
||||
]
|
||||
revision = "5d6fca44a948d2be89a9702de7717f0168403d3d"
|
||||
revision = "e2150783cd35f5b607daca48afd8c57ec54cc995"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/tendermint/abci"
|
||||
@ -261,8 +267,8 @@
|
||||
"server",
|
||||
"types"
|
||||
]
|
||||
revision = "78a8905690ef54f9d57e3b2b0ee7ad3a04ef3f1f"
|
||||
version = "v0.10.3"
|
||||
revision = "ebee2fe114020aa49c70bbbae50b7079fc7e7b90"
|
||||
version = "v0.11.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
@ -292,17 +298,14 @@
|
||||
revision = "915416979bf70efa4bcbf1c6cd5d64c5fff9fc19"
|
||||
version = "v0.6.2"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/tendermint/go-wire"
|
||||
packages = ["."]
|
||||
revision = "fa721242b042ecd4c6ed1a934ee740db4f74e45c"
|
||||
version = "v0.7.3"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/tendermint/iavl"
|
||||
packages = ["."]
|
||||
revision = "fd37a0fa3a7454423233bc3d5ea828f38e0af787"
|
||||
version = "v0.7.0"
|
||||
packages = [
|
||||
".",
|
||||
"sha256truncated"
|
||||
]
|
||||
revision = "c9206995e8f948e99927f5084a88a7e94ca256da"
|
||||
version = "v0.8.0-rc0"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/tendermint/tendermint"
|
||||
@ -344,13 +347,15 @@
|
||||
"types",
|
||||
"version"
|
||||
]
|
||||
revision = "775fef31c2b8fb7ea36f0d57bae3bfa74d353100"
|
||||
version = "v0.19.9-rc0"
|
||||
revision = "27bd1deabe4ba6a2d9b463b8f3e3f1e31b993e61"
|
||||
version = "v0.20.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "develop"
|
||||
name = "github.com/tendermint/tmlibs"
|
||||
packages = [
|
||||
"autofile",
|
||||
"bech32",
|
||||
"cli",
|
||||
"cli/flags",
|
||||
"clist",
|
||||
@ -358,10 +363,10 @@
|
||||
"db",
|
||||
"flowrate",
|
||||
"log",
|
||||
"merkle"
|
||||
"merkle",
|
||||
"merkle/tmhash"
|
||||
]
|
||||
revision = "692f1d86a6e2c0efa698fd1e4541b68c74ffaf38"
|
||||
version = "v0.8.4"
|
||||
revision = "640af0205d98d1f45fb2f912f9c35c8bf816adc9"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
@ -377,7 +382,7 @@
|
||||
"ripemd160",
|
||||
"salsa20/salsa"
|
||||
]
|
||||
revision = "78e79280f680f7dd6b8e48c751887111ebdbcbd8"
|
||||
revision = "8ac0e0d97ce45cd83d1d7243c060cb8461dda5e9"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
@ -397,7 +402,7 @@
|
||||
branch = "master"
|
||||
name = "golang.org/x/sys"
|
||||
packages = ["unix"]
|
||||
revision = "c11f84a56e43e20a78cee75a7c034031ecf57d1f"
|
||||
revision = "9527bec2660bd847c050fda93a0f0c6dee0800bb"
|
||||
|
||||
[[projects]]
|
||||
name = "golang.org/x/text"
|
||||
@ -458,6 +463,6 @@
|
||||
[solve-meta]
|
||||
analyzer-name = "dep"
|
||||
analyzer-version = 1
|
||||
inputs-digest = "71d11bd2a8f3f46ba3fd16759b501ad5b6b48037717d82020ebb25e021b67117"
|
||||
inputs-digest = "31f69b235b2d8f879a215c9e8ca0919adc62d21f6830b17931a3a0efb058721f"
|
||||
solver-name = "gps-cdcl"
|
||||
solver-version = 1
|
||||
|
||||
15
Gopkg.toml
15
Gopkg.toml
@ -54,32 +54,28 @@
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/tendermint/abci"
|
||||
version = "~0.10.3"
|
||||
version = "=0.11.0"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/tendermint/go-crypto"
|
||||
version = "~0.6.2"
|
||||
|
||||
[[override]]
|
||||
name = "github.com/tendermint/go-wire"
|
||||
version = "0.7.3"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/tendermint/go-amino"
|
||||
version = "=0.9.9"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/tendermint/iavl"
|
||||
version = "~0.7.0"
|
||||
version = "0.8.0-rc0"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/tendermint/tendermint"
|
||||
version = "0.19.9-rc0"
|
||||
version = "=0.20.0"
|
||||
|
||||
[[override]]
|
||||
name = "github.com/tendermint/tmlibs"
|
||||
version = "~0.8.4"
|
||||
|
||||
branch = "develop"
|
||||
|
||||
# this got updated and broke, so locked to an old working commit ...
|
||||
[[override]]
|
||||
name = "google.golang.org/genproto"
|
||||
@ -88,4 +84,3 @@
|
||||
[prune]
|
||||
go-tests = true
|
||||
unused-packages = true
|
||||
|
||||
|
||||
29
Makefile
29
Makefile
@ -70,7 +70,7 @@ get_vendor_deps:
|
||||
draw_deps:
|
||||
@# requires brew install graphviz or apt-get install graphviz
|
||||
go get github.com/RobotsAndPencils/goviz
|
||||
@goviz -i github.com/tendermint/tendermint/cmd/tendermint -d 3 | dot -Tpng -o dependency-graph.png
|
||||
@goviz -i github.com/cosmos/cosmos-sdk/cmd/gaia/cmd/gaiad -d 2 | dot -Tpng -o dependency-graph.png
|
||||
|
||||
|
||||
########################################
|
||||
@ -126,7 +126,32 @@ devdoc_update:
|
||||
docker pull tendermint/devdoc
|
||||
|
||||
|
||||
########################################
|
||||
### Remote validator nodes using terraform and ansible
|
||||
|
||||
# Build linux binary
|
||||
build-linux:
|
||||
GOOS=linux GOARCH=amd64 $(MAKE) build
|
||||
|
||||
TESTNET_NAME?=remotenet
|
||||
SERVERS?=4
|
||||
BINARY=$(CURDIR)/build/gaiad
|
||||
remotenet-start:
|
||||
@if [ -z "$(DO_API_TOKEN)" ]; then echo "DO_API_TOKEN environment variable not set." ; false ; fi
|
||||
@if ! [ -f $(HOME)/.ssh/id_rsa.pub ]; then ssh-keygen ; fi
|
||||
@if [ -z "`file $(BINARY) | grep 'ELF 64-bit'`" ]; then echo "Please build a linux binary using 'make build-linux'." ; false ; fi
|
||||
cd networks/remote/terraform && terraform init && terraform apply -var DO_API_TOKEN="$(DO_API_TOKEN)" -var SSH_PUBLIC_FILE="$(HOME)/.ssh/id_rsa.pub" -var SSH_PRIVATE_FILE="$(HOME)/.ssh/id_rsa" -var TESTNET_NAME="$(TESTNET_NAME)" -var SERVERS="$(SERVERS)"
|
||||
cd networks/remote/ansible && ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook -i inventory/digital_ocean.py -l "$(TESTNET_NAME)" -e BINARY=$(BINARY) -e TESTNET_NAME="$(TESTNET_NAME)" setup-validators.yml
|
||||
cd networks/remote/ansible && ansible-playbook -i inventory/digital_ocean.py -l "$(TESTNET_NAME)" start.yml
|
||||
|
||||
remotenet-stop:
|
||||
@if [ -z "$(DO_API_TOKEN)" ]; then echo "DO_API_TOKEN environment variable not set." ; false ; fi
|
||||
cd networks/remote/terraform && terraform destroy -var DO_API_TOKEN="$(DO_API_TOKEN)" -var SSH_PUBLIC_FILE="$(HOME)/.ssh/id_rsa.pub" -var SSH_PRIVATE_FILE="$(HOME)/.ssh/id_rsa"
|
||||
|
||||
remotenet-status:
|
||||
cd networks/remote/ansible && ansible-playbook -i inventory/digital_ocean.py -l "$(TESTNET_NAME)" status.yml
|
||||
|
||||
# To avoid unintended conflicts with file names, always add to .PHONY
|
||||
# unless there is a reason not to.
|
||||
# https://www.gnu.org/software/make/manual/html_node/Phony-Targets.html
|
||||
.PHONY: build build_examples install install_examples dist check_tools get_tools get_vendor_deps draw_deps test test_cli test_unit test_cover test_lint benchmark devdoc_init devdoc devdoc_save devdoc_update
|
||||
.PHONY: build build_examples install install_examples dist check_tools get_tools get_vendor_deps draw_deps test test_cli test_unit test_cover test_lint benchmark devdoc_init devdoc devdoc_save devdoc_update remotenet-start remotenet-stop remotenet-status
|
||||
|
||||
@ -16,7 +16,7 @@ master | [
|
||||
**Note**: Requires [Go 1.10+](https://golang.org/dl/)
|
||||
|
||||
|
||||
## Overview
|
||||
|
||||
@ -3,6 +3,7 @@ package baseapp
|
||||
import (
|
||||
"fmt"
|
||||
"runtime/debug"
|
||||
"strings"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
|
||||
@ -14,6 +15,7 @@ import (
|
||||
"github.com/cosmos/cosmos-sdk/store"
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
"github.com/cosmos/cosmos-sdk/wire"
|
||||
"github.com/cosmos/cosmos-sdk/x/auth"
|
||||
)
|
||||
|
||||
// Key to store the header in the DB itself.
|
||||
@ -22,11 +24,24 @@ import (
|
||||
// and to avoid affecting the Merkle root.
|
||||
var dbHeaderKey = []byte("header")
|
||||
|
||||
// Enum mode for app.runTx
|
||||
type runTxMode uint8
|
||||
|
||||
const (
|
||||
// Check a transaction
|
||||
runTxModeCheck runTxMode = iota
|
||||
// Simulate a transaction
|
||||
runTxModeSimulate runTxMode = iota
|
||||
// Deliver a transaction
|
||||
runTxModeDeliver runTxMode = iota
|
||||
)
|
||||
|
||||
// The ABCI application
|
||||
type BaseApp struct {
|
||||
// initialized on creation
|
||||
Logger log.Logger
|
||||
name string // application name from abci.Info
|
||||
cdc *wire.Codec // Amino codec
|
||||
db dbm.DB // common DB backend
|
||||
cms sdk.CommitMultiStore // Main (uncached) state
|
||||
router Router // handle any kind of message
|
||||
@ -37,9 +52,11 @@ type BaseApp struct {
|
||||
anteHandler sdk.AnteHandler // ante handler for fee and auth
|
||||
|
||||
// may be nil
|
||||
initChainer sdk.InitChainer // initialize state with validators and state blob
|
||||
beginBlocker sdk.BeginBlocker // logic to run before any txs
|
||||
endBlocker sdk.EndBlocker // logic to run after all txs, and to determine valset changes
|
||||
initChainer sdk.InitChainer // initialize state with validators and state blob
|
||||
beginBlocker sdk.BeginBlocker // logic to run before any txs
|
||||
endBlocker sdk.EndBlocker // logic to run after all txs, and to determine valset changes
|
||||
addrPeerFilter sdk.PeerFilter // filter peers by address and port
|
||||
pubkeyPeerFilter sdk.PeerFilter // filter peers by public key
|
||||
|
||||
//--------------------
|
||||
// Volatile
|
||||
@ -48,9 +65,10 @@ type BaseApp struct {
|
||||
// See methods setCheckState and setDeliverState.
|
||||
// .valUpdates accumulate in DeliverTx and are reset in BeginBlock.
|
||||
// QUESTION: should we put valUpdates in the deliverState.ctx?
|
||||
checkState *state // for CheckTx
|
||||
deliverState *state // for DeliverTx
|
||||
valUpdates []abci.Validator // cached validator changes from DeliverTx
|
||||
checkState *state // for CheckTx
|
||||
deliverState *state // for DeliverTx
|
||||
valUpdates []abci.Validator // cached validator changes from DeliverTx
|
||||
signedValidators []abci.SigningValidator // absent validators from begin block
|
||||
}
|
||||
|
||||
var _ abci.Application = (*BaseApp)(nil)
|
||||
@ -61,6 +79,7 @@ func NewBaseApp(name string, cdc *wire.Codec, logger log.Logger, db dbm.DB) *Bas
|
||||
app := &BaseApp{
|
||||
Logger: logger,
|
||||
name: name,
|
||||
cdc: cdc,
|
||||
db: db,
|
||||
cms: store.NewCommitMultiStore(db),
|
||||
router: NewRouter(),
|
||||
@ -108,7 +127,7 @@ func (app *BaseApp) SetTxDecoder(txDecoder sdk.TxDecoder) {
|
||||
// default custom logic for transaction decoding
|
||||
func defaultTxDecoder(cdc *wire.Codec) sdk.TxDecoder {
|
||||
return func(txBytes []byte) (sdk.Tx, sdk.Error) {
|
||||
var tx = sdk.StdTx{}
|
||||
var tx = auth.StdTx{}
|
||||
|
||||
if len(txBytes) == 0 {
|
||||
return nil, sdk.ErrTxDecode("txBytes are empty")
|
||||
@ -137,6 +156,12 @@ func (app *BaseApp) SetEndBlocker(endBlocker sdk.EndBlocker) {
|
||||
func (app *BaseApp) SetAnteHandler(ah sdk.AnteHandler) {
|
||||
app.anteHandler = ah
|
||||
}
|
||||
func (app *BaseApp) SetAddrPeerFilter(pf sdk.PeerFilter) {
|
||||
app.addrPeerFilter = pf
|
||||
}
|
||||
func (app *BaseApp) SetPubKeyPeerFilter(pf sdk.PeerFilter) {
|
||||
app.pubkeyPeerFilter = pf
|
||||
}
|
||||
func (app *BaseApp) Router() Router { return app.router }
|
||||
|
||||
// load latest application version
|
||||
@ -277,15 +302,74 @@ func (app *BaseApp) InitChain(req abci.RequestInitChain) (res abci.ResponseInitC
|
||||
return
|
||||
}
|
||||
|
||||
// Filter peers by address / port
|
||||
func (app *BaseApp) FilterPeerByAddrPort(info string) abci.ResponseQuery {
|
||||
if app.addrPeerFilter != nil {
|
||||
return app.addrPeerFilter(info)
|
||||
}
|
||||
return abci.ResponseQuery{}
|
||||
}
|
||||
|
||||
// Filter peers by public key
|
||||
func (app *BaseApp) FilterPeerByPubKey(info string) abci.ResponseQuery {
|
||||
if app.pubkeyPeerFilter != nil {
|
||||
return app.pubkeyPeerFilter(info)
|
||||
}
|
||||
return abci.ResponseQuery{}
|
||||
}
|
||||
|
||||
// Implements ABCI.
|
||||
// Delegates to CommitMultiStore if it implements Queryable
|
||||
func (app *BaseApp) Query(req abci.RequestQuery) (res abci.ResponseQuery) {
|
||||
queryable, ok := app.cms.(sdk.Queryable)
|
||||
if !ok {
|
||||
msg := "application doesn't support queries"
|
||||
return sdk.ErrUnknownRequest(msg).QueryResult()
|
||||
path := strings.Split(req.Path, "/")
|
||||
// first element is empty string
|
||||
if len(path) > 0 && path[0] == "" {
|
||||
path = path[1:]
|
||||
}
|
||||
return queryable.Query(req)
|
||||
// "/app" prefix for special application queries
|
||||
if len(path) >= 2 && path[0] == "app" {
|
||||
var result sdk.Result
|
||||
switch path[1] {
|
||||
case "simulate":
|
||||
txBytes := req.Data
|
||||
tx, err := app.txDecoder(txBytes)
|
||||
if err != nil {
|
||||
result = err.Result()
|
||||
} else {
|
||||
result = app.Simulate(tx)
|
||||
}
|
||||
default:
|
||||
result = sdk.ErrUnknownRequest(fmt.Sprintf("Unknown query: %s", path)).Result()
|
||||
}
|
||||
value := app.cdc.MustMarshalBinary(result)
|
||||
return abci.ResponseQuery{
|
||||
Code: uint32(sdk.ABCICodeOK),
|
||||
Value: value,
|
||||
}
|
||||
}
|
||||
// "/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)
|
||||
}
|
||||
// "/p2p" prefix for p2p queries
|
||||
if len(path) >= 4 && path[0] == "p2p" {
|
||||
if path[1] == "filter" {
|
||||
if path[2] == "addr" {
|
||||
return app.FilterPeerByAddrPort(path[3])
|
||||
}
|
||||
if path[2] == "pubkey" {
|
||||
return app.FilterPeerByPubKey(path[3])
|
||||
}
|
||||
}
|
||||
}
|
||||
msg := "unknown query path"
|
||||
return sdk.ErrUnknownRequest(msg).QueryResult()
|
||||
}
|
||||
|
||||
// Implements ABCI
|
||||
@ -301,6 +385,8 @@ func (app *BaseApp) BeginBlock(req abci.RequestBeginBlock) (res abci.ResponseBeg
|
||||
if app.beginBlocker != nil {
|
||||
res = app.beginBlocker(app.deliverState.ctx, req)
|
||||
}
|
||||
// set the signed validators for addition to context in deliverTx
|
||||
app.signedValidators = req.Validators
|
||||
return
|
||||
}
|
||||
|
||||
@ -312,7 +398,7 @@ func (app *BaseApp) CheckTx(txBytes []byte) (res abci.ResponseCheckTx) {
|
||||
if err != nil {
|
||||
result = err.Result()
|
||||
} else {
|
||||
result = app.runTx(true, txBytes, tx)
|
||||
result = app.runTx(runTxModeCheck, txBytes, tx)
|
||||
}
|
||||
|
||||
return abci.ResponseCheckTx{
|
||||
@ -320,6 +406,7 @@ func (app *BaseApp) CheckTx(txBytes []byte) (res abci.ResponseCheckTx) {
|
||||
Data: result.Data,
|
||||
Log: result.Log,
|
||||
GasWanted: result.GasWanted,
|
||||
GasUsed: result.GasUsed,
|
||||
Fee: cmn.KI64Pair{
|
||||
[]byte(result.FeeDenom),
|
||||
result.FeeAmount,
|
||||
@ -336,7 +423,7 @@ func (app *BaseApp) DeliverTx(txBytes []byte) (res abci.ResponseDeliverTx) {
|
||||
if err != nil {
|
||||
result = err.Result()
|
||||
} else {
|
||||
result = app.runTx(false, txBytes, tx)
|
||||
result = app.runTx(runTxModeDeliver, txBytes, tx)
|
||||
}
|
||||
|
||||
// After-handler hooks.
|
||||
@ -358,22 +445,35 @@ func (app *BaseApp) DeliverTx(txBytes []byte) (res abci.ResponseDeliverTx) {
|
||||
}
|
||||
}
|
||||
|
||||
// nolint- Mostly for testing
|
||||
// nolint - Mostly for testing
|
||||
func (app *BaseApp) Check(tx sdk.Tx) (result sdk.Result) {
|
||||
return app.runTx(true, nil, tx)
|
||||
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(false, nil, tx)
|
||||
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(isCheckTx bool, txBytes []byte, tx sdk.Tx) (result sdk.Result) {
|
||||
func (app *BaseApp) runTx(mode runTxMode, txBytes []byte, tx sdk.Tx) (result sdk.Result) {
|
||||
// Handle any panics.
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
log := fmt.Sprintf("Recovered: %v\nstack:\n%v", r, string(debug.Stack()))
|
||||
result = sdk.ErrInternal(log).Result()
|
||||
switch r.(type) {
|
||||
case sdk.ErrorOutOfGas:
|
||||
log := fmt.Sprintf("Out of gas in location: %v", r.(sdk.ErrorOutOfGas).Descriptor)
|
||||
result = sdk.ErrOutOfGas(log).Result()
|
||||
default:
|
||||
log := fmt.Sprintf("Recovered: %v\nstack:\n%v", r, string(debug.Stack()))
|
||||
result = sdk.ErrInternal(log).Result()
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
@ -392,10 +492,16 @@ func (app *BaseApp) runTx(isCheckTx bool, txBytes []byte, tx sdk.Tx) (result sdk
|
||||
|
||||
// Get the context
|
||||
var ctx sdk.Context
|
||||
if isCheckTx {
|
||||
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)
|
||||
}
|
||||
|
||||
// Run the ante handler.
|
||||
@ -418,7 +524,7 @@ func (app *BaseApp) runTx(isCheckTx bool, txBytes []byte, tx sdk.Tx) (result sdk
|
||||
|
||||
// Get the correct cache
|
||||
var msCache sdk.CacheMultiStore
|
||||
if isCheckTx == true {
|
||||
if mode == runTxModeCheck || mode == runTxModeSimulate {
|
||||
// CacheWrap app.checkState.ms in case it fails.
|
||||
msCache = app.checkState.CacheMultiStore()
|
||||
ctx = ctx.WithMultiStore(msCache)
|
||||
@ -426,13 +532,15 @@ func (app *BaseApp) runTx(isCheckTx bool, txBytes []byte, tx sdk.Tx) (result sdk
|
||||
// CacheWrap app.deliverState.ms in case it fails.
|
||||
msCache = app.deliverState.CacheMultiStore()
|
||||
ctx = ctx.WithMultiStore(msCache)
|
||||
|
||||
}
|
||||
|
||||
result = handler(ctx, msg)
|
||||
|
||||
// If result was successful, write to app.checkState.ms or app.deliverState.ms
|
||||
if result.IsOK() {
|
||||
// Set gas utilized
|
||||
result.GasUsed = ctx.GasMeter().GasConsumed()
|
||||
|
||||
// If not a simulated run and result was successful, write to app.checkState.ms or app.deliverState.ms
|
||||
if mode != runTxModeSimulate && result.IsOK() {
|
||||
msCache.Write()
|
||||
}
|
||||
|
||||
|
||||
@ -1,21 +1,24 @@
|
||||
package baseapp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
abci "github.com/tendermint/abci/types"
|
||||
"github.com/tendermint/go-crypto"
|
||||
crypto "github.com/tendermint/go-crypto"
|
||||
tmtypes "github.com/tendermint/tendermint/types"
|
||||
cmn "github.com/tendermint/tmlibs/common"
|
||||
dbm "github.com/tendermint/tmlibs/db"
|
||||
"github.com/tendermint/tmlibs/log"
|
||||
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
"github.com/cosmos/cosmos-sdk/wire"
|
||||
"github.com/cosmos/cosmos-sdk/x/auth"
|
||||
)
|
||||
|
||||
func defaultLogger() log.Logger {
|
||||
@ -25,7 +28,9 @@ func defaultLogger() log.Logger {
|
||||
func newBaseApp(name string) *BaseApp {
|
||||
logger := defaultLogger()
|
||||
db := dbm.NewMemDB()
|
||||
return NewBaseApp(name, nil, logger, db)
|
||||
codec := wire.NewCodec()
|
||||
wire.RegisterCrypto(codec)
|
||||
return NewBaseApp(name, codec, logger, db)
|
||||
}
|
||||
|
||||
func TestMountStores(t *testing.T) {
|
||||
@ -78,18 +83,36 @@ func TestLoadVersion(t *testing.T) {
|
||||
header := abci.Header{Height: 1}
|
||||
app.BeginBlock(abci.RequestBeginBlock{Header: header})
|
||||
res := app.Commit()
|
||||
commitID := sdk.CommitID{1, res.Data}
|
||||
commitID1 := sdk.CommitID{1, res.Data}
|
||||
header = abci.Header{Height: 2}
|
||||
app.BeginBlock(abci.RequestBeginBlock{Header: header})
|
||||
res = app.Commit()
|
||||
commitID2 := sdk.CommitID{2, res.Data}
|
||||
|
||||
// reload
|
||||
// reload with LoadLatestVersion
|
||||
app = NewBaseApp(name, nil, logger, db)
|
||||
app.MountStoresIAVL(capKey)
|
||||
err = app.LoadLatestVersion(capKey) // needed to make stores non-nil
|
||||
err = app.LoadLatestVersion(capKey)
|
||||
assert.Nil(t, err)
|
||||
testLoadVersionHelper(t, app, int64(2), commitID2)
|
||||
|
||||
lastHeight = app.LastBlockHeight()
|
||||
lastID = app.LastCommitID()
|
||||
assert.Equal(t, int64(1), lastHeight)
|
||||
assert.Equal(t, commitID, lastID)
|
||||
// reload with LoadVersion, see if you can commit the same block and get
|
||||
// the same result
|
||||
app = NewBaseApp(name, nil, logger, db)
|
||||
app.MountStoresIAVL(capKey)
|
||||
err = app.LoadVersion(1, capKey)
|
||||
assert.Nil(t, err)
|
||||
testLoadVersionHelper(t, app, int64(1), commitID1)
|
||||
app.BeginBlock(abci.RequestBeginBlock{Header: header})
|
||||
app.Commit()
|
||||
testLoadVersionHelper(t, app, int64(2), commitID2)
|
||||
}
|
||||
|
||||
func testLoadVersionHelper(t *testing.T, app *BaseApp, expectedHeight int64, expectedID sdk.CommitID) {
|
||||
lastHeight := app.LastBlockHeight()
|
||||
lastID := app.LastCommitID()
|
||||
assert.Equal(t, expectedHeight, lastHeight)
|
||||
assert.Equal(t, expectedID, lastID)
|
||||
}
|
||||
|
||||
// Test that the app hash is static
|
||||
@ -167,7 +190,7 @@ func TestInitChainer(t *testing.T) {
|
||||
}
|
||||
|
||||
query := abci.RequestQuery{
|
||||
Path: "/main/key",
|
||||
Path: "/store/main/key",
|
||||
Data: key,
|
||||
}
|
||||
|
||||
@ -201,11 +224,91 @@ func TestInitChainer(t *testing.T) {
|
||||
assert.Equal(t, value, res.Value)
|
||||
}
|
||||
|
||||
func getStateCheckingHandler(t *testing.T, capKey *sdk.KVStoreKey, txPerHeight int, checkHeader bool) func(ctx sdk.Context, msg sdk.Msg) sdk.Result {
|
||||
counter := 0
|
||||
return func(ctx sdk.Context, msg sdk.Msg) sdk.Result {
|
||||
store := ctx.KVStore(capKey)
|
||||
// Checking state gets updated between checkTx's / DeliverTx's
|
||||
// on the store within a block.
|
||||
if counter > 0 {
|
||||
// check previous value in store
|
||||
counterBytes := []byte{byte(counter - 1)}
|
||||
prevBytes := store.Get(counterBytes)
|
||||
assert.Equal(t, counterBytes, prevBytes)
|
||||
}
|
||||
|
||||
// set the current counter in the store
|
||||
counterBytes := []byte{byte(counter)}
|
||||
store.Set(counterBytes, counterBytes)
|
||||
|
||||
// check that we can see the current header
|
||||
// wrapped in an if, so it can be reused between CheckTx and DeliverTx tests.
|
||||
if checkHeader {
|
||||
thisHeader := ctx.BlockHeader()
|
||||
height := int64((counter / txPerHeight) + 1)
|
||||
assert.Equal(t, height, thisHeader.Height)
|
||||
}
|
||||
|
||||
counter++
|
||||
return sdk.Result{}
|
||||
}
|
||||
}
|
||||
|
||||
// A mock transaction that has a validation which can fail.
|
||||
type testTx struct {
|
||||
positiveNum int64
|
||||
}
|
||||
|
||||
const msgType2 = "testTx"
|
||||
|
||||
func (tx testTx) Type() string { return msgType2 }
|
||||
func (tx testTx) GetMsg() sdk.Msg { return tx }
|
||||
func (tx testTx) GetSignBytes() []byte { return nil }
|
||||
func (tx testTx) GetSigners() []sdk.Address { return nil }
|
||||
func (tx testTx) GetSignatures() []auth.StdSignature { return nil }
|
||||
func (tx testTx) ValidateBasic() sdk.Error {
|
||||
if tx.positiveNum >= 0 {
|
||||
return nil
|
||||
}
|
||||
return sdk.ErrTxDecode("positiveNum should be a non-negative integer.")
|
||||
}
|
||||
|
||||
// Test that successive CheckTx can see each others' effects
|
||||
// on the store within a block, and that the CheckTx state
|
||||
// gets reset to the latest Committed state during Commit
|
||||
func TestCheckTx(t *testing.T) {
|
||||
// TODO
|
||||
// Initialize an app for testing
|
||||
app := newBaseApp(t.Name())
|
||||
// make a cap key and mount the store
|
||||
capKey := sdk.NewKVStoreKey("main")
|
||||
app.MountStoresIAVL(capKey)
|
||||
err := app.LoadLatestVersion(capKey) // needed to make stores non-nil
|
||||
assert.Nil(t, err)
|
||||
app.SetAnteHandler(func(ctx sdk.Context, tx sdk.Tx) (newCtx sdk.Context, res sdk.Result, abort bool) { return })
|
||||
|
||||
txPerHeight := 3
|
||||
app.Router().AddRoute(msgType, getStateCheckingHandler(t, capKey, txPerHeight, false)).
|
||||
AddRoute(msgType2, func(ctx sdk.Context, msg sdk.Msg) (res sdk.Result) { return })
|
||||
tx := testUpdatePowerTx{} // doesn't matter
|
||||
for i := 0; i < txPerHeight; i++ {
|
||||
app.Check(tx)
|
||||
}
|
||||
// If it gets to this point, then successive CheckTx's can see the effects of
|
||||
// other CheckTx's on the block. The following checks that if another block
|
||||
// is committed, the CheckTx State will reset.
|
||||
app.BeginBlock(abci.RequestBeginBlock{})
|
||||
tx2 := testTx{}
|
||||
for i := 0; i < txPerHeight; i++ {
|
||||
app.Deliver(tx2)
|
||||
}
|
||||
app.EndBlock(abci.RequestEndBlock{})
|
||||
app.Commit()
|
||||
|
||||
checkStateStore := app.checkState.ctx.KVStore(capKey)
|
||||
for i := 0; i < txPerHeight; i++ {
|
||||
storedValue := checkStateStore.Get([]byte{byte(i)})
|
||||
assert.Nil(t, storedValue)
|
||||
}
|
||||
}
|
||||
|
||||
// Test that successive DeliverTx can see each others' effects
|
||||
@ -219,30 +322,9 @@ func TestDeliverTx(t *testing.T) {
|
||||
err := app.LoadLatestVersion(capKey) // needed to make stores non-nil
|
||||
assert.Nil(t, err)
|
||||
|
||||
counter := 0
|
||||
txPerHeight := 2
|
||||
app.SetAnteHandler(func(ctx sdk.Context, tx sdk.Tx) (newCtx sdk.Context, res sdk.Result, abort bool) { return })
|
||||
app.Router().AddRoute(msgType, func(ctx sdk.Context, msg sdk.Msg) sdk.Result {
|
||||
store := ctx.KVStore(capKey)
|
||||
if counter > 0 {
|
||||
// check previous value in store
|
||||
counterBytes := []byte{byte(counter - 1)}
|
||||
prevBytes := store.Get(counterBytes)
|
||||
assert.Equal(t, prevBytes, counterBytes)
|
||||
}
|
||||
|
||||
// set the current counter in the store
|
||||
counterBytes := []byte{byte(counter)}
|
||||
store.Set(counterBytes, counterBytes)
|
||||
|
||||
// check we can see the current header
|
||||
thisHeader := ctx.BlockHeader()
|
||||
height := int64((counter / txPerHeight) + 1)
|
||||
assert.Equal(t, height, thisHeader.Height)
|
||||
|
||||
counter++
|
||||
return sdk.Result{}
|
||||
})
|
||||
app.Router().AddRoute(msgType, getStateCheckingHandler(t, capKey, txPerHeight, true))
|
||||
|
||||
tx := testUpdatePowerTx{} // doesn't matter
|
||||
header := abci.Header{AppHash: []byte("apphash")}
|
||||
@ -260,6 +342,118 @@ func TestDeliverTx(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimulateTx(t *testing.T) {
|
||||
app := newBaseApp(t.Name())
|
||||
|
||||
// make a cap key and mount the store
|
||||
capKey := sdk.NewKVStoreKey("main")
|
||||
app.MountStoresIAVL(capKey)
|
||||
err := app.LoadLatestVersion(capKey) // needed to make stores non-nil
|
||||
assert.Nil(t, err)
|
||||
|
||||
counter := 0
|
||||
app.SetAnteHandler(func(ctx sdk.Context, tx sdk.Tx) (newCtx sdk.Context, res sdk.Result, abort bool) { return })
|
||||
app.Router().AddRoute(msgType, func(ctx sdk.Context, msg sdk.Msg) sdk.Result {
|
||||
ctx.GasMeter().ConsumeGas(10, "test")
|
||||
store := ctx.KVStore(capKey)
|
||||
// ensure store is never written
|
||||
require.Nil(t, store.Get([]byte("key")))
|
||||
store.Set([]byte("key"), []byte("value"))
|
||||
// check we can see the current header
|
||||
thisHeader := ctx.BlockHeader()
|
||||
height := int64(counter)
|
||||
assert.Equal(t, height, thisHeader.Height)
|
||||
counter++
|
||||
return sdk.Result{}
|
||||
})
|
||||
|
||||
tx := testUpdatePowerTx{} // doesn't matter
|
||||
header := abci.Header{AppHash: []byte("apphash")}
|
||||
|
||||
app.SetTxDecoder(func(txBytes []byte) (sdk.Tx, sdk.Error) {
|
||||
var ttx testUpdatePowerTx
|
||||
fromJSON(txBytes, &ttx)
|
||||
return ttx, nil
|
||||
})
|
||||
|
||||
nBlocks := 3
|
||||
for blockN := 0; blockN < nBlocks; blockN++ {
|
||||
// block1
|
||||
header.Height = int64(blockN + 1)
|
||||
app.BeginBlock(abci.RequestBeginBlock{Header: header})
|
||||
result := app.Simulate(tx)
|
||||
require.Equal(t, result.Code, sdk.ABCICodeOK)
|
||||
require.Equal(t, int64(80), result.GasUsed)
|
||||
counter--
|
||||
encoded, err := json.Marshal(tx)
|
||||
require.Nil(t, err)
|
||||
query := abci.RequestQuery{
|
||||
Path: "/app/simulate",
|
||||
Data: encoded,
|
||||
}
|
||||
queryResult := app.Query(query)
|
||||
require.Equal(t, queryResult.Code, uint32(sdk.ABCICodeOK))
|
||||
var res sdk.Result
|
||||
app.cdc.MustUnmarshalBinary(queryResult.Value, &res)
|
||||
require.Equal(t, sdk.ABCICodeOK, res.Code)
|
||||
require.Equal(t, int64(160), res.GasUsed)
|
||||
app.EndBlock(abci.RequestEndBlock{})
|
||||
app.Commit()
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunInvalidTransaction(t *testing.T) {
|
||||
// Initialize an app for testing
|
||||
app := newBaseApp(t.Name())
|
||||
// make a cap key and mount the store
|
||||
capKey := sdk.NewKVStoreKey("main")
|
||||
app.MountStoresIAVL(capKey)
|
||||
err := app.LoadLatestVersion(capKey) // needed to make stores non-nil
|
||||
assert.Nil(t, err)
|
||||
app.SetAnteHandler(func(ctx sdk.Context, tx sdk.Tx) (newCtx sdk.Context, res sdk.Result, abort bool) { return })
|
||||
app.Router().AddRoute(msgType2, func(ctx sdk.Context, msg sdk.Msg) (res sdk.Result) { return })
|
||||
app.BeginBlock(abci.RequestBeginBlock{})
|
||||
// Transaction where validate fails
|
||||
invalidTx := testTx{-1}
|
||||
err1 := app.Deliver(invalidTx)
|
||||
assert.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeTxDecode), err1.Code)
|
||||
// Transaction with no known route
|
||||
unknownRouteTx := testUpdatePowerTx{}
|
||||
err2 := app.Deliver(unknownRouteTx)
|
||||
assert.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeUnknownRequest), err2.Code)
|
||||
}
|
||||
|
||||
// Test that transactions exceeding gas limits fail
|
||||
func TestTxGasLimits(t *testing.T) {
|
||||
logger := defaultLogger()
|
||||
db := dbm.NewMemDB()
|
||||
app := NewBaseApp(t.Name(), nil, logger, db)
|
||||
|
||||
// make a cap key and mount the store
|
||||
capKey := sdk.NewKVStoreKey("main")
|
||||
app.MountStoresIAVL(capKey)
|
||||
err := app.LoadLatestVersion(capKey) // needed to make stores non-nil
|
||||
assert.Nil(t, err)
|
||||
|
||||
app.SetAnteHandler(func(ctx sdk.Context, tx sdk.Tx) (newCtx sdk.Context, res sdk.Result, abort bool) {
|
||||
newCtx = ctx.WithGasMeter(sdk.NewGasMeter(0))
|
||||
return
|
||||
})
|
||||
app.Router().AddRoute(msgType, func(ctx sdk.Context, msg sdk.Msg) sdk.Result {
|
||||
ctx.GasMeter().ConsumeGas(10, "counter")
|
||||
return sdk.Result{}
|
||||
})
|
||||
|
||||
tx := testUpdatePowerTx{} // doesn't matter
|
||||
header := abci.Header{AppHash: []byte("apphash")}
|
||||
|
||||
app.BeginBlock(abci.RequestBeginBlock{Header: header})
|
||||
res := app.Deliver(tx)
|
||||
assert.Equal(t, res.Code, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeOutOfGas), "Expected transaction to run out of gas")
|
||||
app.EndBlock(abci.RequestEndBlock{})
|
||||
app.Commit()
|
||||
}
|
||||
|
||||
// Test that we can only query from the latest committed state.
|
||||
func TestQuery(t *testing.T) {
|
||||
app := newBaseApp(t.Name())
|
||||
@ -280,7 +474,7 @@ func TestQuery(t *testing.T) {
|
||||
})
|
||||
|
||||
query := abci.RequestQuery{
|
||||
Path: "/main/key",
|
||||
Path: "/store/main/key",
|
||||
Data: key,
|
||||
}
|
||||
|
||||
@ -307,6 +501,39 @@ func TestQuery(t *testing.T) {
|
||||
assert.Equal(t, value, res.Value)
|
||||
}
|
||||
|
||||
// Test p2p filter queries
|
||||
func TestP2PQuery(t *testing.T) {
|
||||
app := newBaseApp(t.Name())
|
||||
|
||||
// make a cap key and mount the store
|
||||
capKey := sdk.NewKVStoreKey("main")
|
||||
app.MountStoresIAVL(capKey)
|
||||
err := app.LoadLatestVersion(capKey) // needed to make stores non-nil
|
||||
assert.Nil(t, err)
|
||||
|
||||
app.SetAddrPeerFilter(func(addrport string) abci.ResponseQuery {
|
||||
require.Equal(t, "1.1.1.1:8000", addrport)
|
||||
return abci.ResponseQuery{Code: uint32(3)}
|
||||
})
|
||||
|
||||
app.SetPubKeyPeerFilter(func(pubkey string) abci.ResponseQuery {
|
||||
require.Equal(t, "testpubkey", pubkey)
|
||||
return abci.ResponseQuery{Code: uint32(4)}
|
||||
})
|
||||
|
||||
addrQuery := abci.RequestQuery{
|
||||
Path: "/p2p/filter/addr/1.1.1.1:8000",
|
||||
}
|
||||
res := app.Query(addrQuery)
|
||||
require.Equal(t, uint32(3), res.Code)
|
||||
|
||||
pubkeyQuery := abci.RequestQuery{
|
||||
Path: "/p2p/filter/pubkey/testpubkey",
|
||||
}
|
||||
res = app.Query(pubkeyQuery)
|
||||
require.Equal(t, uint32(4), res.Code)
|
||||
}
|
||||
|
||||
//----------------------
|
||||
// TODO: clean this up
|
||||
|
||||
@ -318,12 +545,12 @@ type testUpdatePowerTx struct {
|
||||
|
||||
const msgType = "testUpdatePowerTx"
|
||||
|
||||
func (tx testUpdatePowerTx) Type() string { return msgType }
|
||||
func (tx testUpdatePowerTx) GetMsg() sdk.Msg { return tx }
|
||||
func (tx testUpdatePowerTx) GetSignBytes() []byte { return nil }
|
||||
func (tx testUpdatePowerTx) ValidateBasic() sdk.Error { return nil }
|
||||
func (tx testUpdatePowerTx) GetSigners() []sdk.Address { return nil }
|
||||
func (tx testUpdatePowerTx) GetSignatures() []sdk.StdSignature { return nil }
|
||||
func (tx testUpdatePowerTx) Type() string { return msgType }
|
||||
func (tx testUpdatePowerTx) GetMsg() sdk.Msg { return tx }
|
||||
func (tx testUpdatePowerTx) GetSignBytes() []byte { return nil }
|
||||
func (tx testUpdatePowerTx) ValidateBasic() sdk.Error { return nil }
|
||||
func (tx testUpdatePowerTx) GetSigners() []sdk.Address { return nil }
|
||||
func (tx testUpdatePowerTx) GetSignatures() []auth.StdSignature { return nil }
|
||||
|
||||
func TestValidatorChange(t *testing.T) {
|
||||
|
||||
@ -381,15 +608,20 @@ func TestValidatorChange(t *testing.T) {
|
||||
|
||||
// Assert that validator updates are correct.
|
||||
for _, val := range valSet {
|
||||
|
||||
pubkey, err := tmtypes.PB2TM.PubKey(val.PubKey)
|
||||
// Sanity
|
||||
assert.NotEqual(t, len(val.PubKey), 0)
|
||||
assert.Nil(t, err)
|
||||
|
||||
// Find matching update and splice it out.
|
||||
for j := 0; j < len(valUpdates); {
|
||||
for j := 0; j < len(valUpdates); j++ {
|
||||
valUpdate := valUpdates[j]
|
||||
|
||||
updatePubkey, err := tmtypes.PB2TM.PubKey(valUpdate.PubKey)
|
||||
assert.Nil(t, err)
|
||||
|
||||
// Matched.
|
||||
if bytes.Equal(valUpdate.PubKey, val.PubKey) {
|
||||
if updatePubkey.Equals(pubkey) {
|
||||
assert.Equal(t, valUpdate.Power, val.Power+1)
|
||||
if j < len(valUpdates)-1 {
|
||||
// Splice it out.
|
||||
@ -399,7 +631,6 @@ func TestValidatorChange(t *testing.T) {
|
||||
}
|
||||
|
||||
// Not matched.
|
||||
j++
|
||||
}
|
||||
}
|
||||
assert.Equal(t, len(valUpdates), 0, "Some validator updates were unexpected")
|
||||
@ -413,7 +644,7 @@ func randPower() int64 {
|
||||
|
||||
func makeVal(secret string) abci.Validator {
|
||||
return abci.Validator{
|
||||
PubKey: makePubKey(secret).Bytes(),
|
||||
PubKey: tmtypes.TM2PB.PubKey(makePubKey(secret)),
|
||||
Power: randPower(),
|
||||
}
|
||||
}
|
||||
|
||||
@ -6,6 +6,7 @@ import (
|
||||
"github.com/pkg/errors"
|
||||
|
||||
"github.com/cosmos/cosmos-sdk/wire"
|
||||
"github.com/cosmos/cosmos-sdk/x/auth"
|
||||
rpcclient "github.com/tendermint/tendermint/rpc/client"
|
||||
ctypes "github.com/tendermint/tendermint/rpc/core/types"
|
||||
cmn "github.com/tendermint/tmlibs/common"
|
||||
@ -58,8 +59,7 @@ func (ctx CoreContext) QuerySubspace(cdc *wire.Codec, subspace []byte, storeName
|
||||
|
||||
// Query from Tendermint with the provided storename and path
|
||||
func (ctx CoreContext) query(key cmn.HexBytes, storeName, endPath string) (res []byte, err error) {
|
||||
|
||||
path := fmt.Sprintf("/%s/%s", storeName, endPath)
|
||||
path := fmt.Sprintf("/store/%s/%s", storeName, endPath)
|
||||
node, err := ctx.GetNode()
|
||||
if err != nil {
|
||||
return res, err
|
||||
@ -110,10 +110,11 @@ func (ctx CoreContext) SignAndBuild(name, passphrase string, msg sdk.Msg, cdc *w
|
||||
return nil, errors.Errorf("Chain ID required but not specified")
|
||||
}
|
||||
sequence := ctx.Sequence
|
||||
signMsg := sdk.StdSignMsg{
|
||||
signMsg := auth.StdSignMsg{
|
||||
ChainID: chainID,
|
||||
Sequences: []int64{sequence},
|
||||
Msg: msg,
|
||||
Fee: auth.NewStdFee(ctx.Gas, sdk.Coin{}), // TODO run simulate to estimate gas?
|
||||
}
|
||||
|
||||
keybase, err := keys.GetKeyBase()
|
||||
@ -128,14 +129,14 @@ func (ctx CoreContext) SignAndBuild(name, passphrase string, msg sdk.Msg, cdc *w
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sigs := []sdk.StdSignature{{
|
||||
sigs := []auth.StdSignature{{
|
||||
PubKey: pubkey,
|
||||
Signature: sig,
|
||||
Sequence: sequence,
|
||||
}}
|
||||
|
||||
// marshal bytes
|
||||
tx := sdk.NewStdTx(signMsg.Msg, signMsg.Fee, sigs)
|
||||
tx := auth.NewStdTx(signMsg.Msg, signMsg.Fee, sigs)
|
||||
|
||||
return cdc.MarshalBinary(tx)
|
||||
}
|
||||
|
||||
@ -3,19 +3,20 @@ package context
|
||||
import (
|
||||
rpcclient "github.com/tendermint/tendermint/rpc/client"
|
||||
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
"github.com/cosmos/cosmos-sdk/x/auth"
|
||||
)
|
||||
|
||||
// typical context created in sdk modules for transactions/queries
|
||||
type CoreContext struct {
|
||||
ChainID string
|
||||
Height int64
|
||||
Gas int64
|
||||
TrustNode bool
|
||||
NodeURI string
|
||||
FromAddressName string
|
||||
Sequence int64
|
||||
Client rpcclient.Client
|
||||
Decoder sdk.AccountDecoder
|
||||
Decoder auth.AccountDecoder
|
||||
AccountStore string
|
||||
}
|
||||
|
||||
@ -31,6 +32,12 @@ func (c CoreContext) WithHeight(height int64) CoreContext {
|
||||
return c
|
||||
}
|
||||
|
||||
// WithGas - return a copy of the context with an updated gas
|
||||
func (c CoreContext) WithGas(gas int64) CoreContext {
|
||||
c.Gas = gas
|
||||
return c
|
||||
}
|
||||
|
||||
// WithTrustNode - return a copy of the context with an updated TrustNode flag
|
||||
func (c CoreContext) WithTrustNode(trustNode bool) CoreContext {
|
||||
c.TrustNode = trustNode
|
||||
@ -63,7 +70,7 @@ func (c CoreContext) WithClient(client rpcclient.Client) CoreContext {
|
||||
}
|
||||
|
||||
// WithDecoder - return a copy of the context with an updated Decoder
|
||||
func (c CoreContext) WithDecoder(decoder sdk.AccountDecoder) CoreContext {
|
||||
func (c CoreContext) WithDecoder(decoder auth.AccountDecoder) CoreContext {
|
||||
c.Decoder = decoder
|
||||
return c
|
||||
}
|
||||
|
||||
@ -30,6 +30,7 @@ func NewCoreContextFromViper() CoreContext {
|
||||
return CoreContext{
|
||||
ChainID: chainID,
|
||||
Height: viper.GetInt64(client.FlagHeight),
|
||||
Gas: viper.GetInt64(client.FlagGas),
|
||||
TrustNode: viper.GetBool(client.FlagTrustNode),
|
||||
FromAddressName: viper.GetString(client.FlagName),
|
||||
NodeURI: nodeURI,
|
||||
|
||||
@ -7,6 +7,7 @@ const (
|
||||
FlagChainID = "chain-id"
|
||||
FlagNode = "node"
|
||||
FlagHeight = "height"
|
||||
FlagGas = "gas"
|
||||
FlagTrustNode = "trust-node"
|
||||
FlagName = "name"
|
||||
FlagSequence = "sequence"
|
||||
@ -25,6 +26,7 @@ func GetCommands(cmds ...*cobra.Command) []*cobra.Command {
|
||||
c.Flags().String(FlagChainID, "", "Chain ID of tendermint node")
|
||||
c.Flags().String(FlagNode, "tcp://localhost:46657", "<host>:<port> to tendermint rpc interface for this chain")
|
||||
c.Flags().Int64(FlagHeight, 0, "block height to query, omit to get most recent provable block")
|
||||
c.Flags().Int64(FlagGas, 200000, "gas limit to set per-transaction")
|
||||
}
|
||||
return cmds
|
||||
}
|
||||
@ -37,6 +39,7 @@ func PostCommands(cmds ...*cobra.Command) []*cobra.Command {
|
||||
c.Flags().String(FlagFee, "", "Fee to pay along with transaction")
|
||||
c.Flags().String(FlagChainID, "", "Chain ID of tendermint node")
|
||||
c.Flags().String(FlagNode, "tcp://localhost:46657", "<host>:<port> to tendermint rpc interface for this chain")
|
||||
c.Flags().Int64(FlagGas, 200000, "gas limit to set per-transaction")
|
||||
}
|
||||
return cmds
|
||||
}
|
||||
|
||||
@ -4,6 +4,7 @@ import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
@ -55,7 +56,7 @@ func QueryKeysRequestHandler(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
keysOutput := make([]KeyOutput, len(infos))
|
||||
for i, info := range infos {
|
||||
keysOutput[i] = KeyOutput{Name: info.Name, Address: info.PubKey.Address().String()}
|
||||
keysOutput[i] = KeyOutput{Name: info.Name, Address: sdk.Address(info.PubKey.Address().Bytes())}
|
||||
}
|
||||
output, err := json.MarshalIndent(keysOutput, "", " ")
|
||||
if err != nil {
|
||||
|
||||
@ -4,6 +4,7 @@ import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
"github.com/gorilla/mux"
|
||||
keys "github.com/tendermint/go-crypto/keys"
|
||||
|
||||
@ -50,7 +51,7 @@ func GetKeyRequestHandler(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
keyOutput := KeyOutput{Name: info.Name, Address: info.PubKey.Address().String()}
|
||||
keyOutput := KeyOutput{Name: info.Name, Address: sdk.Address(info.PubKey.Address())}
|
||||
output, err := json.MarshalIndent(keyOutput, "", " ")
|
||||
if err != nil {
|
||||
w.WriteHeader(500)
|
||||
|
||||
@ -1,19 +1,19 @@
|
||||
package keys
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
|
||||
crypto "github.com/tendermint/go-crypto"
|
||||
keys "github.com/tendermint/go-crypto/keys"
|
||||
"github.com/tendermint/tmlibs/cli"
|
||||
dbm "github.com/tendermint/tmlibs/db"
|
||||
|
||||
"github.com/cosmos/cosmos-sdk/client"
|
||||
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
)
|
||||
|
||||
// KeyDBName is the directory under root where we store the keys
|
||||
@ -47,16 +47,16 @@ func SetKeyBase(kb keys.Keybase) {
|
||||
|
||||
// used for outputting keys.Info over REST
|
||||
type KeyOutput struct {
|
||||
Name string `json:"name"`
|
||||
Address string `json:"address"`
|
||||
PubKey string `json:"pub_key"`
|
||||
Name string `json:"name"`
|
||||
Address sdk.Address `json:"address"`
|
||||
PubKey crypto.PubKey `json:"pub_key"`
|
||||
}
|
||||
|
||||
func NewKeyOutput(info keys.Info) KeyOutput {
|
||||
return KeyOutput{
|
||||
Name: info.Name,
|
||||
Address: info.PubKey.Address().String(),
|
||||
PubKey: strings.ToUpper(hex.EncodeToString(info.PubKey.Bytes())),
|
||||
Address: sdk.Address(info.PubKey.Address().Bytes()),
|
||||
PubKey: info.PubKey,
|
||||
}
|
||||
}
|
||||
|
||||
@ -72,10 +72,10 @@ func printInfo(info keys.Info) {
|
||||
ko := NewKeyOutput(info)
|
||||
switch viper.Get(cli.OutputFlag) {
|
||||
case "text":
|
||||
fmt.Printf("NAME:\tADDRESS:\t\t\t\t\tPUBKEY:\n")
|
||||
fmt.Printf("%s\t%s\t%s\n", ko.Name, ko.Address, ko.PubKey)
|
||||
fmt.Printf("NAME:\tADDRESS:\t\t\t\t\t\tPUBKEY:\n")
|
||||
printKeyOutput(ko)
|
||||
case "json":
|
||||
out, err := json.MarshalIndent(ko, "", "\t")
|
||||
out, err := MarshalJSON(ko)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
@ -87,15 +87,27 @@ func printInfos(infos []keys.Info) {
|
||||
kos := NewKeyOutputs(infos)
|
||||
switch viper.Get(cli.OutputFlag) {
|
||||
case "text":
|
||||
fmt.Printf("NAME:\tADDRESS:\t\t\t\t\tPUBKEY:\n")
|
||||
fmt.Printf("NAME:\tADDRESS:\t\t\t\t\t\tPUBKEY:\n")
|
||||
for _, ko := range kos {
|
||||
fmt.Printf("%s\t%s\t%s\n", ko.Name, ko.Address, ko.PubKey)
|
||||
printKeyOutput(ko)
|
||||
}
|
||||
case "json":
|
||||
out, err := json.MarshalIndent(kos, "", "\t")
|
||||
out, err := MarshalJSON(kos)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Println(string(out))
|
||||
}
|
||||
}
|
||||
|
||||
func printKeyOutput(ko KeyOutput) {
|
||||
bechAccount, err := sdk.Bech32ifyAcc(ko.Address)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
bechPubKey, err := sdk.Bech32ifyAccPub(ko.PubKey)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Printf("%s\t%s\t%s\n", ko.Name, bechAccount, bechPubKey)
|
||||
}
|
||||
|
||||
@ -2,6 +2,7 @@ package lcd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
@ -16,35 +17,42 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
abci "github.com/tendermint/abci/types"
|
||||
crypto "github.com/tendermint/go-crypto"
|
||||
cryptoKeys "github.com/tendermint/go-crypto/keys"
|
||||
tmcfg "github.com/tendermint/tendermint/config"
|
||||
nm "github.com/tendermint/tendermint/node"
|
||||
p2p "github.com/tendermint/tendermint/p2p"
|
||||
pvm "github.com/tendermint/tendermint/privval"
|
||||
"github.com/tendermint/tendermint/proxy"
|
||||
ctypes "github.com/tendermint/tendermint/rpc/core/types"
|
||||
tmrpc "github.com/tendermint/tendermint/rpc/lib/server"
|
||||
tmtypes "github.com/tendermint/tendermint/types"
|
||||
pvm "github.com/tendermint/tendermint/privval"
|
||||
"github.com/tendermint/tmlibs/cli"
|
||||
dbm "github.com/tendermint/tmlibs/db"
|
||||
"github.com/tendermint/tmlibs/log"
|
||||
|
||||
client "github.com/cosmos/cosmos-sdk/client"
|
||||
keys "github.com/cosmos/cosmos-sdk/client/keys"
|
||||
bapp "github.com/cosmos/cosmos-sdk/examples/basecoin/app"
|
||||
btypes "github.com/cosmos/cosmos-sdk/examples/basecoin/types"
|
||||
gapp "github.com/cosmos/cosmos-sdk/cmd/gaia/app"
|
||||
"github.com/cosmos/cosmos-sdk/server"
|
||||
tests "github.com/cosmos/cosmos-sdk/tests"
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
"github.com/cosmos/cosmos-sdk/wire"
|
||||
"github.com/cosmos/cosmos-sdk/x/auth"
|
||||
"github.com/cosmos/cosmos-sdk/x/stake"
|
||||
)
|
||||
|
||||
var (
|
||||
coinDenom = "mycoin"
|
||||
coinDenom = "steak"
|
||||
coinAmount = int64(10000000)
|
||||
|
||||
validatorAddr1 = ""
|
||||
validatorAddr2 = ""
|
||||
|
||||
// XXX bad globals
|
||||
name = "test"
|
||||
password = "0123456789"
|
||||
port string // XXX: but it's the int ...
|
||||
port string
|
||||
seed string
|
||||
sendAddr string
|
||||
)
|
||||
@ -91,10 +99,13 @@ func TestKeys(t *testing.T) {
|
||||
err = cdc.UnmarshalJSON([]byte(body), &m)
|
||||
require.Nil(t, err)
|
||||
|
||||
sendAddrAcc, _ := sdk.GetAccAddressHex(sendAddr)
|
||||
addrAcc, _ := sdk.GetAccAddressHex(addr)
|
||||
|
||||
assert.Equal(t, m[0].Name, name, "Did not serve keys name correctly")
|
||||
assert.Equal(t, m[0].Address, sendAddr, "Did not serve keys Address correctly")
|
||||
assert.Equal(t, m[0].Address, sendAddrAcc, "Did not serve keys Address correctly")
|
||||
assert.Equal(t, m[1].Name, newName, "Did not serve keys name correctly")
|
||||
assert.Equal(t, m[1].Address, addr, "Did not serve keys Address correctly")
|
||||
assert.Equal(t, m[1].Address, addrAcc, "Did not serve keys Address correctly")
|
||||
|
||||
// select key
|
||||
keyEndpoint := fmt.Sprintf("/keys/%s", newName)
|
||||
@ -105,7 +116,7 @@ func TestKeys(t *testing.T) {
|
||||
require.Nil(t, err)
|
||||
|
||||
assert.Equal(t, newName, m2.Name, "Did not serve keys name correctly")
|
||||
assert.Equal(t, addr, m2.Address, "Did not serve keys Address correctly")
|
||||
assert.Equal(t, addrAcc, m2.Address, "Did not serve keys Address correctly")
|
||||
|
||||
// update key
|
||||
jsonStr = []byte(fmt.Sprintf(`{"old_password":"%s", "new_password":"12345678901"}`, newPassword))
|
||||
@ -216,6 +227,7 @@ func TestValidators(t *testing.T) {
|
||||
func TestCoinSend(t *testing.T) {
|
||||
|
||||
// query empty
|
||||
//res, body := request(t, port, "GET", "/accounts/8FA6AB57AD6870F6B5B2E57735F38F2F30E73CB6", nil)
|
||||
res, body := request(t, port, "GET", "/accounts/8FA6AB57AD6870F6B5B2E57735F38F2F30E73CB6", nil)
|
||||
require.Equal(t, http.StatusNoContent, res.StatusCode, body)
|
||||
|
||||
@ -305,6 +317,63 @@ func TestTxs(t *testing.T) {
|
||||
// assert.NotEqual(t, "[]", body)
|
||||
}
|
||||
|
||||
func TestValidatorsQuery(t *testing.T) {
|
||||
validators := getValidators(t)
|
||||
assert.Equal(t, len(validators), 2)
|
||||
|
||||
// make sure all the validators were found (order unknown because sorted by owner addr)
|
||||
foundVal1, foundVal2 := false, false
|
||||
res1, res2 := hex.EncodeToString(validators[0].Owner), hex.EncodeToString(validators[1].Owner)
|
||||
if res1 == validatorAddr1 || res2 == validatorAddr1 {
|
||||
foundVal1 = true
|
||||
}
|
||||
if res1 == validatorAddr2 || res2 == validatorAddr2 {
|
||||
foundVal2 = true
|
||||
}
|
||||
assert.True(t, foundVal1, "validatorAddr1 %v, res1 %v, res2 %v", validatorAddr1, res1, res2)
|
||||
assert.True(t, foundVal2, "validatorAddr2 %v, res1 %v, res2 %v", validatorAddr2, res1, res2)
|
||||
}
|
||||
|
||||
func TestBond(t *testing.T) {
|
||||
|
||||
// create bond TX
|
||||
resultTx := doBond(t, port, seed)
|
||||
tests.WaitForHeight(resultTx.Height+1, port)
|
||||
|
||||
// check if tx was commited
|
||||
assert.Equal(t, uint32(0), resultTx.CheckTx.Code)
|
||||
assert.Equal(t, uint32(0), resultTx.DeliverTx.Code)
|
||||
|
||||
// query sender
|
||||
acc := getAccount(t, sendAddr)
|
||||
coins := acc.GetCoins()
|
||||
assert.Equal(t, int64(87), coins.AmountOf(coinDenom))
|
||||
|
||||
// query candidate
|
||||
bond := getDelegation(t, sendAddr, validatorAddr1)
|
||||
assert.Equal(t, "10/1", bond.Shares.String())
|
||||
}
|
||||
|
||||
func TestUnbond(t *testing.T) {
|
||||
|
||||
// create unbond TX
|
||||
resultTx := doUnbond(t, port, seed)
|
||||
tests.WaitForHeight(resultTx.Height+1, port)
|
||||
|
||||
// check if tx was commited
|
||||
assert.Equal(t, uint32(0), resultTx.CheckTx.Code)
|
||||
assert.Equal(t, uint32(0), resultTx.DeliverTx.Code)
|
||||
|
||||
// query sender
|
||||
acc := getAccount(t, sendAddr)
|
||||
coins := acc.GetCoins()
|
||||
assert.Equal(t, int64(98), coins.AmountOf(coinDenom))
|
||||
|
||||
// query candidate
|
||||
bond := getDelegation(t, sendAddr, validatorAddr1)
|
||||
assert.Equal(t, "9/1", bond.Shares.String())
|
||||
}
|
||||
|
||||
//__________________________________________________________
|
||||
// helpers
|
||||
|
||||
@ -316,30 +385,23 @@ func startTMAndLCD() (*nm.Node, net.Listener, error) {
|
||||
return nil, nil, err
|
||||
}
|
||||
viper.Set(cli.HomeFlag, dir)
|
||||
viper.Set(client.FlagGas, 200000)
|
||||
kb, err := keys.GetKeyBase() // dbm.NewMemDB()) // :(
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var info cryptoKeys.Info
|
||||
info, seed, err = kb.Create(name, password, cryptoKeys.AlgoEd25519) // XXX global seed
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
pubKey := info.PubKey
|
||||
sendAddr = pubKey.Address().String() // XXX global
|
||||
|
||||
config := GetConfig()
|
||||
config.Consensus.TimeoutCommit = 1000
|
||||
config.Consensus.SkipTimeoutCommit = false
|
||||
|
||||
logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout))
|
||||
// logger = log.NewFilter(logger, log.AllowError())
|
||||
logger = log.NewFilter(logger, log.AllowError())
|
||||
privValidatorFile := config.PrivValidatorFile()
|
||||
privVal := pvm.LoadOrGenFilePV(privValidatorFile)
|
||||
db := dbm.NewMemDB()
|
||||
app := bapp.NewBasecoinApp(logger, db)
|
||||
cdc = bapp.MakeCodec() // XXX
|
||||
app := gapp.NewGaiaApp(logger, db)
|
||||
cdc = gapp.MakeCodec() // XXX
|
||||
|
||||
genesisFile := config.GenesisFile()
|
||||
genDoc, err := tmtypes.GenesisDocFromFile(genesisFile)
|
||||
@ -347,25 +409,60 @@ func startTMAndLCD() (*nm.Node, net.Listener, error) {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
coins := sdk.Coins{{coinDenom, coinAmount}}
|
||||
appState := map[string]interface{}{
|
||||
"accounts": []*btypes.GenesisAccount{
|
||||
{
|
||||
Name: "tester",
|
||||
Address: pubKey.Address(),
|
||||
Coins: coins,
|
||||
},
|
||||
genDoc.Validators = append(genDoc.Validators,
|
||||
tmtypes.GenesisValidator{
|
||||
PubKey: crypto.GenPrivKeyEd25519().PubKey(),
|
||||
Power: 1,
|
||||
Name: "val",
|
||||
},
|
||||
}
|
||||
stateBytes, err := json.Marshal(appState)
|
||||
)
|
||||
|
||||
pk1 := genDoc.Validators[0].PubKey
|
||||
pk2 := genDoc.Validators[1].PubKey
|
||||
validatorAddr1 = hex.EncodeToString(pk1.Address())
|
||||
validatorAddr2 = hex.EncodeToString(pk2.Address())
|
||||
|
||||
// NOTE it's bad practice to reuse pk address for the owner address but doing in the
|
||||
// test for simplicity
|
||||
var appGenTxs [2]json.RawMessage
|
||||
appGenTxs[0], _, _, err = gapp.GaiaAppGenTxNF(cdc, pk1, pk1.Address(), "test_val1", true)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
genDoc.AppStateJSON = stateBytes
|
||||
appGenTxs[1], _, _, err = gapp.GaiaAppGenTxNF(cdc, pk2, pk2.Address(), "test_val2", true)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
genesisState, err := gapp.GaiaAppGenState(cdc, appGenTxs[:])
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
// add the sendAddr to genesis
|
||||
var info cryptoKeys.Info
|
||||
info, seed, err = kb.Create(name, password, cryptoKeys.AlgoEd25519) // XXX global seed
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
sendAddr = info.PubKey.Address().String() // XXX global
|
||||
accAuth := auth.NewBaseAccountWithAddress(info.PubKey.Address())
|
||||
accAuth.Coins = sdk.Coins{{"steak", 100}}
|
||||
acc := gapp.NewGenesisAccount(&accAuth)
|
||||
genesisState.Accounts = append(genesisState.Accounts, acc)
|
||||
|
||||
appState, err := wire.MarshalJSONIndent(cdc, genesisState)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
genDoc.AppStateJSON = appState
|
||||
|
||||
// LCD listen address
|
||||
port = fmt.Sprintf("%d", 17377) // XXX
|
||||
listenAddr := fmt.Sprintf("tcp://localhost:%s", port) // XXX
|
||||
var listenAddr string
|
||||
listenAddr, port, err = server.FreeTCPAddr()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
// XXX: need to set this so LCD knows the tendermint node address!
|
||||
viper.Set(client.FlagNode, config.RPC.ListenAddress)
|
||||
@ -375,7 +472,7 @@ func startTMAndLCD() (*nm.Node, net.Listener, error) {
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
lcd, err := startLCD(logger, listenAddr)
|
||||
lcd, err := startLCD(logger, listenAddr, cdc)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
@ -414,7 +511,7 @@ func startTM(cfg *tmcfg.Config, logger log.Logger, genDoc *tmtypes.GenesisDoc, p
|
||||
}
|
||||
|
||||
// start the LCD. note this blocks!
|
||||
func startLCD(logger log.Logger, listenAddr string) (net.Listener, error) {
|
||||
func startLCD(logger log.Logger, listenAddr string, cdc *wire.Codec) (net.Listener, error) {
|
||||
handler := createHandler(cdc)
|
||||
return tmrpc.StartHTTPServer(listenAddr, handler, logger)
|
||||
}
|
||||
@ -436,11 +533,11 @@ func request(t *testing.T, port, method, path string, payload []byte) (*http.Res
|
||||
return res, string(output)
|
||||
}
|
||||
|
||||
func getAccount(t *testing.T, sendAddr string) sdk.Account {
|
||||
func getAccount(t *testing.T, sendAddr string) auth.Account {
|
||||
// get the account to get the sequence
|
||||
res, body := request(t, port, "GET", "/accounts/"+sendAddr, nil)
|
||||
require.Equal(t, http.StatusOK, res.StatusCode, body)
|
||||
var acc sdk.Account
|
||||
var acc auth.Account
|
||||
err := cdc.UnmarshalJSON([]byte(body), &acc)
|
||||
require.Nil(t, err)
|
||||
return acc
|
||||
@ -490,3 +587,81 @@ func doIBCTransfer(t *testing.T, port, seed string) (resultTx ctypes.ResultBroad
|
||||
|
||||
return resultTx
|
||||
}
|
||||
|
||||
func getDelegation(t *testing.T, delegatorAddr, candidateAddr string) stake.Delegation {
|
||||
// get the account to get the sequence
|
||||
res, body := request(t, port, "GET", "/stake/"+delegatorAddr+"/bonding_status/"+candidateAddr, nil)
|
||||
require.Equal(t, http.StatusOK, res.StatusCode, body)
|
||||
var bond stake.Delegation
|
||||
err := cdc.UnmarshalJSON([]byte(body), &bond)
|
||||
require.Nil(t, err)
|
||||
return bond
|
||||
}
|
||||
|
||||
func doBond(t *testing.T, port, seed string) (resultTx ctypes.ResultBroadcastTxCommit) {
|
||||
// get the account to get the sequence
|
||||
acc := getAccount(t, sendAddr)
|
||||
sequence := acc.GetSequence()
|
||||
|
||||
// send
|
||||
jsonStr := []byte(fmt.Sprintf(`{
|
||||
"name": "%s",
|
||||
"password": "%s",
|
||||
"sequence": %d,
|
||||
"delegate": [
|
||||
{
|
||||
"delegator_addr": "%x",
|
||||
"validator_addr": "%s",
|
||||
"bond": { "denom": "%s", "amount": 10 }
|
||||
}
|
||||
],
|
||||
"unbond": []
|
||||
}`, name, password, sequence, acc.GetAddress(), validatorAddr1, coinDenom))
|
||||
res, body := request(t, port, "POST", "/stake/delegations", jsonStr)
|
||||
require.Equal(t, http.StatusOK, res.StatusCode, body)
|
||||
|
||||
var results []ctypes.ResultBroadcastTxCommit
|
||||
err := cdc.UnmarshalJSON([]byte(body), &results)
|
||||
require.Nil(t, err)
|
||||
|
||||
return results[0]
|
||||
}
|
||||
|
||||
func doUnbond(t *testing.T, port, seed string) (resultTx ctypes.ResultBroadcastTxCommit) {
|
||||
// get the account to get the sequence
|
||||
acc := getAccount(t, sendAddr)
|
||||
sequence := acc.GetSequence()
|
||||
|
||||
// send
|
||||
jsonStr := []byte(fmt.Sprintf(`{
|
||||
"name": "%s",
|
||||
"password": "%s",
|
||||
"sequence": %d,
|
||||
"bond": [],
|
||||
"unbond": [
|
||||
{
|
||||
"delegator_addr": "%x",
|
||||
"validator_addr": "%s",
|
||||
"shares": "1"
|
||||
}
|
||||
]
|
||||
}`, name, password, sequence, acc.GetAddress(), validatorAddr1))
|
||||
res, body := request(t, port, "POST", "/stake/delegations", jsonStr)
|
||||
require.Equal(t, http.StatusOK, res.StatusCode, body)
|
||||
|
||||
var results []ctypes.ResultBroadcastTxCommit
|
||||
err := cdc.UnmarshalJSON([]byte(body), &results)
|
||||
require.Nil(t, err)
|
||||
|
||||
return results[0]
|
||||
}
|
||||
|
||||
func getValidators(t *testing.T) []stake.Validator {
|
||||
// get the account to get the sequence
|
||||
res, body := request(t, port, "GET", "/stake/validators", nil)
|
||||
require.Equal(t, http.StatusOK, res.StatusCode, body)
|
||||
var validators stake.Validators
|
||||
err := cdc.UnmarshalJSON([]byte(body), &validators)
|
||||
require.Nil(t, err)
|
||||
return validators
|
||||
}
|
||||
|
||||
@ -22,6 +22,7 @@ import (
|
||||
auth "github.com/cosmos/cosmos-sdk/x/auth/client/rest"
|
||||
bank "github.com/cosmos/cosmos-sdk/x/bank/client/rest"
|
||||
ibc "github.com/cosmos/cosmos-sdk/x/ibc/client/rest"
|
||||
stake "github.com/cosmos/cosmos-sdk/x/stake/client/rest"
|
||||
)
|
||||
|
||||
const (
|
||||
@ -55,6 +56,7 @@ func startRESTServerFn(cdc *wire.Codec) func(cmd *cobra.Command, args []string)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Info("REST server started")
|
||||
|
||||
// Wait forever and cleanup
|
||||
cmn.TrapSignal(func() {
|
||||
@ -83,5 +85,6 @@ func createHandler(cdc *wire.Codec) http.Handler {
|
||||
auth.RegisterRoutes(ctx, r, cdc, "acc")
|
||||
bank.RegisterRoutes(ctx, r, cdc, kb)
|
||||
ibc.RegisterRoutes(ctx, r, cdc, kb)
|
||||
stake.RegisterRoutes(ctx, r, cdc, kb)
|
||||
return r
|
||||
}
|
||||
|
||||
@ -16,7 +16,8 @@ const (
|
||||
flagSelect = "select"
|
||||
)
|
||||
|
||||
func blockCommand() *cobra.Command {
|
||||
//BlockCommand returns the verified block data for a given heights
|
||||
func BlockCommand() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "block [height]",
|
||||
Short: "Get verified data for a the block at given height",
|
||||
|
||||
@ -26,8 +26,6 @@ func AddCommands(cmd *cobra.Command) {
|
||||
cmd.AddCommand(
|
||||
initClientCommand(),
|
||||
statusCommand(),
|
||||
blockCommand(),
|
||||
validatorCommand(),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@ -14,10 +14,11 @@ import (
|
||||
|
||||
// TODO these next two functions feel kinda hacky based on their placement
|
||||
|
||||
func validatorCommand() *cobra.Command {
|
||||
//ValidatorCommand returns the validator set for a given height
|
||||
func ValidatorCommand() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "validatorset [height]",
|
||||
Short: "Get the full validator set at given height",
|
||||
Use: "validator-set [height]",
|
||||
Short: "Get the full tendermint validator set at given height",
|
||||
Args: cobra.MaximumNArgs(1),
|
||||
RunE: printValidators,
|
||||
}
|
||||
|
||||
@ -17,6 +17,7 @@ import (
|
||||
"github.com/cosmos/cosmos-sdk/client/context"
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
"github.com/cosmos/cosmos-sdk/wire"
|
||||
"github.com/cosmos/cosmos-sdk/x/auth"
|
||||
)
|
||||
|
||||
// Get the default command for a tx query
|
||||
@ -95,7 +96,7 @@ type txInfo struct {
|
||||
}
|
||||
|
||||
func parseTx(cdc *wire.Codec, txBytes []byte) (sdk.Tx, error) {
|
||||
var tx sdk.StdTx
|
||||
var tx auth.StdTx
|
||||
err := cdc.UnmarshalBinary(txBytes, &tx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@ -15,6 +15,7 @@ import (
|
||||
"github.com/cosmos/cosmos-sdk/x/auth"
|
||||
"github.com/cosmos/cosmos-sdk/x/bank"
|
||||
"github.com/cosmos/cosmos-sdk/x/ibc"
|
||||
"github.com/cosmos/cosmos-sdk/x/slashing"
|
||||
"github.com/cosmos/cosmos-sdk/x/stake"
|
||||
)
|
||||
|
||||
@ -34,16 +35,19 @@ type GaiaApp struct {
|
||||
cdc *wire.Codec
|
||||
|
||||
// keys to access the substores
|
||||
keyMain *sdk.KVStoreKey
|
||||
keyAccount *sdk.KVStoreKey
|
||||
keyIBC *sdk.KVStoreKey
|
||||
keyStake *sdk.KVStoreKey
|
||||
keyMain *sdk.KVStoreKey
|
||||
keyAccount *sdk.KVStoreKey
|
||||
keyIBC *sdk.KVStoreKey
|
||||
keyStake *sdk.KVStoreKey
|
||||
keySlashing *sdk.KVStoreKey
|
||||
|
||||
// Manage getting and setting accounts
|
||||
accountMapper sdk.AccountMapper
|
||||
coinKeeper bank.Keeper
|
||||
ibcMapper ibc.Mapper
|
||||
stakeKeeper stake.Keeper
|
||||
accountMapper auth.AccountMapper
|
||||
feeCollectionKeeper auth.FeeCollectionKeeper
|
||||
coinKeeper bank.Keeper
|
||||
ibcMapper ibc.Mapper
|
||||
stakeKeeper stake.Keeper
|
||||
slashingKeeper slashing.Keeper
|
||||
}
|
||||
|
||||
func NewGaiaApp(logger log.Logger, db dbm.DB) *GaiaApp {
|
||||
@ -51,12 +55,13 @@ func NewGaiaApp(logger log.Logger, db dbm.DB) *GaiaApp {
|
||||
|
||||
// create your application object
|
||||
var app = &GaiaApp{
|
||||
BaseApp: bam.NewBaseApp(appName, cdc, logger, db),
|
||||
cdc: cdc,
|
||||
keyMain: sdk.NewKVStoreKey("main"),
|
||||
keyAccount: sdk.NewKVStoreKey("acc"),
|
||||
keyIBC: sdk.NewKVStoreKey("ibc"),
|
||||
keyStake: sdk.NewKVStoreKey("stake"),
|
||||
BaseApp: bam.NewBaseApp(appName, cdc, logger, db),
|
||||
cdc: cdc,
|
||||
keyMain: sdk.NewKVStoreKey("main"),
|
||||
keyAccount: sdk.NewKVStoreKey("acc"),
|
||||
keyIBC: sdk.NewKVStoreKey("ibc"),
|
||||
keyStake: sdk.NewKVStoreKey("stake"),
|
||||
keySlashing: sdk.NewKVStoreKey("slashing"),
|
||||
}
|
||||
|
||||
// define the accountMapper
|
||||
@ -70,6 +75,7 @@ func NewGaiaApp(logger log.Logger, db dbm.DB) *GaiaApp {
|
||||
app.coinKeeper = bank.NewKeeper(app.accountMapper)
|
||||
app.ibcMapper = ibc.NewMapper(app.cdc, app.keyIBC, app.RegisterCodespace(ibc.DefaultCodespace))
|
||||
app.stakeKeeper = stake.NewKeeper(app.cdc, app.keyStake, app.coinKeeper, app.RegisterCodespace(stake.DefaultCodespace))
|
||||
app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, app.stakeKeeper, app.RegisterCodespace(slashing.DefaultCodespace))
|
||||
|
||||
// register message routes
|
||||
app.Router().
|
||||
@ -79,9 +85,10 @@ func NewGaiaApp(logger log.Logger, db dbm.DB) *GaiaApp {
|
||||
|
||||
// initialize BaseApp
|
||||
app.SetInitChainer(app.initChainer)
|
||||
app.SetEndBlocker(stake.NewEndBlocker(app.stakeKeeper))
|
||||
app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyIBC, app.keyStake)
|
||||
app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, stake.FeeHandler))
|
||||
app.SetBeginBlocker(app.BeginBlocker)
|
||||
app.SetEndBlocker(app.EndBlocker)
|
||||
app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper))
|
||||
app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyIBC, app.keyStake, app.keySlashing)
|
||||
err := app.LoadLatestVersion(app.keyMain)
|
||||
if err != nil {
|
||||
cmn.Exit(err.Error())
|
||||
@ -96,15 +103,35 @@ func MakeCodec() *wire.Codec {
|
||||
ibc.RegisterWire(cdc)
|
||||
bank.RegisterWire(cdc)
|
||||
stake.RegisterWire(cdc)
|
||||
slashing.RegisterWire(cdc)
|
||||
auth.RegisterWire(cdc)
|
||||
sdk.RegisterWire(cdc)
|
||||
wire.RegisterCrypto(cdc)
|
||||
return cdc
|
||||
}
|
||||
|
||||
// application updates every end block
|
||||
func (app *GaiaApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock {
|
||||
tags := slashing.BeginBlocker(ctx, req, app.slashingKeeper)
|
||||
|
||||
return abci.ResponseBeginBlock{
|
||||
Tags: tags.ToKVPairs(),
|
||||
}
|
||||
}
|
||||
|
||||
// application updates every end block
|
||||
func (app *GaiaApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock {
|
||||
validatorUpdates := stake.EndBlocker(ctx, app.stakeKeeper)
|
||||
|
||||
return abci.ResponseEndBlock{
|
||||
ValidatorUpdates: validatorUpdates,
|
||||
}
|
||||
}
|
||||
|
||||
// custom logic for gaia initialization
|
||||
func (app *GaiaApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain {
|
||||
stateJSON := req.AppStateBytes
|
||||
// TODO is this now the whole genesis file?
|
||||
|
||||
var genesisState GenesisState
|
||||
err := app.cdc.UnmarshalJSON(stateJSON, &genesisState)
|
||||
@ -125,13 +152,13 @@ func (app *GaiaApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci
|
||||
return abci.ResponseInitChain{}
|
||||
}
|
||||
|
||||
// export the state of gaia for a genesis f
|
||||
// export the state of gaia for a genesis file
|
||||
func (app *GaiaApp) ExportAppStateJSON() (appState json.RawMessage, err error) {
|
||||
ctx := app.NewContext(true, abci.Header{})
|
||||
|
||||
// iterate to get the accounts
|
||||
accounts := []GenesisAccount{}
|
||||
appendAccount := func(acc sdk.Account) (stop bool) {
|
||||
appendAccount := func(acc auth.Account) (stop bool) {
|
||||
account := NewGenesisAccountI(acc)
|
||||
accounts = append(accounts, account)
|
||||
return false
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"testing"
|
||||
@ -38,9 +37,9 @@ var (
|
||||
coins = sdk.Coins{{"foocoin", 10}}
|
||||
halfCoins = sdk.Coins{{"foocoin", 5}}
|
||||
manyCoins = sdk.Coins{{"foocoin", 1}, {"barcoin", 1}}
|
||||
fee = sdk.StdFee{
|
||||
fee = auth.StdFee{
|
||||
sdk.Coins{{"foocoin", 0}},
|
||||
0,
|
||||
100000,
|
||||
}
|
||||
|
||||
sendMsg1 = bank.MsgSend{
|
||||
@ -105,7 +104,7 @@ func setGenesis(gapp *GaiaApp, accs ...*auth.BaseAccount) error {
|
||||
|
||||
genesisState := GenesisState{
|
||||
Accounts: genaccs,
|
||||
StakeData: stake.GetDefaultGenesisState(),
|
||||
StakeData: stake.DefaultGenesisState(),
|
||||
}
|
||||
|
||||
stateBytes, err := wire.MarshalJSONIndent(gapp.cdc, genesisState)
|
||||
@ -115,7 +114,7 @@ func setGenesis(gapp *GaiaApp, accs ...*auth.BaseAccount) error {
|
||||
|
||||
// Initialize the chain
|
||||
vals := []abci.Validator{}
|
||||
gapp.InitChain(abci.RequestInitChain{vals, stateBytes})
|
||||
gapp.InitChain(abci.RequestInitChain{Validators: vals, AppStateBytes: stateBytes})
|
||||
gapp.Commit()
|
||||
|
||||
return nil
|
||||
@ -139,30 +138,6 @@ func TestMsgs(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func setGenesisAccounts(gapp *GaiaApp, accs ...*auth.BaseAccount) error {
|
||||
genaccs := make([]GenesisAccount, len(accs))
|
||||
for i, acc := range accs {
|
||||
genaccs[i] = NewGenesisAccount(acc)
|
||||
}
|
||||
|
||||
genesisState := GenesisState{
|
||||
Accounts: genaccs,
|
||||
StakeData: stake.GetDefaultGenesisState(),
|
||||
}
|
||||
|
||||
stateBytes, err := json.MarshalIndent(genesisState, "", "\t")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Initialize the chain
|
||||
vals := []abci.Validator{}
|
||||
gapp.InitChain(abci.RequestInitChain{vals, stateBytes})
|
||||
gapp.Commit()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestGenesis(t *testing.T) {
|
||||
logger, dbs := loggerAndDB()
|
||||
gapp := NewGaiaApp(logger, dbs)
|
||||
@ -178,7 +153,7 @@ func TestGenesis(t *testing.T) {
|
||||
}
|
||||
|
||||
err = setGenesis(gapp, baseAcc)
|
||||
assert.Nil(t, err)
|
||||
require.Nil(t, err)
|
||||
|
||||
// A checkTx context
|
||||
ctx := gapp.BaseApp.NewContext(true, abci.Header{})
|
||||
@ -394,32 +369,38 @@ func TestStakeMsgs(t *testing.T) {
|
||||
require.Equal(t, acc1, res1)
|
||||
require.Equal(t, acc2, res2)
|
||||
|
||||
// Declare Candidacy
|
||||
// Create Validator
|
||||
|
||||
description := stake.NewDescription("foo_moniker", "", "", "")
|
||||
declareCandidacyMsg := stake.NewMsgDeclareCandidacy(
|
||||
createValidatorMsg := stake.NewMsgCreateValidator(
|
||||
addr1, priv1.PubKey(), bondCoin, description,
|
||||
)
|
||||
SignCheckDeliver(t, gapp, declareCandidacyMsg, []int64{0}, true, priv1)
|
||||
SignCheckDeliver(t, gapp, createValidatorMsg, []int64{0}, true, priv1)
|
||||
|
||||
ctxDeliver := gapp.BaseApp.NewContext(false, abci.Header{})
|
||||
res1 = gapp.accountMapper.GetAccount(ctxDeliver, addr1)
|
||||
require.Equal(t, genCoins.Minus(sdk.Coins{bondCoin}), res1.GetCoins())
|
||||
candidate, found := gapp.stakeKeeper.GetCandidate(ctxDeliver, addr1)
|
||||
validator, found := gapp.stakeKeeper.GetValidator(ctxDeliver, addr1)
|
||||
require.True(t, found)
|
||||
require.Equal(t, candidate.Address, addr1)
|
||||
require.Equal(t, addr1, validator.Owner)
|
||||
require.Equal(t, sdk.Bonded, validator.Status())
|
||||
require.True(sdk.RatEq(t, sdk.NewRat(10), validator.PoolShares.Bonded()))
|
||||
|
||||
// Edit Candidacy
|
||||
// check the bond that should have been created as well
|
||||
bond, found := gapp.stakeKeeper.GetDelegation(ctxDeliver, addr1, addr1)
|
||||
require.True(sdk.RatEq(t, sdk.NewRat(10), bond.Shares))
|
||||
|
||||
// Edit Validator
|
||||
|
||||
description = stake.NewDescription("bar_moniker", "", "", "")
|
||||
editCandidacyMsg := stake.NewMsgEditCandidacy(
|
||||
editValidatorMsg := stake.NewMsgEditValidator(
|
||||
addr1, description,
|
||||
)
|
||||
SignDeliver(t, gapp, editCandidacyMsg, []int64{1}, true, priv1)
|
||||
SignDeliver(t, gapp, editValidatorMsg, []int64{1}, true, priv1)
|
||||
|
||||
candidate, found = gapp.stakeKeeper.GetCandidate(ctxDeliver, addr1)
|
||||
validator, found = gapp.stakeKeeper.GetValidator(ctxDeliver, addr1)
|
||||
require.True(t, found)
|
||||
require.Equal(t, candidate.Description, description)
|
||||
require.Equal(t, description, validator.Description)
|
||||
|
||||
// Delegate
|
||||
|
||||
@ -428,12 +409,13 @@ func TestStakeMsgs(t *testing.T) {
|
||||
)
|
||||
SignDeliver(t, gapp, delegateMsg, []int64{0}, true, priv2)
|
||||
|
||||
ctxDeliver = gapp.BaseApp.NewContext(false, abci.Header{})
|
||||
res2 = gapp.accountMapper.GetAccount(ctxDeliver, addr2)
|
||||
require.Equal(t, genCoins.Minus(sdk.Coins{bondCoin}), res2.GetCoins())
|
||||
bond, found := gapp.stakeKeeper.GetDelegatorBond(ctxDeliver, addr2, addr1)
|
||||
bond, found = gapp.stakeKeeper.GetDelegation(ctxDeliver, addr2, addr1)
|
||||
require.True(t, found)
|
||||
require.Equal(t, bond.DelegatorAddr, addr2)
|
||||
require.Equal(t, addr2, bond.DelegatorAddr)
|
||||
require.Equal(t, addr1, bond.ValidatorAddr)
|
||||
require.True(sdk.RatEq(t, sdk.NewRat(10), bond.Shares))
|
||||
|
||||
// Unbond
|
||||
|
||||
@ -442,10 +424,9 @@ func TestStakeMsgs(t *testing.T) {
|
||||
)
|
||||
SignDeliver(t, gapp, unbondMsg, []int64{1}, true, priv2)
|
||||
|
||||
ctxDeliver = gapp.BaseApp.NewContext(false, abci.Header{})
|
||||
res2 = gapp.accountMapper.GetAccount(ctxDeliver, addr2)
|
||||
require.Equal(t, genCoins, res2.GetCoins())
|
||||
_, found = gapp.stakeKeeper.GetDelegatorBond(ctxDeliver, addr2, addr1)
|
||||
_, found = gapp.stakeKeeper.GetDelegation(ctxDeliver, addr2, addr1)
|
||||
require.False(t, found)
|
||||
}
|
||||
|
||||
@ -457,17 +438,17 @@ func CheckBalance(t *testing.T, gapp *GaiaApp, addr sdk.Address, balExpected str
|
||||
assert.Equal(t, balExpected, fmt.Sprintf("%v", res2.GetCoins()))
|
||||
}
|
||||
|
||||
func genTx(msg sdk.Msg, seq []int64, priv ...crypto.PrivKeyEd25519) sdk.StdTx {
|
||||
sigs := make([]sdk.StdSignature, len(priv))
|
||||
func genTx(msg sdk.Msg, seq []int64, priv ...crypto.PrivKeyEd25519) auth.StdTx {
|
||||
sigs := make([]auth.StdSignature, len(priv))
|
||||
for i, p := range priv {
|
||||
sigs[i] = sdk.StdSignature{
|
||||
sigs[i] = auth.StdSignature{
|
||||
PubKey: p.PubKey(),
|
||||
Signature: p.Sign(sdk.StdSignBytes(chainID, seq, fee, msg)),
|
||||
Signature: p.Sign(auth.StdSignBytes(chainID, seq, fee, msg)),
|
||||
Sequence: seq[i],
|
||||
}
|
||||
}
|
||||
|
||||
return sdk.NewStdTx(msg, fee, sigs)
|
||||
return auth.NewStdTx(msg, fee, sigs)
|
||||
|
||||
}
|
||||
|
||||
|
||||
@ -35,7 +35,7 @@ func NewGenesisAccount(acc *auth.BaseAccount) GenesisAccount {
|
||||
}
|
||||
}
|
||||
|
||||
func NewGenesisAccountI(acc sdk.Account) GenesisAccount {
|
||||
func NewGenesisAccountI(acc auth.Account) GenesisAccount {
|
||||
return GenesisAccount{
|
||||
Address: acc.GetAddress(),
|
||||
Coins: acc.GetCoins(),
|
||||
@ -65,7 +65,7 @@ func GaiaAppInit() server.AppInit {
|
||||
fsAppGenState := pflag.NewFlagSet("", pflag.ContinueOnError)
|
||||
|
||||
fsAppGenTx := pflag.NewFlagSet("", pflag.ContinueOnError)
|
||||
fsAppGenTx.String(flagName, "", "validator moniker, if left blank, do not add validator")
|
||||
fsAppGenTx.String(flagName, "", "validator moniker, required")
|
||||
fsAppGenTx.String(flagClientHome, DefaultCLIHome,
|
||||
"home directory for the client, used for key generation")
|
||||
fsAppGenTx.Bool(flagOWK, false, "overwrite the accounts created")
|
||||
@ -74,7 +74,7 @@ func GaiaAppInit() server.AppInit {
|
||||
FlagsAppGenState: fsAppGenState,
|
||||
FlagsAppGenTx: fsAppGenTx,
|
||||
AppGenTx: GaiaAppGenTx,
|
||||
AppGenState: GaiaAppGenState,
|
||||
AppGenState: GaiaAppGenStateJSON,
|
||||
}
|
||||
}
|
||||
|
||||
@ -85,19 +85,35 @@ type GaiaGenTx struct {
|
||||
PubKey crypto.PubKey `json:"pub_key"`
|
||||
}
|
||||
|
||||
// Generate a gaia genesis transaction
|
||||
// Generate a gaia genesis transaction with flags
|
||||
func GaiaAppGenTx(cdc *wire.Codec, pk crypto.PubKey) (
|
||||
appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) {
|
||||
|
||||
var addr sdk.Address
|
||||
var secret string
|
||||
clientRoot := viper.GetString(flagClientHome)
|
||||
overwrite := viper.GetBool(flagOWK)
|
||||
name := viper.GetString(flagName)
|
||||
if name == "" {
|
||||
return nil, nil, tmtypes.GenesisValidator{}, errors.New("Must specify --name (validator moniker)")
|
||||
}
|
||||
|
||||
var addr sdk.Address
|
||||
var secret string
|
||||
addr, secret, err = server.GenerateSaveCoinKey(clientRoot, name, "1234567890", overwrite)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
mm := map[string]string{"secret": secret}
|
||||
var bz []byte
|
||||
bz, err = cdc.MarshalJSON(mm)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
cliPrint = json.RawMessage(bz)
|
||||
return GaiaAppGenTxNF(cdc, pk, addr, name, overwrite)
|
||||
}
|
||||
|
||||
// Generate a gaia genesis transaction without flags
|
||||
func GaiaAppGenTxNF(cdc *wire.Codec, pk crypto.PubKey, addr sdk.Address, name string, overwrite bool) (
|
||||
appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) {
|
||||
|
||||
var bz []byte
|
||||
gaiaGenTx := GaiaGenTx{
|
||||
@ -111,13 +127,6 @@ func GaiaAppGenTx(cdc *wire.Codec, pk crypto.PubKey) (
|
||||
}
|
||||
appGenTx = json.RawMessage(bz)
|
||||
|
||||
mm := map[string]string{"secret": secret}
|
||||
bz, err = cdc.MarshalJSON(mm)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
cliPrint = json.RawMessage(bz)
|
||||
|
||||
validator = tmtypes.GenesisValidator{
|
||||
PubKey: pk,
|
||||
Power: freeFermionVal,
|
||||
@ -127,7 +136,7 @@ func GaiaAppGenTx(cdc *wire.Codec, pk crypto.PubKey) (
|
||||
|
||||
// Create the core parameters for genesis initialization for gaia
|
||||
// note that the pubkey input is this machines pubkey
|
||||
func GaiaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (appState json.RawMessage, err error) {
|
||||
func GaiaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState GenesisState, err error) {
|
||||
|
||||
if len(appGenTxs) == 0 {
|
||||
err = errors.New("must provide at least genesis transaction")
|
||||
@ -135,7 +144,7 @@ func GaiaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (appState jso
|
||||
}
|
||||
|
||||
// start with the default staking genesis state
|
||||
stakeData := stake.GetDefaultGenesisState()
|
||||
stakeData := stake.DefaultGenesisState()
|
||||
|
||||
// get genesis flag account information
|
||||
genaccs := make([]GenesisAccount, len(appGenTxs))
|
||||
@ -155,27 +164,37 @@ func GaiaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (appState jso
|
||||
}
|
||||
acc := NewGenesisAccount(&accAuth)
|
||||
genaccs[i] = acc
|
||||
stakeData.Pool.TotalSupply += freeFermionsAcc // increase the supply
|
||||
stakeData.Pool.LooseUnbondedTokens += freeFermionsAcc // increase the supply
|
||||
|
||||
// add the validator
|
||||
if len(genTx.Name) > 0 {
|
||||
desc := stake.NewDescription(genTx.Name, "", "", "")
|
||||
candidate := stake.NewCandidate(genTx.Address, genTx.PubKey, desc)
|
||||
candidate.Assets = sdk.NewRat(freeFermionVal)
|
||||
stakeData.Candidates = append(stakeData.Candidates, candidate)
|
||||
validator := stake.NewValidator(genTx.Address, genTx.PubKey, desc)
|
||||
validator.PoolShares = stake.NewBondedShares(sdk.NewRat(freeFermionVal))
|
||||
stakeData.Validators = append(stakeData.Validators, validator)
|
||||
|
||||
// pool logic
|
||||
stakeData.Pool.TotalSupply += freeFermionVal
|
||||
stakeData.Pool.BondedPool += freeFermionVal
|
||||
stakeData.Pool.BondedShares = sdk.NewRat(stakeData.Pool.BondedPool)
|
||||
stakeData.Pool.BondedTokens += freeFermionVal
|
||||
stakeData.Pool.BondedShares = sdk.NewRat(stakeData.Pool.BondedTokens)
|
||||
}
|
||||
}
|
||||
|
||||
// create the final app state
|
||||
genesisState := GenesisState{
|
||||
genesisState = GenesisState{
|
||||
Accounts: genaccs,
|
||||
StakeData: stakeData,
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// GaiaAppGenState but with JSON
|
||||
func GaiaAppGenStateJSON(cdc *wire.Codec, appGenTxs []json.RawMessage) (appState json.RawMessage, err error) {
|
||||
|
||||
// create the final app state
|
||||
genesisState, err := GaiaAppGenState(cdc, appGenTxs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
appState, err = wire.MarshalJSONIndent(cdc, genesisState)
|
||||
return
|
||||
}
|
||||
|
||||
@ -13,9 +13,11 @@ import (
|
||||
"github.com/cosmos/cosmos-sdk/cmd/gaia/app"
|
||||
"github.com/cosmos/cosmos-sdk/server"
|
||||
"github.com/cosmos/cosmos-sdk/tests"
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
"github.com/cosmos/cosmos-sdk/wire"
|
||||
"github.com/cosmos/cosmos-sdk/x/auth"
|
||||
"github.com/cosmos/cosmos-sdk/x/stake"
|
||||
crypto "github.com/tendermint/go-crypto"
|
||||
)
|
||||
|
||||
func TestGaiaCLISend(t *testing.T) {
|
||||
@ -28,38 +30,44 @@ func TestGaiaCLISend(t *testing.T) {
|
||||
executeWrite(t, "gaiacli keys add bar", pass)
|
||||
|
||||
// get a free port, also setup some common flags
|
||||
servAddr := server.FreeTCPAddr(t)
|
||||
servAddr, port, err := server.FreeTCPAddr()
|
||||
require.NoError(t, err)
|
||||
flags := fmt.Sprintf("--node=%v --chain-id=%v", servAddr, chainID)
|
||||
|
||||
// start gaiad server
|
||||
cmd, _, _ := tests.GoExecuteT(t, fmt.Sprintf("gaiad start --rpc.laddr=%v", servAddr))
|
||||
defer cmd.Process.Kill()
|
||||
proc := tests.GoExecuteT(t, fmt.Sprintf("gaiad start --rpc.laddr=%v", servAddr))
|
||||
defer proc.Stop(false)
|
||||
tests.WaitForStart(port)
|
||||
|
||||
fooAddr, _ := executeGetAddrPK(t, "gaiacli keys show foo --output=json")
|
||||
fooCech, err := sdk.Bech32ifyAcc(fooAddr)
|
||||
require.NoError(t, err)
|
||||
barAddr, _ := executeGetAddrPK(t, "gaiacli keys show bar --output=json")
|
||||
barCech, err := sdk.Bech32ifyAcc(barAddr)
|
||||
require.NoError(t, err)
|
||||
|
||||
fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooAddr, flags))
|
||||
fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooCech, flags))
|
||||
assert.Equal(t, int64(50), fooAcc.GetCoins().AmountOf("steak"))
|
||||
|
||||
executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%v --name=foo", flags, barAddr), pass)
|
||||
time.Sleep(time.Second * 3) // waiting for some blocks to pass
|
||||
executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%v --name=foo", flags, barCech), pass)
|
||||
time.Sleep(time.Second * 2) // waiting for some blocks to pass
|
||||
|
||||
barAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", barAddr, flags))
|
||||
barAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", barCech, flags))
|
||||
assert.Equal(t, int64(10), barAcc.GetCoins().AmountOf("steak"))
|
||||
fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooAddr, flags))
|
||||
fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooCech, flags))
|
||||
assert.Equal(t, int64(40), fooAcc.GetCoins().AmountOf("steak"))
|
||||
|
||||
// test autosequencing
|
||||
executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%v --name=foo", flags, barAddr), pass)
|
||||
time.Sleep(time.Second * 3) // waiting for some blocks to pass
|
||||
executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%v --name=foo", flags, barCech), pass)
|
||||
time.Sleep(time.Second * 2) // waiting for some blocks to pass
|
||||
|
||||
barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", barAddr, flags))
|
||||
barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", barCech, flags))
|
||||
assert.Equal(t, int64(20), barAcc.GetCoins().AmountOf("steak"))
|
||||
fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooAddr, flags))
|
||||
fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooCech, flags))
|
||||
assert.Equal(t, int64(30), fooAcc.GetCoins().AmountOf("steak"))
|
||||
}
|
||||
|
||||
func TestGaiaCLIDeclareCandidacy(t *testing.T) {
|
||||
func TestGaiaCLICreateValidator(t *testing.T) {
|
||||
|
||||
tests.ExecuteT(t, "gaiad unsafe_reset_all")
|
||||
pass := "1234567890"
|
||||
@ -69,81 +77,79 @@ func TestGaiaCLIDeclareCandidacy(t *testing.T) {
|
||||
executeWrite(t, "gaiacli keys add bar", pass)
|
||||
|
||||
// get a free port, also setup some common flags
|
||||
servAddr := server.FreeTCPAddr(t)
|
||||
servAddr, port, err := server.FreeTCPAddr()
|
||||
require.NoError(t, err)
|
||||
flags := fmt.Sprintf("--node=%v --chain-id=%v", servAddr, chainID)
|
||||
|
||||
// start gaiad server
|
||||
cmd, _, _ := tests.GoExecuteT(t, fmt.Sprintf("gaiad start --rpc.laddr=%v", servAddr))
|
||||
defer cmd.Process.Kill()
|
||||
proc := tests.GoExecuteT(t, fmt.Sprintf("gaiad start --rpc.laddr=%v", servAddr))
|
||||
defer proc.Stop(false)
|
||||
tests.WaitForStart(port)
|
||||
|
||||
fooAddr, _ := executeGetAddrPK(t, "gaiacli keys show foo --output=json")
|
||||
fooCech, err := sdk.Bech32ifyAcc(fooAddr)
|
||||
require.NoError(t, err)
|
||||
barAddr, barPubKey := executeGetAddrPK(t, "gaiacli keys show bar --output=json")
|
||||
barCech, err := sdk.Bech32ifyAcc(barAddr)
|
||||
require.NoError(t, err)
|
||||
barCeshPubKey, err := sdk.Bech32ifyValPub(barPubKey)
|
||||
require.NoError(t, err)
|
||||
|
||||
executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%v --name=foo", flags, barAddr), pass)
|
||||
executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%v --name=foo", flags, barCech), pass)
|
||||
time.Sleep(time.Second * 3) // waiting for some blocks to pass
|
||||
|
||||
fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooAddr, flags))
|
||||
assert.Equal(t, int64(40), fooAcc.GetCoins().AmountOf("steak"))
|
||||
barAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", barAddr, flags))
|
||||
barAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", barCech, flags))
|
||||
assert.Equal(t, int64(10), barAcc.GetCoins().AmountOf("steak"))
|
||||
fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooCech, flags))
|
||||
assert.Equal(t, int64(40), fooAcc.GetCoins().AmountOf("steak"))
|
||||
|
||||
// declare candidacy
|
||||
declStr := fmt.Sprintf("gaiacli declare-candidacy %v", flags)
|
||||
declStr += fmt.Sprintf(" --name=%v", "bar")
|
||||
declStr += fmt.Sprintf(" --address-candidate=%v", barAddr)
|
||||
declStr += fmt.Sprintf(" --pubkey=%v", barPubKey)
|
||||
declStr += fmt.Sprintf(" --amount=%v", "3steak")
|
||||
declStr += fmt.Sprintf(" --moniker=%v", "bar-vally")
|
||||
fmt.Printf("debug declStr: %v\n", declStr)
|
||||
executeWrite(t, declStr, pass)
|
||||
time.Sleep(time.Second) // waiting for some blocks to pass
|
||||
barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", barAddr, flags))
|
||||
assert.Equal(t, int64(7), barAcc.GetCoins().AmountOf("steak"))
|
||||
candidate := executeGetCandidate(t, fmt.Sprintf("gaiacli candidate %v --address-candidate=%v", flags, barAddr))
|
||||
assert.Equal(t, candidate.Address.String(), barAddr)
|
||||
assert.Equal(t, int64(3), candidate.Assets.Evaluate())
|
||||
// create validator
|
||||
cvStr := fmt.Sprintf("gaiacli stake create-validator %v", flags)
|
||||
cvStr += fmt.Sprintf(" --name=%v", "bar")
|
||||
cvStr += fmt.Sprintf(" --address-validator=%v", barCech)
|
||||
cvStr += fmt.Sprintf(" --pubkey=%v", barCeshPubKey)
|
||||
cvStr += fmt.Sprintf(" --amount=%v", "2steak")
|
||||
cvStr += fmt.Sprintf(" --moniker=%v", "bar-vally")
|
||||
|
||||
executeWrite(t, cvStr, pass)
|
||||
time.Sleep(time.Second * 3) // waiting for some blocks to pass
|
||||
|
||||
barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", barCech, flags))
|
||||
require.Equal(t, int64(8), barAcc.GetCoins().AmountOf("steak"), "%v", barAcc)
|
||||
|
||||
validator := executeGetValidator(t, fmt.Sprintf("gaiacli stake validator %v --output=json %v", barCech, flags))
|
||||
assert.Equal(t, validator.Owner, barAddr)
|
||||
assert.Equal(t, "2/1", validator.PoolShares.Amount.String())
|
||||
|
||||
// TODO timeout issues if not connected to the internet
|
||||
// unbond a single share
|
||||
//unbondStr := fmt.Sprintf("gaiacli unbond %v", flags)
|
||||
//unbondStr += fmt.Sprintf(" --name=%v", "bar")
|
||||
//unbondStr += fmt.Sprintf(" --address-candidate=%v", barAddr)
|
||||
//unbondStr += fmt.Sprintf(" --address-delegator=%v", barAddr)
|
||||
//unbondStr += fmt.Sprintf(" --shares=%v", "1")
|
||||
//unbondStr += fmt.Sprintf(" --sequence=%v", "1")
|
||||
//fmt.Printf("debug unbondStr: %v\n", unbondStr)
|
||||
//executeWrite(t, unbondStr, pass)
|
||||
//time.Sleep(time.Second * 3) // waiting for some blocks to pass
|
||||
//barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", barAddr, flags))
|
||||
//assert.Equal(t, int64(99998), barAcc.GetCoins().AmountOf("steak"))
|
||||
//candidate = executeGetCandidate(t, fmt.Sprintf("gaiacli candidate %v --address-candidate=%v", flags, barAddr))
|
||||
//assert.Equal(t, int64(2), candidate.Assets.Evaluate())
|
||||
unbondStr := fmt.Sprintf("gaiacli stake unbond %v", flags)
|
||||
unbondStr += fmt.Sprintf(" --name=%v", "bar")
|
||||
unbondStr += fmt.Sprintf(" --address-validator=%v", barCech)
|
||||
unbondStr += fmt.Sprintf(" --address-delegator=%v", barCech)
|
||||
unbondStr += fmt.Sprintf(" --shares=%v", "1")
|
||||
unbondStr += fmt.Sprintf(" --sequence=%v", "1")
|
||||
t.Log(fmt.Sprintf("debug unbondStr: %v\n", unbondStr))
|
||||
|
||||
executeWrite(t, unbondStr, pass)
|
||||
time.Sleep(time.Second * 3) // waiting for some blocks to pass
|
||||
|
||||
barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", barCech, flags))
|
||||
require.Equal(t, int64(9), barAcc.GetCoins().AmountOf("steak"), "%v", barAcc)
|
||||
validator = executeGetValidator(t, fmt.Sprintf("gaiacli stake validator %v --output=json %v", barCech, flags))
|
||||
assert.Equal(t, "1/1", validator.PoolShares.Amount.String())
|
||||
}
|
||||
|
||||
//___________________________________________________________________________________
|
||||
// executors
|
||||
|
||||
func executeWrite(t *testing.T, cmdStr string, writes ...string) {
|
||||
cmd, wc, _ := tests.GoExecuteT(t, cmdStr)
|
||||
proc := tests.GoExecuteT(t, cmdStr)
|
||||
|
||||
for _, write := range writes {
|
||||
_, err := wc.Write([]byte(write + "\n"))
|
||||
_, err := proc.StdinPipe.Write([]byte(write + "\n"))
|
||||
require.NoError(t, err)
|
||||
}
|
||||
fmt.Printf("debug waiting cmdStr: %v\n", cmdStr)
|
||||
cmd.Wait()
|
||||
}
|
||||
|
||||
func executeWritePrint(t *testing.T, cmdStr string, writes ...string) {
|
||||
cmd, wc, rc := tests.GoExecuteT(t, cmdStr)
|
||||
|
||||
for _, write := range writes {
|
||||
_, err := wc.Write([]byte(write + "\n"))
|
||||
require.NoError(t, err)
|
||||
}
|
||||
fmt.Printf("debug waiting cmdStr: %v\n", cmdStr)
|
||||
cmd.Wait()
|
||||
|
||||
bz := make([]byte, 100000)
|
||||
rc.Read(bz)
|
||||
fmt.Printf("debug read: %v\n", string(bz))
|
||||
proc.Wait()
|
||||
}
|
||||
|
||||
func executeInit(t *testing.T, cmdStr string) (chainID string) {
|
||||
@ -159,10 +165,11 @@ func executeInit(t *testing.T, cmdStr string) (chainID string) {
|
||||
return
|
||||
}
|
||||
|
||||
func executeGetAddrPK(t *testing.T, cmdStr string) (addr, pubKey string) {
|
||||
func executeGetAddrPK(t *testing.T, cmdStr string) (sdk.Address, crypto.PubKey) {
|
||||
out := tests.ExecuteT(t, cmdStr)
|
||||
var ko keys.KeyOutput
|
||||
keys.UnmarshalJSON([]byte(out), &ko)
|
||||
|
||||
return ko.Address, ko.PubKey
|
||||
}
|
||||
|
||||
@ -180,11 +187,11 @@ func executeGetAccount(t *testing.T, cmdStr string) auth.BaseAccount {
|
||||
return acc
|
||||
}
|
||||
|
||||
func executeGetCandidate(t *testing.T, cmdStr string) stake.Candidate {
|
||||
func executeGetValidator(t *testing.T, cmdStr string) stake.Validator {
|
||||
out := tests.ExecuteT(t, cmdStr)
|
||||
var candidate stake.Candidate
|
||||
var validator stake.Validator
|
||||
cdc := app.MakeCodec()
|
||||
err := cdc.UnmarshalJSON([]byte(out), &candidate)
|
||||
require.NoError(t, err, "out %v, err %v", out, err)
|
||||
return candidate
|
||||
err := cdc.UnmarshalJSON([]byte(out), &validator)
|
||||
require.NoError(t, err, "out %v\n, err %v", out, err)
|
||||
return validator
|
||||
}
|
||||
|
||||
@ -14,6 +14,7 @@ import (
|
||||
authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli"
|
||||
bankcmd "github.com/cosmos/cosmos-sdk/x/bank/client/cli"
|
||||
ibccmd "github.com/cosmos/cosmos-sdk/x/ibc/client/cli"
|
||||
slashingcmd "github.com/cosmos/cosmos-sdk/x/slashing/client/cli"
|
||||
stakecmd "github.com/cosmos/cosmos-sdk/x/stake/client/cli"
|
||||
|
||||
"github.com/cosmos/cosmos-sdk/cmd/gaia/app"
|
||||
@ -35,36 +36,83 @@ func main() {
|
||||
// the below functions and eliminate global vars, like we do
|
||||
// with the cdc
|
||||
|
||||
// add standard rpc, and tx commands
|
||||
// add standard rpc commands
|
||||
rpc.AddCommands(rootCmd)
|
||||
rootCmd.AddCommand(client.LineBreak)
|
||||
tx.AddCommands(rootCmd, cdc)
|
||||
rootCmd.AddCommand(client.LineBreak)
|
||||
|
||||
// add query/post commands (custom to binary)
|
||||
//Add state commands
|
||||
tendermintCmd := &cobra.Command{
|
||||
Use: "tendermint",
|
||||
Short: "Tendermint state querying subcommands",
|
||||
}
|
||||
tendermintCmd.AddCommand(
|
||||
rpc.BlockCommand(),
|
||||
rpc.ValidatorCommand(),
|
||||
)
|
||||
tx.AddCommands(tendermintCmd, cdc)
|
||||
|
||||
//Add IBC commands
|
||||
ibcCmd := &cobra.Command{
|
||||
Use: "ibc",
|
||||
Short: "Inter-Blockchain Communication subcommands",
|
||||
}
|
||||
ibcCmd.AddCommand(
|
||||
client.PostCommands(
|
||||
ibccmd.IBCTransferCmd(cdc),
|
||||
ibccmd.IBCRelayCmd(cdc),
|
||||
)...)
|
||||
|
||||
advancedCmd := &cobra.Command{
|
||||
Use: "advanced",
|
||||
Short: "Advanced subcommands",
|
||||
}
|
||||
|
||||
advancedCmd.AddCommand(
|
||||
tendermintCmd,
|
||||
ibcCmd,
|
||||
lcd.ServeCommand(cdc),
|
||||
)
|
||||
rootCmd.AddCommand(
|
||||
advancedCmd,
|
||||
client.LineBreak,
|
||||
)
|
||||
|
||||
//Add stake commands
|
||||
stakeCmd := &cobra.Command{
|
||||
Use: "stake",
|
||||
Short: "Stake and validation subcommands",
|
||||
}
|
||||
stakeCmd.AddCommand(
|
||||
client.GetCommands(
|
||||
stakecmd.GetCmdQueryValidator("stake", cdc),
|
||||
stakecmd.GetCmdQueryValidators("stake", cdc),
|
||||
stakecmd.GetCmdQueryDelegation("stake", cdc),
|
||||
stakecmd.GetCmdQueryDelegations("stake", cdc),
|
||||
slashingcmd.GetCmdQuerySigningInfo("slashing", cdc),
|
||||
)...)
|
||||
stakeCmd.AddCommand(
|
||||
client.PostCommands(
|
||||
stakecmd.GetCmdCreateValidator(cdc),
|
||||
stakecmd.GetCmdEditValidator(cdc),
|
||||
stakecmd.GetCmdDelegate(cdc),
|
||||
stakecmd.GetCmdUnbond(cdc),
|
||||
slashingcmd.GetCmdUnrevoke(cdc),
|
||||
)...)
|
||||
rootCmd.AddCommand(
|
||||
stakeCmd,
|
||||
)
|
||||
|
||||
//Add auth and bank commands
|
||||
rootCmd.AddCommand(
|
||||
client.GetCommands(
|
||||
authcmd.GetAccountCmd("acc", cdc, authcmd.GetAccountDecoder(cdc)),
|
||||
stakecmd.GetCmdQueryCandidate("stake", cdc),
|
||||
stakecmd.GetCmdQueryCandidates("stake", cdc),
|
||||
stakecmd.GetCmdQueryDelegatorBond("stake", cdc),
|
||||
//stakecmd.GetCmdQueryDelegatorBonds("stake", cdc),
|
||||
)...)
|
||||
rootCmd.AddCommand(
|
||||
client.PostCommands(
|
||||
bankcmd.SendTxCmd(cdc),
|
||||
ibccmd.IBCTransferCmd(cdc),
|
||||
ibccmd.IBCRelayCmd(cdc),
|
||||
stakecmd.GetCmdDeclareCandidacy(cdc),
|
||||
stakecmd.GetCmdEditCandidacy(cdc),
|
||||
stakecmd.GetCmdDelegate(cdc),
|
||||
stakecmd.GetCmdUnbond(cdc),
|
||||
)...)
|
||||
|
||||
// add proxy, version and key info
|
||||
rootCmd.AddCommand(
|
||||
client.LineBreak,
|
||||
lcd.ServeCommand(cdc),
|
||||
keys.Commands(),
|
||||
client.LineBreak,
|
||||
version.VersionCmd,
|
||||
|
||||
@ -17,6 +17,7 @@ import (
|
||||
func main() {
|
||||
cdc := app.MakeCodec()
|
||||
ctx := server.NewDefaultContext()
|
||||
cobra.EnableCommandSorting = false
|
||||
rootCmd := &cobra.Command{
|
||||
Use: "gaiad",
|
||||
Short: "Gaia Daemon (server)",
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -103,9 +103,9 @@ type ValidatorGovInfo struct {
|
||||
|
||||
* `Proposals: int64 => Proposal` maps `proposalID` to the `Proposal`
|
||||
`proposalID`
|
||||
* `Options: <proposalID | voterAddress | validatorAddress> => VoteType`: maps to the vote of the `voterAddress` for `proposalID` re its delegation to `validatorAddress`.
|
||||
* `Options: <proposalID | voterAddress | Address> => VoteType`: maps to the vote of the `voterAddress` for `proposalID` re its delegation to `Address`.
|
||||
Returns 0x0 If `voterAddress` has not voted under this validator.
|
||||
* `ValidatorGovInfos: <proposalID | validatorAddress> => ValidatorGovInfo`: maps to the gov info for the `validatorAddress` and `proposalID`.
|
||||
* `ValidatorGovInfos: <proposalID | Address> => ValidatorGovInfo`: maps to the gov info for the `Address` and `proposalID`.
|
||||
Returns `nil` if proposal has not entered voting period or if `address` was not the
|
||||
address of a validator when proposal entered voting period.
|
||||
|
||||
|
||||
@ -184,7 +184,7 @@ vote on the proposal.
|
||||
type TxGovVote struct {
|
||||
ProposalID int64 // proposalID of the proposal
|
||||
Option string // option from OptionSet chosen by the voter
|
||||
ValidatorAddress crypto.address // Address of the validator voter wants to tie its vote to
|
||||
Address crypto.address // Address of the validator voter wants to tie its vote to
|
||||
}
|
||||
```
|
||||
|
||||
@ -202,7 +202,7 @@ Votes need to be tied to a validator in order to compute validator's voting
|
||||
power. If a delegator is bonded to multiple validators, it will have to send
|
||||
one transaction per validator (the UI should facilitate this so that multiple
|
||||
transactions can be sent in one "vote flow"). If the sender is the validator
|
||||
itself, then it will input its own address as `ValidatorAddress`
|
||||
itself, then it will input its own address as `Address`
|
||||
|
||||
Next is a pseudocode proposal of the way `TxGovVote` transactions are
|
||||
handled:
|
||||
@ -223,39 +223,39 @@ handled:
|
||||
// There is no proposal for this proposalID
|
||||
throw
|
||||
|
||||
validator = load(CurrentValidators, txGovVote.ValidatorAddress)
|
||||
validator = load(CurrentValidators, txGovVote.Address)
|
||||
|
||||
if !proposal.InitProcedure.OptionSet.includes(txGovVote.Option) OR
|
||||
(validator == nil) then
|
||||
|
||||
// Throws if
|
||||
// Option is not in Option Set of procedure that was active when vote opened OR if
|
||||
// ValidatorAddress is not the address of a current validator
|
||||
// Address is not the address of a current validator
|
||||
|
||||
throw
|
||||
|
||||
option = load(Options, <txGovVote.ProposalID>:<sender>:<txGovVote.ValidatorAddress>)
|
||||
option = load(Options, <txGovVote.ProposalID>:<sender>:<txGovVote.Address>)
|
||||
|
||||
if (option != nil)
|
||||
// sender has already voted with the Atoms bonded to ValidatorAddress
|
||||
// sender has already voted with the Atoms bonded to Address
|
||||
throw
|
||||
|
||||
if (proposal.VotingStartBlock < 0) OR
|
||||
(CurrentBlock > proposal.VotingStartBlock + proposal.InitProcedure.VotingPeriod) OR
|
||||
(proposal.VotingStartBlock < lastBondingBlock(sender, txGovVote.ValidatorAddress) OR
|
||||
(proposal.VotingStartBlock < lastBondingBlock(sender, txGovVote.Address) OR
|
||||
(proposal.VotingStartBlock < lastUnbondingBlock(sender, txGovVote.Address) OR
|
||||
(proposal.Votes.YesVotes/proposal.InitTotalVotingPower >= 2/3) then
|
||||
|
||||
// Throws if
|
||||
// Vote has not started OR if
|
||||
// Vote had ended OR if
|
||||
// sender bonded Atoms to ValidatorAddress after start of vote OR if
|
||||
// sender unbonded Atoms from ValidatorAddress after start of vote OR if
|
||||
// sender bonded Atoms to Address after start of vote OR if
|
||||
// sender unbonded Atoms from Address after start of vote OR if
|
||||
// special condition is met, i.e. proposal is accepted and closed
|
||||
|
||||
throw
|
||||
|
||||
validatorGovInfo = load(ValidatorGovInfos, <txGovVote.ProposalID>:<validator.ValidatorAddress>)
|
||||
validatorGovInfo = load(ValidatorGovInfos, <txGovVote.ProposalID>:<validator.Address>)
|
||||
|
||||
if (validatorGovInfo == nil)
|
||||
// validator became validator after proposal entered voting period
|
||||
@ -263,39 +263,39 @@ handled:
|
||||
|
||||
// sender can vote, check if sender == validator and store sender's option in Options
|
||||
|
||||
store(Options, <txGovVote.ProposalID>:<sender>:<txGovVote.ValidatorAddress>, txGovVote.Option)
|
||||
store(Options, <txGovVote.ProposalID>:<sender>:<txGovVote.Address>, txGovVote.Option)
|
||||
|
||||
if (sender != validator.address)
|
||||
// Here, sender is not the Address of the validator whose Address is txGovVote.ValidatorAddress
|
||||
// Here, sender is not the Address of the validator whose Address is txGovVote.Address
|
||||
|
||||
if sender does not have bonded Atoms to txGovVote.ValidatorAddress then
|
||||
if sender does not have bonded Atoms to txGovVote.Address then
|
||||
// check in Staking module
|
||||
throw
|
||||
|
||||
validatorOption = load(Options, <txGovVote.ProposalID>:<sender>:<txGovVote.ValidatorAddress>)
|
||||
validatorOption = load(Options, <txGovVote.ProposalID>:<sender>:<txGovVote.Address>)
|
||||
|
||||
if (validatorOption == nil)
|
||||
// Validator has not voted already
|
||||
|
||||
validatorGovInfo.Minus += sender.bondedAmounTo(txGovVote.ValidatorAddress)
|
||||
store(ValidatorGovInfos, <txGovVote.ProposalID>:<validator.ValidatorAddress>, validatorGovInfo)
|
||||
validatorGovInfo.Minus += sender.bondedAmounTo(txGovVote.Address)
|
||||
store(ValidatorGovInfos, <txGovVote.ProposalID>:<validator.Address>, validatorGovInfo)
|
||||
|
||||
else
|
||||
// Validator has already voted
|
||||
// Reduce votes of option chosen by validator by sender's bonded Amount
|
||||
|
||||
proposal.Votes.validatorOption -= sender.bondedAmountTo(txGovVote.ValidatorAddress)
|
||||
proposal.Votes.validatorOption -= sender.bondedAmountTo(txGovVote.Address)
|
||||
|
||||
// increase votes of option chosen by sender by bonded Amount
|
||||
|
||||
senderOption = txGovVote.Option
|
||||
propoal.Votes.senderOption -= sender.bondedAmountTo(txGovVote.ValidatorAddress)
|
||||
propoal.Votes.senderOption -= sender.bondedAmountTo(txGovVote.Address)
|
||||
|
||||
store(Proposals, txGovVote.ProposalID, proposal)
|
||||
|
||||
|
||||
else
|
||||
// sender is the address of the validator whose main Address is txGovVote.ValidatorAddress
|
||||
// sender is the address of the validator whose main Address is txGovVote.Address
|
||||
// i.e. sender == validator
|
||||
|
||||
proposal.Votes.validatorOption += (validatorGovInfo.InitVotingPower - validatorGovInfo.Minus)
|
||||
|
||||
@ -203,7 +203,7 @@ where the ``--sequence`` flag is to be incremented for each transaction, the ``-
|
||||
|
||||
::
|
||||
|
||||
Please enter passphrase for alice:
|
||||
Please enter passphrase for alice:
|
||||
{
|
||||
"check_tx": {
|
||||
"gas": 30
|
||||
@ -250,7 +250,7 @@ First, we need the pub_key data:
|
||||
|
||||
::
|
||||
|
||||
cat $HOME/.gaia2/priv_validator.json
|
||||
cat $HOME/.gaia2/priv_validator.json
|
||||
|
||||
the first part will look like:
|
||||
|
||||
@ -260,17 +260,17 @@ the first part will look like:
|
||||
|
||||
and you want the ``pub_key`` ``data`` that starts with ``96864CE``.
|
||||
|
||||
Now ``bob`` can declare candidacy to that pubkey:
|
||||
Now ``bob`` can create a validator with that pubkey.
|
||||
|
||||
::
|
||||
|
||||
gaiacli declare-candidacy --amount=10mycoin --name=bob --pubkey=<pub_key data> --moniker=bobby
|
||||
gaiacli stake create-validator --amount=10mycoin --name=bob --address-validator=<address> --pub-key=<pubkey> --moniker=bobby
|
||||
|
||||
with an output like:
|
||||
|
||||
::
|
||||
|
||||
Please enter passphrase for bob:
|
||||
Please enter passphrase for bob:
|
||||
{
|
||||
"check_tx": {
|
||||
"gas": 30
|
||||
@ -285,7 +285,7 @@ We should see ``bob``'s account balance decrease by 10 mycoin:
|
||||
|
||||
::
|
||||
|
||||
gaiacli account 5D93A6059B6592833CBC8FA3DA90EE0382198985
|
||||
gaiacli account 5D93A6059B6592833CBC8FA3DA90EE0382198985
|
||||
|
||||
To confirm for certain the new validator is active, ask the tendermint node:
|
||||
|
||||
@ -306,19 +306,19 @@ First let's have ``alice`` send some coins to ``charlie``:
|
||||
|
||||
::
|
||||
|
||||
gaiacli tx --amount=1000mycoin --sequence=2 --name=alice --to=48F74F48281C89E5E4BE9092F735EA519768E8EF
|
||||
gaiacli send --amount=1000mycoin --sequence=2 --name=alice --to=48F74F48281C89E5E4BE9092F735EA519768E8EF
|
||||
|
||||
Then ``charlie`` will delegate some mycoin to ``bob``:
|
||||
|
||||
::
|
||||
|
||||
gaiacli tx delegate --amount=10mycoin --name=charlie --pubkey=<pub_key data>
|
||||
gaiacli stake delegate --amount=10mycoin --address-delegator=<charlie's address> --address-validator=<bob's address> --name=charlie
|
||||
|
||||
You'll see output like:
|
||||
|
||||
::
|
||||
|
||||
Please enter passphrase for charlie:
|
||||
Please enter passphrase for charlie:
|
||||
{
|
||||
"check_tx": {
|
||||
"gas": 30
|
||||
@ -334,7 +334,7 @@ To get more information about the candidate, try:
|
||||
|
||||
::
|
||||
|
||||
gaiacli query candidate --pubkey=<pub_key data>
|
||||
gaiacli stake validator <address>
|
||||
|
||||
and you'll see output similar to:
|
||||
|
||||
@ -367,7 +367,7 @@ It's also possible the query the delegator's bond like so:
|
||||
|
||||
::
|
||||
|
||||
gaiacli query delegator-bond --delegator-address 48F74F48281C89E5E4BE9092F735EA519768E8EF --pubkey 52D6FCD8C92A97F7CCB01205ADF310A18411EA8FDCC10E65BF2FCDB05AD1689B
|
||||
gaiacli stake delegation --address-delegator=<address> --address-validator=<address>
|
||||
|
||||
with an output similar to:
|
||||
|
||||
@ -383,9 +383,9 @@ with an output similar to:
|
||||
"Shares": 20
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
where the ``--delegator-address`` is ``charlie``'s address and the ``-pubkey`` is the same as we've been using.
|
||||
|
||||
where the ``--address-delegator`` is ``charlie``'s address and the ``--address-validator`` is ``bob``'s address.
|
||||
|
||||
|
||||
Unbonding
|
||||
@ -396,7 +396,7 @@ your VotingPower reduce and your account balance increase.
|
||||
|
||||
::
|
||||
|
||||
gaiacli unbond --amount=5mycoin --name=charlie --pubkey=<pub_key data>
|
||||
gaiacli stake unbond --amount=5mycoin --name=charlie --address-delegator=<address> --address-validator=<address>
|
||||
gaiacli account 48F74F48281C89E5E4BE9092F735EA519768E8EF
|
||||
|
||||
See the bond decrease with ``gaiacli query delegator-bond`` like above.
|
||||
See the bond decrease with ``gaiacli stake delegation`` like above.
|
||||
|
||||
@ -16,7 +16,7 @@ First, generate a couple of genesis transactions to be incorparated into the gen
|
||||
gaiacli keys list
|
||||
|
||||
**Note:** If you've already run these tests you may need to overwrite keys using the ``--OWK`` flag
|
||||
When you list the keys you should see two addresses, we'll need these later so take note.
|
||||
When you list the keys you should see two addresses, we'll need these later so take note.
|
||||
Now let's actually create the genesis files for both nodes:
|
||||
|
||||
::
|
||||
@ -44,7 +44,7 @@ Nice. We can also lookup the validator set:
|
||||
|
||||
::
|
||||
|
||||
gaiacli validatorset
|
||||
gaiacli advanced tendermint validator-set
|
||||
|
||||
Then, we try to transfer some ``steak`` to another account:
|
||||
|
||||
@ -72,7 +72,7 @@ Finally, to relinquish all your power, unbond some coins. You should see your Vo
|
||||
|
||||
::
|
||||
|
||||
gaiacli unbond --chain-id=<chain-id> --name=test
|
||||
gaiacli stake unbond --chain-id=<chain-id> --name=test
|
||||
|
||||
That's it!
|
||||
|
||||
|
||||
@ -14,6 +14,7 @@ import (
|
||||
"github.com/cosmos/cosmos-sdk/x/auth"
|
||||
"github.com/cosmos/cosmos-sdk/x/bank"
|
||||
"github.com/cosmos/cosmos-sdk/x/ibc"
|
||||
"github.com/cosmos/cosmos-sdk/x/slashing"
|
||||
"github.com/cosmos/cosmos-sdk/x/stake"
|
||||
|
||||
"github.com/cosmos/cosmos-sdk/examples/basecoin/types"
|
||||
@ -29,16 +30,19 @@ type BasecoinApp struct {
|
||||
cdc *wire.Codec
|
||||
|
||||
// keys to access the substores
|
||||
keyMain *sdk.KVStoreKey
|
||||
keyAccount *sdk.KVStoreKey
|
||||
keyIBC *sdk.KVStoreKey
|
||||
keyStake *sdk.KVStoreKey
|
||||
keyMain *sdk.KVStoreKey
|
||||
keyAccount *sdk.KVStoreKey
|
||||
keyIBC *sdk.KVStoreKey
|
||||
keyStake *sdk.KVStoreKey
|
||||
keySlashing *sdk.KVStoreKey
|
||||
|
||||
// Manage getting and setting accounts
|
||||
accountMapper sdk.AccountMapper
|
||||
coinKeeper bank.Keeper
|
||||
ibcMapper ibc.Mapper
|
||||
stakeKeeper stake.Keeper
|
||||
accountMapper auth.AccountMapper
|
||||
feeCollectionKeeper auth.FeeCollectionKeeper
|
||||
coinKeeper bank.Keeper
|
||||
ibcMapper ibc.Mapper
|
||||
stakeKeeper stake.Keeper
|
||||
slashingKeeper slashing.Keeper
|
||||
}
|
||||
|
||||
func NewBasecoinApp(logger log.Logger, db dbm.DB) *BasecoinApp {
|
||||
@ -48,12 +52,13 @@ func NewBasecoinApp(logger log.Logger, db dbm.DB) *BasecoinApp {
|
||||
|
||||
// Create your application object.
|
||||
var app = &BasecoinApp{
|
||||
BaseApp: bam.NewBaseApp(appName, cdc, logger, db),
|
||||
cdc: cdc,
|
||||
keyMain: sdk.NewKVStoreKey("main"),
|
||||
keyAccount: sdk.NewKVStoreKey("acc"),
|
||||
keyIBC: sdk.NewKVStoreKey("ibc"),
|
||||
keyStake: sdk.NewKVStoreKey("stake"),
|
||||
BaseApp: bam.NewBaseApp(appName, cdc, logger, db),
|
||||
cdc: cdc,
|
||||
keyMain: sdk.NewKVStoreKey("main"),
|
||||
keyAccount: sdk.NewKVStoreKey("acc"),
|
||||
keyIBC: sdk.NewKVStoreKey("ibc"),
|
||||
keyStake: sdk.NewKVStoreKey("stake"),
|
||||
keySlashing: sdk.NewKVStoreKey("slashing"),
|
||||
}
|
||||
|
||||
// Define the accountMapper.
|
||||
@ -67,17 +72,21 @@ func NewBasecoinApp(logger log.Logger, db dbm.DB) *BasecoinApp {
|
||||
app.coinKeeper = bank.NewKeeper(app.accountMapper)
|
||||
app.ibcMapper = ibc.NewMapper(app.cdc, app.keyIBC, app.RegisterCodespace(ibc.DefaultCodespace))
|
||||
app.stakeKeeper = stake.NewKeeper(app.cdc, app.keyStake, app.coinKeeper, app.RegisterCodespace(stake.DefaultCodespace))
|
||||
app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, app.stakeKeeper, app.RegisterCodespace(slashing.DefaultCodespace))
|
||||
|
||||
// register message routes
|
||||
app.Router().
|
||||
AddRoute("auth", auth.NewHandler(app.accountMapper)).
|
||||
AddRoute("bank", bank.NewHandler(app.coinKeeper)).
|
||||
AddRoute("ibc", ibc.NewHandler(app.ibcMapper, app.coinKeeper)).
|
||||
AddRoute("stake", stake.NewHandler(app.stakeKeeper))
|
||||
|
||||
// Initialize BaseApp.
|
||||
app.SetInitChainer(app.initChainer)
|
||||
app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyIBC, app.keyStake)
|
||||
app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, auth.BurnFeeHandler))
|
||||
app.SetBeginBlocker(app.BeginBlocker)
|
||||
app.SetEndBlocker(app.EndBlocker)
|
||||
app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper))
|
||||
app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyIBC, app.keyStake, app.keySlashing)
|
||||
err := app.LoadLatestVersion(app.keyMain)
|
||||
if err != nil {
|
||||
cmn.Exit(err.Error())
|
||||
@ -92,14 +101,33 @@ func MakeCodec() *wire.Codec {
|
||||
sdk.RegisterWire(cdc) // Register Msgs
|
||||
bank.RegisterWire(cdc)
|
||||
stake.RegisterWire(cdc)
|
||||
slashing.RegisterWire(cdc)
|
||||
ibc.RegisterWire(cdc)
|
||||
|
||||
// register custom AppAccount
|
||||
cdc.RegisterInterface((*sdk.Account)(nil), nil)
|
||||
cdc.RegisterInterface((*auth.Account)(nil), nil)
|
||||
cdc.RegisterConcrete(&types.AppAccount{}, "basecoin/Account", nil)
|
||||
return cdc
|
||||
}
|
||||
|
||||
// application updates every end block
|
||||
func (app *BasecoinApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock {
|
||||
tags := slashing.BeginBlocker(ctx, req, app.slashingKeeper)
|
||||
|
||||
return abci.ResponseBeginBlock{
|
||||
Tags: tags.ToKVPairs(),
|
||||
}
|
||||
}
|
||||
|
||||
// application updates every end block
|
||||
func (app *BasecoinApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock {
|
||||
validatorUpdates := stake.EndBlocker(ctx, app.stakeKeeper)
|
||||
|
||||
return abci.ResponseEndBlock{
|
||||
ValidatorUpdates: validatorUpdates,
|
||||
}
|
||||
}
|
||||
|
||||
// Custom logic for basecoin initialization
|
||||
func (app *BasecoinApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain {
|
||||
stateJSON := req.AppStateBytes
|
||||
@ -119,6 +147,10 @@ func (app *BasecoinApp) initChainer(ctx sdk.Context, req abci.RequestInitChain)
|
||||
}
|
||||
app.accountMapper.SetAccount(ctx, acc)
|
||||
}
|
||||
|
||||
// load the initial stake information
|
||||
stake.InitGenesis(ctx, app.stakeKeeper, genesisState.StakeData)
|
||||
|
||||
return abci.ResponseInitChain{}
|
||||
}
|
||||
|
||||
@ -128,7 +160,7 @@ func (app *BasecoinApp) ExportAppStateJSON() (appState json.RawMessage, err erro
|
||||
|
||||
// iterate to get the accounts
|
||||
accounts := []*types.GenesisAccount{}
|
||||
appendAccount := func(acc sdk.Account) (stop bool) {
|
||||
appendAccount := func(acc auth.Account) (stop bool) {
|
||||
account := &types.GenesisAccount{
|
||||
Address: acc.GetAddress(),
|
||||
Coins: acc.GetCoins(),
|
||||
|
||||
@ -11,9 +11,11 @@ import (
|
||||
|
||||
"github.com/cosmos/cosmos-sdk/examples/basecoin/types"
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
"github.com/cosmos/cosmos-sdk/wire"
|
||||
"github.com/cosmos/cosmos-sdk/x/auth"
|
||||
"github.com/cosmos/cosmos-sdk/x/bank"
|
||||
"github.com/cosmos/cosmos-sdk/x/ibc"
|
||||
"github.com/cosmos/cosmos-sdk/x/stake"
|
||||
|
||||
abci "github.com/tendermint/abci/types"
|
||||
crypto "github.com/tendermint/go-crypto"
|
||||
@ -37,9 +39,9 @@ var (
|
||||
coins = sdk.Coins{{"foocoin", 10}}
|
||||
halfCoins = sdk.Coins{{"foocoin", 5}}
|
||||
manyCoins = sdk.Coins{{"foocoin", 1}, {"barcoin", 1}}
|
||||
fee = sdk.StdFee{
|
||||
fee = auth.StdFee{
|
||||
sdk.Coins{{"foocoin", 0}},
|
||||
0,
|
||||
100000,
|
||||
}
|
||||
|
||||
sendMsg1 = bank.MsgSend{
|
||||
@ -85,6 +87,30 @@ var (
|
||||
}
|
||||
)
|
||||
|
||||
func setGenesis(bapp *BasecoinApp, accs ...auth.BaseAccount) error {
|
||||
genaccs := make([]*types.GenesisAccount, len(accs))
|
||||
for i, acc := range accs {
|
||||
genaccs[i] = types.NewGenesisAccount(&types.AppAccount{acc, accName})
|
||||
}
|
||||
|
||||
genesisState := types.GenesisState{
|
||||
Accounts: genaccs,
|
||||
StakeData: stake.DefaultGenesisState(),
|
||||
}
|
||||
|
||||
stateBytes, err := wire.MarshalJSONIndent(bapp.cdc, genesisState)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Initialize the chain
|
||||
vals := []abci.Validator{}
|
||||
bapp.InitChain(abci.RequestInitChain{Validators: vals, AppStateBytes: stateBytes})
|
||||
bapp.Commit()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func loggerAndDB() (log.Logger, dbm.DB) {
|
||||
logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)).With("module", "sdk/app")
|
||||
db := dbm.NewMemDB()
|
||||
@ -96,33 +122,11 @@ func newBasecoinApp() *BasecoinApp {
|
||||
return NewBasecoinApp(logger, db)
|
||||
}
|
||||
|
||||
func setGenesisAccounts(bapp *BasecoinApp, accs ...auth.BaseAccount) error {
|
||||
genaccs := make([]*types.GenesisAccount, len(accs))
|
||||
for i, acc := range accs {
|
||||
genaccs[i] = types.NewGenesisAccount(&types.AppAccount{acc, accName})
|
||||
}
|
||||
|
||||
genesisState := types.GenesisState{
|
||||
Accounts: genaccs,
|
||||
}
|
||||
|
||||
stateBytes, err := json.MarshalIndent(genesisState, "", "\t")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Initialize the chain
|
||||
vals := []abci.Validator{}
|
||||
bapp.InitChain(abci.RequestInitChain{vals, stateBytes})
|
||||
bapp.Commit()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
//_______________________________________________________________________
|
||||
|
||||
func TestMsgs(t *testing.T) {
|
||||
bapp := newBasecoinApp()
|
||||
require.Nil(t, setGenesis(bapp))
|
||||
|
||||
msgs := []struct {
|
||||
msg sdk.Msg
|
||||
@ -161,7 +165,7 @@ func TestSortGenesis(t *testing.T) {
|
||||
|
||||
// Initialize the chain
|
||||
vals := []abci.Validator{}
|
||||
bapp.InitChain(abci.RequestInitChain{vals, []byte(genState)})
|
||||
bapp.InitChain(abci.RequestInitChain{Validators: vals, AppStateBytes: []byte(genState)})
|
||||
bapp.Commit()
|
||||
|
||||
// Unsorted coins means invalid
|
||||
@ -193,8 +197,8 @@ func TestGenesis(t *testing.T) {
|
||||
}
|
||||
acc := &types.AppAccount{baseAcc, "foobart"}
|
||||
|
||||
err = setGenesisAccounts(bapp, baseAcc)
|
||||
assert.Nil(t, err)
|
||||
err = setGenesis(bapp, baseAcc)
|
||||
require.Nil(t, err)
|
||||
|
||||
// A checkTx context
|
||||
ctx := bapp.BaseApp.NewContext(true, abci.Header{})
|
||||
@ -208,6 +212,62 @@ func TestGenesis(t *testing.T) {
|
||||
assert.Equal(t, acc, res1)
|
||||
}
|
||||
|
||||
func TestMsgChangePubKey(t *testing.T) {
|
||||
|
||||
bapp := newBasecoinApp()
|
||||
|
||||
// Construct some genesis bytes to reflect basecoin/types/AppAccount
|
||||
// Give 77 foocoin to the first key
|
||||
coins, err := sdk.ParseCoins("77foocoin")
|
||||
require.Nil(t, err)
|
||||
baseAcc := auth.BaseAccount{
|
||||
Address: addr1,
|
||||
Coins: coins,
|
||||
}
|
||||
|
||||
// Construct genesis state
|
||||
err = setGenesis(bapp, baseAcc)
|
||||
require.Nil(t, err)
|
||||
|
||||
// A checkTx context (true)
|
||||
ctxCheck := bapp.BaseApp.NewContext(true, abci.Header{})
|
||||
res1 := bapp.accountMapper.GetAccount(ctxCheck, addr1)
|
||||
assert.Equal(t, baseAcc, res1.(*types.AppAccount).BaseAccount)
|
||||
|
||||
// Run a CheckDeliver
|
||||
SignCheckDeliver(t, bapp, sendMsg1, []int64{0}, true, priv1)
|
||||
|
||||
// Check balances
|
||||
CheckBalance(t, bapp, addr1, "67foocoin")
|
||||
CheckBalance(t, bapp, addr2, "10foocoin")
|
||||
|
||||
changePubKeyMsg := auth.MsgChangeKey{
|
||||
Address: addr1,
|
||||
NewPubKey: priv2.PubKey(),
|
||||
}
|
||||
|
||||
ctxDeliver := bapp.BaseApp.NewContext(false, abci.Header{})
|
||||
acc := bapp.accountMapper.GetAccount(ctxDeliver, addr1)
|
||||
|
||||
// send a MsgChangePubKey
|
||||
SignCheckDeliver(t, bapp, changePubKeyMsg, []int64{1}, true, priv1)
|
||||
acc = bapp.accountMapper.GetAccount(ctxDeliver, addr1)
|
||||
|
||||
assert.True(t, priv2.PubKey().Equals(acc.GetPubKey()))
|
||||
|
||||
// signing a SendMsg with the old privKey should be an auth error
|
||||
tx := genTx(sendMsg1, []int64{2}, priv1)
|
||||
res := bapp.Deliver(tx)
|
||||
assert.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeUnauthorized), res.Code, res.Log)
|
||||
|
||||
// resigning the tx with the new correct priv key should work
|
||||
SignCheckDeliver(t, bapp, sendMsg1, []int64{2}, true, priv2)
|
||||
|
||||
// Check balances
|
||||
CheckBalance(t, bapp, addr1, "57foocoin")
|
||||
CheckBalance(t, bapp, addr2, "20foocoin")
|
||||
}
|
||||
|
||||
func TestMsgSendWithAccounts(t *testing.T) {
|
||||
bapp := newBasecoinApp()
|
||||
|
||||
@ -221,8 +281,9 @@ func TestMsgSendWithAccounts(t *testing.T) {
|
||||
}
|
||||
|
||||
// Construct genesis state
|
||||
err = setGenesisAccounts(bapp, baseAcc)
|
||||
assert.Nil(t, err)
|
||||
err = setGenesis(bapp, baseAcc)
|
||||
require.Nil(t, err)
|
||||
|
||||
// A checkTx context (true)
|
||||
ctxCheck := bapp.BaseApp.NewContext(true, abci.Header{})
|
||||
res1 := bapp.accountMapper.GetAccount(ctxCheck, addr1)
|
||||
@ -265,8 +326,9 @@ func TestMsgSendMultipleOut(t *testing.T) {
|
||||
Coins: genCoins,
|
||||
}
|
||||
|
||||
err = setGenesisAccounts(bapp, acc1, acc2)
|
||||
assert.Nil(t, err)
|
||||
// Construct genesis state
|
||||
err = setGenesis(bapp, acc1, acc2)
|
||||
require.Nil(t, err)
|
||||
|
||||
// Simulate a Block
|
||||
SignCheckDeliver(t, bapp, sendMsg2, []int64{0}, true, priv1)
|
||||
@ -298,7 +360,7 @@ func TestSengMsgMultipleInOut(t *testing.T) {
|
||||
Coins: genCoins,
|
||||
}
|
||||
|
||||
err = setGenesisAccounts(bapp, acc1, acc2, acc4)
|
||||
err = setGenesis(bapp, acc1, acc2, acc4)
|
||||
assert.Nil(t, err)
|
||||
|
||||
// CheckDeliver
|
||||
@ -322,7 +384,11 @@ func TestMsgSendDependent(t *testing.T) {
|
||||
Coins: genCoins,
|
||||
}
|
||||
|
||||
err = setGenesisAccounts(bapp, acc1)
|
||||
// Construct genesis state
|
||||
err = setGenesis(bapp, acc1)
|
||||
require.Nil(t, err)
|
||||
|
||||
err = setGenesis(bapp, acc1)
|
||||
assert.Nil(t, err)
|
||||
|
||||
// CheckDeliver
|
||||
@ -361,7 +427,7 @@ func TestMsgQuiz(t *testing.T) {
|
||||
|
||||
// Initialize the chain (nil)
|
||||
vals := []abci.Validator{}
|
||||
bapp.InitChain(abci.RequestInitChain{vals, stateBytes})
|
||||
bapp.InitChain(abci.RequestInitChain{Validators: vals, AppStateBytes: stateBytes})
|
||||
bapp.Commit()
|
||||
|
||||
// A checkTx context (true)
|
||||
@ -383,8 +449,9 @@ func TestIBCMsgs(t *testing.T) {
|
||||
}
|
||||
acc1 := &types.AppAccount{baseAcc, "foobart"}
|
||||
|
||||
err := setGenesisAccounts(bapp, baseAcc)
|
||||
err := setGenesis(bapp, baseAcc)
|
||||
assert.Nil(t, err)
|
||||
|
||||
// A checkTx context (true)
|
||||
ctxCheck := bapp.BaseApp.NewContext(true, abci.Header{})
|
||||
res1 := bapp.accountMapper.GetAccount(ctxCheck, addr1)
|
||||
@ -416,17 +483,17 @@ func TestIBCMsgs(t *testing.T) {
|
||||
SignCheckDeliver(t, bapp, receiveMsg, []int64{3}, false, priv1)
|
||||
}
|
||||
|
||||
func genTx(msg sdk.Msg, seq []int64, priv ...crypto.PrivKeyEd25519) sdk.StdTx {
|
||||
sigs := make([]sdk.StdSignature, len(priv))
|
||||
func genTx(msg sdk.Msg, seq []int64, priv ...crypto.PrivKeyEd25519) auth.StdTx {
|
||||
sigs := make([]auth.StdSignature, len(priv))
|
||||
for i, p := range priv {
|
||||
sigs[i] = sdk.StdSignature{
|
||||
sigs[i] = auth.StdSignature{
|
||||
PubKey: p.PubKey(),
|
||||
Signature: p.Sign(sdk.StdSignBytes(chainID, seq, fee, msg)),
|
||||
Signature: p.Sign(auth.StdSignBytes(chainID, seq, fee, msg)),
|
||||
Sequence: seq[i],
|
||||
}
|
||||
}
|
||||
|
||||
return sdk.NewStdTx(msg, fee, sigs)
|
||||
return auth.NewStdTx(msg, fee, sigs)
|
||||
|
||||
}
|
||||
|
||||
|
||||
@ -59,8 +59,8 @@ func main() {
|
||||
bankcmd.SendTxCmd(cdc),
|
||||
ibccmd.IBCTransferCmd(cdc),
|
||||
ibccmd.IBCRelayCmd(cdc),
|
||||
stakecmd.GetCmdDeclareCandidacy(cdc),
|
||||
stakecmd.GetCmdEditCandidacy(cdc),
|
||||
stakecmd.GetCmdCreateValidator(cdc),
|
||||
stakecmd.GetCmdEditValidator(cdc),
|
||||
stakecmd.GetCmdDelegate(cdc),
|
||||
stakecmd.GetCmdUnbond(cdc),
|
||||
)...)
|
||||
|
||||
@ -4,9 +4,10 @@ import (
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
"github.com/cosmos/cosmos-sdk/wire"
|
||||
"github.com/cosmos/cosmos-sdk/x/auth"
|
||||
"github.com/cosmos/cosmos-sdk/x/stake"
|
||||
)
|
||||
|
||||
var _ sdk.Account = (*AppAccount)(nil)
|
||||
var _ auth.Account = (*AppAccount)(nil)
|
||||
|
||||
// Custom extensions for this application. This is just an example of
|
||||
// extending auth.BaseAccount with custom fields.
|
||||
@ -23,8 +24,8 @@ func (acc AppAccount) GetName() string { return acc.Name }
|
||||
func (acc *AppAccount) SetName(name string) { acc.Name = name }
|
||||
|
||||
// Get the AccountDecoder function for the custom AppAccount
|
||||
func GetAccountDecoder(cdc *wire.Codec) sdk.AccountDecoder {
|
||||
return func(accBytes []byte) (res sdk.Account, err error) {
|
||||
func GetAccountDecoder(cdc *wire.Codec) auth.AccountDecoder {
|
||||
return func(accBytes []byte) (res auth.Account, err error) {
|
||||
if len(accBytes) == 0 {
|
||||
return nil, sdk.ErrTxDecode("accBytes are empty")
|
||||
}
|
||||
@ -41,7 +42,8 @@ func GetAccountDecoder(cdc *wire.Codec) sdk.AccountDecoder {
|
||||
|
||||
// State to Unmarshal
|
||||
type GenesisState struct {
|
||||
Accounts []*GenesisAccount `json:"accounts"`
|
||||
Accounts []*GenesisAccount `json:"accounts"`
|
||||
StakeData stake.GenesisState `json:"stake"`
|
||||
}
|
||||
|
||||
// GenesisAccount doesn't need pubkey or sequence
|
||||
|
||||
@ -39,14 +39,15 @@ type DemocoinApp struct {
|
||||
capKeyStakingStore *sdk.KVStoreKey
|
||||
|
||||
// keepers
|
||||
coinKeeper bank.Keeper
|
||||
coolKeeper cool.Keeper
|
||||
powKeeper pow.Keeper
|
||||
ibcMapper ibc.Mapper
|
||||
stakeKeeper simplestake.Keeper
|
||||
feeCollectionKeeper auth.FeeCollectionKeeper
|
||||
coinKeeper bank.Keeper
|
||||
coolKeeper cool.Keeper
|
||||
powKeeper pow.Keeper
|
||||
ibcMapper ibc.Mapper
|
||||
stakeKeeper simplestake.Keeper
|
||||
|
||||
// Manage getting and setting accounts
|
||||
accountMapper sdk.AccountMapper
|
||||
accountMapper auth.AccountMapper
|
||||
}
|
||||
|
||||
func NewDemocoinApp(logger log.Logger, db dbm.DB) *DemocoinApp {
|
||||
@ -89,7 +90,7 @@ func NewDemocoinApp(logger log.Logger, db dbm.DB) *DemocoinApp {
|
||||
// Initialize BaseApp.
|
||||
app.SetInitChainer(app.initChainerFn(app.coolKeeper, app.powKeeper))
|
||||
app.MountStoresIAVL(app.capKeyMainStore, app.capKeyAccountStore, app.capKeyPowStore, app.capKeyIBCStore, app.capKeyStakingStore)
|
||||
app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, auth.BurnFeeHandler))
|
||||
app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper))
|
||||
err := app.LoadLatestVersion(app.capKeyMainStore)
|
||||
if err != nil {
|
||||
cmn.Exit(err.Error())
|
||||
@ -109,7 +110,7 @@ func MakeCodec() *wire.Codec {
|
||||
simplestake.RegisterWire(cdc)
|
||||
|
||||
// Register AppAccount
|
||||
cdc.RegisterInterface((*sdk.Account)(nil), nil)
|
||||
cdc.RegisterInterface((*auth.Account)(nil), nil)
|
||||
cdc.RegisterConcrete(&types.AppAccount{}, "democoin/Account", nil)
|
||||
return cdc
|
||||
}
|
||||
@ -158,7 +159,7 @@ func (app *DemocoinApp) ExportAppStateJSON() (appState json.RawMessage, err erro
|
||||
|
||||
// iterate to get the accounts
|
||||
accounts := []*types.GenesisAccount{}
|
||||
appendAccount := func(acc sdk.Account) (stop bool) {
|
||||
appendAccount := func(acc auth.Account) (stop bool) {
|
||||
account := &types.GenesisAccount{
|
||||
Address: acc.GetAddress(),
|
||||
Coins: acc.GetCoins(),
|
||||
|
||||
@ -31,9 +31,9 @@ var (
|
||||
addr1 = priv1.PubKey().Address()
|
||||
addr2 = crypto.GenPrivKeyEd25519().PubKey().Address()
|
||||
coins = sdk.Coins{{"foocoin", 10}}
|
||||
fee = sdk.StdFee{
|
||||
fee = auth.StdFee{
|
||||
sdk.Coins{{"foocoin", 0}},
|
||||
0,
|
||||
1000000,
|
||||
}
|
||||
|
||||
sendMsg = bank.MsgSend{
|
||||
@ -93,8 +93,8 @@ func TestMsgs(t *testing.T) {
|
||||
|
||||
sequences := []int64{0}
|
||||
for i, m := range msgs {
|
||||
sig := priv1.Sign(sdk.StdSignBytes(chainID, sequences, fee, m.msg))
|
||||
tx := sdk.NewStdTx(m.msg, fee, []sdk.StdSignature{{
|
||||
sig := priv1.Sign(auth.StdSignBytes(chainID, sequences, fee, m.msg))
|
||||
tx := auth.NewStdTx(m.msg, fee, []auth.StdSignature{{
|
||||
PubKey: priv1.PubKey(),
|
||||
Signature: sig,
|
||||
}})
|
||||
@ -142,7 +142,7 @@ func TestGenesis(t *testing.T) {
|
||||
stateBytes, err := json.MarshalIndent(genesisState, "", "\t")
|
||||
|
||||
vals := []abci.Validator{}
|
||||
bapp.InitChain(abci.RequestInitChain{vals, stateBytes})
|
||||
bapp.InitChain(abci.RequestInitChain{Validators: vals, AppStateBytes: stateBytes})
|
||||
bapp.Commit()
|
||||
|
||||
// A checkTx context
|
||||
@ -184,7 +184,7 @@ func TestMsgSendWithAccounts(t *testing.T) {
|
||||
|
||||
// Initialize the chain
|
||||
vals := []abci.Validator{}
|
||||
bapp.InitChain(abci.RequestInitChain{vals, stateBytes})
|
||||
bapp.InitChain(abci.RequestInitChain{Validators: vals, AppStateBytes: stateBytes})
|
||||
bapp.Commit()
|
||||
|
||||
// A checkTx context (true)
|
||||
@ -194,8 +194,8 @@ func TestMsgSendWithAccounts(t *testing.T) {
|
||||
|
||||
// Sign the tx
|
||||
sequences := []int64{0}
|
||||
sig := priv1.Sign(sdk.StdSignBytes(chainID, sequences, fee, sendMsg))
|
||||
tx := sdk.NewStdTx(sendMsg, fee, []sdk.StdSignature{{
|
||||
sig := priv1.Sign(auth.StdSignBytes(chainID, sequences, fee, sendMsg))
|
||||
tx := auth.NewStdTx(sendMsg, fee, []auth.StdSignature{{
|
||||
PubKey: priv1.PubKey(),
|
||||
Signature: sig,
|
||||
}})
|
||||
@ -227,7 +227,7 @@ func TestMsgSendWithAccounts(t *testing.T) {
|
||||
|
||||
// resigning the tx with the bumped sequence should work
|
||||
sequences = []int64{1}
|
||||
sig = priv1.Sign(sdk.StdSignBytes(chainID, sequences, fee, tx.Msg))
|
||||
sig = priv1.Sign(auth.StdSignBytes(chainID, sequences, fee, tx.Msg))
|
||||
tx.Signatures[0].Signature = sig
|
||||
res = bapp.Deliver(tx)
|
||||
assert.Equal(t, sdk.ABCICodeOK, res.Code, res.Log)
|
||||
@ -262,7 +262,7 @@ func TestMsgMine(t *testing.T) {
|
||||
|
||||
// Initialize the chain (nil)
|
||||
vals := []abci.Validator{}
|
||||
bapp.InitChain(abci.RequestInitChain{vals, stateBytes})
|
||||
bapp.InitChain(abci.RequestInitChain{Validators: vals, AppStateBytes: stateBytes})
|
||||
bapp.Commit()
|
||||
|
||||
// A checkTx context (true)
|
||||
@ -309,7 +309,7 @@ func TestMsgQuiz(t *testing.T) {
|
||||
|
||||
// Initialize the chain (nil)
|
||||
vals := []abci.Validator{}
|
||||
bapp.InitChain(abci.RequestInitChain{vals, stateBytes})
|
||||
bapp.InitChain(abci.RequestInitChain{Validators: vals, AppStateBytes: stateBytes})
|
||||
bapp.Commit()
|
||||
|
||||
// A checkTx context (true)
|
||||
@ -356,7 +356,7 @@ func TestHandler(t *testing.T) {
|
||||
}
|
||||
stateBytes, err := json.MarshalIndent(genesisState, "", "\t")
|
||||
require.Nil(t, err)
|
||||
bapp.InitChain(abci.RequestInitChain{vals, stateBytes})
|
||||
bapp.InitChain(abci.RequestInitChain{Validators: vals, AppStateBytes: stateBytes})
|
||||
bapp.Commit()
|
||||
|
||||
// A checkTx context (true)
|
||||
@ -394,9 +394,9 @@ func TestHandler(t *testing.T) {
|
||||
func SignCheckDeliver(t *testing.T, bapp *DemocoinApp, msg sdk.Msg, seq int64, expPass bool) {
|
||||
|
||||
// Sign the tx
|
||||
tx := sdk.NewStdTx(msg, fee, []sdk.StdSignature{{
|
||||
tx := auth.NewStdTx(msg, fee, []auth.StdSignature{{
|
||||
PubKey: priv1.PubKey(),
|
||||
Signature: priv1.Sign(sdk.StdSignBytes(chainID, []int64{seq}, fee, msg)),
|
||||
Signature: priv1.Sign(auth.StdSignBytes(chainID, []int64{seq}, fee, msg)),
|
||||
Sequence: seq,
|
||||
}})
|
||||
|
||||
|
||||
@ -9,7 +9,7 @@ import (
|
||||
"github.com/cosmos/cosmos-sdk/examples/democoin/x/pow"
|
||||
)
|
||||
|
||||
var _ sdk.Account = (*AppAccount)(nil)
|
||||
var _ auth.Account = (*AppAccount)(nil)
|
||||
|
||||
// Custom extensions for this application. This is just an example of
|
||||
// extending auth.BaseAccount with custom fields.
|
||||
@ -26,8 +26,8 @@ func (acc AppAccount) GetName() string { return acc.Name }
|
||||
func (acc *AppAccount) SetName(name string) { acc.Name = name }
|
||||
|
||||
// Get the AccountDecoder function for the custom AppAccount
|
||||
func GetAccountDecoder(cdc *wire.Codec) sdk.AccountDecoder {
|
||||
return func(accBytes []byte) (res sdk.Account, err error) {
|
||||
func GetAccountDecoder(cdc *wire.Codec) auth.AccountDecoder {
|
||||
return func(accBytes []byte) (res auth.Account, err error) {
|
||||
if len(accBytes) == 0 {
|
||||
return nil, sdk.ErrTxDecode("accBytes are empty")
|
||||
}
|
||||
|
||||
@ -2,6 +2,7 @@ package simplestake
|
||||
|
||||
import (
|
||||
abci "github.com/tendermint/abci/types"
|
||||
tmtypes "github.com/tendermint/tendermint/types"
|
||||
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
)
|
||||
@ -27,7 +28,7 @@ func handleMsgBond(ctx sdk.Context, k Keeper, msg MsgBond) sdk.Result {
|
||||
}
|
||||
|
||||
valSet := abci.Validator{
|
||||
PubKey: msg.PubKey.Bytes(),
|
||||
PubKey: tmtypes.TM2PB.PubKey(msg.PubKey),
|
||||
Power: power,
|
||||
}
|
||||
|
||||
@ -44,7 +45,7 @@ func handleMsgUnbond(ctx sdk.Context, k Keeper, msg MsgUnbond) sdk.Result {
|
||||
}
|
||||
|
||||
valSet := abci.Validator{
|
||||
PubKey: pubKey.Bytes(),
|
||||
PubKey: tmtypes.TM2PB.PubKey(pubKey),
|
||||
Power: int64(0),
|
||||
}
|
||||
|
||||
|
||||
@ -31,10 +31,13 @@ func setupMultiStore() (sdk.MultiStore, *sdk.KVStoreKey, *sdk.KVStoreKey) {
|
||||
}
|
||||
|
||||
func TestKeeperGetSet(t *testing.T) {
|
||||
ms, _, capKey := setupMultiStore()
|
||||
ms, authKey, capKey := setupMultiStore()
|
||||
cdc := wire.NewCodec()
|
||||
auth.RegisterBaseAccount(cdc)
|
||||
|
||||
accountMapper := auth.NewAccountMapper(cdc, authKey, &auth.BaseAccount{})
|
||||
stakeKeeper := NewKeeper(capKey, bank.NewKeeper(accountMapper), DefaultCodespace)
|
||||
ctx := sdk.NewContext(ms, abci.Header{}, false, nil, log.NewNopLogger())
|
||||
stakeKeeper := NewKeeper(capKey, bank.NewKeeper(nil), DefaultCodespace)
|
||||
addr := sdk.Address([]byte("some-address"))
|
||||
|
||||
bi := stakeKeeper.getBondInfo(ctx, addr)
|
||||
|
||||
@ -26,7 +26,7 @@ func NewMsgBond(addr sdk.Address, stake sdk.Coin, pubKey crypto.PubKey) MsgBond
|
||||
}
|
||||
|
||||
//nolint
|
||||
func (msg MsgBond) Type() string { return moduleName } //TODO update "stake/declarecandidacy"
|
||||
func (msg MsgBond) Type() string { return moduleName } //TODO update "stake/createvalidator"
|
||||
func (msg MsgBond) GetSigners() []sdk.Address { return []sdk.Address{msg.Address} }
|
||||
|
||||
// basic validation of the bond message
|
||||
@ -65,7 +65,7 @@ func NewMsgUnbond(addr sdk.Address) MsgUnbond {
|
||||
}
|
||||
|
||||
//nolint
|
||||
func (msg MsgUnbond) Type() string { return moduleName } //TODO update "stake/declarecandidacy"
|
||||
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 }
|
||||
|
||||
|
||||
321
examples/examples.md
Normal file
321
examples/examples.md
Normal file
@ -0,0 +1,321 @@
|
||||
# Basecoin Example
|
||||
|
||||
Here we explain how to get started with a basic Basecoin blockchain, how
|
||||
to send transactions between accounts using the ``basecli`` tool, and
|
||||
what is happening under the hood.
|
||||
|
||||
## Setup and Install
|
||||
|
||||
You will need to have go installed on your computer. Please refer to the [cosmos testnet tutorial](https://cosmos.network/validators/tutorial), which will always have the most updated instructions on how to get setup with go and the cosmos repository.
|
||||
|
||||
Once you have go installed, run the command:
|
||||
|
||||
```
|
||||
go get github.com/cosmos/cosmos-sdk
|
||||
```
|
||||
|
||||
There will be an error stating `can't load package: package github.com/cosmos/cosmos-sdk: no Go files`, however you can ignore this error, it doesn't affect us. Now change directories to:
|
||||
|
||||
```
|
||||
cd $GOPATH/src/github.com/cosmos/cosmos-sdk
|
||||
```
|
||||
|
||||
And run :
|
||||
|
||||
```
|
||||
make get_tools // run make update_tools if you already had it installed
|
||||
make get_vendor_deps
|
||||
make install_examples
|
||||
```
|
||||
Then run `make install_examples`, which creates binaries for `basecli` and `basecoind`. You can look at the Makefile if you want to see the details on what these make commands are doing.
|
||||
|
||||
## Using basecli and basecoind
|
||||
|
||||
Check the versions by running:
|
||||
|
||||
```
|
||||
basecli version
|
||||
basecoind version
|
||||
```
|
||||
|
||||
They should read something like `0.17.1-5d18d5f`, but the versions will be constantly updating so don't worry if your version is higher that 0.17.1. That's a good thing.
|
||||
|
||||
Note that you can always check help in the terminal by running `basecli -h` or `basecoind -h`. It is good to check these out if you are stuck, because updates to the code base might slightly change the commands, and you might find the correct command in there.
|
||||
|
||||
Let's start by initializing the basecoind daemon. Run the command
|
||||
|
||||
```
|
||||
basecoind init
|
||||
```
|
||||
|
||||
And you should see something like this:
|
||||
|
||||
```
|
||||
{
|
||||
"chain_id": "test-chain-z77iHG",
|
||||
"node_id": "e14c5056212b5736e201dd1d64c89246f3288129",
|
||||
"app_message": {
|
||||
"secret": "pluck life bracket worry guilt wink upgrade olive tilt output reform census member trouble around abandon"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This creates the `~/.basecoind folder`, which has config.toml, genesis.json, node_key.json, priv_validator.json. Take some time to review what is contained in these files if you want to understand what is going on at a deeper level.
|
||||
|
||||
|
||||
## Generating keys
|
||||
|
||||
The next thing we'll need to do is add the key from priv_validator.json to the gaiacli key manager. For this we need the 16 word seed that represents the private key, and a password. You can also get the 16 word seed from the output seen above, under `"secret"`. Then run the command:
|
||||
|
||||
```
|
||||
basecli keys add alice --recover
|
||||
```
|
||||
|
||||
Which will give you three prompts:
|
||||
|
||||
```
|
||||
Enter a passphrase for your key:
|
||||
Repeat the passphrase:
|
||||
Enter your recovery seed phrase:
|
||||
```
|
||||
|
||||
You just created your first locally stored key, under the name alice, and this account is linked to the private key that is running the basecoind validator node. Once you do this, the ~/.basecli folder is created, which will hold the alice key and any other keys you make. Now that you have the key for alice, you can start up the blockchain by running
|
||||
|
||||
```
|
||||
basecoind start
|
||||
```
|
||||
|
||||
You should see blocks being created at a fast rate, with a lot of output in the terminal.
|
||||
|
||||
Next we need to make some more keys so we can use the send transaction functionality of basecoin. Open a new terminal, and run the following commands, to make two new accounts, and give each account a password you can remember:
|
||||
|
||||
```
|
||||
basecli keys add bob
|
||||
basecli keys add charlie
|
||||
```
|
||||
|
||||
You can see your keys with the command:
|
||||
|
||||
```
|
||||
basecli keys list
|
||||
```
|
||||
|
||||
You should now see alice, bob and charlie's account all show up.
|
||||
|
||||
```
|
||||
NAME: ADDRESS: PUBKEY:
|
||||
alice 90B0B9BE0914ECEE0B6DB74E67B07A00056B9BBD 1624DE62201D47E63694448665F5D0217EA8458177728C91C373047A42BD3C0FB78BD0BFA7
|
||||
bob 29D721F054537C91F618A0FDBF770DA51EF8C48D 1624DE6220F54B2A2CA9EB4EE30DE23A73D15902E087C09CC5616456DDDD3814769E2E0A16
|
||||
charlie 2E8E13EEB8E3F0411ACCBC9BE0384732C24FBD5E 1624DE6220F8C9FB8B07855FD94126F88A155BD6EB973509AE5595EFDE1AF05B4964836A53
|
||||
```
|
||||
|
||||
|
||||
## Send transactions
|
||||
|
||||
Lets send bob and charlie some tokens. First, lets query alice's account so we can see what kind of tokens she has:
|
||||
|
||||
```
|
||||
basecli account 90B0B9BE0914ECEE0B6DB74E67B07A00056B9BBD
|
||||
```
|
||||
|
||||
Where `90B0B9BE0914ECEE0B6DB74E67B07A00056B9BBD` is alice's address we got from running `basecli keys list`. You should see a large amount of "mycoin" there. If you search for bob's or charlie's address, the command will fail, because they haven't been added into the blockchain database yet since they have no coins. We need to send them some!
|
||||
|
||||
The following command will send coins from alice, to bob:
|
||||
|
||||
```
|
||||
basecli send --name=alice --amount=10000mycoin --to=29D721F054537C91F618A0FDBF770DA51EF8C48D
|
||||
--sequence=0 --chain-id=test-chain-AE4XQo
|
||||
```
|
||||
|
||||
Flag Descriptions:
|
||||
- `name` is the name you gave your key
|
||||
- `mycoin` is the name of the token for this basecoin demo, initialized in the genesis.json file
|
||||
- `sequence` is a tally of how many transactions have been made by this account. Since this is the first tx on this account, it is 0
|
||||
- `chain-id` is the unique ID that helps tendermint identify which network to connect to. You can find it in the terminal output from the gaiad daemon in the header block , or in the genesis.json file at `~/.basecoind/config/genesis.json`
|
||||
|
||||
Now if we check bobs account, it should have `10000 mycoin`. You can do so by running :
|
||||
|
||||
```
|
||||
basecli account 29D721F054537C91F618A0FDBF770DA51EF8C48D
|
||||
```
|
||||
|
||||
Now lets send some from bob to charlie. Make sure you send less than bob has, otherwise the transaction will fail:
|
||||
|
||||
```
|
||||
basecli send --name=bob --amount=5000mycoin --to=2E8E13EEB8E3F0411ACCBC9BE0384732C24FBD5E
|
||||
--sequence=0 --chain-id=test-chain-AE4XQo
|
||||
```
|
||||
|
||||
Note how we use the ``--name`` flag to select a different account to send from.
|
||||
|
||||
Lets now try to send from bob back to alice:
|
||||
|
||||
```
|
||||
basecli send --name=bob --amount=3000mycoin --to=90B0B9BE0914ECEE0B6DB74E67B07A00056B9BBD
|
||||
--sequence=1 --chain-id=test-chain-AE4XQo
|
||||
```
|
||||
|
||||
Notice that the sequence is now 1, since we have already recorded bobs 1st transaction as `sequence 0`. Also note the ``hash`` value in the response in the terminal - this is the hash of the transaction. We can query for the transaction with this command:
|
||||
|
||||
```
|
||||
basecli tx <INSERT HASH HERE>
|
||||
```
|
||||
|
||||
It will return the details of the transaction hash, such as how many coins were send and to which address, and on what block it occurred.
|
||||
|
||||
That is the basic implementation of basecoin!
|
||||
|
||||
|
||||
## Reset the basecoind blockchain and basecli data
|
||||
|
||||
**WARNING:** Running these commands will wipe out any existing
|
||||
information in both the ``~/.basecli`` and ``~/.basecoind`` directories,
|
||||
including private keys. This should be no problem considering that basecoin
|
||||
is just an example, but it is always good to pay extra attention when
|
||||
you are removing private keys, in any scenario involving a blockchain.
|
||||
|
||||
To remove all the files created and refresh your environment (e.g., if
|
||||
starting this tutorial again or trying something new), the following
|
||||
commands are run:
|
||||
|
||||
```
|
||||
basecoind unsafe_reset_all
|
||||
rm -rf ~/.basecoind
|
||||
rm -rf ~/.basecli
|
||||
```
|
||||
|
||||
## Technical Details on how Basecoin Works
|
||||
|
||||
This section describes some of the more technical aspects for what is going on under the hood of Basecoin.
|
||||
|
||||
## Proof
|
||||
|
||||
Even if you don't see it in the UI, the result of every query comes with
|
||||
a proof. This is a Merkle proof that the result of the query is actually
|
||||
contained in the state. And the state's Merkle root is contained in a
|
||||
recent block header. Behind the scenes, ``basecli`` will not only
|
||||
verify that this state matches the header, but also that the header is
|
||||
properly signed by the known validator set. It will even update the
|
||||
validator set as needed, so long as there have not been major changes
|
||||
and it is secure to do so. So, if you wonder why the query may take a
|
||||
second... there is a lot of work going on in the background to make sure
|
||||
even a lying full node can't trick your client.
|
||||
|
||||
## Accounts and Transactions
|
||||
|
||||
For a better understanding of how to further use the tools, it helps to
|
||||
understand the underlying data structures, so lets look at accounts and transactions.
|
||||
|
||||
### Accounts
|
||||
|
||||
The Basecoin state consists entirely of a set of accounts. Each account
|
||||
contains an address, a public key, a balance in many different coin denominations,
|
||||
and a strictly increasing sequence number for replay protection. This
|
||||
type of account was directly inspired by accounts in Ethereum, and is
|
||||
unlike Bitcoin's use of Unspent Transaction Outputs (UTXOs).
|
||||
|
||||
```
|
||||
type BaseAccount struct {
|
||||
Address sdk.Address `json:"address"`
|
||||
Coins sdk.Coins `json:"coins"`
|
||||
PubKey crypto.PubKey `json:"public_key"`
|
||||
Sequence int64 `json:"sequence"`
|
||||
}
|
||||
```
|
||||
|
||||
You can also add more fields to accounts, and basecoin actually does so. Basecoin
|
||||
adds a Name field in order to show how easily the base account structure can be
|
||||
modified to suit any applications needs. It takes the `auth.BaseAccount` we see above,
|
||||
and extends it with `Name`.
|
||||
|
||||
```
|
||||
type AppAccount struct {
|
||||
auth.BaseAccount
|
||||
Name string `json:"name"`
|
||||
}
|
||||
```
|
||||
|
||||
Within accounts, coin balances are stored. Basecoin is a multi-asset cryptocurrency, so each account can have many
|
||||
different kinds of tokens, which are held in an array.
|
||||
|
||||
```
|
||||
type Coins []Coin
|
||||
|
||||
type Coin struct {
|
||||
Denom string `json:"denom"`
|
||||
Amount int64 `json:"amount"`
|
||||
}
|
||||
```
|
||||
|
||||
If you want to add more coins to a blockchain, you can do so manually in
|
||||
the ``~/.basecoin/genesis.json`` before you start the blockchain for the
|
||||
first time.
|
||||
|
||||
Accounts are serialized and stored in a Merkle tree under the key
|
||||
``base/a/<address>``, where ``<address>`` is the address of the account.
|
||||
Typically, the address of the account is the 20-byte ``RIPEMD160`` hash
|
||||
of the public key, but other formats are acceptable as well, as defined
|
||||
in the `Tendermint crypto
|
||||
library <https://github.com/tendermint/go-crypto>`__. The Merkle tree
|
||||
used in Basecoin is a balanced, binary search tree, which we call an
|
||||
`IAVL tree <https://github.com/tendermint/iavl>`__.
|
||||
|
||||
### Transactions
|
||||
|
||||
Basecoin defines a transaction type, the `SendTx`, which allows tokens
|
||||
to be sent to other accounts. The `SendTx` takes a list of inputs and
|
||||
a list of outputs, and transfers all the tokens listed in the inputs
|
||||
from their corresponding accounts to the accounts listed in the output.
|
||||
The `SendTx` is structured as follows:
|
||||
```
|
||||
type SendTx struct {
|
||||
Gas int64 `json:"gas"`
|
||||
Fee Coin `json:"fee"`
|
||||
Inputs []TxInput `json:"inputs"`
|
||||
Outputs []TxOutput `json:"outputs"`
|
||||
}
|
||||
|
||||
type TxInput struct {
|
||||
Address []byte `json:"address"` // Hash of the PubKey
|
||||
Coins Coins `json:"coins"` //
|
||||
Sequence int `json:"sequence"` // Must be 1 greater than the last committed TxInput
|
||||
Signature crypto.Signature `json:"signature"` // Depends on the PubKey type and the whole Tx
|
||||
PubKey crypto.PubKey `json:"pub_key"` // Is present iff Sequence == 0
|
||||
}
|
||||
|
||||
type TxOutput struct {
|
||||
Address []byte `json:"address"` // Hash of the PubKey
|
||||
Coins Coins `json:"coins"` //
|
||||
}
|
||||
```
|
||||
Note the `SendTx` includes a field for `Gas` and `Fee`. The
|
||||
`Gas` limits the total amount of computation that can be done by the
|
||||
transaction, while the `Fee` refers to the total amount paid in fees.
|
||||
This is slightly different from Ethereum's concept of `Gas` and
|
||||
`GasPrice`, where `Fee = Gas x GasPrice`. In Basecoin, the `Gas`
|
||||
and `Fee` are independent, and the `GasPrice` is implicit.
|
||||
|
||||
In Basecoin, the `Fee` is meant to be used by the validators to inform
|
||||
the ordering of transactions, like in Bitcoin. And the `Gas` is meant
|
||||
to be used by the application plugin to control its execution. There is
|
||||
currently no means to pass `Fee` information to the Tendermint
|
||||
validators, but it will come soon... so this version of Basecoin does
|
||||
not actually fully implement fees and gas, but it still allows us
|
||||
to send transactions between accounts.
|
||||
|
||||
Note also that the `PubKey` only needs to be sent for
|
||||
`Sequence == 0`. After that, it is stored under the account in the
|
||||
Merkle tree and subsequent transactions can exclude it, using only the
|
||||
`Address` to refer to the sender. Ethereum does not require public
|
||||
keys to be sent in transactions as it uses a different elliptic curve
|
||||
scheme which enables the public key to be derived from the signature
|
||||
itself.
|
||||
|
||||
Finally, note that the use of multiple inputs and multiple outputs
|
||||
allows us to send many different types of tokens between many different
|
||||
accounts at once in an atomic transaction. Thus, the `SendTx` can
|
||||
serve as a basic unit of decentralized exchange. When using multiple
|
||||
inputs and outputs, you must make sure that the sum of coins of the
|
||||
inputs equals the sum of coins of the outputs (no creating money), and
|
||||
that all accounts that provide inputs have signed the transaction.
|
||||
|
||||
@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
"github.com/cosmos/cosmos-sdk/x/auth"
|
||||
)
|
||||
|
||||
// An sdk.Tx which is its own sdk.Msg.
|
||||
@ -34,7 +35,7 @@ func (tx kvstoreTx) GetSigners() []sdk.Address {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (tx kvstoreTx) GetSignatures() []sdk.StdSignature {
|
||||
func (tx kvstoreTx) GetSignatures() []auth.StdSignature {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@ -31,10 +31,9 @@ func TestInitApp(t *testing.T) {
|
||||
app.InitChain(req)
|
||||
app.Commit()
|
||||
|
||||
// XXX test failing
|
||||
// make sure we can query these values
|
||||
query := abci.RequestQuery{
|
||||
Path: "/main/key",
|
||||
Path: "/store/main/key",
|
||||
Data: []byte("foo"),
|
||||
}
|
||||
qres := app.Query(query)
|
||||
@ -70,7 +69,7 @@ func TestDeliverTx(t *testing.T) {
|
||||
|
||||
// make sure we can query these values
|
||||
query := abci.RequestQuery{
|
||||
Path: "/main/key",
|
||||
Path: "/store/main/key",
|
||||
Data: []byte(key),
|
||||
}
|
||||
qres := app.Query(query)
|
||||
|
||||
@ -50,6 +50,10 @@ func (ms multiStore) GetKVStore(key sdk.StoreKey) sdk.KVStore {
|
||||
return ms.kv[key]
|
||||
}
|
||||
|
||||
func (ms multiStore) GetKVStoreWithGas(meter sdk.GasMeter, key sdk.StoreKey) sdk.KVStore {
|
||||
panic("not implemented")
|
||||
}
|
||||
|
||||
func (ms multiStore) GetStore(key sdk.StoreKey) sdk.Store {
|
||||
panic("not implemented")
|
||||
}
|
||||
|
||||
@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
"github.com/cosmos/cosmos-sdk/x/auth"
|
||||
)
|
||||
|
||||
// An sdk.Tx which is its own sdk.Msg.
|
||||
@ -47,7 +48,7 @@ func (tx kvstoreTx) GetSigners() []sdk.Address {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (tx kvstoreTx) GetSignatures() []sdk.StdSignature {
|
||||
func (tx kvstoreTx) GetSignatures() []auth.StdSignature {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
67
networks/remote/README.rst
Normal file
67
networks/remote/README.rst
Normal file
@ -0,0 +1,67 @@
|
||||
Terraform & Ansible
|
||||
===================
|
||||
|
||||
Automated deployments are done using `Terraform <https://www.terraform.io/>`__ to create servers on Digital Ocean then
|
||||
`Ansible <http://www.ansible.com/>`__ to create and manage testnets on those servers.
|
||||
|
||||
Prerequisites
|
||||
-------------
|
||||
|
||||
- Install `Terraform <https://www.terraform.io/downloads.html>`__ and `Ansible <http://docs.ansible.com/ansible/latest/installation_guide/intro_installation.html>`__ on a Linux machine.
|
||||
- Create a `DigitalOcean API token <https://cloud.digitalocean.com/settings/api/tokens>`__ with read and write capability.
|
||||
- Install the python dopy package (``pip install dopy``) (This is necessary for the digitalocean.py script for ansible.)
|
||||
- Create SSH keys
|
||||
|
||||
::
|
||||
|
||||
export DO_API_TOKEN="abcdef01234567890abcdef01234567890"
|
||||
export TESTNET_NAME="remotenet"
|
||||
export SSH_PRIVATE_FILE="$HOME/.ssh/id_rsa"
|
||||
export SSH_PUBLIC_FILE="$HOME/.ssh/id_rsa.pub"
|
||||
|
||||
These will be used by both ``terraform`` and ``ansible``.
|
||||
|
||||
Create a remote network
|
||||
-----------------------
|
||||
|
||||
::
|
||||
|
||||
make remotenet-start
|
||||
|
||||
|
||||
Optionally, you can set the number of servers you want to launch and the name of the testnet (which defaults to remotenet):
|
||||
|
||||
::
|
||||
|
||||
TESTNET_NAME="mytestnet" SERVERS=7 make remotenet-start
|
||||
|
||||
|
||||
Quickly see the /status endpoint
|
||||
--------------------------------
|
||||
|
||||
::
|
||||
|
||||
make remotenet-status
|
||||
|
||||
|
||||
Delete servers
|
||||
--------------
|
||||
|
||||
::
|
||||
|
||||
make remotenet-stop
|
||||
|
||||
Logging
|
||||
-------
|
||||
|
||||
You can ship logs to Logz.io, an Elastic stack (Elastic search, Logstash and Kibana) service provider. You can set up your nodes to log there automatically. Create an account and get your API key from the notes on `this page <https://app.logz.io/#/dashboard/data-sources/Filebeat>`__, then:
|
||||
|
||||
::
|
||||
|
||||
yum install systemd-devel || echo "This will only work on RHEL-based systems."
|
||||
apt-get install libsystemd-dev || echo "This will only work on Debian-based systems."
|
||||
|
||||
go get github.com/mheese/journalbeat
|
||||
ansible-playbook -i inventory/digital_ocean.py -l remotenet logzio.yml -e LOGZIO_TOKEN=ABCDEFGHIJKLMNOPQRSTUVWXYZ012345
|
||||
|
||||
|
||||
2
networks/remote/ansible/.gitignore
vendored
Normal file
2
networks/remote/ansible/.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
*.retry
|
||||
files/*
|
||||
4
networks/remote/ansible/ansible.cfg
Normal file
4
networks/remote/ansible/ansible.cfg
Normal file
@ -0,0 +1,4 @@
|
||||
[defaults]
|
||||
retry_files_enabled = False
|
||||
host_key_checking = False
|
||||
|
||||
9
networks/remote/ansible/clear-config.yml
Normal file
9
networks/remote/ansible/clear-config.yml
Normal file
@ -0,0 +1,9 @@
|
||||
---
|
||||
|
||||
- hosts: all
|
||||
user: root
|
||||
any_errors_fatal: true
|
||||
gather_facts: no
|
||||
roles:
|
||||
- clear-config
|
||||
|
||||
675
networks/remote/ansible/inventory/COPYING
Normal file
675
networks/remote/ansible/inventory/COPYING
Normal file
@ -0,0 +1,675 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
|
||||
34
networks/remote/ansible/inventory/digital_ocean.ini
Normal file
34
networks/remote/ansible/inventory/digital_ocean.ini
Normal file
@ -0,0 +1,34 @@
|
||||
# Ansible DigitalOcean external inventory script settings
|
||||
#
|
||||
|
||||
[digital_ocean]
|
||||
|
||||
# The module needs your DigitalOcean API Token.
|
||||
# It may also be specified on the command line via --api-token
|
||||
# or via the environment variables DO_API_TOKEN or DO_API_KEY
|
||||
#
|
||||
#api_token = 123456abcdefg
|
||||
|
||||
|
||||
# API calls to DigitalOcean may be slow. For this reason, we cache the results
|
||||
# of an API call. Set this to the path you want cache files to be written to.
|
||||
# One file will be written to this directory:
|
||||
# - ansible-digital_ocean.cache
|
||||
#
|
||||
cache_path = /tmp
|
||||
|
||||
|
||||
# The number of seconds a cache file is considered valid. After this many
|
||||
# seconds, a new API call will be made, and the cache file will be updated.
|
||||
#
|
||||
cache_max_age = 300
|
||||
|
||||
# Use the private network IP address instead of the public when available.
|
||||
#
|
||||
use_private_network = False
|
||||
|
||||
# Pass variables to every group, e.g.:
|
||||
#
|
||||
# group_variables = { 'ansible_user': 'root' }
|
||||
#
|
||||
group_variables = {}
|
||||
471
networks/remote/ansible/inventory/digital_ocean.py
Executable file
471
networks/remote/ansible/inventory/digital_ocean.py
Executable file
@ -0,0 +1,471 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
'''
|
||||
DigitalOcean external inventory script
|
||||
======================================
|
||||
|
||||
Generates Ansible inventory of DigitalOcean Droplets.
|
||||
|
||||
In addition to the --list and --host options used by Ansible, there are options
|
||||
for generating JSON of other DigitalOcean data. This is useful when creating
|
||||
droplets. For example, --regions will return all the DigitalOcean Regions.
|
||||
This information can also be easily found in the cache file, whose default
|
||||
location is /tmp/ansible-digital_ocean.cache).
|
||||
|
||||
The --pretty (-p) option pretty-prints the output for better human readability.
|
||||
|
||||
----
|
||||
Although the cache stores all the information received from DigitalOcean,
|
||||
the cache is not used for current droplet information (in --list, --host,
|
||||
--all, and --droplets). This is so that accurate droplet information is always
|
||||
found. You can force this script to use the cache with --force-cache.
|
||||
|
||||
----
|
||||
Configuration is read from `digital_ocean.ini`, then from environment variables,
|
||||
then and command-line arguments.
|
||||
|
||||
Most notably, the DigitalOcean API Token must be specified. It can be specified
|
||||
in the INI file or with the following environment variables:
|
||||
export DO_API_TOKEN='abc123' or
|
||||
export DO_API_KEY='abc123'
|
||||
|
||||
Alternatively, it can be passed on the command-line with --api-token.
|
||||
|
||||
If you specify DigitalOcean credentials in the INI file, a handy way to
|
||||
get them into your environment (e.g., to use the digital_ocean module)
|
||||
is to use the output of the --env option with export:
|
||||
export $(digital_ocean.py --env)
|
||||
|
||||
----
|
||||
The following groups are generated from --list:
|
||||
- ID (droplet ID)
|
||||
- NAME (droplet NAME)
|
||||
- image_ID
|
||||
- image_NAME
|
||||
- distro_NAME (distribution NAME from image)
|
||||
- region_NAME
|
||||
- size_NAME
|
||||
- status_STATUS
|
||||
|
||||
For each host, the following variables are registered:
|
||||
- do_backup_ids
|
||||
- do_created_at
|
||||
- do_disk
|
||||
- do_features - list
|
||||
- do_id
|
||||
- do_image - object
|
||||
- do_ip_address
|
||||
- do_private_ip_address
|
||||
- do_kernel - object
|
||||
- do_locked
|
||||
- do_memory
|
||||
- do_name
|
||||
- do_networks - object
|
||||
- do_next_backup_window
|
||||
- do_region - object
|
||||
- do_size - object
|
||||
- do_size_slug
|
||||
- do_snapshot_ids - list
|
||||
- do_status
|
||||
- do_tags
|
||||
- do_vcpus
|
||||
- do_volume_ids
|
||||
|
||||
-----
|
||||
```
|
||||
usage: digital_ocean.py [-h] [--list] [--host HOST] [--all]
|
||||
[--droplets] [--regions] [--images] [--sizes]
|
||||
[--ssh-keys] [--domains] [--pretty]
|
||||
[--cache-path CACHE_PATH]
|
||||
[--cache-max_age CACHE_MAX_AGE]
|
||||
[--force-cache]
|
||||
[--refresh-cache]
|
||||
[--api-token API_TOKEN]
|
||||
|
||||
Produce an Ansible Inventory file based on DigitalOcean credentials
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
--list List all active Droplets as Ansible inventory
|
||||
(default: True)
|
||||
--host HOST Get all Ansible inventory variables about a specific
|
||||
Droplet
|
||||
--all List all DigitalOcean information as JSON
|
||||
--droplets List Droplets as JSON
|
||||
--regions List Regions as JSON
|
||||
--images List Images as JSON
|
||||
--sizes List Sizes as JSON
|
||||
--ssh-keys List SSH keys as JSON
|
||||
--domains List Domains as JSON
|
||||
--pretty, -p Pretty-print results
|
||||
--cache-path CACHE_PATH
|
||||
Path to the cache files (default: .)
|
||||
--cache-max_age CACHE_MAX_AGE
|
||||
Maximum age of the cached items (default: 0)
|
||||
--force-cache Only use data from the cache
|
||||
--refresh-cache Force refresh of cache by making API requests to
|
||||
DigitalOcean (default: False - use cache files)
|
||||
--api-token API_TOKEN, -a API_TOKEN
|
||||
DigitalOcean API Token
|
||||
```
|
||||
|
||||
'''
|
||||
|
||||
# (c) 2013, Evan Wies <evan@neomantra.net>
|
||||
#
|
||||
# Inspired by the EC2 inventory plugin:
|
||||
# https://github.com/ansible/ansible/blob/devel/contrib/inventory/ec2.py
|
||||
#
|
||||
# This file is part of Ansible,
|
||||
#
|
||||
# Ansible is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Ansible is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
######################################################################
|
||||
|
||||
import os
|
||||
import sys
|
||||
import re
|
||||
import argparse
|
||||
from time import time
|
||||
import ConfigParser
|
||||
import ast
|
||||
|
||||
try:
|
||||
import json
|
||||
except ImportError:
|
||||
import simplejson as json
|
||||
|
||||
try:
|
||||
from dopy.manager import DoManager
|
||||
except ImportError as e:
|
||||
sys.exit("failed=True msg='`dopy` library required for this script'")
|
||||
|
||||
|
||||
class DigitalOceanInventory(object):
|
||||
|
||||
###########################################################################
|
||||
# Main execution path
|
||||
###########################################################################
|
||||
|
||||
def __init__(self):
|
||||
''' Main execution path '''
|
||||
|
||||
# DigitalOceanInventory data
|
||||
self.data = {} # All DigitalOcean data
|
||||
self.inventory = {} # Ansible Inventory
|
||||
|
||||
# Define defaults
|
||||
self.cache_path = '.'
|
||||
self.cache_max_age = 0
|
||||
self.use_private_network = False
|
||||
self.group_variables = {}
|
||||
|
||||
# Read settings, environment variables, and CLI arguments
|
||||
self.read_settings()
|
||||
self.read_environment()
|
||||
self.read_cli_args()
|
||||
|
||||
# Verify credentials were set
|
||||
if not hasattr(self, 'api_token'):
|
||||
sys.stderr.write('''Could not find values for DigitalOcean api_token.
|
||||
They must be specified via either ini file, command line argument (--api-token),
|
||||
or environment variables (DO_API_TOKEN)\n''')
|
||||
sys.exit(-1)
|
||||
|
||||
# env command, show DigitalOcean credentials
|
||||
if self.args.env:
|
||||
print("DO_API_TOKEN=%s" % self.api_token)
|
||||
sys.exit(0)
|
||||
|
||||
# Manage cache
|
||||
self.cache_filename = self.cache_path + "/ansible-digital_ocean.cache"
|
||||
self.cache_refreshed = False
|
||||
|
||||
if self.is_cache_valid():
|
||||
self.load_from_cache()
|
||||
if len(self.data) == 0:
|
||||
if self.args.force_cache:
|
||||
sys.stderr.write('''Cache is empty and --force-cache was specified\n''')
|
||||
sys.exit(-1)
|
||||
|
||||
self.manager = DoManager(None, self.api_token, api_version=2)
|
||||
|
||||
# Pick the json_data to print based on the CLI command
|
||||
if self.args.droplets:
|
||||
self.load_from_digital_ocean('droplets')
|
||||
json_data = {'droplets': self.data['droplets']}
|
||||
elif self.args.regions:
|
||||
self.load_from_digital_ocean('regions')
|
||||
json_data = {'regions': self.data['regions']}
|
||||
elif self.args.images:
|
||||
self.load_from_digital_ocean('images')
|
||||
json_data = {'images': self.data['images']}
|
||||
elif self.args.sizes:
|
||||
self.load_from_digital_ocean('sizes')
|
||||
json_data = {'sizes': self.data['sizes']}
|
||||
elif self.args.ssh_keys:
|
||||
self.load_from_digital_ocean('ssh_keys')
|
||||
json_data = {'ssh_keys': self.data['ssh_keys']}
|
||||
elif self.args.domains:
|
||||
self.load_from_digital_ocean('domains')
|
||||
json_data = {'domains': self.data['domains']}
|
||||
elif self.args.all:
|
||||
self.load_from_digital_ocean()
|
||||
json_data = self.data
|
||||
elif self.args.host:
|
||||
json_data = self.load_droplet_variables_for_host()
|
||||
else: # '--list' this is last to make it default
|
||||
self.load_from_digital_ocean('droplets')
|
||||
self.build_inventory()
|
||||
json_data = self.inventory
|
||||
|
||||
if self.cache_refreshed:
|
||||
self.write_to_cache()
|
||||
|
||||
if self.args.pretty:
|
||||
print(json.dumps(json_data, sort_keys=True, indent=2))
|
||||
else:
|
||||
print(json.dumps(json_data))
|
||||
# That's all she wrote...
|
||||
|
||||
###########################################################################
|
||||
# Script configuration
|
||||
###########################################################################
|
||||
|
||||
def read_settings(self):
|
||||
''' Reads the settings from the digital_ocean.ini file '''
|
||||
config = ConfigParser.SafeConfigParser()
|
||||
config.read(os.path.dirname(os.path.realpath(__file__)) + '/digital_ocean.ini')
|
||||
|
||||
# Credentials
|
||||
if config.has_option('digital_ocean', 'api_token'):
|
||||
self.api_token = config.get('digital_ocean', 'api_token')
|
||||
|
||||
# Cache related
|
||||
if config.has_option('digital_ocean', 'cache_path'):
|
||||
self.cache_path = config.get('digital_ocean', 'cache_path')
|
||||
if config.has_option('digital_ocean', 'cache_max_age'):
|
||||
self.cache_max_age = config.getint('digital_ocean', 'cache_max_age')
|
||||
|
||||
# Private IP Address
|
||||
if config.has_option('digital_ocean', 'use_private_network'):
|
||||
self.use_private_network = config.getboolean('digital_ocean', 'use_private_network')
|
||||
|
||||
# Group variables
|
||||
if config.has_option('digital_ocean', 'group_variables'):
|
||||
self.group_variables = ast.literal_eval(config.get('digital_ocean', 'group_variables'))
|
||||
|
||||
def read_environment(self):
|
||||
''' Reads the settings from environment variables '''
|
||||
# Setup credentials
|
||||
if os.getenv("DO_API_TOKEN"):
|
||||
self.api_token = os.getenv("DO_API_TOKEN")
|
||||
if os.getenv("DO_API_KEY"):
|
||||
self.api_token = os.getenv("DO_API_KEY")
|
||||
|
||||
def read_cli_args(self):
|
||||
''' Command line argument processing '''
|
||||
parser = argparse.ArgumentParser(description='Produce an Ansible Inventory file based on DigitalOcean credentials')
|
||||
|
||||
parser.add_argument('--list', action='store_true', help='List all active Droplets as Ansible inventory (default: True)')
|
||||
parser.add_argument('--host', action='store', help='Get all Ansible inventory variables about a specific Droplet')
|
||||
|
||||
parser.add_argument('--all', action='store_true', help='List all DigitalOcean information as JSON')
|
||||
parser.add_argument('--droplets', '-d', action='store_true', help='List Droplets as JSON')
|
||||
parser.add_argument('--regions', action='store_true', help='List Regions as JSON')
|
||||
parser.add_argument('--images', action='store_true', help='List Images as JSON')
|
||||
parser.add_argument('--sizes', action='store_true', help='List Sizes as JSON')
|
||||
parser.add_argument('--ssh-keys', action='store_true', help='List SSH keys as JSON')
|
||||
parser.add_argument('--domains', action='store_true', help='List Domains as JSON')
|
||||
|
||||
parser.add_argument('--pretty', '-p', action='store_true', help='Pretty-print results')
|
||||
|
||||
parser.add_argument('--cache-path', action='store', help='Path to the cache files (default: .)')
|
||||
parser.add_argument('--cache-max_age', action='store', help='Maximum age of the cached items (default: 0)')
|
||||
parser.add_argument('--force-cache', action='store_true', default=False, help='Only use data from the cache')
|
||||
parser.add_argument('--refresh-cache', '-r', action='store_true', default=False,
|
||||
help='Force refresh of cache by making API requests to DigitalOcean (default: False - use cache files)')
|
||||
|
||||
parser.add_argument('--env', '-e', action='store_true', help='Display DO_API_TOKEN')
|
||||
parser.add_argument('--api-token', '-a', action='store', help='DigitalOcean API Token')
|
||||
|
||||
self.args = parser.parse_args()
|
||||
|
||||
if self.args.api_token:
|
||||
self.api_token = self.args.api_token
|
||||
|
||||
# Make --list default if none of the other commands are specified
|
||||
if (not self.args.droplets and not self.args.regions and
|
||||
not self.args.images and not self.args.sizes and
|
||||
not self.args.ssh_keys and not self.args.domains and
|
||||
not self.args.all and not self.args.host):
|
||||
self.args.list = True
|
||||
|
||||
###########################################################################
|
||||
# Data Management
|
||||
###########################################################################
|
||||
|
||||
def load_from_digital_ocean(self, resource=None):
|
||||
'''Get JSON from DigitalOcean API'''
|
||||
if self.args.force_cache and os.path.isfile(self.cache_filename):
|
||||
return
|
||||
# We always get fresh droplets
|
||||
if self.is_cache_valid() and not (resource == 'droplets' or resource is None):
|
||||
return
|
||||
if self.args.refresh_cache:
|
||||
resource = None
|
||||
|
||||
if resource == 'droplets' or resource is None:
|
||||
self.data['droplets'] = self.manager.all_active_droplets()
|
||||
self.cache_refreshed = True
|
||||
if resource == 'regions' or resource is None:
|
||||
self.data['regions'] = self.manager.all_regions()
|
||||
self.cache_refreshed = True
|
||||
if resource == 'images' or resource is None:
|
||||
self.data['images'] = self.manager.all_images(filter=None)
|
||||
self.cache_refreshed = True
|
||||
if resource == 'sizes' or resource is None:
|
||||
self.data['sizes'] = self.manager.sizes()
|
||||
self.cache_refreshed = True
|
||||
if resource == 'ssh_keys' or resource is None:
|
||||
self.data['ssh_keys'] = self.manager.all_ssh_keys()
|
||||
self.cache_refreshed = True
|
||||
if resource == 'domains' or resource is None:
|
||||
self.data['domains'] = self.manager.all_domains()
|
||||
self.cache_refreshed = True
|
||||
|
||||
def build_inventory(self):
|
||||
'''Build Ansible inventory of droplets'''
|
||||
self.inventory = {
|
||||
'all': {
|
||||
'hosts': [],
|
||||
'vars': self.group_variables
|
||||
},
|
||||
'_meta': {'hostvars': {}}
|
||||
}
|
||||
|
||||
# add all droplets by id and name
|
||||
for droplet in self.data['droplets']:
|
||||
# when using private_networking, the API reports the private one in "ip_address".
|
||||
if 'private_networking' in droplet['features'] and not self.use_private_network:
|
||||
for net in droplet['networks']['v4']:
|
||||
if net['type'] == 'public':
|
||||
dest = net['ip_address']
|
||||
else:
|
||||
continue
|
||||
else:
|
||||
dest = droplet['ip_address']
|
||||
|
||||
self.inventory['all']['hosts'].append(dest)
|
||||
|
||||
self.inventory[droplet['id']] = [dest]
|
||||
self.inventory[droplet['name']] = [dest]
|
||||
|
||||
# groups that are always present
|
||||
for group in ('region_' + droplet['region']['slug'],
|
||||
'image_' + str(droplet['image']['id']),
|
||||
'size_' + droplet['size']['slug'],
|
||||
'distro_' + self.to_safe(droplet['image']['distribution']),
|
||||
'status_' + droplet['status']):
|
||||
if group not in self.inventory:
|
||||
self.inventory[group] = {'hosts': [], 'vars': {}}
|
||||
self.inventory[group]['hosts'].append(dest)
|
||||
|
||||
# groups that are not always present
|
||||
for group in (droplet['image']['slug'],
|
||||
droplet['image']['name']):
|
||||
if group:
|
||||
image = 'image_' + self.to_safe(group)
|
||||
if image not in self.inventory:
|
||||
self.inventory[image] = {'hosts': [], 'vars': {}}
|
||||
self.inventory[image]['hosts'].append(dest)
|
||||
|
||||
if droplet['tags']:
|
||||
for tag in droplet['tags']:
|
||||
if tag not in self.inventory:
|
||||
self.inventory[tag] = {'hosts': [], 'vars': {}}
|
||||
self.inventory[tag]['hosts'].append(dest)
|
||||
|
||||
# hostvars
|
||||
info = self.do_namespace(droplet)
|
||||
self.inventory['_meta']['hostvars'][dest] = info
|
||||
|
||||
def load_droplet_variables_for_host(self):
|
||||
'''Generate a JSON response to a --host call'''
|
||||
host = int(self.args.host)
|
||||
droplet = self.manager.show_droplet(host)
|
||||
info = self.do_namespace(droplet)
|
||||
return {'droplet': info}
|
||||
|
||||
###########################################################################
|
||||
# Cache Management
|
||||
###########################################################################
|
||||
|
||||
def is_cache_valid(self):
|
||||
''' Determines if the cache files have expired, or if it is still valid '''
|
||||
if os.path.isfile(self.cache_filename):
|
||||
mod_time = os.path.getmtime(self.cache_filename)
|
||||
current_time = time()
|
||||
if (mod_time + self.cache_max_age) > current_time:
|
||||
return True
|
||||
return False
|
||||
|
||||
def load_from_cache(self):
|
||||
''' Reads the data from the cache file and assigns it to member variables as Python Objects'''
|
||||
try:
|
||||
cache = open(self.cache_filename, 'r')
|
||||
json_data = cache.read()
|
||||
cache.close()
|
||||
data = json.loads(json_data)
|
||||
except IOError:
|
||||
data = {'data': {}, 'inventory': {}}
|
||||
|
||||
self.data = data['data']
|
||||
self.inventory = data['inventory']
|
||||
|
||||
def write_to_cache(self):
|
||||
''' Writes data in JSON format to a file '''
|
||||
data = {'data': self.data, 'inventory': self.inventory}
|
||||
json_data = json.dumps(data, sort_keys=True, indent=2)
|
||||
|
||||
cache = open(self.cache_filename, 'w')
|
||||
cache.write(json_data)
|
||||
cache.close()
|
||||
|
||||
###########################################################################
|
||||
# Utilities
|
||||
###########################################################################
|
||||
|
||||
def push(self, my_dict, key, element):
|
||||
''' Pushed an element onto an array that may not have been defined in the dict '''
|
||||
if key in my_dict:
|
||||
my_dict[key].append(element)
|
||||
else:
|
||||
my_dict[key] = [element]
|
||||
|
||||
def to_safe(self, word):
|
||||
''' Converts 'bad' characters in a string to underscores so they can be used as Ansible groups '''
|
||||
return re.sub("[^A-Za-z0-9\-\.]", "_", word)
|
||||
|
||||
def do_namespace(self, data):
|
||||
''' Returns a copy of the dictionary with all the keys put in a 'do_' namespace '''
|
||||
info = {}
|
||||
for k, v in data.items():
|
||||
info['do_' + k] = v
|
||||
return info
|
||||
|
||||
|
||||
###########################################################################
|
||||
# Run the script
|
||||
DigitalOceanInventory()
|
||||
14
networks/remote/ansible/logzio.yml
Normal file
14
networks/remote/ansible/logzio.yml
Normal file
@ -0,0 +1,14 @@
|
||||
---
|
||||
|
||||
#Note: You need to add LOGZIO_TOKEN variable with your API key. Like this: ansible-playbook -e LOGZIO_TOKEN=ABCXYZ123456
|
||||
|
||||
- hosts: all
|
||||
user: root
|
||||
any_errors_fatal: true
|
||||
gather_facts: no
|
||||
vars:
|
||||
- service: gaiad
|
||||
- JOURNALBEAT_BINARY: "{{lookup('env', 'GOPATH')}}/bin/journalbeat"
|
||||
roles:
|
||||
- logzio
|
||||
|
||||
12
networks/remote/ansible/roles/clear-config/tasks/main.yml
Normal file
12
networks/remote/ansible/roles/clear-config/tasks/main.yml
Normal file
@ -0,0 +1,12 @@
|
||||
---
|
||||
|
||||
- name: Stop service
|
||||
service: name=gaiad state=stopped
|
||||
|
||||
- name: Delete files
|
||||
file: "path={{item}} state=absent"
|
||||
with_items:
|
||||
- /usr/bin/gaiad
|
||||
- /home/gaiad/.gaiad
|
||||
- /home/gaiad/.gaiacli
|
||||
|
||||
@ -0,0 +1,15 @@
|
||||
[Unit]
|
||||
Description=journalbeat
|
||||
#propagates activation, deactivation and activation fails.
|
||||
Requires=network-online.target
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
Restart=on-failure
|
||||
ExecStart=/usr/bin/journalbeat -c /etc/journalbeat/journalbeat.yml -path.home /usr/share/journalbeat -path.config /etc/journalbeat -path.data /var/lib/journalbeat -path.logs /var/log/journalbeat
|
||||
Restart=always
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
|
||||
|
||||
8
networks/remote/ansible/roles/logzio/handlers/main.yml
Normal file
8
networks/remote/ansible/roles/logzio/handlers/main.yml
Normal file
@ -0,0 +1,8 @@
|
||||
---
|
||||
|
||||
- name: reload daemon
|
||||
command: "systemctl daemon-reload"
|
||||
|
||||
- name: restart journalbeat
|
||||
service: name=journalbeat state=restarted
|
||||
|
||||
27
networks/remote/ansible/roles/logzio/tasks/main.yml
Normal file
27
networks/remote/ansible/roles/logzio/tasks/main.yml
Normal file
@ -0,0 +1,27 @@
|
||||
---
|
||||
|
||||
- name: Copy journalbeat binary
|
||||
copy: src="{{JOURNALBEAT_BINARY}}" dest=/usr/bin/journalbeat mode=0755
|
||||
notify: restart journalbeat
|
||||
|
||||
- name: Create folders
|
||||
file: "path={{item}} state=directory recurse=yes"
|
||||
with_items:
|
||||
- /etc/journalbeat
|
||||
- /etc/pki/tls/certs
|
||||
- /usr/share/journalbeat
|
||||
- /var/log/journalbeat
|
||||
|
||||
- name: Copy journalbeat config
|
||||
template: src=journalbeat.yml.j2 dest=/etc/journalbeat/journalbeat.yml mode=0600
|
||||
notify: restart journalbeat
|
||||
|
||||
- name: Get server certificate for Logz.io
|
||||
get_url: "url=https://raw.githubusercontent.com/logzio/public-certificates/master/COMODORSADomainValidationSecureServerCA.crt force=yes dest=/etc/pki/tls/certs/COMODORSADomainValidationSecureServerCA.crt"
|
||||
|
||||
- name: Copy journalbeat service config
|
||||
copy: src=journalbeat.service dest=/etc/systemd/system/journalbeat.service
|
||||
notify:
|
||||
- reload daemon
|
||||
- restart journalbeat
|
||||
|
||||
@ -0,0 +1,342 @@
|
||||
#======================== Journalbeat Configuration ============================
|
||||
|
||||
journalbeat:
|
||||
# What position in journald to seek to at start up
|
||||
# options: cursor, tail, head (defaults to tail)
|
||||
#seek_position: tail
|
||||
|
||||
# If seek_position is set to cursor and seeking to cursor fails
|
||||
# fall back to this method. If set to none will it will exit
|
||||
# options: tail, head, none (defaults to tail)
|
||||
#cursor_seek_fallback: tail
|
||||
|
||||
# Store the cursor of the successfully published events
|
||||
#write_cursor_state: true
|
||||
|
||||
# Path to the file to store the cursor (defaults to ".journalbeat-cursor-state")
|
||||
#cursor_state_file: .journalbeat-cursor-state
|
||||
|
||||
# How frequently should we save the cursor to disk (defaults to 5s)
|
||||
#cursor_flush_period: 5s
|
||||
|
||||
# Path to the file to store the queue of events pending (defaults to ".journalbeat-pending-queue")
|
||||
#pending_queue.file: .journalbeat-pending-queue
|
||||
|
||||
# How frequently should we save the queue to disk (defaults to 1s).
|
||||
# Pending queue represents the WAL of events queued to be published
|
||||
# or being published and waiting for acknowledgement. In case of a
|
||||
# regular restart of journalbeat all the events not yet acknowledged
|
||||
# will be flushed to disk during the shutdown.
|
||||
# In case of disaster most probably journalbeat won't get a chance to shutdown
|
||||
# itself gracefully and this flush period option will serve you as a
|
||||
# backup creation frequency option.
|
||||
#pending_queue.flush_period: 1s
|
||||
|
||||
# Lowercase and remove leading underscores, e.g. "_MESSAGE" -> "message"
|
||||
# (defaults to false)
|
||||
#clean_field_names: false
|
||||
|
||||
# All journal entries are strings by default. You can try to convert them to numbers.
|
||||
# (defaults to false)
|
||||
#convert_to_numbers: false
|
||||
|
||||
# Store all the fields of the Systemd Journal entry under this field
|
||||
# Can be almost any string suitable to be a field name of an ElasticSearch document.
|
||||
# Dots can be used to create nested fields.
|
||||
# Two exceptions:
|
||||
# - no repeated dots;
|
||||
# - no trailing dots, e.g. "journal..field_name." will fail
|
||||
# (defaults to "" hence stores on the upper level of the event)
|
||||
#move_metadata_to_field: ""
|
||||
|
||||
# Specific units to monitor.
|
||||
units: ["{{service}}.service"]
|
||||
|
||||
# Specify Journal paths to open. You can pass an array of paths to Systemd Journal paths.
|
||||
# If you want to open Journal from directory just pass an array consisting of one element
|
||||
# representing the path. See: https://www.freedesktop.org/software/systemd/man/sd_journal_open.html
|
||||
# By default this setting is empty thus journalbeat will attempt to find all journal files automatically
|
||||
#journal_paths: ["/var/log/journal"]
|
||||
|
||||
#default_type: journal
|
||||
|
||||
#================================ General ======================================
|
||||
|
||||
# The name of the shipper that publishes the network data. It can be used to group
|
||||
# all the transactions sent by a single shipper in the web interface.
|
||||
# If this options is not defined, the hostname is used.
|
||||
#name: journalbeat
|
||||
|
||||
# The tags of the shipper are included in their own field with each
|
||||
# transaction published. Tags make it easy to group servers by different
|
||||
# logical properties.
|
||||
tags: ["{{service}}"]
|
||||
|
||||
# Optional fields that you can specify to add additional information to the
|
||||
# output. Fields can be scalar values, arrays, dictionaries, or any nested
|
||||
# combination of these.
|
||||
fields:
|
||||
logzio_codec: plain
|
||||
token: {{LOGZIO_TOKEN}}
|
||||
|
||||
# If this option is set to true, the custom fields are stored as top-level
|
||||
# fields in the output document instead of being grouped under a fields
|
||||
# sub-dictionary. Default is false.
|
||||
fields_under_root: true
|
||||
|
||||
# Internal queue size for single events in processing pipeline
|
||||
#queue_size: 1000
|
||||
|
||||
# The internal queue size for bulk events in the processing pipeline.
|
||||
# Do not modify this value.
|
||||
#bulk_queue_size: 0
|
||||
|
||||
# Sets the maximum number of CPUs that can be executing simultaneously. The
|
||||
# default is the number of logical CPUs available in the system.
|
||||
#max_procs:
|
||||
|
||||
#================================ Processors ===================================
|
||||
|
||||
# Processors are used to reduce the number of fields in the exported event or to
|
||||
# enhance the event with external metadata. This section defines a list of
|
||||
# processors that are applied one by one and the first one receives the initial
|
||||
# event:
|
||||
#
|
||||
# event -> filter1 -> event1 -> filter2 ->event2 ...
|
||||
#
|
||||
# The supported processors are drop_fields, drop_event, include_fields, and
|
||||
# add_cloud_metadata.
|
||||
#
|
||||
# For example, you can use the following processors to keep the fields that
|
||||
# contain CPU load percentages, but remove the fields that contain CPU ticks
|
||||
# values:
|
||||
#
|
||||
processors:
|
||||
#- include_fields:
|
||||
# fields: ["cpu"]
|
||||
- drop_fields:
|
||||
fields: ["beat.name", "beat.version", "logzio_codec", "SYSLOG_IDENTIFIER", "SYSLOG_FACILITY", "PRIORITY"]
|
||||
#
|
||||
# The following example drops the events that have the HTTP response code 200:
|
||||
#
|
||||
#processors:
|
||||
#- drop_event:
|
||||
# when:
|
||||
# equals:
|
||||
# http.code: 200
|
||||
#
|
||||
# The following example enriches each event with metadata from the cloud
|
||||
# provider about the host machine. It works on EC2, GCE, and DigitalOcean.
|
||||
#
|
||||
#processors:
|
||||
#- add_cloud_metadata:
|
||||
#
|
||||
|
||||
#================================ Outputs ======================================
|
||||
|
||||
# Configure what outputs to use when sending the data collected by the beat.
|
||||
# Multiple outputs may be used.
|
||||
|
||||
#----------------------------- Logstash output ---------------------------------
|
||||
output.logstash:
|
||||
# Boolean flag to enable or disable the output module.
|
||||
enabled: true
|
||||
|
||||
# The Logstash hosts
|
||||
hosts: ["listener.logz.io:5015"]
|
||||
|
||||
# Number of workers per Logstash host.
|
||||
#worker: 1
|
||||
|
||||
# Set gzip compression level.
|
||||
#compression_level: 3
|
||||
|
||||
# Optional load balance the events between the Logstash hosts
|
||||
#loadbalance: true
|
||||
|
||||
# Number of batches to be send asynchronously to logstash while processing
|
||||
# new batches.
|
||||
#pipelining: 0
|
||||
|
||||
# Optional index name. The default index name is set to name of the beat
|
||||
# in all lowercase.
|
||||
#index: 'beatname'
|
||||
|
||||
# SOCKS5 proxy server URL
|
||||
#proxy_url: socks5://user:password@socks5-server:2233
|
||||
|
||||
# Resolve names locally when using a proxy server. Defaults to false.
|
||||
#proxy_use_local_resolver: false
|
||||
|
||||
# Enable SSL support. SSL is automatically enabled, if any SSL setting is set.
|
||||
ssl.enabled: true
|
||||
|
||||
# Configure SSL verification mode. If `none` is configured, all server hosts
|
||||
# and certificates will be accepted. In this mode, SSL based connections are
|
||||
# susceptible to man-in-the-middle attacks. Use only for testing. Default is
|
||||
# `full`.
|
||||
ssl.verification_mode: full
|
||||
|
||||
# List of supported/valid TLS versions. By default all TLS versions 1.0 up to
|
||||
# 1.2 are enabled.
|
||||
#ssl.supported_protocols: [TLSv1.0, TLSv1.1, TLSv1.2]
|
||||
|
||||
# Optional SSL configuration options. SSL is off by default.
|
||||
# List of root certificates for HTTPS server verifications
|
||||
ssl.certificate_authorities: ["/etc/pki/tls/certs/COMODORSADomainValidationSecureServerCA.crt"]
|
||||
|
||||
# Certificate for SSL client authentication
|
||||
#ssl.certificate: "/etc/pki/client/cert.pem"
|
||||
|
||||
# Client Certificate Key
|
||||
#ssl.key: "/etc/pki/client/cert.key"
|
||||
|
||||
# Optional passphrase for decrypting the Certificate Key.
|
||||
#ssl.key_passphrase: ''
|
||||
|
||||
# Configure cipher suites to be used for SSL connections
|
||||
#ssl.cipher_suites: []
|
||||
|
||||
# Configure curve types for ECDHE based cipher suites
|
||||
#ssl.curve_types: []
|
||||
|
||||
#------------------------------- File output -----------------------------------
|
||||
#output.file:
|
||||
# Boolean flag to enable or disable the output module.
|
||||
#enabled: true
|
||||
|
||||
# Path to the directory where to save the generated files. The option is
|
||||
# mandatory.
|
||||
#path: "/tmp/beatname"
|
||||
|
||||
# Name of the generated files. The default is `beatname` and it generates
|
||||
# files: `beatname`, `beatname.1`, `beatname.2`, etc.
|
||||
#filename: beatname
|
||||
|
||||
# Maximum size in kilobytes of each file. When this size is reached, and on
|
||||
# every beatname restart, the files are rotated. The default value is 10240
|
||||
# kB.
|
||||
#rotate_every_kb: 10000
|
||||
|
||||
# Maximum number of files under path. When this number of files is reached,
|
||||
# the oldest file is deleted and the rest are shifted from last to first. The
|
||||
# default is 7 files.
|
||||
#number_of_files: 7
|
||||
|
||||
|
||||
#----------------------------- Console output ---------------------------------
|
||||
#output.console:
|
||||
# Boolean flag to enable or disable the output module.
|
||||
#enabled: true
|
||||
|
||||
# Pretty print json event
|
||||
#pretty: false
|
||||
|
||||
#================================= Paths ======================================
|
||||
|
||||
# The home path for the beatname installation. This is the default base path
|
||||
# for all other path settings and for miscellaneous files that come with the
|
||||
# distribution (for example, the sample dashboards).
|
||||
# If not set by a CLI flag or in the configuration file, the default for the
|
||||
# home path is the location of the binary.
|
||||
#path.home:
|
||||
|
||||
# The configuration path for the beatname installation. This is the default
|
||||
# base path for configuration files, including the main YAML configuration file
|
||||
# and the Elasticsearch template file. If not set by a CLI flag or in the
|
||||
# configuration file, the default for the configuration path is the home path.
|
||||
#path.config: ${path.home}
|
||||
|
||||
# The data path for the beatname installation. This is the default base path
|
||||
# for all the files in which beatname needs to store its data. If not set by a
|
||||
# CLI flag or in the configuration file, the default for the data path is a data
|
||||
# subdirectory inside the home path.
|
||||
#path.data: ${path.home}/data
|
||||
|
||||
# The logs path for a beatname installation. This is the default location for
|
||||
# the Beat's log files. If not set by a CLI flag or in the configuration file,
|
||||
# the default for the logs path is a logs subdirectory inside the home path.
|
||||
#path.logs: ${path.home}/logs
|
||||
|
||||
#============================== Dashboards =====================================
|
||||
# These settings control loading the sample dashboards to the Kibana index. Loading
|
||||
# the dashboards is disabled by default and can be enabled either by setting the
|
||||
# options here, or by using the `-setup` CLI flag.
|
||||
#dashboards.enabled: false
|
||||
|
||||
# The URL from where to download the dashboards archive. By default this URL
|
||||
# has a value which is computed based on the Beat name and version. For released
|
||||
# versions, this URL points to the dashboard archive on the artifacts.elastic.co
|
||||
# website.
|
||||
#dashboards.url:
|
||||
|
||||
# The directory from where to read the dashboards. It is used instead of the URL
|
||||
# when it has a value.
|
||||
#dashboards.directory:
|
||||
|
||||
# The file archive (zip file) from where to read the dashboards. It is used instead
|
||||
# of the URL when it has a value.
|
||||
#dashboards.file:
|
||||
|
||||
# If this option is enabled, the snapshot URL is used instead of the default URL.
|
||||
#dashboards.snapshot: false
|
||||
|
||||
# The URL from where to download the snapshot version of the dashboards. By default
|
||||
# this has a value which is computed based on the Beat name and version.
|
||||
#dashboards.snapshot_url
|
||||
|
||||
# In case the archive contains the dashboards from multiple Beats, this lets you
|
||||
# select which one to load. You can load all the dashboards in the archive by
|
||||
# setting this to the empty string.
|
||||
#dashboards.beat: beatname
|
||||
|
||||
# The name of the Kibana index to use for setting the configuration. Default is ".kibana"
|
||||
#dashboards.kibana_index: .kibana
|
||||
|
||||
# The Elasticsearch index name. This overwrites the index name defined in the
|
||||
# dashboards and index pattern. Example: testbeat-*
|
||||
#dashboards.index:
|
||||
|
||||
#================================ Logging ======================================
|
||||
# There are three options for the log output: syslog, file, stderr.
|
||||
# Under Windows systems, the log files are per default sent to the file output,
|
||||
# under all other system per default to syslog.
|
||||
|
||||
# Sets log level. The default log level is info.
|
||||
# Available log levels are: critical, error, warning, info, debug
|
||||
#logging.level: info
|
||||
|
||||
# Enable debug output for selected components. To enable all selectors use ["*"]
|
||||
# Other available selectors are "beat", "publish", "service"
|
||||
# Multiple selectors can be chained.
|
||||
#logging.selectors: [ ]
|
||||
|
||||
# Send all logging output to syslog. The default is false.
|
||||
#logging.to_syslog: true
|
||||
|
||||
# If enabled, beatname periodically logs its internal metrics that have changed
|
||||
# in the last period. For each metric that changed, the delta from the value at
|
||||
# the beginning of the period is logged. Also, the total values for
|
||||
# all non-zero internal metrics are logged on shutdown. The default is true.
|
||||
#logging.metrics.enabled: true
|
||||
|
||||
# The period after which to log the internal metrics. The default is 30s.
|
||||
#logging.metrics.period: 30s
|
||||
|
||||
# Logging to rotating files files. Set logging.to_files to false to disable logging to
|
||||
# files.
|
||||
logging.to_files: true
|
||||
logging.files:
|
||||
# Configure the path where the logs are written. The default is the logs directory
|
||||
# under the home path (the binary location).
|
||||
#path: /var/log/beatname
|
||||
|
||||
# The name of the files where the logs are written to.
|
||||
#name: beatname
|
||||
|
||||
# Configure log file size limit. If limit is reached, log file will be
|
||||
# automatically rotated
|
||||
#rotateeverybytes: 10485760 # = 10MB
|
||||
|
||||
# Number of rotated log files to keep. Oldest files will be deleted first.
|
||||
#keepfiles: 7
|
||||
@ -0,0 +1,4 @@
|
||||
---
|
||||
|
||||
TESTNET_NAME: remotenet
|
||||
|
||||
@ -0,0 +1,50 @@
|
||||
---
|
||||
|
||||
- name: Copy binary
|
||||
copy:
|
||||
src: "{{BINARY}}"
|
||||
dest: /usr/bin
|
||||
mode: 0755
|
||||
|
||||
- name: Get node ID
|
||||
command: "cat /etc/gaiad-nodeid"
|
||||
changed_when: false
|
||||
register: nodeid
|
||||
|
||||
- name: Create initial transaction
|
||||
command: "/usr/bin/gaiad init gen-tx --name=node{{nodeid.stdout_lines[0]}}"
|
||||
become: yes
|
||||
become_user: gaiad
|
||||
args:
|
||||
creates: /home/gaiad/.gaiad/config/gentx
|
||||
|
||||
- name: Find gentx file
|
||||
command: "ls /home/gaiad/.gaiad/config/gentx"
|
||||
changed_when: false
|
||||
register: gentxfile
|
||||
|
||||
- name: Clear local gen-tx list
|
||||
file: path=files/ state=absent
|
||||
connection: local
|
||||
run_once: yes
|
||||
|
||||
- name: Get gen-tx
|
||||
fetch:
|
||||
dest: files/
|
||||
src: "/home/gaiad/.gaiad/config/gentx/{{gentxfile.stdout_lines[0]}}"
|
||||
flat: yes
|
||||
|
||||
- name: Copy generated transactions to all nodes
|
||||
copy:
|
||||
src: files/
|
||||
dest: /home/gaiad/.gaiad/config/gentx/
|
||||
become: yes
|
||||
become_user: gaiad
|
||||
|
||||
- name: Generate genesis.json
|
||||
command: "/usr/bin/gaiad init --gen-txs --name=node{{nodeid.stdout_lines[0]}} --chain-id={{TESTNET_NAME}}"
|
||||
become: yes
|
||||
become_user: gaiad
|
||||
args:
|
||||
creates: /home/gaiad/.gaiad/config/genesis.json
|
||||
|
||||
5
networks/remote/ansible/roles/start/tasks/main.yml
Normal file
5
networks/remote/ansible/roles/start/tasks/main.yml
Normal file
@ -0,0 +1,5 @@
|
||||
---
|
||||
|
||||
- name: start service
|
||||
service: "name={{service}} state=started"
|
||||
|
||||
5
networks/remote/ansible/roles/stop/tasks/main.yml
Normal file
5
networks/remote/ansible/roles/stop/tasks/main.yml
Normal file
@ -0,0 +1,5 @@
|
||||
---
|
||||
|
||||
- name: stop service
|
||||
service: "name={{service}} state=stopped"
|
||||
|
||||
9
networks/remote/ansible/setup-validators.yml
Normal file
9
networks/remote/ansible/setup-validators.yml
Normal file
@ -0,0 +1,9 @@
|
||||
---
|
||||
|
||||
- hosts: all
|
||||
user: root
|
||||
any_errors_fatal: true
|
||||
gather_facts: no
|
||||
roles:
|
||||
- setup-validators
|
||||
|
||||
11
networks/remote/ansible/start.yml
Normal file
11
networks/remote/ansible/start.yml
Normal file
@ -0,0 +1,11 @@
|
||||
---
|
||||
|
||||
- hosts: all
|
||||
user: root
|
||||
any_errors_fatal: true
|
||||
gather_facts: no
|
||||
vars:
|
||||
- service: gaiad
|
||||
roles:
|
||||
- start
|
||||
|
||||
17
networks/remote/ansible/status.yml
Normal file
17
networks/remote/ansible/status.yml
Normal file
@ -0,0 +1,17 @@
|
||||
---
|
||||
|
||||
- hosts: all
|
||||
connection: local
|
||||
any_errors_fatal: true
|
||||
gather_facts: no
|
||||
|
||||
tasks:
|
||||
- name: Gather status
|
||||
uri:
|
||||
body_format: json
|
||||
url: "http://{{inventory_hostname}}:46657/status"
|
||||
register: status
|
||||
|
||||
- name: Print status
|
||||
debug: var=status.json.result
|
||||
|
||||
11
networks/remote/ansible/stop.yml
Normal file
11
networks/remote/ansible/stop.yml
Normal file
@ -0,0 +1,11 @@
|
||||
---
|
||||
|
||||
- hosts: all
|
||||
user: root
|
||||
any_errors_fatal: true
|
||||
gather_facts: no
|
||||
vars:
|
||||
- service: gaiad
|
||||
roles:
|
||||
- stop
|
||||
|
||||
4
networks/remote/terraform/.gitignore
vendored
Normal file
4
networks/remote/terraform/.gitignore
vendored
Normal file
@ -0,0 +1,4 @@
|
||||
.terraform
|
||||
terraform.tfstate
|
||||
terraform.tfstate.backup
|
||||
terraform.tfstate.d
|
||||
53
networks/remote/terraform/README.rst
Normal file
53
networks/remote/terraform/README.rst
Normal file
@ -0,0 +1,53 @@
|
||||
Using Terraform
|
||||
===============
|
||||
|
||||
This is a `Terraform <https://www.terraform.io/>`__ configuration that sets up DigitalOcean droplets.
|
||||
|
||||
Prerequisites
|
||||
-------------
|
||||
|
||||
- Install `HashiCorp Terraform <https://www.terraform.io>`__ on a linux machine.
|
||||
- Create a `DigitalOcean API token <https://cloud.digitalocean.com/settings/api/tokens>`__ with read and write capability.
|
||||
- Create SSH keys
|
||||
|
||||
Build
|
||||
-----
|
||||
|
||||
::
|
||||
|
||||
export DO_API_TOKEN="abcdef01234567890abcdef01234567890"
|
||||
export TESTNET_NAME="remotenet"
|
||||
export SSH_PUBLIC_FILE="$HOME/.ssh/id_rsa.pub"
|
||||
export SSH_PRIVATE_FILE="$HOME/.ssh/id_rsa"
|
||||
|
||||
terraform init
|
||||
terraform apply -var DO_API_TOKEN="$DO_API_TOKEN" -var SSH_PUBLIC_FILE="$SSH_PUBLIC_FILE" -var SSH_PRIVATE_FILE="$SSH_PRIVATE_FILE"
|
||||
|
||||
At the end you will get a list of IP addresses that belongs to your new droplets.
|
||||
|
||||
Destroy
|
||||
-------
|
||||
|
||||
Run the below:
|
||||
|
||||
::
|
||||
|
||||
terraform destroy -var DO_API_TOKEN="$DO_API_TOKEN" -var SSH_PUBLIC_FILE="$SSH_PUBLIC_FILE" -var SSH_PRIVATE_FILE="$SSH_PRIVATE_FILE"
|
||||
|
||||
Good to know
|
||||
------------
|
||||
|
||||
The DigitalOcean API was not very reliable for me. If you find that terraform fails to install a specific server (for example cluster[2]), check
|
||||
the regions variable and remove data center names that you find unreliable. The variable is at cluster/variables.tf
|
||||
|
||||
Example:
|
||||
|
||||
::
|
||||
|
||||
variable "regions" {
|
||||
description = "Regions to launch in"
|
||||
type = "list"
|
||||
default = ["TOR1", "LON1"]
|
||||
}
|
||||
|
||||
|
||||
46
networks/remote/terraform/cluster/main.tf
Normal file
46
networks/remote/terraform/cluster/main.tf
Normal file
@ -0,0 +1,46 @@
|
||||
resource "digitalocean_tag" "cluster" {
|
||||
name = "${var.name}"
|
||||
}
|
||||
|
||||
resource "digitalocean_ssh_key" "cluster" {
|
||||
name = "${var.name}"
|
||||
public_key = "${file(var.ssh_public_file)}"
|
||||
}
|
||||
|
||||
resource "digitalocean_droplet" "cluster" {
|
||||
name = "${var.name}-node${count.index}"
|
||||
image = "centos-7-x64"
|
||||
size = "${var.instance_size}"
|
||||
region = "${element(var.regions, count.index)}"
|
||||
ssh_keys = ["${digitalocean_ssh_key.cluster.id}"]
|
||||
count = "${var.servers}"
|
||||
tags = ["${digitalocean_tag.cluster.id}"]
|
||||
|
||||
lifecycle = {
|
||||
prevent_destroy = false
|
||||
}
|
||||
|
||||
connection {
|
||||
private_key = "${file(var.ssh_private_file)}"
|
||||
timeout = "30s"
|
||||
}
|
||||
|
||||
provisioner "file" {
|
||||
source = "files/terraform.sh"
|
||||
destination = "/tmp/terraform.sh"
|
||||
}
|
||||
|
||||
provisioner "file" {
|
||||
source = "files/gaiad.service"
|
||||
destination = "/etc/systemd/system/gaiad.service"
|
||||
}
|
||||
|
||||
provisioner "remote-exec" {
|
||||
inline = [
|
||||
"chmod +x /tmp/terraform.sh",
|
||||
"/tmp/terraform.sh ${var.name} ${count.index}",
|
||||
]
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
15
networks/remote/terraform/cluster/outputs.tf
Normal file
15
networks/remote/terraform/cluster/outputs.tf
Normal file
@ -0,0 +1,15 @@
|
||||
// The cluster name
|
||||
output "name" {
|
||||
value = "${var.name}"
|
||||
}
|
||||
|
||||
// The list of cluster instance IDs
|
||||
output "instances" {
|
||||
value = ["${digitalocean_droplet.cluster.*.id}"]
|
||||
}
|
||||
|
||||
// The list of cluster instance public IPs
|
||||
output "public_ips" {
|
||||
value = ["${digitalocean_droplet.cluster.*.ipv4_address}"]
|
||||
}
|
||||
|
||||
30
networks/remote/terraform/cluster/variables.tf
Normal file
30
networks/remote/terraform/cluster/variables.tf
Normal file
@ -0,0 +1,30 @@
|
||||
variable "name" {
|
||||
description = "The cluster name, e.g remotenet"
|
||||
}
|
||||
|
||||
variable "regions" {
|
||||
description = "Regions to launch in"
|
||||
type = "list"
|
||||
default = ["AMS2", "TOR1", "LON1", "NYC3", "SFO2", "SGP1", "FRA1"]
|
||||
}
|
||||
|
||||
variable "ssh_private_file" {
|
||||
description = "SSH private key filename to use to connect to the nodes"
|
||||
type = "string"
|
||||
}
|
||||
|
||||
variable "ssh_public_file" {
|
||||
description = "SSH public key filename to copy to the nodes"
|
||||
type = "string"
|
||||
}
|
||||
|
||||
variable "instance_size" {
|
||||
description = "The instance size to use"
|
||||
default = "2gb"
|
||||
}
|
||||
|
||||
variable "servers" {
|
||||
description = "Desired instance count"
|
||||
default = 4
|
||||
}
|
||||
|
||||
17
networks/remote/terraform/files/gaiad.service
Normal file
17
networks/remote/terraform/files/gaiad.service
Normal file
@ -0,0 +1,17 @@
|
||||
[Unit]
|
||||
Description=gaiad
|
||||
Requires=network-online.target
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
Restart=on-failure
|
||||
User=gaiad
|
||||
Group=gaiad
|
||||
PermissionsStartOnly=true
|
||||
ExecStart=/usr/bin/gaiad start
|
||||
ExecReload=/bin/kill -HUP $MAINPID
|
||||
KillSignal=SIGTERM
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
|
||||
19
networks/remote/terraform/files/terraform.sh
Normal file
19
networks/remote/terraform/files/terraform.sh
Normal file
@ -0,0 +1,19 @@
|
||||
#!/bin/bash
|
||||
# Script to initialize a testnet settings on a server
|
||||
|
||||
#Usage: terraform.sh <testnet_name> <testnet_node_number>
|
||||
|
||||
#Add gaiad node number for remote identification
|
||||
echo "$2" > /etc/gaiad-nodeid
|
||||
|
||||
#Create gaiad user
|
||||
useradd -m -s /bin/bash gaiad
|
||||
#cp -r /root/.ssh /home/gaiad/.ssh
|
||||
#chown -R gaiad.gaiad /home/gaiad/.ssh
|
||||
#chmod -R 700 /home/gaiad/.ssh
|
||||
|
||||
#Reload services to enable the gaiad service (note that the gaiad binary is not available yet)
|
||||
systemctl daemon-reload
|
||||
systemctl enable gaiad
|
||||
|
||||
|
||||
43
networks/remote/terraform/main.tf
Normal file
43
networks/remote/terraform/main.tf
Normal file
@ -0,0 +1,43 @@
|
||||
#Terraform Configuration
|
||||
|
||||
variable "DO_API_TOKEN" {
|
||||
description = "DigitalOcean Access Token"
|
||||
}
|
||||
|
||||
variable "TESTNET_NAME" {
|
||||
description = "Name of the testnet"
|
||||
default = "remotenet"
|
||||
}
|
||||
|
||||
variable "SSH_PRIVATE_FILE" {
|
||||
description = "SSH private key file to be used to connect to the nodes"
|
||||
type = "string"
|
||||
}
|
||||
|
||||
variable "SSH_PUBLIC_FILE" {
|
||||
description = "SSH public key file to be used on the nodes"
|
||||
type = "string"
|
||||
}
|
||||
|
||||
variable "SERVERS" {
|
||||
description = "Number of nodes in testnet"
|
||||
default = "4"
|
||||
}
|
||||
|
||||
provider "digitalocean" {
|
||||
token = "${var.DO_API_TOKEN}"
|
||||
}
|
||||
|
||||
module "cluster" {
|
||||
source = "./cluster"
|
||||
name = "${var.TESTNET_NAME}"
|
||||
ssh_private_file = "${var.SSH_PRIVATE_FILE}"
|
||||
ssh_public_file = "${var.SSH_PUBLIC_FILE}"
|
||||
servers = "${var.SERVERS}"
|
||||
}
|
||||
|
||||
|
||||
output "public_ips" {
|
||||
value = "${module.cluster.public_ips}"
|
||||
}
|
||||
|
||||
@ -37,7 +37,9 @@ func TestStartStandAlone(t *testing.T) {
|
||||
|
||||
app, err := mock.NewApp(home, logger)
|
||||
require.Nil(t, err)
|
||||
svr, err := server.NewServer(FreeTCPAddr(t), "socket", app)
|
||||
svrAddr, _, err := FreeTCPAddr()
|
||||
require.Nil(t, err)
|
||||
svr, err := server.NewServer(svrAddr, "socket", app)
|
||||
require.Nil(t, err, "Error creating listener")
|
||||
svr.SetLogger(logger.With("module", "abci-server"))
|
||||
svr.Start()
|
||||
@ -69,7 +71,9 @@ func TestStartWithTendermint(t *testing.T) {
|
||||
// set up app and start up
|
||||
viper.Set(flagWithTendermint, true)
|
||||
startCmd := StartCmd(ctx, mock.NewApp)
|
||||
startCmd.Flags().Set(flagAddress, FreeTCPAddr(t)) // set to a new free address
|
||||
svrAddr, _, err := FreeTCPAddr()
|
||||
require.NoError(t, err)
|
||||
startCmd.Flags().Set(flagAddress, svrAddr) // set to a new free address
|
||||
timeout := time.Duration(5) * time.Second
|
||||
|
||||
close(RunOrTimeout(startCmd, timeout, t))
|
||||
|
||||
@ -16,14 +16,17 @@ import (
|
||||
|
||||
// Get a free address for a test tendermint server
|
||||
// protocol is either tcp, http, etc
|
||||
func FreeTCPAddr(t *testing.T) string {
|
||||
func FreeTCPAddr() (addr, port string, err error) {
|
||||
l, err := net.Listen("tcp", "0.0.0.0:0")
|
||||
defer l.Close()
|
||||
require.Nil(t, err)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
port := l.Addr().(*net.TCPAddr).Port
|
||||
addr := fmt.Sprintf("tcp://0.0.0.0:%d", port)
|
||||
return addr
|
||||
portI := l.Addr().(*net.TCPAddr).Port
|
||||
port = fmt.Sprintf("%d", portI)
|
||||
addr = fmt.Sprintf("tcp://0.0.0.0:%s", port)
|
||||
return
|
||||
}
|
||||
|
||||
// setupViper creates a homedir to run inside,
|
||||
|
||||
@ -1,14 +1,13 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/cosmos/cosmos-sdk/wire"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands"
|
||||
"github.com/tendermint/tendermint/p2p"
|
||||
pvm "github.com/tendermint/tendermint/privval"
|
||||
@ -41,21 +40,24 @@ func ShowValidatorCmd(ctx *Context) *cobra.Command {
|
||||
|
||||
cfg := ctx.Config
|
||||
privValidator := pvm.LoadOrGenFilePV(cfg.PrivValidatorFile())
|
||||
pubKey := privValidator.PubKey
|
||||
valPubKey := privValidator.PubKey
|
||||
|
||||
if viper.GetBool(flagJSON) {
|
||||
|
||||
cdc := wire.NewCodec()
|
||||
wire.RegisterCrypto(cdc)
|
||||
pubKeyJSONBytes, err := cdc.MarshalJSON(pubKey)
|
||||
pubKeyJSONBytes, err := cdc.MarshalJSON(valPubKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(string(pubKeyJSONBytes))
|
||||
return nil
|
||||
}
|
||||
pubKeyHex := strings.ToUpper(hex.EncodeToString(pubKey.Bytes()))
|
||||
fmt.Println(pubKeyHex)
|
||||
pubkey, err := sdk.Bech32ifyValPub(valPubKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(pubkey)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
@ -9,6 +9,7 @@ import (
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
|
||||
"github.com/cosmos/cosmos-sdk/client"
|
||||
"github.com/cosmos/cosmos-sdk/version"
|
||||
"github.com/cosmos/cosmos-sdk/wire"
|
||||
tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands"
|
||||
@ -72,14 +73,24 @@ func AddCommands(
|
||||
|
||||
rootCmd.PersistentFlags().String("log_level", ctx.Config.LogLevel, "Log level")
|
||||
|
||||
tendermintCmd := &cobra.Command{
|
||||
Use: "tendermint",
|
||||
Short: "Tendermint subcommands",
|
||||
}
|
||||
|
||||
tendermintCmd.AddCommand(
|
||||
ShowNodeIDCmd(ctx),
|
||||
ShowValidatorCmd(ctx),
|
||||
)
|
||||
|
||||
rootCmd.AddCommand(
|
||||
InitCmd(ctx, cdc, appInit),
|
||||
StartCmd(ctx, appCreator),
|
||||
UnsafeResetAllCmd(ctx),
|
||||
ShowNodeIDCmd(ctx),
|
||||
ShowValidatorCmd(ctx),
|
||||
client.LineBreak,
|
||||
tendermintCmd,
|
||||
ExportCmd(ctx, cdc, appExport),
|
||||
UnsafeResetAllCmd(ctx),
|
||||
client.LineBreak,
|
||||
version.VersionCmd,
|
||||
)
|
||||
}
|
||||
|
||||
@ -5,7 +5,6 @@ import (
|
||||
"sort"
|
||||
"sync"
|
||||
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
cmn "github.com/tendermint/tmlibs/common"
|
||||
)
|
||||
|
||||
@ -134,16 +133,6 @@ func (ci *cacheKVStore) ReverseIterator(start, end []byte) Iterator {
|
||||
return ci.iterator(start, end, false)
|
||||
}
|
||||
|
||||
// Implements KVStore.
|
||||
func (ci *cacheKVStore) SubspaceIterator(prefix []byte) Iterator {
|
||||
return ci.iterator(prefix, sdk.PrefixEndBytes(prefix), true)
|
||||
}
|
||||
|
||||
// Implements KVStore.
|
||||
func (ci *cacheKVStore) ReverseSubspaceIterator(prefix []byte) Iterator {
|
||||
return ci.iterator(prefix, sdk.PrefixEndBytes(prefix), false)
|
||||
}
|
||||
|
||||
func (ci *cacheKVStore) iterator(start, end []byte, ascending bool) Iterator {
|
||||
var parent, cache Iterator
|
||||
if ascending {
|
||||
|
||||
@ -72,3 +72,8 @@ func (cms cacheMultiStore) GetStore(key StoreKey) Store {
|
||||
func (cms cacheMultiStore) GetKVStore(key StoreKey) KVStore {
|
||||
return cms.stores[key].(KVStore)
|
||||
}
|
||||
|
||||
// Implements MultiStore.
|
||||
func (cms cacheMultiStore) GetKVStoreWithGas(meter sdk.GasMeter, key StoreKey) KVStore {
|
||||
return NewGasKVStore(meter, cms.GetKVStore(key))
|
||||
}
|
||||
|
||||
@ -19,13 +19,5 @@ func (dsa dbStoreAdapter) CacheWrap() CacheWrap {
|
||||
return NewCacheKVStore(dsa)
|
||||
}
|
||||
|
||||
func (dsa dbStoreAdapter) SubspaceIterator(prefix []byte) Iterator {
|
||||
return dsa.Iterator(prefix, sdk.PrefixEndBytes(prefix))
|
||||
}
|
||||
|
||||
func (dsa dbStoreAdapter) ReverseSubspaceIterator(prefix []byte) Iterator {
|
||||
return dsa.ReverseIterator(prefix, sdk.PrefixEndBytes(prefix))
|
||||
}
|
||||
|
||||
// dbm.DB implements KVStore so we can CacheKVStore it.
|
||||
var _ KVStore = dbStoreAdapter{dbm.DB(nil)}
|
||||
|
||||
138
store/gaskvstore.go
Normal file
138
store/gaskvstore.go
Normal file
@ -0,0 +1,138 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
)
|
||||
|
||||
// nolint
|
||||
const (
|
||||
HasCost = 10
|
||||
ReadCostFlat = 10
|
||||
ReadCostPerByte = 1
|
||||
WriteCostFlat = 10
|
||||
WriteCostPerByte = 10
|
||||
KeyCostFlat = 5
|
||||
ValueCostFlat = 10
|
||||
ValueCostPerByte = 1
|
||||
)
|
||||
|
||||
// gasKVStore applies gas tracking to an underlying kvstore
|
||||
type gasKVStore struct {
|
||||
gasMeter sdk.GasMeter
|
||||
parent sdk.KVStore
|
||||
}
|
||||
|
||||
// nolint
|
||||
func NewGasKVStore(gasMeter sdk.GasMeter, parent sdk.KVStore) *gasKVStore {
|
||||
kvs := &gasKVStore{
|
||||
gasMeter: gasMeter,
|
||||
parent: parent,
|
||||
}
|
||||
return kvs
|
||||
}
|
||||
|
||||
// Implements Store.
|
||||
func (gi *gasKVStore) GetStoreType() sdk.StoreType {
|
||||
return gi.parent.GetStoreType()
|
||||
}
|
||||
|
||||
// Implements KVStore.
|
||||
func (gi *gasKVStore) Get(key []byte) (value []byte) {
|
||||
gi.gasMeter.ConsumeGas(ReadCostFlat, "GetFlat")
|
||||
value = gi.parent.Get(key)
|
||||
// TODO overflow-safe math?
|
||||
gi.gasMeter.ConsumeGas(ReadCostPerByte*sdk.Gas(len(value)), "ReadPerByte")
|
||||
return value
|
||||
}
|
||||
|
||||
// Implements KVStore.
|
||||
func (gi *gasKVStore) Set(key []byte, value []byte) {
|
||||
gi.gasMeter.ConsumeGas(WriteCostFlat, "SetFlat")
|
||||
// TODO overflow-safe math?
|
||||
gi.gasMeter.ConsumeGas(WriteCostPerByte*sdk.Gas(len(value)), "SetPerByte")
|
||||
gi.parent.Set(key, value)
|
||||
}
|
||||
|
||||
// Implements KVStore.
|
||||
func (gi *gasKVStore) Has(key []byte) bool {
|
||||
gi.gasMeter.ConsumeGas(HasCost, "Has")
|
||||
return gi.parent.Has(key)
|
||||
}
|
||||
|
||||
// Implements KVStore.
|
||||
func (gi *gasKVStore) Delete(key []byte) {
|
||||
// No gas costs for deletion
|
||||
gi.parent.Delete(key)
|
||||
}
|
||||
|
||||
// Implements KVStore.
|
||||
func (gi *gasKVStore) Iterator(start, end []byte) sdk.Iterator {
|
||||
return gi.iterator(start, end, true)
|
||||
}
|
||||
|
||||
// Implements KVStore.
|
||||
func (gi *gasKVStore) ReverseIterator(start, end []byte) sdk.Iterator {
|
||||
return gi.iterator(start, end, false)
|
||||
}
|
||||
|
||||
// Implements KVStore.
|
||||
func (gi *gasKVStore) CacheWrap() sdk.CacheWrap {
|
||||
panic("you cannot CacheWrap a GasKVStore")
|
||||
}
|
||||
|
||||
func (gi *gasKVStore) iterator(start, end []byte, ascending bool) sdk.Iterator {
|
||||
var parent sdk.Iterator
|
||||
if ascending {
|
||||
parent = gi.parent.Iterator(start, end)
|
||||
} else {
|
||||
parent = gi.parent.ReverseIterator(start, end)
|
||||
}
|
||||
return newGasIterator(gi.gasMeter, parent)
|
||||
}
|
||||
|
||||
type gasIterator struct {
|
||||
gasMeter sdk.GasMeter
|
||||
parent sdk.Iterator
|
||||
}
|
||||
|
||||
func newGasIterator(gasMeter sdk.GasMeter, parent sdk.Iterator) sdk.Iterator {
|
||||
return &gasIterator{
|
||||
gasMeter: gasMeter,
|
||||
parent: parent,
|
||||
}
|
||||
}
|
||||
|
||||
// Implements Iterator.
|
||||
func (g *gasIterator) Domain() (start []byte, end []byte) {
|
||||
return g.parent.Domain()
|
||||
}
|
||||
|
||||
// Implements Iterator.
|
||||
func (g *gasIterator) Valid() bool {
|
||||
return g.parent.Valid()
|
||||
}
|
||||
|
||||
// Implements Iterator.
|
||||
func (g *gasIterator) Next() {
|
||||
g.parent.Next()
|
||||
}
|
||||
|
||||
// Implements Iterator.
|
||||
func (g *gasIterator) Key() (key []byte) {
|
||||
g.gasMeter.ConsumeGas(KeyCostFlat, "KeyFlat")
|
||||
key = g.parent.Key()
|
||||
return key
|
||||
}
|
||||
|
||||
// Implements Iterator.
|
||||
func (g *gasIterator) Value() (value []byte) {
|
||||
value = g.parent.Value()
|
||||
g.gasMeter.ConsumeGas(ValueCostFlat, "ValueFlat")
|
||||
g.gasMeter.ConsumeGas(ValueCostPerByte*sdk.Gas(len(value)), "ValuePerByte")
|
||||
return value
|
||||
}
|
||||
|
||||
// Implements Iterator.
|
||||
func (g *gasIterator) Close() {
|
||||
g.parent.Close()
|
||||
}
|
||||
68
store/gaskvstore_test.go
Normal file
68
store/gaskvstore_test.go
Normal file
@ -0,0 +1,68 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
dbm "github.com/tendermint/tmlibs/db"
|
||||
)
|
||||
|
||||
func newGasKVStore() KVStore {
|
||||
meter := sdk.NewGasMeter(1000)
|
||||
mem := dbStoreAdapter{dbm.NewMemDB()}
|
||||
return NewGasKVStore(meter, mem)
|
||||
}
|
||||
|
||||
func TestGasKVStoreBasic(t *testing.T) {
|
||||
mem := dbStoreAdapter{dbm.NewMemDB()}
|
||||
meter := sdk.NewGasMeter(1000)
|
||||
st := NewGasKVStore(meter, mem)
|
||||
require.Empty(t, st.Get(keyFmt(1)), "Expected `key1` to be empty")
|
||||
st.Set(keyFmt(1), valFmt(1))
|
||||
require.Equal(t, valFmt(1), st.Get(keyFmt(1)))
|
||||
st.Delete(keyFmt(1))
|
||||
require.Empty(t, st.Get(keyFmt(1)), "Expected `key1` to be empty")
|
||||
require.Equal(t, meter.GasConsumed(), sdk.Gas(183))
|
||||
}
|
||||
|
||||
func TestGasKVStoreIterator(t *testing.T) {
|
||||
mem := dbStoreAdapter{dbm.NewMemDB()}
|
||||
meter := sdk.NewGasMeter(1000)
|
||||
st := NewGasKVStore(meter, mem)
|
||||
require.Empty(t, st.Get(keyFmt(1)), "Expected `key1` to be empty")
|
||||
require.Empty(t, st.Get(keyFmt(2)), "Expected `key2` to be empty")
|
||||
st.Set(keyFmt(1), valFmt(1))
|
||||
st.Set(keyFmt(2), valFmt(2))
|
||||
iterator := st.Iterator(nil, nil)
|
||||
ka := iterator.Key()
|
||||
require.Equal(t, ka, keyFmt(1))
|
||||
va := iterator.Value()
|
||||
require.Equal(t, va, valFmt(1))
|
||||
iterator.Next()
|
||||
kb := iterator.Key()
|
||||
require.Equal(t, kb, keyFmt(2))
|
||||
vb := iterator.Value()
|
||||
require.Equal(t, vb, valFmt(2))
|
||||
iterator.Next()
|
||||
require.False(t, iterator.Valid())
|
||||
require.Panics(t, iterator.Next)
|
||||
require.Equal(t, meter.GasConsumed(), sdk.Gas(356))
|
||||
}
|
||||
|
||||
func TestGasKVStoreOutOfGasSet(t *testing.T) {
|
||||
mem := dbStoreAdapter{dbm.NewMemDB()}
|
||||
meter := sdk.NewGasMeter(0)
|
||||
st := NewGasKVStore(meter, mem)
|
||||
require.Panics(t, func() { st.Set(keyFmt(1), valFmt(1)) }, "Expected out-of-gas")
|
||||
}
|
||||
|
||||
func TestGasKVStoreOutOfGasIterator(t *testing.T) {
|
||||
mem := dbStoreAdapter{dbm.NewMemDB()}
|
||||
meter := sdk.NewGasMeter(200)
|
||||
st := NewGasKVStore(meter, mem)
|
||||
st.Set(keyFmt(1), valFmt(1))
|
||||
iterator := st.Iterator(nil, nil)
|
||||
iterator.Next()
|
||||
require.Panics(t, func() { iterator.Value() }, "Expected out-of-gas")
|
||||
}
|
||||
@ -125,16 +125,6 @@ func (st *iavlStore) ReverseIterator(start, end []byte) Iterator {
|
||||
return newIAVLIterator(st.tree.Tree(), start, end, false)
|
||||
}
|
||||
|
||||
// Implements KVStore.
|
||||
func (st *iavlStore) SubspaceIterator(prefix []byte) Iterator {
|
||||
return st.Iterator(prefix, sdk.PrefixEndBytes(prefix))
|
||||
}
|
||||
|
||||
// Implements KVStore.
|
||||
func (st *iavlStore) ReverseSubspaceIterator(prefix []byte) Iterator {
|
||||
return st.ReverseIterator(prefix, sdk.PrefixEndBytes(prefix))
|
||||
}
|
||||
|
||||
// Query implements ABCI interface, allows queries
|
||||
//
|
||||
// by default we will return from (latest height -1),
|
||||
@ -180,7 +170,7 @@ func (st *iavlStore) Query(req abci.RequestQuery) (res abci.ResponseQuery) {
|
||||
subspace := req.Data
|
||||
res.Key = subspace
|
||||
var KVs []KVPair
|
||||
iterator := st.SubspaceIterator(subspace)
|
||||
iterator := sdk.KVStorePrefixIterator(st, subspace)
|
||||
for ; iterator.Valid(); iterator.Next() {
|
||||
KVs = append(KVs, KVPair{iterator.Key(), iterator.Value()})
|
||||
}
|
||||
|
||||
@ -157,7 +157,7 @@ func TestIAVLSubspaceIterator(t *testing.T) {
|
||||
|
||||
i := 0
|
||||
|
||||
iter := iavlStore.SubspaceIterator([]byte("test"))
|
||||
iter := sdk.KVStorePrefixIterator(iavlStore, []byte("test"))
|
||||
expected := []string{"test1", "test2", "test3"}
|
||||
for i = 0; iter.Valid(); iter.Next() {
|
||||
expectedKey := expected[i]
|
||||
@ -168,7 +168,7 @@ func TestIAVLSubspaceIterator(t *testing.T) {
|
||||
}
|
||||
assert.Equal(t, len(expected), i)
|
||||
|
||||
iter = iavlStore.SubspaceIterator([]byte{byte(55), byte(255), byte(255)})
|
||||
iter = sdk.KVStorePrefixIterator(iavlStore, []byte{byte(55), byte(255), byte(255)})
|
||||
expected2 := [][]byte{
|
||||
[]byte{byte(55), byte(255), byte(255), byte(0)},
|
||||
[]byte{byte(55), byte(255), byte(255), byte(1)},
|
||||
@ -183,7 +183,7 @@ func TestIAVLSubspaceIterator(t *testing.T) {
|
||||
}
|
||||
assert.Equal(t, len(expected), i)
|
||||
|
||||
iter = iavlStore.SubspaceIterator([]byte{byte(255), byte(255)})
|
||||
iter = sdk.KVStorePrefixIterator(iavlStore, []byte{byte(255), byte(255)})
|
||||
expected2 = [][]byte{
|
||||
[]byte{byte(255), byte(255), byte(0)},
|
||||
[]byte{byte(255), byte(255), byte(1)},
|
||||
@ -216,7 +216,7 @@ func TestIAVLReverseSubspaceIterator(t *testing.T) {
|
||||
|
||||
i := 0
|
||||
|
||||
iter := iavlStore.ReverseSubspaceIterator([]byte("test"))
|
||||
iter := sdk.KVStoreReversePrefixIterator(iavlStore, []byte("test"))
|
||||
expected := []string{"test3", "test2", "test1"}
|
||||
for i = 0; iter.Valid(); iter.Next() {
|
||||
expectedKey := expected[i]
|
||||
@ -227,7 +227,7 @@ func TestIAVLReverseSubspaceIterator(t *testing.T) {
|
||||
}
|
||||
assert.Equal(t, len(expected), i)
|
||||
|
||||
iter = iavlStore.ReverseSubspaceIterator([]byte{byte(55), byte(255), byte(255)})
|
||||
iter = sdk.KVStoreReversePrefixIterator(iavlStore, []byte{byte(55), byte(255), byte(255)})
|
||||
expected2 := [][]byte{
|
||||
[]byte{byte(55), byte(255), byte(255), byte(255)},
|
||||
[]byte{byte(55), byte(255), byte(255), byte(1)},
|
||||
@ -242,7 +242,7 @@ func TestIAVLReverseSubspaceIterator(t *testing.T) {
|
||||
}
|
||||
assert.Equal(t, len(expected), i)
|
||||
|
||||
iter = iavlStore.ReverseSubspaceIterator([]byte{byte(255), byte(255)})
|
||||
iter = sdk.KVStoreReversePrefixIterator(iavlStore, []byte{byte(255), byte(255)})
|
||||
expected2 = [][]byte{
|
||||
[]byte{byte(255), byte(255), byte(255)},
|
||||
[]byte{byte(255), byte(255), byte(1)},
|
||||
|
||||
@ -183,6 +183,11 @@ func (rs *rootMultiStore) GetKVStore(key StoreKey) KVStore {
|
||||
return rs.stores[key].(KVStore)
|
||||
}
|
||||
|
||||
// Implements MultiStore.
|
||||
func (rs *rootMultiStore) GetKVStoreWithGas(meter sdk.GasMeter, key StoreKey) KVStore {
|
||||
return NewGasKVStore(meter, rs.GetKVStore(key))
|
||||
}
|
||||
|
||||
// getStoreByName will first convert the original name to
|
||||
// a special key, before looking up the CommitStore.
|
||||
// This is not exposed to the extensions (which will need the
|
||||
|
||||
104
tests/gobash.go
104
tests/gobash.go
@ -1,51 +1,91 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
cmn "github.com/tendermint/tmlibs/common"
|
||||
)
|
||||
|
||||
func getCmd(t *testing.T, command string) *exec.Cmd {
|
||||
// Execute the command, return stdout, logging stdout/err to t.
|
||||
func ExecuteT(t *testing.T, cmd string) (out string) {
|
||||
t.Log("Running", cmn.Cyan(cmd))
|
||||
|
||||
//split command into command and args
|
||||
split := strings.Split(command, " ")
|
||||
// Split cmd to name and args.
|
||||
split := strings.Split(cmd, " ")
|
||||
require.True(t, len(split) > 0, "no command provided")
|
||||
|
||||
var cmd *exec.Cmd
|
||||
if len(split) == 1 {
|
||||
cmd = exec.Command(split[0])
|
||||
} else {
|
||||
cmd = exec.Command(split[0], split[1:]...)
|
||||
name, args := split[0], []string(nil)
|
||||
if len(split) > 1 {
|
||||
args = split[1:]
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
||||
// Execute the command, return standard output and error, try a few times if requested
|
||||
func ExecuteT(t *testing.T, command string) (out string) {
|
||||
cmd := getCmd(t, command)
|
||||
bz, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
// Start process and wait.
|
||||
proc, err := StartProcess("", name, args, nil, nil)
|
||||
require.NoError(t, err)
|
||||
proc.Wait()
|
||||
|
||||
// Get the output.
|
||||
outbz := proc.StdoutBuffer.Bytes()
|
||||
errbz := proc.StderrBuffer.Bytes()
|
||||
|
||||
// Log output.
|
||||
if len(outbz) > 0 {
|
||||
t.Log("Stdout:", cmn.Green(string(outbz)))
|
||||
}
|
||||
require.NoError(t, err, string(bz))
|
||||
out = strings.Trim(string(bz), "\n") //trim any new lines
|
||||
time.Sleep(time.Second)
|
||||
if len(errbz) > 0 {
|
||||
t.Log("Stderr:", cmn.Red(string(errbz)))
|
||||
}
|
||||
|
||||
// Collect STDOUT output.
|
||||
out = strings.Trim(string(outbz), "\n") //trim any new lines
|
||||
return out
|
||||
}
|
||||
|
||||
// Asynchronously execute the command, return standard output and error
|
||||
func GoExecuteT(t *testing.T, command string) (cmd *exec.Cmd, pipeIn io.WriteCloser, pipeOut io.ReadCloser) {
|
||||
cmd = getCmd(t, command)
|
||||
pipeIn, err := cmd.StdinPipe()
|
||||
// Execute the command, launch goroutines to log stdout/err to t.
|
||||
// Caller should wait for .Wait() or .Stop() to terminate.
|
||||
func GoExecuteT(t *testing.T, cmd string) (proc *Process) {
|
||||
t.Log("Running", cmn.Cyan(cmd))
|
||||
|
||||
// Split cmd to name and args.
|
||||
split := strings.Split(cmd, " ")
|
||||
require.True(t, len(split) > 0, "no command provided")
|
||||
name, args := split[0], []string(nil)
|
||||
if len(split) > 1 {
|
||||
args = split[1:]
|
||||
}
|
||||
|
||||
// Start process.
|
||||
proc, err := StartProcess("", name, args, nil, nil)
|
||||
require.NoError(t, err)
|
||||
pipeOut, err = cmd.StdoutPipe()
|
||||
require.NoError(t, err)
|
||||
cmd.Start()
|
||||
time.Sleep(time.Second)
|
||||
return cmd, pipeIn, pipeOut
|
||||
|
||||
// Run goroutines to log stdout.
|
||||
go func() {
|
||||
buf := make([]byte, 10240) // TODO Document the effects.
|
||||
for {
|
||||
n, err := proc.StdoutBuffer.Read(buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if n > 0 {
|
||||
t.Log("Stdout:", cmn.Green(string(buf[:n])))
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Run goroutines to log stderr.
|
||||
go func() {
|
||||
buf := make([]byte, 10240) // TODO Document the effects.
|
||||
for {
|
||||
n, err := proc.StderrBuffer.Read(buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if n > 0 {
|
||||
t.Log("Stderr:", cmn.Red(string(buf[:n])))
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return proc
|
||||
}
|
||||
|
||||
110
tests/process.go
Normal file
110
tests/process.go
Normal file
@ -0,0 +1,110 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"time"
|
||||
)
|
||||
|
||||
// execution process
|
||||
type Process struct {
|
||||
ExecPath string
|
||||
Args []string
|
||||
Pid int
|
||||
StartTime time.Time
|
||||
EndTime time.Time
|
||||
Cmd *exec.Cmd `json:"-"`
|
||||
ExitState *os.ProcessState `json:"-"`
|
||||
WaitCh chan struct{} `json:"-"`
|
||||
StdinPipe io.WriteCloser `json:"-"`
|
||||
StdoutBuffer *bytes.Buffer `json:"-"`
|
||||
StderrBuffer *bytes.Buffer `json:"-"`
|
||||
}
|
||||
|
||||
// dir: The working directory. If "", os.Getwd() is used.
|
||||
// name: Command name
|
||||
// args: Args to command. (should not include name)
|
||||
// outFile, errFile: If not nil, will use, otherwise new Buffers will be
|
||||
// allocated. Either way, Process.Cmd.StdoutPipe and Process.Cmd.StderrPipe will be nil
|
||||
// respectively.
|
||||
func StartProcess(dir string, name string, args []string, outFile, errFile io.WriteCloser) (*Process, error) {
|
||||
var cmd = exec.Command(name, args...) // is not yet started.
|
||||
// cmd dir
|
||||
if dir == "" {
|
||||
pwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
cmd.Dir = pwd
|
||||
} else {
|
||||
cmd.Dir = dir
|
||||
}
|
||||
// cmd stdin
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// cmd stdout, stderr
|
||||
var outBuffer, errBuffer *bytes.Buffer
|
||||
if outFile != nil {
|
||||
cmd.Stdout = outFile
|
||||
} else {
|
||||
outBuffer = bytes.NewBuffer(nil)
|
||||
cmd.Stdout = outBuffer
|
||||
}
|
||||
if errFile != nil {
|
||||
cmd.Stderr = errFile
|
||||
} else {
|
||||
errBuffer = bytes.NewBuffer(nil)
|
||||
cmd.Stderr = errBuffer
|
||||
}
|
||||
// cmd start
|
||||
if err := cmd.Start(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
proc := &Process{
|
||||
ExecPath: name,
|
||||
Args: args,
|
||||
Pid: cmd.Process.Pid,
|
||||
StartTime: time.Now(),
|
||||
Cmd: cmd,
|
||||
ExitState: nil,
|
||||
WaitCh: make(chan struct{}),
|
||||
StdinPipe: stdin,
|
||||
}
|
||||
if outBuffer != nil {
|
||||
proc.StdoutBuffer = outBuffer
|
||||
}
|
||||
if errBuffer != nil {
|
||||
proc.StderrBuffer = errBuffer
|
||||
}
|
||||
go func() {
|
||||
err := proc.Cmd.Wait()
|
||||
if err != nil {
|
||||
// fmt.Printf("Process exit: %v\n", err)
|
||||
if exitError, ok := err.(*exec.ExitError); ok {
|
||||
proc.ExitState = exitError.ProcessState
|
||||
}
|
||||
}
|
||||
proc.ExitState = proc.Cmd.ProcessState
|
||||
proc.EndTime = time.Now() // TODO make this goroutine-safe
|
||||
close(proc.WaitCh)
|
||||
}()
|
||||
return proc, nil
|
||||
}
|
||||
|
||||
// stop the process
|
||||
func (proc *Process) Stop(kill bool) error {
|
||||
if kill {
|
||||
// fmt.Printf("Killing process %v\n", proc.Cmd.Process)
|
||||
return proc.Cmd.Process.Kill()
|
||||
}
|
||||
return proc.Cmd.Process.Signal(os.Interrupt)
|
||||
}
|
||||
|
||||
// wait for the process
|
||||
func (proc *Process) Wait() {
|
||||
<-proc.WaitCh
|
||||
}
|
||||
@ -9,7 +9,6 @@ import (
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
//"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@ -239,7 +238,9 @@ func StartNodeServerForTest(t *testing.T, home string) *exec.Cmd {
|
||||
// expects TestInitBaseCoin to have been run
|
||||
func StartLCDServerForTest(t *testing.T, home, chainID string) (cmd *exec.Cmd, port string) {
|
||||
cmdName := whereIsBasecli()
|
||||
port = strings.Split(server.FreeTCPAddr(t), ":")[2]
|
||||
var err error
|
||||
_, port, err = server.FreeTCPAddr()
|
||||
require.NoError(t, err)
|
||||
cmdArgs := []string{
|
||||
"rest-server",
|
||||
"--home",
|
||||
@ -252,7 +253,7 @@ func StartLCDServerForTest(t *testing.T, home, chainID string) (cmd *exec.Cmd, p
|
||||
cmd = exec.Command(cmdName, cmdArgs...)
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
err := cmd.Start()
|
||||
err = cmd.Start()
|
||||
require.Nil(t, err)
|
||||
time.Sleep(time.Second * 2) // TODO: LOL
|
||||
return cmd, port
|
||||
|
||||
@ -11,16 +11,22 @@ import (
|
||||
rpcclient "github.com/tendermint/tendermint/rpc/lib/client"
|
||||
)
|
||||
|
||||
// TODO: these functions just print to Stdout.
|
||||
// consider using the logger.
|
||||
|
||||
// Uses localhost
|
||||
func WaitForHeight(height int64, port string) {
|
||||
for {
|
||||
var resultBlock ctypes.ResultBlock
|
||||
|
||||
url := fmt.Sprintf("http://localhost:%v%v", port, "/blocks/latest")
|
||||
res, err := http.Get(url)
|
||||
url := fmt.Sprintf("http://localhost:%v/blocks/latest", port)
|
||||
|
||||
// get url, try a few times
|
||||
var res *http.Response
|
||||
var err error
|
||||
for i := 0; i < 5; i++ {
|
||||
res, err = http.Get(url)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
@ -31,6 +37,7 @@ func WaitForHeight(height int64, port string) {
|
||||
}
|
||||
res.Body.Close()
|
||||
|
||||
var resultBlock ctypes.ResultBlock
|
||||
err = cdc.UnmarshalJSON([]byte(body), &resultBlock)
|
||||
if err != nil {
|
||||
fmt.Println("RES", res)
|
||||
@ -45,45 +52,35 @@ func WaitForHeight(height int64, port string) {
|
||||
}
|
||||
}
|
||||
|
||||
// wait for 2 blocks.
|
||||
// uses localhost
|
||||
// wait for tendermint to start
|
||||
func WaitForStart(port string) {
|
||||
waitHeight := int64(2)
|
||||
for {
|
||||
var err error
|
||||
for i := 0; i < 5; i++ {
|
||||
time.Sleep(time.Second)
|
||||
|
||||
url := fmt.Sprintf("http://localhost:%v%v", port, "/blocks/latest")
|
||||
res, err := http.Get(url)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
url := fmt.Sprintf("http://localhost:%v/blocks/latest", port)
|
||||
|
||||
// get url, try a few times
|
||||
var res *http.Response
|
||||
res, err = http.Get(url)
|
||||
if err == nil || res == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// waiting for server to start ...
|
||||
if res.StatusCode != http.StatusOK {
|
||||
res.Body.Close()
|
||||
continue
|
||||
}
|
||||
|
||||
body, err := ioutil.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
res.Body.Close()
|
||||
|
||||
resultBlock := new(ctypes.ResultBlock)
|
||||
err = cdc.UnmarshalJSON([]byte(body), &resultBlock)
|
||||
if err != nil {
|
||||
fmt.Println("RES", res)
|
||||
fmt.Println("BODY", string(body))
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if resultBlock.Block.Height >= waitHeight {
|
||||
return
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: these functions just print to Stdout.
|
||||
// consider using the logger.
|
||||
|
||||
// Wait for the RPC server to respond to /status
|
||||
func WaitForRPC(laddr string) {
|
||||
fmt.Println("LADDR", laddr)
|
||||
|
||||
@ -10,3 +10,6 @@ type BeginBlocker func(ctx Context, req abci.RequestBeginBlock) abci.ResponseBeg
|
||||
|
||||
// run code after the transactions in a block and return updates to the validator set
|
||||
type EndBlocker func(ctx Context, req abci.RequestEndBlock) abci.ResponseEndBlock
|
||||
|
||||
// respond to p2p filtering queries from Tendermint
|
||||
type PeerFilter func(info string) abci.ResponseQuery
|
||||
|
||||
113
types/account.go
113
types/account.go
@ -3,16 +3,46 @@ package types
|
||||
import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
crypto "github.com/tendermint/go-crypto"
|
||||
"github.com/tendermint/tmlibs/bech32"
|
||||
cmn "github.com/tendermint/tmlibs/common"
|
||||
)
|
||||
|
||||
// Address in go-crypto style
|
||||
//Address is a go crypto-style Address
|
||||
type Address = cmn.HexBytes
|
||||
|
||||
// Bech32 prefixes
|
||||
const (
|
||||
Bech32PrefixAccAddr = "cosmosaccaddr"
|
||||
Bech32PrefixAccPub = "cosmosaccpub"
|
||||
Bech32PrefixValAddr = "cosmosvaladdr"
|
||||
Bech32PrefixValPub = "cosmosvalpub"
|
||||
)
|
||||
|
||||
// Bech32ifyAcc takes Address and returns the bech32 encoded string
|
||||
func Bech32ifyAcc(addr Address) (string, error) {
|
||||
return bech32.ConvertAndEncode(Bech32PrefixAccAddr, addr.Bytes())
|
||||
}
|
||||
|
||||
// Bech32ifyAccPub takes AccountPubKey and returns the bech32 encoded string
|
||||
func Bech32ifyAccPub(pub crypto.PubKey) (string, error) {
|
||||
return bech32.ConvertAndEncode(Bech32PrefixAccPub, pub.Bytes())
|
||||
}
|
||||
|
||||
// Bech32ifyVal returns the bech32 encoded string for a validator address
|
||||
func bech32ifyVal(addr Address) (string, error) {
|
||||
return bech32.ConvertAndEncode(Bech32PrefixValAddr, addr.Bytes())
|
||||
}
|
||||
|
||||
// Bech32ifyValPub returns the bech32 encoded string for a validator pubkey
|
||||
func Bech32ifyValPub(pub crypto.PubKey) (string, error) {
|
||||
return bech32.ConvertAndEncode(Bech32PrefixValPub, pub.Bytes())
|
||||
}
|
||||
|
||||
// create an Address from a string
|
||||
func GetAddress(address string) (addr Address, err error) {
|
||||
func GetAccAddressHex(address string) (addr Address, err error) {
|
||||
if len(address) == 0 {
|
||||
return addr, errors.New("must use provide address")
|
||||
}
|
||||
@ -23,30 +53,63 @@ func GetAddress(address string) (addr Address, err error) {
|
||||
return Address(bz), nil
|
||||
}
|
||||
|
||||
// Account is a standard account using a sequence number for replay protection
|
||||
// and a pubkey for authentication.
|
||||
type Account interface {
|
||||
GetAddress() Address
|
||||
SetAddress(Address) error // errors if already set.
|
||||
|
||||
GetPubKey() crypto.PubKey // can return nil.
|
||||
SetPubKey(crypto.PubKey) error
|
||||
|
||||
GetSequence() int64
|
||||
SetSequence(int64) error
|
||||
|
||||
GetCoins() Coins
|
||||
SetCoins(Coins) error
|
||||
// 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
|
||||
}
|
||||
|
||||
// AccountMapper stores and retrieves accounts from stores
|
||||
// retrieved from the context.
|
||||
type AccountMapper interface {
|
||||
NewAccountWithAddress(ctx Context, addr Address) Account
|
||||
GetAccount(ctx Context, addr Address) Account
|
||||
SetAccount(ctx Context, acc Account)
|
||||
IterateAccounts(ctx Context, process func(Account) (stop bool))
|
||||
// create an Address from a hex string
|
||||
func GetValAddressHex(address string) (addr Address, err error) {
|
||||
if len(address) == 0 {
|
||||
return addr, errors.New("must use provide address")
|
||||
}
|
||||
bz, err := hex.DecodeString(address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return Address(bz), nil
|
||||
}
|
||||
|
||||
// AccountDecoder unmarshals account bytes
|
||||
type AccountDecoder func(accountBytes []byte) (Account, error)
|
||||
// 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
|
||||
}
|
||||
|
||||
//Decode a validator publickey into a public key
|
||||
func GetValPubKeyBech32(pubkey string) (pk crypto.PubKey, err error) {
|
||||
bz, err := getFromBech32(pubkey, Bech32PrefixValPub)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pk, err = crypto.PubKeyFromBytes(bz)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return pk, nil
|
||||
}
|
||||
|
||||
func getFromBech32(bech32str, prefix string) ([]byte, error) {
|
||||
if len(bech32str) == 0 {
|
||||
return nil, errors.New("must provide non-empty string")
|
||||
}
|
||||
hrp, bz, err := bech32.DecodeAndConvert(bech32str)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if hrp != prefix {
|
||||
return nil, fmt.Errorf("Invalid bech32 prefix. Expected %s, Got %s", prefix, hrp)
|
||||
}
|
||||
|
||||
return bz, nil
|
||||
}
|
||||
|
||||
@ -31,6 +31,7 @@ type Context struct {
|
||||
|
||||
// create a new context
|
||||
func NewContext(ms MultiStore, header abci.Header, isCheckTx bool, txBytes []byte, logger log.Logger) Context {
|
||||
|
||||
c := Context{
|
||||
Context: context.Background(),
|
||||
pst: newThePast(),
|
||||
@ -43,6 +44,8 @@ func NewContext(ms MultiStore, header abci.Header, isCheckTx bool, txBytes []byt
|
||||
c = c.WithIsCheckTx(isCheckTx)
|
||||
c = c.WithTxBytes(txBytes)
|
||||
c = c.WithLogger(logger)
|
||||
c = c.WithSigningValidators(nil)
|
||||
c = c.WithGasMeter(NewInfiniteGasMeter())
|
||||
return c
|
||||
}
|
||||
|
||||
@ -68,7 +71,7 @@ func (c Context) Value(key interface{}) interface{} {
|
||||
|
||||
// KVStore fetches a KVStore from the MultiStore.
|
||||
func (c Context) KVStore(key StoreKey) KVStore {
|
||||
return c.multiStore().GetKVStore(key)
|
||||
return c.multiStore().GetKVStoreWithGas(c.GasMeter(), key)
|
||||
}
|
||||
|
||||
//----------------------------------------
|
||||
@ -127,6 +130,8 @@ const (
|
||||
contextKeyIsCheckTx
|
||||
contextKeyTxBytes
|
||||
contextKeyLogger
|
||||
contextKeySigningValidators
|
||||
contextKeyGasMeter
|
||||
)
|
||||
|
||||
// NOTE: Do not expose MultiStore.
|
||||
@ -155,6 +160,12 @@ func (c Context) TxBytes() []byte {
|
||||
func (c Context) Logger() log.Logger {
|
||||
return c.Value(contextKeyLogger).(log.Logger)
|
||||
}
|
||||
func (c Context) SigningValidators() []abci.SigningValidator {
|
||||
return c.Value(contextKeySigningValidators).([]abci.SigningValidator)
|
||||
}
|
||||
func (c Context) GasMeter() GasMeter {
|
||||
return c.Value(contextKeyGasMeter).(GasMeter)
|
||||
}
|
||||
func (c Context) WithMultiStore(ms MultiStore) Context {
|
||||
return c.withValue(contextKeyMultiStore, ms)
|
||||
}
|
||||
@ -177,6 +188,12 @@ func (c Context) WithTxBytes(txBytes []byte) Context {
|
||||
func (c Context) WithLogger(logger log.Logger) Context {
|
||||
return c.withValue(contextKeyLogger, logger)
|
||||
}
|
||||
func (c Context) WithSigningValidators(SigningValidators []abci.SigningValidator) Context {
|
||||
return c.withValue(contextKeySigningValidators, SigningValidators)
|
||||
}
|
||||
func (c Context) WithGasMeter(meter GasMeter) Context {
|
||||
return c.withValue(contextKeyGasMeter, meter)
|
||||
}
|
||||
|
||||
// Cache the multistore and return a new cached context. The cached context is
|
||||
// written to the context when writeCache is called.
|
||||
|
||||
@ -52,6 +52,7 @@ const (
|
||||
CodeUnknownAddress CodeType = 9
|
||||
CodeInsufficientCoins CodeType = 10
|
||||
CodeInvalidCoins CodeType = 11
|
||||
CodeOutOfGas CodeType = 12
|
||||
|
||||
// CodespaceRoot is a codespace for error codes in this file only.
|
||||
// Notice that 0 is an "unset" codespace, which can be overridden with
|
||||
@ -88,6 +89,8 @@ func CodeToDefaultMsg(code CodeType) string {
|
||||
return "Insufficient coins"
|
||||
case CodeInvalidCoins:
|
||||
return "Invalid coins"
|
||||
case CodeOutOfGas:
|
||||
return "Out of gas"
|
||||
default:
|
||||
return fmt.Sprintf("Unknown code %d", code)
|
||||
}
|
||||
@ -131,6 +134,9 @@ func ErrInsufficientCoins(msg string) Error {
|
||||
func ErrInvalidCoins(msg string) Error {
|
||||
return newErrorWithRootCodespace(CodeInvalidCoins, msg)
|
||||
}
|
||||
func ErrOutOfGas(msg string) Error {
|
||||
return newErrorWithRootCodespace(CodeOutOfGas, msg)
|
||||
}
|
||||
|
||||
//----------------------------------------
|
||||
// Error & sdkError
|
||||
|
||||
58
types/gas.go
Normal file
58
types/gas.go
Normal file
@ -0,0 +1,58 @@
|
||||
package types
|
||||
|
||||
import ()
|
||||
|
||||
// Gas measured by the SDK
|
||||
type Gas = int64
|
||||
|
||||
// Error thrown when out of gas
|
||||
type ErrorOutOfGas struct {
|
||||
Descriptor string
|
||||
}
|
||||
|
||||
// GasMeter interface to track gas consumption
|
||||
type GasMeter interface {
|
||||
GasConsumed() Gas
|
||||
ConsumeGas(amount Gas, descriptor string)
|
||||
}
|
||||
|
||||
type basicGasMeter struct {
|
||||
limit Gas
|
||||
consumed Gas
|
||||
}
|
||||
|
||||
func NewGasMeter(limit Gas) GasMeter {
|
||||
return &basicGasMeter{
|
||||
limit: limit,
|
||||
consumed: 0,
|
||||
}
|
||||
}
|
||||
|
||||
func (g *basicGasMeter) GasConsumed() Gas {
|
||||
return g.consumed
|
||||
}
|
||||
|
||||
func (g *basicGasMeter) ConsumeGas(amount Gas, descriptor string) {
|
||||
g.consumed += amount
|
||||
if g.consumed > g.limit {
|
||||
panic(ErrorOutOfGas{descriptor})
|
||||
}
|
||||
}
|
||||
|
||||
type infiniteGasMeter struct {
|
||||
consumed Gas
|
||||
}
|
||||
|
||||
func NewInfiniteGasMeter() GasMeter {
|
||||
return &infiniteGasMeter{
|
||||
consumed: 0,
|
||||
}
|
||||
}
|
||||
|
||||
func (g *infiniteGasMeter) GasConsumed() Gas {
|
||||
return g.consumed
|
||||
}
|
||||
|
||||
func (g *infiniteGasMeter) ConsumeGas(amount Gas, descriptor string) {
|
||||
g.consumed += amount
|
||||
}
|
||||
@ -3,8 +3,5 @@ package types
|
||||
// core function variable which application runs for transactions
|
||||
type Handler func(ctx Context, msg Msg) Result
|
||||
|
||||
// core function variable which application runs to handle fees
|
||||
type FeeHandler func(ctx Context, tx Tx, fee Coins)
|
||||
|
||||
// If newCtx.IsZero(), ctx is used instead.
|
||||
type AnteHandler func(ctx Context, tx Tx) (newCtx Context, result Result, abort bool)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user