Merge branch 'develop' into cwgoes/misc-fixes
This commit is contained in:
commit
49adacab53
|
@ -38,6 +38,7 @@ jobs:
|
|||
command: |
|
||||
export PATH="$GOBIN:$PATH"
|
||||
make install
|
||||
make install_examples
|
||||
- persist_to_workspace:
|
||||
root: /tmp/workspace
|
||||
paths:
|
||||
|
|
265
CHANGELOG.md
265
CHANGELOG.md
|
@ -1,8 +1,48 @@
|
|||
# Changelog
|
||||
|
||||
## 0.18.1
|
||||
|
||||
BREAKING CHANGES
|
||||
|
||||
* [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
|
||||
* Switch to bech32cosmos on all human readable inputs and outputs
|
||||
|
||||
BUG FIXES
|
||||
|
||||
* auto-sequencing transactions correctly
|
||||
* query sequence via account store
|
||||
* fixed duplicate pub_key in stake.Validator
|
||||
|
||||
## 0.18.0
|
||||
|
||||
*TBD*
|
||||
_TBD_
|
||||
|
||||
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
|
||||
|
||||
FEATURES
|
||||
|
||||
|
@ -12,10 +52,23 @@ FEATURES
|
|||
* 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
|
||||
|
||||
* Auto-sequencing now works correctly
|
||||
* [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!
|
||||
* [docs] Downgraded Swagger to v2 for downstream compatibility
|
||||
|
||||
## 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)
|
||||
|
||||
|
@ -28,6 +81,7 @@ 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
|
||||
|
||||
|
@ -65,7 +119,6 @@ BREAKING CHANGES
|
|||
* gaiad init now requires use of `--name` flag
|
||||
* Removed Get from Msg interface
|
||||
* types/rational now extends big.Rat
|
||||
* Queries against the store must be prefixed with the path "/store"
|
||||
|
||||
FEATURES:
|
||||
|
||||
|
@ -82,6 +135,7 @@ FEATURES:
|
|||
* 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)
|
||||
|
@ -111,6 +165,7 @@ FEATURES:
|
|||
* Add FeeHandler to ante handler
|
||||
|
||||
BUG FIXES
|
||||
|
||||
* MountStoreWithDB without providing a custom store works.
|
||||
|
||||
## 0.14.1 (April 9, 2018)
|
||||
|
@ -217,6 +272,7 @@ IMPROVEMENTS
|
|||
* [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
|
||||
|
@ -315,29 +371,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
|
||||
|
||||
* 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
|
||||
* 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,
|
||||
* 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
|
||||
* 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)
|
||||
|
||||
|
@ -345,111 +402,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).
|
||||
* 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:
|
||||
* Consolidate genesis files so the Basecoin genesis is an object under `app_options` in Tendermint genesis. For instance:
|
||||
|
||||
```
|
||||
{
|
||||
|
@ -493,48 +557,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,
|
||||
* 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
|
||||
* 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
|
||||
|
|
|
@ -13,6 +13,12 @@
|
|||
packages = ["btcec"]
|
||||
revision = "1432d294a5b055c297457c25434efbf13384cc46"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/cosmos/bech32cosmos"
|
||||
packages = ["go"]
|
||||
revision = "efca97cd8c0852c44d96dfdcc70565c306eddff0"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/davecgh/go-spew"
|
||||
packages = ["spew"]
|
||||
|
@ -457,6 +463,6 @@
|
|||
[solve-meta]
|
||||
analyzer-name = "dep"
|
||||
analyzer-version = 1
|
||||
inputs-digest = "7540d2ecdb5d7d5084ab4e6132e929bbd501bd6add3006d8f08a6b2c127e0c7d"
|
||||
inputs-digest = "f0c6224dc5f30c1a7dea716d619665831ea0932b0eb9afc6ac897dbc459134fa"
|
||||
solver-name = "gps-cdcl"
|
||||
solver-version = 1
|
||||
|
|
|
@ -85,6 +85,11 @@
|
|||
name = "google.golang.org/genproto"
|
||||
revision = "7fd901a49ba6a7f87732eb344f6e3c5b19d1b200"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/cosmos/bech32cosmos"
|
||||
branch = "master"
|
||||
|
||||
|
||||
[prune]
|
||||
go-tests = true
|
||||
unused-packages = true
|
||||
|
|
27
Makefile
27
Makefile
|
@ -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
|
||||
|
|
|
@ -15,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.
|
||||
|
@ -125,7 +126,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")
|
||||
|
|
|
@ -11,13 +11,14 @@ import (
|
|||
"github.com/stretchr/testify/require"
|
||||
|
||||
abci "github.com/tendermint/abci/types"
|
||||
"github.com/tendermint/go-crypto"
|
||||
crypto "github.com/tendermint/go-crypto"
|
||||
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 {
|
||||
|
@ -451,7 +452,7 @@ 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) GetSignatures() []auth.StdSignature { return nil }
|
||||
|
||||
func TestValidatorChange(t *testing.T) {
|
||||
|
||||
|
|
|
@ -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,7 +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("/store/%s/key", storeName)
|
||||
path := fmt.Sprintf("/store/%s/%s", storeName, endPath)
|
||||
node, err := ctx.GetNode()
|
||||
if err != nil {
|
||||
return res, err
|
||||
|
@ -109,11 +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: sdk.NewStdFee(10000, sdk.Coin{}), // TODO run simulate to estimate gas?
|
||||
Fee: auth.NewStdFee(10000, 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,7 +3,7 @@ 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
|
||||
|
@ -15,7 +15,7 @@ type CoreContext struct {
|
|||
FromAddressName string
|
||||
Sequence int64
|
||||
Client rpcclient.Client
|
||||
Decoder sdk.AccountDecoder
|
||||
Decoder auth.AccountDecoder
|
||||
AccountStore string
|
||||
}
|
||||
|
||||
|
@ -63,7 +63,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
|
||||
}
|
||||
|
|
|
@ -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,20 @@
|
|||
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
|
||||
|
@ -48,15 +49,15 @@ 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"`
|
||||
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,8 +73,8 @@ 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")
|
||||
if err != nil {
|
||||
|
@ -87,9 +88,9 @@ 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")
|
||||
|
@ -99,3 +100,15 @@ func printInfos(infos []keys.Info) {
|
|||
fmt.Println(string(out))
|
||||
}
|
||||
}
|
||||
|
||||
func printKeyOutput(ko KeyOutput) {
|
||||
bechAccount, err := sdk.Bech32CosmosifyAcc(ko.Address)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
bechPubKey, err := sdk.Bech32CosmosifyAccPub(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,6 +17,7 @@ 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"
|
||||
|
@ -31,16 +33,21 @@ import (
|
|||
|
||||
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"
|
||||
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"
|
||||
|
@ -91,10 +98,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 +115,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 +226,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 +316,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
|
||||
|
||||
|
@ -320,26 +388,18 @@ func startTMAndLCD() (*nm.Node, net.Listener, error) {
|
|||
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,21 +407,53 @@ 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
|
||||
|
@ -375,7 +467,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 +506,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 +528,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 +582,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 (
|
||||
|
@ -83,5 +84,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
|
||||
}
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -40,7 +40,8 @@ type GaiaApp struct {
|
|||
keyStake *sdk.KVStoreKey
|
||||
|
||||
// Manage getting and setting accounts
|
||||
accountMapper sdk.AccountMapper
|
||||
accountMapper auth.AccountMapper
|
||||
feeCollectionKeeper auth.FeeCollectionKeeper
|
||||
coinKeeper bank.Keeper
|
||||
ibcMapper ibc.Mapper
|
||||
stakeKeeper stake.Keeper
|
||||
|
@ -81,7 +82,7 @@ func NewGaiaApp(logger log.Logger, db dbm.DB) *GaiaApp {
|
|||
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.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper))
|
||||
err := app.LoadLatestVersion(app.keyMain)
|
||||
if err != nil {
|
||||
cmn.Exit(err.Error())
|
||||
|
@ -131,7 +132,7 @@ func (app *GaiaApp) ExportAppStateJSON() (appState json.RawMessage, err error) {
|
|||
|
||||
// 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
|
||||
|
|
|
@ -38,7 +38,7 @@ 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}},
|
||||
100000,
|
||||
}
|
||||
|
@ -105,7 +105,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)
|
||||
|
@ -147,7 +147,7 @@ func setGenesisAccounts(gapp *GaiaApp, accs ...*auth.BaseAccount) error {
|
|||
|
||||
genesisState := GenesisState{
|
||||
Accounts: genaccs,
|
||||
StakeData: stake.GetDefaultGenesisState(),
|
||||
StakeData: stake.DefaultGenesisState(),
|
||||
}
|
||||
|
||||
stateBytes, err := json.MarshalIndent(genesisState, "", "\t")
|
||||
|
@ -405,9 +405,15 @@ func TestStakeMsgs(t *testing.T) {
|
|||
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()))
|
||||
|
||||
// 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 Candidacy
|
||||
|
||||
|
@ -417,9 +423,9 @@ func TestStakeMsgs(t *testing.T) {
|
|||
)
|
||||
SignDeliver(t, gapp, editCandidacyMsg, []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 +434,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 +449,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 +463,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(),
|
||||
|
@ -74,7 +74,7 @@ func GaiaAppInit() server.AppInit {
|
|||
FlagsAppGenState: fsAppGenState,
|
||||
FlagsAppGenTx: fsAppGenTx,
|
||||
AppGenTx: GaiaAppGenTx,
|
||||
AppGenState: GaiaAppGenState,
|
||||
AppGenState: GaiaAppGenStateJSON,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -85,22 +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{
|
||||
|
@ -114,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,
|
||||
|
@ -130,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")
|
||||
|
@ -138,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))
|
||||
|
@ -158,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) {
|
||||
|
@ -38,24 +40,32 @@ func TestGaiaCLISend(t *testing.T) {
|
|||
fooAddr, _ := executeGetAddrPK(t, "gaiacli keys show foo --output=json")
|
||||
barAddr, _ := executeGetAddrPK(t, "gaiacli keys show bar --output=json")
|
||||
|
||||
fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooAddr, flags))
|
||||
fooBech, err := sdk.Bech32CosmosifyAcc(fooAddr)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
barBech, err := sdk.Bech32CosmosifyAcc(barAddr)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooBech, 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
|
||||
|
||||
barAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", barAddr, flags))
|
||||
barAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", barBech, 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", fooBech, 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
|
||||
|
||||
barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", barAddr, flags))
|
||||
barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", barBech, 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", fooBech, flags))
|
||||
assert.Equal(t, int64(30), fooAcc.GetCoins().AmountOf("steak"))
|
||||
}
|
||||
|
||||
|
@ -77,21 +87,32 @@ func TestGaiaCLIDeclareCandidacy(t *testing.T) {
|
|||
defer cmd.Process.Kill()
|
||||
|
||||
fooAddr, _ := executeGetAddrPK(t, "gaiacli keys show foo --output=json")
|
||||
barAddr, barPubKey := executeGetAddrPK(t, "gaiacli keys show bar --output=json")
|
||||
barAddr, _ := executeGetAddrPK(t, "gaiacli keys show bar --output=json")
|
||||
|
||||
executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%v --name=foo", flags, barAddr), pass)
|
||||
fooBech, err := sdk.Bech32CosmosifyAcc(fooAddr)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
barBech, err := sdk.Bech32CosmosifyAcc(barAddr)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
valPrivkey := crypto.GenPrivKeyEd25519()
|
||||
valAddr := sdk.Address((valPrivkey.PubKey().Address()))
|
||||
bechVal, err := sdk.Bech32CosmosifyVal(valAddr)
|
||||
|
||||
executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%v --name=foo", flags, barBech), pass)
|
||||
time.Sleep(time.Second * 3) // waiting for some blocks to pass
|
||||
|
||||
fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooAddr, flags))
|
||||
fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooBech, 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", barBech, flags))
|
||||
assert.Equal(t, int64(10), barAcc.GetCoins().AmountOf("steak"))
|
||||
|
||||
// declare candidacy
|
||||
declStr := fmt.Sprintf("gaiacli declare-candidacy %v", flags)
|
||||
declStr := fmt.Sprintf("gaiacli create-validator %v", flags)
|
||||
declStr += fmt.Sprintf(" --name=%v", "bar")
|
||||
declStr += fmt.Sprintf(" --address-candidate=%v", barAddr)
|
||||
declStr += fmt.Sprintf(" --pubkey=%v", barPubKey)
|
||||
declStr += fmt.Sprintf(" --validator-address=%v", bechVal)
|
||||
declStr += fmt.Sprintf(" --amount=%v", "3steak")
|
||||
declStr += fmt.Sprintf(" --moniker=%v", "bar-vally")
|
||||
fmt.Printf("debug declStr: %v\n", declStr)
|
||||
|
@ -100,8 +121,8 @@ func TestGaiaCLIDeclareCandidacy(t *testing.T) {
|
|||
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())
|
||||
assert.Equal(t, candidate.Owner.String(), barAddr)
|
||||
assert.Equal(t, int64(3), candidate.PoolShares)
|
||||
|
||||
// TODO timeout issues if not connected to the internet
|
||||
// unbond a single share
|
||||
|
@ -117,7 +138,7 @@ func TestGaiaCLIDeclareCandidacy(t *testing.T) {
|
|||
//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())
|
||||
//assert.Equal(t, int64(2), candidate.BondedShares.Evaluate())
|
||||
}
|
||||
|
||||
func executeWrite(t *testing.T, cmdStr string, writes ...string) {
|
||||
|
@ -125,6 +146,9 @@ func executeWrite(t *testing.T, cmdStr string, writes ...string) {
|
|||
|
||||
for _, write := range writes {
|
||||
_, err := wc.Write([]byte(write + "\n"))
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
require.NoError(t, err)
|
||||
}
|
||||
fmt.Printf("debug waiting cmdStr: %v\n", cmdStr)
|
||||
|
@ -159,7 +183,7 @@ 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)
|
||||
|
@ -180,9 +204,9 @@ func executeGetAccount(t *testing.T, cmdStr string) auth.BaseAccount {
|
|||
return acc
|
||||
}
|
||||
|
||||
func executeGetCandidate(t *testing.T, cmdStr string) stake.Candidate {
|
||||
func executeGetCandidate(t *testing.T, cmdStr string) stake.Validator {
|
||||
out := tests.ExecuteT(t, cmdStr)
|
||||
var candidate stake.Candidate
|
||||
var candidate stake.Validator
|
||||
cdc := app.MakeCodec()
|
||||
err := cdc.UnmarshalJSON([]byte(out), &candidate)
|
||||
require.NoError(t, err, "out %v, err %v", out, err)
|
||||
|
|
|
@ -45,10 +45,10 @@ func main() {
|
|||
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),
|
||||
stakecmd.GetCmdQueryValidator("stake", cdc),
|
||||
stakecmd.GetCmdQueryValidators("stake", cdc),
|
||||
stakecmd.GetCmdQueryDelegation("stake", cdc),
|
||||
stakecmd.GetCmdQueryDelegations("stake", cdc),
|
||||
)...)
|
||||
rootCmd.AddCommand(
|
||||
client.PostCommands(
|
||||
|
|
|
@ -1,10 +1,13 @@
|
|||
openapi: 3.0.0
|
||||
servers:
|
||||
- url: 'http://localhost:8998'
|
||||
swagger: '2.0'
|
||||
info:
|
||||
version: "1.1.0"
|
||||
title: Light client daemon to interface with full Gaia node via REST
|
||||
description: Specification for the LCD provided by `gaia rest-server`
|
||||
version: '1.1.0'
|
||||
title: Light client daemon to interface with Cosmos baseserver via REST
|
||||
description: Specification for the LCD provided by `gaiacli rest-server`
|
||||
|
||||
|
||||
securityDefinitions:
|
||||
kms:
|
||||
type: basic
|
||||
|
||||
paths:
|
||||
/version:
|
||||
|
@ -13,73 +16,69 @@ paths:
|
|||
description: Get the version of the LCD running locally to compare against expected
|
||||
responses:
|
||||
200:
|
||||
description: Plaintext version i.e. "0.16.0-dev-26440095"
|
||||
description: Plaintext version i.e. "v0.5.0"
|
||||
/node_info:
|
||||
description: Only the node info. Block information can be queried via /block/latest
|
||||
get:
|
||||
description: Only the node info. Block information can be queried via /block/latest
|
||||
summary: The propertied of the connected node
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
200:
|
||||
description: Node status
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
description: ???
|
||||
pub_key:
|
||||
$ref: '#/definitions/PubKey'
|
||||
moniker:
|
||||
type: string
|
||||
example: 159.89.198.221
|
||||
network:
|
||||
type: string
|
||||
example: gaia-2
|
||||
remote_addr:
|
||||
type: string
|
||||
listen_addr:
|
||||
type: string
|
||||
example: 192.168.56.1:46656
|
||||
network:
|
||||
type: string
|
||||
example: gaia-5000
|
||||
version:
|
||||
description: Tendermint version
|
||||
type: string
|
||||
example: 0.19.1
|
||||
channels:
|
||||
description: ???
|
||||
type: string
|
||||
pub_key:
|
||||
$ref: '#/components/schemas/PubKey'
|
||||
moniker:
|
||||
type: string
|
||||
example: 159.89.198.221
|
||||
remote_addr:
|
||||
type: string
|
||||
example: 0.15.0
|
||||
other:
|
||||
description: more information on versions and options for the node
|
||||
description: more information on versions
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
/syncing:
|
||||
get:
|
||||
summary: Syncing state of node
|
||||
description: Get if the node is currently syning with other nodes
|
||||
responses:
|
||||
200:
|
||||
description: "true" or "false"
|
||||
description: '"true" or "false"'
|
||||
|
||||
/keys:
|
||||
get:
|
||||
summary: List of accounts stored locally
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
200:
|
||||
description: Array of accounts
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/Account'
|
||||
$ref: '#/definitions/Account'
|
||||
post:
|
||||
summary: Create a new account locally
|
||||
responses:
|
||||
200:
|
||||
description: Returns address of the account created
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
consumes:
|
||||
- application/json
|
||||
parameters:
|
||||
- in: body
|
||||
name: account
|
||||
description: The account to create
|
||||
schema:
|
||||
type: object
|
||||
required:
|
||||
|
@ -93,15 +92,17 @@ paths:
|
|||
type: string
|
||||
seed:
|
||||
type: string
|
||||
description: The account to create.
|
||||
responses:
|
||||
200:
|
||||
description: Returns address of the account created
|
||||
/keys/seed:
|
||||
get:
|
||||
summary: Create a new seed to create a new account with
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
200:
|
||||
description: 12 word Seed
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: string
|
||||
/keys/{name}:
|
||||
|
@ -110,24 +111,26 @@ paths:
|
|||
name: name
|
||||
description: Account name
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
get:
|
||||
summary: Get a certain locally stored account
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
200:
|
||||
description: Locally stored account
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/Account"
|
||||
$ref: "#/definitions/Account"
|
||||
404:
|
||||
description: Account is not available
|
||||
put:
|
||||
summary: Update the password for this account
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
summary: Update the password for this account in the KMS
|
||||
consumes:
|
||||
- application/json
|
||||
parameters:
|
||||
- in: body
|
||||
name: account
|
||||
description: The new and old password
|
||||
schema:
|
||||
type: object
|
||||
required:
|
||||
|
@ -147,9 +150,12 @@ paths:
|
|||
description: Account is not available
|
||||
delete:
|
||||
summary: Remove an account
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
consumes:
|
||||
- application/json
|
||||
parameters:
|
||||
- in: body
|
||||
name: account
|
||||
description: The password of the account to remove from the KMS
|
||||
schema:
|
||||
type: object
|
||||
required:
|
||||
|
@ -176,18 +182,18 @@ paths:
|
|||
# type: object
|
||||
# properties:
|
||||
# fees:
|
||||
# $ref: "#/components/schemas/Coins"
|
||||
# $ref: "#/definitions/Coins"
|
||||
# outputs:
|
||||
# type: array
|
||||
# items:
|
||||
# type: object
|
||||
# properties:
|
||||
# pub_key:
|
||||
# $ref: "#/components/schemas/PubKey"
|
||||
# $ref: "#/definitions/PubKey"
|
||||
# amount:
|
||||
# type: array
|
||||
# items:
|
||||
# $ref: "#/components/schemas/Coins"
|
||||
# $ref: "#/definitions/Coins"
|
||||
# responses:
|
||||
# 202:
|
||||
# description: Tx was send and will probably be added to the next block
|
||||
|
@ -200,21 +206,16 @@ paths:
|
|||
name: address
|
||||
description: Account address
|
||||
required: true
|
||||
schema:
|
||||
$ref: "#/components/schemas/Address"
|
||||
type: string
|
||||
get:
|
||||
summary: Get the account balances
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
200:
|
||||
description: Account balances
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type:
|
||||
description: "???"
|
||||
type: string
|
||||
value:
|
||||
$ref: "#/components/schemas/Balance"
|
||||
$ref: "#/definitions/Balance"
|
||||
204:
|
||||
description: There is no data for the requested account. This is not a 404 as the account might exist, just does not hold data.
|
||||
/accounts/{address}/send:
|
||||
|
@ -223,31 +224,29 @@ paths:
|
|||
name: address
|
||||
description: Account address
|
||||
required: true
|
||||
schema:
|
||||
$ref: "#/components/schemas/Address"
|
||||
type: string
|
||||
post:
|
||||
summary: Send coins (build -> sign -> send)
|
||||
security:
|
||||
- sign: []
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
- kms: []
|
||||
consumes:
|
||||
- application/json
|
||||
parameters:
|
||||
- in: body
|
||||
name: account
|
||||
description: The password of the account to remove from the KMS
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
name:
|
||||
description: Name of locally stored key
|
||||
type: string
|
||||
password:
|
||||
type: string
|
||||
amount:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/components/schemas/Coins"
|
||||
$ref: "#/definitions/Coins"
|
||||
chain_id:
|
||||
description: Target chain
|
||||
type: string
|
||||
src_chain_id:
|
||||
type: string
|
||||
squence:
|
||||
type: number
|
||||
|
@ -256,66 +255,76 @@ paths:
|
|||
description: Tx was send and will probably be added to the next block
|
||||
400:
|
||||
description: The Tx was malformated
|
||||
/accounts/{address}/nonce:
|
||||
parameters:
|
||||
- in: path
|
||||
name: address
|
||||
description: Account address
|
||||
required: true
|
||||
type: string
|
||||
get:
|
||||
summary: Get the nonce for a certain account
|
||||
responses:
|
||||
200:
|
||||
description: Plaintext nonce i.e. "4" defaults to "0"
|
||||
/blocks/latest:
|
||||
get:
|
||||
summary: Get the latest block
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
200:
|
||||
description: The latest block
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/Block"
|
||||
$ref: "#/definitions/Block"
|
||||
/blocks/{height}:
|
||||
parameters:
|
||||
- in: path
|
||||
name: height
|
||||
description: Block height
|
||||
required: true
|
||||
schema:
|
||||
type: number
|
||||
get:
|
||||
summary: Get a block at a certain height
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
200:
|
||||
description: The block at a specific height
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/Block"
|
||||
$ref: "#/definitions/Block"
|
||||
404:
|
||||
description: Block at height is not available
|
||||
/validatorsets/latest:
|
||||
get:
|
||||
summary: Get the latest validator set
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
200:
|
||||
description: The validator set at the latest block height
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/components/schemas/Delegate"
|
||||
$ref: "#/definitions/Delegate"
|
||||
/validatorsets/{height}:
|
||||
parameters:
|
||||
- in: path
|
||||
name: height
|
||||
description: Block height
|
||||
required: true
|
||||
schema:
|
||||
type: number
|
||||
get:
|
||||
summary: Get a validator set a certain height
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
200:
|
||||
description: The validator set at a specific block height
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/components/schemas/Delegate"
|
||||
$ref: "#/definitions/Delegate"
|
||||
404:
|
||||
description: Block at height not available
|
||||
# /txs:
|
||||
|
@ -348,7 +357,7 @@ paths:
|
|||
# schema:
|
||||
# type: array
|
||||
# items:
|
||||
# $ref: "#/components/schemas/Tx"
|
||||
# $ref: "#/definitions/Tx"
|
||||
# 404:
|
||||
# description: Pagination is out of bounds
|
||||
# /txs/sign:
|
||||
|
@ -361,14 +370,14 @@ paths:
|
|||
# content:
|
||||
# application/json:
|
||||
# schema:
|
||||
# $ref: "#/components/schemas/TxBuild"
|
||||
# $ref: "#/definitions/TxBuild"
|
||||
# responses:
|
||||
# 200:
|
||||
# description: The signed Tx
|
||||
# content:
|
||||
# application/json:
|
||||
# schema:
|
||||
# $ref: "#/components/schemas/TxSigned"
|
||||
# $ref: "#/definitions/TxSigned"
|
||||
# 401:
|
||||
# description: Account name and/or password where wrong
|
||||
# /txs/broadcast:
|
||||
|
@ -378,7 +387,7 @@ paths:
|
|||
# content:
|
||||
# application/json:
|
||||
# schema:
|
||||
# $ref: "#/components/schemas/TxSigned"
|
||||
# $ref: "#/definitions/TxSigned"
|
||||
# responses:
|
||||
# 202:
|
||||
# description: Tx was send and will probably be added to the next block
|
||||
|
@ -390,17 +399,16 @@ paths:
|
|||
name: hash
|
||||
description: Tx hash
|
||||
required: true
|
||||
schema:
|
||||
$ref: "#/components/schemas/Hash"
|
||||
type: string
|
||||
get:
|
||||
summary: Get a Tx by hash
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
200:
|
||||
description: Tx with the provided hash
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/Tx"
|
||||
$ref: "#/definitions/Tx"
|
||||
404:
|
||||
description: Tx not available for provided hash
|
||||
# /delegates:
|
||||
|
@ -409,7 +417,7 @@ paths:
|
|||
# name: delegator
|
||||
# description: Query for all delegates a delegator has stake with
|
||||
# schema:
|
||||
# $ref: "#/components/schemas/Address"
|
||||
# $ref: "#/definitions/Address"
|
||||
# get:
|
||||
# summary: Get a list of canidates/delegates/validators (optionally filtered by delegator)
|
||||
# responses:
|
||||
|
@ -420,7 +428,7 @@ paths:
|
|||
# schema:
|
||||
# type: array
|
||||
# items:
|
||||
# $ref: "#/components/schemas/Delegate"
|
||||
# $ref: "#/definitions/Delegate"
|
||||
# /delegates/bond:
|
||||
# post:
|
||||
# summary: Bond atoms (build -> sign -> send)
|
||||
|
@ -435,9 +443,9 @@ paths:
|
|||
# type: object
|
||||
# properties:
|
||||
# amount:
|
||||
# $ref: "#/components/schemas/Coins"
|
||||
# $ref: "#/definitions/Coins"
|
||||
# pub_key:
|
||||
# $ref: "#/components/schemas/PubKey"
|
||||
# $ref: "#/definitions/PubKey"
|
||||
# responses:
|
||||
# 202:
|
||||
# description: Tx was send and will probably be added to the next block
|
||||
|
@ -457,9 +465,9 @@ paths:
|
|||
# type: object
|
||||
# properties:
|
||||
# amount:
|
||||
# $ref: "#/components/schemas/Coins"
|
||||
# $ref: "#/definitions/Coins"
|
||||
# pub_key:
|
||||
# $ref: "#/components/schemas/PubKey"
|
||||
# $ref: "#/definitions/PubKey"
|
||||
# responses:
|
||||
# 202:
|
||||
# description: Tx was send and will probably be added to the next block
|
||||
|
@ -482,7 +490,7 @@ paths:
|
|||
# content:
|
||||
# application/json:
|
||||
# schema:
|
||||
# $ref: "#/components/schemas/Delegate"
|
||||
# $ref: "#/definitions/Delegate"
|
||||
# 404:
|
||||
# description: No delegate found for provided pub_key
|
||||
# /delegates/{pubkey}/bond:
|
||||
|
@ -505,7 +513,7 @@ paths:
|
|||
# type: object
|
||||
# properties:
|
||||
# amount:
|
||||
# $ref: "#/components/schemas/Coins"
|
||||
# $ref: "#/definitions/Coins"
|
||||
# responses:
|
||||
# 202:
|
||||
# description: Tx was send and will probably be added to the next block
|
||||
|
@ -531,15 +539,14 @@ paths:
|
|||
# type: object
|
||||
# properties:
|
||||
# amount:
|
||||
# $ref: "#/components/schemas/Coins"
|
||||
# $ref: "#/definitions/Coins"
|
||||
# responses:
|
||||
# 202:
|
||||
# description: Tx was send and will probably be added to the next block
|
||||
# 400:
|
||||
# description: The Tx was malformated
|
||||
|
||||
components:
|
||||
schemas:
|
||||
definitions:
|
||||
Address:
|
||||
type: string
|
||||
example: DF096FDE8D380FA5B2AD20DB2962C82DDEA1ED9B
|
||||
|
@ -603,9 +610,9 @@ components:
|
|||
type: string
|
||||
default: sigs
|
||||
addr:
|
||||
$ref: "#/components/schemas/Address"
|
||||
$ref: "#/definitions/Address"
|
||||
tx:
|
||||
$ref: "#/components/schemas/Tx"
|
||||
$ref: "#/definitions/Tx"
|
||||
TxBuild:
|
||||
type: object
|
||||
properties:
|
||||
|
@ -616,7 +623,7 @@ components:
|
|||
type: object
|
||||
properties:
|
||||
tx:
|
||||
$ref: "#/components/schemas/Tx"
|
||||
$ref: "#/definitions/Tx"
|
||||
signature:
|
||||
type: object
|
||||
properties:
|
||||
|
@ -636,7 +643,7 @@ components:
|
|||
type: object
|
||||
properties:
|
||||
tx:
|
||||
$ref: "#/components/schemas/Tx"
|
||||
$ref: "#/definitions/Tx"
|
||||
signature:
|
||||
type: object
|
||||
properties:
|
||||
|
@ -644,7 +651,7 @@ components:
|
|||
type: string
|
||||
example: 81B11E717789600CC192B26F452A983DF13B985EE75ABD9DD9E68D7BA007A958
|
||||
Pubkey:
|
||||
$ref: "#/components/schemas/PubKey"
|
||||
$ref: "#/definitions/PubKey"
|
||||
PubKey:
|
||||
type: object
|
||||
properties:
|
||||
|
@ -662,27 +669,28 @@ components:
|
|||
type: string
|
||||
example: Main Account
|
||||
address:
|
||||
$ref: "#/components/schemas/Address"
|
||||
$ref: "#/definitions/Address"
|
||||
pub_key:
|
||||
$ref: "#/components/schemas/PubKey"
|
||||
$ref: "#/definitions/PubKey"
|
||||
Balance:
|
||||
type: object
|
||||
properties:
|
||||
address:
|
||||
type: string
|
||||
height:
|
||||
type: number
|
||||
example: 123456
|
||||
coins:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/components/schemas/Coins"
|
||||
public_key:
|
||||
$ref: "#/components/schemas/PubKey"
|
||||
sequence:
|
||||
type: number
|
||||
$ref: "#/definitions/Coins"
|
||||
credit:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
BlockID:
|
||||
type: object
|
||||
properties:
|
||||
hash:
|
||||
$ref: "#/components/schemas/Hash"
|
||||
$ref: "#/definitions/Hash"
|
||||
parts:
|
||||
type: object
|
||||
properties:
|
||||
|
@ -690,7 +698,7 @@ components:
|
|||
type: number
|
||||
example: 0
|
||||
hash:
|
||||
$ref: "#/components/schemas/Hash"
|
||||
$ref: "#/definitions/Hash"
|
||||
Block:
|
||||
type: object
|
||||
properties:
|
||||
|
@ -710,51 +718,54 @@ components:
|
|||
type: number
|
||||
example: 0
|
||||
last_block_id:
|
||||
$ref: "#/components/schemas/BlockID"
|
||||
$ref: "#/definitions/BlockID"
|
||||
total_txs:
|
||||
type: number
|
||||
example: 35
|
||||
last_commit_hash:
|
||||
$ref: "#/components/schemas/Hash"
|
||||
$ref: "#/definitions/Hash"
|
||||
data_hash:
|
||||
$ref: "#/components/schemas/Hash"
|
||||
$ref: "#/definitions/Hash"
|
||||
validators_hash:
|
||||
$ref: "#/components/schemas/Hash"
|
||||
$ref: "#/definitions/Hash"
|
||||
consensus_hash:
|
||||
$ref: "#/components/schemas/Hash"
|
||||
$ref: "#/definitions/Hash"
|
||||
app_hash:
|
||||
$ref: "#/components/schemas/Hash"
|
||||
$ref: "#/definitions/Hash"
|
||||
last_results_hash:
|
||||
$ref: "#/components/schemas/Hash"
|
||||
$ref: "#/definitions/Hash"
|
||||
evidence_hash:
|
||||
$ref: "#/components/schemas/Hash"
|
||||
$ref: "#/definitions/Hash"
|
||||
txs:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/components/schemas/Tx"
|
||||
$ref: "#/definitions/Tx"
|
||||
evidence:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
last_commit:
|
||||
type: object
|
||||
properties:
|
||||
blockID:
|
||||
$ref: "#/components/schemas/BlockID"
|
||||
$ref: "#/definitions/BlockID"
|
||||
precommits:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
Delegate:
|
||||
type: object
|
||||
properties:
|
||||
pub_key:
|
||||
$ref: "#/components/schemas/PubKey"
|
||||
$ref: "#/definitions/PubKey"
|
||||
power:
|
||||
type: number
|
||||
example: 1000
|
||||
name:
|
||||
type: string
|
||||
example: "159.89.3.34"
|
||||
|
||||
|
||||
securitySchemes:
|
||||
sign:
|
||||
type: http
|
||||
scheme: basic
|
||||
# Added by API Auto Mocking Plugin
|
||||
host: virtserver.swaggerhub.com
|
||||
basePath: /faboweb1/Cosmos-LCD-2/1.0.0
|
||||
schemes:
|
||||
- https
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -35,7 +35,8 @@ type BasecoinApp struct {
|
|||
keyStake *sdk.KVStoreKey
|
||||
|
||||
// Manage getting and setting accounts
|
||||
accountMapper sdk.AccountMapper
|
||||
accountMapper auth.AccountMapper
|
||||
feeCollectionKeeper auth.FeeCollectionKeeper
|
||||
coinKeeper bank.Keeper
|
||||
ibcMapper ibc.Mapper
|
||||
stakeKeeper stake.Keeper
|
||||
|
@ -70,7 +71,7 @@ func NewBasecoinApp(logger log.Logger, db dbm.DB) *BasecoinApp {
|
|||
|
||||
// register message routes
|
||||
app.Router().
|
||||
AddRoute("auth", auth.NewHandler(app.accountMapper.(auth.AccountMapper))).
|
||||
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))
|
||||
|
@ -78,7 +79,7 @@ func NewBasecoinApp(logger log.Logger, db dbm.DB) *BasecoinApp {
|
|||
// 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.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper))
|
||||
err := app.LoadLatestVersion(app.keyMain)
|
||||
if err != nil {
|
||||
cmn.Exit(err.Error())
|
||||
|
@ -96,7 +97,7 @@ func MakeCodec() *wire.Codec {
|
|||
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
|
||||
}
|
||||
|
@ -129,7 +130,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(),
|
||||
|
|
|
@ -37,7 +37,7 @@ 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}},
|
||||
100000,
|
||||
}
|
||||
|
@ -471,17 +471,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)
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -6,7 +6,7 @@ import (
|
|||
"github.com/cosmos/cosmos-sdk/x/auth"
|
||||
)
|
||||
|
||||
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 +23,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")
|
||||
}
|
||||
|
|
|
@ -39,6 +39,7 @@ type DemocoinApp struct {
|
|||
capKeyStakingStore *sdk.KVStoreKey
|
||||
|
||||
// keepers
|
||||
feeCollectionKeeper auth.FeeCollectionKeeper
|
||||
coinKeeper bank.Keeper
|
||||
coolKeeper cool.Keeper
|
||||
powKeeper pow.Keeper
|
||||
|
@ -46,7 +47,7 @@ type DemocoinApp struct {
|
|||
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,7 +31,7 @@ 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}},
|
||||
1000000,
|
||||
}
|
||||
|
@ -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,
|
||||
}})
|
||||
|
@ -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)
|
||||
|
@ -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")
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
|
||||
ctx := sdk.NewContext(ms, abci.Header{}, false, nil, log.NewNopLogger())
|
||||
stakeKeeper := NewKeeper(capKey, bank.NewKeeper(nil), DefaultCodespace)
|
||||
accountMapper := auth.NewAccountMapper(cdc, authKey, &auth.BaseAccount{})
|
||||
stakeKeeper := NewKeeper(capKey, bank.NewKeeper(accountMapper), DefaultCodespace)
|
||||
addr := sdk.Address([]byte("some-address"))
|
||||
|
||||
bi := stakeKeeper.getBondInfo(ctx, addr)
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
||||
|
|
|
@ -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
|
||||
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
*.retry
|
||||
files/*
|
|
@ -0,0 +1,4 @@
|
|||
[defaults]
|
||||
retry_files_enabled = False
|
||||
host_key_checking = False
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
---
|
||||
|
||||
- hosts: all
|
||||
user: root
|
||||
any_errors_fatal: true
|
||||
gather_facts: no
|
||||
roles:
|
||||
- clear-config
|
||||
|
|
@ -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>.
|
||||
|
|
@ -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 = {}
|
|
@ -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()
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
---
|
||||
|
||||
- name: reload daemon
|
||||
command: "systemctl daemon-reload"
|
||||
|
||||
- name: restart journalbeat
|
||||
service: name=journalbeat state=restarted
|
||||
|
|
@ -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
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
|
||||
- name: start service
|
||||
service: "name={{service}} state=started"
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
|
||||
- name: stop service
|
||||
service: "name={{service}} state=stopped"
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
---
|
||||
|
||||
- hosts: all
|
||||
user: root
|
||||
any_errors_fatal: true
|
||||
gather_facts: no
|
||||
roles:
|
||||
- setup-validators
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
---
|
||||
|
||||
- hosts: all
|
||||
user: root
|
||||
any_errors_fatal: true
|
||||
gather_facts: no
|
||||
vars:
|
||||
- service: gaiad
|
||||
roles:
|
||||
- start
|
||||
|
|
@ -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
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
---
|
||||
|
||||
- hosts: all
|
||||
user: root
|
||||
any_errors_fatal: true
|
||||
gather_facts: no
|
||||
vars:
|
||||
- service: gaiad
|
||||
roles:
|
||||
- stop
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
.terraform
|
||||
terraform.tfstate
|
||||
terraform.tfstate.backup
|
||||
terraform.tfstate.d
|
|
@ -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"]
|
||||
}
|
||||
|
||||
|
|
@ -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}",
|
||||
]
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -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}"]
|
||||
}
|
||||
|
|
@ -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
|
||||
}
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
||||
|
|
@ -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}"
|
||||
}
|
||||
|
|
@ -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/types/priv_validator"
|
||||
|
@ -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)
|
||||
addr, err := sdk.Bech32CosmosifyValPub(valPubKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(addr)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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)}
|
||||
|
|
|
@ -75,16 +75,6 @@ func (gi *gasKVStore) ReverseIterator(start, end []byte) sdk.Iterator {
|
|||
return gi.iterator(start, end, false)
|
||||
}
|
||||
|
||||
// Implements KVStore.
|
||||
func (gi *gasKVStore) SubspaceIterator(prefix []byte) sdk.Iterator {
|
||||
return gi.iterator(prefix, sdk.PrefixEndBytes(prefix), true)
|
||||
}
|
||||
|
||||
// Implements KVStore.
|
||||
func (gi *gasKVStore) ReverseSubspaceIterator(prefix []byte) sdk.Iterator {
|
||||
return gi.iterator(prefix, sdk.PrefixEndBytes(prefix), false)
|
||||
}
|
||||
|
||||
// Implements KVStore.
|
||||
func (gi *gasKVStore) CacheWrap() sdk.CacheWrap {
|
||||
panic("you cannot CacheWrap a GasKVStore")
|
||||
|
|
|
@ -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)},
|
||||
|
|
113
types/account.go
113
types/account.go
|
@ -3,16 +3,46 @@ package types
|
|||
import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
bech32cosmos "github.com/cosmos/bech32cosmos/go"
|
||||
crypto "github.com/tendermint/go-crypto"
|
||||
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"
|
||||
)
|
||||
|
||||
// Bech32CosmosifyAcc takes Address and returns the Bech32Cosmos encoded string
|
||||
func Bech32CosmosifyAcc(addr Address) (string, error) {
|
||||
return bech32cosmos.ConvertAndEncode(Bech32PrefixAccAddr, addr.Bytes())
|
||||
}
|
||||
|
||||
// Bech32CosmosifyAccPub takes AccountPubKey and returns the Bech32Cosmos encoded string
|
||||
func Bech32CosmosifyAccPub(pub crypto.PubKey) (string, error) {
|
||||
return bech32cosmos.ConvertAndEncode(Bech32PrefixAccPub, pub.Bytes())
|
||||
}
|
||||
|
||||
// Bech32CosmosifyVal returns the Bech32Cosmos encoded string for a validator address
|
||||
func Bech32CosmosifyVal(addr Address) (string, error) {
|
||||
return bech32cosmos.ConvertAndEncode(Bech32PrefixValAddr, addr.Bytes())
|
||||
}
|
||||
|
||||
// Bech32CosmosifyValPub returns the Bech32Cosmos encoded string for a validator pubkey
|
||||
func Bech32CosmosifyValPub(pub crypto.PubKey) (string, error) {
|
||||
return bech32cosmos.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 GetAccAddressBech32Cosmos(address string) (addr Address, err error) {
|
||||
bz, err := getFromBech32Cosmos(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 bech32cosmos string
|
||||
func GetValAddressBech32Cosmos(address string) (addr Address, err error) {
|
||||
bz, err := getFromBech32Cosmos(address, Bech32PrefixValAddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return Address(bz), nil
|
||||
}
|
||||
|
||||
//Decode a validator publickey into a public key
|
||||
func GetValPubKeyBech32Cosmos(pubkey string) (pk crypto.PubKey, err error) {
|
||||
bz, err := getFromBech32Cosmos(pubkey, Bech32PrefixValPub)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pk, err = crypto.PubKeyFromBytes(bz)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return pk, nil
|
||||
}
|
||||
|
||||
func getFromBech32Cosmos(bech32, prefix string) ([]byte, error) {
|
||||
if len(bech32) == 0 {
|
||||
return nil, errors.New("must provide non-empty string")
|
||||
}
|
||||
hrp, bz, err := bech32cosmos.DecodeAndConvert(bech32)
|
||||
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
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -5,6 +5,7 @@ import (
|
|||
"math/big"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// "that's one big rat!"
|
||||
|
@ -83,14 +84,14 @@ func NewRatFromDecimal(decimalStr string) (f Rat, err Error) {
|
|||
func (r Rat) Num() int64 { return r.Rat.Num().Int64() } // Num - return the numerator
|
||||
func (r Rat) Denom() int64 { return r.Rat.Denom().Int64() } // Denom - return the denominator
|
||||
func (r Rat) IsZero() bool { return r.Num() == 0 } // IsZero - Is the Rat equal to zero
|
||||
func (r Rat) Equal(r2 Rat) bool { return (&(r.Rat)).Cmp(&(r2.Rat)) == 0 } // Equal - rationals are equal
|
||||
func (r Rat) GT(r2 Rat) bool { return (&(r.Rat)).Cmp(&(r2.Rat)) == 1 } // Equal - rationals are equal
|
||||
func (r Rat) LT(r2 Rat) bool { return (&(r.Rat)).Cmp(&(r2.Rat)) == -1 } // Equal - rationals are equal
|
||||
func (r Rat) Equal(r2 Rat) bool { return (&(r.Rat)).Cmp(&(r2.Rat)) == 0 }
|
||||
func (r Rat) GT(r2 Rat) bool { return (&(r.Rat)).Cmp(&(r2.Rat)) == 1 } // greater than
|
||||
func (r Rat) LT(r2 Rat) bool { return (&(r.Rat)).Cmp(&(r2.Rat)) == -1 } // less than
|
||||
func (r Rat) Mul(r2 Rat) Rat { return Rat{*new(big.Rat).Mul(&(r.Rat), &(r2.Rat))} } // Mul - multiplication
|
||||
func (r Rat) Quo(r2 Rat) Rat { return Rat{*new(big.Rat).Quo(&(r.Rat), &(r2.Rat))} } // Quo - quotient
|
||||
func (r Rat) Add(r2 Rat) Rat { return Rat{*new(big.Rat).Add(&(r.Rat), &(r2.Rat))} } // Add - addition
|
||||
func (r Rat) Sub(r2 Rat) Rat { return Rat{*new(big.Rat).Sub(&(r.Rat), &(r2.Rat))} } // Sub - subtraction
|
||||
func (r Rat) String() string { return fmt.Sprintf("%v/%v", r.Num(), r.Denom()) } // Sub - subtraction
|
||||
func (r Rat) String() string { return fmt.Sprintf("%v/%v", r.Num(), r.Denom()) }
|
||||
|
||||
var (
|
||||
zero = big.NewInt(0)
|
||||
|
@ -168,3 +169,25 @@ func (r *Rat) UnmarshalAmino(text string) (err error) {
|
|||
r.Rat = *tempRat
|
||||
return nil
|
||||
}
|
||||
|
||||
//___________________________________________________________________________________
|
||||
// helpers
|
||||
|
||||
// test if two rat arrays are the equal
|
||||
func RatsEqual(r1s, r2s []Rat) bool {
|
||||
if len(r1s) != len(r2s) {
|
||||
return false
|
||||
}
|
||||
|
||||
for i, r1 := range r1s {
|
||||
if !r1.Equal(r2s[i]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// intended to be used with require/assert: require.True(RatEq(...))
|
||||
func RatEq(t *testing.T, exp, got Rat) (*testing.T, bool, string, Rat, Rat) {
|
||||
return t, exp.Equal(got), "expected:\t%v\ngot:\t\t%v", exp, got
|
||||
}
|
||||
|
|
|
@ -276,3 +276,24 @@ func TestEmbeddedStructSerializationGoWire(t *testing.T) {
|
|||
assert.Equal(t, obj.Field2, obj2.Field2)
|
||||
assert.True(t, obj.Field3.Equal(obj2.Field3), "original: %v, unmarshalled: %v", obj, obj2)
|
||||
}
|
||||
|
||||
func TestRatsEqual(t *testing.T) {
|
||||
tests := []struct {
|
||||
r1s, r2s []Rat
|
||||
eq bool
|
||||
}{
|
||||
{[]Rat{NewRat(0)}, []Rat{NewRat(0)}, true},
|
||||
{[]Rat{NewRat(0)}, []Rat{NewRat(1)}, false},
|
||||
{[]Rat{NewRat(0)}, []Rat{}, false},
|
||||
{[]Rat{NewRat(0), NewRat(1)}, []Rat{NewRat(0), NewRat(1)}, true},
|
||||
{[]Rat{NewRat(1), NewRat(0)}, []Rat{NewRat(1), NewRat(0)}, true},
|
||||
{[]Rat{NewRat(1), NewRat(0)}, []Rat{NewRat(0), NewRat(1)}, false},
|
||||
{[]Rat{NewRat(1), NewRat(0)}, []Rat{NewRat(1)}, false},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
assert.Equal(t, tc.eq, RatsEqual(tc.r1s, tc.r2s))
|
||||
assert.Equal(t, tc.eq, RatsEqual(tc.r2s, tc.r1s))
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,10 +0,0 @@
|
|||
package types
|
||||
|
||||
import crypto "github.com/tendermint/go-crypto"
|
||||
|
||||
// Standard Signature
|
||||
type StdSignature struct {
|
||||
crypto.PubKey `json:"pub_key"` // optional
|
||||
crypto.Signature `json:"signature"`
|
||||
Sequence int64 `json:"sequence"`
|
||||
}
|
|
@ -0,0 +1,79 @@
|
|||
package types
|
||||
|
||||
import (
|
||||
abci "github.com/tendermint/abci/types"
|
||||
"github.com/tendermint/go-crypto"
|
||||
)
|
||||
|
||||
// status of a validator
|
||||
type BondStatus byte
|
||||
|
||||
// nolint
|
||||
const (
|
||||
Unbonded BondStatus = 0x00
|
||||
Unbonding BondStatus = 0x01
|
||||
Bonded BondStatus = 0x02
|
||||
)
|
||||
|
||||
//BondStatusToString for pretty prints of Bond Status
|
||||
func BondStatusToString(b BondStatus) string {
|
||||
switch b {
|
||||
case 0x00:
|
||||
return "Unbonded"
|
||||
case 0x01:
|
||||
return "Unbonding"
|
||||
case 0x02:
|
||||
return "Bonded"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// validator for a delegated proof of stake system
|
||||
type Validator interface {
|
||||
GetStatus() BondStatus // status of the validator
|
||||
GetOwner() Address // owner address to receive/return validators coins
|
||||
GetPubKey() crypto.PubKey // validation pubkey
|
||||
GetPower() Rat // validation power
|
||||
GetBondHeight() int64 // height in which the validator became active
|
||||
}
|
||||
|
||||
// validator which fulfills abci validator interface for use in Tendermint
|
||||
func ABCIValidator(v Validator) abci.Validator {
|
||||
return abci.Validator{
|
||||
PubKey: v.GetPubKey().Bytes(),
|
||||
Power: v.GetPower().Evaluate(),
|
||||
}
|
||||
}
|
||||
|
||||
// properties for the set of all validators
|
||||
type ValidatorSet interface {
|
||||
// iterate through validator by owner-address, execute func for each validator
|
||||
IterateValidators(Context,
|
||||
func(index int64, validator Validator) (stop bool))
|
||||
|
||||
// iterate through bonded validator by pubkey-address, execute func for each validator
|
||||
IterateValidatorsBonded(Context,
|
||||
func(index int64, validator Validator) (stop bool))
|
||||
|
||||
Validator(Context, Address) Validator // get a particular validator by owner address
|
||||
TotalPower(Context) Rat // total power of the validator set
|
||||
}
|
||||
|
||||
//_______________________________________________________________________________
|
||||
|
||||
// delegation bond for a delegated proof of stake system
|
||||
type Delegation interface {
|
||||
GetDelegator() Address // delegator address for the bond
|
||||
GetValidator() Address // validator owner address for the bond
|
||||
GetBondShares() Rat // amount of validator's shares
|
||||
}
|
||||
|
||||
// properties for the set of all delegations for a particular
|
||||
type DelegationSet interface {
|
||||
|
||||
// iterate through all delegations from one delegator by validator-address,
|
||||
// execute func for each validator
|
||||
IterateDelegators(Context, delegator Address,
|
||||
fn func(index int64, delegation Delegation) (stop bool))
|
||||
}
|
|
@ -84,7 +84,7 @@ type CommitMultiStore interface {
|
|||
LoadVersion(ver int64) error
|
||||
}
|
||||
|
||||
//----------------------------------------
|
||||
//---------subsp-------------------------------
|
||||
// KVStore
|
||||
|
||||
// KVStore is a simple interface to get/set data
|
||||
|
@ -113,25 +113,26 @@ type KVStore interface {
|
|||
// CONTRACT: No writes may happen within a domain while an iterator exists over it.
|
||||
ReverseIterator(start, end []byte) Iterator
|
||||
|
||||
// Iterator over all the keys with a certain prefix in ascending order.
|
||||
// CONTRACT: No writes may happen within a domain while an iterator exists over it.
|
||||
SubspaceIterator(prefix []byte) Iterator
|
||||
|
||||
// Iterator over all the keys with a certain prefix in descending order.
|
||||
// CONTRACT: No writes may happen within a domain while an iterator exists over it.
|
||||
ReverseSubspaceIterator(prefix []byte) Iterator
|
||||
|
||||
// TODO Not yet implemented.
|
||||
// CreateSubKVStore(key *storeKey) (KVStore, error)
|
||||
|
||||
// TODO Not yet implemented.
|
||||
// GetSubKVStore(key *storeKey) KVStore
|
||||
|
||||
}
|
||||
|
||||
// Alias iterator to db's Iterator for convenience.
|
||||
type Iterator = dbm.Iterator
|
||||
|
||||
// Iterator over all the keys with a certain prefix in ascending order
|
||||
func KVStorePrefixIterator(kvs KVStore, prefix []byte) Iterator {
|
||||
return kvs.Iterator(prefix, PrefixEndBytes(prefix))
|
||||
}
|
||||
|
||||
// Iterator over all the keys with a certain prefix in descending order.
|
||||
func KVStoreReversePrefixIterator(kvs KVStore, prefix []byte) Iterator {
|
||||
return kvs.ReverseIterator(prefix, PrefixEndBytes(prefix))
|
||||
}
|
||||
|
||||
// CacheKVStore cache-wraps a KVStore. After calling .Write() on
|
||||
// the CacheKVStore, all previously created CacheKVStores on the
|
||||
// object expire.
|
||||
|
|
119
types/tx_msg.go
119
types/tx_msg.go
|
@ -31,128 +31,11 @@ type Tx interface {
|
|||
|
||||
// Gets the Msg.
|
||||
GetMsg() Msg
|
||||
|
||||
// Signatures returns the signature of signers who signed the Msg.
|
||||
// CONTRACT: Length returned is same as length of
|
||||
// pubkeys returned from MsgKeySigners, and the order
|
||||
// matches.
|
||||
// CONTRACT: If the signature is missing (ie the Msg is
|
||||
// invalid), then the corresponding signature is
|
||||
// .Empty().
|
||||
GetSignatures() []StdSignature
|
||||
}
|
||||
|
||||
var _ Tx = (*StdTx)(nil)
|
||||
|
||||
// StdTx is a standard way to wrap a Msg with Fee and Signatures.
|
||||
// NOTE: the first signature is the FeePayer (Signatures must not be nil).
|
||||
type StdTx struct {
|
||||
Msg `json:"msg"`
|
||||
Fee StdFee `json:"fee"`
|
||||
Signatures []StdSignature `json:"signatures"`
|
||||
}
|
||||
|
||||
func NewStdTx(msg Msg, fee StdFee, sigs []StdSignature) StdTx {
|
||||
return StdTx{
|
||||
Msg: msg,
|
||||
Fee: fee,
|
||||
Signatures: sigs,
|
||||
}
|
||||
}
|
||||
|
||||
//nolint
|
||||
func (tx StdTx) GetMsg() Msg { return tx.Msg }
|
||||
func (tx StdTx) GetSignatures() []StdSignature { return tx.Signatures }
|
||||
|
||||
// FeePayer returns the address responsible for paying the fees
|
||||
// for the transactions. It's the first address returned by msg.GetSigners().
|
||||
// If GetSigners() is empty, this panics.
|
||||
func FeePayer(tx Tx) Address {
|
||||
return tx.GetMsg().GetSigners()[0]
|
||||
}
|
||||
|
||||
//__________________________________________________________
|
||||
|
||||
// StdFee includes the amount of coins paid in fees and the maximum
|
||||
// gas to be used by the transaction. The ratio yields an effective "gasprice",
|
||||
// which must be above some miminum to be accepted into the mempool.
|
||||
type StdFee struct {
|
||||
Amount Coins `json:"amount"`
|
||||
Gas int64 `json:"gas"`
|
||||
}
|
||||
|
||||
func NewStdFee(gas int64, amount ...Coin) StdFee {
|
||||
return StdFee{
|
||||
Amount: amount,
|
||||
Gas: gas,
|
||||
}
|
||||
}
|
||||
|
||||
// fee bytes for signing later
|
||||
func (fee StdFee) Bytes() []byte {
|
||||
// normalize. XXX
|
||||
// this is a sign of something ugly
|
||||
// (in the lcd_test, client side its null,
|
||||
// server side its [])
|
||||
if len(fee.Amount) == 0 {
|
||||
fee.Amount = Coins{}
|
||||
}
|
||||
bz, err := json.Marshal(fee) // TODO
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return bz
|
||||
}
|
||||
|
||||
//__________________________________________________________
|
||||
|
||||
// StdSignDoc is replay-prevention structure.
|
||||
// It includes the result of msg.GetSignBytes(),
|
||||
// as well as the ChainID (prevent cross chain replay)
|
||||
// and the Sequence numbers for each signature (prevent
|
||||
// inchain replay and enforce tx ordering per account).
|
||||
type StdSignDoc struct {
|
||||
ChainID string `json:"chain_id"`
|
||||
Sequences []int64 `json:"sequences"`
|
||||
FeeBytes []byte `json:"fee_bytes"`
|
||||
MsgBytes []byte `json:"msg_bytes"`
|
||||
AltBytes []byte `json:"alt_bytes"`
|
||||
}
|
||||
|
||||
// StdSignBytes returns the bytes to sign for a transaction.
|
||||
// TODO: change the API to just take a chainID and StdTx ?
|
||||
func StdSignBytes(chainID string, sequences []int64, fee StdFee, msg Msg) []byte {
|
||||
bz, err := json.Marshal(StdSignDoc{
|
||||
ChainID: chainID,
|
||||
Sequences: sequences,
|
||||
FeeBytes: fee.Bytes(),
|
||||
MsgBytes: msg.GetSignBytes(),
|
||||
})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return bz
|
||||
}
|
||||
|
||||
// StdSignMsg is a convenience structure for passing along
|
||||
// a Msg with the other requirements for a StdSignDoc before
|
||||
// it is signed. For use in the CLI.
|
||||
type StdSignMsg struct {
|
||||
ChainID string
|
||||
Sequences []int64
|
||||
Fee StdFee
|
||||
Msg Msg
|
||||
// XXX: Alt
|
||||
}
|
||||
|
||||
// get message bytes
|
||||
func (msg StdSignMsg) Bytes() []byte {
|
||||
return StdSignBytes(msg.ChainID, msg.Sequences, msg.Fee, msg.Msg)
|
||||
}
|
||||
|
||||
//__________________________________________________________
|
||||
|
||||
// TxDeocder unmarshals transaction bytes
|
||||
// TxDecoder unmarshals transaction bytes
|
||||
type TxDecoder func(txBytes []byte) (Tx, Error)
|
||||
|
||||
//__________________________________________________________
|
||||
|
|
|
@ -3,16 +3,34 @@ package auth
|
|||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/tendermint/go-crypto"
|
||||
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
"github.com/cosmos/cosmos-sdk/wire"
|
||||
crypto "github.com/tendermint/go-crypto"
|
||||
)
|
||||
|
||||
// Account is a standard account using a sequence number for replay protection
|
||||
// and a pubkey for authentication.
|
||||
type Account interface {
|
||||
GetAddress() sdk.Address
|
||||
SetAddress(sdk.Address) error // errors if already set.
|
||||
|
||||
GetPubKey() crypto.PubKey // can return nil.
|
||||
SetPubKey(crypto.PubKey) error
|
||||
|
||||
GetSequence() int64
|
||||
SetSequence(int64) error
|
||||
|
||||
GetCoins() sdk.Coins
|
||||
SetCoins(sdk.Coins) error
|
||||
}
|
||||
|
||||
// AccountDecoder unmarshals account bytes
|
||||
type AccountDecoder func(accountBytes []byte) (Account, error)
|
||||
|
||||
//-----------------------------------------------------------
|
||||
// BaseAccount
|
||||
|
||||
var _ sdk.Account = (*BaseAccount)(nil)
|
||||
var _ Account = (*BaseAccount)(nil)
|
||||
|
||||
// BaseAccount - base account structure.
|
||||
// Extend this by embedding this in your AppAccount.
|
||||
|
@ -82,7 +100,7 @@ func (acc *BaseAccount) SetSequence(seq int64) error {
|
|||
|
||||
// Most users shouldn't use this, but this comes handy for tests.
|
||||
func RegisterBaseAccount(cdc *wire.Codec) {
|
||||
cdc.RegisterInterface((*sdk.Account)(nil), nil)
|
||||
cdc.RegisterInterface((*Account)(nil), nil)
|
||||
cdc.RegisterConcrete(&BaseAccount{}, "cosmos-sdk/BaseAccount", nil)
|
||||
wire.RegisterCrypto(cdc)
|
||||
}
|
|
@ -18,7 +18,7 @@ func keyPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.Address) {
|
|||
return key, pub, addr
|
||||
}
|
||||
|
||||
func TestBaseAccountAddressPubKey(t *testing.T) {
|
||||
func TestBaseAddressPubKey(t *testing.T) {
|
||||
_, pub1, addr1 := keyPubAddr()
|
||||
_, pub2, addr2 := keyPubAddr()
|
||||
acc := NewBaseAccountWithAddress(addr1)
|
|
@ -9,19 +9,27 @@ import (
|
|||
)
|
||||
|
||||
const (
|
||||
deductFeesCost sdk.Gas = 10
|
||||
verifyCost = 100
|
||||
)
|
||||
|
||||
// NewAnteHandler returns an AnteHandler that checks
|
||||
// and increments sequence numbers, checks signatures,
|
||||
// and deducts fees from the first signer.
|
||||
func NewAnteHandler(am sdk.AccountMapper, feeHandler sdk.FeeHandler) sdk.AnteHandler {
|
||||
func NewAnteHandler(am AccountMapper, fck FeeCollectionKeeper) sdk.AnteHandler {
|
||||
|
||||
return func(
|
||||
ctx sdk.Context, tx sdk.Tx,
|
||||
) (_ sdk.Context, _ sdk.Result, abort bool) {
|
||||
|
||||
// This AnteHandler requires Txs to be StdTxs
|
||||
stdTx, ok := tx.(StdTx)
|
||||
if !ok {
|
||||
return ctx, sdk.ErrInternal("tx must be StdTx").Result(), true
|
||||
}
|
||||
|
||||
// Assert that there are signatures.
|
||||
var sigs = tx.GetSignatures()
|
||||
var sigs = stdTx.GetSignatures()
|
||||
if len(sigs) == 0 {
|
||||
return ctx,
|
||||
sdk.ErrUnauthorized("no signers").Result(),
|
||||
|
@ -30,12 +38,6 @@ func NewAnteHandler(am sdk.AccountMapper, feeHandler sdk.FeeHandler) sdk.AnteHan
|
|||
|
||||
msg := tx.GetMsg()
|
||||
|
||||
// TODO: will this always be a stdtx? should that be used in the function signature?
|
||||
stdTx, ok := tx.(sdk.StdTx)
|
||||
if !ok {
|
||||
return ctx, sdk.ErrInternal("tx must be sdk.StdTx").Result(), true
|
||||
}
|
||||
|
||||
// Assert that number of signatures is correct.
|
||||
var signerAddrs = msg.GetSigners()
|
||||
if len(sigs) != len(signerAddrs) {
|
||||
|
@ -56,10 +58,10 @@ func NewAnteHandler(am sdk.AccountMapper, feeHandler sdk.FeeHandler) sdk.AnteHan
|
|||
if chainID == "" {
|
||||
chainID = viper.GetString("chain-id")
|
||||
}
|
||||
signBytes := sdk.StdSignBytes(ctx.ChainID(), sequences, fee, msg)
|
||||
signBytes := StdSignBytes(ctx.ChainID(), sequences, fee, msg)
|
||||
|
||||
// Check sig and nonce and collect signer accounts.
|
||||
var signerAccs = make([]sdk.Account, len(signerAddrs))
|
||||
var signerAccs = make([]Account, len(signerAddrs))
|
||||
for i := 0; i < len(sigs); i++ {
|
||||
signerAddr, sig := signerAddrs[i], sigs[i]
|
||||
|
||||
|
@ -76,11 +78,12 @@ func NewAnteHandler(am sdk.AccountMapper, feeHandler sdk.FeeHandler) sdk.AnteHan
|
|||
if i == 0 {
|
||||
// TODO: min fee
|
||||
if !fee.Amount.IsZero() {
|
||||
ctx.GasMeter().ConsumeGas(deductFeesCost, "deductFees")
|
||||
signerAcc, res = deductFees(signerAcc, fee)
|
||||
feeHandler(ctx, tx, fee.Amount)
|
||||
if !res.IsOK() {
|
||||
return ctx, res, true
|
||||
}
|
||||
fck.addCollectedFees(ctx, fee.Amount)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -104,9 +107,9 @@ func NewAnteHandler(am sdk.AccountMapper, feeHandler sdk.FeeHandler) sdk.AnteHan
|
|||
// verify the signature and increment the sequence.
|
||||
// if the account doesn't have a pubkey, set it.
|
||||
func processSig(
|
||||
ctx sdk.Context, am sdk.AccountMapper,
|
||||
addr sdk.Address, sig sdk.StdSignature, signBytes []byte) (
|
||||
acc sdk.Account, res sdk.Result) {
|
||||
ctx sdk.Context, am AccountMapper,
|
||||
addr sdk.Address, sig StdSignature, signBytes []byte) (
|
||||
acc Account, res sdk.Result) {
|
||||
|
||||
// Get the account.
|
||||
acc = am.GetAccount(ctx, addr)
|
||||
|
@ -152,7 +155,7 @@ func processSig(
|
|||
// Deduct the fee from the account.
|
||||
// We could use the CoinKeeper (in addition to the AccountMapper,
|
||||
// because the CoinKeeper doesn't give us accounts), but it seems easier to do this.
|
||||
func deductFees(acc sdk.Account, fee sdk.StdFee) (sdk.Account, sdk.Result) {
|
||||
func deductFees(acc Account, fee StdFee) (Account, sdk.Result) {
|
||||
coins := acc.GetCoins()
|
||||
feeAmount := fee.Amount
|
||||
|
||||
|
@ -166,5 +169,4 @@ func deductFees(acc sdk.Account, fee sdk.StdFee) (sdk.Account, sdk.Result) {
|
|||
}
|
||||
|
||||
// BurnFeeHandler burns all fees (decreasing total supply)
|
||||
func BurnFeeHandler(ctx sdk.Context, tx sdk.Tx, fee sdk.Coins) {
|
||||
}
|
||||
func BurnFeeHandler(_ sdk.Context, _ sdk.Tx, _ sdk.Coins) {}
|
||||
|
|
|
@ -17,8 +17,8 @@ func newTestMsg(addrs ...sdk.Address) *sdk.TestMsg {
|
|||
return sdk.NewTestMsg(addrs...)
|
||||
}
|
||||
|
||||
func newStdFee() sdk.StdFee {
|
||||
return sdk.NewStdFee(100,
|
||||
func newStdFee() StdFee {
|
||||
return NewStdFee(100,
|
||||
sdk.Coin{"atom", 150},
|
||||
)
|
||||
}
|
||||
|
@ -52,28 +52,29 @@ func checkInvalidTx(t *testing.T, anteHandler sdk.AnteHandler, ctx sdk.Context,
|
|||
assert.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, code), result.Code)
|
||||
}
|
||||
|
||||
func newTestTx(ctx sdk.Context, msg sdk.Msg, privs []crypto.PrivKey, seqs []int64, fee sdk.StdFee) sdk.Tx {
|
||||
signBytes := sdk.StdSignBytes(ctx.ChainID(), seqs, fee, msg)
|
||||
func newTestTx(ctx sdk.Context, msg sdk.Msg, privs []crypto.PrivKey, seqs []int64, fee StdFee) sdk.Tx {
|
||||
signBytes := StdSignBytes(ctx.ChainID(), seqs, fee, msg)
|
||||
return newTestTxWithSignBytes(msg, privs, seqs, fee, signBytes)
|
||||
}
|
||||
|
||||
func newTestTxWithSignBytes(msg sdk.Msg, privs []crypto.PrivKey, seqs []int64, fee sdk.StdFee, signBytes []byte) sdk.Tx {
|
||||
sigs := make([]sdk.StdSignature, len(privs))
|
||||
func newTestTxWithSignBytes(msg sdk.Msg, privs []crypto.PrivKey, seqs []int64, fee StdFee, signBytes []byte) sdk.Tx {
|
||||
sigs := make([]StdSignature, len(privs))
|
||||
for i, priv := range privs {
|
||||
sigs[i] = sdk.StdSignature{PubKey: priv.PubKey(), Signature: priv.Sign(signBytes), Sequence: seqs[i]}
|
||||
sigs[i] = StdSignature{PubKey: priv.PubKey(), Signature: priv.Sign(signBytes), Sequence: seqs[i]}
|
||||
}
|
||||
tx := sdk.NewStdTx(msg, fee, sigs)
|
||||
tx := NewStdTx(msg, fee, sigs)
|
||||
return tx
|
||||
}
|
||||
|
||||
// Test various error cases in the AnteHandler control flow.
|
||||
func TestAnteHandlerSigErrors(t *testing.T) {
|
||||
// setup
|
||||
ms, capKey := setupMultiStore()
|
||||
ms, capKey, capKey2 := setupMultiStore()
|
||||
cdc := wire.NewCodec()
|
||||
RegisterBaseAccount(cdc)
|
||||
mapper := NewAccountMapper(cdc, capKey, &BaseAccount{})
|
||||
anteHandler := NewAnteHandler(mapper, BurnFeeHandler)
|
||||
feeCollector := NewFeeCollectionKeeper(cdc, capKey2)
|
||||
anteHandler := NewAnteHandler(mapper, feeCollector)
|
||||
ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, nil, log.NewNopLogger())
|
||||
|
||||
// keys and addresses
|
||||
|
@ -110,11 +111,12 @@ func TestAnteHandlerSigErrors(t *testing.T) {
|
|||
// Test logic around sequence checking with one signer and many signers.
|
||||
func TestAnteHandlerSequences(t *testing.T) {
|
||||
// setup
|
||||
ms, capKey := setupMultiStore()
|
||||
ms, capKey, capKey2 := setupMultiStore()
|
||||
cdc := wire.NewCodec()
|
||||
RegisterBaseAccount(cdc)
|
||||
mapper := NewAccountMapper(cdc, capKey, &BaseAccount{})
|
||||
anteHandler := NewAnteHandler(mapper, BurnFeeHandler)
|
||||
feeCollector := NewFeeCollectionKeeper(cdc, capKey2)
|
||||
anteHandler := NewAnteHandler(mapper, feeCollector)
|
||||
ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, nil, log.NewNopLogger())
|
||||
|
||||
// keys and addresses
|
||||
|
@ -176,11 +178,12 @@ func TestAnteHandlerSequences(t *testing.T) {
|
|||
// Test logic around fee deduction.
|
||||
func TestAnteHandlerFees(t *testing.T) {
|
||||
// setup
|
||||
ms, capKey := setupMultiStore()
|
||||
ms, capKey, capKey2 := setupMultiStore()
|
||||
cdc := wire.NewCodec()
|
||||
RegisterBaseAccount(cdc)
|
||||
mapper := NewAccountMapper(cdc, capKey, &BaseAccount{})
|
||||
anteHandler := NewAnteHandler(mapper, BurnFeeHandler)
|
||||
feeCollector := NewFeeCollectionKeeper(cdc, capKey2)
|
||||
anteHandler := NewAnteHandler(mapper, feeCollector)
|
||||
ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, nil, log.NewNopLogger())
|
||||
|
||||
// keys and addresses
|
||||
|
@ -194,7 +197,7 @@ func TestAnteHandlerFees(t *testing.T) {
|
|||
var tx sdk.Tx
|
||||
msg := newTestMsg(addr1)
|
||||
privs, seqs := []crypto.PrivKey{priv1}, []int64{0}
|
||||
fee := sdk.NewStdFee(100,
|
||||
fee := NewStdFee(100,
|
||||
sdk.Coin{"atom", 150},
|
||||
)
|
||||
|
||||
|
@ -206,18 +209,23 @@ func TestAnteHandlerFees(t *testing.T) {
|
|||
mapper.SetAccount(ctx, acc1)
|
||||
checkInvalidTx(t, anteHandler, ctx, tx, sdk.CodeInsufficientFunds)
|
||||
|
||||
assert.True(t, feeCollector.GetCollectedFees(ctx).IsEqual(emptyCoins))
|
||||
|
||||
acc1.SetCoins(sdk.Coins{{"atom", 150}})
|
||||
mapper.SetAccount(ctx, acc1)
|
||||
checkValidTx(t, anteHandler, ctx, tx)
|
||||
|
||||
assert.True(t, feeCollector.GetCollectedFees(ctx).IsEqual(sdk.Coins{{"atom", 150}}))
|
||||
}
|
||||
|
||||
func TestAnteHandlerBadSignBytes(t *testing.T) {
|
||||
// setup
|
||||
ms, capKey := setupMultiStore()
|
||||
ms, capKey, capKey2 := setupMultiStore()
|
||||
cdc := wire.NewCodec()
|
||||
RegisterBaseAccount(cdc)
|
||||
mapper := NewAccountMapper(cdc, capKey, &BaseAccount{})
|
||||
anteHandler := NewAnteHandler(mapper, BurnFeeHandler)
|
||||
feeCollector := NewFeeCollectionKeeper(cdc, capKey2)
|
||||
anteHandler := NewAnteHandler(mapper, feeCollector)
|
||||
ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, nil, log.NewNopLogger())
|
||||
|
||||
// keys and addresses
|
||||
|
@ -252,7 +260,7 @@ func TestAnteHandlerBadSignBytes(t *testing.T) {
|
|||
cases := []struct {
|
||||
chainID string
|
||||
seqs []int64
|
||||
fee sdk.StdFee
|
||||
fee StdFee
|
||||
msg sdk.Msg
|
||||
code sdk.CodeType
|
||||
}{
|
||||
|
@ -268,7 +276,7 @@ func TestAnteHandlerBadSignBytes(t *testing.T) {
|
|||
for _, cs := range cases {
|
||||
tx := newTestTxWithSignBytes(
|
||||
msg, privs, seqs, fee,
|
||||
sdk.StdSignBytes(cs.chainID, cs.seqs, cs.fee, cs.msg),
|
||||
StdSignBytes(cs.chainID, cs.seqs, cs.fee, cs.msg),
|
||||
)
|
||||
checkInvalidTx(t, anteHandler, ctx, tx, cs.code)
|
||||
}
|
||||
|
@ -288,11 +296,12 @@ func TestAnteHandlerBadSignBytes(t *testing.T) {
|
|||
|
||||
func TestAnteHandlerSetPubKey(t *testing.T) {
|
||||
// setup
|
||||
ms, capKey := setupMultiStore()
|
||||
ms, capKey, capKey2 := setupMultiStore()
|
||||
cdc := wire.NewCodec()
|
||||
RegisterBaseAccount(cdc)
|
||||
mapper := NewAccountMapper(cdc, capKey, &BaseAccount{})
|
||||
anteHandler := NewAnteHandler(mapper, BurnFeeHandler)
|
||||
feeCollector := NewFeeCollectionKeeper(cdc, capKey2)
|
||||
anteHandler := NewAnteHandler(mapper, feeCollector)
|
||||
ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, nil, log.NewNopLogger())
|
||||
|
||||
// keys and addresses
|
||||
|
@ -322,7 +331,7 @@ func TestAnteHandlerSetPubKey(t *testing.T) {
|
|||
// test public key not found
|
||||
msg = newTestMsg(addr2)
|
||||
tx = newTestTx(ctx, msg, privs, seqs, fee)
|
||||
sigs := tx.GetSignatures()
|
||||
sigs := tx.(StdTx).GetSignatures()
|
||||
sigs[0].PubKey = nil
|
||||
checkInvalidTx(t, anteHandler, ctx, tx, sdk.CodeInvalidPubKey)
|
||||
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
package cli
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
@ -9,6 +8,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"
|
||||
)
|
||||
|
||||
// GetAccountCmd for the auth.BaseAccount type
|
||||
|
@ -17,8 +17,8 @@ func GetAccountCmdDefault(storeName string, cdc *wire.Codec) *cobra.Command {
|
|||
}
|
||||
|
||||
// Get account decoder for auth.DefaultAccount
|
||||
func GetAccountDecoder(cdc *wire.Codec) sdk.AccountDecoder {
|
||||
return func(accBytes []byte) (acct sdk.Account, err error) {
|
||||
func GetAccountDecoder(cdc *wire.Codec) auth.AccountDecoder {
|
||||
return func(accBytes []byte) (acct auth.Account, err error) {
|
||||
// acct := new(auth.BaseAccount)
|
||||
err = cdc.UnmarshalBinaryBare(accBytes, &acct)
|
||||
if err != nil {
|
||||
|
@ -30,7 +30,7 @@ func GetAccountDecoder(cdc *wire.Codec) sdk.AccountDecoder {
|
|||
|
||||
// GetAccountCmd returns a query account that will display the
|
||||
// state of the account at a given address
|
||||
func GetAccountCmd(storeName string, cdc *wire.Codec, decoder sdk.AccountDecoder) *cobra.Command {
|
||||
func GetAccountCmd(storeName string, cdc *wire.Codec, decoder auth.AccountDecoder) *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "account [address]",
|
||||
Short: "Query account balance",
|
||||
|
@ -39,11 +39,11 @@ func GetAccountCmd(storeName string, cdc *wire.Codec, decoder sdk.AccountDecoder
|
|||
|
||||
// find the key to look up the account
|
||||
addr := args[0]
|
||||
bz, err := hex.DecodeString(addr)
|
||||
|
||||
key, err := sdk.GetAccAddressBech32Cosmos(addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
key := sdk.Address(bz)
|
||||
|
||||
// perform query
|
||||
ctx := context.NewCoreContextFromViper()
|
||||
|
|
|
@ -10,19 +10,20 @@ import (
|
|||
"github.com/cosmos/cosmos-sdk/client/context"
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
"github.com/cosmos/cosmos-sdk/wire"
|
||||
auth "github.com/cosmos/cosmos-sdk/x/auth/client/cli"
|
||||
"github.com/cosmos/cosmos-sdk/x/auth"
|
||||
authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli"
|
||||
)
|
||||
|
||||
// register REST routes
|
||||
func RegisterRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec, storeName string) {
|
||||
r.HandleFunc(
|
||||
"/accounts/{address}",
|
||||
QueryAccountRequestHandlerFn(storeName, cdc, auth.GetAccountDecoder(cdc), ctx),
|
||||
QueryAccountRequestHandlerFn(storeName, cdc, authcmd.GetAccountDecoder(cdc), ctx),
|
||||
).Methods("GET")
|
||||
}
|
||||
|
||||
// query accountREST Handler
|
||||
func QueryAccountRequestHandlerFn(storeName string, cdc *wire.Codec, decoder sdk.AccountDecoder, ctx context.CoreContext) http.HandlerFunc {
|
||||
func QueryAccountRequestHandlerFn(storeName string, cdc *wire.Codec, decoder auth.AccountDecoder, ctx context.CoreContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
addr := vars["address"]
|
||||
|
|
|
@ -34,15 +34,15 @@ const (
|
|||
)
|
||||
|
||||
// add the signers to the context
|
||||
func WithSigners(ctx types.Context, accounts []types.Account) types.Context {
|
||||
func WithSigners(ctx types.Context, accounts []Account) types.Context {
|
||||
return ctx.WithValue(contextKeySigners, accounts)
|
||||
}
|
||||
|
||||
// get the signers from the context
|
||||
func GetSigners(ctx types.Context) []types.Account {
|
||||
func GetSigners(ctx types.Context) []Account {
|
||||
v := ctx.Value(contextKeySigners)
|
||||
if v == nil {
|
||||
return []types.Account{}
|
||||
return []Account{}
|
||||
}
|
||||
return v.([]types.Account)
|
||||
return v.([]Account)
|
||||
}
|
||||
|
|
|
@ -12,7 +12,7 @@ import (
|
|||
)
|
||||
|
||||
func TestContextWithSigners(t *testing.T) {
|
||||
ms, _ := setupMultiStore()
|
||||
ms, _, _ := setupMultiStore()
|
||||
ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, nil, log.NewNopLogger())
|
||||
|
||||
_, _, addr1 := keyPubAddr()
|
||||
|
@ -26,7 +26,7 @@ func TestContextWithSigners(t *testing.T) {
|
|||
signers := GetSigners(ctx)
|
||||
assert.Equal(t, 0, len(signers))
|
||||
|
||||
ctx2 := WithSigners(ctx, []sdk.Account{&acc1, &acc2})
|
||||
ctx2 := WithSigners(ctx, []Account{&acc1, &acc2})
|
||||
|
||||
// original context is unchanged
|
||||
signers = GetSigners(ctx)
|
||||
|
|
|
@ -0,0 +1,62 @@
|
|||
package auth
|
||||
|
||||
import (
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
wire "github.com/cosmos/cosmos-sdk/wire"
|
||||
)
|
||||
|
||||
var (
|
||||
collectedFeesKey = []byte("collectedFees")
|
||||
)
|
||||
|
||||
// This FeeCollectionKeeper handles collection of fees in the anteHandler
|
||||
// and setting of MinFees for different fee tokens
|
||||
type FeeCollectionKeeper struct {
|
||||
|
||||
// The (unexposed) key used to access the fee store from the Context.
|
||||
key sdk.StoreKey
|
||||
|
||||
// The wire codec for binary encoding/decoding of accounts.
|
||||
cdc *wire.Codec
|
||||
}
|
||||
|
||||
// NewFeeKeeper returns a new FeeKeeper
|
||||
func NewFeeCollectionKeeper(cdc *wire.Codec, key sdk.StoreKey) FeeCollectionKeeper {
|
||||
return FeeCollectionKeeper{
|
||||
key: key,
|
||||
cdc: cdc,
|
||||
}
|
||||
}
|
||||
|
||||
// Adds to Collected Fee Pool
|
||||
func (fck FeeCollectionKeeper) GetCollectedFees(ctx sdk.Context) sdk.Coins {
|
||||
store := ctx.KVStore(fck.key)
|
||||
bz := store.Get(collectedFeesKey)
|
||||
if bz == nil {
|
||||
return sdk.Coins{}
|
||||
}
|
||||
|
||||
feePool := &(sdk.Coins{})
|
||||
fck.cdc.MustUnmarshalBinary(bz, feePool)
|
||||
return *feePool
|
||||
}
|
||||
|
||||
// Sets to Collected Fee Pool
|
||||
func (fck FeeCollectionKeeper) setCollectedFees(ctx sdk.Context, coins sdk.Coins) {
|
||||
bz := fck.cdc.MustMarshalBinary(coins)
|
||||
store := ctx.KVStore(fck.key)
|
||||
store.Set(collectedFeesKey, bz)
|
||||
}
|
||||
|
||||
// Adds to Collected Fee Pool
|
||||
func (fck FeeCollectionKeeper) addCollectedFees(ctx sdk.Context, coins sdk.Coins) sdk.Coins {
|
||||
newCoins := fck.GetCollectedFees(ctx).Plus(coins)
|
||||
fck.setCollectedFees(ctx, newCoins)
|
||||
|
||||
return newCoins
|
||||
}
|
||||
|
||||
// Clears the collected Fee Pool
|
||||
func (fck FeeCollectionKeeper) ClearCollectedFees(ctx sdk.Context) {
|
||||
fck.setCollectedFees(ctx, sdk.Coins{})
|
||||
}
|
|
@ -0,0 +1,75 @@
|
|||
package auth
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
abci "github.com/tendermint/abci/types"
|
||||
"github.com/tendermint/tmlibs/log"
|
||||
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
wire "github.com/cosmos/cosmos-sdk/wire"
|
||||
)
|
||||
|
||||
var (
|
||||
emptyCoins = sdk.Coins{}
|
||||
oneCoin = sdk.Coins{{"foocoin", 1}}
|
||||
twoCoins = sdk.Coins{{"foocoin", 2}}
|
||||
)
|
||||
|
||||
func TestFeeCollectionKeeperGetSet(t *testing.T) {
|
||||
ms, _, capKey2 := setupMultiStore()
|
||||
cdc := wire.NewCodec()
|
||||
|
||||
// make context and keeper
|
||||
ctx := sdk.NewContext(ms, abci.Header{}, false, nil, log.NewNopLogger())
|
||||
fck := NewFeeCollectionKeeper(cdc, capKey2)
|
||||
|
||||
// no coins initially
|
||||
currFees := fck.GetCollectedFees(ctx)
|
||||
assert.True(t, currFees.IsEqual(emptyCoins))
|
||||
|
||||
// set feeCollection to oneCoin
|
||||
fck.setCollectedFees(ctx, oneCoin)
|
||||
|
||||
// check that it is equal to oneCoin
|
||||
assert.True(t, fck.GetCollectedFees(ctx).IsEqual(oneCoin))
|
||||
}
|
||||
|
||||
func TestFeeCollectionKeeperAdd(t *testing.T) {
|
||||
ms, _, capKey2 := setupMultiStore()
|
||||
cdc := wire.NewCodec()
|
||||
|
||||
// make context and keeper
|
||||
ctx := sdk.NewContext(ms, abci.Header{}, false, nil, log.NewNopLogger())
|
||||
fck := NewFeeCollectionKeeper(cdc, capKey2)
|
||||
|
||||
// no coins initially
|
||||
assert.True(t, fck.GetCollectedFees(ctx).IsEqual(emptyCoins))
|
||||
|
||||
// add oneCoin and check that pool is now oneCoin
|
||||
fck.addCollectedFees(ctx, oneCoin)
|
||||
assert.True(t, fck.GetCollectedFees(ctx).IsEqual(oneCoin))
|
||||
|
||||
// add oneCoin again and check that pool is now twoCoins
|
||||
fck.addCollectedFees(ctx, oneCoin)
|
||||
assert.True(t, fck.GetCollectedFees(ctx).IsEqual(twoCoins))
|
||||
}
|
||||
|
||||
func TestFeeCollectionKeeperClear(t *testing.T) {
|
||||
ms, _, capKey2 := setupMultiStore()
|
||||
cdc := wire.NewCodec()
|
||||
|
||||
// make context and keeper
|
||||
ctx := sdk.NewContext(ms, abci.Header{}, false, nil, log.NewNopLogger())
|
||||
fck := NewFeeCollectionKeeper(cdc, capKey2)
|
||||
|
||||
// set coins initially
|
||||
fck.setCollectedFees(ctx, twoCoins)
|
||||
assert.True(t, fck.GetCollectedFees(ctx).IsEqual(twoCoins))
|
||||
|
||||
// clear fees and see that pool is now empty
|
||||
fck.ClearCollectedFees(ctx)
|
||||
assert.True(t, fck.GetCollectedFees(ctx).IsEqual(emptyCoins))
|
||||
}
|
|
@ -6,14 +6,14 @@ import (
|
|||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
)
|
||||
|
||||
// NewHandler returns a handler for "auth" type messages.
|
||||
// NewHandler returns a handler for "baseaccount" type messages.
|
||||
func NewHandler(am AccountMapper) sdk.Handler {
|
||||
return func(ctx sdk.Context, msg sdk.Msg) sdk.Result {
|
||||
switch msg := msg.(type) {
|
||||
case MsgChangeKey:
|
||||
return handleMsgChangeKey(ctx, am, msg)
|
||||
default:
|
||||
errMsg := "Unrecognized auth Msg type: " + reflect.TypeOf(msg).Name()
|
||||
errMsg := "Unrecognized baseaccount Msg type: " + reflect.TypeOf(msg).Name()
|
||||
return sdk.ErrUnknownRequest(errMsg).Result()
|
||||
}
|
||||
}
|
||||
|
@ -23,7 +23,7 @@ func NewHandler(am AccountMapper) sdk.Handler {
|
|||
// Should be very expensive, because once this happens, an account is un-prunable
|
||||
func handleMsgChangeKey(ctx sdk.Context, am AccountMapper, msg MsgChangeKey) sdk.Result {
|
||||
|
||||
err := am.setPubKey(ctx, msg.Address, msg.NewPubKey)
|
||||
err := am.SetPubKey(ctx, msg.Address, msg.NewPubKey)
|
||||
if err != nil {
|
||||
return err.Result()
|
||||
}
|
||||
|
|
|
@ -9,9 +9,6 @@ import (
|
|||
crypto "github.com/tendermint/go-crypto"
|
||||
)
|
||||
|
||||
var _ sdk.AccountMapper = (*AccountMapper)(nil)
|
||||
|
||||
// Implements sdk.AccountMapper.
|
||||
// This AccountMapper encodes/decodes accounts using the
|
||||
// go-amino (binary) encoding/decoding library.
|
||||
type AccountMapper struct {
|
||||
|
@ -19,8 +16,8 @@ type AccountMapper struct {
|
|||
// The (unexposed) key used to access the store from the Context.
|
||||
key sdk.StoreKey
|
||||
|
||||
// The prototypical sdk.Account concrete type.
|
||||
proto sdk.Account
|
||||
// The prototypical Account concrete type.
|
||||
proto Account
|
||||
|
||||
// The wire codec for binary encoding/decoding of accounts.
|
||||
cdc *wire.Codec
|
||||
|
@ -29,7 +26,7 @@ type AccountMapper struct {
|
|||
// NewAccountMapper returns a new sdk.AccountMapper that
|
||||
// uses go-amino to (binary) encode and decode concrete sdk.Accounts.
|
||||
// nolint
|
||||
func NewAccountMapper(cdc *wire.Codec, key sdk.StoreKey, proto sdk.Account) AccountMapper {
|
||||
func NewAccountMapper(cdc *wire.Codec, key sdk.StoreKey, proto Account) AccountMapper {
|
||||
return AccountMapper{
|
||||
key: key,
|
||||
proto: proto,
|
||||
|
@ -38,14 +35,14 @@ func NewAccountMapper(cdc *wire.Codec, key sdk.StoreKey, proto sdk.Account) Acco
|
|||
}
|
||||
|
||||
// Implaements sdk.AccountMapper.
|
||||
func (am AccountMapper) NewAccountWithAddress(ctx sdk.Context, addr sdk.Address) sdk.Account {
|
||||
func (am AccountMapper) NewAccountWithAddress(ctx sdk.Context, addr sdk.Address) Account {
|
||||
acc := am.clonePrototype()
|
||||
acc.SetAddress(addr)
|
||||
return acc
|
||||
}
|
||||
|
||||
// Implements sdk.AccountMapper.
|
||||
func (am AccountMapper) GetAccount(ctx sdk.Context, addr sdk.Address) sdk.Account {
|
||||
func (am AccountMapper) GetAccount(ctx sdk.Context, addr sdk.Address) Account {
|
||||
store := ctx.KVStore(am.key)
|
||||
bz := store.Get(addr)
|
||||
if bz == nil {
|
||||
|
@ -56,7 +53,7 @@ func (am AccountMapper) GetAccount(ctx sdk.Context, addr sdk.Address) sdk.Accoun
|
|||
}
|
||||
|
||||
// Implements sdk.AccountMapper.
|
||||
func (am AccountMapper) SetAccount(ctx sdk.Context, acc sdk.Account) {
|
||||
func (am AccountMapper) SetAccount(ctx sdk.Context, acc Account) {
|
||||
addr := acc.GetAddress()
|
||||
store := ctx.KVStore(am.key)
|
||||
bz := am.encodeAccount(acc)
|
||||
|
@ -64,7 +61,7 @@ func (am AccountMapper) SetAccount(ctx sdk.Context, acc sdk.Account) {
|
|||
}
|
||||
|
||||
// Implements sdk.AccountMapper.
|
||||
func (am AccountMapper) IterateAccounts(ctx sdk.Context, process func(sdk.Account) (stop bool)) {
|
||||
func (am AccountMapper) IterateAccounts(ctx sdk.Context, process func(Account) (stop bool)) {
|
||||
store := ctx.KVStore(am.key)
|
||||
iter := store.Iterator(nil, nil)
|
||||
for {
|
||||
|
@ -89,7 +86,8 @@ func (am AccountMapper) GetPubKey(ctx sdk.Context, addr sdk.Address) (crypto.Pub
|
|||
return acc.GetPubKey(), nil
|
||||
}
|
||||
|
||||
func (am AccountMapper) setPubKey(ctx sdk.Context, addr sdk.Address, newPubKey crypto.PubKey) sdk.Error {
|
||||
// Sets the PubKey of the account at address
|
||||
func (am AccountMapper) SetPubKey(ctx sdk.Context, addr sdk.Address, newPubKey crypto.PubKey) sdk.Error {
|
||||
acc := am.GetAccount(ctx, addr)
|
||||
if acc == nil {
|
||||
return sdk.ErrUnknownAddress(addr.String())
|
||||
|
@ -122,7 +120,7 @@ func (am AccountMapper) setSequence(ctx sdk.Context, addr sdk.Address, newSequen
|
|||
// misc.
|
||||
|
||||
// Creates a new struct (or pointer to struct) from am.proto.
|
||||
func (am AccountMapper) clonePrototype() sdk.Account {
|
||||
func (am AccountMapper) clonePrototype() Account {
|
||||
protoRt := reflect.TypeOf(am.proto)
|
||||
if protoRt.Kind() == reflect.Ptr {
|
||||
protoCrt := protoRt.Elem()
|
||||
|
@ -130,7 +128,7 @@ func (am AccountMapper) clonePrototype() sdk.Account {
|
|||
panic("accountMapper requires a struct proto sdk.Account, or a pointer to one")
|
||||
}
|
||||
protoRv := reflect.New(protoCrt)
|
||||
clone, ok := protoRv.Interface().(sdk.Account)
|
||||
clone, ok := protoRv.Interface().(Account)
|
||||
if !ok {
|
||||
panic(fmt.Sprintf("accountMapper requires a proto sdk.Account, but %v doesn't implement sdk.Account", protoRt))
|
||||
}
|
||||
|
@ -138,14 +136,14 @@ func (am AccountMapper) clonePrototype() sdk.Account {
|
|||
}
|
||||
|
||||
protoRv := reflect.New(protoRt).Elem()
|
||||
clone, ok := protoRv.Interface().(sdk.Account)
|
||||
clone, ok := protoRv.Interface().(Account)
|
||||
if !ok {
|
||||
panic(fmt.Sprintf("accountMapper requires a proto sdk.Account, but %v doesn't implement sdk.Account", protoRt))
|
||||
}
|
||||
return clone
|
||||
}
|
||||
|
||||
func (am AccountMapper) encodeAccount(acc sdk.Account) []byte {
|
||||
func (am AccountMapper) encodeAccount(acc Account) []byte {
|
||||
bz, err := am.cdc.MarshalBinaryBare(acc)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
|
@ -153,7 +151,7 @@ func (am AccountMapper) encodeAccount(acc sdk.Account) []byte {
|
|||
return bz
|
||||
}
|
||||
|
||||
func (am AccountMapper) decodeAccount(bz []byte) (acc sdk.Account) {
|
||||
func (am AccountMapper) decodeAccount(bz []byte) (acc Account) {
|
||||
err := am.cdc.UnmarshalBinaryBare(bz, &acc)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
|
|
|
@ -14,17 +14,19 @@ import (
|
|||
wire "github.com/cosmos/cosmos-sdk/wire"
|
||||
)
|
||||
|
||||
func setupMultiStore() (sdk.MultiStore, *sdk.KVStoreKey) {
|
||||
func setupMultiStore() (sdk.MultiStore, *sdk.KVStoreKey, *sdk.KVStoreKey) {
|
||||
db := dbm.NewMemDB()
|
||||
capKey := sdk.NewKVStoreKey("capkey")
|
||||
capKey2 := sdk.NewKVStoreKey("capkey2")
|
||||
ms := store.NewCommitMultiStore(db)
|
||||
ms.MountStoreWithDB(capKey, sdk.StoreTypeIAVL, db)
|
||||
ms.MountStoreWithDB(capKey2, sdk.StoreTypeIAVL, db)
|
||||
ms.LoadLatestVersion()
|
||||
return ms, capKey
|
||||
return ms, capKey, capKey2
|
||||
}
|
||||
|
||||
func TestAccountMapperGetSet(t *testing.T) {
|
||||
ms, capKey := setupMultiStore()
|
||||
ms, capKey, _ := setupMultiStore()
|
||||
cdc := wire.NewCodec()
|
||||
RegisterBaseAccount(cdc)
|
||||
|
||||
|
|
|
@ -3,9 +3,8 @@ package auth
|
|||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/tendermint/go-crypto"
|
||||
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
crypto "github.com/tendermint/go-crypto"
|
||||
)
|
||||
|
||||
// MsgChangeKey - high level transaction of the auth module
|
||||
|
|
|
@ -0,0 +1,131 @@
|
|||
package auth
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
crypto "github.com/tendermint/go-crypto"
|
||||
)
|
||||
|
||||
var _ sdk.Tx = (*StdTx)(nil)
|
||||
|
||||
// StdTx is a standard way to wrap a Msg with Fee and Signatures.
|
||||
// NOTE: the first signature is the FeePayer (Signatures must not be nil).
|
||||
type StdTx struct {
|
||||
Msg sdk.Msg `json:"msg"`
|
||||
Fee StdFee `json:"fee"`
|
||||
Signatures []StdSignature `json:"signatures"`
|
||||
}
|
||||
|
||||
func NewStdTx(msg sdk.Msg, fee StdFee, sigs []StdSignature) StdTx {
|
||||
return StdTx{
|
||||
Msg: msg,
|
||||
Fee: fee,
|
||||
Signatures: sigs,
|
||||
}
|
||||
}
|
||||
|
||||
//nolint
|
||||
func (tx StdTx) GetMsg() sdk.Msg { return tx.Msg }
|
||||
|
||||
// Signatures returns the signature of signers who signed the Msg.
|
||||
// CONTRACT: Length returned is same as length of
|
||||
// pubkeys returned from MsgKeySigners, and the order
|
||||
// matches.
|
||||
// CONTRACT: If the signature is missing (ie the Msg is
|
||||
// invalid), then the corresponding signature is
|
||||
// .Empty().
|
||||
func (tx StdTx) GetSignatures() []StdSignature { return tx.Signatures }
|
||||
|
||||
// FeePayer returns the address responsible for paying the fees
|
||||
// for the transactions. It's the first address returned by msg.GetSigners().
|
||||
// If GetSigners() is empty, this panics.
|
||||
func FeePayer(tx sdk.Tx) sdk.Address {
|
||||
return tx.GetMsg().GetSigners()[0]
|
||||
}
|
||||
|
||||
//__________________________________________________________
|
||||
|
||||
// StdFee includes the amount of coins paid in fees and the maximum
|
||||
// gas to be used by the transaction. The ratio yields an effective "gasprice",
|
||||
// which must be above some miminum to be accepted into the mempool.
|
||||
type StdFee struct {
|
||||
Amount sdk.Coins `json:"amount"`
|
||||
Gas int64 `json:"gas"`
|
||||
}
|
||||
|
||||
func NewStdFee(gas int64, amount ...sdk.Coin) StdFee {
|
||||
return StdFee{
|
||||
Amount: amount,
|
||||
Gas: gas,
|
||||
}
|
||||
}
|
||||
|
||||
// fee bytes for signing later
|
||||
func (fee StdFee) Bytes() []byte {
|
||||
// normalize. XXX
|
||||
// this is a sign of something ugly
|
||||
// (in the lcd_test, client side its null,
|
||||
// server side its [])
|
||||
if len(fee.Amount) == 0 {
|
||||
fee.Amount = sdk.Coins{}
|
||||
}
|
||||
bz, err := json.Marshal(fee) // TODO
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return bz
|
||||
}
|
||||
|
||||
//__________________________________________________________
|
||||
|
||||
// StdSignDoc is replay-prevention structure.
|
||||
// It includes the result of msg.GetSignBytes(),
|
||||
// as well as the ChainID (prevent cross chain replay)
|
||||
// and the Sequence numbers for each signature (prevent
|
||||
// inchain replay and enforce tx ordering per account).
|
||||
type StdSignDoc struct {
|
||||
ChainID string `json:"chain_id"`
|
||||
Sequences []int64 `json:"sequences"`
|
||||
FeeBytes []byte `json:"fee_bytes"`
|
||||
MsgBytes []byte `json:"msg_bytes"`
|
||||
AltBytes []byte `json:"alt_bytes"`
|
||||
}
|
||||
|
||||
// StdSignBytes returns the bytes to sign for a transaction.
|
||||
// TODO: change the API to just take a chainID and StdTx ?
|
||||
func StdSignBytes(chainID string, sequences []int64, fee StdFee, msg sdk.Msg) []byte {
|
||||
bz, err := json.Marshal(StdSignDoc{
|
||||
ChainID: chainID,
|
||||
Sequences: sequences,
|
||||
FeeBytes: fee.Bytes(),
|
||||
MsgBytes: msg.GetSignBytes(),
|
||||
})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return bz
|
||||
}
|
||||
|
||||
// StdSignMsg is a convenience structure for passing along
|
||||
// a Msg with the other requirements for a StdSignDoc before
|
||||
// it is signed. For use in the CLI.
|
||||
type StdSignMsg struct {
|
||||
ChainID string
|
||||
Sequences []int64
|
||||
Fee StdFee
|
||||
Msg sdk.Msg
|
||||
// XXX: Alt
|
||||
}
|
||||
|
||||
// get message bytes
|
||||
func (msg StdSignMsg) Bytes() []byte {
|
||||
return StdSignBytes(msg.ChainID, msg.Sequences, msg.Fee, msg.Msg)
|
||||
}
|
||||
|
||||
// Standard Signature
|
||||
type StdSignature struct {
|
||||
crypto.PubKey `json:"pub_key"` // optional
|
||||
crypto.Signature `json:"signature"`
|
||||
Sequence int64 `json:"sequence"`
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package types
|
||||
package auth
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
@ -6,18 +6,20 @@ import (
|
|||
"github.com/stretchr/testify/assert"
|
||||
|
||||
crypto "github.com/tendermint/go-crypto"
|
||||
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
)
|
||||
|
||||
func newStdFee() StdFee {
|
||||
return NewStdFee(100,
|
||||
Coin{"atom", 150},
|
||||
)
|
||||
}
|
||||
// func newStdFee() StdFee {
|
||||
// return NewStdFee(100,
|
||||
// Coin{"atom", 150},
|
||||
// )
|
||||
// }
|
||||
|
||||
func TestStdTx(t *testing.T) {
|
||||
priv := crypto.GenPrivKeyEd25519()
|
||||
addr := priv.PubKey().Address()
|
||||
msg := NewTestMsg(addr)
|
||||
msg := sdk.NewTestMsg(addr)
|
||||
fee := newStdFee()
|
||||
sigs := []StdSignature{}
|
||||
|
|
@ -1,12 +1,12 @@
|
|||
package auth
|
||||
|
||||
import (
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
"github.com/cosmos/cosmos-sdk/wire"
|
||||
)
|
||||
|
||||
// Register concrete types on wire codec for default AppAccount
|
||||
func RegisterWire(cdc *wire.Codec) {
|
||||
cdc.RegisterInterface((*sdk.Account)(nil), nil)
|
||||
cdc.RegisterInterface((*Account)(nil), nil)
|
||||
cdc.RegisterConcrete(&BaseAccount{}, "auth/Account", nil)
|
||||
cdc.RegisterConcrete(MsgChangeKey{}, "auth/ChangeKey", nil)
|
||||
}
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
package cli
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
@ -34,12 +33,11 @@ func SendTxCmd(cdc *wire.Codec) *cobra.Command {
|
|||
}
|
||||
|
||||
toStr := viper.GetString(flagTo)
|
||||
bz, err := hex.DecodeString(toStr)
|
||||
|
||||
to, err := sdk.GetAccAddressBech32Cosmos(toStr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
to := sdk.Address(bz)
|
||||
|
||||
// parse coins
|
||||
amount := viper.GetString(flagAmount)
|
||||
coins, err := sdk.ParseCoins(amount)
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
package rest
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
|
@ -58,13 +57,12 @@ func SendRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreCont
|
|||
return
|
||||
}
|
||||
|
||||
bz, err := hex.DecodeString(address)
|
||||
to, err := sdk.GetAccAddressHex(address)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
w.Write([]byte(err.Error()))
|
||||
return
|
||||
}
|
||||
to := sdk.Address(bz)
|
||||
|
||||
// build message
|
||||
msg := client.BuildMsg(info.PubKey.Address(), to, m.Amount)
|
||||
|
|
|
@ -4,6 +4,7 @@ import (
|
|||
"fmt"
|
||||
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
"github.com/cosmos/cosmos-sdk/x/auth"
|
||||
)
|
||||
|
||||
const (
|
||||
|
@ -16,11 +17,11 @@ const (
|
|||
|
||||
// Keeper manages transfers between accounts
|
||||
type Keeper struct {
|
||||
am sdk.AccountMapper
|
||||
am auth.AccountMapper
|
||||
}
|
||||
|
||||
// NewKeeper returns a new Keeper
|
||||
func NewKeeper(am sdk.AccountMapper) Keeper {
|
||||
func NewKeeper(am auth.AccountMapper) Keeper {
|
||||
return Keeper{am: am}
|
||||
}
|
||||
|
||||
|
@ -63,11 +64,11 @@ func (keeper Keeper) InputOutputCoins(ctx sdk.Context, inputs []Input, outputs [
|
|||
|
||||
// SendKeeper only allows transfers between accounts, without the possibility of creating coins
|
||||
type SendKeeper struct {
|
||||
am sdk.AccountMapper
|
||||
am auth.AccountMapper
|
||||
}
|
||||
|
||||
// NewSendKeeper returns a new Keeper
|
||||
func NewSendKeeper(am sdk.AccountMapper) SendKeeper {
|
||||
func NewSendKeeper(am auth.AccountMapper) SendKeeper {
|
||||
return SendKeeper{am: am}
|
||||
}
|
||||
|
||||
|
@ -95,11 +96,11 @@ func (keeper SendKeeper) InputOutputCoins(ctx sdk.Context, inputs []Input, outpu
|
|||
|
||||
// ViewKeeper only allows reading of balances
|
||||
type ViewKeeper struct {
|
||||
am sdk.AccountMapper
|
||||
am auth.AccountMapper
|
||||
}
|
||||
|
||||
// NewViewKeeper returns a new Keeper
|
||||
func NewViewKeeper(am sdk.AccountMapper) ViewKeeper {
|
||||
func NewViewKeeper(am auth.AccountMapper) ViewKeeper {
|
||||
return ViewKeeper{am: am}
|
||||
}
|
||||
|
||||
|
@ -115,7 +116,7 @@ func (keeper ViewKeeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coi
|
|||
|
||||
//______________________________________________________________________________________________
|
||||
|
||||
func getCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address) sdk.Coins {
|
||||
func getCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.Address) sdk.Coins {
|
||||
ctx.GasMeter().ConsumeGas(costGetCoins, "getCoins")
|
||||
acc := am.GetAccount(ctx, addr)
|
||||
if acc == nil {
|
||||
|
@ -124,7 +125,7 @@ func getCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address) sdk.Coins
|
|||
return acc.GetCoins()
|
||||
}
|
||||
|
||||
func setCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address, amt sdk.Coins) sdk.Error {
|
||||
func setCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.Address, amt sdk.Coins) sdk.Error {
|
||||
ctx.GasMeter().ConsumeGas(costSetCoins, "setCoins")
|
||||
acc := am.GetAccount(ctx, addr)
|
||||
if acc == nil {
|
||||
|
@ -136,13 +137,13 @@ func setCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address, amt sdk.C
|
|||
}
|
||||
|
||||
// HasCoins returns whether or not an account has at least amt coins.
|
||||
func hasCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address, amt sdk.Coins) bool {
|
||||
func hasCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.Address, amt sdk.Coins) bool {
|
||||
ctx.GasMeter().ConsumeGas(costHasCoins, "hasCoins")
|
||||
return getCoins(ctx, am, addr).IsGTE(amt)
|
||||
}
|
||||
|
||||
// SubtractCoins subtracts amt from the coins at the addr.
|
||||
func subtractCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Tags, sdk.Error) {
|
||||
func subtractCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Tags, sdk.Error) {
|
||||
ctx.GasMeter().ConsumeGas(costSubtractCoins, "subtractCoins")
|
||||
oldCoins := getCoins(ctx, am, addr)
|
||||
newCoins := oldCoins.Minus(amt)
|
||||
|
@ -155,7 +156,7 @@ func subtractCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address, amt
|
|||
}
|
||||
|
||||
// AddCoins adds amt to the coins at the addr.
|
||||
func addCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Tags, sdk.Error) {
|
||||
func addCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Tags, sdk.Error) {
|
||||
ctx.GasMeter().ConsumeGas(costAddCoins, "addCoins")
|
||||
oldCoins := getCoins(ctx, am, addr)
|
||||
newCoins := oldCoins.Plus(amt)
|
||||
|
@ -169,7 +170,7 @@ func addCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address, amt sdk.C
|
|||
|
||||
// SendCoins moves coins from one account to another
|
||||
// NOTE: Make sure to revert state changes from tx on error
|
||||
func sendCoins(ctx sdk.Context, am sdk.AccountMapper, fromAddr sdk.Address, toAddr sdk.Address, amt sdk.Coins) (sdk.Tags, sdk.Error) {
|
||||
func sendCoins(ctx sdk.Context, am auth.AccountMapper, fromAddr sdk.Address, toAddr sdk.Address, amt sdk.Coins) (sdk.Tags, sdk.Error) {
|
||||
_, subTags, err := subtractCoins(ctx, am, fromAddr, amt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@ -185,7 +186,7 @@ func sendCoins(ctx sdk.Context, am sdk.AccountMapper, fromAddr sdk.Address, toAd
|
|||
|
||||
// InputOutputCoins handles a list of inputs and outputs
|
||||
// NOTE: Make sure to revert state changes from tx on error
|
||||
func inputOutputCoins(ctx sdk.Context, am sdk.AccountMapper, inputs []Input, outputs []Output) (sdk.Tags, sdk.Error) {
|
||||
func inputOutputCoins(ctx sdk.Context, am auth.AccountMapper, inputs []Input, outputs []Output) (sdk.Tags, sdk.Error) {
|
||||
allTags := sdk.EmptyTags()
|
||||
|
||||
for _, in := range inputs {
|
||||
|
|
|
@ -0,0 +1,91 @@
|
|||
package stake
|
||||
|
||||
//// keeper of the staking store
|
||||
//type Keeper struct {
|
||||
//storeKey sdk.StoreKey
|
||||
//cdc *wire.Codec
|
||||
//coinKeeper bank.Keeper
|
||||
|
||||
//// codespace
|
||||
//codespace sdk.CodespaceType
|
||||
//}
|
||||
|
||||
//func NewKeeper(cdc *wire.Codec, key sdk.StoreKey, ck bank.Keeper, codespace sdk.CodespaceType) Keeper {
|
||||
//keeper := Keeper{
|
||||
//storeKey: key,
|
||||
//cdc: cdc,
|
||||
//coinKeeper: ck,
|
||||
//codespace: codespace,
|
||||
//}
|
||||
//return keeper
|
||||
//}
|
||||
|
||||
////_________________________________________________________________________
|
||||
|
||||
//// cummulative power of the non-absent prevotes
|
||||
//func (k Keeper) GetTotalPrecommitVotingPower(ctx sdk.Context) sdk.Rat {
|
||||
//store := ctx.KVStore(k.storeKey)
|
||||
|
||||
//// get absent prevote indexes
|
||||
//absents := ctx.AbsentValidators()
|
||||
|
||||
//TotalPower := sdk.ZeroRat()
|
||||
//i := int32(0)
|
||||
//iterator := store.SubspaceIterator(ValidatorsBondedKey)
|
||||
//for ; iterator.Valid(); iterator.Next() {
|
||||
|
||||
//skip := false
|
||||
//for j, absentIndex := range absents {
|
||||
//if absentIndex > i {
|
||||
//break
|
||||
//}
|
||||
|
||||
//// if non-voting validator found, skip adding its power
|
||||
//if absentIndex == i {
|
||||
//absents = append(absents[:j], absents[j+1:]...) // won't need again
|
||||
//skip = true
|
||||
//break
|
||||
//}
|
||||
//}
|
||||
//if skip {
|
||||
//continue
|
||||
//}
|
||||
|
||||
//bz := iterator.Value()
|
||||
//var validator Validator
|
||||
//k.cdc.MustUnmarshalBinary(bz, &validator)
|
||||
//TotalPower = TotalPower.Add(validator.Power)
|
||||
//i++
|
||||
//}
|
||||
//iterator.Close()
|
||||
//return TotalPower
|
||||
//}
|
||||
|
||||
////_______________________________________________________________________
|
||||
|
||||
//// XXX TODO trim functionality
|
||||
|
||||
//// retrieve all the power changes which occur after a height
|
||||
//func (k Keeper) GetPowerChangesAfterHeight(ctx sdk.Context, earliestHeight int64) (pcs []PowerChange) {
|
||||
//store := ctx.KVStore(k.storeKey)
|
||||
|
||||
//iterator := store.SubspaceIterator(PowerChangeKey) //smallest to largest
|
||||
//for ; iterator.Valid(); iterator.Next() {
|
||||
//pcBytes := iterator.Value()
|
||||
//var pc PowerChange
|
||||
//k.cdc.MustUnmarshalBinary(pcBytes, &pc)
|
||||
//if pc.Height < earliestHeight {
|
||||
//break
|
||||
//}
|
||||
//pcs = append(pcs, pc)
|
||||
//}
|
||||
//iterator.Close()
|
||||
//return
|
||||
//}
|
||||
|
||||
//// set a power change
|
||||
//func (k Keeper) setPowerChange(ctx sdk.Context, pc PowerChange) {
|
||||
//store := ctx.KVStore(k.storeKey)
|
||||
//b := k.cdc.MustMarshalBinary(pc)
|
||||
//store.Set(GetPowerChangeKey(pc.Height), b)
|
||||
//}
|
|
@ -0,0 +1,31 @@
|
|||
package stake
|
||||
|
||||
//// test if is a gotValidator from the last update
|
||||
//func TestGetTotalPrecommitVotingPower(t *testing.T) {
|
||||
//ctx, _, keeper := createTestInput(t, false, 0)
|
||||
|
||||
//amts := []int64{10000, 1000, 100, 10, 1}
|
||||
//var candidatesIn [5]Candidate
|
||||
//for i, amt := range amts {
|
||||
//candidatesIn[i] = NewCandidate(addrVals[i], pks[i], Description{})
|
||||
//candidatesIn[i].BondedShares = sdk.NewRat(amt)
|
||||
//candidatesIn[i].DelegatorShares = sdk.NewRat(amt)
|
||||
//keeper.setCandidate(ctx, candidatesIn[i])
|
||||
//}
|
||||
|
||||
//// test that an empty gotValidator set doesn't have any gotValidators
|
||||
//gotValidators := keeper.GetValidators(ctx)
|
||||
//assert.Equal(t, 5, len(gotValidators))
|
||||
|
||||
//totPow := keeper.GetTotalPrecommitVotingPower(ctx)
|
||||
//exp := sdk.NewRat(11111)
|
||||
//assert.True(t, exp.Equal(totPow), "exp %v, got %v", exp, totPow)
|
||||
|
||||
//// set absent gotValidators to be the 1st and 3rd record sorted by pubKey address
|
||||
//ctx = ctx.WithAbsentValidators([]int32{1, 3})
|
||||
//totPow = keeper.GetTotalPrecommitVotingPower(ctx)
|
||||
|
||||
//// XXX verify that this order should infact exclude these two records
|
||||
//exp = sdk.NewRat(11100)
|
||||
//assert.True(t, exp.Equal(totPow), "exp %v, got %v", exp, totPow)
|
||||
//}
|
|
@ -0,0 +1,72 @@
|
|||
package stake
|
||||
|
||||
import (
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
)
|
||||
|
||||
// burn burn burn
|
||||
func BurnFeeHandler(ctx sdk.Context, _ sdk.Tx, collectedFees sdk.Coins) {}
|
||||
|
||||
//// Handle fee distribution to the validators and delegators
|
||||
//func (k Keeper) FeeHandler(ctx sdk.Context, collectedFees sdk.Coins) {
|
||||
//pool := k.GetPool(ctx)
|
||||
//params := k.GetParams(ctx)
|
||||
|
||||
//// XXX determine
|
||||
//candidate := NewCandidate(addrs[0], pks[0], Description{})
|
||||
|
||||
//// calculate the proposer reward
|
||||
//precommitPower := k.GetTotalPrecommitVotingPower(ctx)
|
||||
//toProposer := coinsMulRat(collectedFees, (sdk.NewRat(1, 100).Add(sdk.NewRat(4, 100).Mul(precommitPower).Quo(pool.BondedShares))))
|
||||
//candidate.ProposerRewardPool = candidate.ProposerRewardPool.Plus(toProposer)
|
||||
|
||||
//toReservePool := coinsMulRat(collectedFees, params.ReservePoolFee)
|
||||
//pool.FeeReservePool = pool.FeeReservePool.Plus(toReservePool)
|
||||
|
||||
//distributedReward := (collectedFees.Minus(toProposer)).Minus(toReservePool)
|
||||
//pool.FeePool = pool.FeePool.Plus(distributedReward)
|
||||
//pool.FeeSumReceived = pool.FeeSumReceived.Plus(distributedReward)
|
||||
//pool.FeeRecent = distributedReward
|
||||
|
||||
//// lastly update the FeeRecent term
|
||||
//pool.FeeRecent = collectedFees
|
||||
|
||||
//k.setPool(ctx, pool)
|
||||
//}
|
||||
|
||||
//func coinsMulRat(coins sdk.Coins, rat sdk.Rat) sdk.Coins {
|
||||
//var res sdk.Coins
|
||||
//for _, coin := range coins {
|
||||
//coinMulAmt := rat.Mul(sdk.NewRat(coin.Amount)).Evaluate()
|
||||
//coinMul := sdk.Coins{{coin.Denom, coinMulAmt}}
|
||||
//res = res.Plus(coinMul)
|
||||
//}
|
||||
//return res
|
||||
//}
|
||||
|
||||
////____________________________________________________________________________-
|
||||
|
||||
//// calculate adjustment changes for a candidate at a height
|
||||
//func CalculateAdjustmentChange(candidate Candidate, pool Pool, denoms []string, height int64) (Candidate, Pool) {
|
||||
|
||||
//heightRat := sdk.NewRat(height)
|
||||
//lastHeightRat := sdk.NewRat(height - 1)
|
||||
//candidateFeeCount := candidate.BondedShares.Mul(heightRat)
|
||||
//poolFeeCount := pool.BondedShares.Mul(heightRat)
|
||||
|
||||
//for i, denom := range denoms {
|
||||
//poolFeeSumReceived := sdk.NewRat(pool.FeeSumReceived.AmountOf(denom))
|
||||
//poolFeeRecent := sdk.NewRat(pool.FeeRecent.AmountOf(denom))
|
||||
//// calculate simple and projected pools
|
||||
//simplePool := candidateFeeCount.Quo(poolFeeCount).Mul(poolFeeSumReceived)
|
||||
//calc1 := candidate.PrevBondedShares.Mul(lastHeightRat).Quo(pool.PrevBondedShares.Mul(lastHeightRat)).Mul(poolFeeRecent)
|
||||
//calc2 := candidate.BondedShares.Quo(pool.BondedShares).Mul(poolFeeRecent)
|
||||
//projectedPool := calc1.Add(calc2)
|
||||
|
||||
//AdjustmentChange := simplePool.Sub(projectedPool)
|
||||
//candidate.FeeAdjustments[i] = candidate.FeeAdjustments[i].Add(AdjustmentChange)
|
||||
//pool.FeeAdjustments[i] = pool.FeeAdjustments[i].Add(AdjustmentChange)
|
||||
//}
|
||||
|
||||
//return candidate, pool
|
||||
//}
|
|
@ -0,0 +1,107 @@
|
|||
package stake
|
||||
|
||||
//// GenesisState - all staking state that must be provided at genesis
|
||||
//type GenesisState struct {
|
||||
//Pool Pool `json:"pool"`
|
||||
//Params Params `json:"params"`
|
||||
//}
|
||||
|
||||
//func NewGenesisState(pool Pool, params Params, candidates []Candidate, bonds []Delegation) GenesisState {
|
||||
//return GenesisState{
|
||||
//Pool: pool,
|
||||
//Params: params,
|
||||
//}
|
||||
//}
|
||||
|
||||
//// get raw genesis raw message for testing
|
||||
//func DefaultGenesisState() GenesisState {
|
||||
//return GenesisState{
|
||||
//Pool: initialPool(),
|
||||
//Params: defaultParams(),
|
||||
//}
|
||||
//}
|
||||
|
||||
//// fee information for a validator
|
||||
//type Validator struct {
|
||||
//Adjustments []sdk.Rat `json:"fee_adjustments"` // XXX Adjustment factors for lazy fee accounting, couples with Params.BondDenoms
|
||||
//PrevBondedShares sdk.Rat `json:"prev_bonded_shares"` // total shares of a global hold pools
|
||||
//}
|
||||
|
||||
////_________________________________________________________________________
|
||||
|
||||
//// Params defines the high level settings for staking
|
||||
//type Params struct {
|
||||
//FeeDenoms []string `json:"fee_denoms"` // accepted fee denoms
|
||||
//ReservePoolFee sdk.Rat `json:"reserve_pool_fee"` // percent of fees which go to reserve pool
|
||||
//}
|
||||
|
||||
//func (p Params) equal(p2 Params) bool {
|
||||
//return p.BondDenom == p2.BondDenom &&
|
||||
//p.ReservePoolFee.Equal(p2.ReservePoolFee)
|
||||
//}
|
||||
|
||||
//func defaultParams() Params {
|
||||
//return Params{
|
||||
//FeeDenoms: []string{"steak"},
|
||||
//ReservePoolFee: sdk.NewRat(5, 100),
|
||||
//}
|
||||
//}
|
||||
|
||||
////_________________________________________________________________________
|
||||
|
||||
//// Pool - dynamic parameters of the current state
|
||||
//type Pool struct {
|
||||
//FeeReservePool sdk.Coins `json:"fee_reserve_pool"` // XXX reserve pool of collected fees for use by governance
|
||||
//FeePool sdk.Coins `json:"fee_pool"` // XXX fee pool for all the fee shares which have already been distributed
|
||||
//FeeSumReceived sdk.Coins `json:"fee_sum_received"` // XXX sum of all fees received, post reserve pool `json:"fee_sum_received"`
|
||||
//FeeRecent sdk.Coins `json:"fee_recent"` // XXX most recent fee collected
|
||||
//FeeAdjustments []sdk.Rat `json:"fee_adjustments"` // XXX Adjustment factors for lazy fee accounting, couples with Params.BondDenoms
|
||||
//PrevBondedShares sdk.Rat `json:"prev_bonded_shares"` // XXX last recorded bonded shares
|
||||
//}
|
||||
|
||||
//func (p Pool) equal(p2 Pool) bool {
|
||||
//return p.FeeReservePool.IsEqual(p2.FeeReservePool) &&
|
||||
//p.FeePool.IsEqual(p2.FeePool) &&
|
||||
//p.FeeSumReceived.IsEqual(p2.FeeSumReceived) &&
|
||||
//p.FeeRecent.IsEqual(p2.FeeRecent) &&
|
||||
//sdk.RatsEqual(p.FeeAdjustments, p2.FeeAdjustments) &&
|
||||
//p.PrevBondedShares.Equal(p2.PrevBondedShares)
|
||||
//}
|
||||
|
||||
//// initial pool for testing
|
||||
//func initialPool() Pool {
|
||||
//return Pool{
|
||||
//FeeReservePool: sdk.Coins(nil),
|
||||
//FeePool: sdk.Coins(nil),
|
||||
//FeeSumReceived: sdk.Coins(nil),
|
||||
//FeeRecent: sdk.Coins(nil),
|
||||
//FeeAdjustments: []sdk.Rat{sdk.ZeroRat()},
|
||||
//PrevBondedShares: sdk.ZeroRat(),
|
||||
//}
|
||||
//}
|
||||
|
||||
////_________________________________________________________________________
|
||||
|
||||
//// Used in calculation of fee shares, added to a queue for each block where a power change occures
|
||||
//type PowerChange struct {
|
||||
//Height int64 `json:"height"` // block height at change
|
||||
//Power sdk.Rat `json:"power"` // total power at change
|
||||
//PrevPower sdk.Rat `json:"prev_power"` // total power at previous height-1
|
||||
//FeesIn sdk.Coins `json:"fees_in"` // fees in at block height
|
||||
//PrevFeePool sdk.Coins `json:"prev_fee_pool"` // total fees in at previous block height
|
||||
//}
|
||||
|
||||
////_________________________________________________________________________
|
||||
//// KEY MANAGEMENT
|
||||
|
||||
//var (
|
||||
//// Keys for store prefixes
|
||||
//PowerChangeKey = []byte{0x09} // prefix for power change object
|
||||
//)
|
||||
|
||||
//// get the key for the accumulated update validators
|
||||
//func GetPowerChangeKey(height int64) []byte {
|
||||
//heightBytes := make([]byte, binary.MaxVarintLen64)
|
||||
//binary.BigEndian.PutUint64(heightBytes, ^uint64(height)) // invert height (older validators first)
|
||||
//return append(PowerChangeKey, heightBytes...)
|
||||
//}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue