diff --git a/.circleci/config.yml b/.circleci/config.yml index 6dde65ea44..fd81f11142 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -5,27 +5,6 @@ defaults: &linux_defaults docker: - image: circleci/golang:1.12.5 - -############ -# -# Configure macos integration tests - -macos_config: &macos_defaults - macos: - xcode: "10.1.0" - working_directory: /Users/distiller/project/src/github.com/cosmos/cosmos-sdk - environment: - GO_VERSION: "1.12.5" - -set_macos_env: &macos_env - run: - name: Set environment - command: | - echo 'export PATH=$PATH:$HOME/go/bin' >> $BASH_ENV - echo 'export GOPATH=$HOME/project' >> $BASH_ENV - echo 'export PATH=$PATH:$HOME/go/bin:$GOPATH/bin' >> $BASH_ENV - echo 'export GO111MODULE=on' - ############ # # Configure docs deployment @@ -50,17 +29,20 @@ jobs: - run: name: tools command: | - make tools TOOLS_DESTDIR=/tmp/workspace/bin + make runsim tools TOOLS_DESTDIR=/tmp/workspace/bin + cp $GOPATH/bin/runsim /tmp/workspace/bin - run: - name: binaries + name: cache go modules command: | - export PATH=/tmp/workspace/bin:$PATH make go-mod-cache - make install - save_cache: key: go-mod-v1-{{ checksum "go.sum" }} paths: - "/go/pkg/mod" + - run: + name: build + command: | + make build - persist_to_workspace: root: /tmp/workspace paths: @@ -83,22 +65,7 @@ jobs: export PATH=/tmp/workspace/bin:$PATH make ci-lint - integration_tests: - <<: *linux_defaults - parallelism: 1 - steps: - - attach_workspace: - at: /tmp/workspace - - checkout - - restore_cache: - keys: - - go-mod-v1-{{ checksum "go.sum" }} - - run: - name: Test cli - command: | - make test_cli - - test_sim_gaia_nondeterminism: + test_sim_app_nondeterminism: <<: *linux_defaults parallelism: 1 steps: @@ -111,9 +78,9 @@ jobs: - run: name: Test individual module simulations command: | - make test_sim_gaia_nondeterminism + make test_sim_app_nondeterminism - test_sim_gaia_fast: + test_sim_app_fast: <<: *linux_defaults parallelism: 1 steps: @@ -124,11 +91,11 @@ jobs: keys: - go-mod-v1-{{ checksum "go.sum" }} - run: - name: Test full Gaia simulation + name: Test full application simulation command: | - make test_sim_gaia_fast + make test_sim_app_fast - test_sim_gaia_import_export: + test_sim_app_import_export: <<: *linux_defaults parallelism: 1 steps: @@ -139,13 +106,12 @@ jobs: keys: - go-mod-v1-{{ checksum "go.sum" }} - run: - name: Test Gaia import/export simulation + name: Test application import/export simulation command: | export GO111MODULE=on - make runsim - runsim -j 4 50 5 TestGaiaImportExport + /tmp/workspace/bin/runsim -j 4 github.com/cosmos/cosmos-sdk/simapp 50 5 TestAppImportExport - test_sim_gaia_simulation_after_import: + test_sim_app_simulation_after_import: <<: *linux_defaults parallelism: 1 steps: @@ -156,13 +122,12 @@ jobs: keys: - go-mod-v1-{{ checksum "go.sum" }} - run: - name: Test Gaia import/export simulation + name: Test application import/export simulation command: | export GO111MODULE=on - make runsim - runsim -j 4 50 5 TestGaiaSimulationAfterImport + /tmp/workspace/bin/runsim -j 4 github.com/cosmos/cosmos-sdk/simapp 50 5 TestAppSimulationAfterImport - test_sim_gaia_multi_seed_long: + test_sim_app_multi_seed_long: <<: *linux_defaults parallelism: 1 steps: @@ -173,13 +138,12 @@ jobs: keys: - go-mod-v1-{{ checksum "go.sum" }} - run: - name: Test multi-seed Gaia simulation long + name: Test multi-seed application simulation long command: | export GO111MODULE=on - make runsim - runsim -j 4 500 50 TestFullGaiaSimulation + /tmp/workspace/bin/runsim -j 4 github.com/cosmos/cosmos-sdk/simapp 500 50 TestFullAppSimulation - test_sim_gaia_multi_seed: + test_sim_app_multi_seed: <<: *linux_defaults parallelism: 1 steps: @@ -190,11 +154,10 @@ jobs: keys: - go-mod-v1-{{ checksum "go.sum" }} - run: - name: Test multi-seed Gaia simulation short + name: Test multi-seed application simulation short command: | export GO111MODULE=on - make runsim - runsim -j 4 50 10 TestFullGaiaSimulation + /tmp/workspace/bin/runsim -j 4 github.com/cosmos/cosmos-sdk/simapp 50 10 TestFullAppSimulation test_cover: <<: *linux_defaults @@ -212,7 +175,7 @@ jobs: command: | export VERSION="$(git describe --tags --long | sed 's/v\(.*\)/\1/')" export GO111MODULE=on - for pkg in $(go list ./... | grep -v github.com/cosmos/cosmos-sdk/cmd/gaia/cli_test | grep -v '/simulation' | circleci tests split --split-by=timings); do + for pkg in $(go list ./... | grep -v '/simulation' | circleci tests split --split-by=timings); do id=$(echo "$pkg" | sed 's|[/.]|_|g') go test -mod=readonly -timeout 8m -race -coverprofile=/tmp/workspace/profiles/$id.out -covermode=atomic -tags='ledger test_ledger_mock' "$pkg" | tee "/tmp/logs/$id-$RANDOM.log" done @@ -253,33 +216,6 @@ jobs: name: upload command: bash <(curl -s https://codecov.io/bash) -f coverage.txt - localnet: - working_directory: /home/circleci/.go_workspace/src/github.com/cosmos/cosmos-sdk - machine: - image: circleci/classic:latest - environment: - GOPATH: /home/circleci/.go_workspace/ - GOOS: linux - GOARCH: amd64 - GO_VERSION: "1.12.5" - parallelism: 1 - steps: - - checkout - - run: - name: run localnet and exit on failure - command: | - pushd /tmp - wget https://dl.google.com/go/go$GO_VERSION.linux-amd64.tar.gz - sudo tar -xvf go$GO_VERSION.linux-amd64.tar.gz - sudo rm -rf /usr/local/go - sudo mv go /usr/local - popd - set -x - make tools - make build-linux - make localnet-start - ./scripts/localnet-blocks-test.sh 40 5 10 localhost - deploy_docs: <<: *docs_deploy steps: @@ -304,114 +240,10 @@ jobs: echo "Website build started" fi - macos_ci: - <<: *macos_defaults - steps: - - *macos_env - - run: - name: Install go - command: | - source $BASH_ENV - curl -L -O https://dl.google.com/go/go$GO_VERSION.darwin-amd64.tar.gz - tar -C $HOME -xzf go$GO_VERSION.darwin-amd64.tar.gz - rm go$GO_VERSION.darwin-amd64.tar.gz - go version - - checkout - - run: - name: Install SDK - command: | - source $BASH_ENV - make tools - make install - - run: - name: Integration tests - command: - source $BASH_ENV - make test_cli - - run: - name: Test full gaia simulation - command: | - source $BASH_ENV - make test_sim_gaia_fast - - docker_image: - <<: *linux_defaults - steps: - - attach_workspace: - at: /tmp/workspace - - checkout - - setup_remote_docker: - docker_layer_caching: true - - run: | - GAIAD_VERSION='' - if [ "${CIRCLE_BRANCH}" = "master" ]; then - GAIAD_VERSION="stable" - elif [ "${CIRCLE_BRANCH}" = "develop" ]; then - GAIAD_VERSION="develop" - fi - if [ -z "${GAIAD_VERSION}" ]; then - docker build . - else - docker build -t tendermint/gaia:$GAIAD_VERSION . - docker login --password-stdin -u $DOCKER_USER <<<$DOCKER_PASS - docker push tendermint/gaia:$GAIAD_VERSION - fi - - docker_tagged: - <<: *linux_defaults - steps: - - attach_workspace: - at: /tmp/workspace - - checkout - - setup_remote_docker: - docker_layer_caching: true - - run: | - docker build -t tendermint/gaia:$CIRCLE_TAG . - docker login --password-stdin -u $DOCKER_USER <<<$DOCKER_PASS - docker push tendermint/gaia:$CIRCLE_TAG - - reproducible_builds: - <<: *linux_defaults - steps: - - attach_workspace: - at: /tmp/workspace - - checkout - - setup_remote_docker: - docker_layer_caching: true - - run: - name: Build gaia - no_output_timeout: 20m - command: | - sudo apt-get install -y ruby - bash -x ./cmd/gaia/contrib/gitian-build.sh all - for os in darwin linux windows; do - cp gitian-build-${os}/result/gaia-${os}-res.yml . - rm -rf gitian-build-${os}/ - done - - store_artifacts: - path: /go/src/github.com/cosmos/cosmos-sdk/gaia-darwin-res.yml - - store_artifacts: - path: /go/src/github.com/cosmos/cosmos-sdk/gaia-linux-res.yml - - store_artifacts: - path: /go/src/github.com/cosmos/cosmos-sdk/gaia-windows-res.yml - workflows: version: 2 test-suite: jobs: - - docker_image: - requires: - - setup_dependencies - - docker_tagged: - filters: - tags: - only: - - /^v.*/ - branches: - ignore: - - /.*/ - requires: - - setup_dependencies - macos_ci: filters: branches: @@ -433,25 +265,22 @@ workflows: - lint: requires: - setup_dependencies - - integration_tests: + - test_sim_app_nondeterminism: requires: - setup_dependencies - - test_sim_gaia_nondeterminism: + - test_sim_app_fast: requires: - setup_dependencies - - test_sim_gaia_fast: + - test_sim_app_import_export: requires: - setup_dependencies - - test_sim_gaia_import_export: + - test_sim_app_simulation_after_import: requires: - setup_dependencies - - test_sim_gaia_simulation_after_import: + - test_sim_app_multi_seed: requires: - setup_dependencies - - test_sim_gaia_multi_seed: - requires: - - setup_dependencies - - test_sim_gaia_multi_seed_long: + - test_sim_app_multi_seed_long: requires: - setup_dependencies filters: @@ -462,7 +291,6 @@ workflows: - test_cover: requires: - setup_dependencies - - localnet - upload_coverage: requires: - test_cover diff --git a/.clog.yaml b/.clog.yaml index 1294809e29..b779210bd4 100644 --- a/.clog.yaml +++ b/.clog.yaml @@ -5,8 +5,5 @@ sections: bugfixes: Bugfixes tags: - - gaia - - gaiacli - - gaiarest - sdk - tendermint diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md index 49cd078376..346969aef1 100644 --- a/.github/ISSUE_TEMPLATE/bug-report.md +++ b/.github/ISSUE_TEMPLATE/bug-report.md @@ -16,7 +16,7 @@ v Please also ensure that this is not a duplicate issue :) ## Version - + ## Steps to Reproduce diff --git a/.pending/breaking/gaia/4027-gaiad-and-gaiac b/.pending/breaking/gaia/4027-gaiad-and-gaiac deleted file mode 100644 index c5055047e7..0000000000 --- a/.pending/breaking/gaia/4027-gaiad-and-gaiac +++ /dev/null @@ -1,2 +0,0 @@ -#4027 gaiad and gaiacli version commands do not return the checksum of the go.sum file shipped along with the source release tarball. -Go modules feature guarantees dependencies reproducibility and as long as binaries are built via the Makefile shipped with the sources, no dependendencies can break such guarantee. diff --git a/.pending/breaking/gaia/4159-use-module-patt b/.pending/breaking/gaia/4159-use-module-patt deleted file mode 100644 index 1a3d4398da..0000000000 --- a/.pending/breaking/gaia/4159-use-module-patt +++ /dev/null @@ -1 +0,0 @@ -#4159 use module pattern and module manager for initialization \ No newline at end of file diff --git a/.pending/breaking/gaia/4272-Merge-gaiarepla b/.pending/breaking/gaia/4272-Merge-gaiarepla deleted file mode 100644 index 5aecf7bc16..0000000000 --- a/.pending/breaking/gaia/4272-Merge-gaiarepla +++ /dev/null @@ -1,2 +0,0 @@ -#4272 Merge gaiareplay functionality into gaiad replay. -Drop `gaiareplay` in favor of new `gaiad replay` command. diff --git a/.pending/breaking/gaiacli/3715-query-distr-rew b/.pending/breaking/gaiacli/3715-query-distr-rew deleted file mode 100644 index 5303400b68..0000000000 --- a/.pending/breaking/gaiacli/3715-query-distr-rew +++ /dev/null @@ -1,2 +0,0 @@ -#3715 query distr rewards returns per-validator -rewards along with rewards total amount. diff --git a/.pending/breaking/gaiacli/4142-Turn-gaiacli-tx b/.pending/breaking/gaiacli/4142-Turn-gaiacli-tx deleted file mode 100644 index ed4c73b5bd..0000000000 --- a/.pending/breaking/gaiacli/4142-Turn-gaiacli-tx +++ /dev/null @@ -1,2 +0,0 @@ -#4142 Turn gaiacli tx send's --from into a required argument. -New shorter syntax: `gaiacli tx send FROM TO AMOUNT` diff --git a/.pending/breaking/gaiacli/4228-merge-gaiakeyutil-into-gaiacli b/.pending/breaking/gaiacli/4228-merge-gaiakeyutil-into-gaiacli deleted file mode 100644 index e986900a8e..0000000000 --- a/.pending/breaking/gaiacli/4228-merge-gaiakeyutil-into-gaiacli +++ /dev/null @@ -1,2 +0,0 @@ -#4228 Merge gaiakeyutil functionality into gaiacli keys. -Drop `gaiakeyutil` in favor of new `gaiacli keys parse` command. Syntax and semantic are preserved. diff --git a/.pending/breaking/gaiarest/3715-Update-distribu b/.pending/breaking/gaiarest/3715-Update-distribu deleted file mode 100644 index 1c562efa45..0000000000 --- a/.pending/breaking/gaiarest/3715-Update-distribu +++ /dev/null @@ -1,3 +0,0 @@ -#3715 Update /distribution/delegators/{delegatorAddr}/rewards GET endpoint -as per new specs. For a given delegation, the endpoint now returns the -comprehensive list of validator-reward tuples along with the grand total. diff --git a/.pending/breaking/gaiarest/3942-Support-query-t b/.pending/breaking/gaiarest/3942-Support-query-t deleted file mode 100644 index a5ab311473..0000000000 --- a/.pending/breaking/gaiarest/3942-Support-query-t +++ /dev/null @@ -1 +0,0 @@ -#3942 Update pagination data in txs query. diff --git a/.pending/breaking/gaiarest/4049-update-tag b/.pending/breaking/gaiarest/4049-update-tag deleted file mode 100644 index 6a200b715b..0000000000 --- a/.pending/breaking/gaiarest/4049-update-tag +++ /dev/null @@ -1 +0,0 @@ -#4049 update tag MsgWithdrawValidatorCommission to match type \ No newline at end of file diff --git a/.pending/breaking/sdk/4104-Gaia-has-been-m b/.pending/breaking/sdk/4104-Gaia-has-been-m new file mode 100644 index 0000000000..ebb298c652 --- /dev/null +++ b/.pending/breaking/sdk/4104-Gaia-has-been-m @@ -0,0 +1 @@ +#4104 Gaia has been moved to its own repository: https://github.com/cosmos/gaia diff --git a/.pending/bugfixes/gaia/4113-Fix-incorrect-G b/.pending/bugfixes/gaia/4113-Fix-incorrect-G deleted file mode 100644 index 2a5d1680b7..0000000000 --- a/.pending/bugfixes/gaia/4113-Fix-incorrect-G +++ /dev/null @@ -1 +0,0 @@ -#4113 Fix incorrect `$GOBIN` in `Install Go` \ No newline at end of file diff --git a/.pending/bugfixes/gaiacli/3945-There-s-no-chec b/.pending/bugfixes/gaiacli/3945-There-s-no-chec deleted file mode 100644 index e8ab060541..0000000000 --- a/.pending/bugfixes/gaiacli/3945-There-s-no-chec +++ /dev/null @@ -1 +0,0 @@ -#3945 There's no check for chain-id in TxBuilder.SignStdTx \ No newline at end of file diff --git a/.pending/bugfixes/gaiacli/4190-Fix-redelegatio b/.pending/bugfixes/gaiacli/4190-Fix-redelegatio deleted file mode 100644 index c9106a0382..0000000000 --- a/.pending/bugfixes/gaiacli/4190-Fix-redelegatio +++ /dev/null @@ -1 +0,0 @@ -#4190 Fix redelegations-from by using the correct params and query endpoint. diff --git a/.pending/bugfixes/gaiacli/4219-Empty-mnemonic- b/.pending/bugfixes/gaiacli/4219-Empty-mnemonic- deleted file mode 100644 index c0509645a3..0000000000 --- a/.pending/bugfixes/gaiacli/4219-Empty-mnemonic- +++ /dev/null @@ -1 +0,0 @@ -#4219 Return an error when an empty mnemonic is provided during key recovery. diff --git a/.pending/bugfixes/gaiacli/4345-Improved-NanoX-detection b/.pending/bugfixes/gaiacli/4345-Improved-NanoX-detection deleted file mode 100644 index 98c5fa5fb9..0000000000 --- a/.pending/bugfixes/gaiacli/4345-Improved-NanoX-detection +++ /dev/null @@ -1 +0,0 @@ -#4345 Improved Ledger Nano X detection diff --git a/.pending/improvements/gaia/4042-Add-description b/.pending/improvements/gaia/4042-Add-description deleted file mode 100644 index 03ed9cc618..0000000000 --- a/.pending/improvements/gaia/4042-Add-description +++ /dev/null @@ -1 +0,0 @@ -#4042 Update docs and scripts to include the correct `GO111MODULE=on` environment variable. diff --git a/.pending/improvements/gaia/4062-Remove-cmd-gaia b/.pending/improvements/gaia/4062-Remove-cmd-gaia deleted file mode 100644 index b0d5e7c9ec..0000000000 --- a/.pending/improvements/gaia/4062-Remove-cmd-gaia +++ /dev/null @@ -1 +0,0 @@ -#4066 Fix 'ExportGenesisFile() incorrectly overwrites genesis' diff --git a/.pending/improvements/gaia/4064-Remove-dep-and- b/.pending/improvements/gaia/4064-Remove-dep-and- deleted file mode 100644 index 3792deb540..0000000000 --- a/.pending/improvements/gaia/4064-Remove-dep-and- +++ /dev/null @@ -1 +0,0 @@ -#4064 Remove `dep` and `vendor` from `doc` and `version`. \ No newline at end of file diff --git a/.pending/improvements/gaia/4080-add-missing-inv b/.pending/improvements/gaia/4080-add-missing-inv deleted file mode 100644 index 48c8172da0..0000000000 --- a/.pending/improvements/gaia/4080-add-missing-inv +++ /dev/null @@ -1 +0,0 @@ -#4080 add missing invariants during simulations \ No newline at end of file diff --git a/.pending/improvements/gaia/4343-Upgrade-toolcha b/.pending/improvements/gaia/4343-Upgrade-toolcha deleted file mode 100644 index 484d522c0d..0000000000 --- a/.pending/improvements/gaia/4343-Upgrade-toolcha +++ /dev/null @@ -1 +0,0 @@ -#4343 Upgrade toolchain to Go 1.12.5. diff --git a/.pending/improvements/gaiacli/3426-remove-redundant-account-check b/.pending/improvements/gaiacli/3426-remove-redundant-account-check deleted file mode 100644 index adf96e7675..0000000000 --- a/.pending/improvements/gaiacli/3426-remove-redundant-account-check +++ /dev/null @@ -1 +0,0 @@ -#4068 Remove redundant account check on `gaiacli` diff --git a/.pending/improvements/gaiacli/4227-Support-for-Ledger-App-1.5 b/.pending/improvements/gaiacli/4227-Support-for-Ledger-App-1.5 deleted file mode 100644 index 97bc1e81b1..0000000000 --- a/.pending/improvements/gaiacli/4227-Support-for-Ledger-App-1.5 +++ /dev/null @@ -1 +0,0 @@ -#4227 Support for Ledger App v1.5 diff --git a/.pending/improvements/gaiarest/2007-Return-200-status-code-on-empty-results b/.pending/improvements/gaiarest/2007-Return-200-status-code-on-empty-results deleted file mode 100644 index af20022008..0000000000 --- a/.pending/improvements/gaiarest/2007-Return-200-status-code-on-empty-results +++ /dev/null @@ -1 +0,0 @@ -#2007 Return 200 status code on empty results diff --git a/.pending/improvements/gaiarest/4123-Fix-typo-url-er b/.pending/improvements/gaiarest/4123-Fix-typo-url-er deleted file mode 100644 index 8f25a8f05e..0000000000 --- a/.pending/improvements/gaiarest/4123-Fix-typo-url-er +++ /dev/null @@ -1 +0,0 @@ -#4123 Fix typo, url error and outdated command description of doc clients. \ No newline at end of file diff --git a/.pending/improvements/gaiarest/4129-Translate-doc-c b/.pending/improvements/gaiarest/4129-Translate-doc-c deleted file mode 100644 index ab2710210f..0000000000 --- a/.pending/improvements/gaiarest/4129-Translate-doc-c +++ /dev/null @@ -1 +0,0 @@ -#4129 Translate doc clients to chinese. \ No newline at end of file diff --git a/.pending/improvements/gaiarest/4141-Fix-txs-encode- b/.pending/improvements/gaiarest/4141-Fix-txs-encode- deleted file mode 100644 index 0c19a16242..0000000000 --- a/.pending/improvements/gaiarest/4141-Fix-txs-encode- +++ /dev/null @@ -1 +0,0 @@ -#4141 Fix /txs/encode endpoint \ No newline at end of file diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index f779aae3a2..0000000000 --- a/Dockerfile +++ /dev/null @@ -1,33 +0,0 @@ -# Simple usage with a mounted data directory: -# > docker build -t gaia . -# > docker run -it -p 46657:46657 -p 46656:46656 -v ~/.gaiad:/root/.gaiad -v ~/.gaiacli:/root/.gaiacli gaia gaiad init -# > docker run -it -p 46657:46657 -p 46656:46656 -v ~/.gaiad:/root/.gaiad -v ~/.gaiacli:/root/.gaiacli gaia gaiad start -FROM golang:alpine AS build-env - -# Set up dependencies -ENV PACKAGES curl make git libc-dev bash gcc linux-headers eudev-dev python - -# Set working directory for the build -WORKDIR /go/src/github.com/cosmos/cosmos-sdk - -# Add source files -COPY . . - -# Install minimum necessary dependencies, build Cosmos SDK, remove packages -RUN apk add --no-cache $PACKAGES && \ - make tools && \ - make install - -# Final image -FROM alpine:edge - -# Install ca-certificates -RUN apk add --update ca-certificates -WORKDIR /root - -# Copy over binaries from the build-env -COPY --from=build-env /go/bin/gaiad /usr/bin/gaiad -COPY --from=build-env /go/bin/gaiacli /usr/bin/gaiacli - -# Run gaiad by default, omit entrypoint to ease using container with gaiacli -CMD ["gaiad"] diff --git a/Makefile b/Makefile index ef68d42b0b..ccf976d1c2 100644 --- a/Makefile +++ b/Makefile @@ -6,62 +6,11 @@ VERSION := $(shell echo $(shell git describe --tags) | sed 's/^v//') COMMIT := $(shell git log -1 --format='%H') LEDGER_ENABLED ?= true BINDIR ?= $(GOPATH)/bin +SIMAPP = github.com/cosmos/cosmos-sdk/simapp export GO111MODULE = on -# process build tags - -build_tags = netgo -ifeq ($(LEDGER_ENABLED),true) - ifeq ($(OS),Windows_NT) - GCCEXE = $(shell where gcc.exe 2> NUL) - ifeq ($(GCCEXE),) - $(error gcc.exe not installed for ledger support, please install or set LEDGER_ENABLED=false) - else - build_tags += ledger - endif - else - UNAME_S = $(shell uname -s) - ifeq ($(UNAME_S),OpenBSD) - $(warning OpenBSD detected, disabling ledger support (https://github.com/cosmos/cosmos-sdk/issues/1988)) - else - GCC = $(shell command -v gcc 2> /dev/null) - ifeq ($(GCC),) - $(error gcc not installed for ledger support, please install or set LEDGER_ENABLED=false) - else - build_tags += ledger - endif - endif - endif -endif - -ifeq ($(WITH_CLEVELDB),yes) - build_tags += gcc -endif -build_tags += $(BUILD_TAGS) -build_tags := $(strip $(build_tags)) - -whitespace := -whitespace += $(whitespace) -comma := , -build_tags_comma_sep := $(subst $(whitespace),$(comma),$(build_tags)) - -# process linker flags - -ldflags = -X github.com/cosmos/cosmos-sdk/version.Name=gaia \ - -X github.com/cosmos/cosmos-sdk/version.Version=$(VERSION) \ - -X github.com/cosmos/cosmos-sdk/version.Commit=$(COMMIT) \ - -X "github.com/cosmos/cosmos-sdk/version.BuildTags=$(build_tags_comma_sep)" - -ifeq ($(WITH_CLEVELDB),yes) - ldflags += -X github.com/cosmos/cosmos-sdk/types.DBBackend=cleveldb -endif -ldflags += $(LDFLAGS) -ldflags := $(strip $(ldflags)) - -BUILD_FLAGS := -tags "$(build_tags)" -ldflags '$(ldflags)' - -all: tools install lint test +all: tools build lint test # The below include contains the tools target. include contrib/devtools/Makefile @@ -69,33 +18,17 @@ include contrib/devtools/Makefile ######################################## ### CI -ci: tools install test_cover lint test +ci: tools build test_cover lint test ######################################## -### Build/Install +### Build build: go.sum -ifeq ($(OS),Windows_NT) - go build -mod=readonly $(BUILD_FLAGS) -o build/gaiad.exe ./cmd/gaia/cmd/gaiad - go build -mod=readonly $(BUILD_FLAGS) -o build/gaiacli.exe ./cmd/gaia/cmd/gaiacli -else - go build -mod=readonly $(BUILD_FLAGS) -o build/gaiad ./cmd/gaia/cmd/gaiad - go build -mod=readonly $(BUILD_FLAGS) -o build/gaiacli ./cmd/gaia/cmd/gaiacli -endif - -build-linux: go.sum - LEDGER_ENABLED=false GOOS=linux GOARCH=amd64 $(MAKE) build + @go build -mod=readonly ./... update_gaia_lite_docs: @statik -src=client/lcd/swagger-ui -dest=client/lcd -f -install: go.sum check-ledger update_gaia_lite_docs - go install -mod=readonly $(BUILD_FLAGS) ./cmd/gaia/cmd/gaiad - go install -mod=readonly $(BUILD_FLAGS) ./cmd/gaia/cmd/gaiacli - -install_debug: go.sum - go install -mod=readonly $(BUILD_FLAGS) ./cmd/gaia/cmd/gaiadebug - dist: @bash publish/dist.sh @bash publish/publish.sh @@ -139,13 +72,10 @@ godocs: test: test_unit -test_cli: build - @go test -mod=readonly -p 4 `go list ./cmd/gaia/cli_test/...` -tags=cli_test +test_ledger_mock: + @go test -mod=readonly `go list github.com/cosmos/cosmos-sdk/crypto` -tags='cgo ledger test_ledger_mock' -test_ledger: - # First test with mock - @go test -mod=readonly `go list github.com/cosmos/cosmos-sdk/crypto` -tags='cgo ledger test_ledger_mock' - # Now test with a real device +test_ledger: test_ledger_mock @go test -mod=readonly -v `go list github.com/cosmos/cosmos-sdk/crypto` -tags='cgo ledger' test_unit: @@ -154,59 +84,60 @@ test_unit: test_race: @VERSION=$(VERSION) go test -mod=readonly -race $(PACKAGES_NOSIMULATION) -test_sim_gaia_nondeterminism: +test_sim_app_nondeterminism: @echo "Running nondeterminism test..." - @go test -mod=readonly ./cmd/gaia/app -run TestAppStateDeterminism -SimulationEnabled=true -v -timeout 10m + @go test -mod=readonly $(SIMAPP) -run TestAppStateDeterminism -SimulationEnabled=true -v -timeout 10m -test_sim_gaia_custom_genesis_fast: +test_sim_app_custom_genesis_fast: @echo "Running custom genesis simulation..." @echo "By default, ${HOME}/.gaiad/config/genesis.json will be used." - @go test -mod=readonly ./cmd/gaia/app -run TestFullGaiaSimulation -SimulationGenesis=${HOME}/.gaiad/config/genesis.json \ + @go test -mod=readonly $(SIMAPP) -run TestFullAppSimulation -SimulationGenesis=${HOME}/.gaiad/config/genesis.json \ -SimulationEnabled=true -SimulationNumBlocks=100 -SimulationBlockSize=200 -SimulationCommit=true -SimulationSeed=99 -SimulationPeriod=5 -v -timeout 24h -test_sim_gaia_fast: - @echo "Running quick Gaia simulation. This may take several minutes..." - @go test -mod=readonly ./cmd/gaia/app -run TestFullGaiaSimulation -SimulationEnabled=true -SimulationNumBlocks=100 -SimulationBlockSize=200 -SimulationCommit=true -SimulationSeed=99 -SimulationPeriod=5 -v -timeout 24h +test_sim_app_fast: + @echo "Running quick application simulation. This may take several minutes..." + @go test -mod=readonly $(SIMAPP) -run TestFullAppSimulation -SimulationEnabled=true -SimulationNumBlocks=100 -SimulationBlockSize=200 -SimulationCommit=true -SimulationSeed=99 -SimulationPeriod=5 -v -timeout 24h -test_sim_gaia_import_export: runsim - @echo "Running Gaia import/export simulation. This may take several minutes..." - $(BINDIR)/runsim -e 25 5 TestGaiaImportExport +test_sim_app_import_export: runsim + @echo "Running application import/export simulation. This may take several minutes..." + $(BINDIR)/runsim -e $(SIMAPP) 25 5 TestAppImportExport -test_sim_gaia_simulation_after_import: runsim - @echo "Running Gaia simulation-after-import. This may take several minutes..." - $(BINDIR)/runsim -e 25 5 TestGaiaSimulationAfterImport +test_sim_app_simulation_after_import: runsim + @echo "Running application simulation-after-import. This may take several minutes..." + $(BINDIR)/runsim -e $(SIMAPP) 25 5 TestAppSimulationAfterImport -test_sim_gaia_custom_genesis_multi_seed: runsim +test_sim_app_custom_genesis_multi_seed: runsim @echo "Running multi-seed custom genesis simulation..." @echo "By default, ${HOME}/.gaiad/config/genesis.json will be used." - $(BINDIR)/runsim -g ${HOME}/.gaiad/config/genesis.json 400 5 TestFullGaiaSimulation + $(BINDIR)/runsim -g ${HOME}/.gaiad/config/genesis.json $(SIMAPP) 400 5 TestFullAppSimulation -test_sim_gaia_multi_seed: runsim - @echo "Running multi-seed Gaia simulation. This may take awhile!" - $(BINDIR)/runsim 400 5 TestFullGaiaSimulation +test_sim_app_multi_seed: runsim + @echo "Running multi-seed application simulation. This may take awhile!" + $(BINDIR)/runsim $(SIMAPP) 400 5 TestFullAppSimulation test_sim_benchmark_invariants: @echo "Running simulation invariant benchmarks..." - @go test -mod=readonly ./cmd/gaia/app -benchmem -bench=BenchmarkInvariants -run=^$ \ + @go test -mod=readonly $(SIMAPP) -benchmem -bench=BenchmarkInvariants -run=^$ \ -SimulationEnabled=true -SimulationNumBlocks=1000 -SimulationBlockSize=200 \ -SimulationCommit=true -SimulationSeed=57 -v -timeout 24h # Don't move it into tools - this will be gone once gaia has moved into the new repo runsim: $(BINDIR)/runsim -$(BINDIR)/runsim: cmd/gaia/contrib/runsim/main.go - go install github.com/cosmos/cosmos-sdk/cmd/gaia/contrib/runsim +$(BINDIR)/runsim: contrib/runsim/main.go + go install github.com/cosmos/cosmos-sdk/contrib/runsim SIM_NUM_BLOCKS ?= 500 SIM_BLOCK_SIZE ?= 200 SIM_COMMIT ?= true -test_sim_gaia_benchmark: - @echo "Running Gaia benchmark for numBlocks=$(SIM_NUM_BLOCKS), blockSize=$(SIM_BLOCK_SIZE). This may take awhile!" - @go test -mod=readonly -benchmem -run=^$$ github.com/cosmos/cosmos-sdk/cmd/gaia/app -bench ^BenchmarkFullGaiaSimulation$$ \ + +test_sim_app_benchmark: + @echo "Running application benchmark for numBlocks=$(SIM_NUM_BLOCKS), blockSize=$(SIM_BLOCK_SIZE). This may take awhile!" + @go test -mod=readonly -benchmem -run=^$$ $(SIMAPP) -bench ^BenchmarkFullAppSimulation$$ \ -SimulationEnabled=true -SimulationNumBlocks=$(SIM_NUM_BLOCKS) -SimulationBlockSize=$(SIM_BLOCK_SIZE) -SimulationCommit=$(SIM_COMMIT) -timeout 24h -test_sim_gaia_profile: - @echo "Running Gaia benchmark for numBlocks=$(SIM_NUM_BLOCKS), blockSize=$(SIM_BLOCK_SIZE). This may take awhile!" - @go test -mod=readonly -benchmem -run=^$$ github.com/cosmos/cosmos-sdk/cmd/gaia/app -bench ^BenchmarkFullGaiaSimulation$$ \ +test_sim_app_profile: + @echo "Running application benchmark for numBlocks=$(SIM_NUM_BLOCKS), blockSize=$(SIM_BLOCK_SIZE). This may take awhile!" + @go test -mod=readonly -benchmem -run=^$$ $(SIMAPP) -bench ^BenchmarkFullAppSimulation$$ \ -SimulationEnabled=true -SimulationNumBlocks=$(SIM_NUM_BLOCKS) -SimulationBlockSize=$(SIM_BLOCK_SIZE) -SimulationCommit=$(SIM_COMMIT) -timeout 24h -cpuprofile cpu.out -memprofile mem.out test_cover: @@ -251,22 +182,6 @@ devdoc_update: docker pull tendermint/devdoc -######################################## -### Local validator nodes using docker and docker-compose - -build-docker-gaiadnode: - $(MAKE) -C networks/local - -# Run a 4-node testnet locally -localnet-start: localnet-stop - @if ! [ -f build/node0/gaiad/config/genesis.json ]; then docker run --rm -v $(CURDIR)/build:/gaiad:Z tendermint/gaiadnode testnet --v 4 -o . --starting-ip-address 192.168.10.2 ; fi - docker-compose up -d - -# Stop testnet -localnet-stop: - docker-compose down - - ######################################## ### Packaging @@ -276,11 +191,9 @@ snapcraft-local.yaml: snapcraft-local.yaml.in # 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: install install_debug dist clean \ -draw_deps test test_cli test_unit \ -test_cover lint benchmark devdoc_init devdoc devdoc_save devdoc_update \ -build-linux build-docker-gaiadnode localnet-start localnet-stop \ -format check-ledger test_sim_gaia_nondeterminism test_sim_modules test_sim_gaia_fast \ -test_sim_gaia_custom_genesis_fast test_sim_gaia_custom_genesis_multi_seed \ -test_sim_gaia_multi_seed test_sim_gaia_import_export test_sim_benchmark_invariants \ +.PHONY: build dist clean draw_deps test test_unit test_cover lint \ +benchmark devdoc_init devdoc devdoc_save devdoc_update runsim \ +format test_sim_app_nondeterminism test_sim_modules test_sim_app_fast \ +test_sim_app_custom_genesis_fast test_sim_app_custom_genesis_multi_seed \ +test_sim_app_multi_seed test_sim_app_import_export test_sim_benchmark_invariants \ go-mod-cache diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index d184085647..eb94c73880 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -231,7 +231,7 @@ func (app *BaseApp) initFromMainStore(baseKey *sdk.KVStoreKey) error { app.setConsensusParams(consensusParams) } - // needed for `gaiad export`, which inits from store but never calls initchain + // needed for the export command which inits from store but never calls initchain app.setCheckState(abci.Header{}) app.Seal() diff --git a/client/config.go b/client/config.go index 4946a96ea8..af2b81d9e5 100644 --- a/client/config.go +++ b/client/config.go @@ -28,12 +28,12 @@ var configDefaults = map[string]string{ "broadcast-mode": "sync", } -// ConfigCmd returns a CLI command to interactively create a -// Gaia CLI config file. +// ConfigCmd returns a CLI command to interactively create an application CLI +// config file. func ConfigCmd(defaultCLIHome string) *cobra.Command { cmd := &cobra.Command{ Use: "config [value]", - Short: "Create or query a Gaia CLI configuration file", + Short: "Create or query an application CLI configuration file", RunE: runConfigCmd, Args: cobra.RangeArgs(0, 2), } diff --git a/client/context/errors.go b/client/context/errors.go index f8f6b63244..55f11f8453 100644 --- a/client/context/errors.go +++ b/client/context/errors.go @@ -17,6 +17,6 @@ Are you sure there has been a transaction involving it?`, addr) // height can't be verified. The reason is that the base checkpoint of the certifier is // newer than the given height func ErrVerifyCommit(height int64) error { - return fmt.Errorf(`The height of base truststore in gaia-lite is higher than height %d. + return fmt.Errorf(`The height of base truststore in the light client is higher than height %d. Can't verify blockchain proof at this height. Please set --trust-node to true and try again`, height) } diff --git a/client/keys/delete.go b/client/keys/delete.go index 3803a3a188..0082e0d8fa 100644 --- a/client/keys/delete.go +++ b/client/keys/delete.go @@ -27,8 +27,7 @@ func deleteKeyCommand() *cobra.Command { Note that removing offline or ledger keys will remove only the public key references stored locally, i.e. -private keys stored in a ledger device cannot be deleted with -gaiacli. +private keys stored in a ledger device cannot be deleted with the CLI. `, RunE: runDeleteCmd, Args: cobra.ExactArgs(1), diff --git a/client/lcd/root.go b/client/lcd/root.go index bdeaf57bfb..1e4c7d1098 100644 --- a/client/lcd/root.go +++ b/client/lcd/root.go @@ -69,7 +69,7 @@ func (rs *RestServer) Start(listenAddr string, maxOpen int, readTimeout, writeTi } rs.log.Info( fmt.Sprintf( - "Starting Gaia Lite REST service (chain-id: %q)...", + "Starting application REST service (chain-id: %q)...", viper.GetString(client.FlagChainID), ), ) @@ -77,7 +77,7 @@ func (rs *RestServer) Start(listenAddr string, maxOpen int, readTimeout, writeTi return rpcserver.StartHTTPServer(rs.listener, rs.Mux, rs.log, cfg) } -// ServeCommand will start a Gaia Lite REST service as a blocking process. It +// ServeCommand will start the application REST service as a blocking process. It // takes a codec to create a RestServer object and a function to register all // necessary routes. func ServeCommand(cdc *codec.Codec, registerRoutesFn func(*RestServer)) *cobra.Command { diff --git a/client/tx/broadcast.go b/client/tx/broadcast.go index 15afff00fa..bb45b73999 100644 --- a/client/tx/broadcast.go +++ b/client/tx/broadcast.go @@ -71,7 +71,7 @@ flag and signed with the sign command. Read a transaction from [file_path] and broadcast it to a node. If you supply a dash (-) argument in place of an input filename, the command reads from standard input. -$ gaiacli tx broadcast ./mytxn.json +$ tx broadcast ./mytxn.json `), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) (err error) { diff --git a/client/tx/query.go b/client/tx/query.go index ea223c63b6..849168aa51 100644 --- a/client/tx/query.go +++ b/client/tx/query.go @@ -37,7 +37,7 @@ func SearchTxCmd(cdc *codec.Codec) *cobra.Command { Search for transactions that match the exact given tags where results are paginated. Example: -$ gaiacli query txs --tags ':&:' --page 1 --limit 30 +$ query txs --tags ':&:' --page 1 --limit 30 `), RunE: func(cmd *cobra.Command, args []string) error { tagsStr := viper.GetString(flagTags) diff --git a/cmd/gaia/Makefile b/cmd/gaia/Makefile deleted file mode 100644 index 518812ceed..0000000000 --- a/cmd/gaia/Makefile +++ /dev/null @@ -1,150 +0,0 @@ -#!/usr/bin/make -f - -PACKAGES_SIMTEST=$(shell go list ./... | grep '/simulation') -VERSION := $(shell echo $(shell git describe --tags) | sed 's/^v//') -COMMIT := $(shell git log -1 --format='%H') -LEDGER_ENABLED ?= true -GOBIN ?= $(GOPATH)/bin - -export GO111MODULE = on - -# process build tags - -build_tags = netgo -ifeq ($(LEDGER_ENABLED),true) - ifeq ($(OS),Windows_NT) - GCCEXE = $(shell where gcc.exe 2> NUL) - ifeq ($(GCCEXE),) - $(error gcc.exe not installed for ledger support, please install or set LEDGER_ENABLED=false) - else - build_tags += ledger - endif - else - UNAME_S = $(shell uname -s) - ifeq ($(UNAME_S),OpenBSD) - $(warning OpenBSD detected, disabling ledger support (https://github.com/cosmos/cosmos-sdk/issues/1988)) - else - GCC = $(shell command -v gcc 2> /dev/null) - ifeq ($(GCC),) - $(error gcc not installed for ledger support, please install or set LEDGER_ENABLED=false) - else - build_tags += ledger - endif - endif - endif -endif - -ifeq ($(WITH_CLEVELDB),yes) - build_tags += gcc -endif -build_tags += $(BUILD_TAGS) -build_tags := $(strip $(build_tags)) - -whitespace := -whitespace += $(whitespace) -comma := , -build_tags_comma_sep := $(subst $(whitespace),$(comma),$(build_tags)) - -# process linker flags - -ldflags = -X github.com/cosmos/cosmos-sdk/version.Name=gaia \ - -X github.com/cosmos/cosmos-sdk/version.Version=$(VERSION) \ - -X github.com/cosmos/cosmos-sdk/version.Commit=$(COMMIT) \ - -X "github.com/cosmos/cosmos-sdk/version.BuildTags=$(build_tags_comma_sep)" - -ifeq ($(WITH_CLEVELDB),yes) - ldflags += -X github.com/cosmos/cosmos-sdk/types.DBBackend=cleveldb -endif -ldflags += $(LDFLAGS) -ldflags := $(strip $(ldflags)) - -BUILD_FLAGS := -tags "$(build_tags)" -ldflags '$(ldflags)' - -# The below include contains the tools target. -include ../../contrib/devtools/Makefile - -all: install lint check - -build: ../../go.sum -ifeq ($(OS),Windows_NT) - go build -mod=readonly $(BUILD_FLAGS) -o build/gaiad.exe ../../cmd/gaia/cmd/gaiad - go build -mod=readonly $(BUILD_FLAGS) -o build/gaiacli.exe ../../cmd/gaia/cmd/gaiacli -else - go build -mod=readonly $(BUILD_FLAGS) -o build/gaiad ../../cmd/gaia/cmd/gaiad - go build -mod=readonly $(BUILD_FLAGS) -o build/gaiacli ../../cmd/gaia/cmd/gaiacli -endif - -build-linux: ../../go.sum - LEDGER_ENABLED=false GOOS=linux GOARCH=amd64 $(MAKE) build - -install: ../../go.sum check-ledger - go install -mod=readonly $(BUILD_FLAGS) ../../cmd/gaia/cmd/gaiad - go install -mod=readonly $(BUILD_FLAGS) ../../cmd/gaia/cmd/gaiacli - -install-debug: ../../go.sum - go install -mod=readonly $(BUILD_FLAGS) ../../cmd/gaia/cmd/gaiadebug - - -######################################## -### Tools & dependencies - -go-mod-cache: go.sum - @echo "--> Download go modules to local cache" - @go mod download - -go.sum: go.mod - @echo "--> Ensure dependencies have not been modified" - @go mod verify - -draw-deps: - @# requires brew install graphviz or apt-get install graphviz - go get github.com/RobotsAndPencils/goviz - @goviz -i ./cmd/gaiad -d 2 | dot -Tpng -o dependency-graph.png - -clean: - rm -rf snapcraft-local.yaml build/ - -distclean: clean - rm -rf vendor/ - -######################################## -### Testing - - -check: check-unit -check-unit: - @VERSION=$(VERSION) go test -mod=readonly -race -tags='ledger test_ledger_mock' ./... - -check-race: - @VERSION=$(VERSION) go test -mod=readonly -tags='ledger test_ledger_mock' -race ./... - -check-cover: - @go test -mod=readonly -timeout 30m -race -coverprofile=coverage.txt -covermode=atomic -tags='ledger test_ledger_mock' ./... - -check-build: build - @go test -mod=readonly -p 4 `go list ./cli_test/...` -tags=cli_test - -check-all: check-unit check-race check-cover check-build - -lint: ci-lint -ci-lint: - golangci-lint run - find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" | xargs gofmt -d -s - go mod verify - -format: - find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/lcd/statik/statik.go" | xargs gofmt -w -s - find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/lcd/statik/statik.go" | xargs misspell -w - find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/lcd/statik/statik.go" | xargs goimports -w -local github.com/cosmos/cosmos-sdk - -benchmark: - @go test -mod=readonly -bench=. ./... - - -# include simulations -include sims.mk - -.PHONY: all build-linux install install-debug \ - go-mod-cache draw-deps clean \ - check check-all check-build check-cover check-ledger check-unit check-race - diff --git a/cmd/gaia/app/benchmarks/txsize_test.go b/cmd/gaia/app/benchmarks/txsize_test.go deleted file mode 100644 index af381a3fd6..0000000000 --- a/cmd/gaia/app/benchmarks/txsize_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package app - -import ( - "fmt" - - "github.com/tendermint/tendermint/crypto/secp256k1" - - "github.com/cosmos/cosmos-sdk/cmd/gaia/app" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/bank" -) - -// This will fail half the time with the second output being 173 -// This is due to secp256k1 signatures not being constant size. -// nolint: vet -func ExampleTxSendSize() { - cdc := app.MakeCodec() - var gas uint64 = 1 - - priv1 := secp256k1.GenPrivKeySecp256k1([]byte{0}) - addr1 := sdk.AccAddress(priv1.PubKey().Address()) - priv2 := secp256k1.GenPrivKeySecp256k1([]byte{1}) - addr2 := sdk.AccAddress(priv2.PubKey().Address()) - coins := sdk.Coins{sdk.NewCoin("denom", sdk.NewInt(10))} - msg1 := bank.MsgMultiSend{ - Inputs: []bank.Input{bank.NewInput(addr1, coins)}, - Outputs: []bank.Output{bank.NewOutput(addr2, coins)}, - } - fee := auth.NewStdFee(gas, coins) - signBytes := auth.StdSignBytes("example-chain-ID", - 1, 1, fee, []sdk.Msg{msg1}, "") - sig, _ := priv1.Sign(signBytes) - sigs := []auth.StdSignature{{nil, sig}} - tx := auth.NewStdTx([]sdk.Msg{msg1}, fee, sigs, "") - fmt.Println(len(cdc.MustMarshalBinaryBare([]sdk.Msg{msg1}))) - fmt.Println(len(cdc.MustMarshalBinaryBare(tx))) - // output: 80 - // 169 -} diff --git a/cmd/gaia/app/test_util.go b/cmd/gaia/app/test_util.go deleted file mode 100644 index 6f89efab49..0000000000 --- a/cmd/gaia/app/test_util.go +++ /dev/null @@ -1,22 +0,0 @@ -package app - -import ( - "io" - - "github.com/tendermint/tendermint/libs/log" - - bam "github.com/cosmos/cosmos-sdk/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking" - dbm "github.com/tendermint/tendermint/libs/db" -) - -// used for debugging by gaia/cmd/gaiadebug -// NOTE to not use this function with non-test code -func NewGaiaAppUNSAFE(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bool, - invCheckPeriod uint, baseAppOptions ...func(*bam.BaseApp), -) (gapp *GaiaApp, keyMain, keyStaking *sdk.KVStoreKey, stakingKeeper staking.Keeper) { - - gapp = NewGaiaApp(logger, db, traceStore, loadLatest, invCheckPeriod, baseAppOptions...) - return gapp, gapp.keyMain, gapp.keyStaking, gapp.stakingKeeper -} diff --git a/cmd/gaia/cli_test/README.md b/cmd/gaia/cli_test/README.md deleted file mode 100644 index 857150ca57..0000000000 --- a/cmd/gaia/cli_test/README.md +++ /dev/null @@ -1,51 +0,0 @@ -# Gaia CLI Integration tests - -The gaia cli integration tests live in this folder. You can run the full suite by running: - -```bash -$ go test -mod=readonly -p 4 `go list ./cmd/gaia/cli_test/...` -tags=cli_test -# OR! -$ make test_cli -``` -> NOTE: While the full suite runs in parallel, some of the tests can take up to a minute to complete - -### Test Structure - -This integration suite [uses a thin wrapper](https://godoc.org/github.com/cosmos/cosmos-sdk/tests) over the [`os/exec`](https://golang.org/pkg/os/exec/) package. This allows the integration test to run against built binaries (both `gaiad` and `gaiacli` are used) while being written in golang. This allows tests to take advantage of the various golang code we have for operations like marshal/unmarshal, crypto, etc... - -> NOTE: The tests will use whatever `gaiad` or `gaiacli` binaries are available in your `$PATH`. You can check which binary will be run by the suite by running `which gaiad` or `which gaiacli`. If you have your `$GOPATH` properly setup they should be in `$GOPATH/bin/gaia*`. This will ensure that your test uses the latest binary you have built - -Tests generally follow this structure: - -```go -func TestMyNewCommand(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start gaiad server - proc := f.GDStart() - defer proc.Stop(false) - - // Your test code goes here... - - f.Cleanup() -} -``` - -This boilerplate above: -- Ensures the tests run in parallel. Because the tests are calling out to `os/exec` for many operations these tests can take a long time to run. -- Creates `.gaiad` and `.gaiacli` folders in a new temp folder. -- Uses `gaiacli` to create 2 accounts for use in testing: `foo` and `bar` -- Creates a genesis file with coins (`1000footoken,1000feetoken,150stake`) controlled by the `foo` key -- Generates an initial bonding transaction (`gentx`) to make the `foo` key a validator at genesis -- Starts `gaiad` and stops it once the test exits -- Cleans up test state on a successful run - -### Notes when adding/running tests - -- Because the tests run against a built binary, you should make sure you build every time the code changes and you want to test again, otherwise you will be testing against an older version. If you are adding new tests this can easily lead to confusing test results. -- The [`test_helpers.go`](./test_helpers.go) file is organized according to the format of `gaiacli` and `gaiad` commands. There are comments with section headers describing the different areas. Helper functions to call CLI functionality are generally named after the command (e.g. `gaiacli query staking validator` would be `QueryStakingValidator`). Try to keep functions grouped by their position in the command tree. -- Test state that is needed by `tx` and `query` commands (`home`, `chain_id`, etc...) is stored on the `Fixtures` object. This makes constructing your new tests almost trivial. -- Sometimes if you exit a test early there can be still running `gaiad` and `gaiacli` processes that will interrupt subsequent runs. Still running `gaiacli` processes will block access to the keybase while still running `gaiad` processes will block ports and prevent new tests from spinning up. You can ensure new tests spin up clean by running `pkill -9 gaiad && pkill -9 gaiacli` before each test run. -- Most `query` and `tx` commands take a variadic `flags` argument. This pattern allows for the creation of a general function which is easily modified by adding flags. See the `TxSend` function and its use for a good example. -- `Tx*` functions follow a general pattern and return `(success bool, stdout string, stderr string)`. This allows for easy testing of multiple different flag configurations. See `TestGaiaCLICreateValidator` or `TestGaiaCLISubmitProposal` for a good example of the pattern. diff --git a/cmd/gaia/cli_test/cli_test.go b/cmd/gaia/cli_test/cli_test.go deleted file mode 100644 index 8ba0573cff..0000000000 --- a/cmd/gaia/cli_test/cli_test.go +++ /dev/null @@ -1,1251 +0,0 @@ -// +build cli_test - -package clitest - -import ( - "encoding/base64" - "errors" - "fmt" - "io/ioutil" - "os" - "path" - "path/filepath" - "strings" - "testing" - "time" - - "github.com/tendermint/tendermint/crypto/ed25519" - tmtypes "github.com/tendermint/tendermint/types" - - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/cmd/gaia/app" - "github.com/cosmos/cosmos-sdk/tests" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/auth/genaccounts" - "github.com/cosmos/cosmos-sdk/x/gov" - "github.com/cosmos/cosmos-sdk/x/mint" -) - -func TestGaiaCLIKeysAddMultisig(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // key names order does not matter - f.KeysAdd("msig1", "--multisig-threshold=2", - fmt.Sprintf("--multisig=%s,%s", keyBar, keyBaz)) - f.KeysAdd("msig2", "--multisig-threshold=2", - fmt.Sprintf("--multisig=%s,%s", keyBaz, keyBar)) - require.Equal(t, f.KeysShow("msig1").Address, f.KeysShow("msig2").Address) - - f.KeysAdd("msig3", "--multisig-threshold=2", - fmt.Sprintf("--multisig=%s,%s", keyBar, keyBaz), - "--nosort") - f.KeysAdd("msig4", "--multisig-threshold=2", - fmt.Sprintf("--multisig=%s,%s", keyBaz, keyBar), - "--nosort") - require.NotEqual(t, f.KeysShow("msig3").Address, f.KeysShow("msig4").Address) - - // Cleanup testing directories - f.Cleanup() -} - -func TestGaiaCLIKeysAddRecover(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - exitSuccess, _, _ := f.KeysAddRecover("empty-mnemonic", "") - require.False(t, exitSuccess) - - exitSuccess, _, _ = f.KeysAddRecover("test-recover", "dentist task convince chimney quality leave banana trade firm crawl eternal easily") - require.True(t, exitSuccess) - require.Equal(t, "cosmos1qcfdf69js922qrdr4yaww3ax7gjml6pdds46f4", f.KeyAddress("test-recover").String()) - - // Cleanup testing directories - f.Cleanup() -} - -func TestGaiaCLIKeysAddRecoverHDPath(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - f.KeysAddRecoverHDPath("test-recoverHD1", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", 0, 0) - require.Equal(t, "cosmos1qcfdf69js922qrdr4yaww3ax7gjml6pdds46f4", f.KeyAddress("test-recoverHD1").String()) - - f.KeysAddRecoverHDPath("test-recoverH2", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", 1, 5) - require.Equal(t, "cosmos1pdfav2cjhry9k79nu6r8kgknnjtq6a7rykmafy", f.KeyAddress("test-recoverH2").String()) - - f.KeysAddRecoverHDPath("test-recoverH3", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", 1, 17) - require.Equal(t, "cosmos1909k354n6wl8ujzu6kmh49w4d02ax7qvlkv4sn", f.KeyAddress("test-recoverH3").String()) - - f.KeysAddRecoverHDPath("test-recoverH4", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", 2, 17) - require.Equal(t, "cosmos1v9plmhvyhgxk3th9ydacm7j4z357s3nhtwsjat", f.KeyAddress("test-recoverH4").String()) - - // Cleanup testing directories - f.Cleanup() -} - -func TestGaiaCLIMinimumFees(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start gaiad server with minimum fees - minGasPrice, _ := sdk.NewDecFromStr("0.000006") - fees := fmt.Sprintf( - "--minimum-gas-prices=%s,%s", - sdk.NewDecCoinFromDec(feeDenom, minGasPrice), - sdk.NewDecCoinFromDec(fee2Denom, minGasPrice), - ) - proc := f.GDStart(fees) - defer proc.Stop(false) - - barAddr := f.KeyAddress(keyBar) - - // Send a transaction that will get rejected - success, _, _ := f.TxSend(keyFoo, barAddr, sdk.NewInt64Coin(fee2Denom, 10), "-y") - require.False(f.T, success) - tests.WaitForNextNBlocksTM(1, f.Port) - - // Ensure tx w/ correct fees pass - txFees := fmt.Sprintf("--fees=%s", sdk.NewInt64Coin(feeDenom, 2)) - success, _, _ = f.TxSend(keyFoo, barAddr, sdk.NewInt64Coin(fee2Denom, 10), txFees, "-y") - require.True(f.T, success) - tests.WaitForNextNBlocksTM(1, f.Port) - - // Ensure tx w/ improper fees fails - txFees = fmt.Sprintf("--fees=%s", sdk.NewInt64Coin(feeDenom, 1)) - success, _, _ = f.TxSend(keyFoo, barAddr, sdk.NewInt64Coin(fooDenom, 10), txFees, "-y") - require.False(f.T, success) - - // Cleanup testing directories - f.Cleanup() -} - -func TestGaiaCLIGasPrices(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start gaiad server with minimum fees - minGasPrice, _ := sdk.NewDecFromStr("0.000006") - proc := f.GDStart(fmt.Sprintf("--minimum-gas-prices=%s", sdk.NewDecCoinFromDec(feeDenom, minGasPrice))) - defer proc.Stop(false) - - barAddr := f.KeyAddress(keyBar) - - // insufficient gas prices (tx fails) - badGasPrice, _ := sdk.NewDecFromStr("0.000003") - success, _, _ := f.TxSend( - keyFoo, barAddr, sdk.NewInt64Coin(fooDenom, 50), - fmt.Sprintf("--gas-prices=%s", sdk.NewDecCoinFromDec(feeDenom, badGasPrice)), "-y") - require.False(t, success) - - // wait for a block confirmation - tests.WaitForNextNBlocksTM(1, f.Port) - - // sufficient gas prices (tx passes) - success, _, _ = f.TxSend( - keyFoo, barAddr, sdk.NewInt64Coin(fooDenom, 50), - fmt.Sprintf("--gas-prices=%s", sdk.NewDecCoinFromDec(feeDenom, minGasPrice)), "-y") - require.True(t, success) - - // wait for a block confirmation - tests.WaitForNextNBlocksTM(1, f.Port) - - f.Cleanup() -} - -func TestGaiaCLIFeesDeduction(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start gaiad server with minimum fees - minGasPrice, _ := sdk.NewDecFromStr("0.000006") - proc := f.GDStart(fmt.Sprintf("--minimum-gas-prices=%s", sdk.NewDecCoinFromDec(feeDenom, minGasPrice))) - defer proc.Stop(false) - - // Save key addresses for later use - fooAddr := f.KeyAddress(keyFoo) - barAddr := f.KeyAddress(keyBar) - - fooAcc := f.QueryAccount(fooAddr) - fooAmt := fooAcc.GetCoins().AmountOf(fooDenom) - - // test simulation - success, _, _ := f.TxSend( - keyFoo, barAddr, sdk.NewInt64Coin(fooDenom, 1000), - fmt.Sprintf("--fees=%s", sdk.NewInt64Coin(feeDenom, 2)), "--dry-run") - require.True(t, success) - - // Wait for a block - tests.WaitForNextNBlocksTM(1, f.Port) - - // ensure state didn't change - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, fooAmt.Int64(), fooAcc.GetCoins().AmountOf(fooDenom).Int64()) - - // insufficient funds (coins + fees) tx fails - largeCoins := sdk.TokensFromTendermintPower(10000000) - success, _, _ = f.TxSend( - keyFoo, barAddr, sdk.NewCoin(fooDenom, largeCoins), - fmt.Sprintf("--fees=%s", sdk.NewInt64Coin(feeDenom, 2)), "-y") - require.False(t, success) - - // Wait for a block - tests.WaitForNextNBlocksTM(1, f.Port) - - // ensure state didn't change - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, fooAmt.Int64(), fooAcc.GetCoins().AmountOf(fooDenom).Int64()) - - // test success (transfer = coins + fees) - success, _, _ = f.TxSend( - keyFoo, barAddr, sdk.NewInt64Coin(fooDenom, 500), - fmt.Sprintf("--fees=%s", sdk.NewInt64Coin(feeDenom, 2)), "-y") - require.True(t, success) - - f.Cleanup() -} - -func TestGaiaCLISend(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start gaiad server - proc := f.GDStart() - defer proc.Stop(false) - - // Save key addresses for later use - fooAddr := f.KeyAddress(keyFoo) - barAddr := f.KeyAddress(keyBar) - - fooAcc := f.QueryAccount(fooAddr) - startTokens := sdk.TokensFromTendermintPower(50) - require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(denom)) - - // Send some tokens from one account to the other - sendTokens := sdk.TokensFromTendermintPower(10) - f.TxSend(keyFoo, barAddr, sdk.NewCoin(denom, sendTokens), "-y") - tests.WaitForNextNBlocksTM(1, f.Port) - - // Ensure account balances match expected - barAcc := f.QueryAccount(barAddr) - require.Equal(t, sendTokens, barAcc.GetCoins().AmountOf(denom)) - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, startTokens.Sub(sendTokens), fooAcc.GetCoins().AmountOf(denom)) - - // Test --dry-run - success, _, _ := f.TxSend(keyFoo, barAddr, sdk.NewCoin(denom, sendTokens), "--dry-run") - require.True(t, success) - - // Test --generate-only - success, stdout, stderr := f.TxSend( - fooAddr.String(), barAddr, sdk.NewCoin(denom, sendTokens), "--generate-only=true", - ) - require.Empty(t, stderr) - require.True(t, success) - msg := unmarshalStdTx(f.T, stdout) - require.NotZero(t, msg.Fee.Gas) - require.Len(t, msg.Msgs, 1) - require.Len(t, msg.GetSignatures(), 0) - - // Check state didn't change - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, startTokens.Sub(sendTokens), fooAcc.GetCoins().AmountOf(denom)) - - // test autosequencing - f.TxSend(keyFoo, barAddr, sdk.NewCoin(denom, sendTokens), "-y") - tests.WaitForNextNBlocksTM(1, f.Port) - - // Ensure account balances match expected - barAcc = f.QueryAccount(barAddr) - require.Equal(t, sendTokens.MulRaw(2), barAcc.GetCoins().AmountOf(denom)) - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, startTokens.Sub(sendTokens.MulRaw(2)), fooAcc.GetCoins().AmountOf(denom)) - - // test memo - f.TxSend(keyFoo, barAddr, sdk.NewCoin(denom, sendTokens), "--memo='testmemo'", "-y") - tests.WaitForNextNBlocksTM(1, f.Port) - - // Ensure account balances match expected - barAcc = f.QueryAccount(barAddr) - require.Equal(t, sendTokens.MulRaw(3), barAcc.GetCoins().AmountOf(denom)) - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, startTokens.Sub(sendTokens.MulRaw(3)), fooAcc.GetCoins().AmountOf(denom)) - - f.Cleanup() -} - -func TestGaiaCLIConfirmTx(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start gaiad server - proc := f.GDStart() - defer proc.Stop(false) - - // Save key addresses for later use - fooAddr := f.KeyAddress(keyFoo) - barAddr := f.KeyAddress(keyBar) - - fooAcc := f.QueryAccount(fooAddr) - startTokens := sdk.TokensFromTendermintPower(50) - require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(denom)) - - // send some tokens from one account to the other - sendTokens := sdk.TokensFromTendermintPower(10) - f.txSendWithConfirm(keyFoo, barAddr, sdk.NewCoin(denom, sendTokens), "Y") - tests.WaitForNextNBlocksTM(1, f.Port) - - // ensure account balances match expected - barAcc := f.QueryAccount(barAddr) - require.Equal(t, sendTokens, barAcc.GetCoins().AmountOf(denom)) - - // send some tokens from one account to the other (cancelling confirmation) - f.txSendWithConfirm(keyFoo, barAddr, sdk.NewCoin(denom, sendTokens), "n") - tests.WaitForNextNBlocksTM(1, f.Port) - - // ensure account balances match expected - barAcc = f.QueryAccount(barAddr) - require.Equal(t, sendTokens, barAcc.GetCoins().AmountOf(denom)) - - // Cleanup testing directories - f.Cleanup() -} - -func TestGaiaCLIGasAuto(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start gaiad server - proc := f.GDStart() - defer proc.Stop(false) - - fooAddr := f.KeyAddress(keyFoo) - barAddr := f.KeyAddress(keyBar) - - fooAcc := f.QueryAccount(fooAddr) - startTokens := sdk.TokensFromTendermintPower(50) - require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(denom)) - - // Test failure with auto gas disabled and very little gas set by hand - sendTokens := sdk.TokensFromTendermintPower(10) - success, _, _ := f.TxSend(keyFoo, barAddr, sdk.NewCoin(denom, sendTokens), "--gas=10", "-y") - require.False(t, success) - - // Check state didn't change - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(denom)) - - // Test failure with negative gas - success, _, _ = f.TxSend(keyFoo, barAddr, sdk.NewCoin(denom, sendTokens), "--gas=-100", "-y") - require.False(t, success) - - // Check state didn't change - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(denom)) - - // Test failure with 0 gas - success, _, _ = f.TxSend(keyFoo, barAddr, sdk.NewCoin(denom, sendTokens), "--gas=0", "-y") - require.False(t, success) - - // Check state didn't change - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(denom)) - - // Enable auto gas - success, stdout, stderr := f.TxSend(keyFoo, barAddr, sdk.NewCoin(denom, sendTokens), "--gas=auto", "-y") - require.NotEmpty(t, stderr) - require.True(t, success) - cdc := app.MakeCodec() - sendResp := sdk.TxResponse{} - err := cdc.UnmarshalJSON([]byte(stdout), &sendResp) - require.Nil(t, err) - require.True(t, sendResp.GasWanted >= sendResp.GasUsed) - tests.WaitForNextNBlocksTM(1, f.Port) - - // Check state has changed accordingly - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, startTokens.Sub(sendTokens), fooAcc.GetCoins().AmountOf(denom)) - - f.Cleanup() -} - -func TestGaiaCLICreateValidator(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start gaiad server - proc := f.GDStart() - defer proc.Stop(false) - - barAddr := f.KeyAddress(keyBar) - barVal := sdk.ValAddress(barAddr) - - consPubKey := sdk.MustBech32ifyConsPub(ed25519.GenPrivKey().PubKey()) - - sendTokens := sdk.TokensFromTendermintPower(10) - f.TxSend(keyFoo, barAddr, sdk.NewCoin(denom, sendTokens), "-y") - tests.WaitForNextNBlocksTM(1, f.Port) - - barAcc := f.QueryAccount(barAddr) - require.Equal(t, sendTokens, barAcc.GetCoins().AmountOf(denom)) - - // Generate a create validator transaction and ensure correctness - success, stdout, stderr := f.TxStakingCreateValidator(barAddr.String(), consPubKey, sdk.NewInt64Coin(denom, 2), "--generate-only") - - require.True(f.T, success) - require.Empty(f.T, stderr) - msg := unmarshalStdTx(f.T, stdout) - require.NotZero(t, msg.Fee.Gas) - require.Equal(t, len(msg.Msgs), 1) - require.Equal(t, 0, len(msg.GetSignatures())) - - // Test --dry-run - newValTokens := sdk.TokensFromTendermintPower(2) - success, _, _ = f.TxStakingCreateValidator(keyBar, consPubKey, sdk.NewCoin(denom, newValTokens), "--dry-run") - require.True(t, success) - - // Create the validator - f.TxStakingCreateValidator(keyBar, consPubKey, sdk.NewCoin(denom, newValTokens), "-y") - tests.WaitForNextNBlocksTM(1, f.Port) - - // Ensure funds were deducted properly - barAcc = f.QueryAccount(barAddr) - require.Equal(t, sendTokens.Sub(newValTokens), barAcc.GetCoins().AmountOf(denom)) - - // Ensure that validator state is as expected - validator := f.QueryStakingValidator(barVal) - require.Equal(t, validator.OperatorAddress, barVal) - require.True(sdk.IntEq(t, newValTokens, validator.Tokens)) - - // Query delegations to the validator - validatorDelegations := f.QueryStakingDelegationsTo(barVal) - require.Len(t, validatorDelegations, 1) - require.NotZero(t, validatorDelegations[0].Shares) - - // unbond a single share - unbondAmt := sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromTendermintPower(1)) - success = f.TxStakingUnbond(keyBar, unbondAmt.String(), barVal, "-y") - require.True(t, success) - tests.WaitForNextNBlocksTM(1, f.Port) - - // Ensure bonded staking is correct - remainingTokens := newValTokens.Sub(unbondAmt.Amount) - validator = f.QueryStakingValidator(barVal) - require.Equal(t, remainingTokens, validator.Tokens) - - // Get unbonding delegations from the validator - validatorUbds := f.QueryStakingUnbondingDelegationsFrom(barVal) - require.Len(t, validatorUbds, 1) - require.Len(t, validatorUbds[0].Entries, 1) - require.Equal(t, remainingTokens.String(), validatorUbds[0].Entries[0].Balance.String()) - - f.Cleanup() -} - -func TestGaiaCLIQueryRewards(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - cdc := app.MakeCodec() - - genesisState := f.GenesisState() - inflationMin := sdk.MustNewDecFromStr("10000.0") - var mintData mint.GenesisState - cdc.UnmarshalJSON(genesisState[mint.ModuleName], &mintData) - mintData.Minter.Inflation = inflationMin - mintData.Params.InflationMin = inflationMin - mintData.Params.InflationMax = sdk.MustNewDecFromStr("15000.0") - mintDataBz, err := cdc.MarshalJSON(mintData) - require.NoError(t, err) - genesisState[mint.ModuleName] = mintDataBz - - genFile := filepath.Join(f.GaiadHome, "config", "genesis.json") - genDoc, err := tmtypes.GenesisDocFromFile(genFile) - require.NoError(t, err) - genDoc.AppState, err = cdc.MarshalJSON(genesisState) - require.NoError(t, err) - require.NoError(t, genDoc.SaveAs(genFile)) - - // start gaiad server - proc := f.GDStart() - defer proc.Stop(false) - - fooAddr := f.KeyAddress(keyFoo) - rewards := f.QueryRewards(fooAddr) - require.Equal(t, 1, len(rewards.Rewards)) - - f.Cleanup() -} - -func TestGaiaCLISubmitProposal(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start gaiad server - proc := f.GDStart() - defer proc.Stop(false) - - f.QueryGovParamDeposit() - f.QueryGovParamVoting() - f.QueryGovParamTallying() - - fooAddr := f.KeyAddress(keyFoo) - - fooAcc := f.QueryAccount(fooAddr) - startTokens := sdk.TokensFromTendermintPower(50) - require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(sdk.DefaultBondDenom)) - - proposalsQuery := f.QueryGovProposals() - require.Empty(t, proposalsQuery) - - // Test submit generate only for submit proposal - proposalTokens := sdk.TokensFromTendermintPower(5) - success, stdout, stderr := f.TxGovSubmitProposal( - fooAddr.String(), "Text", "Test", "test", sdk.NewCoin(denom, proposalTokens), "--generate-only", "-y") - require.True(t, success) - require.Empty(t, stderr) - msg := unmarshalStdTx(t, stdout) - require.NotZero(t, msg.Fee.Gas) - require.Equal(t, len(msg.Msgs), 1) - require.Equal(t, 0, len(msg.GetSignatures())) - - // Test --dry-run - success, _, _ = f.TxGovSubmitProposal(keyFoo, "Text", "Test", "test", sdk.NewCoin(denom, proposalTokens), "--dry-run") - require.True(t, success) - - // Create the proposal - f.TxGovSubmitProposal(keyFoo, "Text", "Test", "test", sdk.NewCoin(denom, proposalTokens), "-y") - tests.WaitForNextNBlocksTM(1, f.Port) - - // Ensure transaction tags can be queried - searchResult := f.QueryTxs(1, 50, "action:submit_proposal", fmt.Sprintf("sender:%s", fooAddr)) - require.Len(t, searchResult.Txs, 1) - - // Ensure deposit was deducted - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, startTokens.Sub(proposalTokens), fooAcc.GetCoins().AmountOf(denom)) - - // Ensure propsal is directly queryable - proposal1 := f.QueryGovProposal(1) - require.Equal(t, uint64(1), proposal1.ProposalID) - require.Equal(t, gov.StatusDepositPeriod, proposal1.Status) - - // Ensure query proposals returns properly - proposalsQuery = f.QueryGovProposals() - require.Equal(t, uint64(1), proposalsQuery[0].ProposalID) - - // Query the deposits on the proposal - deposit := f.QueryGovDeposit(1, fooAddr) - require.Equal(t, proposalTokens, deposit.Amount.AmountOf(denom)) - - // Test deposit generate only - depositTokens := sdk.TokensFromTendermintPower(10) - success, stdout, stderr = f.TxGovDeposit(1, fooAddr.String(), sdk.NewCoin(denom, depositTokens), "--generate-only") - require.True(t, success) - require.Empty(t, stderr) - msg = unmarshalStdTx(t, stdout) - require.NotZero(t, msg.Fee.Gas) - require.Equal(t, len(msg.Msgs), 1) - require.Equal(t, 0, len(msg.GetSignatures())) - - // Run the deposit transaction - f.TxGovDeposit(1, keyFoo, sdk.NewCoin(denom, depositTokens), "-y") - tests.WaitForNextNBlocksTM(1, f.Port) - - // test query deposit - deposits := f.QueryGovDeposits(1) - require.Len(t, deposits, 1) - require.Equal(t, proposalTokens.Add(depositTokens), deposits[0].Amount.AmountOf(denom)) - - // Ensure querying the deposit returns the proper amount - deposit = f.QueryGovDeposit(1, fooAddr) - require.Equal(t, proposalTokens.Add(depositTokens), deposit.Amount.AmountOf(denom)) - - // Ensure tags are set on the transaction - searchResult = f.QueryTxs(1, 50, "action:deposit", fmt.Sprintf("sender:%s", fooAddr)) - require.Len(t, searchResult.Txs, 1) - - // Ensure account has expected amount of funds - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, startTokens.Sub(proposalTokens.Add(depositTokens)), fooAcc.GetCoins().AmountOf(denom)) - - // Fetch the proposal and ensure it is now in the voting period - proposal1 = f.QueryGovProposal(1) - require.Equal(t, uint64(1), proposal1.ProposalID) - require.Equal(t, gov.StatusVotingPeriod, proposal1.Status) - - // Test vote generate only - success, stdout, stderr = f.TxGovVote(1, gov.OptionYes, fooAddr.String(), "--generate-only") - require.True(t, success) - require.Empty(t, stderr) - msg = unmarshalStdTx(t, stdout) - require.NotZero(t, msg.Fee.Gas) - require.Equal(t, len(msg.Msgs), 1) - require.Equal(t, 0, len(msg.GetSignatures())) - - // Vote on the proposal - f.TxGovVote(1, gov.OptionYes, keyFoo, "-y") - tests.WaitForNextNBlocksTM(1, f.Port) - - // Query the vote - vote := f.QueryGovVote(1, fooAddr) - require.Equal(t, uint64(1), vote.ProposalID) - require.Equal(t, gov.OptionYes, vote.Option) - - // Query the votes - votes := f.QueryGovVotes(1) - require.Len(t, votes, 1) - require.Equal(t, uint64(1), votes[0].ProposalID) - require.Equal(t, gov.OptionYes, votes[0].Option) - - // Ensure tags are applied to voting transaction properly - searchResult = f.QueryTxs(1, 50, "action:vote", fmt.Sprintf("sender:%s", fooAddr)) - require.Len(t, searchResult.Txs, 1) - - // Ensure no proposals in deposit period - proposalsQuery = f.QueryGovProposals("--status=DepositPeriod") - require.Empty(t, proposalsQuery) - - // Ensure the proposal returns as in the voting period - proposalsQuery = f.QueryGovProposals("--status=VotingPeriod") - require.Equal(t, uint64(1), proposalsQuery[0].ProposalID) - - // submit a second test proposal - f.TxGovSubmitProposal(keyFoo, "Text", "Apples", "test", sdk.NewCoin(denom, proposalTokens), "-y") - tests.WaitForNextNBlocksTM(1, f.Port) - - // Test limit on proposals query - proposalsQuery = f.QueryGovProposals("--limit=1") - require.Equal(t, uint64(2), proposalsQuery[0].ProposalID) - - f.Cleanup() -} - -func TestGaiaCLISubmitParamChangeProposal(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - proc := f.GDStart() - defer proc.Stop(false) - - fooAddr := f.KeyAddress(keyFoo) - fooAcc := f.QueryAccount(fooAddr) - startTokens := sdk.TokensFromTendermintPower(50) - require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(sdk.DefaultBondDenom)) - - // write proposal to file - proposalTokens := sdk.TokensFromTendermintPower(5) - proposal := fmt.Sprintf(`{ - "title": "Param Change", - "description": "Update max validators", - "changes": [ - { - "subspace": "staking", - "key": "MaxValidators", - "value": 105 - } - ], - "deposit": [ - { - "denom": "stake", - "amount": "%s" - } - ] -} -`, proposalTokens.String()) - - proposalFile := WriteToNewTempFile(t, proposal) - - // create the param change proposal - f.TxGovSubmitParamChangeProposal(keyFoo, proposalFile.Name(), sdk.NewCoin(denom, proposalTokens), "-y") - tests.WaitForNextNBlocksTM(1, f.Port) - - // ensure transaction tags can be queried - txsPage := f.QueryTxs(1, 50, "action:submit_proposal", fmt.Sprintf("sender:%s", fooAddr)) - require.Len(t, txsPage.Txs, 1) - - // ensure deposit was deducted - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, startTokens.Sub(proposalTokens).String(), fooAcc.GetCoins().AmountOf(sdk.DefaultBondDenom).String()) - - // ensure proposal is directly queryable - proposal1 := f.QueryGovProposal(1) - require.Equal(t, uint64(1), proposal1.ProposalID) - require.Equal(t, gov.StatusDepositPeriod, proposal1.Status) - - // ensure correct query proposals result - proposalsQuery := f.QueryGovProposals() - require.Equal(t, uint64(1), proposalsQuery[0].ProposalID) - - // ensure the correct deposit amount on the proposal - deposit := f.QueryGovDeposit(1, fooAddr) - require.Equal(t, proposalTokens, deposit.Amount.AmountOf(denom)) - - // Cleanup testing directories - f.Cleanup() -} - -func TestGaiaCLIQueryTxPagination(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start gaiad server - proc := f.GDStart() - defer proc.Stop(false) - - fooAddr := f.KeyAddress(keyFoo) - barAddr := f.KeyAddress(keyBar) - - accFoo := f.QueryAccount(fooAddr) - seq := accFoo.GetSequence() - - for i := 1; i <= 30; i++ { - success, _, _ := f.TxSend(keyFoo, barAddr, sdk.NewInt64Coin(fooDenom, int64(i)), fmt.Sprintf("--sequence=%d", seq), "-y") - require.True(t, success) - seq++ - } - - // perPage = 15, 2 pages - txsPage1 := f.QueryTxs(1, 15, fmt.Sprintf("sender:%s", fooAddr)) - require.Len(t, txsPage1.Txs, 15) - require.Equal(t, txsPage1.Count, 15) - txsPage2 := f.QueryTxs(2, 15, fmt.Sprintf("sender:%s", fooAddr)) - require.Len(t, txsPage2.Txs, 15) - require.NotEqual(t, txsPage1.Txs, txsPage2.Txs) - txsPage3 := f.QueryTxs(3, 15, fmt.Sprintf("sender:%s", fooAddr)) - require.Len(t, txsPage3.Txs, 15) - require.Equal(t, txsPage2.Txs, txsPage3.Txs) - - // perPage = 16, 2 pages - txsPage1 = f.QueryTxs(1, 16, fmt.Sprintf("sender:%s", fooAddr)) - require.Len(t, txsPage1.Txs, 16) - txsPage2 = f.QueryTxs(2, 16, fmt.Sprintf("sender:%s", fooAddr)) - require.Len(t, txsPage2.Txs, 14) - require.NotEqual(t, txsPage1.Txs, txsPage2.Txs) - - // perPage = 50 - txsPageFull := f.QueryTxs(1, 50, fmt.Sprintf("sender:%s", fooAddr)) - require.Len(t, txsPageFull.Txs, 30) - require.Equal(t, txsPageFull.Txs, append(txsPage1.Txs, txsPage2.Txs...)) - - // perPage = 0 - f.QueryTxsInvalid(errors.New("ERROR: page must greater than 0"), 0, 50, fmt.Sprintf("sender:%s", fooAddr)) - - // limit = 0 - f.QueryTxsInvalid(errors.New("ERROR: limit must greater than 0"), 1, 0, fmt.Sprintf("sender:%s", fooAddr)) - - // Cleanup testing directories - f.Cleanup() -} - -func TestGaiaCLIValidateSignatures(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start gaiad server - proc := f.GDStart() - defer proc.Stop(false) - - fooAddr := f.KeyAddress(keyFoo) - barAddr := f.KeyAddress(keyBar) - - // generate sendTx with default gas - success, stdout, stderr := f.TxSend(fooAddr.String(), barAddr, sdk.NewInt64Coin(denom, 10), "--generate-only") - require.True(t, success) - require.Empty(t, stderr) - - // write unsigned tx to file - unsignedTxFile := WriteToNewTempFile(t, stdout) - defer os.Remove(unsignedTxFile.Name()) - - // validate we can successfully sign - success, stdout, stderr = f.TxSign(keyFoo, unsignedTxFile.Name()) - require.True(t, success) - require.Empty(t, stderr) - stdTx := unmarshalStdTx(t, stdout) - require.Equal(t, len(stdTx.Msgs), 1) - require.Equal(t, 1, len(stdTx.GetSignatures())) - require.Equal(t, fooAddr.String(), stdTx.GetSigners()[0].String()) - - // write signed tx to file - signedTxFile := WriteToNewTempFile(t, stdout) - defer os.Remove(signedTxFile.Name()) - - // validate signatures - success, _, _ = f.TxSign(keyFoo, signedTxFile.Name(), "--validate-signatures") - require.True(t, success) - - // modify the transaction - stdTx.Memo = "MODIFIED-ORIGINAL-TX-BAD" - bz := marshalStdTx(t, stdTx) - modSignedTxFile := WriteToNewTempFile(t, string(bz)) - defer os.Remove(modSignedTxFile.Name()) - - // validate signature validation failure due to different transaction sig bytes - success, _, _ = f.TxSign(keyFoo, modSignedTxFile.Name(), "--validate-signatures") - require.False(t, success) - - f.Cleanup() -} - -func TestGaiaCLISendGenerateSignAndBroadcast(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start gaiad server - proc := f.GDStart() - defer proc.Stop(false) - - fooAddr := f.KeyAddress(keyFoo) - barAddr := f.KeyAddress(keyBar) - - // Test generate sendTx with default gas - sendTokens := sdk.TokensFromTendermintPower(10) - success, stdout, stderr := f.TxSend(fooAddr.String(), barAddr, sdk.NewCoin(denom, sendTokens), "--generate-only") - require.True(t, success) - require.Empty(t, stderr) - msg := unmarshalStdTx(t, stdout) - require.Equal(t, msg.Fee.Gas, uint64(client.DefaultGasLimit)) - require.Equal(t, len(msg.Msgs), 1) - require.Equal(t, 0, len(msg.GetSignatures())) - - // Test generate sendTx with --gas=$amount - success, stdout, stderr = f.TxSend(fooAddr.String(), barAddr, sdk.NewCoin(denom, sendTokens), "--gas=100", "--generate-only") - require.True(t, success) - require.Empty(t, stderr) - msg = unmarshalStdTx(t, stdout) - require.Equal(t, msg.Fee.Gas, uint64(100)) - require.Equal(t, len(msg.Msgs), 1) - require.Equal(t, 0, len(msg.GetSignatures())) - - // Test generate sendTx, estimate gas - success, stdout, stderr = f.TxSend(fooAddr.String(), barAddr, sdk.NewCoin(denom, sendTokens), "--generate-only") - require.True(t, success) - require.Empty(t, stderr) - msg = unmarshalStdTx(t, stdout) - require.True(t, msg.Fee.Gas > 0) - require.Equal(t, len(msg.Msgs), 1) - - // Write the output to disk - unsignedTxFile := WriteToNewTempFile(t, stdout) - defer os.Remove(unsignedTxFile.Name()) - - // Test sign --validate-signatures - success, stdout, _ = f.TxSign(keyFoo, unsignedTxFile.Name(), "--validate-signatures") - require.False(t, success) - require.Equal(t, fmt.Sprintf("Signers:\n 0: %v\n\nSignatures:\n\n", fooAddr.String()), stdout) - - // Test sign - success, stdout, _ = f.TxSign(keyFoo, unsignedTxFile.Name()) - require.True(t, success) - msg = unmarshalStdTx(t, stdout) - require.Equal(t, len(msg.Msgs), 1) - require.Equal(t, 1, len(msg.GetSignatures())) - require.Equal(t, fooAddr.String(), msg.GetSigners()[0].String()) - - // Write the output to disk - signedTxFile := WriteToNewTempFile(t, stdout) - defer os.Remove(signedTxFile.Name()) - - // Test sign --validate-signatures - success, stdout, _ = f.TxSign(keyFoo, signedTxFile.Name(), "--validate-signatures") - require.True(t, success) - require.Equal(t, fmt.Sprintf("Signers:\n 0: %v\n\nSignatures:\n 0: %v\t\t\t[OK]\n\n", fooAddr.String(), - fooAddr.String()), stdout) - - // Ensure foo has right amount of funds - fooAcc := f.QueryAccount(fooAddr) - startTokens := sdk.TokensFromTendermintPower(50) - require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(denom)) - - // Test broadcast - success, _, _ = f.TxBroadcast(signedTxFile.Name()) - require.True(t, success) - tests.WaitForNextNBlocksTM(1, f.Port) - - // Ensure account state - barAcc := f.QueryAccount(barAddr) - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, sendTokens, barAcc.GetCoins().AmountOf(denom)) - require.Equal(t, startTokens.Sub(sendTokens), fooAcc.GetCoins().AmountOf(denom)) - - f.Cleanup() -} - -func TestGaiaCLIMultisignInsufficientCosigners(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start gaiad server with minimum fees - proc := f.GDStart() - defer proc.Stop(false) - - fooBarBazAddr := f.KeyAddress(keyFooBarBaz) - barAddr := f.KeyAddress(keyBar) - - // Send some tokens from one account to the other - success, _, _ := f.TxSend(keyFoo, fooBarBazAddr, sdk.NewInt64Coin(denom, 10), "-y") - require.True(t, success) - tests.WaitForNextNBlocksTM(1, f.Port) - - // Test generate sendTx with multisig - success, stdout, _ := f.TxSend(fooBarBazAddr.String(), barAddr, sdk.NewInt64Coin(denom, 5), "--generate-only") - require.True(t, success) - - // Write the output to disk - unsignedTxFile := WriteToNewTempFile(t, stdout) - defer os.Remove(unsignedTxFile.Name()) - - // Sign with foo's key - success, stdout, _ = f.TxSign(keyFoo, unsignedTxFile.Name(), "--multisig", fooBarBazAddr.String(), "-y") - require.True(t, success) - - // Write the output to disk - fooSignatureFile := WriteToNewTempFile(t, stdout) - defer os.Remove(fooSignatureFile.Name()) - - // Multisign, not enough signatures - success, stdout, _ = f.TxMultisign(unsignedTxFile.Name(), keyFooBarBaz, []string{fooSignatureFile.Name()}) - require.True(t, success) - - // Write the output to disk - signedTxFile := WriteToNewTempFile(t, stdout) - defer os.Remove(signedTxFile.Name()) - - // Validate the multisignature - success, _, _ = f.TxSign(keyFooBarBaz, signedTxFile.Name(), "--validate-signatures") - require.False(t, success) - - // Broadcast the transaction - success, _, _ = f.TxBroadcast(signedTxFile.Name()) - require.False(t, success) - - // Cleanup testing directories - f.Cleanup() -} - -func TestGaiaCLIEncode(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start gaiad server - proc := f.GDStart() - defer proc.Stop(false) - - cdc := app.MakeCodec() - - // Build a testing transaction and write it to disk - barAddr := f.KeyAddress(keyBar) - keyAddr := f.KeyAddress(keyFoo) - - sendTokens := sdk.TokensFromTendermintPower(10) - success, stdout, stderr := f.TxSend(keyAddr.String(), barAddr, sdk.NewCoin(denom, sendTokens), "--generate-only", "--memo", "deadbeef") - require.True(t, success) - require.Empty(t, stderr) - - // Write it to disk - jsonTxFile := WriteToNewTempFile(t, stdout) - defer os.Remove(jsonTxFile.Name()) - - // Run the encode command, and trim the extras from the stdout capture - success, base64Encoded, _ := f.TxEncode(jsonTxFile.Name()) - require.True(t, success) - trimmedBase64 := strings.Trim(base64Encoded, "\"\n") - - // Decode the base64 - decodedBytes, err := base64.StdEncoding.DecodeString(trimmedBase64) - require.Nil(t, err) - - // Check that the transaction decodes as epxceted - var decodedTx auth.StdTx - require.Nil(t, cdc.UnmarshalBinaryLengthPrefixed(decodedBytes, &decodedTx)) - require.Equal(t, "deadbeef", decodedTx.Memo) -} - -func TestGaiaCLIMultisignSortSignatures(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start gaiad server with minimum fees - proc := f.GDStart() - defer proc.Stop(false) - - fooBarBazAddr := f.KeyAddress(keyFooBarBaz) - barAddr := f.KeyAddress(keyBar) - - // Send some tokens from one account to the other - success, _, _ := f.TxSend(keyFoo, fooBarBazAddr, sdk.NewInt64Coin(denom, 10), "-y") - require.True(t, success) - tests.WaitForNextNBlocksTM(1, f.Port) - - // Ensure account balances match expected - fooBarBazAcc := f.QueryAccount(fooBarBazAddr) - require.Equal(t, int64(10), fooBarBazAcc.GetCoins().AmountOf(denom).Int64()) - - // Test generate sendTx with multisig - success, stdout, _ := f.TxSend(fooBarBazAddr.String(), barAddr, sdk.NewInt64Coin(denom, 5), "--generate-only") - require.True(t, success) - - // Write the output to disk - unsignedTxFile := WriteToNewTempFile(t, stdout) - defer os.Remove(unsignedTxFile.Name()) - - // Sign with foo's key - success, stdout, _ = f.TxSign(keyFoo, unsignedTxFile.Name(), "--multisig", fooBarBazAddr.String()) - require.True(t, success) - - // Write the output to disk - fooSignatureFile := WriteToNewTempFile(t, stdout) - defer os.Remove(fooSignatureFile.Name()) - - // Sign with baz's key - success, stdout, _ = f.TxSign(keyBaz, unsignedTxFile.Name(), "--multisig", fooBarBazAddr.String()) - require.True(t, success) - - // Write the output to disk - bazSignatureFile := WriteToNewTempFile(t, stdout) - defer os.Remove(bazSignatureFile.Name()) - - // Multisign, keys in different order - success, stdout, _ = f.TxMultisign(unsignedTxFile.Name(), keyFooBarBaz, []string{ - bazSignatureFile.Name(), fooSignatureFile.Name()}) - require.True(t, success) - - // Write the output to disk - signedTxFile := WriteToNewTempFile(t, stdout) - defer os.Remove(signedTxFile.Name()) - - // Validate the multisignature - success, _, _ = f.TxSign(keyFooBarBaz, signedTxFile.Name(), "--validate-signatures") - require.True(t, success) - - // Broadcast the transaction - success, _, _ = f.TxBroadcast(signedTxFile.Name()) - require.True(t, success) - - // Cleanup testing directories - f.Cleanup() -} - -func TestGaiaCLIMultisign(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start gaiad server with minimum fees - proc := f.GDStart() - defer proc.Stop(false) - - fooBarBazAddr := f.KeyAddress(keyFooBarBaz) - bazAddr := f.KeyAddress(keyBaz) - - // Send some tokens from one account to the other - success, _, _ := f.TxSend(keyFoo, fooBarBazAddr, sdk.NewInt64Coin(denom, 10), "-y") - require.True(t, success) - tests.WaitForNextNBlocksTM(1, f.Port) - - // Ensure account balances match expected - fooBarBazAcc := f.QueryAccount(fooBarBazAddr) - require.Equal(t, int64(10), fooBarBazAcc.GetCoins().AmountOf(denom).Int64()) - - // Test generate sendTx with multisig - success, stdout, stderr := f.TxSend(fooBarBazAddr.String(), bazAddr, sdk.NewInt64Coin(denom, 10), "--generate-only") - require.True(t, success) - require.Empty(t, stderr) - - // Write the output to disk - unsignedTxFile := WriteToNewTempFile(t, stdout) - defer os.Remove(unsignedTxFile.Name()) - - // Sign with foo's key - success, stdout, _ = f.TxSign(keyFoo, unsignedTxFile.Name(), "--multisig", fooBarBazAddr.String(), "-y") - require.True(t, success) - - // Write the output to disk - fooSignatureFile := WriteToNewTempFile(t, stdout) - defer os.Remove(fooSignatureFile.Name()) - - // Sign with bar's key - success, stdout, _ = f.TxSign(keyBar, unsignedTxFile.Name(), "--multisig", fooBarBazAddr.String(), "-y") - require.True(t, success) - - // Write the output to disk - barSignatureFile := WriteToNewTempFile(t, stdout) - defer os.Remove(barSignatureFile.Name()) - - // Multisign - success, stdout, _ = f.TxMultisign(unsignedTxFile.Name(), keyFooBarBaz, []string{ - fooSignatureFile.Name(), barSignatureFile.Name()}) - require.True(t, success) - - // Write the output to disk - signedTxFile := WriteToNewTempFile(t, stdout) - defer os.Remove(signedTxFile.Name()) - - // Validate the multisignature - success, _, _ = f.TxSign(keyFooBarBaz, signedTxFile.Name(), "--validate-signatures", "-y") - require.True(t, success) - - // Broadcast the transaction - success, _, _ = f.TxBroadcast(signedTxFile.Name()) - require.True(t, success) - - // Cleanup testing directories - f.Cleanup() -} - -func TestGaiaCLIConfig(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - node := fmt.Sprintf("%s:%s", f.RPCAddr, f.Port) - - // Set available configuration options - f.CLIConfig("broadcast-mode", "block") - f.CLIConfig("node", node) - f.CLIConfig("output", "text") - f.CLIConfig("trust-node", "true") - f.CLIConfig("chain-id", f.ChainID) - f.CLIConfig("trace", "false") - f.CLIConfig("indent", "true") - - config, err := ioutil.ReadFile(path.Join(f.GaiacliHome, "config", "config.toml")) - require.NoError(t, err) - expectedConfig := fmt.Sprintf(`broadcast-mode = "block" -chain-id = "%s" -indent = true -node = "%s" -output = "text" -trace = false -trust-node = true -`, f.ChainID, node) - require.Equal(t, expectedConfig, string(config)) - - f.Cleanup() -} - -func TestGaiadCollectGentxs(t *testing.T) { - t.Parallel() - var customMaxBytes, customMaxGas int64 = 99999999, 1234567 - f := NewFixtures(t) - - // Initialise temporary directories - gentxDir, err := ioutil.TempDir("", "") - gentxDoc := filepath.Join(gentxDir, "gentx.json") - require.NoError(t, err) - - // Reset testing path - f.UnsafeResetAll() - - // Initialize keys - f.KeysAdd(keyFoo) - - // Configure json output - f.CLIConfig("output", "json") - - // Run init - f.GDInit(keyFoo) - - // Customise genesis.json - - genFile := f.GenesisFile() - genDoc, err := tmtypes.GenesisDocFromFile(genFile) - require.NoError(t, err) - genDoc.ConsensusParams.Block.MaxBytes = customMaxBytes - genDoc.ConsensusParams.Block.MaxGas = customMaxGas - genDoc.SaveAs(genFile) - - // Add account to genesis.json - f.AddGenesisAccount(f.KeyAddress(keyFoo), startCoins) - - // Write gentx file - f.GenTx(keyFoo, fmt.Sprintf("--output-document=%s", gentxDoc)) - - // Collect gentxs from a custom directory - f.CollectGenTxs(fmt.Sprintf("--gentx-dir=%s", gentxDir)) - - genDoc, err = tmtypes.GenesisDocFromFile(genFile) - require.NoError(t, err) - require.Equal(t, genDoc.ConsensusParams.Block.MaxBytes, customMaxBytes) - require.Equal(t, genDoc.ConsensusParams.Block.MaxGas, customMaxGas) - - f.Cleanup(gentxDir) -} - -func TestGaiadAddGenesisAccount(t *testing.T) { - t.Parallel() - f := NewFixtures(t) - - // Reset testing path - f.UnsafeResetAll() - - // Initialize keys - f.KeysDelete(keyFoo) - f.KeysDelete(keyBar) - f.KeysDelete(keyBaz) - f.KeysAdd(keyFoo) - f.KeysAdd(keyBar) - f.KeysAdd(keyBaz) - - // Configure json output - f.CLIConfig("output", "json") - - // Run init - f.GDInit(keyFoo) - - // Add account to genesis.json - bazCoins := sdk.Coins{ - sdk.NewInt64Coin("acoin", 1000000), - sdk.NewInt64Coin("bcoin", 1000000), - } - - f.AddGenesisAccount(f.KeyAddress(keyFoo), startCoins) - f.AddGenesisAccount(f.KeyAddress(keyBar), bazCoins) - genesisState := f.GenesisState() - - cdc := app.MakeCodec() - accounts := genaccounts.GetGenesisStateFromAppState(cdc, genesisState).Accounts - - require.Equal(t, accounts[0].Address, f.KeyAddress(keyFoo)) - require.Equal(t, accounts[1].Address, f.KeyAddress(keyBar)) - require.True(t, accounts[0].Coins.IsEqual(startCoins)) - require.True(t, accounts[1].Coins.IsEqual(bazCoins)) - - // Cleanup testing directories - f.Cleanup() -} - -func TestSlashingGetParams(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start gaiad server - proc := f.GDStart() - defer proc.Stop(false) - - params := f.QuerySlashingParams() - require.Equal(t, time.Duration(120000000000), params.MaxEvidenceAge) - require.Equal(t, int64(100), params.SignedBlocksWindow) - require.Equal(t, sdk.NewDecWithPrec(5, 1), params.MinSignedPerWindow) - - sinfo := f.QuerySigningInfo(f.GDTendermint("show-validator")) - require.Equal(t, int64(0), sinfo.StartHeight) - require.False(t, sinfo.Tombstoned) - - // Cleanup testing directories - f.Cleanup() -} - -func TestValidateGenesis(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start gaiad server - proc := f.GDStart() - defer proc.Stop(false) - - f.ValidateGenesis() - - // Cleanup testing directories - f.Cleanup() -} diff --git a/cmd/gaia/cli_test/doc.go b/cmd/gaia/cli_test/doc.go deleted file mode 100644 index bcf9c5e4d0..0000000000 --- a/cmd/gaia/cli_test/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package clitest - -// package clitest runs integration tests which make use of CLI commands. diff --git a/cmd/gaia/cli_test/test_helpers.go b/cmd/gaia/cli_test/test_helpers.go deleted file mode 100644 index d77dd626c2..0000000000 --- a/cmd/gaia/cli_test/test_helpers.go +++ /dev/null @@ -1,730 +0,0 @@ -package clitest - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "os" - "path/filepath" - "strings" - "testing" - "time" - - "github.com/cosmos/cosmos-sdk/client" - - "github.com/stretchr/testify/require" - - cmn "github.com/tendermint/tendermint/libs/common" - tmtypes "github.com/tendermint/tendermint/types" - - clientkeys "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/cmd/gaia/app" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/crypto/keys" - "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/tests" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/distribution" - "github.com/cosmos/cosmos-sdk/x/gov" - "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/staking" -) - -const ( - denom = "stake" - keyFoo = "foo" - keyBar = "bar" - fooDenom = "footoken" - feeDenom = "feetoken" - fee2Denom = "fee2token" - keyBaz = "baz" - keyVesting = "vesting" - keyFooBarBaz = "foobarbaz" -) - -var ( - startCoins = sdk.Coins{ - sdk.NewCoin(feeDenom, sdk.TokensFromTendermintPower(1000000)), - sdk.NewCoin(fee2Denom, sdk.TokensFromTendermintPower(1000000)), - sdk.NewCoin(fooDenom, sdk.TokensFromTendermintPower(1000)), - sdk.NewCoin(denom, sdk.TokensFromTendermintPower(150)), - } - - vestingCoins = sdk.Coins{ - sdk.NewCoin(feeDenom, sdk.TokensFromTendermintPower(500000)), - } -) - -//___________________________________________________________________________________ -// Fixtures - -// Fixtures is used to setup the testing environment -type Fixtures struct { - BuildDir string - RootDir string - GaiadBinary string - GaiacliBinary string - ChainID string - RPCAddr string - Port string - GaiadHome string - GaiacliHome string - P2PAddr string - T *testing.T -} - -// NewFixtures creates a new instance of Fixtures with many vars set -func NewFixtures(t *testing.T) *Fixtures { - tmpDir, err := ioutil.TempDir("", "gaia_integration_"+t.Name()+"_") - require.NoError(t, err) - - servAddr, port, err := server.FreeTCPAddr() - require.NoError(t, err) - - p2pAddr, _, err := server.FreeTCPAddr() - require.NoError(t, err) - - buildDir := os.Getenv("BUILDDIR") - if buildDir == "" { - buildDir, err = filepath.Abs("../../../build/") - require.NoError(t, err) - } - - return &Fixtures{ - T: t, - BuildDir: buildDir, - RootDir: tmpDir, - GaiadBinary: filepath.Join(buildDir, "gaiad"), - GaiacliBinary: filepath.Join(buildDir, "gaiacli"), - GaiadHome: filepath.Join(tmpDir, ".gaiad"), - GaiacliHome: filepath.Join(tmpDir, ".gaiacli"), - RPCAddr: servAddr, - P2PAddr: p2pAddr, - Port: port, - } -} - -// GenesisFile returns the path of the genesis file -func (f Fixtures) GenesisFile() string { - return filepath.Join(f.GaiadHome, "config", "genesis.json") -} - -// GenesisFile returns the application's genesis state -func (f Fixtures) GenesisState() app.GenesisState { - cdc := codec.New() - genDoc, err := tmtypes.GenesisDocFromFile(f.GenesisFile()) - require.NoError(f.T, err) - - var appState app.GenesisState - require.NoError(f.T, cdc.UnmarshalJSON(genDoc.AppState, &appState)) - return appState -} - -// InitFixtures is called at the beginning of a test and initializes a chain -// with 1 validator. -func InitFixtures(t *testing.T) (f *Fixtures) { - f = NewFixtures(t) - - // reset test state - f.UnsafeResetAll() - - // ensure keystore has foo and bar keys - f.KeysDelete(keyFoo) - f.KeysDelete(keyBar) - f.KeysDelete(keyBar) - f.KeysDelete(keyFooBarBaz) - f.KeysAdd(keyFoo) - f.KeysAdd(keyBar) - f.KeysAdd(keyBaz) - f.KeysAdd(keyVesting) - f.KeysAdd(keyFooBarBaz, "--multisig-threshold=2", fmt.Sprintf( - "--multisig=%s,%s,%s", keyFoo, keyBar, keyBaz)) - - // ensure that CLI output is in JSON format - f.CLIConfig("output", "json") - - // NOTE: GDInit sets the ChainID - f.GDInit(keyFoo) - - f.CLIConfig("chain-id", f.ChainID) - f.CLIConfig("broadcast-mode", "block") - - // start an account with tokens - f.AddGenesisAccount(f.KeyAddress(keyFoo), startCoins) - f.AddGenesisAccount( - f.KeyAddress(keyVesting), startCoins, - fmt.Sprintf("--vesting-amount=%s", vestingCoins), - fmt.Sprintf("--vesting-start-time=%d", time.Now().UTC().UnixNano()), - fmt.Sprintf("--vesting-end-time=%d", time.Now().Add(60*time.Second).UTC().UnixNano()), - ) - - f.GenTx(keyFoo) - f.CollectGenTxs() - - return -} - -// Cleanup is meant to be run at the end of a test to clean up an remaining test state -func (f *Fixtures) Cleanup(dirs ...string) { - clean := append(dirs, f.RootDir) - for _, d := range clean { - require.NoError(f.T, os.RemoveAll(d)) - } -} - -// Flags returns the flags necessary for making most CLI calls -func (f *Fixtures) Flags() string { - return fmt.Sprintf("--home=%s --node=%s", f.GaiacliHome, f.RPCAddr) -} - -//___________________________________________________________________________________ -// gaiad - -// UnsafeResetAll is gaiad unsafe-reset-all -func (f *Fixtures) UnsafeResetAll(flags ...string) { - cmd := fmt.Sprintf("%s --home=%s unsafe-reset-all", f.GaiadBinary, f.GaiadHome) - executeWrite(f.T, addFlags(cmd, flags)) - err := os.RemoveAll(filepath.Join(f.GaiadHome, "config", "gentx")) - require.NoError(f.T, err) -} - -// GDInit is gaiad init -// NOTE: GDInit sets the ChainID for the Fixtures instance -func (f *Fixtures) GDInit(moniker string, flags ...string) { - cmd := fmt.Sprintf("%s init -o --home=%s %s", f.GaiadBinary, f.GaiadHome, moniker) - _, stderr := tests.ExecuteT(f.T, addFlags(cmd, flags), client.DefaultKeyPass) - - var chainID string - var initRes map[string]json.RawMessage - - err := json.Unmarshal([]byte(stderr), &initRes) - require.NoError(f.T, err) - - err = json.Unmarshal(initRes["chain_id"], &chainID) - require.NoError(f.T, err) - - f.ChainID = chainID -} - -// AddGenesisAccount is gaiad add-genesis-account -func (f *Fixtures) AddGenesisAccount(address sdk.AccAddress, coins sdk.Coins, flags ...string) { - cmd := fmt.Sprintf("%s add-genesis-account %s %s --home=%s", f.GaiadBinary, address, coins, f.GaiadHome) - executeWriteCheckErr(f.T, addFlags(cmd, flags)) -} - -// GenTx is gaiad gentx -func (f *Fixtures) GenTx(name string, flags ...string) { - cmd := fmt.Sprintf("%s gentx --name=%s --home=%s --home-client=%s", f.GaiadBinary, name, f.GaiadHome, f.GaiacliHome) - executeWriteCheckErr(f.T, addFlags(cmd, flags), client.DefaultKeyPass) -} - -// CollectGenTxs is gaiad collect-gentxs -func (f *Fixtures) CollectGenTxs(flags ...string) { - cmd := fmt.Sprintf("%s collect-gentxs --home=%s", f.GaiadBinary, f.GaiadHome) - executeWriteCheckErr(f.T, addFlags(cmd, flags), client.DefaultKeyPass) -} - -// GDStart runs gaiad start with the appropriate flags and returns a process -func (f *Fixtures) GDStart(flags ...string) *tests.Process { - cmd := fmt.Sprintf("%s start --home=%s --rpc.laddr=%v --p2p.laddr=%v", f.GaiadBinary, f.GaiadHome, f.RPCAddr, f.P2PAddr) - proc := tests.GoExecuteTWithStdout(f.T, addFlags(cmd, flags)) - tests.WaitForTMStart(f.Port) - tests.WaitForNextNBlocksTM(1, f.Port) - return proc -} - -// GDTendermint returns the results of gaiad tendermint [query] -func (f *Fixtures) GDTendermint(query string) string { - cmd := fmt.Sprintf("%s tendermint %s --home=%s", f.GaiadBinary, query, f.GaiadHome) - success, stdout, stderr := executeWriteRetStdStreams(f.T, cmd) - require.Empty(f.T, stderr) - require.True(f.T, success) - return strings.TrimSpace(stdout) -} - -// ValidateGenesis runs gaiad validate-genesis -func (f *Fixtures) ValidateGenesis() { - cmd := fmt.Sprintf("%s validate-genesis --home=%s", f.GaiadBinary, f.GaiadHome) - executeWriteCheckErr(f.T, cmd) -} - -//___________________________________________________________________________________ -// gaiacli keys - -// KeysDelete is gaiacli keys delete -func (f *Fixtures) KeysDelete(name string, flags ...string) { - cmd := fmt.Sprintf("%s keys delete --home=%s %s", f.GaiacliBinary, f.GaiacliHome, name) - executeWrite(f.T, addFlags(cmd, append(append(flags, "-y"), "-f"))) -} - -// KeysAdd is gaiacli keys add -func (f *Fixtures) KeysAdd(name string, flags ...string) { - cmd := fmt.Sprintf("%s keys add --home=%s %s", f.GaiacliBinary, f.GaiacliHome, name) - executeWriteCheckErr(f.T, addFlags(cmd, flags), client.DefaultKeyPass) -} - -// KeysAddRecover prepares gaiacli keys add --recover -func (f *Fixtures) KeysAddRecover(name, mnemonic string, flags ...string) (exitSuccess bool, stdout, stderr string) { - cmd := fmt.Sprintf("%s keys add --home=%s --recover %s", f.GaiacliBinary, f.GaiacliHome, name) - return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), client.DefaultKeyPass, mnemonic) -} - -// KeysAddRecoverHDPath prepares gaiacli keys add --recover --account --index -func (f *Fixtures) KeysAddRecoverHDPath(name, mnemonic string, account uint32, index uint32, flags ...string) { - cmd := fmt.Sprintf("%s keys add --home=%s --recover %s --account %d --index %d", f.GaiacliBinary, f.GaiacliHome, name, account, index) - executeWriteCheckErr(f.T, addFlags(cmd, flags), client.DefaultKeyPass, mnemonic) -} - -// KeysShow is gaiacli keys show -func (f *Fixtures) KeysShow(name string, flags ...string) keys.KeyOutput { - cmd := fmt.Sprintf("%s keys show --home=%s %s", f.GaiacliBinary, f.GaiacliHome, name) - out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") - var ko keys.KeyOutput - err := clientkeys.UnmarshalJSON([]byte(out), &ko) - require.NoError(f.T, err) - return ko -} - -// KeyAddress returns the SDK account address from the key -func (f *Fixtures) KeyAddress(name string) sdk.AccAddress { - ko := f.KeysShow(name) - accAddr, err := sdk.AccAddressFromBech32(ko.Address) - require.NoError(f.T, err) - return accAddr -} - -//___________________________________________________________________________________ -// gaiacli config - -// CLIConfig is gaiacli config -func (f *Fixtures) CLIConfig(key, value string, flags ...string) { - cmd := fmt.Sprintf("%s config --home=%s %s %s", f.GaiacliBinary, f.GaiacliHome, key, value) - executeWriteCheckErr(f.T, addFlags(cmd, flags)) -} - -//___________________________________________________________________________________ -// gaiacli tx send/sign/broadcast - -// TxSend is gaiacli tx send -func (f *Fixtures) TxSend(from string, to sdk.AccAddress, amount sdk.Coin, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx send %s %s %s %v", f.GaiacliBinary, from, to, amount, f.Flags()) - return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), client.DefaultKeyPass) -} - -func (f *Fixtures) txSendWithConfirm( - from string, to sdk.AccAddress, amount sdk.Coin, confirm string, flags ...string, -) (bool, string, string) { - - cmd := fmt.Sprintf("%s tx send %s %s %s %v", f.GaiacliBinary, from, to, amount, f.Flags()) - return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), confirm, client.DefaultKeyPass) -} - -// TxSign is gaiacli tx sign -func (f *Fixtures) TxSign(signer, fileName string, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx sign %v --from=%s %v", f.GaiacliBinary, f.Flags(), signer, fileName) - return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), client.DefaultKeyPass) -} - -// TxBroadcast is gaiacli tx broadcast -func (f *Fixtures) TxBroadcast(fileName string, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx broadcast %v %v", f.GaiacliBinary, f.Flags(), fileName) - return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), client.DefaultKeyPass) -} - -// TxEncode is gaiacli tx encode -func (f *Fixtures) TxEncode(fileName string, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx encode %v %v", f.GaiacliBinary, f.Flags(), fileName) - return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), client.DefaultKeyPass) -} - -// TxMultisign is gaiacli tx multisign -func (f *Fixtures) TxMultisign(fileName, name string, signaturesFiles []string, - flags ...string) (bool, string, string) { - - cmd := fmt.Sprintf("%s tx multisign %v %s %s %s", f.GaiacliBinary, f.Flags(), - fileName, name, strings.Join(signaturesFiles, " "), - ) - return executeWriteRetStdStreams(f.T, cmd) -} - -//___________________________________________________________________________________ -// gaiacli tx staking - -// TxStakingCreateValidator is gaiacli tx staking create-validator -func (f *Fixtures) TxStakingCreateValidator(from, consPubKey string, amount sdk.Coin, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx staking create-validator %v --from=%s --pubkey=%s", f.GaiacliBinary, f.Flags(), from, consPubKey) - cmd += fmt.Sprintf(" --amount=%v --moniker=%v --commission-rate=%v", amount, from, "0.05") - cmd += fmt.Sprintf(" --commission-max-rate=%v --commission-max-change-rate=%v", "0.20", "0.10") - cmd += fmt.Sprintf(" --min-self-delegation=%v", "1") - return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), client.DefaultKeyPass) -} - -// TxStakingUnbond is gaiacli tx staking unbond -func (f *Fixtures) TxStakingUnbond(from, shares string, validator sdk.ValAddress, flags ...string) bool { - cmd := fmt.Sprintf("%s tx staking unbond %s %v --from=%s %v", f.GaiacliBinary, validator, shares, from, f.Flags()) - return executeWrite(f.T, addFlags(cmd, flags), client.DefaultKeyPass) -} - -//___________________________________________________________________________________ -// gaiacli tx gov - -// TxGovSubmitProposal is gaiacli tx gov submit-proposal -func (f *Fixtures) TxGovSubmitProposal(from, typ, title, description string, deposit sdk.Coin, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx gov submit-proposal %v --from=%s --type=%s", f.GaiacliBinary, f.Flags(), from, typ) - cmd += fmt.Sprintf(" --title=%s --description=%s --deposit=%s", title, description, deposit) - return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), client.DefaultKeyPass) -} - -// TxGovDeposit is gaiacli tx gov deposit -func (f *Fixtures) TxGovDeposit(proposalID int, from string, amount sdk.Coin, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx gov deposit %d %s --from=%s %v", f.GaiacliBinary, proposalID, amount, from, f.Flags()) - return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), client.DefaultKeyPass) -} - -// TxGovVote is gaiacli tx gov vote -func (f *Fixtures) TxGovVote(proposalID int, option gov.VoteOption, from string, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx gov vote %d %s --from=%s %v", f.GaiacliBinary, proposalID, option, from, f.Flags()) - return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), client.DefaultKeyPass) -} - -// TxGovSubmitParamChangeProposal executes a CLI parameter change proposal -// submission. -func (f *Fixtures) TxGovSubmitParamChangeProposal( - from, proposalPath string, deposit sdk.Coin, flags ...string, -) (bool, string, string) { - - cmd := fmt.Sprintf( - "%s tx gov submit-proposal param-change %s --from=%s %v", - f.GaiacliBinary, proposalPath, from, f.Flags(), - ) - - return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), client.DefaultKeyPass) -} - -//___________________________________________________________________________________ -// gaiacli query account - -// QueryAccount is gaiacli query account -func (f *Fixtures) QueryAccount(address sdk.AccAddress, flags ...string) auth.BaseAccount { - cmd := fmt.Sprintf("%s query account %s %v", f.GaiacliBinary, address, f.Flags()) - out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") - var initRes map[string]json.RawMessage - err := json.Unmarshal([]byte(out), &initRes) - require.NoError(f.T, err, "out %v, err %v", out, err) - value := initRes["value"] - var acc auth.BaseAccount - cdc := codec.New() - codec.RegisterCrypto(cdc) - err = cdc.UnmarshalJSON(value, &acc) - require.NoError(f.T, err, "value %v, err %v", string(value), err) - return acc -} - -//___________________________________________________________________________________ -// gaiacli query txs - -// QueryTxs is gaiacli query txs -func (f *Fixtures) QueryTxs(page, limit int, tags ...string) *sdk.SearchTxsResult { - cmd := fmt.Sprintf("%s query txs --page=%d --limit=%d --tags='%s' %v", f.GaiacliBinary, page, limit, queryTags(tags), f.Flags()) - out, _ := tests.ExecuteT(f.T, cmd, "") - var result sdk.SearchTxsResult - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &result) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return &result -} - -// QueryTxsInvalid query txs with wrong parameters and compare expected error -func (f *Fixtures) QueryTxsInvalid(expectedErr error, page, limit int, tags ...string) { - cmd := fmt.Sprintf("%s query txs --page=%d --limit=%d --tags='%s' %v", f.GaiacliBinary, page, limit, queryTags(tags), f.Flags()) - _, err := tests.ExecuteT(f.T, cmd, "") - require.EqualError(f.T, expectedErr, err) -} - -//___________________________________________________________________________________ -// gaiacli query staking - -// QueryStakingValidator is gaiacli query staking validator -func (f *Fixtures) QueryStakingValidator(valAddr sdk.ValAddress, flags ...string) staking.Validator { - cmd := fmt.Sprintf("%s query staking validator %s %v", f.GaiacliBinary, valAddr, f.Flags()) - out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") - var validator staking.Validator - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &validator) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return validator -} - -// QueryStakingUnbondingDelegationsFrom is gaiacli query staking unbonding-delegations-from -func (f *Fixtures) QueryStakingUnbondingDelegationsFrom(valAddr sdk.ValAddress, flags ...string) []staking.UnbondingDelegation { - cmd := fmt.Sprintf("%s query staking unbonding-delegations-from %s %v", f.GaiacliBinary, valAddr, f.Flags()) - out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") - var ubds []staking.UnbondingDelegation - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &ubds) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return ubds -} - -// QueryStakingDelegationsTo is gaiacli query staking delegations-to -func (f *Fixtures) QueryStakingDelegationsTo(valAddr sdk.ValAddress, flags ...string) []staking.Delegation { - cmd := fmt.Sprintf("%s query staking delegations-to %s %v", f.GaiacliBinary, valAddr, f.Flags()) - out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") - var delegations []staking.Delegation - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &delegations) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return delegations -} - -// QueryStakingPool is gaiacli query staking pool -func (f *Fixtures) QueryStakingPool(flags ...string) staking.Pool { - cmd := fmt.Sprintf("%s query staking pool %v", f.GaiacliBinary, f.Flags()) - out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") - var pool staking.Pool - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &pool) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return pool -} - -// QueryStakingParameters is gaiacli query staking parameters -func (f *Fixtures) QueryStakingParameters(flags ...string) staking.Params { - cmd := fmt.Sprintf("%s query staking params %v", f.GaiacliBinary, f.Flags()) - out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") - var params staking.Params - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), ¶ms) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return params -} - -//___________________________________________________________________________________ -// gaiacli query gov - -// QueryGovParamDeposit is gaiacli query gov param deposit -func (f *Fixtures) QueryGovParamDeposit() gov.DepositParams { - cmd := fmt.Sprintf("%s query gov param deposit %s", f.GaiacliBinary, f.Flags()) - out, _ := tests.ExecuteT(f.T, cmd, "") - var depositParam gov.DepositParams - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &depositParam) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return depositParam -} - -// QueryGovParamVoting is gaiacli query gov param voting -func (f *Fixtures) QueryGovParamVoting() gov.VotingParams { - cmd := fmt.Sprintf("%s query gov param voting %s", f.GaiacliBinary, f.Flags()) - out, _ := tests.ExecuteT(f.T, cmd, "") - var votingParam gov.VotingParams - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &votingParam) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return votingParam -} - -// QueryGovParamTallying is gaiacli query gov param tallying -func (f *Fixtures) QueryGovParamTallying() gov.TallyParams { - cmd := fmt.Sprintf("%s query gov param tallying %s", f.GaiacliBinary, f.Flags()) - out, _ := tests.ExecuteT(f.T, cmd, "") - var tallyingParam gov.TallyParams - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &tallyingParam) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return tallyingParam -} - -// QueryGovProposals is gaiacli query gov proposals -func (f *Fixtures) QueryGovProposals(flags ...string) gov.Proposals { - cmd := fmt.Sprintf("%s query gov proposals %v", f.GaiacliBinary, f.Flags()) - stdout, stderr := tests.ExecuteT(f.T, addFlags(cmd, flags), "") - if strings.Contains(stderr, "No matching proposals found") { - return gov.Proposals{} - } - require.Empty(f.T, stderr) - var out gov.Proposals - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(stdout), &out) - require.NoError(f.T, err) - return out -} - -// QueryGovProposal is gaiacli query gov proposal -func (f *Fixtures) QueryGovProposal(proposalID int, flags ...string) gov.Proposal { - cmd := fmt.Sprintf("%s query gov proposal %d %v", f.GaiacliBinary, proposalID, f.Flags()) - out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") - var proposal gov.Proposal - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &proposal) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return proposal -} - -// QueryGovVote is gaiacli query gov vote -func (f *Fixtures) QueryGovVote(proposalID int, voter sdk.AccAddress, flags ...string) gov.Vote { - cmd := fmt.Sprintf("%s query gov vote %d %s %v", f.GaiacliBinary, proposalID, voter, f.Flags()) - out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") - var vote gov.Vote - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &vote) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return vote -} - -// QueryGovVotes is gaiacli query gov votes -func (f *Fixtures) QueryGovVotes(proposalID int, flags ...string) []gov.Vote { - cmd := fmt.Sprintf("%s query gov votes %d %v", f.GaiacliBinary, proposalID, f.Flags()) - out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") - var votes []gov.Vote - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &votes) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return votes -} - -// QueryGovDeposit is gaiacli query gov deposit -func (f *Fixtures) QueryGovDeposit(proposalID int, depositor sdk.AccAddress, flags ...string) gov.Deposit { - cmd := fmt.Sprintf("%s query gov deposit %d %s %v", f.GaiacliBinary, proposalID, depositor, f.Flags()) - out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") - var deposit gov.Deposit - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &deposit) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return deposit -} - -// QueryGovDeposits is gaiacli query gov deposits -func (f *Fixtures) QueryGovDeposits(propsalID int, flags ...string) []gov.Deposit { - cmd := fmt.Sprintf("%s query gov deposits %d %v", f.GaiacliBinary, propsalID, f.Flags()) - out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") - var deposits []gov.Deposit - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &deposits) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return deposits -} - -//___________________________________________________________________________________ -// query slashing - -// QuerySigningInfo returns the signing info for a validator -func (f *Fixtures) QuerySigningInfo(val string) slashing.ValidatorSigningInfo { - cmd := fmt.Sprintf("%s query slashing signing-info %s %s", f.GaiacliBinary, val, f.Flags()) - res, errStr := tests.ExecuteT(f.T, cmd, "") - require.Empty(f.T, errStr) - cdc := app.MakeCodec() - var sinfo slashing.ValidatorSigningInfo - err := cdc.UnmarshalJSON([]byte(res), &sinfo) - require.NoError(f.T, err) - return sinfo -} - -// QuerySlashingParams is gaiacli query slashing params -func (f *Fixtures) QuerySlashingParams() slashing.Params { - cmd := fmt.Sprintf("%s query slashing params %s", f.GaiacliBinary, f.Flags()) - res, errStr := tests.ExecuteT(f.T, cmd, "") - require.Empty(f.T, errStr) - cdc := app.MakeCodec() - var params slashing.Params - err := cdc.UnmarshalJSON([]byte(res), ¶ms) - require.NoError(f.T, err) - return params -} - -//___________________________________________________________________________________ -// query distribution - -// QuerySigningInfo returns the signing info for a validator -func (f *Fixtures) QueryRewards(delAddr sdk.AccAddress, flags ...string) distribution.QueryDelegatorTotalRewardsResponse { - cmd := fmt.Sprintf("%s query distr rewards %s %s", f.GaiacliBinary, delAddr, f.Flags()) - res, errStr := tests.ExecuteT(f.T, cmd, "") - require.Empty(f.T, errStr) - cdc := app.MakeCodec() - var rewards distribution.QueryDelegatorTotalRewardsResponse - err := cdc.UnmarshalJSON([]byte(res), &rewards) - require.NoError(f.T, err) - return rewards -} - -//___________________________________________________________________________________ -// executors - -func executeWriteCheckErr(t *testing.T, cmdStr string, writes ...string) { - require.True(t, executeWrite(t, cmdStr, writes...)) -} - -func executeWrite(t *testing.T, cmdStr string, writes ...string) (exitSuccess bool) { - exitSuccess, _, _ = executeWriteRetStdStreams(t, cmdStr, writes...) - return -} - -func executeWriteRetStdStreams(t *testing.T, cmdStr string, writes ...string) (bool, string, string) { - proc := tests.GoExecuteT(t, cmdStr) - - // Enables use of interactive commands - for _, write := range writes { - _, err := proc.StdinPipe.Write([]byte(write + "\n")) - require.NoError(t, err) - } - - // Read both stdout and stderr from the process - stdout, stderr, err := proc.ReadAll() - if err != nil { - fmt.Println("Err on proc.ReadAll()", err, cmdStr) - } - - // Log output. - if len(stdout) > 0 { - t.Log("Stdout:", cmn.Green(string(stdout))) - } - if len(stderr) > 0 { - t.Log("Stderr:", cmn.Red(string(stderr))) - } - - // Wait for process to exit - proc.Wait() - - // Return succes, stdout, stderr - return proc.ExitState.Success(), string(stdout), string(stderr) -} - -//___________________________________________________________________________________ -// utils - -func addFlags(cmd string, flags []string) string { - for _, f := range flags { - cmd += " " + f - } - return strings.TrimSpace(cmd) -} - -func queryTags(tags []string) (out string) { - for _, tag := range tags { - out += tag + "&" - } - return strings.TrimSuffix(out, "&") -} - -// Write the given string to a new temporary file -func WriteToNewTempFile(t *testing.T, s string) *os.File { - fp, err := ioutil.TempFile(os.TempDir(), "cosmos_cli_test_") - require.Nil(t, err) - _, err = fp.WriteString(s) - require.Nil(t, err) - return fp -} - -func marshalStdTx(t *testing.T, stdTx auth.StdTx) []byte { - cdc := app.MakeCodec() - bz, err := cdc.MarshalBinaryBare(stdTx) - require.NoError(t, err) - return bz -} - -func unmarshalStdTx(t *testing.T, s string) (stdTx auth.StdTx) { - cdc := app.MakeCodec() - require.Nil(t, cdc.UnmarshalJSON([]byte(s), &stdTx)) - return -} diff --git a/cmd/gaia/cmd/gaiacli/main.go b/cmd/gaia/cmd/gaiacli/main.go deleted file mode 100644 index b9a5543f4f..0000000000 --- a/cmd/gaia/cmd/gaiacli/main.go +++ /dev/null @@ -1,211 +0,0 @@ -package main - -import ( - "fmt" - "net/http" - "os" - "path" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/client/lcd" - "github.com/cosmos/cosmos-sdk/client/rpc" - "github.com/cosmos/cosmos-sdk/client/tx" - "github.com/cosmos/cosmos-sdk/cmd/gaia/app" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - at "github.com/cosmos/cosmos-sdk/x/auth" - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - auth "github.com/cosmos/cosmos-sdk/x/auth/client/rest" - bankcmd "github.com/cosmos/cosmos-sdk/x/bank/client/cli" - bank "github.com/cosmos/cosmos-sdk/x/bank/client/rest" - crisisclient "github.com/cosmos/cosmos-sdk/x/crisis/client" - distcmd "github.com/cosmos/cosmos-sdk/x/distribution" - distClient "github.com/cosmos/cosmos-sdk/x/distribution/client" - dist "github.com/cosmos/cosmos-sdk/x/distribution/client/rest" - gv "github.com/cosmos/cosmos-sdk/x/gov" - govClient "github.com/cosmos/cosmos-sdk/x/gov/client" - gov "github.com/cosmos/cosmos-sdk/x/gov/client/rest" - "github.com/cosmos/cosmos-sdk/x/mint" - mintclient "github.com/cosmos/cosmos-sdk/x/mint/client" - mintrest "github.com/cosmos/cosmos-sdk/x/mint/client/rest" - paramcli "github.com/cosmos/cosmos-sdk/x/params/client/cli" - paramsrest "github.com/cosmos/cosmos-sdk/x/params/client/rest" - sl "github.com/cosmos/cosmos-sdk/x/slashing" - slashingclient "github.com/cosmos/cosmos-sdk/x/slashing/client" - slashing "github.com/cosmos/cosmos-sdk/x/slashing/client/rest" - st "github.com/cosmos/cosmos-sdk/x/staking" - stakingclient "github.com/cosmos/cosmos-sdk/x/staking/client" - staking "github.com/cosmos/cosmos-sdk/x/staking/client/rest" - - "github.com/rakyll/statik/fs" - "github.com/spf13/cobra" - "github.com/spf13/viper" - - amino "github.com/tendermint/go-amino" - "github.com/tendermint/tendermint/libs/cli" - - _ "github.com/cosmos/cosmos-sdk/client/lcd/statik" -) - -func main() { - // Configure cobra to sort commands - cobra.EnableCommandSorting = false - - // Instantiate the codec for the command line application - cdc := app.MakeCodec() - - // Read in the configuration file for the sdk - config := sdk.GetConfig() - config.SetBech32PrefixForAccount(sdk.Bech32PrefixAccAddr, sdk.Bech32PrefixAccPub) - config.SetBech32PrefixForValidator(sdk.Bech32PrefixValAddr, sdk.Bech32PrefixValPub) - config.SetBech32PrefixForConsensusNode(sdk.Bech32PrefixConsAddr, sdk.Bech32PrefixConsPub) - config.Seal() - - // TODO: setup keybase, viper object, etc. to be passed into - // the below functions and eliminate global vars, like we do - // with the cdc - - // Module clients hold cli commnads (tx,query) and lcd routes - // TODO: Make the lcd command take a list of ModuleClient - mc := []sdk.ModuleClient{ - govClient.NewModuleClient(gv.StoreKey, cdc, paramcli.GetCmdSubmitProposal(cdc)), - distClient.NewModuleClient(distcmd.StoreKey, cdc), - stakingclient.NewModuleClient(st.StoreKey, cdc), - mintclient.NewModuleClient(mint.StoreKey, cdc), - slashingclient.NewModuleClient(sl.StoreKey, cdc), - crisisclient.NewModuleClient(sl.StoreKey, cdc), - } - - rootCmd := &cobra.Command{ - Use: "gaiacli", - Short: "Command line interface for interacting with gaiad", - } - - // Add --chain-id to persistent flags and mark it required - rootCmd.PersistentFlags().String(client.FlagChainID, "", "Chain ID of tendermint node") - rootCmd.PersistentPreRunE = func(_ *cobra.Command, _ []string) error { - return initConfig(rootCmd) - } - - // Construct Root Command - rootCmd.AddCommand( - rpc.StatusCommand(), - client.ConfigCmd(app.DefaultCLIHome), - queryCmd(cdc, mc), - txCmd(cdc, mc), - client.LineBreak, - lcd.ServeCommand(cdc, registerRoutes), - client.LineBreak, - keys.Commands(), - client.LineBreak, - version.VersionCmd, - client.NewCompletionCmd(rootCmd, true), - ) - - // Add flags and prefix all env exposed with GA - executor := cli.PrepareMainCmd(rootCmd, "GA", app.DefaultCLIHome) - - err := executor.Execute() - if err != nil { - fmt.Printf("Failed executing CLI command: %s, exiting...\n", err) - os.Exit(1) - } -} - -func queryCmd(cdc *amino.Codec, mc []sdk.ModuleClient) *cobra.Command { - queryCmd := &cobra.Command{ - Use: "query", - Aliases: []string{"q"}, - Short: "Querying subcommands", - } - - queryCmd.AddCommand( - rpc.ValidatorCommand(cdc), - rpc.BlockCommand(), - tx.SearchTxCmd(cdc), - tx.QueryTxCmd(cdc), - client.LineBreak, - authcmd.GetAccountCmd(at.StoreKey, cdc), - ) - - for _, m := range mc { - mQueryCmd := m.GetQueryCmd() - if mQueryCmd != nil { - queryCmd.AddCommand(mQueryCmd) - } - } - - return queryCmd -} - -func txCmd(cdc *amino.Codec, mc []sdk.ModuleClient) *cobra.Command { - txCmd := &cobra.Command{ - Use: "tx", - Short: "Transactions subcommands", - } - - txCmd.AddCommand( - bankcmd.SendTxCmd(cdc), - client.LineBreak, - authcmd.GetSignCommand(cdc), - authcmd.GetMultiSignCommand(cdc), - tx.GetBroadcastCommand(cdc), - tx.GetEncodeCommand(cdc), - client.LineBreak, - ) - - for _, m := range mc { - txCmd.AddCommand(m.GetTxCmd()) - } - - return txCmd -} - -// registerRoutes registers the routes from the different modules for the LCD. -// NOTE: details on the routes added for each module are in the module documentation -// NOTE: If making updates here you also need to update the test helper in client/lcd/test_helper.go -func registerRoutes(rs *lcd.RestServer) { - registerSwaggerUI(rs) - rpc.RegisterRoutes(rs.CliCtx, rs.Mux) - tx.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc) - auth.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, at.StoreKey) - bank.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, rs.KeyBase) - dist.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, distcmd.StoreKey) - staking.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, rs.KeyBase) - slashing.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, rs.KeyBase) - gov.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, paramsrest.ProposalRESTHandler(rs.CliCtx, rs.Cdc)) - mintrest.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc) -} - -func registerSwaggerUI(rs *lcd.RestServer) { - statikFS, err := fs.New() - if err != nil { - panic(err) - } - staticServer := http.FileServer(statikFS) - rs.Mux.PathPrefix("/swagger-ui/").Handler(http.StripPrefix("/swagger-ui/", staticServer)) -} - -func initConfig(cmd *cobra.Command) error { - home, err := cmd.PersistentFlags().GetString(cli.HomeFlag) - if err != nil { - return err - } - - cfgFile := path.Join(home, "config", "config.toml") - if _, err := os.Stat(cfgFile); err == nil { - viper.SetConfigFile(cfgFile) - - if err := viper.ReadInConfig(); err != nil { - return err - } - } - if err := viper.BindPFlag(client.FlagChainID, cmd.PersistentFlags().Lookup(client.FlagChainID)); err != nil { - return err - } - if err := viper.BindPFlag(cli.EncodingFlag, cmd.PersistentFlags().Lookup(cli.EncodingFlag)); err != nil { - return err - } - return viper.BindPFlag(cli.OutputFlag, cmd.PersistentFlags().Lookup(cli.OutputFlag)) -} diff --git a/cmd/gaia/cmd/gaiad/main.go b/cmd/gaia/cmd/gaiad/main.go deleted file mode 100644 index 78d59c7c6e..0000000000 --- a/cmd/gaia/cmd/gaiad/main.go +++ /dev/null @@ -1,93 +0,0 @@ -package main - -import ( - "encoding/json" - "io" - - "github.com/spf13/cobra" - "github.com/spf13/viper" - - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/cli" - dbm "github.com/tendermint/tendermint/libs/db" - "github.com/tendermint/tendermint/libs/log" - tmtypes "github.com/tendermint/tendermint/types" - - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/cmd/gaia/app" - "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/store" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/genaccounts" - genaccscli "github.com/cosmos/cosmos-sdk/x/auth/genaccounts/client/cli" - genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" -) - -// gaiad custom flags -const flagInvCheckPeriod = "inv-check-period" - -var invCheckPeriod uint - -func main() { - cdc := app.MakeCodec() - - config := sdk.GetConfig() - config.SetBech32PrefixForAccount(sdk.Bech32PrefixAccAddr, sdk.Bech32PrefixAccPub) - config.SetBech32PrefixForValidator(sdk.Bech32PrefixValAddr, sdk.Bech32PrefixValPub) - config.SetBech32PrefixForConsensusNode(sdk.Bech32PrefixConsAddr, sdk.Bech32PrefixConsPub) - config.Seal() - - ctx := server.NewDefaultContext() - cobra.EnableCommandSorting = false - rootCmd := &cobra.Command{ - Use: "gaiad", - Short: "Gaia Daemon (server)", - PersistentPreRunE: server.PersistentPreRunEFn(ctx), - } - - rootCmd.AddCommand(genutilcli.InitCmd(ctx, cdc, app.ModuleBasics, app.DefaultNodeHome)) - rootCmd.AddCommand(genutilcli.CollectGenTxsCmd(ctx, cdc, genaccounts.AppModuleBasic{}, app.DefaultNodeHome)) - rootCmd.AddCommand(genutilcli.GenTxCmd(ctx, cdc, app.ModuleBasics, genaccounts.AppModuleBasic{}, app.DefaultNodeHome, app.DefaultCLIHome)) - rootCmd.AddCommand(genutilcli.ValidateGenesisCmd(ctx, cdc, app.ModuleBasics)) - rootCmd.AddCommand(genaccscli.AddGenesisAccountCmd(ctx, cdc, app.DefaultNodeHome, app.DefaultCLIHome)) - rootCmd.AddCommand(client.NewCompletionCmd(rootCmd, true)) - rootCmd.AddCommand(testnetCmd(ctx, cdc, app.ModuleBasics, genaccounts.AppModuleBasic{})) - rootCmd.AddCommand(replayCmd()) - - server.AddCommands(ctx, cdc, rootCmd, newApp, exportAppStateAndTMValidators) - - // prepare and add flags - executor := cli.PrepareBaseCmd(rootCmd, "GA", app.DefaultNodeHome) - rootCmd.PersistentFlags().UintVar(&invCheckPeriod, flagInvCheckPeriod, - 0, "Assert registered invariants every N blocks") - err := executor.Execute() - if err != nil { - panic(err) - } -} - -func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer) abci.Application { - return app.NewGaiaApp( - logger, db, traceStore, true, invCheckPeriod, - baseapp.SetPruning(store.NewPruningOptionsFromString(viper.GetString("pruning"))), - baseapp.SetMinGasPrices(viper.GetString(server.FlagMinGasPrices)), - baseapp.SetHaltHeight(uint64(viper.GetInt(server.FlagHaltHeight))), - ) -} - -func exportAppStateAndTMValidators( - logger log.Logger, db dbm.DB, traceStore io.Writer, height int64, forZeroHeight bool, jailWhiteList []string, -) (json.RawMessage, []tmtypes.GenesisValidator, error) { - - if height != -1 { - gApp := app.NewGaiaApp(logger, db, traceStore, false, uint(1)) - err := gApp.LoadHeight(height) - if err != nil { - return nil, nil, err - } - return gApp.ExportAppStateAndValidators(forZeroHeight, jailWhiteList) - } - gApp := app.NewGaiaApp(logger, db, traceStore, true, uint(1)) - return gApp.ExportAppStateAndValidators(forZeroHeight, jailWhiteList) -} diff --git a/cmd/gaia/cmd/gaiad/replay.go b/cmd/gaia/cmd/gaiad/replay.go deleted file mode 100644 index 4511ff21bc..0000000000 --- a/cmd/gaia/cmd/gaiad/replay.go +++ /dev/null @@ -1,190 +0,0 @@ -package main - -import ( - "fmt" - "io" - "os" - "path/filepath" - "time" - - cpm "github.com/otiai10/copy" - "github.com/spf13/cobra" - - abci "github.com/tendermint/tendermint/abci/types" - bcm "github.com/tendermint/tendermint/blockchain" - cmn "github.com/tendermint/tendermint/libs/common" - "github.com/tendermint/tendermint/proxy" - tmsm "github.com/tendermint/tendermint/state" - tm "github.com/tendermint/tendermint/types" - - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/cmd/gaia/app" - "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/store" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func replayCmd() *cobra.Command { - return &cobra.Command{ - Use: "replay ", - Short: "Replay gaia transactions", - RunE: func(_ *cobra.Command, args []string) error { - return replayTxs(args[0]) - }, - Args: cobra.ExactArgs(1), - } -} - -func replayTxs(rootDir string) error { - - if false { - // Copy the rootDir to a new directory, to preserve the old one. - fmt.Fprintln(os.Stderr, "Copying rootdir over") - oldRootDir := rootDir - rootDir = oldRootDir + "_replay" - if cmn.FileExists(rootDir) { - cmn.Exit(fmt.Sprintf("temporary copy dir %v already exists", rootDir)) - } - if err := cpm.Copy(oldRootDir, rootDir); err != nil { - return err - } - } - - configDir := filepath.Join(rootDir, "config") - dataDir := filepath.Join(rootDir, "data") - ctx := server.NewDefaultContext() - - // App DB - // appDB := dbm.NewMemDB() - fmt.Fprintln(os.Stderr, "Opening app database") - appDB, err := sdk.NewLevelDB("application", dataDir) - if err != nil { - return err - } - - // TM DB - // tmDB := dbm.NewMemDB() - fmt.Fprintln(os.Stderr, "Opening tendermint state database") - tmDB, err := sdk.NewLevelDB("state", dataDir) - if err != nil { - return err - } - - // Blockchain DB - fmt.Fprintln(os.Stderr, "Opening blockstore database") - bcDB, err := sdk.NewLevelDB("blockstore", dataDir) - if err != nil { - return err - } - - // TraceStore - var traceStoreWriter io.Writer - var traceStoreDir = filepath.Join(dataDir, "trace.log") - traceStoreWriter, err = os.OpenFile( - traceStoreDir, - os.O_WRONLY|os.O_APPEND|os.O_CREATE, - 0666, - ) - if err != nil { - return err - } - - // Application - fmt.Fprintln(os.Stderr, "Creating application") - myapp := app.NewGaiaApp( - ctx.Logger, appDB, traceStoreWriter, true, uint(1), - baseapp.SetPruning(store.PruneEverything), // nothing - ) - - // Genesis - var genDocPath = filepath.Join(configDir, "genesis.json") - genDoc, err := tm.GenesisDocFromFile(genDocPath) - if err != nil { - return err - } - genState, err := tmsm.MakeGenesisState(genDoc) - if err != nil { - return err - } - // tmsm.SaveState(tmDB, genState) - - cc := proxy.NewLocalClientCreator(myapp) - proxyApp := proxy.NewAppConns(cc) - err = proxyApp.Start() - if err != nil { - return err - } - defer func() { - _ = proxyApp.Stop() - }() - - state := tmsm.LoadState(tmDB) - if state.LastBlockHeight == 0 { - // Send InitChain msg - fmt.Fprintln(os.Stderr, "Sending InitChain msg") - validators := tm.TM2PB.ValidatorUpdates(genState.Validators) - csParams := tm.TM2PB.ConsensusParams(genDoc.ConsensusParams) - req := abci.RequestInitChain{ - Time: genDoc.GenesisTime, - ChainId: genDoc.ChainID, - ConsensusParams: csParams, - Validators: validators, - AppStateBytes: genDoc.AppState, - } - res, err := proxyApp.Consensus().InitChainSync(req) - if err != nil { - return err - } - newValidatorz, err := tm.PB2TM.ValidatorUpdates(res.Validators) - if err != nil { - return err - } - newValidators := tm.NewValidatorSet(newValidatorz) - - // Take the genesis state. - state = genState - state.Validators = newValidators - state.NextValidators = newValidators - } - - // Create executor - fmt.Fprintln(os.Stderr, "Creating block executor") - blockExec := tmsm.NewBlockExecutor(tmDB, ctx.Logger, proxyApp.Consensus(), - tmsm.MockMempool{}, tmsm.MockEvidencePool{}) - - // Create block store - fmt.Fprintln(os.Stderr, "Creating block store") - blockStore := bcm.NewBlockStore(bcDB) - - tz := []time.Duration{0, 0, 0} - for i := int(state.LastBlockHeight) + 1; ; i++ { - fmt.Fprintln(os.Stderr, "Running block ", i) - t1 := time.Now() - - // Apply block - fmt.Printf("loading and applying block %d\n", i) - blockmeta := blockStore.LoadBlockMeta(int64(i)) - if blockmeta == nil { - fmt.Printf("Couldn't find block meta %d... done?\n", i) - return nil - } - block := blockStore.LoadBlock(int64(i)) - if block == nil { - return fmt.Errorf("couldn't find block %d", i) - } - - t2 := time.Now() - - state, err = blockExec.ApplyBlock(state, blockmeta.BlockID, block) - if err != nil { - return err - } - - t3 := time.Now() - tz[0] += t2.Sub(t1) - tz[1] += t3.Sub(t2) - - fmt.Fprintf(os.Stderr, "new app hash: %X\n", state.AppHash) - fmt.Fprintln(os.Stderr, tz) - } -} diff --git a/cmd/gaia/cmd/gaiad/testnet.go b/cmd/gaia/cmd/gaiad/testnet.go deleted file mode 100644 index eb172897e1..0000000000 --- a/cmd/gaia/cmd/gaiad/testnet.go +++ /dev/null @@ -1,375 +0,0 @@ -package main - -// DONTCOVER - -import ( - "encoding/json" - "fmt" - "net" - "os" - "path/filepath" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/server" - srvconfig "github.com/cosmos/cosmos-sdk/server/config" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - authtx "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" - "github.com/cosmos/cosmos-sdk/x/auth/genaccounts" - "github.com/cosmos/cosmos-sdk/x/genutil" - "github.com/cosmos/cosmos-sdk/x/staking" - "github.com/spf13/cobra" - "github.com/spf13/viper" - tmconfig "github.com/tendermint/tendermint/config" - "github.com/tendermint/tendermint/crypto" - cmn "github.com/tendermint/tendermint/libs/common" - "github.com/tendermint/tendermint/types" - tmtime "github.com/tendermint/tendermint/types/time" -) - -var ( - flagNodeDirPrefix = "node-dir-prefix" - flagNumValidators = "v" - flagOutputDir = "output-dir" - flagNodeDaemonHome = "node-daemon-home" - flagNodeCLIHome = "node-cli-home" - flagStartingIPAddress = "starting-ip-address" -) - -// get cmd to initialize all files for tendermint testnet and application -func testnetCmd(ctx *server.Context, cdc *codec.Codec, - mbm sdk.ModuleBasicManager, genAccIterator genutil.GenesisAccountsIterator) *cobra.Command { - - cmd := &cobra.Command{ - Use: "testnet", - Short: "Initialize files for a Gaiad testnet", - Long: `testnet will create "v" number of directories and populate each with -necessary files (private validator, genesis, config, etc.). - -Note, strict routability for addresses is turned off in the config file. - -Example: - gaiad testnet --v 4 --output-dir ./output --starting-ip-address 192.168.10.2 - `, - RunE: func(_ *cobra.Command, _ []string) error { - config := ctx.Config - - outputDir := viper.GetString(flagOutputDir) - chainID := viper.GetString(client.FlagChainID) - minGasPrices := viper.GetString(server.FlagMinGasPrices) - nodeDirPrefix := viper.GetString(flagNodeDirPrefix) - nodeDaemonHome := viper.GetString(flagNodeDaemonHome) - nodeCLIHome := viper.GetString(flagNodeCLIHome) - startingIPAddress := viper.GetString(flagStartingIPAddress) - numValidators := viper.GetInt(flagNumValidators) - - return InitTestnet(config, cdc, mbm, genAccIterator, outputDir, chainID, minGasPrices, - nodeDirPrefix, nodeDaemonHome, nodeCLIHome, startingIPAddress, numValidators) - }, - } - - cmd.Flags().Int(flagNumValidators, 4, - "Number of validators to initialize the testnet with") - cmd.Flags().StringP(flagOutputDir, "o", "./mytestnet", - "Directory to store initialization data for the testnet") - cmd.Flags().String(flagNodeDirPrefix, "node", - "Prefix the directory name for each node with (node results in node0, node1, ...)") - cmd.Flags().String(flagNodeDaemonHome, "gaiad", - "Home directory of the node's daemon configuration") - cmd.Flags().String(flagNodeCLIHome, "gaiacli", - "Home directory of the node's cli configuration") - cmd.Flags().String(flagStartingIPAddress, "192.168.0.1", - "Starting IP address (192.168.0.1 results in persistent peers list ID0@192.168.0.1:46656, ID1@192.168.0.2:46656, ...)") - cmd.Flags().String( - client.FlagChainID, "", "genesis file chain-id, if left blank will be randomly created") - cmd.Flags().String( - server.FlagMinGasPrices, fmt.Sprintf("0.000006%s", sdk.DefaultBondDenom), - "Minimum gas prices to accept for transactions; All fees in a tx must meet this minimum (e.g. 0.01photino,0.001stake)") - return cmd -} - -const nodeDirPerm = 0755 - -// Initialize the testnet -func InitTestnet(config *tmconfig.Config, cdc *codec.Codec, mbm sdk.ModuleBasicManager, - genAccIterator genutil.GenesisAccountsIterator, - outputDir, chainID, minGasPrices, nodeDirPrefix, nodeDaemonHome, - nodeCLIHome, startingIPAddress string, numValidators int) error { - - if chainID == "" { - chainID = "chain-" + cmn.RandStr(6) - } - - monikers := make([]string, numValidators) - nodeIDs := make([]string, numValidators) - valPubKeys := make([]crypto.PubKey, numValidators) - - gaiaConfig := srvconfig.DefaultConfig() - gaiaConfig.MinGasPrices = minGasPrices - - var ( - accs []genaccounts.GenesisAccount - genFiles []string - ) - - // generate private keys, node IDs, and initial transactions - for i := 0; i < numValidators; i++ { - nodeDirName := fmt.Sprintf("%s%d", nodeDirPrefix, i) - nodeDir := filepath.Join(outputDir, nodeDirName, nodeDaemonHome) - clientDir := filepath.Join(outputDir, nodeDirName, nodeCLIHome) - gentxsDir := filepath.Join(outputDir, "gentxs") - - config.SetRoot(nodeDir) - - err := os.MkdirAll(filepath.Join(nodeDir, "config"), nodeDirPerm) - if err != nil { - _ = os.RemoveAll(outputDir) - return err - } - - err = os.MkdirAll(clientDir, nodeDirPerm) - if err != nil { - _ = os.RemoveAll(outputDir) - return err - } - - monikers = append(monikers, nodeDirName) - config.Moniker = nodeDirName - - ip, err := getIP(i, startingIPAddress) - if err != nil { - _ = os.RemoveAll(outputDir) - return err - } - - nodeIDs[i], valPubKeys[i], err = genutil.InitializeNodeValidatorFiles(config) - if err != nil { - _ = os.RemoveAll(outputDir) - return err - } - - memo := fmt.Sprintf("%s@%s:26656", nodeIDs[i], ip) - genFiles = append(genFiles, config.GenesisFile()) - - buf := client.BufferStdin() - prompt := fmt.Sprintf( - "Password for account '%s' (default %s):", nodeDirName, client.DefaultKeyPass, - ) - - keyPass, err := client.GetPassword(prompt, buf) - if err != nil && keyPass != "" { - // An error was returned that either failed to read the password from - // STDIN or the given password is not empty but failed to meet minimum - // length requirements. - return err - } - - if keyPass == "" { - keyPass = client.DefaultKeyPass - } - - addr, secret, err := server.GenerateSaveCoinKey(clientDir, nodeDirName, keyPass, true) - if err != nil { - _ = os.RemoveAll(outputDir) - return err - } - - info := map[string]string{"secret": secret} - - cliPrint, err := json.Marshal(info) - if err != nil { - return err - } - - // save private key seed words - err = writeFile(fmt.Sprintf("%v.json", "key_seed"), clientDir, cliPrint) - if err != nil { - return err - } - - accTokens := sdk.TokensFromTendermintPower(1000) - accStakingTokens := sdk.TokensFromTendermintPower(500) - accs = append(accs, genaccounts.GenesisAccount{ - Address: addr, - Coins: sdk.Coins{ - sdk.NewCoin(fmt.Sprintf("%stoken", nodeDirName), accTokens), - sdk.NewCoin(sdk.DefaultBondDenom, accStakingTokens), - }, - }) - - valTokens := sdk.TokensFromTendermintPower(100) - msg := staking.NewMsgCreateValidator( - sdk.ValAddress(addr), - valPubKeys[i], - sdk.NewCoin(sdk.DefaultBondDenom, valTokens), - staking.NewDescription(nodeDirName, "", "", ""), - staking.NewCommissionMsg(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - sdk.OneInt(), - ) - kb, err := keys.NewKeyBaseFromDir(clientDir) - if err != nil { - return err - } - tx := auth.NewStdTx([]sdk.Msg{msg}, auth.StdFee{}, []auth.StdSignature{}, memo) - txBldr := authtx.NewTxBuilderFromCLI().WithChainID(chainID).WithMemo(memo).WithKeybase(kb) - - signedTx, err := txBldr.SignStdTx(nodeDirName, client.DefaultKeyPass, tx, false) - if err != nil { - _ = os.RemoveAll(outputDir) - return err - } - - txBytes, err := cdc.MarshalJSON(signedTx) - if err != nil { - _ = os.RemoveAll(outputDir) - return err - } - - // gather gentxs folder - err = writeFile(fmt.Sprintf("%v.json", nodeDirName), gentxsDir, txBytes) - if err != nil { - _ = os.RemoveAll(outputDir) - return err - } - - // TODO: Rename config file to server.toml as it's not particular to Gaia - // (REF: https://github.com/cosmos/cosmos-sdk/issues/4125). - gaiaConfigFilePath := filepath.Join(nodeDir, "config/gaiad.toml") - srvconfig.WriteConfigFile(gaiaConfigFilePath, gaiaConfig) - } - - if err := initGenFiles(cdc, mbm, chainID, accs, genFiles, numValidators); err != nil { - return err - } - - err := collectGenFiles( - cdc, config, chainID, monikers, nodeIDs, valPubKeys, numValidators, - outputDir, nodeDirPrefix, nodeDaemonHome, genAccIterator, - ) - if err != nil { - return err - } - - fmt.Printf("Successfully initialized %d node directories\n", numValidators) - return nil -} - -func initGenFiles(cdc *codec.Codec, mbm sdk.ModuleBasicManager, chainID string, - accs []genaccounts.GenesisAccount, genFiles []string, numValidators int) error { - - appGenState := mbm.DefaultGenesis() - - // set the accounts in the genesis state - appGenState = genaccounts.SetGenesisStateInAppState(cdc, appGenState, - genaccounts.NewGenesisState(accs)) - - appGenStateJSON, err := codec.MarshalJSONIndent(cdc, appGenState) - if err != nil { - return err - } - - genDoc := types.GenesisDoc{ - ChainID: chainID, - AppState: appGenStateJSON, - Validators: nil, - } - - // generate empty genesis files for each validator and save - for i := 0; i < numValidators; i++ { - if err := genDoc.SaveAs(genFiles[i]); err != nil { - return err - } - } - return nil -} - -func collectGenFiles( - cdc *codec.Codec, config *tmconfig.Config, chainID string, - monikers, nodeIDs []string, valPubKeys []crypto.PubKey, - numValidators int, outputDir, nodeDirPrefix, nodeDaemonHome string, - genAccIterator genutil.GenesisAccountsIterator) error { - - var appState json.RawMessage - genTime := tmtime.Now() - - for i := 0; i < numValidators; i++ { - nodeDirName := fmt.Sprintf("%s%d", nodeDirPrefix, i) - nodeDir := filepath.Join(outputDir, nodeDirName, nodeDaemonHome) - gentxsDir := filepath.Join(outputDir, "gentxs") - moniker := monikers[i] - config.Moniker = nodeDirName - - config.SetRoot(nodeDir) - - nodeID, valPubKey := nodeIDs[i], valPubKeys[i] - initCfg := genutil.NewInitConfig(chainID, gentxsDir, moniker, nodeID, valPubKey) - - genDoc, err := types.GenesisDocFromFile(config.GenesisFile()) - if err != nil { - return err - } - - nodeAppState, err := genutil.GenAppStateFromConfig(cdc, config, initCfg, *genDoc, genAccIterator) - if err != nil { - return err - } - - if appState == nil { - // set the canonical application state (they should not differ) - appState = nodeAppState - } - - genFile := config.GenesisFile() - - // overwrite each validator's genesis file to have a canonical genesis time - err = genutil.ExportGenesisFileWithTime(genFile, chainID, nil, appState, genTime) - if err != nil { - return err - } - } - - return nil -} - -func getIP(i int, startingIPAddr string) (ip string, err error) { - if len(startingIPAddr) == 0 { - ip, err = server.ExternalIP() - if err != nil { - return "", err - } - return ip, nil - } - return calculateIP(startingIPAddr, i) -} - -func calculateIP(ip string, i int) (string, error) { - ipv4 := net.ParseIP(ip).To4() - if ipv4 == nil { - return "", fmt.Errorf("%v: non ipv4 address", ip) - } - - for j := 0; j < i; j++ { - ipv4[3]++ - } - - return ipv4.String(), nil -} - -func writeFile(name string, dir string, contents []byte) error { - writePath := filepath.Join(dir) - file := filepath.Join(writePath, name) - - err := cmn.EnsureDir(writePath, 0700) - if err != nil { - return err - } - - err = cmn.WriteFile(file, contents, 0600) - if err != nil { - return err - } - - return nil -} diff --git a/cmd/gaia/cmd/gaiadebug/README.md b/cmd/gaia/cmd/gaiadebug/README.md deleted file mode 100644 index c2f0b8bc06..0000000000 --- a/cmd/gaia/cmd/gaiadebug/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# Gaiadebug - -Simple tool for simple debugging. - -We try to accept both hex and base64 formats and provide a useful response. - -Note we often encode bytes as hex in the logs, but as base64 in the JSON. - -## Pubkeys - -The following give the same result: - -``` -gaiadebug pubkey TZTQnfqOsi89SeoXVnIw+tnFJnr4X8qVC0U8AsEmFk4= -gaiadebug pubkey 4D94D09DFA8EB22F3D49EA17567230FAD9C5267AF85FCA950B453C02C126164E -``` - -## Txs - -Pass in a hex/base64 tx and get back the full JSON - -``` -gaiadebug tx -``` - -## Hack - -This is a command with boilerplate for using Go as a scripting language to hack -on an existing Gaia state. - -Currently we have an example for the state of gaia-6001 after it -[crashed](https://github.com/cosmos/cosmos-sdk/blob/master/cmd/gaia/testnets/STATUS.md#june-13-2018-230-est---published-postmortem-of-gaia-6001-failure). -If you run `gaiadebug hack $HOME/.gaiad` on that -state, it will do a binary search on the state history to find when the state -invariant was violated. diff --git a/cmd/gaia/cmd/gaiadebug/hack.go b/cmd/gaia/cmd/gaiadebug/hack.go deleted file mode 100644 index 7e33bb8cfe..0000000000 --- a/cmd/gaia/cmd/gaiadebug/hack.go +++ /dev/null @@ -1,103 +0,0 @@ -package main - -import ( - "encoding/base64" - "encoding/hex" - "fmt" - "os" - "path" - - "github.com/cosmos/cosmos-sdk/store" - - "github.com/cosmos/cosmos-sdk/baseapp" - - "github.com/spf13/cobra" - "github.com/spf13/viper" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/crypto/ed25519" - - "github.com/tendermint/tendermint/libs/log" - - sdk "github.com/cosmos/cosmos-sdk/types" - - gaia "github.com/cosmos/cosmos-sdk/cmd/gaia/app" -) - -func runHackCmd(cmd *cobra.Command, args []string) error { - - if len(args) != 1 { - return fmt.Errorf("Expected 1 arg") - } - - // ".gaiad" - dataDir := args[0] - dataDir = path.Join(dataDir, "data") - - // load the app - logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) - db, err := sdk.NewLevelDB("gaia", dataDir) - if err != nil { - fmt.Println(err) - os.Exit(1) - } - app, keyMain, keyStaking, stakingKeeper := gaia.NewGaiaAppUNSAFE( - logger, db, nil, false, 0, baseapp.SetPruning(store.NewPruningOptionsFromString(viper.GetString("pruning")))) - - // print some info - id := app.LastCommitID() - lastBlockHeight := app.LastBlockHeight() - fmt.Println("ID", id) - fmt.Println("LastBlockHeight", lastBlockHeight) - - //---------------------------------------------------- - // XXX: start hacking! - //---------------------------------------------------- - // eg. gaia-6001 testnet bug - // We paniced when iterating through the "bypower" keys. - // The following powerKey was there, but the corresponding "trouble" validator did not exist. - // So here we do a binary search on the past states to find when the powerKey first showed up ... - - // operator of the validator the bonds, gets jailed, later unbonds, and then later is still found in the bypower store - trouble := hexToBytes("D3DC0FF59F7C3B548B7AFA365561B87FD0208AF8") - // this is his "bypower" key - powerKey := hexToBytes("05303030303030303030303033FFFFFFFFFFFF4C0C0000FFFED3DC0FF59F7C3B548B7AFA365561B87FD0208AF8") - - topHeight := lastBlockHeight - bottomHeight := int64(0) - checkHeight := topHeight - for { - // load the given version of the state - err = app.LoadVersion(checkHeight, keyMain) - if err != nil { - fmt.Println(err) - os.Exit(1) - } - ctx := app.NewContext(true, abci.Header{}) - - // check for the powerkey and the validator from the store - store := ctx.KVStore(keyStaking) - res := store.Get(powerKey) - val, _ := stakingKeeper.GetValidator(ctx, trouble) - fmt.Println("checking height", checkHeight, res, val) - if res == nil { - bottomHeight = checkHeight - } else { - topHeight = checkHeight - } - checkHeight = (topHeight + bottomHeight) / 2 - } -} - -func base64ToPub(b64 string) ed25519.PubKeyEd25519 { - data, _ := base64.StdEncoding.DecodeString(b64) - var pubKey ed25519.PubKeyEd25519 - copy(pubKey[:], data) - return pubKey - -} - -func hexToBytes(h string) []byte { - trouble, _ := hex.DecodeString(h) - return trouble - -} diff --git a/cmd/gaia/cmd/gaiadebug/main.go b/cmd/gaia/cmd/gaiadebug/main.go deleted file mode 100644 index 095c77a9fe..0000000000 --- a/cmd/gaia/cmd/gaiadebug/main.go +++ /dev/null @@ -1,256 +0,0 @@ -package main - -import ( - "bytes" - "encoding/base64" - "encoding/hex" - "encoding/json" - "fmt" - "os" - "strconv" - "strings" - - "github.com/spf13/cobra" - "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/ed25519" - - gaia "github.com/cosmos/cosmos-sdk/cmd/gaia/app" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" -) - -func init() { - - config := sdk.GetConfig() - config.SetBech32PrefixForAccount(sdk.Bech32PrefixAccAddr, sdk.Bech32PrefixAccPub) - config.SetBech32PrefixForValidator(sdk.Bech32PrefixValAddr, sdk.Bech32PrefixValPub) - config.SetBech32PrefixForConsensusNode(sdk.Bech32PrefixConsAddr, sdk.Bech32PrefixConsPub) - config.Seal() - - rootCmd.AddCommand(txCmd) - rootCmd.AddCommand(pubkeyCmd) - rootCmd.AddCommand(addrCmd) - rootCmd.AddCommand(hackCmd) - rootCmd.AddCommand(rawBytesCmd) -} - -var rootCmd = &cobra.Command{ - Use: "gaiadebug", - Short: "Gaia debug tool", - SilenceUsage: true, -} - -var txCmd = &cobra.Command{ - Use: "tx", - Short: "Decode a gaia tx from hex or base64", - RunE: runTxCmd, -} - -var pubkeyCmd = &cobra.Command{ - Use: "pubkey", - Short: "Decode a pubkey from hex, base64, or bech32", - RunE: runPubKeyCmd, -} - -var addrCmd = &cobra.Command{ - Use: "addr", - Short: "Convert an address between hex and bech32", - RunE: runAddrCmd, -} - -var hackCmd = &cobra.Command{ - Use: "hack", - Short: "Boilerplate to Hack on an existing state by scripting some Go...", - RunE: runHackCmd, -} - -var rawBytesCmd = &cobra.Command{ - Use: "raw-bytes", - Short: "Convert raw bytes output (eg. [10 21 13 255]) to hex", - RunE: runRawBytesCmd, -} - -func runRawBytesCmd(cmd *cobra.Command, args []string) error { - if len(args) != 1 { - return fmt.Errorf("Expected single arg") - } - stringBytes := args[0] - stringBytes = strings.Trim(stringBytes, "[") - stringBytes = strings.Trim(stringBytes, "]") - spl := strings.Split(stringBytes, " ") - - byteArray := []byte{} - for _, s := range spl { - b, err := strconv.Atoi(s) - if err != nil { - return err - } - byteArray = append(byteArray, byte(b)) - } - fmt.Printf("%X\n", byteArray) - return nil -} - -func runPubKeyCmd(cmd *cobra.Command, args []string) error { - if len(args) != 1 { - return fmt.Errorf("Expected single arg") - } - - pubkeyString := args[0] - var pubKeyI crypto.PubKey - - // try hex, then base64, then bech32 - pubkeyBytes, err := hex.DecodeString(pubkeyString) - if err != nil { - var err2 error - pubkeyBytes, err2 = base64.StdEncoding.DecodeString(pubkeyString) - if err2 != nil { - var err3 error - pubKeyI, err3 = sdk.GetAccPubKeyBech32(pubkeyString) - if err3 != nil { - var err4 error - pubKeyI, err4 = sdk.GetValPubKeyBech32(pubkeyString) - - if err4 != nil { - var err5 error - pubKeyI, err5 = sdk.GetConsPubKeyBech32(pubkeyString) - if err5 != nil { - return fmt.Errorf(`Expected hex, base64, or bech32. Got errors: - hex: %v, - base64: %v - bech32 Acc: %v - bech32 Val: %v - bech32 Cons: %v`, - err, err2, err3, err4, err5) - } - - } - } - - } - } - - var pubKey ed25519.PubKeyEd25519 - if pubKeyI == nil { - copy(pubKey[:], pubkeyBytes) - } else { - pubKey = pubKeyI.(ed25519.PubKeyEd25519) - pubkeyBytes = pubKey[:] - } - - cdc := gaia.MakeCodec() - pubKeyJSONBytes, err := cdc.MarshalJSON(pubKey) - if err != nil { - return err - } - accPub, err := sdk.Bech32ifyAccPub(pubKey) - if err != nil { - return err - } - valPub, err := sdk.Bech32ifyValPub(pubKey) - if err != nil { - return err - } - - consenusPub, err := sdk.Bech32ifyConsPub(pubKey) - if err != nil { - return err - } - fmt.Println("Address:", pubKey.Address()) - fmt.Printf("Hex: %X\n", pubkeyBytes) - fmt.Println("JSON (base64):", string(pubKeyJSONBytes)) - fmt.Println("Bech32 Acc:", accPub) - fmt.Println("Bech32 Validator Operator:", valPub) - fmt.Println("Bech32 Validator Consensus:", consenusPub) - return nil -} - -func runAddrCmd(cmd *cobra.Command, args []string) error { - if len(args) != 1 { - return fmt.Errorf("Expected single arg") - } - - addrString := args[0] - var addr []byte - - // try hex, then bech32 - var err error - addr, err = hex.DecodeString(addrString) - if err != nil { - var err2 error - addr, err2 = sdk.AccAddressFromBech32(addrString) - if err2 != nil { - var err3 error - addr, err3 = sdk.ValAddressFromBech32(addrString) - - if err3 != nil { - return fmt.Errorf(`Expected hex or bech32. Got errors: - hex: %v, - bech32 acc: %v - bech32 val: %v - `, err, err2, err3) - - } - } - } - - accAddr := sdk.AccAddress(addr) - valAddr := sdk.ValAddress(addr) - - fmt.Println("Address:", addr) - fmt.Printf("Address (hex): %X\n", addr) - fmt.Printf("Bech32 Acc: %s\n", accAddr) - fmt.Printf("Bech32 Val: %s\n", valAddr) - return nil -} - -func runTxCmd(cmd *cobra.Command, args []string) error { - if len(args) != 1 { - return fmt.Errorf("Expected single arg") - } - - txString := args[0] - - // try hex, then base64 - txBytes, err := hex.DecodeString(txString) - if err != nil { - var err2 error - txBytes, err2 = base64.StdEncoding.DecodeString(txString) - if err2 != nil { - return fmt.Errorf(`Expected hex or base64. Got errors: - hex: %v, - base64: %v - `, err, err2) - } - } - - var tx = auth.StdTx{} - cdc := gaia.MakeCodec() - - err = cdc.UnmarshalBinaryLengthPrefixed(txBytes, &tx) - if err != nil { - return err - } - - bz, err := cdc.MarshalJSON(tx) - if err != nil { - return err - } - - buf := bytes.NewBuffer([]byte{}) - err = json.Indent(buf, bz, "", " ") - if err != nil { - return err - } - - fmt.Println(buf.String()) - return nil -} - -func main() { - err := rootCmd.Execute() - if err != nil { - os.Exit(1) - } - os.Exit(0) -} diff --git a/cmd/gaia/contrib/gitian-build.sh b/cmd/gaia/contrib/gitian-build.sh deleted file mode 100755 index 22e6d5133c..0000000000 --- a/cmd/gaia/contrib/gitian-build.sh +++ /dev/null @@ -1,201 +0,0 @@ -#!/bin/bash - -# symbol prefixes: -# g_ -> global -# l_ - local variable -# f_ -> function - -set -euo pipefail - -GITIAN_CACHE_DIRNAME='.gitian-builder-cache' -GO_DEBIAN_RELEASE='1.12.5-1' -GO_TARBALL="golang-debian-${GO_DEBIAN_RELEASE}.tar.gz" -GO_TARBALL_URL="https://salsa.debian.org/go-team/compiler/golang/-/archive/debian/${GO_DEBIAN_RELEASE}/${GO_TARBALL}" - -# Defaults - -DEFAULT_SIGN_COMMAND='gpg --detach-sign' -DEFAULT_GAIA_SIGS=${GAIA_SIGS:-'gaia.sigs'} -DEFAULT_GITIAN_REPO='https://github.com/devrandom/gitian-builder' -DEFAULT_GBUILD_FLAGS='' -DEFAULT_SIGS_REPO='https://github.com/cosmos/gaia.sigs' - -# Overrides - -SIGN_COMMAND=${SIGN_COMMAND:-${DEFAULT_SIGN_COMMAND}} -GITIAN_REPO=${GITIAN_REPO:-${DEFAULT_GITIAN_REPO}} -GBUILD_FLAGS=${GBUILD_FLAGS:-${DEFAULT_GBUILD_FLAGS}} - -# Globals - -g_workdir='' -g_gitian_cache='' -g_cached_gitian='' -g_cached_go_tarball='' -g_sign_identity='' -g_sigs_dir='' -g_flag_commit='' - - -f_help() { - cat >&2 <&2 - mkdir "${l_builddir}/inputs/" - cp -v "${g_cached_go_tarball}" "${l_builddir}/inputs/" - done -} - -f_build() { - local l_descriptor - - l_descriptor=$1 - - bin/gbuild --commit cosmos-sdk="$g_commit" ${GBUILD_FLAGS} "$l_descriptor" - libexec/stop-target || f_echo_stderr "warning: couldn't stop target" -} - -f_sign_verify() { - local l_descriptor - - l_descriptor=$1 - - bin/gsign -p "${SIGN_COMMAND}" -s "${g_sign_identity}" --destination="${g_sigs_dir}" --release=${g_release} ${l_descriptor} - bin/gverify --destination="${g_sigs_dir}" --release="${g_release}" ${l_descriptor} -} - -f_commit_sig() { - local l_release_name - - l_release_name=$1 - - pushd "${g_sigs_dir}" - git add . || echo "git add failed" >&2 - git commit -m "Add ${l_release_name} reproducible build" || echo "git commit failed" >&2 - popd -} - -f_prep_docker_image() { - pushd $1 - bin/make-base-vm --docker --suite bionic --arch amd64 - popd -} - -f_ensure_cache() { - g_gitian_cache="${g_workdir}/${GITIAN_CACHE_DIRNAME}" - [ -d "${g_gitian_cache}" ] || mkdir "${g_gitian_cache}" - - g_cached_go_tarball="${g_gitian_cache}/${GO_TARBALL}" - if [ ! -f "${g_cached_go_tarball}" ]; then - f_echo_stderr "${g_cached_go_tarball}: cache miss, caching..." - curl -L "${GO_TARBALL_URL}" --output "${g_cached_go_tarball}" - fi - - g_cached_gitian="${g_gitian_cache}/gitian-builder" - if [ ! -d "${g_cached_gitian}" ]; then - f_echo_stderr "${g_cached_gitian}: cache miss, caching..." - git clone ${GITIAN_REPO} "${g_cached_gitian}" - fi -} - -f_demangle_platforms() { - case "${1}" in - all) - printf '%s' 'darwin linux windows' ;; - linux|darwin|windows) - printf '%s' "${1}" ;; - *) - echo "invalid platform -- ${1}" - exit 1 - esac -} - -f_echo_stderr() { - echo $@ >&2 -} - - -while getopts ":cs:h" opt; do - case "${opt}" in - h) f_help ; exit 0 ;; - c) g_flag_commit=y ;; - s) g_sign_identity="${OPTARG}" ;; - esac -done - -shift "$((OPTIND-1))" - -g_platforms=$(f_demangle_platforms "${1}") -g_workdir="$(pwd)" -g_commit="$(git rev-parse HEAD)" -g_sigs_dir=${GAIA_SIGS:-"${g_workdir}/${DEFAULT_GAIA_SIGS}"} - -f_ensure_cache - -f_prep_docker_image "${g_cached_gitian}" - -f_prep_build "${g_platforms}" - -export USE_DOCKER=1 -for g_os in ${g_platforms}; do - g_release="$(git describe --tags --abbrev=9 | sed 's/^v//')-${g_os}" - g_descriptor="${g_workdir}/cmd/gaia/contrib/gitian-descriptors/gitian-${g_os}.yml" - [ -f ${g_descriptor} ] - g_builddir="$(f_builddir ${g_os})" - - pushd "${g_builddir}" - f_build "${g_descriptor}" - if [ -n "${g_sign_identity}" ]; then - f_sign_verify "${g_descriptor}" - fi - popd - - if [ -n "${g_sign_identity}" -a -n "${g_flag_commit}" ]; then - [ -d "${g_sigs_dir}/.git/" ] && f_commit_sig ${g_release} || f_echo_stderr "couldn't commit, ${g_sigs_dir} is not a git clone" - fi -done - -exit 0 diff --git a/cmd/gaia/contrib/gitian-descriptors/gitian-darwin.yml b/cmd/gaia/contrib/gitian-descriptors/gitian-darwin.yml deleted file mode 100644 index 67cd69c5af..0000000000 --- a/cmd/gaia/contrib/gitian-descriptors/gitian-darwin.yml +++ /dev/null @@ -1,116 +0,0 @@ ---- -name: "gaia-darwin" -enable_cache: true -distro: "ubuntu" -suites: -- "bionic" -architectures: -- "amd64" -packages: -- "bsdmainutils" -- "build-essential" -- "ca-certificates" -- "curl" -- "debhelper" -- "dpkg-dev" -- "devscripts" -- "fakeroot" -- "git" -- "golang-any" -- "xxd" -- "quilt" -remotes: -- "url": "https://github.com/cosmos/cosmos-sdk.git" - "dir": "cosmos-sdk" -files: -- "golang-debian-1.12.5-1.tar.gz" -script: | - set -e -o pipefail - - GO_SRC_RELEASE=golang-debian-1.12.5-1 - GO_SRC_TARBALL="${GO_SRC_RELEASE}.tar.gz" - # Compile go and configure the environment - export TAR_OPTIONS="--mtime="$REFERENCE_DATE\\\ $REFERENCE_TIME"" - export BUILD_DIR=`pwd` - tar xf "${GO_SRC_TARBALL}" - rm -f "${GO_SRC_TARBALL}" - [ -d "${GO_SRC_RELEASE}/" ] - mv "${GO_SRC_RELEASE}/" go/ - pushd go/ - QUILT_PATCHES=debian/patches quilt push -a - fakeroot debian/rules build RUN_TESTS=false GOCACHE=/tmp/go-cache - popd - - export GOOS=darwin - export GOROOT=${BUILD_DIR}/go - export GOPATH=${BUILD_DIR}/gopath - mkdir -p ${GOPATH}/bin - - export PATH_orig=${PATH} - export PATH=$GOPATH/bin:$GOROOT/bin:$PATH - - export ARCHS='386 amd64' - export GO111MODULE=on - - # Make release tarball - pushd cosmos-sdk - VERSION=$(git describe --tags | sed 's/^v//') - COMMIT=$(git log -1 --format='%H') - DISTNAME=gaia-${VERSION} - git archive --format tar.gz --prefix ${DISTNAME}/ -o ${DISTNAME}.tar.gz HEAD - SOURCEDIST=`pwd`/`echo gaia-*.tar.gz` - popd - - # Correct tar file order - mkdir -p temp - pushd temp - tar xf $SOURCEDIST - rm $SOURCEDIST - find gaia-* | sort | tar --no-recursion --mode='u+rw,go+r-w,a+X' --owner=0 --group=0 -c -T - | gzip -9n > $SOURCEDIST - popd - - # Prepare GOPATH and install deps - distsrc=${GOPATH}/src/github.com/cosmos/cosmos-sdk - mkdir -p ${distsrc} - pushd ${distsrc} - tar --strip-components=1 -xf $SOURCEDIST - go mod download - popd - - # Configure LDFLAGS for reproducible builds - LDFLAGS="-extldflags=-static -buildid=${VERSION} -s -w \ - -X github.com/cosmos/cosmos-sdk/version.Name=gaia \ - -X github.com/cosmos/cosmos-sdk/version.Version=${VERSION} \ - -X github.com/cosmos/cosmos-sdk/version.Commit=${COMMIT} \ - -X github.com/cosmos/cosmos-sdk/version.BuildTags=netgo,ledger" - - # Extract release tarball and build - for arch in ${ARCHS}; do - INSTALLPATH=`pwd`/installed/${DISTNAME}-${arch} - mkdir -p ${INSTALLPATH} - - # Build gaia tool suite - pushd ${distsrc} - for prog in gaiacli gaiad; do - GOARCH=${arch} GOROOT_FINAL=${GOROOT} go build -a \ - -gcflags=all=-trimpath=${GOPATH} \ - -asmflags=all=-trimpath=${GOPATH} \ - -mod=readonly -tags "netgo ledger" \ - -ldflags="${LDFLAGS}" \ - -o ${INSTALLPATH}/${prog} ./cmd/gaia/cmd/${prog} - - done - popd # ${distsrc} - - pushd ${INSTALLPATH} - find -type f | sort | tar \ - --no-recursion --mode='u+rw,go+r-w,a+X' \ - --numeric-owner --sort=name \ - --owner=0 --group=0 -c -T - | gzip -9n > ${OUTDIR}/${DISTNAME}-darwin-${arch}.tar.gz - popd # installed - done - - rm -rf ${distsrc} - - mkdir -p $OUTDIR/src - mv $SOURCEDIST $OUTDIR/src diff --git a/cmd/gaia/contrib/gitian-descriptors/gitian-linux.yml b/cmd/gaia/contrib/gitian-descriptors/gitian-linux.yml deleted file mode 100644 index f3112baa2b..0000000000 --- a/cmd/gaia/contrib/gitian-descriptors/gitian-linux.yml +++ /dev/null @@ -1,115 +0,0 @@ ---- -name: "gaia-linux" -enable_cache: true -distro: "ubuntu" -suites: -- "bionic" -architectures: -- "amd64" -packages: -- "bsdmainutils" -- "build-essential" -- "ca-certificates" -- "curl" -- "debhelper" -- "dpkg-dev" -- "devscripts" -- "fakeroot" -- "git" -- "golang-any" -- "xxd" -- "quilt" -remotes: -- "url": "https://github.com/cosmos/cosmos-sdk.git" - "dir": "cosmos-sdk" -files: -- "golang-debian-1.12.5-1.tar.gz" -script: | - set -e -o pipefail - - GO_SRC_RELEASE=golang-debian-1.12.5-1 - GO_SRC_TARBALL="${GO_SRC_RELEASE}.tar.gz" - # Compile go and configure the environment - export TAR_OPTIONS="--mtime="$REFERENCE_DATE\\\ $REFERENCE_TIME"" - export BUILD_DIR=`pwd` - tar xf "${GO_SRC_TARBALL}" - rm -f "${GO_SRC_TARBALL}" - [ -d "${GO_SRC_RELEASE}/" ] - mv "${GO_SRC_RELEASE}/" go/ - pushd go/ - QUILT_PATCHES=debian/patches quilt push -a - fakeroot debian/rules build RUN_TESTS=false GOCACHE=/tmp/go-cache - popd - - export GOROOT=${BUILD_DIR}/go - export GOPATH=${BUILD_DIR}/gopath - mkdir -p ${GOPATH}/bin - - export PATH_orig=${PATH} - export PATH=$GOPATH/bin:$GOROOT/bin:$PATH - - export ARCHS='386 amd64 arm arm64' - export GO111MODULE=on - - # Make release tarball - pushd cosmos-sdk - VERSION=$(git describe --tags | sed 's/^v//') - COMMIT=$(git log -1 --format='%H') - DISTNAME=gaia-${VERSION} - git archive --format tar.gz --prefix ${DISTNAME}/ -o ${DISTNAME}.tar.gz HEAD - SOURCEDIST=`pwd`/`echo gaia-*.tar.gz` - popd - - # Correct tar file order - mkdir -p temp - pushd temp - tar xf $SOURCEDIST - rm $SOURCEDIST - find gaia-* | sort | tar --no-recursion --mode='u+rw,go+r-w,a+X' --owner=0 --group=0 -c -T - | gzip -9n > $SOURCEDIST - popd - - # Prepare GOPATH and install deps - distsrc=${GOPATH}/src/github.com/cosmos/cosmos-sdk - mkdir -p ${distsrc} - pushd ${distsrc} - tar --strip-components=1 -xf $SOURCEDIST - go mod download - popd - - # Configure LDFLAGS for reproducible builds - LDFLAGS="-extldflags=-static -buildid=${VERSION} -s -w \ - -X github.com/cosmos/cosmos-sdk/version.Name=gaia \ - -X github.com/cosmos/cosmos-sdk/version.Version=${VERSION} \ - -X github.com/cosmos/cosmos-sdk/version.Commit=${COMMIT} \ - -X github.com/cosmos/cosmos-sdk/version.BuildTags=netgo,ledger" - - # Extract release tarball and build - for arch in ${ARCHS}; do - INSTALLPATH=`pwd`/installed/${DISTNAME}-${arch} - mkdir -p ${INSTALLPATH} - - # Build gaia tool suite - pushd ${distsrc} - for prog in gaiacli gaiad; do - GOARCH=${arch} GOROOT_FINAL=${GOROOT} go build -a \ - -gcflags=all=-trimpath=${GOPATH} \ - -asmflags=all=-trimpath=${GOPATH} \ - -mod=readonly -tags "netgo ledger" \ - -ldflags="${LDFLAGS}" \ - -o ${INSTALLPATH}/${prog} ./cmd/gaia/cmd/${prog} - - done - popd # ${distsrc} - - pushd ${INSTALLPATH} - find -type f | sort | tar \ - --no-recursion --mode='u+rw,go+r-w,a+X' \ - --numeric-owner --sort=name \ - --owner=0 --group=0 -c -T - | gzip -9n > ${OUTDIR}/${DISTNAME}-linux-${arch}.tar.gz - popd # installed - done - - rm -rf ${distsrc} - - mkdir -p $OUTDIR/src - mv $SOURCEDIST $OUTDIR/src diff --git a/cmd/gaia/contrib/gitian-descriptors/gitian-windows.yml b/cmd/gaia/contrib/gitian-descriptors/gitian-windows.yml deleted file mode 100644 index 4ad03c328b..0000000000 --- a/cmd/gaia/contrib/gitian-descriptors/gitian-windows.yml +++ /dev/null @@ -1,116 +0,0 @@ ---- -name: "gaia-windows" -enable_cache: true -distro: "ubuntu" -suites: -- "bionic" -architectures: -- "amd64" -packages: -- "bsdmainutils" -- "build-essential" -- "ca-certificates" -- "curl" -- "debhelper" -- "dpkg-dev" -- "devscripts" -- "fakeroot" -- "git" -- "golang-any" -- "xxd" -- "quilt" -remotes: -- "url": "https://github.com/cosmos/cosmos-sdk.git" - "dir": "cosmos-sdk" -files: -- "golang-debian-1.12.5-1.tar.gz" -script: | - set -e -o pipefail - - GO_SRC_RELEASE=golang-debian-1.12.5-1 - GO_SRC_TARBALL="${GO_SRC_RELEASE}.tar.gz" - # Compile go and configure the environment - export TAR_OPTIONS="--mtime="$REFERENCE_DATE\\\ $REFERENCE_TIME"" - export BUILD_DIR=`pwd` - tar xf "${GO_SRC_TARBALL}" - rm -f "${GO_SRC_TARBALL}" - [ -d "${GO_SRC_RELEASE}/" ] - mv "${GO_SRC_RELEASE}/" go/ - pushd go/ - QUILT_PATCHES=debian/patches quilt push -a - fakeroot debian/rules build RUN_TESTS=false GOCACHE=/tmp/go-cache - popd - - export GOROOT=${BUILD_DIR}/go - export GOPATH=${BUILD_DIR}/gopath - mkdir -p ${GOPATH}/bin - - export PATH_orig=${PATH} - export PATH=$GOPATH/bin:$GOROOT/bin:$PATH - - export ARCHS='386 amd64' - export GO111MODULE=on - - # Make release tarball - pushd cosmos-sdk - VERSION=$(git describe --tags | sed 's/^v//') - COMMIT=$(git log -1 --format='%H') - DISTNAME=gaia-${VERSION} - git archive --format tar.gz --prefix ${DISTNAME}/ -o ${DISTNAME}.tar.gz HEAD - SOURCEDIST=`pwd`/`echo gaia-*.tar.gz` - popd - - # Correct tar file order - mkdir -p temp - pushd temp - tar xf $SOURCEDIST - rm $SOURCEDIST - find gaia-* | sort | tar --no-recursion --mode='u+rw,go+r-w,a+X' --owner=0 --group=0 -c -T - | gzip -9n > $SOURCEDIST - popd - - # Prepare GOPATH and install deps - distsrc=${GOPATH}/src/github.com/cosmos/cosmos-sdk - mkdir -p ${distsrc} - pushd ${distsrc} - tar --strip-components=1 -xf $SOURCEDIST - go mod download - popd - - # Configure LDFLAGS for reproducible builds - LDFLAGS="-extldflags=-static -buildid=${VERSION} -s -w \ - -X github.com/cosmos/cosmos-sdk/version.Name=gaia \ - -X github.com/cosmos/cosmos-sdk/version.Version=${VERSION} \ - -X github.com/cosmos/cosmos-sdk/version.Commit=${COMMIT} \ - -X github.com/cosmos/cosmos-sdk/version.BuildTags=netgo,ledger" - - # Extract release tarball and build - for arch in ${ARCHS}; do - INSTALLPATH=`pwd`/installed/${DISTNAME}-${arch} - mkdir -p ${INSTALLPATH} - - # Build gaia tool suite - pushd ${distsrc} - for prog in gaiacli gaiad; do - exe=${prog}.exe - GOARCH=${arch} GOROOT_FINAL=${GOROOT} go build -a \ - -gcflags=all=-trimpath=${GOPATH} \ - -asmflags=all=-trimpath=${GOPATH} \ - -mod=readonly -tags "netgo ledger" \ - -ldflags="${LDFLAGS}" \ - -o ${INSTALLPATH}/${exe} ./cmd/gaia/cmd/${prog} - - done - popd # ${distsrc} - - pushd ${INSTALLPATH} - find -type f | sort | tar \ - --no-recursion --mode='u+rw,go+r-w,a+X' \ - --numeric-owner --sort=name \ - --owner=0 --group=0 -c -T - | gzip -9n > ${OUTDIR}/${DISTNAME}-windows-${arch}.tar.gz - popd # installed - done - - rm -rf ${distsrc} - - mkdir -p $OUTDIR/src - mv $SOURCEDIST $OUTDIR/src diff --git a/cmd/gaia/contrib/gitian-keys/README.md b/cmd/gaia/contrib/gitian-keys/README.md deleted file mode 100644 index 645014337f..0000000000 --- a/cmd/gaia/contrib/gitian-keys/README.md +++ /dev/null @@ -1,29 +0,0 @@ -## PGP keys of Gitian builders and Gaia Developers - -The file `keys.txt` contains fingerprints of the public keys of Gitian builders -and active developers. - -The associated keys are mainly used to sign git commits or the build results -of Gitian builds. - -The most recent version of each pgp key can be found on most PGP key servers. - -Fetch the latest version from the key server to see if any key was revoked in -the meantime. -To fetch the latest version of all pgp keys in your gpg homedir, - -```sh -gpg --refresh-keys -``` - -To fetch keys of Gitian builders and active core developers, feed the list of -fingerprints of the primary keys into gpg: - -```sh -while read fingerprint keyholder_name; \ -do gpg --keyserver hkp://subset.pool.sks-keyservers.net \ ---recv-keys ${fingerprint}; done < ./keys.txt -``` - -Add your key to the list if you are a Gaia core developer or you have -provided Gitian signatures for two major or minor releases of Gaia. diff --git a/cmd/gaia/contrib/gitian-keys/keys.txt b/cmd/gaia/contrib/gitian-keys/keys.txt deleted file mode 100644 index 1d9cf6ec5b..0000000000 --- a/cmd/gaia/contrib/gitian-keys/keys.txt +++ /dev/null @@ -1,2 +0,0 @@ -04160004A8276E40BB9890FBE8A48AE5311D765A Alessio Treglia -237396563D09DCD65B122AE7EC1904F1389EF7E5 Karoly Albert Szabo diff --git a/cmd/gaia/lcd_test/helpers_test.go b/cmd/gaia/lcd_test/helpers_test.go deleted file mode 100644 index 0ff227d0c6..0000000000 --- a/cmd/gaia/lcd_test/helpers_test.go +++ /dev/null @@ -1,1557 +0,0 @@ -package lcd_test - -import ( - "bytes" - "fmt" - "io/ioutil" - "net" - "net/http" - "os" - "path/filepath" - "regexp" - "sort" - "strings" - "testing" - - "github.com/spf13/viper" - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/client" - clientkeys "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/client/lcd" - "github.com/cosmos/cosmos-sdk/client/rpc" - "github.com/cosmos/cosmos-sdk/client/tx" - clienttx "github.com/cosmos/cosmos-sdk/client/tx" - "github.com/cosmos/cosmos-sdk/client/utils" - gapp "github.com/cosmos/cosmos-sdk/cmd/gaia/app" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/crypto/keys" - crkeys "github.com/cosmos/cosmos-sdk/crypto/keys" - "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/tests" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth" - authrest "github.com/cosmos/cosmos-sdk/x/auth/client/rest" - txbuilder "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" - "github.com/cosmos/cosmos-sdk/x/auth/genaccounts" - bankrest "github.com/cosmos/cosmos-sdk/x/bank/client/rest" - "github.com/cosmos/cosmos-sdk/x/crisis" - distr "github.com/cosmos/cosmos-sdk/x/distribution" - distrrest "github.com/cosmos/cosmos-sdk/x/distribution/client/rest" - "github.com/cosmos/cosmos-sdk/x/genutil" - "github.com/cosmos/cosmos-sdk/x/gov" - govrest "github.com/cosmos/cosmos-sdk/x/gov/client/rest" - gcutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" - "github.com/cosmos/cosmos-sdk/x/mint" - mintrest "github.com/cosmos/cosmos-sdk/x/mint/client/rest" - paramsrest "github.com/cosmos/cosmos-sdk/x/params/client/rest" - paramscutils "github.com/cosmos/cosmos-sdk/x/params/client/utils" - "github.com/cosmos/cosmos-sdk/x/slashing" - slashingrest "github.com/cosmos/cosmos-sdk/x/slashing/client/rest" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingrest "github.com/cosmos/cosmos-sdk/x/staking/client/rest" - - abci "github.com/tendermint/tendermint/abci/types" - tmcfg "github.com/tendermint/tendermint/config" - "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/ed25519" - "github.com/tendermint/tendermint/crypto/secp256k1" - "github.com/tendermint/tendermint/libs/cli" - dbm "github.com/tendermint/tendermint/libs/db" - "github.com/tendermint/tendermint/libs/log" - nm "github.com/tendermint/tendermint/node" - "github.com/tendermint/tendermint/p2p" - pvm "github.com/tendermint/tendermint/privval" - "github.com/tendermint/tendermint/proxy" - ctypes "github.com/tendermint/tendermint/rpc/core/types" - tmrpc "github.com/tendermint/tendermint/rpc/lib/server" - tmtypes "github.com/tendermint/tendermint/types" -) - -var cdc = codec.New() - -func init() { - codec.RegisterCrypto(cdc) -} - -// makePathname creates a unique pathname for each test. It will panic if it -// cannot get the current working directory. -func makePathname() string { - p, err := os.Getwd() - if err != nil { - panic(err) - } - - sep := string(filepath.Separator) - return strings.Replace(p, sep, "_", -1) -} - -// GetConfig returns a Tendermint config for the test cases. -func GetConfig() *tmcfg.Config { - pathname := makePathname() - config := tmcfg.ResetTestRoot(pathname) - - tmAddr, _, err := server.FreeTCPAddr() - if err != nil { - panic(err) - } - - rcpAddr, _, err := server.FreeTCPAddr() - if err != nil { - panic(err) - } - - grpcAddr, _, err := server.FreeTCPAddr() - if err != nil { - panic(err) - } - - config.P2P.ListenAddress = tmAddr - config.RPC.ListenAddress = rcpAddr - config.RPC.GRPCListenAddress = grpcAddr - - return config -} - -// CreateAddr adds an address to the key store and returns an address and seed. -// It also requires that the key could be created. -func CreateAddr(t *testing.T, name, password string, kb crkeys.Keybase) (sdk.AccAddress, string) { - var ( - err error - info crkeys.Info - seed string - ) - - info, seed, err = kb.CreateMnemonic(name, crkeys.English, password, crkeys.Secp256k1) - require.NoError(t, err) - - return sdk.AccAddress(info.GetPubKey().Address()), seed -} - -// CreateAddr adds multiple address to the key store and returns the addresses and associated seeds in lexographical order by address. -// It also requires that the keys could be created. -func CreateAddrs(t *testing.T, kb crkeys.Keybase, numAddrs int) (addrs []sdk.AccAddress, seeds, names, passwords []string) { - var ( - err error - info crkeys.Info - seed string - ) - - addrSeeds := AddrSeedSlice{} - - for i := 0; i < numAddrs; i++ { - name := fmt.Sprintf("test%d", i) - password := "1234567890" - info, seed, err = kb.CreateMnemonic(name, crkeys.English, password, crkeys.Secp256k1) - require.NoError(t, err) - addrSeeds = append(addrSeeds, AddrSeed{Address: sdk.AccAddress(info.GetPubKey().Address()), Seed: seed, Name: name, Password: password}) - } - - sort.Sort(addrSeeds) - - for i := range addrSeeds { - addrs = append(addrs, addrSeeds[i].Address) - seeds = append(seeds, addrSeeds[i].Seed) - names = append(names, addrSeeds[i].Name) - passwords = append(passwords, addrSeeds[i].Password) - } - - return addrs, seeds, names, passwords -} - -// AddrSeed combines an Address with the mnemonic of the private key to that address -type AddrSeed struct { - Address sdk.AccAddress - Seed string - Name string - Password string -} - -// AddrSeedSlice implements `Interface` in sort package. -type AddrSeedSlice []AddrSeed - -func (b AddrSeedSlice) Len() int { - return len(b) -} - -// Less sorts lexicographically by Address -func (b AddrSeedSlice) Less(i, j int) bool { - // bytes package already implements Comparable for []byte. - switch bytes.Compare(b[i].Address.Bytes(), b[j].Address.Bytes()) { - case -1: - return true - case 0, 1: - return false - default: - panic("not fail-able with `bytes.Comparable` bounded [-1, 1].") - } -} - -func (b AddrSeedSlice) Swap(i, j int) { - b[j], b[i] = b[i], b[j] -} - -// InitClientHome initialises client home dir. -func InitClientHome(t *testing.T, dir string) string { - var err error - if dir == "" { - dir, err = ioutil.TempDir("", "lcd_test") - require.NoError(t, err) - } - // TODO: this should be set in NewRestServer - // and pass down the CLIContext to achieve - // parallelism. - viper.Set(cli.HomeFlag, dir) - return dir -} - -// TODO: Make InitializeTestLCD safe to call in multiple tests at the same time -// InitializeTestLCD starts Tendermint and the LCD in process, listening on -// their respective sockets where nValidators is the total number of validators -// and initAddrs are the accounts to initialize with some stake tokens. It -// returns a cleanup function, a set of validator public keys, and a port. -func InitializeTestLCD(t *testing.T, nValidators int, initAddrs []sdk.AccAddress, minting bool) ( - cleanup func(), valConsPubKeys []crypto.PubKey, valOperAddrs []sdk.ValAddress, port string) { - - if nValidators < 1 { - panic("InitializeTestLCD must use at least one validator") - } - - config := GetConfig() - config.Consensus.TimeoutCommit = 100 - config.Consensus.SkipTimeoutCommit = false - config.TxIndex.IndexAllTags = true - - logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) - logger = log.NewFilter(logger, log.AllowError()) - - privVal := pvm.LoadOrGenFilePV(config.PrivValidatorKeyFile(), - config.PrivValidatorStateFile()) - privVal.Reset() - - db := dbm.NewMemDB() - app := gapp.NewGaiaApp(logger, db, nil, true, 0) - cdc = gapp.MakeCodec() - - genesisFile := config.GenesisFile() - genDoc, err := tmtypes.GenesisDocFromFile(genesisFile) - require.Nil(t, err) - genDoc.Validators = nil - require.NoError(t, genDoc.SaveAs(genesisFile)) - - // append any additional (non-proposing) validators - var genTxs []auth.StdTx - var accs []genaccounts.GenesisAccount - for i := 0; i < nValidators; i++ { - operPrivKey := secp256k1.GenPrivKey() - operAddr := operPrivKey.PubKey().Address() - pubKey := privVal.GetPubKey() - - power := int64(100) - if i > 0 { - pubKey = ed25519.GenPrivKey().PubKey() - power = 1 - } - startTokens := sdk.TokensFromTendermintPower(power) - - msg := staking.NewMsgCreateValidator( - sdk.ValAddress(operAddr), - pubKey, - sdk.NewCoin(sdk.DefaultBondDenom, startTokens), - staking.NewDescription(fmt.Sprintf("validator-%d", i+1), "", "", ""), - staking.NewCommissionMsg(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - sdk.OneInt(), - ) - stdSignMsg := txbuilder.StdSignMsg{ - ChainID: genDoc.ChainID, - Msgs: []sdk.Msg{msg}, - } - sig, err := operPrivKey.Sign(stdSignMsg.Bytes()) - require.Nil(t, err) - - tx := auth.NewStdTx([]sdk.Msg{msg}, auth.StdFee{}, []auth.StdSignature{{Signature: sig, PubKey: operPrivKey.PubKey()}}, "") - genTxs = append(genTxs, tx) - - valConsPubKeys = append(valConsPubKeys, pubKey) - valOperAddrs = append(valOperAddrs, sdk.ValAddress(operAddr)) - - accAuth := auth.NewBaseAccountWithAddress(sdk.AccAddress(operAddr)) - accTokens := sdk.TokensFromTendermintPower(150) - accAuth.Coins = sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, accTokens)} - accs = append(accs, genaccounts.NewGenesisAccount(&accAuth)) - } - - genesisState := gapp.NewDefaultGenesisState() - genDoc.AppState, err = cdc.MarshalJSON(genesisState) - require.NoError(t, err) - genesisState, err = genutil.SetGenTxsInAppGenesisState(cdc, genesisState, genTxs) - require.NoError(t, err) - - // add some tokens to init accounts - stakingDataBz := genesisState[staking.ModuleName] - var stakingData staking.GenesisState - cdc.MustUnmarshalJSON(stakingDataBz, &stakingData) - for _, addr := range initAddrs { - accAuth := auth.NewBaseAccountWithAddress(addr) - accTokens := sdk.TokensFromTendermintPower(100) - accAuth.Coins = sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, accTokens)} - acc := genaccounts.NewGenesisAccount(&accAuth) - accs = append(accs, acc) - } - - // now add the account tokens to the non-bonded pool - for _, acc := range accs { - accTokens := acc.Coins.AmountOf(sdk.DefaultBondDenom) - stakingData.Pool.NotBondedTokens = stakingData.Pool.NotBondedTokens.Add(accTokens) - } - stakingDataBz = cdc.MustMarshalJSON(stakingData) - genesisState[staking.ModuleName] = stakingDataBz - - genaccountsData := genaccounts.NewGenesisState(accs) - genaccountsDataBz := cdc.MustMarshalJSON(genaccountsData) - genesisState[genaccounts.ModuleName] = genaccountsDataBz - - // mint genesis (none set within genesisState) - mintData := mint.DefaultGenesisState() - inflationMin := sdk.ZeroDec() - if minting { - inflationMin = sdk.MustNewDecFromStr("10000.0") - mintData.Params.InflationMax = sdk.MustNewDecFromStr("15000.0") - } else { - mintData.Params.InflationMax = inflationMin - } - mintData.Minter.Inflation = inflationMin - mintData.Params.InflationMin = inflationMin - mintDataBz := cdc.MustMarshalJSON(mintData) - genesisState[mint.ModuleName] = mintDataBz - - // initialize crisis data - crisisDataBz := genesisState[crisis.ModuleName] - var crisisData crisis.GenesisState - cdc.MustUnmarshalJSON(crisisDataBz, &crisisData) - crisisData.ConstantFee = sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000) - crisisDataBz = cdc.MustMarshalJSON(crisisData) - genesisState[crisis.ModuleName] = crisisDataBz - - // double check inflation is set according to the minting boolean flag - if minting { - require.Equal(t, sdk.MustNewDecFromStr("15000.0"), mintData.Params.InflationMax) - require.Equal(t, sdk.MustNewDecFromStr("10000.0"), mintData.Minter.Inflation) - require.Equal(t, sdk.MustNewDecFromStr("10000.0"), mintData.Params.InflationMin) - } else { - require.Equal(t, sdk.ZeroDec(), mintData.Params.InflationMax) - require.Equal(t, sdk.ZeroDec(), mintData.Minter.Inflation) - require.Equal(t, sdk.ZeroDec(), mintData.Params.InflationMin) - } - - appState, err := codec.MarshalJSONIndent(cdc, genesisState) - require.NoError(t, err) - genDoc.AppState = appState - - listenAddr, port, err := server.FreeTCPAddr() - require.NoError(t, err) - - // NOTE: Need to set this so LCD knows the tendermint node address! - viper.Set(client.FlagNode, config.RPC.ListenAddress) - viper.Set(client.FlagChainID, genDoc.ChainID) - // TODO Set to false once the upstream Tendermint proof verification issue is fixed. - viper.Set(client.FlagTrustNode, true) - - node := startTM(t, config, logger, genDoc, privVal, app) - require.NoError(t, err) - - tests.WaitForNextHeightTM(tests.ExtractPortFromAddress(config.RPC.ListenAddress)) - lcd, err := startLCD(logger, listenAddr, cdc, t) - require.NoError(t, err) - - tests.WaitForLCDStart(port) - tests.WaitForHeight(1, port) - - cleanup = func() { - logger.Debug("cleaning up LCD initialization") - node.Stop() //nolint:errcheck - node.Wait() - lcd.Close() - os.RemoveAll(config.RootDir) - } - - return cleanup, valConsPubKeys, valOperAddrs, port -} - -// startTM creates and starts an in-process Tendermint node with memDB and -// in-process ABCI application. It returns the new node or any error that -// occurred. -// -// TODO: Clean up the WAL dir or enable it to be not persistent! -func startTM( - t *testing.T, tmcfg *tmcfg.Config, logger log.Logger, genDoc *tmtypes.GenesisDoc, - privVal tmtypes.PrivValidator, app abci.Application, -) *nm.Node { - - genDocProvider := func() (*tmtypes.GenesisDoc, error) { return genDoc, nil } - dbProvider := func(*nm.DBContext) (dbm.DB, error) { return dbm.NewMemDB(), nil } - nodeKey, err := p2p.LoadOrGenNodeKey(tmcfg.NodeKeyFile()) - require.NoError(t, err) - - node, err := nm.NewNode( - tmcfg, - privVal, - nodeKey, - proxy.NewLocalClientCreator(app), - genDocProvider, - dbProvider, - nm.DefaultMetricsProvider(tmcfg.Instrumentation), - logger.With("module", "node"), - ) - require.NoError(t, err) - - err = node.Start() - require.NoError(t, err) - - tests.WaitForRPC(tmcfg.RPC.ListenAddress) - logger.Info("Tendermint running!") - - return node -} - -// startLCD starts the LCD. -func startLCD(logger log.Logger, listenAddr string, cdc *codec.Codec, t *testing.T) (net.Listener, error) { - rs := lcd.NewRestServer(cdc) - registerRoutes(rs) - listener, err := tmrpc.Listen(listenAddr, tmrpc.DefaultConfig()) - if err != nil { - return nil, err - } - go tmrpc.StartHTTPServer(listener, rs.Mux, logger, tmrpc.DefaultConfig()) //nolint:errcheck - return listener, nil -} - -// TODO generalize this with the module basic manager -// NOTE: If making updates here also update cmd/gaia/cmd/gaiacli/main.go -func registerRoutes(rs *lcd.RestServer) { - rpc.RegisterRoutes(rs.CliCtx, rs.Mux) - tx.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc) - authrest.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, auth.StoreKey) - bankrest.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, rs.KeyBase) - distrrest.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, distr.StoreKey) - stakingrest.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, rs.KeyBase) - slashingrest.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, rs.KeyBase) - govrest.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, paramsrest.ProposalRESTHandler(rs.CliCtx, rs.Cdc)) - mintrest.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc) -} - -// Request makes a test LCD test request. It returns a response object and a -// stringified response body. -func Request(t *testing.T, port, method, path string, payload []byte) (*http.Response, string) { - var ( - err error - res *http.Response - ) - url := fmt.Sprintf("http://localhost:%v%v", port, path) - fmt.Printf("REQUEST %s %s\n", method, url) - - req, err := http.NewRequest(method, url, bytes.NewBuffer(payload)) - require.Nil(t, err) - - res, err = http.DefaultClient.Do(req) - require.Nil(t, err) - - output, err := ioutil.ReadAll(res.Body) - res.Body.Close() - require.Nil(t, err) - - return res, string(output) -} - -// ---------------------------------------------------------------------- -// ICS 0 - Tendermint -// ---------------------------------------------------------------------- -// GET /node_info The properties of the connected node -func getNodeInfo(t *testing.T, port string) p2p.DefaultNodeInfo { - res, body := Request(t, port, "GET", "/node_info", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var nodeInfo p2p.DefaultNodeInfo - err := cdc.UnmarshalJSON([]byte(body), &nodeInfo) - require.Nil(t, err, "Couldn't parse node info") - - require.NotEqual(t, p2p.DefaultNodeInfo{}, nodeInfo, "res: %v", res) - return nodeInfo -} - -// GET /syncing Syncing state of node -func getSyncStatus(t *testing.T, port string, syncing bool) { - res, body := Request(t, port, "GET", "/syncing", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - if syncing { - require.Equal(t, "true", body) - return - } - require.Equal(t, "false", body) -} - -// GET /blocks/latest Get the latest block -// GET /blocks/{height} Get a block at a certain height -func getBlock(t *testing.T, port string, height int, expectFail bool) ctypes.ResultBlock { - var url string - if height > 0 { - url = fmt.Sprintf("/blocks/%d", height) - } else { - url = "/blocks/latest" - } - var resultBlock ctypes.ResultBlock - - res, body := Request(t, port, "GET", url, nil) - if expectFail { - require.Equal(t, http.StatusNotFound, res.StatusCode, body) - return resultBlock - } - require.Equal(t, http.StatusOK, res.StatusCode, body) - - err := cdc.UnmarshalJSON([]byte(body), &resultBlock) - require.Nil(t, err, "Couldn't parse block") - - require.NotEqual(t, ctypes.ResultBlock{}, resultBlock) - return resultBlock -} - -// GET /validatorsets/{height} Get a validator set a certain height -// GET /validatorsets/latest Get the latest validator set -func getValidatorSets(t *testing.T, port string, height int, expectFail bool) rpc.ResultValidatorsOutput { - var url string - if height > 0 { - url = fmt.Sprintf("/validatorsets/%d", height) - } else { - url = "/validatorsets/latest" - } - var resultVals rpc.ResultValidatorsOutput - - res, body := Request(t, port, "GET", url, nil) - - if expectFail { - require.Equal(t, http.StatusNotFound, res.StatusCode, body) - return resultVals - } - - require.Equal(t, http.StatusOK, res.StatusCode, body) - - err := cdc.UnmarshalJSON([]byte(body), &resultVals) - require.Nil(t, err, "Couldn't parse validatorset") - - require.NotEqual(t, rpc.ResultValidatorsOutput{}, resultVals) - return resultVals -} - -// GET /txs/{hash} get tx by hash -func getTransaction(t *testing.T, port string, hash string) sdk.TxResponse { - var tx sdk.TxResponse - res, body := getTransactionRequest(t, port, hash) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - err := cdc.UnmarshalJSON([]byte(body), &tx) - require.NoError(t, err) - return tx -} - -func getTransactionRequest(t *testing.T, port, hash string) (*http.Response, string) { - return Request(t, port, "GET", fmt.Sprintf("/txs/%s", hash), nil) -} - -// POST /txs broadcast txs - -// GET /txs search transactions -func getTransactions(t *testing.T, port string, tags ...string) *sdk.SearchTxsResult { - var txs []sdk.TxResponse - result := sdk.NewSearchTxsResult(0, 0, 1, 30, txs) - if len(tags) == 0 { - return &result - } - queryStr := strings.Join(tags, "&") - res, body := Request(t, port, "GET", fmt.Sprintf("/txs?%s", queryStr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - err := cdc.UnmarshalJSON([]byte(body), &result) - require.NoError(t, err) - return &result -} - -// ---------------------------------------------------------------------- -// ICS 1 - Keys -// ---------------------------------------------------------------------- -// GET /keys List of accounts stored locally -func getKeys(t *testing.T, port string) []keys.KeyOutput { - res, body := Request(t, port, "GET", "/keys", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - var m []keys.KeyOutput - err := cdc.UnmarshalJSON([]byte(body), &m) - require.Nil(t, err) - return m -} - -// POST /keys Create a new account locally -func doKeysPost(t *testing.T, port, name, password, mnemonic string, account int, index int) keys.KeyOutput { - pk := clientkeys.NewAddNewKey(name, password, mnemonic, account, index) - req, err := cdc.MarshalJSON(pk) - require.NoError(t, err) - - res, body := Request(t, port, "POST", "/keys", req) - - require.Equal(t, http.StatusOK, res.StatusCode, body) - var resp keys.KeyOutput - err = cdc.UnmarshalJSON([]byte(body), &resp) - require.Nil(t, err, body) - return resp -} - -// GET /keys/seed Create a new seed to create a new account defaultValidFor -func getKeysSeed(t *testing.T, port string) string { - res, body := Request(t, port, "GET", "/keys/seed", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - reg, err := regexp.Compile(`([a-z]+ ){12}`) - require.Nil(t, err) - match := reg.MatchString(body) - require.True(t, match, "Returned seed has wrong format", body) - return body -} - -// POST /keys/{name}/recove Recover a account from a seed -func doRecoverKey(t *testing.T, port, recoverName, recoverPassword, mnemonic string, account uint32, index uint32) { - pk := clientkeys.NewRecoverKey(recoverPassword, mnemonic, int(account), int(index)) - req, err := cdc.MarshalJSON(pk) - require.NoError(t, err) - - res, body := Request(t, port, "POST", fmt.Sprintf("/keys/%s/recover", recoverName), req) - - require.Equal(t, http.StatusOK, res.StatusCode, body) - var resp keys.KeyOutput - err = codec.Cdc.UnmarshalJSON([]byte(body), &resp) - require.Nil(t, err, body) - - addr1Bech32 := resp.Address - _, err = sdk.AccAddressFromBech32(addr1Bech32) - require.NoError(t, err, "Failed to return a correct bech32 address") -} - -// GET /keys/{name} Get a certain locally stored account -func getKey(t *testing.T, port, name string) keys.KeyOutput { - res, body := Request(t, port, "GET", fmt.Sprintf("/keys/%s", name), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - var resp keys.KeyOutput - err := cdc.UnmarshalJSON([]byte(body), &resp) - require.Nil(t, err) - return resp -} - -// PUT /keys/{name} Update the password for this account in the KMS -func updateKey(t *testing.T, port, name, oldPassword, newPassword string, fail bool) { - kr := clientkeys.NewUpdateKeyReq(oldPassword, newPassword) - req, err := cdc.MarshalJSON(kr) - require.NoError(t, err) - keyEndpoint := fmt.Sprintf("/keys/%s", name) - res, body := Request(t, port, "PUT", keyEndpoint, req) - if fail { - require.Equal(t, http.StatusUnauthorized, res.StatusCode, body) - return - } - require.Equal(t, http.StatusOK, res.StatusCode, body) -} - -// DELETE /keys/{name} Remove an account -func deleteKey(t *testing.T, port, name, password string) { - dk := clientkeys.NewDeleteKeyReq(password) - req, err := cdc.MarshalJSON(dk) - require.NoError(t, err) - keyEndpoint := fmt.Sprintf("/keys/%s", name) - res, body := Request(t, port, "DELETE", keyEndpoint, req) - require.Equal(t, http.StatusOK, res.StatusCode, body) -} - -// GET /auth/accounts/{address} Get the account information on blockchain -func getAccount(t *testing.T, port string, addr sdk.AccAddress) auth.Account { - res, body := Request(t, port, "GET", fmt.Sprintf("/auth/accounts/%s", addr.String()), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - var acc auth.Account - err := cdc.UnmarshalJSON([]byte(body), &acc) - require.Nil(t, err) - return acc -} - -// ---------------------------------------------------------------------- -// ICS 20 - Tokens -// ---------------------------------------------------------------------- - -// POST /tx/broadcast Send a signed Tx -func doBroadcast(t *testing.T, port string, tx auth.StdTx) (*http.Response, string) { - txReq := clienttx.BroadcastReq{Tx: tx, Mode: "block"} - - req, err := cdc.MarshalJSON(txReq) - require.Nil(t, err) - - return Request(t, port, "POST", "/txs", req) -} - -// doTransfer performs a balance transfer with auto gas calculation. It also signs -// the tx and broadcasts it. -func doTransfer( - t *testing.T, port, seed, name, memo, pwd string, addr sdk.AccAddress, fees sdk.Coins, -) (sdk.AccAddress, sdk.TxResponse) { - - resp, body, recvAddr := doTransferWithGas( - t, port, seed, name, memo, pwd, addr, "", 1.0, false, true, fees, - ) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - var txResp sdk.TxResponse - err := cdc.UnmarshalJSON([]byte(body), &txResp) - require.NoError(t, err) - - return recvAddr, txResp -} - -// doTransferWithGas performs a balance transfer with a specified gas value. The -// broadcast parameter determines if the tx should only be generated or also -// signed and broadcasted. The sending account's number and sequence are -// determined prior to generating the tx. -func doTransferWithGas( - t *testing.T, port, seed, name, memo, pwd string, addr sdk.AccAddress, - gas string, gasAdjustment float64, simulate, broadcast bool, fees sdk.Coins, -) (resp *http.Response, body string, receiveAddr sdk.AccAddress) { - - // create receive address - kb := crkeys.NewInMemory() - - receiveInfo, _, err := kb.CreateMnemonic( - "receive_address", crkeys.English, client.DefaultKeyPass, crkeys.SigningAlgo("secp256k1"), - ) - require.Nil(t, err) - - receiveAddr = sdk.AccAddress(receiveInfo.GetPubKey().Address()) - acc := getAccount(t, port, addr) - accnum := acc.GetAccountNumber() - sequence := acc.GetSequence() - chainID := viper.GetString(client.FlagChainID) - - from := addr.String() - baseReq := rest.NewBaseReq( - from, memo, chainID, gas, fmt.Sprintf("%f", gasAdjustment), accnum, sequence, fees, nil, simulate, - ) - - sr := bankrest.SendReq{ - Amount: sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 1)}, - BaseReq: baseReq, - } - - req, err := cdc.MarshalJSON(sr) - require.NoError(t, err) - - // generate tx - resp, body = Request(t, port, "POST", fmt.Sprintf("/bank/accounts/%s/transfers", receiveAddr), req) - if !broadcast { - return resp, body, receiveAddr - } - - // sign and broadcast - resp, body = signAndBroadcastGenTx(t, port, name, pwd, body, acc, gasAdjustment, simulate) - return resp, body, receiveAddr -} - -// doTransferWithGasAccAuto is similar to doTransferWithGas except that it -// automatically determines the account's number and sequence when generating the -// tx. -func doTransferWithGasAccAuto( - t *testing.T, port, seed, name, memo, pwd string, addr sdk.AccAddress, - gas string, gasAdjustment float64, simulate, broadcast bool, fees sdk.Coins, -) (resp *http.Response, body string, receiveAddr sdk.AccAddress) { - - // create receive address - kb := crkeys.NewInMemory() - acc := getAccount(t, port, addr) - - receiveInfo, _, err := kb.CreateMnemonic( - "receive_address", crkeys.English, client.DefaultKeyPass, crkeys.SigningAlgo("secp256k1"), - ) - require.Nil(t, err) - - receiveAddr = sdk.AccAddress(receiveInfo.GetPubKey().Address()) - chainID := viper.GetString(client.FlagChainID) - - from := addr.String() - baseReq := rest.NewBaseReq( - from, memo, chainID, gas, fmt.Sprintf("%f", gasAdjustment), 0, 0, fees, nil, simulate, - ) - - sr := bankrest.SendReq{ - Amount: sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 1)}, - BaseReq: baseReq, - } - - req, err := cdc.MarshalJSON(sr) - require.NoError(t, err) - - resp, body = Request(t, port, "POST", fmt.Sprintf("/bank/accounts/%s/transfers", receiveAddr), req) - if !broadcast { - return resp, body, receiveAddr - } - - // sign and broadcast - resp, body = signAndBroadcastGenTx(t, port, name, pwd, body, acc, gasAdjustment, simulate) - return resp, body, receiveAddr -} - -// signAndBroadcastGenTx accepts a successfully generated unsigned tx, signs it, -// and broadcasts it. -func signAndBroadcastGenTx( - t *testing.T, port, name, pwd, genTx string, acc auth.Account, gasAdjustment float64, simulate bool, -) (resp *http.Response, body string) { - - chainID := viper.GetString(client.FlagChainID) - - var tx auth.StdTx - err := cdc.UnmarshalJSON([]byte(genTx), &tx) - require.Nil(t, err) - - txbldr := txbuilder.NewTxBuilder( - utils.GetTxEncoder(cdc), - acc.GetAccountNumber(), - acc.GetSequence(), - tx.Fee.Gas, - gasAdjustment, - simulate, - chainID, - tx.Memo, - tx.Fee.Amount, - nil, - ) - - signedTx, err := txbldr.SignStdTx(name, pwd, tx, false) - require.NoError(t, err) - - return doBroadcast(t, port, signedTx) -} - -// ---------------------------------------------------------------------- -// ICS 21 - Stake -// ---------------------------------------------------------------------- - -// POST /staking/delegators/{delegatorAddr}/delegations Submit delegation -func doDelegate( - t *testing.T, port, name, pwd string, delAddr sdk.AccAddress, - valAddr sdk.ValAddress, amount sdk.Int, fees sdk.Coins, -) sdk.TxResponse { - - acc := getAccount(t, port, delAddr) - accnum := acc.GetAccountNumber() - sequence := acc.GetSequence() - chainID := viper.GetString(client.FlagChainID) - from := acc.GetAddress().String() - - baseReq := rest.NewBaseReq(from, "", chainID, "", "", accnum, sequence, fees, nil, false) - msg := stakingrest.DelegateRequest{ - BaseReq: baseReq, - DelegatorAddress: delAddr, - ValidatorAddress: valAddr, - Amount: sdk.NewCoin(sdk.DefaultBondDenom, amount), - } - - req, err := cdc.MarshalJSON(msg) - require.NoError(t, err) - - resp, body := Request(t, port, "POST", fmt.Sprintf("/staking/delegators/%s/delegations", delAddr.String()), req) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - // sign and broadcast - resp, body = signAndBroadcastGenTx(t, port, name, pwd, body, acc, client.DefaultGasAdjustment, false) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - var txResp sdk.TxResponse - err = cdc.UnmarshalJSON([]byte(body), &txResp) - require.NoError(t, err) - - return txResp -} - -// POST /staking/delegators/{delegatorAddr}/delegations Submit delegation -func doUndelegate( - t *testing.T, port, name, pwd string, delAddr sdk.AccAddress, - valAddr sdk.ValAddress, amount sdk.Int, fees sdk.Coins, -) sdk.TxResponse { - - acc := getAccount(t, port, delAddr) - accnum := acc.GetAccountNumber() - sequence := acc.GetSequence() - chainID := viper.GetString(client.FlagChainID) - from := acc.GetAddress().String() - - baseReq := rest.NewBaseReq(from, "", chainID, "", "", accnum, sequence, fees, nil, false) - msg := stakingrest.UndelegateRequest{ - BaseReq: baseReq, - DelegatorAddress: delAddr, - ValidatorAddress: valAddr, - Amount: sdk.NewCoin(sdk.DefaultBondDenom, amount), - } - - req, err := cdc.MarshalJSON(msg) - require.NoError(t, err) - - resp, body := Request(t, port, "POST", fmt.Sprintf("/staking/delegators/%s/unbonding_delegations", delAddr), req) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - resp, body = signAndBroadcastGenTx(t, port, name, pwd, body, acc, client.DefaultGasAdjustment, false) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - var txResp sdk.TxResponse - err = cdc.UnmarshalJSON([]byte(body), &txResp) - require.NoError(t, err) - - return txResp -} - -// POST /staking/delegators/{delegatorAddr}/delegations Submit delegation -func doBeginRedelegation( - t *testing.T, port, name, pwd string, delAddr sdk.AccAddress, valSrcAddr, - valDstAddr sdk.ValAddress, amount sdk.Int, fees sdk.Coins, -) sdk.TxResponse { - - acc := getAccount(t, port, delAddr) - accnum := acc.GetAccountNumber() - sequence := acc.GetSequence() - chainID := viper.GetString(client.FlagChainID) - from := acc.GetAddress().String() - - baseReq := rest.NewBaseReq(from, "", chainID, "", "", accnum, sequence, fees, nil, false) - msg := stakingrest.RedelegateRequest{ - BaseReq: baseReq, - DelegatorAddress: delAddr, - ValidatorSrcAddress: valSrcAddr, - ValidatorDstAddress: valDstAddr, - Amount: sdk.NewCoin(sdk.DefaultBondDenom, amount), - } - - req, err := cdc.MarshalJSON(msg) - require.NoError(t, err) - - resp, body := Request(t, port, "POST", fmt.Sprintf("/staking/delegators/%s/redelegations", delAddr), req) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - resp, body = signAndBroadcastGenTx(t, port, name, pwd, body, acc, client.DefaultGasAdjustment, false) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - var txResp sdk.TxResponse - err = cdc.UnmarshalJSON([]byte(body), &txResp) - require.NoError(t, err) - - return txResp -} - -// GET /staking/delegators/{delegatorAddr}/delegations Get all delegations from a delegator -func getDelegatorDelegations(t *testing.T, port string, delegatorAddr sdk.AccAddress) staking.DelegationResponses { - res, body := Request(t, port, "GET", fmt.Sprintf("/staking/delegators/%s/delegations", delegatorAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var dels staking.DelegationResponses - - err := cdc.UnmarshalJSON([]byte(body), &dels) - require.Nil(t, err) - - return dels -} - -// GET /staking/delegators/{delegatorAddr}/unbonding_delegations Get all unbonding delegations from a delegator -func getDelegatorUnbondingDelegations(t *testing.T, port string, delegatorAddr sdk.AccAddress) []staking.UnbondingDelegation { - res, body := Request(t, port, "GET", fmt.Sprintf("/staking/delegators/%s/unbonding_delegations", delegatorAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var ubds []staking.UnbondingDelegation - - err := cdc.UnmarshalJSON([]byte(body), &ubds) - require.Nil(t, err) - - return ubds -} - -// GET /staking/redelegations?delegator=0xdeadbeef&validator_from=0xdeadbeef&validator_to=0xdeadbeef& Get redelegations filters by params passed in -func getRedelegations(t *testing.T, port string, delegatorAddr sdk.AccAddress, srcValidatorAddr sdk.ValAddress, dstValidatorAddr sdk.ValAddress) staking.RedelegationResponses { - var res *http.Response - var body string - endpoint := "/staking/redelegations?" - if !delegatorAddr.Empty() { - endpoint += fmt.Sprintf("delegator=%s&", delegatorAddr) - } - if !srcValidatorAddr.Empty() { - endpoint += fmt.Sprintf("validator_from=%s&", srcValidatorAddr) - } - if !dstValidatorAddr.Empty() { - endpoint += fmt.Sprintf("validator_to=%s&", dstValidatorAddr) - } - - res, body = Request(t, port, "GET", endpoint, nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var redels staking.RedelegationResponses - err := cdc.UnmarshalJSON([]byte(body), &redels) - require.Nil(t, err) - - return redels -} - -// GET /staking/delegators/{delegatorAddr}/validators Query all validators that a delegator is bonded to -func getDelegatorValidators(t *testing.T, port string, delegatorAddr sdk.AccAddress) []staking.Validator { - res, body := Request(t, port, "GET", fmt.Sprintf("/staking/delegators/%s/validators", delegatorAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var bondedValidators []staking.Validator - - err := cdc.UnmarshalJSON([]byte(body), &bondedValidators) - require.Nil(t, err) - - return bondedValidators -} - -// GET /staking/delegators/{delegatorAddr}/validators/{validatorAddr} Query a validator that a delegator is bonded to -func getDelegatorValidator(t *testing.T, port string, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) staking.Validator { - res, body := Request(t, port, "GET", fmt.Sprintf("/staking/delegators/%s/validators/%s", delegatorAddr, validatorAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var bondedValidator staking.Validator - err := cdc.UnmarshalJSON([]byte(body), &bondedValidator) - require.Nil(t, err) - - return bondedValidator -} - -// GET /staking/delegators/{delegatorAddr}/txs Get all staking txs (i.e msgs) from a delegator -func getBondingTxs(t *testing.T, port string, delegatorAddr sdk.AccAddress, query string) []sdk.TxResponse { - var res *http.Response - var body string - - if len(query) > 0 { - res, body = Request(t, port, "GET", fmt.Sprintf("/staking/delegators/%s/txs?type=%s", delegatorAddr, query), nil) - } else { - res, body = Request(t, port, "GET", fmt.Sprintf("/staking/delegators/%s/txs", delegatorAddr), nil) - } - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var txs []sdk.TxResponse - - err := cdc.UnmarshalJSON([]byte(body), &txs) - require.Nil(t, err) - - return txs -} - -// GET /staking/delegators/{delegatorAddr}/delegations/{validatorAddr} Query the current delegation between a delegator and a validator -func getDelegation(t *testing.T, port string, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) staking.DelegationResp { - res, body := Request(t, port, "GET", fmt.Sprintf("/staking/delegators/%s/delegations/%s", delegatorAddr, validatorAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var bond staking.DelegationResp - err := cdc.UnmarshalJSON([]byte(body), &bond) - require.Nil(t, err) - - return bond -} - -// GET /staking/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr} Query all unbonding delegations between a delegator and a validator -func getUnbondingDelegation(t *testing.T, port string, delegatorAddr sdk.AccAddress, - validatorAddr sdk.ValAddress) staking.UnbondingDelegation { - - res, body := Request(t, port, "GET", - fmt.Sprintf("/staking/delegators/%s/unbonding_delegations/%s", - delegatorAddr, validatorAddr), nil) - - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var unbond staking.UnbondingDelegation - err := cdc.UnmarshalJSON([]byte(body), &unbond) - require.Nil(t, err) - - return unbond -} - -// GET /staking/validators Get all validator candidates -func getValidators(t *testing.T, port string) []staking.Validator { - res, body := Request(t, port, "GET", "/staking/validators", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var validators []staking.Validator - err := cdc.UnmarshalJSON([]byte(body), &validators) - require.Nil(t, err) - - return validators -} - -// GET /staking/validators/{validatorAddr} Query the information from a single validator -func getValidator(t *testing.T, port string, validatorAddr sdk.ValAddress) staking.Validator { - res, body := Request(t, port, "GET", fmt.Sprintf("/staking/validators/%s", validatorAddr.String()), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var validator staking.Validator - err := cdc.UnmarshalJSON([]byte(body), &validator) - require.Nil(t, err) - - return validator -} - -// GET /staking/validators/{validatorAddr}/delegations Get all delegations from a validator -func getValidatorDelegations(t *testing.T, port string, validatorAddr sdk.ValAddress) []staking.Delegation { - res, body := Request(t, port, "GET", fmt.Sprintf("/staking/validators/%s/delegations", validatorAddr.String()), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var delegations []staking.Delegation - err := cdc.UnmarshalJSON([]byte(body), &delegations) - require.Nil(t, err) - - return delegations -} - -// GET /staking/validators/{validatorAddr}/unbonding_delegations Get all unbonding delegations from a validator -func getValidatorUnbondingDelegations(t *testing.T, port string, validatorAddr sdk.ValAddress) []staking.UnbondingDelegation { - res, body := Request(t, port, "GET", fmt.Sprintf("/staking/validators/%s/unbonding_delegations", validatorAddr.String()), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var ubds []staking.UnbondingDelegation - err := cdc.UnmarshalJSON([]byte(body), &ubds) - require.Nil(t, err) - - return ubds -} - -// GET /staking/pool Get the current state of the staking pool -func getStakingPool(t *testing.T, port string) staking.Pool { - res, body := Request(t, port, "GET", "/staking/pool", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.NotNil(t, body) - var pool staking.Pool - err := cdc.UnmarshalJSON([]byte(body), &pool) - require.Nil(t, err) - return pool -} - -// GET /staking/parameters Get the current staking parameter values -func getStakingParams(t *testing.T, port string) staking.Params { - res, body := Request(t, port, "GET", "/staking/parameters", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var params staking.Params - err := cdc.UnmarshalJSON([]byte(body), ¶ms) - require.Nil(t, err) - return params -} - -// ---------------------------------------------------------------------- -// ICS 22 - Gov -// ---------------------------------------------------------------------- -// POST /gov/proposals Submit a proposal -func doSubmitProposal( - t *testing.T, port, seed, name, pwd string, proposerAddr sdk.AccAddress, - amount sdk.Int, fees sdk.Coins, -) sdk.TxResponse { - - acc := getAccount(t, port, proposerAddr) - accnum := acc.GetAccountNumber() - sequence := acc.GetSequence() - chainID := viper.GetString(client.FlagChainID) - from := acc.GetAddress().String() - - baseReq := rest.NewBaseReq(from, "", chainID, "", "", accnum, sequence, fees, nil, false) - pr := govrest.PostProposalReq{ - Title: "Test", - Description: "test", - ProposalType: "Text", - Proposer: proposerAddr, - InitialDeposit: sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, amount)}, - BaseReq: baseReq, - } - - req, err := cdc.MarshalJSON(pr) - require.NoError(t, err) - - // submitproposal - resp, body := Request(t, port, "POST", "/gov/proposals", req) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - resp, body = signAndBroadcastGenTx(t, port, name, pwd, body, acc, client.DefaultGasAdjustment, false) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - var txResp sdk.TxResponse - err = cdc.UnmarshalJSON([]byte(body), &txResp) - require.NoError(t, err) - - return txResp -} - -func doSubmitParamChangeProposal( - t *testing.T, port, seed, name, pwd string, proposerAddr sdk.AccAddress, - amount sdk.Int, fees sdk.Coins, -) sdk.TxResponse { - - acc := getAccount(t, port, proposerAddr) - accnum := acc.GetAccountNumber() - sequence := acc.GetSequence() - chainID := viper.GetString(client.FlagChainID) - from := acc.GetAddress().String() - - baseReq := rest.NewBaseReq(from, "", chainID, "", "", accnum, sequence, fees, nil, false) - pr := paramscutils.ParamChangeProposalReq{ - BaseReq: baseReq, - Title: "Test", - Description: "test", - Proposer: proposerAddr, - Deposit: sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, amount)}, - Changes: paramscutils.ParamChangesJSON{ - paramscutils.NewParamChangeJSON("staking", "MaxValidators", "", []byte(`105`)), - }, - } - - req, err := cdc.MarshalJSON(pr) - require.NoError(t, err) - - resp, body := Request(t, port, "POST", "/gov/proposals/param_change", req) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - resp, body = signAndBroadcastGenTx(t, port, name, pwd, body, acc, client.DefaultGasAdjustment, false) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - var txResp sdk.TxResponse - err = cdc.UnmarshalJSON([]byte(body), &txResp) - require.NoError(t, err) - - return txResp -} - -// GET /gov/proposals Query proposals -func getProposalsAll(t *testing.T, port string) []gov.Proposal { - res, body := Request(t, port, "GET", "/gov/proposals", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var proposals []gov.Proposal - err := cdc.UnmarshalJSON([]byte(body), &proposals) - require.Nil(t, err) - return proposals -} - -// GET /gov/proposals?depositor=%s Query proposals -func getProposalsFilterDepositor(t *testing.T, port string, depositorAddr sdk.AccAddress) []gov.Proposal { - res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals?depositor=%s", depositorAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var proposals []gov.Proposal - err := cdc.UnmarshalJSON([]byte(body), &proposals) - require.Nil(t, err) - return proposals -} - -// GET /gov/proposals?voter=%s Query proposals -func getProposalsFilterVoter(t *testing.T, port string, voterAddr sdk.AccAddress) []gov.Proposal { - res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals?voter=%s", voterAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var proposals []gov.Proposal - err := cdc.UnmarshalJSON([]byte(body), &proposals) - require.Nil(t, err) - return proposals -} - -// GET /gov/proposals?depositor=%s&voter=%s Query proposals -func getProposalsFilterVoterDepositor(t *testing.T, port string, voterAddr, depositorAddr sdk.AccAddress) []gov.Proposal { - res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals?depositor=%s&voter=%s", depositorAddr, voterAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var proposals []gov.Proposal - err := cdc.UnmarshalJSON([]byte(body), &proposals) - require.Nil(t, err) - return proposals -} - -// GET /gov/proposals?status=%s Query proposals -func getProposalsFilterStatus(t *testing.T, port string, status gov.ProposalStatus) []gov.Proposal { - res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals?status=%s", status), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var proposals []gov.Proposal - err := cdc.UnmarshalJSON([]byte(body), &proposals) - require.Nil(t, err) - return proposals -} - -// POST /gov/proposals/{proposalId}/deposits Deposit tokens to a proposal -func doDeposit( - t *testing.T, port, seed, name, pwd string, proposerAddr sdk.AccAddress, - proposalID uint64, amount sdk.Int, fees sdk.Coins, -) sdk.TxResponse { - - acc := getAccount(t, port, proposerAddr) - accnum := acc.GetAccountNumber() - sequence := acc.GetSequence() - chainID := viper.GetString(client.FlagChainID) - from := acc.GetAddress().String() - - baseReq := rest.NewBaseReq(from, "", chainID, "", "", accnum, sequence, fees, nil, false) - dr := govrest.DepositReq{ - Depositor: proposerAddr, - Amount: sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, amount)}, - BaseReq: baseReq, - } - - req, err := cdc.MarshalJSON(dr) - require.NoError(t, err) - - resp, body := Request(t, port, "POST", fmt.Sprintf("/gov/proposals/%d/deposits", proposalID), req) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - resp, body = signAndBroadcastGenTx(t, port, name, pwd, body, acc, client.DefaultGasAdjustment, false) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - var txResp sdk.TxResponse - err = cdc.UnmarshalJSON([]byte(body), &txResp) - require.NoError(t, err) - - return txResp -} - -// GET /gov/proposals/{proposalId}/deposits Query deposits -func getDeposits(t *testing.T, port string, proposalID uint64) []gov.Deposit { - res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals/%d/deposits", proposalID), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - var deposits []gov.Deposit - err := cdc.UnmarshalJSON([]byte(body), &deposits) - require.Nil(t, err) - return deposits -} - -// GET /gov/proposals/{proposalId}/tally Get a proposal's tally result at the current time -func getTally(t *testing.T, port string, proposalID uint64) gov.TallyResult { - res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals/%d/tally", proposalID), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - var tally gov.TallyResult - err := cdc.UnmarshalJSON([]byte(body), &tally) - require.Nil(t, err) - return tally -} - -// POST /gov/proposals/{proposalId}/votes Vote a proposal -func doVote( - t *testing.T, port, seed, name, pwd string, proposerAddr sdk.AccAddress, - proposalID uint64, option string, fees sdk.Coins, -) sdk.TxResponse { - - // get the account to get the sequence - acc := getAccount(t, port, proposerAddr) - accnum := acc.GetAccountNumber() - sequence := acc.GetSequence() - chainID := viper.GetString(client.FlagChainID) - from := acc.GetAddress().String() - - baseReq := rest.NewBaseReq(from, "", chainID, "", "", accnum, sequence, fees, nil, false) - vr := govrest.VoteReq{ - Voter: proposerAddr, - Option: option, - BaseReq: baseReq, - } - - req, err := cdc.MarshalJSON(vr) - require.NoError(t, err) - - resp, body := Request(t, port, "POST", fmt.Sprintf("/gov/proposals/%d/votes", proposalID), req) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - resp, body = signAndBroadcastGenTx(t, port, name, pwd, body, acc, client.DefaultGasAdjustment, false) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - var txResp sdk.TxResponse - err = cdc.UnmarshalJSON([]byte(body), &txResp) - require.NoError(t, err) - - return txResp -} - -// GET /gov/proposals/{proposalId}/votes Query voters -func getVotes(t *testing.T, port string, proposalID uint64) []gov.Vote { - res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals/%d/votes", proposalID), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - var votes []gov.Vote - err := cdc.UnmarshalJSON([]byte(body), &votes) - require.Nil(t, err) - return votes -} - -// GET /gov/proposals/{proposalId} Query a proposal -func getProposal(t *testing.T, port string, proposalID uint64) gov.Proposal { - res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals/%d", proposalID), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - var proposal gov.Proposal - err := cdc.UnmarshalJSON([]byte(body), &proposal) - require.Nil(t, err) - return proposal -} - -// GET /gov/proposals/{proposalId}/deposits/{depositor} Query deposit -func getDeposit(t *testing.T, port string, proposalID uint64, depositorAddr sdk.AccAddress) gov.Deposit { - res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals/%d/deposits/%s", proposalID, depositorAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - var deposit gov.Deposit - err := cdc.UnmarshalJSON([]byte(body), &deposit) - require.Nil(t, err) - return deposit -} - -// GET /gov/proposals/{proposalId}/votes/{voter} Query vote -func getVote(t *testing.T, port string, proposalID uint64, voterAddr sdk.AccAddress) gov.Vote { - res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals/%d/votes/%s", proposalID, voterAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - var vote gov.Vote - err := cdc.UnmarshalJSON([]byte(body), &vote) - require.Nil(t, err) - return vote -} - -// GET /gov/proposals/{proposalId}/proposer -func getProposer(t *testing.T, port string, proposalID uint64) gcutils.Proposer { - res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals/%d/proposer", proposalID), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var proposer gcutils.Proposer - err := cdc.UnmarshalJSON([]byte(body), &proposer) - - require.Nil(t, err) - return proposer -} - -// GET /gov/parameters/deposit Query governance deposit parameters -func getDepositParam(t *testing.T, port string) gov.DepositParams { - res, body := Request(t, port, "GET", "/gov/parameters/deposit", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var depositParams gov.DepositParams - err := cdc.UnmarshalJSON([]byte(body), &depositParams) - require.Nil(t, err) - return depositParams -} - -// GET /gov/parameters/tallying Query governance tally parameters -func getTallyingParam(t *testing.T, port string) gov.TallyParams { - res, body := Request(t, port, "GET", "/gov/parameters/tallying", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var tallyParams gov.TallyParams - err := cdc.UnmarshalJSON([]byte(body), &tallyParams) - require.Nil(t, err) - return tallyParams -} - -// GET /gov/parameters/voting Query governance voting parameters -func getVotingParam(t *testing.T, port string) gov.VotingParams { - res, body := Request(t, port, "GET", "/gov/parameters/voting", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var votingParams gov.VotingParams - err := cdc.UnmarshalJSON([]byte(body), &votingParams) - require.Nil(t, err) - return votingParams -} - -// ---------------------------------------------------------------------- -// ICS 23 - Slashing -// ---------------------------------------------------------------------- -// GET /slashing/validators/{validatorPubKey}/signing_info Get sign info of given validator -func getSigningInfo(t *testing.T, port string, validatorPubKey string) slashing.ValidatorSigningInfo { - res, body := Request(t, port, "GET", fmt.Sprintf("/slashing/validators/%s/signing_info", validatorPubKey), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var signingInfo slashing.ValidatorSigningInfo - err := cdc.UnmarshalJSON([]byte(body), &signingInfo) - require.Nil(t, err) - - return signingInfo -} - -// ---------------------------------------------------------------------- -// ICS 23 - SlashingList -// ---------------------------------------------------------------------- -// GET /slashing/signing_infos Get sign info of all validators with pagination -func getSigningInfoList(t *testing.T, port string) []slashing.ValidatorSigningInfo { - res, body := Request(t, port, "GET", "/slashing/signing_infos?page=1&limit=1", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var signingInfo []slashing.ValidatorSigningInfo - err := cdc.UnmarshalJSON([]byte(body), &signingInfo) - require.Nil(t, err) - - return signingInfo -} - -// TODO: Test this functionality, it is not currently in any of the tests -// POST /slashing/validators/{validatorAddr}/unjail Unjail a jailed validator -func doUnjail( - t *testing.T, port, seed, name, pwd string, valAddr sdk.ValAddress, fees sdk.Coins, -) sdk.TxResponse { - - acc := getAccount(t, port, sdk.AccAddress(valAddr.Bytes())) - from := acc.GetAddress().String() - chainID := viper.GetString(client.FlagChainID) - - baseReq := rest.NewBaseReq(from, "", chainID, "", "", 1, 1, fees, nil, false) - ur := slashingrest.UnjailReq{ - BaseReq: baseReq, - } - req, err := cdc.MarshalJSON(ur) - require.NoError(t, err) - - resp, body := Request(t, port, "POST", fmt.Sprintf("/slashing/validators/%s/unjail", valAddr.String()), req) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - resp, body = signAndBroadcastGenTx(t, port, name, pwd, body, acc, client.DefaultGasAdjustment, false) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - var txResp sdk.TxResponse - err = cdc.UnmarshalJSON([]byte(body), &txResp) - require.NoError(t, err) - - return txResp -} - -type unjailReq struct { - BaseReq rest.BaseReq `json:"base_req"` -} - -// ICS24 - fee distribution - -// POST /distribution/delegators/{delgatorAddr}/rewards Withdraw delegator rewards -func doWithdrawDelegatorAllRewards( - t *testing.T, port, seed, name, pwd string, delegatorAddr sdk.AccAddress, fees sdk.Coins, -) sdk.TxResponse { - // get the account to get the sequence - acc := getAccount(t, port, delegatorAddr) - accnum := acc.GetAccountNumber() - sequence := acc.GetSequence() - chainID := viper.GetString(client.FlagChainID) - from := acc.GetAddress().String() - - baseReq := rest.NewBaseReq(from, "", chainID, "", "", accnum, sequence, fees, nil, false) - wr := struct { - BaseReq rest.BaseReq `json:"base_req"` - }{BaseReq: baseReq} - - req := cdc.MustMarshalJSON(wr) - - resp, body := Request(t, port, "POST", fmt.Sprintf("/distribution/delegators/%s/rewards", delegatorAddr), req) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - resp, body = signAndBroadcastGenTx(t, port, name, pwd, body, acc, client.DefaultGasAdjustment, false) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - var txResp sdk.TxResponse - err := cdc.UnmarshalJSON([]byte(body), &txResp) - require.NoError(t, err) - - return txResp -} - -func mustParseDecCoins(dcstring string) sdk.DecCoins { - dcoins, err := sdk.ParseDecCoins(dcstring) - if err != nil { - panic(err) - } - return dcoins -} diff --git a/cmd/gaia/lcd_test/lcd_test.go b/cmd/gaia/lcd_test/lcd_test.go deleted file mode 100644 index 8a0ff0bfa8..0000000000 --- a/cmd/gaia/lcd_test/lcd_test.go +++ /dev/null @@ -1,1104 +0,0 @@ -package lcd_test - -import ( - "encoding/base64" - "encoding/hex" - "encoding/json" - "fmt" - "net/http" - "os" - "regexp" - "strings" - "testing" - "time" - - "github.com/cosmos/cosmos-sdk/x/mint" - - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/crypto/keys/mintkey" - "github.com/cosmos/cosmos-sdk/tests" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/version" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/bank" - dclcommon "github.com/cosmos/cosmos-sdk/x/distribution/client/common" - distrrest "github.com/cosmos/cosmos-sdk/x/distribution/client/rest" - disttypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - "github.com/cosmos/cosmos-sdk/x/gov" - "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/staking" -) - -const ( - name1 = "test1" - memo = "LCD test tx" - pw = client.DefaultKeyPass -) - -var fees = sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 5)} - -func init() { - mintkey.BcryptSecurityParameter = 1 - version.Version = os.Getenv("VERSION") -} - -func TestVersion(t *testing.T) { - // skip the test if the VERSION environment variable has not been set - if version.Version == "" { - t.SkipNow() - } - - cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{}, true) - defer cleanup() - - // node info - res, body := Request(t, port, "GET", "/version", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - reg, err := regexp.Compile(`\d+\.\d+\.\d+.*`) - require.Nil(t, err) - match := reg.MatchString(body) - require.True(t, match, body, body) - - // node info - res, body = Request(t, port, "GET", "/node_version", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - reg, err = regexp.Compile(`\d+\.\d+\.\d+.*`) - require.Nil(t, err) - match = reg.MatchString(body) - require.True(t, match, body) -} - -func TestNodeStatus(t *testing.T) { - cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{}, true) - defer cleanup() - getNodeInfo(t, port) - getSyncStatus(t, port, false) -} - -func TestBlock(t *testing.T) { - cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{}, true) - defer cleanup() - getBlock(t, port, -1, false) - getBlock(t, port, 2, false) - getBlock(t, port, 100000000, true) -} - -func TestValidators(t *testing.T) { - cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{}, true) - defer cleanup() - resultVals := getValidatorSets(t, port, -1, false) - require.Contains(t, resultVals.Validators[0].Address.String(), "cosmosvalcons") - require.Contains(t, resultVals.Validators[0].PubKey, "cosmosvalconspub") - getValidatorSets(t, port, 2, false) - getValidatorSets(t, port, 10000000, true) -} - -func TestCoinSend(t *testing.T) { - kb, err := keys.NewKeyBaseFromDir(InitClientHome(t, "")) - require.NoError(t, err) - addr, seed := CreateAddr(t, name1, pw, kb) - cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}, true) - defer cleanup() - - bz, err := hex.DecodeString("8FA6AB57AD6870F6B5B2E57735F38F2F30E73CB6") - require.NoError(t, err) - someFakeAddr := sdk.AccAddress(bz) - - // query empty - res, body := Request(t, port, "GET", fmt.Sprintf("/auth/accounts/%s", someFakeAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - acc := getAccount(t, port, addr) - initialBalance := acc.GetCoins() - - // create TX - receiveAddr, resultTx := doTransfer(t, port, seed, name1, memo, pw, addr, fees) - tests.WaitForHeight(resultTx.Height+1, port) - - // check if tx was committed - require.Equal(t, uint32(0), resultTx.Code) - - // query sender - acc = getAccount(t, port, addr) - coins := acc.GetCoins() - expectedBalance := initialBalance[0].Sub(fees[0]) - - require.Equal(t, sdk.DefaultBondDenom, coins[0].Denom) - require.Equal(t, expectedBalance.Amount.SubRaw(1), coins[0].Amount) - expectedBalance = coins[0] - - // query receiver - acc2 := getAccount(t, port, receiveAddr) - coins2 := acc2.GetCoins() - require.Equal(t, sdk.DefaultBondDenom, coins2[0].Denom) - require.Equal(t, int64(1), coins2[0].Amount.Int64()) - - // test failure with too little gas - res, body, _ = doTransferWithGas(t, port, seed, name1, memo, pw, addr, "100", 0, false, true, fees) - require.Equal(t, http.StatusInternalServerError, res.StatusCode, body) - require.Nil(t, err) - - // test failure with negative gas - res, body, _ = doTransferWithGas(t, port, seed, name1, memo, pw, addr, "-200", 0, false, false, fees) - require.Equal(t, http.StatusBadRequest, res.StatusCode, body) - - // test failure with negative adjustment - res, body, _ = doTransferWithGas(t, port, seed, name1, memo, pw, addr, "10000", -0.1, true, false, fees) - require.Equal(t, http.StatusBadRequest, res.StatusCode, body) - - // test failure with 0 gas - res, body, _ = doTransferWithGas(t, port, seed, name1, memo, pw, addr, "0", 0, false, true, fees) - require.Equal(t, http.StatusInternalServerError, res.StatusCode, body) - - // test failure with wrong adjustment - res, body, _ = doTransferWithGas(t, port, seed, name1, memo, pw, addr, client.GasFlagAuto, 0.1, false, true, fees) - - require.Equal(t, http.StatusInternalServerError, res.StatusCode, body) - - // run simulation and test success with estimated gas - res, body, _ = doTransferWithGas( - t, port, seed, name1, memo, pw, addr, "10000", 1.0, true, false, fees, - ) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var gasEstResp rest.GasEstimateResponse - require.Nil(t, cdc.UnmarshalJSON([]byte(body), &gasEstResp)) - require.NotZero(t, gasEstResp.GasEstimate) - - acc = getAccount(t, port, addr) - require.Equal(t, expectedBalance.Amount, acc.GetCoins().AmountOf(sdk.DefaultBondDenom)) - - // run successful tx - gas := fmt.Sprintf("%d", gasEstResp.GasEstimate) - res, body, _ = doTransferWithGas(t, port, seed, name1, memo, pw, addr, gas, 1.0, false, true, fees) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - err = cdc.UnmarshalJSON([]byte(body), &resultTx) - require.Nil(t, err) - - tests.WaitForHeight(resultTx.Height+1, port) - require.Equal(t, uint32(0), resultTx.Code) - - acc = getAccount(t, port, addr) - expectedBalance = expectedBalance.Sub(fees[0]) - require.Equal(t, expectedBalance.Amount.SubRaw(1), acc.GetCoins().AmountOf(sdk.DefaultBondDenom)) -} - -func TestCoinSendAccAuto(t *testing.T) { - kb, err := keys.NewKeyBaseFromDir(InitClientHome(t, "")) - require.NoError(t, err) - addr, seed := CreateAddr(t, name1, pw, kb) - cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}, true) - defer cleanup() - - acc := getAccount(t, port, addr) - initialBalance := acc.GetCoins() - - // send a transfer tx without specifying account number and sequence - res, body, _ := doTransferWithGasAccAuto( - t, port, seed, name1, memo, pw, addr, "200000", 1.0, false, true, fees, - ) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - // query sender - acc = getAccount(t, port, addr) - coins := acc.GetCoins() - expectedBalance := initialBalance[0].Sub(fees[0]) - - require.Equal(t, sdk.DefaultBondDenom, coins[0].Denom) - require.Equal(t, expectedBalance.Amount.SubRaw(1), coins[0].Amount) -} - -func TestCoinMultiSendGenerateOnly(t *testing.T) { - kb, err := keys.NewKeyBaseFromDir(InitClientHome(t, "")) - require.NoError(t, err) - addr, seed := CreateAddr(t, name1, pw, kb) - cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}, true) - defer cleanup() - - // generate only - res, body, _ := doTransferWithGas(t, port, seed, "", memo, "", addr, "200000", 1, false, false, fees) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var stdTx auth.StdTx - require.Nil(t, cdc.UnmarshalJSON([]byte(body), &stdTx)) - require.Equal(t, len(stdTx.Msgs), 1) - require.Equal(t, stdTx.GetMsgs()[0].Route(), bank.RouterKey) - require.Equal(t, stdTx.GetMsgs()[0].GetSigners(), []sdk.AccAddress{addr}) - require.Equal(t, 0, len(stdTx.Signatures)) - require.Equal(t, memo, stdTx.Memo) - require.NotZero(t, stdTx.Fee.Gas) - require.IsType(t, stdTx.GetMsgs()[0], bank.MsgSend{}) - require.Equal(t, addr, stdTx.GetMsgs()[0].(bank.MsgSend).FromAddress) -} - -func TestCoinSendGenerateSignAndBroadcast(t *testing.T) { - kb, err := keys.NewKeyBaseFromDir(InitClientHome(t, "")) - require.NoError(t, err) - addr, seed := CreateAddr(t, name1, pw, kb) - cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}, true) - - defer cleanup() - acc := getAccount(t, port, addr) - - // simulate tx - res, body, _ := doTransferWithGas( - t, port, seed, name1, memo, "", addr, client.GasFlagAuto, 1.0, true, false, fees, - ) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var gasEstResp rest.GasEstimateResponse - require.Nil(t, cdc.UnmarshalJSON([]byte(body), &gasEstResp)) - require.NotZero(t, gasEstResp.GasEstimate) - - // generate tx - gas := fmt.Sprintf("%d", gasEstResp.GasEstimate) - res, body, _ = doTransferWithGas(t, port, seed, name1, memo, "", addr, gas, 1, false, false, fees) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var tx auth.StdTx - require.Nil(t, cdc.UnmarshalJSON([]byte(body), &tx)) - require.Equal(t, len(tx.Msgs), 1) - require.Equal(t, tx.Msgs[0].Route(), bank.RouterKey) - require.Equal(t, tx.Msgs[0].GetSigners(), []sdk.AccAddress{addr}) - require.Equal(t, 0, len(tx.Signatures)) - require.Equal(t, memo, tx.Memo) - require.NotZero(t, tx.Fee.Gas) - - gasEstimate := int64(tx.Fee.Gas) - _, body = signAndBroadcastGenTx(t, port, name1, pw, body, acc, 1.0, false) - - // check if tx was committed - var txResp sdk.TxResponse - require.Nil(t, cdc.UnmarshalJSON([]byte(body), &txResp)) - require.Equal(t, uint32(0), txResp.Code) - require.Equal(t, gasEstimate, txResp.GasWanted) -} - -func TestEncodeTx(t *testing.T) { - kb, err := keys.NewKeyBaseFromDir(InitClientHome(t, "")) - require.NoError(t, err) - addr, seed := CreateAddr(t, name1, pw, kb) - cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}, true) - defer cleanup() - - res, body, _ := doTransferWithGas(t, port, seed, name1, memo, "", addr, "2", 1, false, false, fees) - var tx auth.StdTx - require.Nil(t, cdc.UnmarshalJSON([]byte(body), &tx)) - - encodedJSON, _ := cdc.MarshalJSON(tx) - res, body = Request(t, port, "POST", "/txs/encode", encodedJSON) - - // Make sure it came back ok, and that we can decode it back to the transaction - // 200 response. - require.Equal(t, http.StatusOK, res.StatusCode, body) - encodeResp := struct { - Tx string `json:"tx"` - }{} - - require.Nil(t, cdc.UnmarshalJSON([]byte(body), &encodeResp)) - - // verify that the base64 decodes - decodedBytes, err := base64.StdEncoding.DecodeString(encodeResp.Tx) - require.Nil(t, err) - - // check that the transaction decodes as expected - var decodedTx auth.StdTx - require.Nil(t, cdc.UnmarshalBinaryLengthPrefixed(decodedBytes, &decodedTx)) - require.Equal(t, memo, decodedTx.Memo) -} - -func TestTxs(t *testing.T) { - kb, err := keys.NewKeyBaseFromDir(InitClientHome(t, "")) - require.NoError(t, err) - addr, seed := CreateAddr(t, name1, pw, kb) - cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}, true) - defer cleanup() - - var emptyTxs []sdk.TxResponse - txResult := getTransactions(t, port) - require.Equal(t, emptyTxs, txResult.Txs) - - // query empty - txResult = getTransactions(t, port, fmt.Sprintf("sender=%s", addr.String())) - require.Equal(t, emptyTxs, txResult.Txs) - - // also tests url decoding - txResult = getTransactions(t, port, fmt.Sprintf("sender=%s", addr.String())) - require.Equal(t, emptyTxs, txResult.Txs) - - txResult = getTransactions(t, port, fmt.Sprintf("action=submit%%20proposal&sender=%s", addr.String())) - require.Equal(t, emptyTxs, txResult.Txs) - - // create tx - receiveAddr, resultTx := doTransfer(t, port, seed, name1, memo, pw, addr, fees) - tests.WaitForHeight(resultTx.Height+1, port) - - // check if tx is queryable - tx := getTransaction(t, port, resultTx.TxHash) - require.Equal(t, resultTx.TxHash, tx.TxHash) - - // query sender - txResult = getTransactions(t, port, fmt.Sprintf("sender=%s", addr.String())) - require.Len(t, txResult.Txs, 1) - require.Equal(t, resultTx.Height, txResult.Txs[0].Height) - - // query recipient - txResult = getTransactions(t, port, fmt.Sprintf("recipient=%s", receiveAddr.String())) - require.Len(t, txResult.Txs, 1) - require.Equal(t, resultTx.Height, txResult.Txs[0].Height) - - // query transaction that doesn't exist - validTxHash := "9ADBECAAD8DACBEC3F4F535704E7CF715C765BDCEDBEF086AFEAD31BA664FB0B" - res, body := getTransactionRequest(t, port, validTxHash) - require.True(t, strings.Contains(body, validTxHash)) - require.Equal(t, http.StatusNotFound, res.StatusCode) - - // bad query string - res, body = getTransactionRequest(t, port, "badtxhash") - require.True(t, strings.Contains(body, "encoding/hex")) - require.Equal(t, http.StatusInternalServerError, res.StatusCode) -} - -func TestPoolParamsQuery(t *testing.T) { - kb, err := keys.NewKeyBaseFromDir(InitClientHome(t, "")) - require.NoError(t, err) - addr, _ := CreateAddr(t, name1, pw, kb) - cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}, true) - defer cleanup() - - defaultParams := staking.DefaultParams() - - params := getStakingParams(t, port) - require.True(t, defaultParams.Equal(params)) - - pool := getStakingPool(t, port) - - initialPool := staking.InitialPool() - tokens := sdk.TokensFromTendermintPower(100) - freeTokens := sdk.TokensFromTendermintPower(50) - initialPool.NotBondedTokens = initialPool.NotBondedTokens.Add(tokens) - initialPool.BondedTokens = initialPool.BondedTokens.Add(tokens) // Delegate tx on GaiaAppGenState - initialPool.NotBondedTokens = initialPool.NotBondedTokens.Add(freeTokens) - - require.Equal(t, initialPool.BondedTokens, pool.BondedTokens) - - //TODO include this test once REST for distribution is online, need to include distribution tokens from inflation - // for this equality to make sense - //require.Equal(t, initialPool.NotBondedTokens, pool.NotBondedTokens) -} - -func TestValidatorsQuery(t *testing.T) { - cleanup, valPubKeys, operAddrs, port := InitializeTestLCD(t, 1, []sdk.AccAddress{}, true) - defer cleanup() - - require.Equal(t, 1, len(valPubKeys)) - require.Equal(t, 1, len(operAddrs)) - - validators := getValidators(t, port) - require.Equal(t, 1, len(validators), fmt.Sprintf("%+v", validators)) - - // make sure all the validators were found (order unknown because sorted by operator addr) - foundVal := false - - if validators[0].ConsPubKey == valPubKeys[0] { - foundVal = true - } - - require.True(t, foundVal, "pk %v, operator %v", operAddrs[0], validators[0].OperatorAddress) -} - -func TestValidatorQuery(t *testing.T) { - cleanup, valPubKeys, operAddrs, port := InitializeTestLCD(t, 1, []sdk.AccAddress{}, true) - defer cleanup() - require.Equal(t, 1, len(valPubKeys)) - require.Equal(t, 1, len(operAddrs)) - - validator := getValidator(t, port, operAddrs[0]) - require.Equal(t, validator.OperatorAddress, operAddrs[0], "The returned validator does not hold the correct data") -} - -func TestBonding(t *testing.T) { - kb, err := keys.NewKeyBaseFromDir(InitClientHome(t, "")) - require.NoError(t, err) - addr, _ := CreateAddr(t, name1, pw, kb) - - cleanup, valPubKeys, operAddrs, port := InitializeTestLCD(t, 2, []sdk.AccAddress{addr}, false) - tests.WaitForHeight(1, port) - defer cleanup() - - require.Equal(t, 2, len(valPubKeys)) - require.Equal(t, 2, len(operAddrs)) - - amt := sdk.TokensFromTendermintPower(60) - amtDec := amt.ToDec() - validator := getValidator(t, port, operAddrs[0]) - - acc := getAccount(t, port, addr) - initialBalance := acc.GetCoins() - - // create bond TX - delTokens := sdk.TokensFromTendermintPower(60) - resultTx := doDelegate(t, port, name1, pw, addr, operAddrs[0], delTokens, fees) - tests.WaitForHeight(resultTx.Height+1, port) - - require.Equal(t, uint32(0), resultTx.Code) - - // query tx - txResult := getTransactions(t, port, - fmt.Sprintf("action=delegate&sender=%s", addr), - fmt.Sprintf("destination-validator=%s", operAddrs[0]), - ) - require.Len(t, txResult.Txs, 1) - require.Equal(t, resultTx.Height, txResult.Txs[0].Height) - - // verify balance - acc = getAccount(t, port, addr) - coins := acc.GetCoins() - expectedBalance := initialBalance[0].Sub(fees[0]) - require.Equal(t, expectedBalance.Amount.Sub(delTokens), coins.AmountOf(sdk.DefaultBondDenom)) - expectedBalance = coins[0] - - // query delegation - bond := getDelegation(t, port, addr, operAddrs[0]) - require.Equal(t, amtDec, bond.Shares) - - delegatorDels := getDelegatorDelegations(t, port, addr) - require.Len(t, delegatorDels, 1) - require.Equal(t, amtDec, delegatorDels[0].Shares) - - // query all delegations to validator - bonds := getValidatorDelegations(t, port, operAddrs[0]) - require.Len(t, bonds, 2) - - bondedValidators := getDelegatorValidators(t, port, addr) - require.Len(t, bondedValidators, 1) - require.Equal(t, operAddrs[0], bondedValidators[0].OperatorAddress) - require.Equal(t, validator.DelegatorShares.Add(amtDec).String(), bondedValidators[0].DelegatorShares.String()) - - bondedValidator := getDelegatorValidator(t, port, addr, operAddrs[0]) - require.Equal(t, operAddrs[0], bondedValidator.OperatorAddress) - - // testing unbonding - unbondingTokens := sdk.TokensFromTendermintPower(30) - resultTx = doUndelegate(t, port, name1, pw, addr, operAddrs[0], unbondingTokens, fees) - tests.WaitForHeight(resultTx.Height+1, port) - - require.Equal(t, uint32(0), resultTx.Code) - - // sender should have not received any coins as the unbonding has only just begun - acc = getAccount(t, port, addr) - coins = acc.GetCoins() - expectedBalance = expectedBalance.Sub(fees[0]) - require.True(t, - expectedBalance.Amount.LT(coins.AmountOf(sdk.DefaultBondDenom)) || - expectedBalance.Amount.Equal(coins.AmountOf(sdk.DefaultBondDenom)), - "should get tokens back from automatic withdrawal after an unbonding delegation", - ) - expectedBalance = coins[0] - - // query tx - txResult = getTransactions(t, port, - fmt.Sprintf("action=begin_unbonding&sender=%s", addr), - fmt.Sprintf("source-validator=%s", operAddrs[0]), - ) - require.Len(t, txResult.Txs, 1) - require.Equal(t, resultTx.Height, txResult.Txs[0].Height) - - ubd := getUnbondingDelegation(t, port, addr, operAddrs[0]) - require.Len(t, ubd.Entries, 1) - require.Equal(t, delTokens.QuoRaw(2), ubd.Entries[0].Balance) - - // test redelegation - rdTokens := sdk.TokensFromTendermintPower(30) - resultTx = doBeginRedelegation(t, port, name1, pw, addr, operAddrs[0], operAddrs[1], rdTokens, fees) - require.Equal(t, uint32(0), resultTx.Code) - tests.WaitForHeight(resultTx.Height+1, port) - - // query delegations, unbondings and redelegations from validator and delegator - delegatorDels = getDelegatorDelegations(t, port, addr) - require.Len(t, delegatorDels, 1) - require.Equal(t, operAddrs[1], delegatorDels[0].ValidatorAddress) - - // TODO uncomment once all validators actually sign in the lcd tests - //validator2 := getValidator(t, port, operAddrs[1]) - //delTokensAfterRedelegation := validator2.ShareTokens(delegatorDels[0].GetShares()) - //require.Equal(t, rdTokens.ToDec(), delTokensAfterRedelegation) - - // verify balance after paying fees - acc = getAccount(t, port, addr) - expectedBalance = expectedBalance.Sub(fees[0]) - require.True(t, - expectedBalance.Amount.LT(coins.AmountOf(sdk.DefaultBondDenom)) || - expectedBalance.Amount.Equal(coins.AmountOf(sdk.DefaultBondDenom)), - "should get tokens back from automatic withdrawal after an unbonding delegation", - ) - - // query tx - txResult = getTransactions(t, port, - fmt.Sprintf("action=begin_redelegate&sender=%s", addr), - fmt.Sprintf("source-validator=%s", operAddrs[0]), - fmt.Sprintf("destination-validator=%s", operAddrs[1]), - ) - require.Len(t, txResult.Txs, 1) - require.Equal(t, resultTx.Height, txResult.Txs[0].Height) - - redelegation := getRedelegations(t, port, addr, operAddrs[0], operAddrs[1]) - require.Len(t, redelegation, 1) - require.Len(t, redelegation[0].Entries, 1) - - delegatorUbds := getDelegatorUnbondingDelegations(t, port, addr) - require.Len(t, delegatorUbds, 1) - require.Len(t, delegatorUbds[0].Entries, 1) - require.Equal(t, rdTokens, delegatorUbds[0].Entries[0].Balance) - - delegatorReds := getRedelegations(t, port, addr, nil, nil) - require.Len(t, delegatorReds, 1) - require.Len(t, delegatorReds[0].Entries, 1) - - validatorUbds := getValidatorUnbondingDelegations(t, port, operAddrs[0]) - require.Len(t, validatorUbds, 1) - require.Len(t, validatorUbds[0].Entries, 1) - require.Equal(t, rdTokens, validatorUbds[0].Entries[0].Balance) - - validatorReds := getRedelegations(t, port, nil, operAddrs[0], nil) - require.Len(t, validatorReds, 1) - require.Len(t, validatorReds[0].Entries, 1) - - // TODO Undonding status not currently implemented - // require.Equal(t, sdk.Unbonding, bondedValidators[0].Status) - - // query txs - txs := getBondingTxs(t, port, addr, "") - require.Len(t, txs, 3, "All Txs found") - - txs = getBondingTxs(t, port, addr, "bond") - require.Len(t, txs, 1, "All bonding txs found") - - txs = getBondingTxs(t, port, addr, "unbond") - require.Len(t, txs, 1, "All unbonding txs found") - - txs = getBondingTxs(t, port, addr, "redelegate") - require.Len(t, txs, 1, "All redelegation txs found") -} - -func TestSubmitProposal(t *testing.T) { - kb, err := keys.NewKeyBaseFromDir(InitClientHome(t, "")) - require.NoError(t, err) - addr, seed := CreateAddr(t, name1, pw, kb) - cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}, true) - defer cleanup() - - acc := getAccount(t, port, addr) - initialBalance := acc.GetCoins() - - // create SubmitProposal TX - proposalTokens := sdk.TokensFromTendermintPower(5) - resultTx := doSubmitProposal(t, port, seed, name1, pw, addr, proposalTokens, fees) - tests.WaitForHeight(resultTx.Height+1, port) - - // check if tx was committed - require.Equal(t, uint32(0), resultTx.Code) - - var proposalID uint64 - bz, err := hex.DecodeString(resultTx.Data) - require.NoError(t, err) - cdc.MustUnmarshalBinaryLengthPrefixed(bz, &proposalID) - - // verify balance - acc = getAccount(t, port, addr) - expectedBalance := initialBalance[0].Sub(fees[0]) - require.Equal(t, expectedBalance.Amount.Sub(proposalTokens), acc.GetCoins().AmountOf(sdk.DefaultBondDenom)) - - // query proposal - proposal := getProposal(t, port, proposalID) - require.Equal(t, "Test", proposal.GetTitle()) - - proposer := getProposer(t, port, proposalID) - require.Equal(t, addr.String(), proposer.Proposer) - require.Equal(t, proposalID, proposer.ProposalID) -} - -func TestSubmitParamChangeProposal(t *testing.T) { - kb, err := keys.NewKeyBaseFromDir(InitClientHome(t, "")) - require.NoError(t, err) - addr, seed := CreateAddr(t, name1, pw, kb) - cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}, true) - defer cleanup() - - acc := getAccount(t, port, addr) - initialBalance := acc.GetCoins() - - // create proposal tx - proposalTokens := sdk.TokensFromTendermintPower(5) - resultTx := doSubmitParamChangeProposal(t, port, seed, name1, pw, addr, proposalTokens, fees) - tests.WaitForHeight(resultTx.Height+1, port) - - // check if tx was committed - require.Equal(t, uint32(0), resultTx.Code) - - var proposalID uint64 - bz, err := hex.DecodeString(resultTx.Data) - require.NoError(t, err) - cdc.MustUnmarshalBinaryLengthPrefixed(bz, &proposalID) - - // verify balance - acc = getAccount(t, port, addr) - expectedBalance := initialBalance[0].Sub(fees[0]) - require.Equal(t, expectedBalance.Amount.Sub(proposalTokens), acc.GetCoins().AmountOf(sdk.DefaultBondDenom)) - - // query proposal - proposal := getProposal(t, port, proposalID) - require.Equal(t, "Test", proposal.GetTitle()) - - proposer := getProposer(t, port, proposalID) - require.Equal(t, addr.String(), proposer.Proposer) - require.Equal(t, proposalID, proposer.ProposalID) -} - -func TestDeposit(t *testing.T) { - kb, err := keys.NewKeyBaseFromDir(InitClientHome(t, "")) - require.NoError(t, err) - addr, seed := CreateAddr(t, name1, pw, kb) - cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}, true) - defer cleanup() - - acc := getAccount(t, port, addr) - initialBalance := acc.GetCoins() - - // create SubmitProposal TX - proposalTokens := sdk.TokensFromTendermintPower(5) - resultTx := doSubmitProposal(t, port, seed, name1, pw, addr, proposalTokens, fees) - tests.WaitForHeight(resultTx.Height+1, port) - - // check if tx was committed - require.Equal(t, uint32(0), resultTx.Code) - - var proposalID uint64 - bz, err := hex.DecodeString(resultTx.Data) - require.NoError(t, err) - cdc.MustUnmarshalBinaryLengthPrefixed(bz, &proposalID) - - // verify balance - acc = getAccount(t, port, addr) - coins := acc.GetCoins() - expectedBalance := initialBalance[0].Sub(fees[0]) - require.Equal(t, expectedBalance.Amount.Sub(proposalTokens), coins.AmountOf(sdk.DefaultBondDenom)) - expectedBalance = coins[0] - - // query proposal - proposal := getProposal(t, port, proposalID) - require.Equal(t, "Test", proposal.GetTitle()) - - // create SubmitProposal TX - depositTokens := sdk.TokensFromTendermintPower(5) - resultTx = doDeposit(t, port, seed, name1, pw, addr, proposalID, depositTokens, fees) - tests.WaitForHeight(resultTx.Height+1, port) - - // verify balance after deposit and fee - acc = getAccount(t, port, addr) - expectedBalance = expectedBalance.Sub(fees[0]) - require.Equal(t, expectedBalance.Amount.Sub(depositTokens), acc.GetCoins().AmountOf(sdk.DefaultBondDenom)) - - // query tx - txResult := getTransactions(t, port, fmt.Sprintf("action=deposit&sender=%s", addr)) - require.Len(t, txResult.Txs, 1) - require.Equal(t, resultTx.Height, txResult.Txs[0].Height) - - // query proposal - totalCoins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromTendermintPower(10))} - proposal = getProposal(t, port, proposalID) - require.True(t, proposal.TotalDeposit.IsEqual(totalCoins)) - - // query deposit - deposit := getDeposit(t, port, proposalID, addr) - require.True(t, deposit.Amount.IsEqual(totalCoins)) -} - -func TestVote(t *testing.T) { - kb, err := keys.NewKeyBaseFromDir(InitClientHome(t, "")) - require.NoError(t, err) - addr, seed := CreateAddr(t, name1, pw, kb) - cleanup, _, operAddrs, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}, true) - defer cleanup() - - acc := getAccount(t, port, addr) - initialBalance := acc.GetCoins() - - // create SubmitProposal TX - proposalTokens := sdk.TokensFromTendermintPower(10) - resultTx := doSubmitProposal(t, port, seed, name1, pw, addr, proposalTokens, fees) - tests.WaitForHeight(resultTx.Height+1, port) - - // check if tx was committed - require.Equal(t, uint32(0), resultTx.Code) - - var proposalID uint64 - bz, err := hex.DecodeString(resultTx.Data) - require.NoError(t, err) - cdc.MustUnmarshalBinaryLengthPrefixed(bz, &proposalID) - - // verify balance - acc = getAccount(t, port, addr) - coins := acc.GetCoins() - expectedBalance := initialBalance[0].Sub(fees[0]) - require.Equal(t, expectedBalance.Amount.Sub(proposalTokens), coins.AmountOf(sdk.DefaultBondDenom)) - expectedBalance = coins[0] - - // query proposal - proposal := getProposal(t, port, proposalID) - require.Equal(t, "Test", proposal.GetTitle()) - require.Equal(t, gov.StatusVotingPeriod, proposal.Status) - - // vote - resultTx = doVote(t, port, seed, name1, pw, addr, proposalID, "Yes", fees) - tests.WaitForHeight(resultTx.Height+1, port) - - // verify balance after vote and fee - acc = getAccount(t, port, addr) - coins = acc.GetCoins() - expectedBalance = expectedBalance.Sub(fees[0]) - require.Equal(t, expectedBalance.Amount, coins.AmountOf(sdk.DefaultBondDenom)) - expectedBalance = coins[0] - - // query tx - txResult := getTransactions(t, port, fmt.Sprintf("action=vote&sender=%s", addr)) - require.Len(t, txResult.Txs, 1) - require.Equal(t, resultTx.Height, txResult.Txs[0].Height) - - vote := getVote(t, port, proposalID, addr) - require.Equal(t, proposalID, vote.ProposalID) - require.Equal(t, gov.OptionYes, vote.Option) - - tally := getTally(t, port, proposalID) - require.Equal(t, sdk.ZeroInt(), tally.Yes, "tally should be 0 as the address is not bonded") - - // create bond TX - delTokens := sdk.TokensFromTendermintPower(60) - resultTx = doDelegate(t, port, name1, pw, addr, operAddrs[0], delTokens, fees) - tests.WaitForHeight(resultTx.Height+1, port) - - // verify balance - acc = getAccount(t, port, addr) - coins = acc.GetCoins() - expectedBalance = expectedBalance.Sub(fees[0]) - require.Equal(t, expectedBalance.Amount.Sub(delTokens), coins.AmountOf(sdk.DefaultBondDenom)) - expectedBalance = coins[0] - - tally = getTally(t, port, proposalID) - require.Equal(t, delTokens, tally.Yes, "tally should be equal to the amount delegated") - - // change vote option - resultTx = doVote(t, port, seed, name1, pw, addr, proposalID, "No", fees) - tests.WaitForHeight(resultTx.Height+1, port) - - // verify balance - acc = getAccount(t, port, addr) - expectedBalance = expectedBalance.Sub(fees[0]) - require.Equal(t, expectedBalance.Amount, acc.GetCoins().AmountOf(sdk.DefaultBondDenom)) - - tally = getTally(t, port, proposalID) - require.Equal(t, sdk.ZeroInt(), tally.Yes, "tally should be 0 the user changed the option") - require.Equal(t, delTokens, tally.No, "tally should be equal to the amount delegated") -} - -func TestUnjail(t *testing.T) { - kb, err := keys.NewKeyBaseFromDir(InitClientHome(t, "")) - require.NoError(t, err) - addr, _ := CreateAddr(t, name1, pw, kb) - cleanup, valPubKeys, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}, true) - defer cleanup() - - // NOTE: any less than this and it fails - tests.WaitForHeight(3, port) - pkString, _ := sdk.Bech32ifyConsPub(valPubKeys[0]) - signingInfo := getSigningInfo(t, port, pkString) - tests.WaitForHeight(4, port) - require.Equal(t, true, signingInfo.IndexOffset > 0) - require.Equal(t, time.Unix(0, 0).UTC(), signingInfo.JailedUntil) - require.Equal(t, true, signingInfo.MissedBlocksCounter == 0) - signingInfoList := getSigningInfoList(t, port) - require.NotZero(t, len(signingInfoList)) -} - -func TestProposalsQuery(t *testing.T) { - kb, err := keys.NewKeyBaseFromDir(InitClientHome(t, "")) - require.NoError(t, err) - addrs, seeds, names, passwords := CreateAddrs(t, kb, 2) - - cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addrs[0], addrs[1]}, true) - defer cleanup() - - depositParam := getDepositParam(t, port) - halfMinDeposit := depositParam.MinDeposit.AmountOf(sdk.DefaultBondDenom).QuoRaw(2) - getVotingParam(t, port) - getTallyingParam(t, port) - - // Addr1 proposes (and deposits) proposals #1 and #2 - resultTx := doSubmitProposal(t, port, seeds[0], names[0], passwords[0], addrs[0], halfMinDeposit, fees) - var proposalID1 uint64 - bz, err := hex.DecodeString(resultTx.Data) - require.NoError(t, err) - cdc.MustUnmarshalBinaryLengthPrefixed(bz, &proposalID1) - tests.WaitForHeight(resultTx.Height+1, port) - - resultTx = doSubmitProposal(t, port, seeds[0], names[0], passwords[0], addrs[0], halfMinDeposit, fees) - var proposalID2 uint64 - bz, err = hex.DecodeString(resultTx.Data) - require.NoError(t, err) - cdc.MustUnmarshalBinaryLengthPrefixed(bz, &proposalID2) - tests.WaitForHeight(resultTx.Height+1, port) - - // Addr2 proposes (and deposits) proposals #3 - resultTx = doSubmitProposal(t, port, seeds[1], names[1], passwords[1], addrs[1], halfMinDeposit, fees) - var proposalID3 uint64 - bz, err = hex.DecodeString(resultTx.Data) - require.NoError(t, err) - cdc.MustUnmarshalBinaryLengthPrefixed(bz, &proposalID3) - tests.WaitForHeight(resultTx.Height+1, port) - - // Addr2 deposits on proposals #2 & #3 - resultTx = doDeposit(t, port, seeds[1], names[1], passwords[1], addrs[1], proposalID2, halfMinDeposit, fees) - tests.WaitForHeight(resultTx.Height+1, port) - - resultTx = doDeposit(t, port, seeds[1], names[1], passwords[1], addrs[1], proposalID3, halfMinDeposit, fees) - tests.WaitForHeight(resultTx.Height+1, port) - - // check deposits match proposal and individual deposits - deposits := getDeposits(t, port, proposalID1) - require.Len(t, deposits, 1) - deposit := getDeposit(t, port, proposalID1, addrs[0]) - require.Equal(t, deposit, deposits[0]) - - deposits = getDeposits(t, port, proposalID2) - require.Len(t, deposits, 2) - deposit = getDeposit(t, port, proposalID2, addrs[0]) - require.True(t, deposit.Equals(deposits[0])) - deposit = getDeposit(t, port, proposalID2, addrs[1]) - require.True(t, deposit.Equals(deposits[1])) - - deposits = getDeposits(t, port, proposalID3) - require.Len(t, deposits, 1) - deposit = getDeposit(t, port, proposalID3, addrs[1]) - require.Equal(t, deposit, deposits[0]) - - // increasing the amount of the deposit should update the existing one - depositTokens := sdk.TokensFromTendermintPower(1) - resultTx = doDeposit(t, port, seeds[0], names[0], passwords[0], addrs[0], proposalID1, depositTokens, fees) - tests.WaitForHeight(resultTx.Height+1, port) - - deposits = getDeposits(t, port, proposalID1) - require.Len(t, deposits, 1) - - // Only proposals #1 should be in Deposit Period - proposals := getProposalsFilterStatus(t, port, gov.StatusDepositPeriod) - require.Len(t, proposals, 1) - require.Equal(t, proposalID1, proposals[0].ProposalID) - - // Only proposals #2 and #3 should be in Voting Period - proposals = getProposalsFilterStatus(t, port, gov.StatusVotingPeriod) - require.Len(t, proposals, 2) - require.Equal(t, proposalID2, proposals[0].ProposalID) - require.Equal(t, proposalID3, proposals[1].ProposalID) - - // Addr1 votes on proposals #2 & #3 - resultTx = doVote(t, port, seeds[0], names[0], passwords[0], addrs[0], proposalID2, "Yes", fees) - tests.WaitForHeight(resultTx.Height+1, port) - resultTx = doVote(t, port, seeds[0], names[0], passwords[0], addrs[0], proposalID3, "Yes", fees) - tests.WaitForHeight(resultTx.Height+1, port) - - // Addr2 votes on proposal #3 - resultTx = doVote(t, port, seeds[1], names[1], passwords[1], addrs[1], proposalID3, "Yes", fees) - tests.WaitForHeight(resultTx.Height+1, port) - - // Test query all proposals - proposals = getProposalsAll(t, port) - require.Equal(t, proposalID1, (proposals[0]).ProposalID) - require.Equal(t, proposalID2, (proposals[1]).ProposalID) - require.Equal(t, proposalID3, (proposals[2]).ProposalID) - - // Test query deposited by addr1 - proposals = getProposalsFilterDepositor(t, port, addrs[0]) - require.Equal(t, proposalID1, (proposals[0]).ProposalID) - - // Test query deposited by addr2 - proposals = getProposalsFilterDepositor(t, port, addrs[1]) - require.Equal(t, proposalID2, (proposals[0]).ProposalID) - require.Equal(t, proposalID3, (proposals[1]).ProposalID) - - // Test query voted by addr1 - proposals = getProposalsFilterVoter(t, port, addrs[0]) - require.Equal(t, proposalID2, (proposals[0]).ProposalID) - require.Equal(t, proposalID3, (proposals[1]).ProposalID) - - // Test query voted by addr2 - proposals = getProposalsFilterVoter(t, port, addrs[1]) - require.Equal(t, proposalID3, (proposals[0]).ProposalID) - - // Test query voted and deposited by addr1 - proposals = getProposalsFilterVoterDepositor(t, port, addrs[0], addrs[0]) - require.Equal(t, proposalID2, (proposals[0]).ProposalID) - - // Test query votes on Proposal 2 - votes := getVotes(t, port, proposalID2) - require.Len(t, votes, 1) - require.Equal(t, addrs[0], votes[0].Voter) - - // Test query votes on Proposal 3 - votes = getVotes(t, port, proposalID3) - require.Len(t, votes, 2) - require.True(t, addrs[0].String() == votes[0].Voter.String() || addrs[0].String() == votes[1].Voter.String()) - require.True(t, addrs[1].String() == votes[0].Voter.String() || addrs[1].String() == votes[1].Voter.String()) -} - -func TestSlashingGetParams(t *testing.T) { - cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{}, true) - defer cleanup() - - res, body := Request(t, port, "GET", "/slashing/parameters", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var params slashing.Params - err := cdc.UnmarshalJSON([]byte(body), ¶ms) - require.NoError(t, err) -} - -func TestDistributionGetParams(t *testing.T) { - cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{}, true) - defer cleanup() - - res, body := Request(t, port, "GET", "/distribution/parameters", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.NoError(t, cdc.UnmarshalJSON([]byte(body), &dclcommon.PrettyParams{})) -} - -func TestDistributionFlow(t *testing.T) { - kb, err := keys.NewKeyBaseFromDir(InitClientHome(t, "")) - require.NoError(t, err) - addr, seed := CreateAddr(t, name1, pw, kb) - cleanup, _, valAddrs, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}, true) - defer cleanup() - - valAddr := valAddrs[0] - operAddr := sdk.AccAddress(valAddr) - - var rewards sdk.DecCoins - res, body := Request(t, port, "GET", fmt.Sprintf("/distribution/validators/%s/outstanding_rewards", valAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.NoError(t, cdc.UnmarshalJSON([]byte(body), &rewards)) - - var valDistInfo distrrest.ValidatorDistInfo - res, body = Request(t, port, "GET", "/distribution/validators/"+valAddr.String(), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.NoError(t, cdc.UnmarshalJSON([]byte(body), &valDistInfo)) - require.Equal(t, valDistInfo.OperatorAddress.String(), sdk.AccAddress(valAddr).String()) - - // Delegate some coins - delTokens := sdk.TokensFromTendermintPower(60) - resultTx := doDelegate(t, port, name1, pw, addr, valAddr, delTokens, fees) - tests.WaitForHeight(resultTx.Height+1, port) - require.Equal(t, uint32(0), resultTx.Code) - - // send some coins - _, resultTx = doTransfer(t, port, seed, name1, memo, pw, addr, fees) - tests.WaitForHeight(resultTx.Height+5, port) - require.Equal(t, uint32(0), resultTx.Code) - - // Query outstanding rewards changed - res, body = Request(t, port, "GET", fmt.Sprintf("/distribution/validators/%s/outstanding_rewards", valAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.NoError(t, cdc.UnmarshalJSON([]byte(body), &rewards)) - - // Query validator distribution info - res, body = Request(t, port, "GET", "/distribution/validators/"+valAddr.String(), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - require.NoError(t, cdc.UnmarshalJSON([]byte(body), &valDistInfo)) - - // Query validator's rewards - res, body = Request(t, port, "GET", fmt.Sprintf("/distribution/validators/%s/rewards", valAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.NoError(t, cdc.UnmarshalJSON([]byte(body), &rewards)) - - // Query self-delegation - res, body = Request(t, port, "GET", fmt.Sprintf("/distribution/delegators/%s/rewards/%s", operAddr, valAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.NoError(t, cdc.UnmarshalJSON([]byte(body), &rewards)) - - // Query delegation - res, body = Request(t, port, "GET", fmt.Sprintf("/distribution/delegators/%s/rewards/%s", addr, valAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.NoError(t, cdc.UnmarshalJSON([]byte(body), &rewards)) - - // Query delegator's rewards total - var delRewards disttypes.QueryDelegatorTotalRewardsResponse - res, body = Request(t, port, "GET", fmt.Sprintf("/distribution/delegators/%s/rewards", operAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.NoError(t, json.Unmarshal([]byte(body), &delRewards)) - - // Query delegator's withdrawal address - var withdrawAddr string - res, body = Request(t, port, "GET", fmt.Sprintf("/distribution/delegators/%s/withdraw_address", operAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.NoError(t, cdc.UnmarshalJSON([]byte(body), &withdrawAddr)) - require.Equal(t, operAddr.String(), withdrawAddr) - - // Withdraw delegator's rewards - resultTx = doWithdrawDelegatorAllRewards(t, port, seed, name1, pw, addr, fees) - require.Equal(t, uint32(0), resultTx.Code) -} - -func TestMintingQueries(t *testing.T) { - kb, err := keys.NewKeyBaseFromDir(InitClientHome(t, "")) - require.NoError(t, err) - addr, _ := CreateAddr(t, name1, pw, kb) - cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}, true) - defer cleanup() - - res, body := Request(t, port, "GET", "/minting/parameters", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var params mint.Params - require.NoError(t, cdc.UnmarshalJSON([]byte(body), ¶ms)) - - res, body = Request(t, port, "GET", "/minting/inflation", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var inflation sdk.Dec - require.NoError(t, cdc.UnmarshalJSON([]byte(body), &inflation)) - - res, body = Request(t, port, "GET", "/minting/annual-provisions", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var annualProvisions sdk.Dec - require.NoError(t, cdc.UnmarshalJSON([]byte(body), &annualProvisions)) -} - -func TestAccountBalanceQuery(t *testing.T) { - kb, err := keys.NewKeyBaseFromDir(InitClientHome(t, "")) - require.NoError(t, err) - addr, _ := CreateAddr(t, name1, pw, kb) - cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}, true) - defer cleanup() - - bz, err := hex.DecodeString("8FA6AB57AD6870F6B5B2E57735F38F2F30E73CB6") - require.NoError(t, err) - someFakeAddr := sdk.AccAddress(bz) - - // empty account - res, body := Request(t, port, "GET", fmt.Sprintf("/auth/accounts/%s", someFakeAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.Contains(t, body, `"type":"auth/Account"`) - - // empty account balance - res, body = Request(t, port, "GET", fmt.Sprintf("/bank/balances/%s", someFakeAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.Contains(t, body, "[]") - -} diff --git a/cmd/gaia/sims.mk b/cmd/gaia/sims.mk deleted file mode 100644 index 918b8c93f6..0000000000 --- a/cmd/gaia/sims.mk +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/make -f - -######################################## -### Simulations - -runsim: $(GOPATH)/bin/runsim -$(GOPATH)/bin/runsim: contrib/runsim/main.go - go install github.com/cosmos/cosmos-sdk/cmd/gaia/contrib/runsim - -sim-gaia-nondeterminism: - @echo "Running nondeterminism test..." - @go test -mod=readonly ./cmd/gaia/app -run TestAppStateDeterminism -SimulationEnabled=true -v -timeout 10m - -sim-gaia-custom-genesis-fast: - @echo "Running custom genesis simulation..." - @echo "By default, ${HOME}/.gaiad/config/genesis.json will be used." - @go test -mod=readonly github.com/cosmos/cosmos-sdk/cmd/gaia/app -run TestFullGaiaSimulation -SimulationGenesis=${HOME}/.gaiad/config/genesis.json \ - -SimulationEnabled=true -SimulationNumBlocks=100 -SimulationBlockSize=200 -SimulationCommit=true -SimulationSeed=99 -SimulationPeriod=5 -v -timeout 24h - -sim-gaia-fast: - @echo "Running quick Gaia simulation. This may take several minutes..." - @go test -mod=readonly github.com/cosmos/cosmos-sdk/cmd/gaia/app -run TestFullGaiaSimulation -SimulationEnabled=true -SimulationNumBlocks=100 -SimulationBlockSize=200 -SimulationCommit=true -SimulationSeed=99 -SimulationPeriod=5 -v -timeout 24h - -sim-gaia-import-export: runsim - @echo "Running Gaia import/export simulation. This may take several minutes..." - $(GOPATH)/bin/runsim 25 5 TestGaiaImportExport - -sim-gaia-simulation-after-import: runsim - @echo "Running Gaia simulation-after-import. This may take several minutes..." - $(GOPATH)/bin/runsim 25 5 TestGaiaSimulationAfterImport - -sim-gaia-custom-genesis-multi-seed: runsim - @echo "Running multi-seed custom genesis simulation..." - @echo "By default, ${HOME}/.gaiad/config/genesis.json will be used." - $(GOPATH)/bin/runsim -g ${HOME}/.gaiad/config/genesis.json 400 5 TestFullGaiaSimulation - -sim-gaia-multi-seed: runsim - @echo "Running multi-seed Gaia simulation. This may take awhile!" - $(GOPATH)/bin/runsim 400 5 TestFullGaiaSimulation - -sim-benchmark-invariants: - @echo "Running simulation invariant benchmarks..." - @go test -mod=readonly github.com/cosmos/cosmos-sdk/cmd/gaia/app -benchmem -bench=BenchmarkInvariants -run=^$ \ - -SimulationEnabled=true -SimulationNumBlocks=1000 -SimulationBlockSize=200 \ - -SimulationCommit=true -SimulationSeed=57 -v -timeout 24h - -SIM_NUM_BLOCKS ?= 500 -SIM_BLOCK_SIZE ?= 200 -SIM_COMMIT ?= true -sim-gaia-benchmark: - @echo "Running Gaia benchmark for numBlocks=$(SIM_NUM_BLOCKS), blockSize=$(SIM_BLOCK_SIZE). This may take awhile!" - @go test -mod=readonly -benchmem -run=^$$ github.com/cosmos/cosmos-sdk/cmd/gaia/app -bench ^BenchmarkFullGaiaSimulation$$ \ - -SimulationEnabled=true -SimulationNumBlocks=$(SIM_NUM_BLOCKS) -SimulationBlockSize=$(SIM_BLOCK_SIZE) -SimulationCommit=$(SIM_COMMIT) -timeout 24h - -sim-gaia-profile: - @echo "Running Gaia benchmark for numBlocks=$(SIM_NUM_BLOCKS), blockSize=$(SIM_BLOCK_SIZE). This may take awhile!" - @go test -mod=readonly -benchmem -run=^$$ github.com/cosmos/cosmos-sdk/cmd/gaia/app -bench ^BenchmarkFullGaiaSimulation$$ \ - -SimulationEnabled=true -SimulationNumBlocks=$(SIM_NUM_BLOCKS) -SimulationBlockSize=$(SIM_BLOCK_SIZE) -SimulationCommit=$(SIM_COMMIT) -timeout 24h -cpuprofile cpu.out -memprofile mem.out - -.PHONY: sim-gaia-nondeterminism sim-gaia-custom-genesis-fast sim-gaia-fast sim-gaia-import-export \ - sim-gaia-simulation-after-import sim-gaia-custom-genesis-multi-seed sim-gaia-multi-seed \ - sim-benchmark-invariants sim-gaia-benchmark sim-gaia-profile diff --git a/cmd/gaia/contrib/runsim/main.go b/contrib/runsim/main.go similarity index 91% rename from cmd/gaia/contrib/runsim/main.go rename to contrib/runsim/main.go index 092579dbc9..b8ceb2d11e 100644 --- a/cmd/gaia/contrib/runsim/main.go +++ b/contrib/runsim/main.go @@ -37,6 +37,7 @@ var ( // command line arguments and options jobs = runtime.GOMAXPROCS(0) + pkgName string blocks string period string testname string @@ -60,7 +61,7 @@ func init() { flag.Usage = func() { fmt.Fprintf(flag.CommandLine.Output(), - `Usage: %s [-j maxprocs] [-g genesis.json] [-e] [blocks] [period] [testname] + `Usage: %s [-j maxprocs] [-g genesis.json] [-e] [package] [blocks] [period] [testname] Run simulations in parallel `, filepath.Base(os.Args[0])) @@ -72,7 +73,7 @@ func main() { var err error flag.Parse() - if flag.NArg() != 3 { + if flag.NArg() != 4 { log.Fatal("wrong number of arguments") } @@ -108,9 +109,10 @@ func main() { }() // initialise common test parameters - blocks = flag.Arg(0) - period = flag.Arg(1) - testname = flag.Arg(2) + pkgName = flag.Arg(0) + blocks = flag.Arg(1) + period = flag.Arg(2) + testname = flag.Arg(3) tempdir, err = ioutil.TempDir("", "") if err != nil { log.Fatal(err) @@ -157,10 +159,10 @@ wait: } func buildCommand(testname, blocks, period, genesis string, seed int) string { - return fmt.Sprintf("go test github.com/cosmos/cosmos-sdk/cmd/gaia/app -run %s -SimulationEnabled=true "+ + return fmt.Sprintf("go test %s -run %s -SimulationEnabled=true "+ "-SimulationNumBlocks=%s -SimulationGenesis=%s "+ "-SimulationVerbose=true -SimulationCommit=true -SimulationSeed=%d -SimulationPeriod=%s -v -timeout 24h", - testname, blocks, genesis, seed, period) + pkgName, testname, blocks, genesis, seed, period) } func makeCmd(cmdStr string) *exec.Cmd { @@ -169,7 +171,7 @@ func makeCmd(cmdStr string) *exec.Cmd { } func makeFilename(seed int) string { - return fmt.Sprintf("gaia-simulation-seed-%d-date-%s", seed, time.Now().Format("01-02-2006_15:04:05.000000000")) + return fmt.Sprintf("app-simulation-seed-%d-date-%s", seed, time.Now().Format("01-02-2006_15:04:05.000000000")) } func worker(id int, seeds <-chan int) { diff --git a/crypto/keys/mintkey/mintkey.go b/crypto/keys/mintkey/mintkey.go index 4806bcc4dd..c517d3da1b 100644 --- a/crypto/keys/mintkey/mintkey.go +++ b/crypto/keys/mintkey/mintkey.go @@ -29,7 +29,7 @@ const ( // threat this then exposes would be something that changes this during // runtime before the user creates their key. This vulnerability must // succeed to update this to that same value before every subsequent call -// to gaiacli keys in future startups / or the attacker must get access +// to the keys command in future startups / or the attacker must get access // to the filesystem. However, with a similar threat model (changing // variables in runtime), one can cause the user to sign a different tx // than what they see, which is a significantly cheaper attack then breaking diff --git a/docker-compose.yml b/docker-compose.yml deleted file mode 100644 index a0001416e2..0000000000 --- a/docker-compose.yml +++ /dev/null @@ -1,68 +0,0 @@ -version: '3' - -services: - gaiadnode0: - container_name: gaiadnode0 - image: "tendermint/gaiadnode" - ports: - - "26656-26657:26656-26657" - environment: - - ID=0 - - LOG=${LOG:-gaiad.log} - volumes: - - ./build:/gaiad:Z - networks: - localnet: - ipv4_address: 192.168.10.2 - - gaiadnode1: - container_name: gaiadnode1 - image: "tendermint/gaiadnode" - ports: - - "26659-26660:26656-26657" - environment: - - ID=1 - - LOG=${LOG:-gaiad.log} - volumes: - - ./build:/gaiad:Z - networks: - localnet: - ipv4_address: 192.168.10.3 - - gaiadnode2: - container_name: gaiadnode2 - image: "tendermint/gaiadnode" - environment: - - ID=2 - - LOG=${LOG:-gaiad.log} - ports: - - "26661-26662:26656-26657" - volumes: - - ./build:/gaiad:Z - networks: - localnet: - ipv4_address: 192.168.10.4 - - gaiadnode3: - container_name: gaiadnode3 - image: "tendermint/gaiadnode" - environment: - - ID=3 - - LOG=${LOG:-gaiad.log} - ports: - - "26663-26664:26656-26657" - volumes: - - ./build:/gaiad:Z - networks: - localnet: - ipv4_address: 192.168.10.5 - -networks: - localnet: - driver: bridge - ipam: - driver: default - config: - - - subnet: 192.168.10.0/16 - diff --git a/networks/Makefile b/networks/Makefile deleted file mode 100644 index 36db88f4d7..0000000000 --- a/networks/Makefile +++ /dev/null @@ -1,143 +0,0 @@ -######################################## -### These targets were broken out of the main Makefile to enable easy setup of testnets. -### They use a form of terraform + ansible to build full nodes in AWS. -### The shell scripts in this folder are example uses of the targets. - -# Name of the testnet. Used in chain-id. -TESTNET_NAME?=remotenet - -# Name of the servers grouped together for management purposes. Used in tagging the servers in the cloud. -CLUSTER_NAME?=$(TESTNET_NAME) - -# Number of servers to put in one availability zone in AWS. -SERVERS?=1 - -# Number of regions to use in AWS. One region usually contains 2-3 availability zones. -REGION_LIMIT?=1 - -# Path to gaiad for deployment. Must be a Linux binary. -BINARY?=$(CURDIR)/../build/gaiad -GAIACLI_BINARY?=$(CURDIR)/../build/gaiacli - -# Path to the genesis.json and config.toml files to deploy on full nodes. -GENESISFILE?=$(CURDIR)/../build/genesis.json -CONFIGFILE?=$(CURDIR)/../build/config.toml - -# Name of application for app deployments -APP_NAME ?= faucettestnet1 -# Region to deploy VPC and application in AWS -REGION ?= us-east-2 - -all: - @echo "There is no all. Only sum of the ones." - -disclaimer: - @echo "WARNING: These are example network configuration scripts only and have not undergone security review. They should not be used for production deployments." - -######################################## -### Extract genesis.json and config.toml from a node in a cluster - -extract-config: disclaimer - #Make sure you have AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY or your IAM roles set for AWS API access. - @if ! [ -f $(HOME)/.ssh/id_rsa.pub ]; then ssh-keygen ; fi - cd remote/ansible && \ - ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook \ - -i inventory/ec2.py \ - -l "tag_Environment_$(CLUSTER_NAME)" \ - -b -u centos \ - -e TESTNET_NAME="$(TESTNET_NAME)" \ - -e GENESISFILE="$(GENESISFILE)" \ - -e CONFIGFILE="$(CONFIGFILE)" \ - extract-config.yml - - -######################################## -### Remote validator nodes using terraform and ansible in AWS - -validators-start: disclaimer - #Make sure you have AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY or your IAM roles set for AWS API access. - @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 remote/terraform-aws && terraform init && (terraform workspace new "$(CLUSTER_NAME)" || terraform workspace select "$(CLUSTER_NAME)") && terraform apply -auto-approve -var SSH_PUBLIC_FILE="$(HOME)/.ssh/id_rsa.pub" -var SSH_PRIVATE_FILE="$(HOME)/.ssh/id_rsa" -var TESTNET_NAME="$(CLUSTER_NAME)" -var SERVERS="$(SERVERS)" -var REGION_LIMIT="$(REGION_LIMIT)" - cd remote/ansible && ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook -i inventory/ec2.py -l "tag_Environment_$(CLUSTER_NAME)" -u centos -b -e BINARY=$(BINARY) -e TESTNET_NAME="$(TESTNET_NAME)" setup-validators.yml - cd remote/ansible && ansible-playbook -i inventory/ec2.py -l "tag_Environment_$(CLUSTER_NAME)" -u centos -b start.yml - -validators-stop: disclaimer - cd remote/terraform-aws && terraform workspace select "$(CLUSTER_NAME)" && terraform destroy -force -var SSH_PUBLIC_FILE="$(HOME)/.ssh/id_rsa.pub" -var SSH_PRIVATE_FILE="$(HOME)/.ssh/id_rsa" && terraform workspace select default && terraform workspace delete "$(CLUSTER_NAME)" - rm -rf remote/ansible/keys/ remote/ansible/files/ - -validators-status: disclaimer - cd remote/ansible && ansible-playbook -i inventory/ec2.py -l "tag_Environment_$(CLUSTER_NAME)" status.yml - -#validators-clear: -# cd remote/ansible && ansible-playbook -i inventory/ec2.py -l "tag_Environment_$(CLUSTER_NAME)" -u centos -b clear-config.yml - - -######################################## -### Remote full nodes using terraform and ansible in Amazon AWS - -fullnodes-start: disclaimer - #Make sure you have AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY or your IAM roles set for AWS API access. - @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 remote/terraform-aws && terraform init && (terraform workspace new "$(CLUSTER_NAME)" || terraform workspace select "$(CLUSTER_NAME)") && terraform apply -auto-approve -var SSH_PUBLIC_FILE="$(HOME)/.ssh/id_rsa.pub" -var SSH_PRIVATE_FILE="$(HOME)/.ssh/id_rsa" -var TESTNET_NAME="$(CLUSTER_NAME)" -var SERVERS="$(SERVERS)" -var REGION_LIMIT="$(REGION_LIMIT)" - cd remote/ansible && ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook -i inventory/ec2.py -l "tag_Environment_$(CLUSTER_NAME)" -u centos -b -e BINARY=$(BINARY) -e TESTNET_NAME="$(TESTNET_NAME)" -e GENESISFILE="$(GENESISFILE)" -e CONFIGFILE="$(CONFIGFILE)" setup-fullnodes.yml - cd remote/ansible && ansible-playbook -i inventory/ec2.py -l "tag_Environment_$(CLUSTER_NAME)" -u centos -b start.yml - -fullnodes-stop: disclaimer - cd remote/terraform-aws && terraform workspace select "$(CLUSTER_NAME)" && terraform destroy -force -var SSH_PUBLIC_FILE="$(HOME)/.ssh/id_rsa.pub" -var SSH_PRIVATE_FILE="$(HOME)/.ssh/id_rsa" && terraform workspace select default && terraform workspace delete "$(CLUSTER_NAME)" - rm -rf remote/ansible/keys/ remote/ansible/files/ - -fullnodes-status: disclaimer - cd remote/ansible && ansible-playbook -i inventory/ec2.py -l "tag_Environment_$(CLUSTER_NAME)" status.yml - -######################################## -### Other calls - -upgrade-gaiad: disclaimer - #Make sure you have AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY or your IAM roles set for AWS API access. - @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 remote/ansible && ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook -i inventory/ec2.py -l "tag_Environment_$(CLUSTER_NAME)" -u centos -b -e BINARY=$(BINARY) upgrade-gaiad.yml - -UNSAFE_RESET_ALL?=no -upgrade-seeds: disclaimer - #Make sure you have AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY or your IAM roles set for AWS API access. - @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 - @if [ -z "`file $(GAIACLI_BINARY) | grep 'ELF 64-bit'`" ]; then echo "Please build a linux binary using 'make build-linux'." ; false ; fi - cd remote/ansible && ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook -i inventory/ec2.py -l "tag_Environment_$(CLUSTER_NAME)" -u centos -b -e BINARY=$(BINARY) -e GAIACLI_BINARY=$(GAIACLI_BINARY) -e UNSAFE_RESET_ALL=$(UNSAFE_RESET_ALL) upgrade-gaia.yml - - -list: - remote/ansible/inventory/ec2.py | python -c 'import json,sys ; print "\n".join(json.loads("".join(sys.stdin.readlines()))["tag_Environment_$(CLUSTER_NAME)"])' - -install-datadog: disclaimer - #Make sure you have AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY or your IAM roles set for AWS API access. - @if [ -z "$(DD_API_KEY)" ]; then echo "DD_API_KEY environment variable not set." ; false ; fi - cd remote/ansible && ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook -i inventory/ec2.py -l "tag_Environment_$(CLUSTER_NAME)" -u centos -b -e DD_API_KEY="$(DD_API_KEY)" -e TESTNET_NAME="$(TESTNET_NAME)" -e CLUSTER_NAME="$(CLUSTER_NAME)" install-datadog-agent.yml - -remove-datadog: disclaimer - #Make sure you have AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY or your IAM roles set for AWS API access. - cd remote/ansible && ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook -i inventory/ec2.py -l "tag_Environment_$(CLUSTER_NAME)" -u centos -b remove-datadog-agent.yml - - -######################################## -### Application infrastructure setup - -app-start: disclaimer - #Make sure you have AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY or your IAM roles set for AWS API access. - @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 remote/terraform-app && terraform init && (terraform workspace new "$(APP_NAME)" || terraform workspace select "$(APP_NAME)") && terraform apply -auto-approve -var SSH_PUBLIC_FILE="$(HOME)/.ssh/id_rsa.pub" -var SSH_PRIVATE_FILE="$(HOME)/.ssh/id_rsa" -var APP_NAME="$(APP_NAME)" -var SERVERS="$(SERVERS)" -var REGION="$(REGION)" - cd remote/ansible && ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook -i inventory/ec2.py -l "tag_Environment_$(APP_NAME)" -u centos -b -e BINARY=$(BINARY) -e TESTNET_NAME="$(TESTNET_NAME)" -e GENESISFILE="$(GENESISFILE)" -e CONFIGFILE="$(CONFIGFILE)" setup-fullnodes.yml - cd remote/ansible && ansible-playbook -i inventory/ec2.py -l "tag_Environment_$(APP_NAME)" -u centos -b start.yml - -app-stop: disclaimer - cd remote/terraform-app && terraform workspace select "$(APP_NAME)" && terraform destroy -force -var SSH_PUBLIC_FILE="$(HOME)/.ssh/id_rsa.pub" -var SSH_PRIVATE_FILE="$(HOME)/.ssh/id_rsa" -var APP_NAME=$(APP_NAME) && terraform workspace select default && terraform workspace delete "$(APP_NAME)" - rm -rf remote/ansible/keys/ remote/ansible/files/ - -# 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: all extract-config validators-start validators-stop validators-status fullnodes-start fullnodes-stop fullnodes-status upgrade-gaiad list install-datadog remove-datadog app-start app-stop diff --git a/networks/README.md b/networks/README.md deleted file mode 100644 index 9e948d4c27..0000000000 --- a/networks/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# Networks - -Here contains the files required for automated deployment of either local or remote testnets. - -Doing so is best accomplished using the `make` targets. For more information, see the -[networks documentation](/docs/gaia/networks.md) diff --git a/networks/add-cluster.sh b/networks/add-cluster.sh deleted file mode 100755 index a8936a099f..0000000000 --- a/networks/add-cluster.sh +++ /dev/null @@ -1,25 +0,0 @@ -#!/bin/sh -# add-cluster - example make call to add a set of nodes to an existing testnet in AWS -# WARNING: Run it from the current directory - it uses relative paths to ship the binary and the genesis.json,config.toml files - -if [ $# -ne 4 ]; then - echo "Usage: ./add-cluster.sh " - exit 1 -fi -set -eux - -# The testnet name is the same on all nodes -export TESTNET_NAME=$1 -export CLUSTER_NAME=$2 -export REGION_LIMIT=$3 -export SERVERS=$4 - -# Build the AWS full nodes -rm -rf remote/ansible/keys -make fullnodes-start - -# Save the private key seed words from the nodes -SEEDFOLDER="${TESTNET_NAME}-${CLUSTER_NAME}-seedwords" -mkdir -p "${SEEDFOLDER}" -test ! -f "${SEEDFOLDER}/node0" && mv remote/ansible/keys/* "${SEEDFOLDER}" - diff --git a/networks/add-datadog.sh b/networks/add-datadog.sh deleted file mode 100755 index 6432cc9e4e..0000000000 --- a/networks/add-datadog.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/sh -# add-datadog - add datadog agent to a set of nodes - -if [ $# -ne 2 ]; then - echo "Usage: ./add-datadog.sh " - exit 1 -fi -set -eux - -export TESTNET_NAME=$1 -export CLUSTER_NAME=$2 - -make install-datadog - diff --git a/networks/del-cluster.sh b/networks/del-cluster.sh deleted file mode 100755 index 0c4dec8d15..0000000000 --- a/networks/del-cluster.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/sh -# del-cluster - example make call to delete a set of nodes on an existing testnet in AWS - -if [ $# -ne 1 ]; then - echo "Usage: ./add-cluster.sh " - exit 1 -fi -set -eux - -export CLUSTER_NAME=$1 - -# Delete the AWS nodes -make fullnodes-stop - diff --git a/networks/del-datadog.sh b/networks/del-datadog.sh deleted file mode 100755 index c9bf335268..0000000000 --- a/networks/del-datadog.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/sh -# del-datadog - aremove datadog agent from a set of nodes - -if [ $# -ne 1 ]; then - echo "Usage: ./del-datadog.sh " - exit 1 -fi -set -eux - -export CLUSTER_NAME=$1 - -make remove-datadog - diff --git a/networks/list.sh b/networks/list.sh deleted file mode 100755 index fd1b132faa..0000000000 --- a/networks/list.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/sh -# list - list the IPs of a set of nodes - -if [ $# -ne 1 ]; then - echo "Usage: ./list.sh " - exit 1 -fi -set -eux - -export CLUSTER_NAME=$1 - -make list - diff --git a/networks/local/Makefile b/networks/local/Makefile deleted file mode 100644 index c707a168ee..0000000000 --- a/networks/local/Makefile +++ /dev/null @@ -1,7 +0,0 @@ -# Makefile for the "gaiadnode" docker image. - -all: - docker build --tag tendermint/gaiadnode gaiadnode - -.PHONY: all - diff --git a/networks/local/gaiadnode/Dockerfile b/networks/local/gaiadnode/Dockerfile deleted file mode 100644 index d82036a460..0000000000 --- a/networks/local/gaiadnode/Dockerfile +++ /dev/null @@ -1,16 +0,0 @@ -FROM alpine:3.7 -MAINTAINER Greg Szabo - -RUN apk update && \ - apk upgrade && \ - apk --no-cache add curl jq file - -VOLUME [ /gaiad ] -WORKDIR /gaiad -EXPOSE 26656 26657 -ENTRYPOINT ["/usr/bin/wrapper.sh"] -CMD ["start"] -STOPSIGNAL SIGTERM - -COPY wrapper.sh /usr/bin/wrapper.sh - diff --git a/networks/local/gaiadnode/wrapper.sh b/networks/local/gaiadnode/wrapper.sh deleted file mode 100755 index b3e90a2a0c..0000000000 --- a/networks/local/gaiadnode/wrapper.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env sh - -## -## Input parameters -## -BINARY=/gaiad/${BINARY:-gaiad} -ID=${ID:-0} -LOG=${LOG:-gaiad.log} - -## -## Assert linux binary -## -if ! [ -f "${BINARY}" ]; then - echo "The binary $(basename "${BINARY}") cannot be found. Please add the binary to the shared folder. Please use the BINARY environment variable if the name of the binary is not 'gaiad' E.g.: -e BINARY=gaiad_my_test_version" - exit 1 -fi -BINARY_CHECK="$(file "$BINARY" | grep 'ELF 64-bit LSB executable, x86-64')" -if [ -z "${BINARY_CHECK}" ]; then - echo "Binary needs to be OS linux, ARCH amd64" - exit 1 -fi - -## -## Run binary with all parameters -## -export GAIADHOME="/gaiad/node${ID}/gaiad" - -if [ -d "`dirname ${GAIADHOME}/${LOG}`" ]; then - "$BINARY" --home "$GAIADHOME" "$@" | tee "${GAIADHOME}/${LOG}" -else - "$BINARY" --home "$GAIADHOME" "$@" -fi - -chmod 777 -R /gaiad - diff --git a/networks/new-testnet.sh b/networks/new-testnet.sh deleted file mode 100755 index ae7b73deab..0000000000 --- a/networks/new-testnet.sh +++ /dev/null @@ -1,30 +0,0 @@ -#!/bin/sh -# new-testnet - example make call to create a new set of validator nodes in AWS -# WARNING: Run it from the current directory - it uses relative paths to ship the binary - -if [ $# -ne 4 ]; then - echo "Usage: ./new-testnet.sh " - exit 1 -fi -set -eux - -if [ -z "`file ../build/gaiad | grep 'ELF 64-bit'`" ]; then - # Build the linux binary we're going to ship to the nodes - make -C .. build-linux -fi - -# The testnet name is the same on all nodes -export TESTNET_NAME=$1 -export CLUSTER_NAME=$2 -export REGION_LIMIT=$3 -export SERVERS=$4 - -# Build the AWS validator nodes and extract the genesis.json and config.toml from one of them -rm -rf remote/ansible/keys -make validators-start extract-config - -# Save the private key seed words from the validators -SEEDFOLDER="${TESTNET_NAME}-${CLUSTER_NAME}-seedwords" -mkdir -p "${SEEDFOLDER}" -test ! -f "${SEEDFOLDER}/node0" && mv remote/ansible/keys/* "${SEEDFOLDER}" - diff --git a/networks/remote/ansible/.gitignore b/networks/remote/ansible/.gitignore deleted file mode 100644 index bebb9186b3..0000000000 --- a/networks/remote/ansible/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -*.retry -files/* -keys/* diff --git a/networks/remote/ansible/add-lcd.yml b/networks/remote/ansible/add-lcd.yml deleted file mode 100644 index bdc0703487..0000000000 --- a/networks/remote/ansible/add-lcd.yml +++ /dev/null @@ -1,8 +0,0 @@ ---- - -- hosts: all - any_errors_fatal: true - gather_facts: no - roles: - - add-lcd - diff --git a/networks/remote/ansible/clear-config.yml b/networks/remote/ansible/clear-config.yml deleted file mode 100644 index 80831e75c2..0000000000 --- a/networks/remote/ansible/clear-config.yml +++ /dev/null @@ -1,8 +0,0 @@ ---- - -- hosts: all - any_errors_fatal: true - gather_facts: no - roles: - - clear-config - diff --git a/networks/remote/ansible/extract-config.yml b/networks/remote/ansible/extract-config.yml deleted file mode 100644 index d901bb6980..0000000000 --- a/networks/remote/ansible/extract-config.yml +++ /dev/null @@ -1,8 +0,0 @@ ---- - -- hosts: all - any_errors_fatal: true - gather_facts: no - roles: - - extract-config - diff --git a/networks/remote/ansible/increase-openfiles.yml b/networks/remote/ansible/increase-openfiles.yml deleted file mode 100644 index 1adcb821c1..0000000000 --- a/networks/remote/ansible/increase-openfiles.yml +++ /dev/null @@ -1,8 +0,0 @@ ---- - -- hosts: all - any_errors_fatal: true - gather_facts: no - roles: - - increase-openfiles - diff --git a/networks/remote/ansible/install-datadog-agent.yml b/networks/remote/ansible/install-datadog-agent.yml deleted file mode 100644 index b88600eae9..0000000000 --- a/networks/remote/ansible/install-datadog-agent.yml +++ /dev/null @@ -1,12 +0,0 @@ ---- - -#DD_API_KEY,TESTNET_NAME,CLUSTER_NAME required - -- hosts: all - any_errors_fatal: true - gather_facts: no - roles: - - setup-journald - - install-datadog-agent - - update-datadog-agent - diff --git a/networks/remote/ansible/inventory/COPYING b/networks/remote/ansible/inventory/COPYING deleted file mode 100644 index 10926e87f1..0000000000 --- a/networks/remote/ansible/inventory/COPYING +++ /dev/null @@ -1,675 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - 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. - - - Copyright (C) - - 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 . - -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: - - Copyright (C) - 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 -. - - 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 -. - diff --git a/networks/remote/ansible/inventory/digital_ocean.ini b/networks/remote/ansible/inventory/digital_ocean.ini deleted file mode 100644 index b809554b20..0000000000 --- a/networks/remote/ansible/inventory/digital_ocean.ini +++ /dev/null @@ -1,34 +0,0 @@ -# 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 = {} diff --git a/networks/remote/ansible/inventory/digital_ocean.py b/networks/remote/ansible/inventory/digital_ocean.py deleted file mode 100755 index 24ba64370e..0000000000 --- a/networks/remote/ansible/inventory/digital_ocean.py +++ /dev/null @@ -1,471 +0,0 @@ -#!/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 -# -# 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 . - -###################################################################### - -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() diff --git a/networks/remote/ansible/inventory/ec2.ini b/networks/remote/ansible/inventory/ec2.ini deleted file mode 100644 index e11a69cc16..0000000000 --- a/networks/remote/ansible/inventory/ec2.ini +++ /dev/null @@ -1,209 +0,0 @@ -# Ansible EC2 external inventory script settings -# - -[ec2] - -# to talk to a private eucalyptus instance uncomment these lines -# and edit edit eucalyptus_host to be the host name of your cloud controller -#eucalyptus = True -#eucalyptus_host = clc.cloud.domain.org - -# AWS regions to make calls to. Set this to 'all' to make request to all regions -# in AWS and merge the results together. Alternatively, set this to a comma -# separated list of regions. E.g. 'us-east-1,us-west-1,us-west-2' and do not -# provide the 'regions_exclude' option. If this is set to 'auto', AWS_REGION or -# AWS_DEFAULT_REGION environment variable will be read to determine the region. -regions = all -regions_exclude = us-gov-west-1, cn-north-1 - -# When generating inventory, Ansible needs to know how to address a server. -# Each EC2 instance has a lot of variables associated with it. Here is the list: -# http://docs.pythonboto.org/en/latest/ref/ec2.html#module-boto.ec2.instance -# Below are 2 variables that are used as the address of a server: -# - destination_variable -# - vpc_destination_variable - -# This is the normal destination variable to use. If you are running Ansible -# from outside EC2, then 'public_dns_name' makes the most sense. If you are -# running Ansible from within EC2, then perhaps you want to use the internal -# address, and should set this to 'private_dns_name'. The key of an EC2 tag -# may optionally be used; however the boto instance variables hold precedence -# in the event of a collision. -destination_variable = public_dns_name - -# This allows you to override the inventory_name with an ec2 variable, instead -# of using the destination_variable above. Addressing (aka ansible_ssh_host) -# will still use destination_variable. Tags should be written as 'tag_TAGNAME'. -#hostname_variable = tag_Name - -# For server inside a VPC, using DNS names may not make sense. When an instance -# has 'subnet_id' set, this variable is used. If the subnet is public, setting -# this to 'ip_address' will return the public IP address. For instances in a -# private subnet, this should be set to 'private_ip_address', and Ansible must -# be run from within EC2. The key of an EC2 tag may optionally be used; however -# the boto instance variables hold precedence in the event of a collision. -# WARNING: - instances that are in the private vpc, _without_ public ip address -# will not be listed in the inventory until You set: -# vpc_destination_variable = private_ip_address -vpc_destination_variable = ip_address - -# The following two settings allow flexible ansible host naming based on a -# python format string and a comma-separated list of ec2 tags. Note that: -# -# 1) If the tags referenced are not present for some instances, empty strings -# will be substituted in the format string. -# 2) This overrides both destination_variable and vpc_destination_variable. -# -#destination_format = {0}.{1}.example.com -#destination_format_tags = Name,environment - -# To tag instances on EC2 with the resource records that point to them from -# Route53, set 'route53' to True. -route53 = False - -# To use Route53 records as the inventory hostnames, uncomment and set -# to equal the domain name you wish to use. You must also have 'route53' (above) -# set to True. -# route53_hostnames = .example.com - -# To exclude RDS instances from the inventory, uncomment and set to False. -#rds = False - -# To exclude ElastiCache instances from the inventory, uncomment and set to False. -#elasticache = False - -# Additionally, you can specify the list of zones to exclude looking up in -# 'route53_excluded_zones' as a comma-separated list. -# route53_excluded_zones = samplezone1.com, samplezone2.com - -# By default, only EC2 instances in the 'running' state are returned. Set -# 'all_instances' to True to return all instances regardless of state. -all_instances = False - -# By default, only EC2 instances in the 'running' state are returned. Specify -# EC2 instance states to return as a comma-separated list. This -# option is overridden when 'all_instances' is True. -# instance_states = pending, running, shutting-down, terminated, stopping, stopped - -# By default, only RDS instances in the 'available' state are returned. Set -# 'all_rds_instances' to True return all RDS instances regardless of state. -all_rds_instances = False - -# Include RDS cluster information (Aurora etc.) -include_rds_clusters = False - -# By default, only ElastiCache clusters and nodes in the 'available' state -# are returned. Set 'all_elasticache_clusters' and/or 'all_elastic_nodes' -# to True return all ElastiCache clusters and nodes, regardless of state. -# -# Note that all_elasticache_nodes only applies to listed clusters. That means -# if you set all_elastic_clusters to false, no node will be return from -# unavailable clusters, regardless of the state and to what you set for -# all_elasticache_nodes. -all_elasticache_replication_groups = False -all_elasticache_clusters = False -all_elasticache_nodes = False - -# API calls to EC2 are 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. Two files -# will be written to this directory: -# - ansible-ec2.cache -# - ansible-ec2.index -cache_path = ~/.ansible/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. -# To disable the cache, set this value to 0 -cache_max_age = 300 - -# Organize groups into a nested/hierarchy instead of a flat namespace. -nested_groups = False - -# Replace - tags when creating groups to avoid issues with ansible -replace_dash_in_groups = True - -# If set to true, any tag of the form "a,b,c" is expanded into a list -# and the results are used to create additional tag_* inventory groups. -expand_csv_tags = False - -# The EC2 inventory output can become very large. To manage its size, -# configure which groups should be created. -group_by_instance_id = True -group_by_region = True -group_by_availability_zone = True -group_by_aws_account = False -group_by_ami_id = True -group_by_instance_type = True -group_by_instance_state = False -group_by_key_pair = True -group_by_vpc_id = True -group_by_security_group = True -group_by_tag_keys = True -group_by_tag_none = True -group_by_route53_names = True -group_by_rds_engine = True -group_by_rds_parameter_group = True -group_by_elasticache_engine = True -group_by_elasticache_cluster = True -group_by_elasticache_parameter_group = True -group_by_elasticache_replication_group = True - -# If you only want to include hosts that match a certain regular expression -# pattern_include = staging-* - -# If you want to exclude any hosts that match a certain regular expression -# pattern_exclude = staging-* - -# Instance filters can be used to control which instances are retrieved for -# inventory. For the full list of possible filters, please read the EC2 API -# docs: http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeInstances.html#query-DescribeInstances-filters -# Filters are key/value pairs separated by '=', to list multiple filters use -# a list separated by commas. See examples below. - -# If you want to apply multiple filters simultaneously, set stack_filters to -# True. Default behaviour is to combine the results of all filters. Stacking -# allows the use of multiple conditions to filter down, for example by -# environment and type of host. -stack_filters = False - -# Retrieve only instances with (key=value) env=staging tag -# instance_filters = tag:env=staging - -# Retrieve only instances with role=webservers OR role=dbservers tag -# instance_filters = tag:role=webservers,tag:role=dbservers - -# Retrieve only t1.micro instances OR instances with tag env=staging -# instance_filters = instance-type=t1.micro,tag:env=staging - -# You can use wildcards in filter values also. Below will list instances which -# tag Name value matches webservers1* -# (ex. webservers15, webservers1a, webservers123 etc) -# instance_filters = tag:Name=webservers1* - -# An IAM role can be assumed, so all requests are run as that role. -# This can be useful for connecting across different accounts, or to limit user -# access -# iam_role = role-arn - -# A boto configuration profile may be used to separate out credentials -# see http://boto.readthedocs.org/en/latest/boto_config_tut.html -# boto_profile = some-boto-profile-name - - -[credentials] - -# The AWS credentials can optionally be specified here. Credentials specified -# here are ignored if the environment variable AWS_ACCESS_KEY_ID or -# AWS_PROFILE is set, or if the boto_profile property above is set. -# -# Supplying AWS credentials here is not recommended, as it introduces -# non-trivial security concerns. When going down this route, please make sure -# to set access permissions for this file correctly, e.g. handle it the same -# way as you would a private SSH key. -# -# Unlike the boto and AWS configure files, this section does not support -# profiles. -# -# aws_access_key_id = AXXXXXXXXXXXXXX -# aws_secret_access_key = XXXXXXXXXXXXXXXXXXX -# aws_security_token = XXXXXXXXXXXXXXXXXXXXXXXXXXXX diff --git a/networks/remote/ansible/inventory/ec2.py b/networks/remote/ansible/inventory/ec2.py deleted file mode 100755 index 9614c5fe91..0000000000 --- a/networks/remote/ansible/inventory/ec2.py +++ /dev/null @@ -1,1595 +0,0 @@ -#!/usr/bin/env python - -''' -EC2 external inventory script -================================= - -Generates inventory that Ansible can understand by making API request to -AWS EC2 using the Boto library. - -NOTE: This script assumes Ansible is being executed where the environment -variables needed for Boto have already been set: - export AWS_ACCESS_KEY_ID='AK123' - export AWS_SECRET_ACCESS_KEY='abc123' - -optional region environement variable if region is 'auto' - -This script also assumes there is an ec2.ini file alongside it. To specify a -different path to ec2.ini, define the EC2_INI_PATH environment variable: - - export EC2_INI_PATH=/path/to/my_ec2.ini - -If you're using eucalyptus you need to set the above variables and -you need to define: - - export EC2_URL=http://hostname_of_your_cc:port/services/Eucalyptus - -If you're using boto profiles (requires boto>=2.24.0) you can choose a profile -using the --boto-profile command line argument (e.g. ec2.py --boto-profile prod) or using -the AWS_PROFILE variable: - - AWS_PROFILE=prod ansible-playbook -i ec2.py myplaybook.yml - -For more details, see: http://docs.pythonboto.org/en/latest/boto_config_tut.html - -When run against a specific host, this script returns the following variables: - - ec2_ami_launch_index - - ec2_architecture - - ec2_association - - ec2_attachTime - - ec2_attachment - - ec2_attachmentId - - ec2_block_devices - - ec2_client_token - - ec2_deleteOnTermination - - ec2_description - - ec2_deviceIndex - - ec2_dns_name - - ec2_eventsSet - - ec2_group_name - - ec2_hypervisor - - ec2_id - - ec2_image_id - - ec2_instanceState - - ec2_instance_type - - ec2_ipOwnerId - - ec2_ip_address - - ec2_item - - ec2_kernel - - ec2_key_name - - ec2_launch_time - - ec2_monitored - - ec2_monitoring - - ec2_networkInterfaceId - - ec2_ownerId - - ec2_persistent - - ec2_placement - - ec2_platform - - ec2_previous_state - - ec2_private_dns_name - - ec2_private_ip_address - - ec2_publicIp - - ec2_public_dns_name - - ec2_ramdisk - - ec2_reason - - ec2_region - - ec2_requester_id - - ec2_root_device_name - - ec2_root_device_type - - ec2_security_group_ids - - ec2_security_group_names - - ec2_shutdown_state - - ec2_sourceDestCheck - - ec2_spot_instance_request_id - - ec2_state - - ec2_state_code - - ec2_state_reason - - ec2_status - - ec2_subnet_id - - ec2_tenancy - - ec2_virtualization_type - - ec2_vpc_id - -These variables are pulled out of a boto.ec2.instance object. There is a lack of -consistency with variable spellings (camelCase and underscores) since this -just loops through all variables the object exposes. It is preferred to use the -ones with underscores when multiple exist. - -In addition, if an instance has AWS Tags associated with it, each tag is a new -variable named: - - ec2_tag_[Key] = [Value] - -Security groups are comma-separated in 'ec2_security_group_ids' and -'ec2_security_group_names'. -''' - -# (c) 2012, Peter Sankauskas -# -# 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 . - -###################################################################### - -import sys -import os -import argparse -import re -from time import time -import boto -from boto import ec2 -from boto import rds -from boto import elasticache -from boto import route53 -from boto import sts -import six - -from ansible.module_utils import ec2 as ec2_utils - -HAS_BOTO3 = False -try: - import boto3 - HAS_BOTO3 = True -except ImportError: - pass - -from six.moves import configparser -from collections import defaultdict - -try: - import json -except ImportError: - import simplejson as json - - -class Ec2Inventory(object): - - def _empty_inventory(self): - return {"_meta": {"hostvars": {}}} - - def __init__(self): - ''' Main execution path ''' - - # Inventory grouped by instance IDs, tags, security groups, regions, - # and availability zones - self.inventory = self._empty_inventory() - - self.aws_account_id = None - - # Index of hostname (address) to instance ID - self.index = {} - - # Boto profile to use (if any) - self.boto_profile = None - - # AWS credentials. - self.credentials = {} - - # Read settings and parse CLI arguments - self.parse_cli_args() - self.read_settings() - - # Make sure that profile_name is not passed at all if not set - # as pre 2.24 boto will fall over otherwise - if self.boto_profile: - if not hasattr(boto.ec2.EC2Connection, 'profile_name'): - self.fail_with_error("boto version must be >= 2.24 to use profile") - - # Cache - if self.args.refresh_cache: - self.do_api_calls_update_cache() - elif not self.is_cache_valid(): - self.do_api_calls_update_cache() - - # Data to print - if self.args.host: - data_to_print = self.get_host_info() - - elif self.args.list: - # Display list of instances for inventory - if self.inventory == self._empty_inventory(): - data_to_print = self.get_inventory_from_cache() - else: - data_to_print = self.json_format_dict(self.inventory, True) - - print(data_to_print) - - def is_cache_valid(self): - ''' Determines if the cache files have expired, or if it is still valid ''' - - if os.path.isfile(self.cache_path_cache): - mod_time = os.path.getmtime(self.cache_path_cache) - current_time = time() - if (mod_time + self.cache_max_age) > current_time: - if os.path.isfile(self.cache_path_index): - return True - - return False - - def read_settings(self): - ''' Reads the settings from the ec2.ini file ''' - - scriptbasename = __file__ - scriptbasename = os.path.basename(scriptbasename) - scriptbasename = scriptbasename.replace('.py', '') - - defaults = { - 'ec2': { - 'ini_path': os.path.join(os.path.dirname(__file__), '%s.ini' % scriptbasename) - } - } - - if six.PY3: - config = configparser.ConfigParser() - else: - config = configparser.SafeConfigParser() - ec2_ini_path = os.environ.get('EC2_INI_PATH', defaults['ec2']['ini_path']) - ec2_ini_path = os.path.expanduser(os.path.expandvars(ec2_ini_path)) - config.read(ec2_ini_path) - - # is eucalyptus? - self.eucalyptus_host = None - self.eucalyptus = False - if config.has_option('ec2', 'eucalyptus'): - self.eucalyptus = config.getboolean('ec2', 'eucalyptus') - if self.eucalyptus and config.has_option('ec2', 'eucalyptus_host'): - self.eucalyptus_host = config.get('ec2', 'eucalyptus_host') - - # Regions - self.regions = [] - configRegions = config.get('ec2', 'regions') - if (configRegions == 'all'): - if self.eucalyptus_host: - self.regions.append(boto.connect_euca(host=self.eucalyptus_host).region.name, **self.credentials) - else: - configRegions_exclude = config.get('ec2', 'regions_exclude') - for regionInfo in ec2.regions(): - if regionInfo.name not in configRegions_exclude: - self.regions.append(regionInfo.name) - else: - self.regions = configRegions.split(",") - if 'auto' in self.regions: - env_region = os.environ.get('AWS_REGION') - if env_region is None: - env_region = os.environ.get('AWS_DEFAULT_REGION') - self.regions = [env_region] - - # Destination addresses - self.destination_variable = config.get('ec2', 'destination_variable') - self.vpc_destination_variable = config.get('ec2', 'vpc_destination_variable') - - if config.has_option('ec2', 'hostname_variable'): - self.hostname_variable = config.get('ec2', 'hostname_variable') - else: - self.hostname_variable = None - - if config.has_option('ec2', 'destination_format') and \ - config.has_option('ec2', 'destination_format_tags'): - self.destination_format = config.get('ec2', 'destination_format') - self.destination_format_tags = config.get('ec2', 'destination_format_tags').split(',') - else: - self.destination_format = None - self.destination_format_tags = None - - # Route53 - self.route53_enabled = config.getboolean('ec2', 'route53') - if config.has_option('ec2', 'route53_hostnames'): - self.route53_hostnames = config.get('ec2', 'route53_hostnames') - else: - self.route53_hostnames = None - self.route53_excluded_zones = [] - if config.has_option('ec2', 'route53_excluded_zones'): - self.route53_excluded_zones.extend( - config.get('ec2', 'route53_excluded_zones', '').split(',')) - - # Include RDS instances? - self.rds_enabled = True - if config.has_option('ec2', 'rds'): - self.rds_enabled = config.getboolean('ec2', 'rds') - - # Include RDS cluster instances? - if config.has_option('ec2', 'include_rds_clusters'): - self.include_rds_clusters = config.getboolean('ec2', 'include_rds_clusters') - else: - self.include_rds_clusters = False - - # Include ElastiCache instances? - self.elasticache_enabled = True - if config.has_option('ec2', 'elasticache'): - self.elasticache_enabled = config.getboolean('ec2', 'elasticache') - - # Return all EC2 instances? - if config.has_option('ec2', 'all_instances'): - self.all_instances = config.getboolean('ec2', 'all_instances') - else: - self.all_instances = False - - # Instance states to be gathered in inventory. Default is 'running'. - # Setting 'all_instances' to 'yes' overrides this option. - ec2_valid_instance_states = [ - 'pending', - 'running', - 'shutting-down', - 'terminated', - 'stopping', - 'stopped' - ] - self.ec2_instance_states = [] - if self.all_instances: - self.ec2_instance_states = ec2_valid_instance_states - elif config.has_option('ec2', 'instance_states'): - for instance_state in config.get('ec2', 'instance_states').split(','): - instance_state = instance_state.strip() - if instance_state not in ec2_valid_instance_states: - continue - self.ec2_instance_states.append(instance_state) - else: - self.ec2_instance_states = ['running'] - - # Return all RDS instances? (if RDS is enabled) - if config.has_option('ec2', 'all_rds_instances') and self.rds_enabled: - self.all_rds_instances = config.getboolean('ec2', 'all_rds_instances') - else: - self.all_rds_instances = False - - # Return all ElastiCache replication groups? (if ElastiCache is enabled) - if config.has_option('ec2', 'all_elasticache_replication_groups') and self.elasticache_enabled: - self.all_elasticache_replication_groups = config.getboolean('ec2', 'all_elasticache_replication_groups') - else: - self.all_elasticache_replication_groups = False - - # Return all ElastiCache clusters? (if ElastiCache is enabled) - if config.has_option('ec2', 'all_elasticache_clusters') and self.elasticache_enabled: - self.all_elasticache_clusters = config.getboolean('ec2', 'all_elasticache_clusters') - else: - self.all_elasticache_clusters = False - - # Return all ElastiCache nodes? (if ElastiCache is enabled) - if config.has_option('ec2', 'all_elasticache_nodes') and self.elasticache_enabled: - self.all_elasticache_nodes = config.getboolean('ec2', 'all_elasticache_nodes') - else: - self.all_elasticache_nodes = False - - # boto configuration profile (prefer CLI argument then environment variables then config file) - self.boto_profile = self.args.boto_profile or os.environ.get('AWS_PROFILE') - if config.has_option('ec2', 'boto_profile') and not self.boto_profile: - self.boto_profile = config.get('ec2', 'boto_profile') - - # AWS credentials (prefer environment variables) - if not (self.boto_profile or os.environ.get('AWS_ACCESS_KEY_ID') or - os.environ.get('AWS_PROFILE')): - if config.has_option('credentials', 'aws_access_key_id'): - aws_access_key_id = config.get('credentials', 'aws_access_key_id') - else: - aws_access_key_id = None - if config.has_option('credentials', 'aws_secret_access_key'): - aws_secret_access_key = config.get('credentials', 'aws_secret_access_key') - else: - aws_secret_access_key = None - if config.has_option('credentials', 'aws_security_token'): - aws_security_token = config.get('credentials', 'aws_security_token') - else: - aws_security_token = None - if aws_access_key_id: - self.credentials = { - 'aws_access_key_id': aws_access_key_id, - 'aws_secret_access_key': aws_secret_access_key - } - if aws_security_token: - self.credentials['security_token'] = aws_security_token - - # Cache related - cache_dir = os.path.expanduser(config.get('ec2', 'cache_path')) - if self.boto_profile: - cache_dir = os.path.join(cache_dir, 'profile_' + self.boto_profile) - if not os.path.exists(cache_dir): - os.makedirs(cache_dir) - - cache_name = 'ansible-ec2' - cache_id = self.boto_profile or os.environ.get('AWS_ACCESS_KEY_ID', self.credentials.get('aws_access_key_id')) - if cache_id: - cache_name = '%s-%s' % (cache_name, cache_id) - self.cache_path_cache = os.path.join(cache_dir, "%s.cache" % cache_name) - self.cache_path_index = os.path.join(cache_dir, "%s.index" % cache_name) - self.cache_max_age = config.getint('ec2', 'cache_max_age') - - if config.has_option('ec2', 'expand_csv_tags'): - self.expand_csv_tags = config.getboolean('ec2', 'expand_csv_tags') - else: - self.expand_csv_tags = False - - # Configure nested groups instead of flat namespace. - if config.has_option('ec2', 'nested_groups'): - self.nested_groups = config.getboolean('ec2', 'nested_groups') - else: - self.nested_groups = False - - # Replace dash or not in group names - if config.has_option('ec2', 'replace_dash_in_groups'): - self.replace_dash_in_groups = config.getboolean('ec2', 'replace_dash_in_groups') - else: - self.replace_dash_in_groups = True - - # IAM role to assume for connection - if config.has_option('ec2', 'iam_role'): - self.iam_role = config.get('ec2', 'iam_role') - else: - self.iam_role = None - - # Configure which groups should be created. - group_by_options = [ - 'group_by_instance_id', - 'group_by_region', - 'group_by_availability_zone', - 'group_by_ami_id', - 'group_by_instance_type', - 'group_by_instance_state', - 'group_by_key_pair', - 'group_by_vpc_id', - 'group_by_security_group', - 'group_by_tag_keys', - 'group_by_tag_none', - 'group_by_route53_names', - 'group_by_rds_engine', - 'group_by_rds_parameter_group', - 'group_by_elasticache_engine', - 'group_by_elasticache_cluster', - 'group_by_elasticache_parameter_group', - 'group_by_elasticache_replication_group', - 'group_by_aws_account', - ] - for option in group_by_options: - if config.has_option('ec2', option): - setattr(self, option, config.getboolean('ec2', option)) - else: - setattr(self, option, True) - - # Do we need to just include hosts that match a pattern? - try: - pattern_include = config.get('ec2', 'pattern_include') - if pattern_include and len(pattern_include) > 0: - self.pattern_include = re.compile(pattern_include) - else: - self.pattern_include = None - except configparser.NoOptionError: - self.pattern_include = None - - # Do we need to exclude hosts that match a pattern? - try: - pattern_exclude = config.get('ec2', 'pattern_exclude') - if pattern_exclude and len(pattern_exclude) > 0: - self.pattern_exclude = re.compile(pattern_exclude) - else: - self.pattern_exclude = None - except configparser.NoOptionError: - self.pattern_exclude = None - - # Do we want to stack multiple filters? - if config.has_option('ec2', 'stack_filters'): - self.stack_filters = config.getboolean('ec2', 'stack_filters') - else: - self.stack_filters = False - - # Instance filters (see boto and EC2 API docs). Ignore invalid filters. - self.ec2_instance_filters = defaultdict(list) - if config.has_option('ec2', 'instance_filters'): - - filters = [f for f in config.get('ec2', 'instance_filters').split(',') if f] - - for instance_filter in filters: - instance_filter = instance_filter.strip() - if not instance_filter or '=' not in instance_filter: - continue - filter_key, filter_value = [x.strip() for x in instance_filter.split('=', 1)] - if not filter_key: - continue - self.ec2_instance_filters[filter_key].append(filter_value) - - def parse_cli_args(self): - ''' Command line argument processing ''' - - parser = argparse.ArgumentParser(description='Produce an Ansible Inventory file based on EC2') - parser.add_argument('--list', action='store_true', default=True, - help='List instances (default: True)') - parser.add_argument('--host', action='store', - help='Get all the variables about a specific instance') - parser.add_argument('--refresh-cache', action='store_true', default=False, - help='Force refresh of cache by making API requests to EC2 (default: False - use cache files)') - parser.add_argument('--profile', '--boto-profile', action='store', dest='boto_profile', - help='Use boto profile for connections to EC2') - self.args = parser.parse_args() - - def do_api_calls_update_cache(self): - ''' Do API calls to each region, and save data in cache files ''' - - if self.route53_enabled: - self.get_route53_records() - - for region in self.regions: - self.get_instances_by_region(region) - if self.rds_enabled: - self.get_rds_instances_by_region(region) - if self.elasticache_enabled: - self.get_elasticache_clusters_by_region(region) - self.get_elasticache_replication_groups_by_region(region) - if self.include_rds_clusters: - self.include_rds_clusters_by_region(region) - - self.write_to_cache(self.inventory, self.cache_path_cache) - self.write_to_cache(self.index, self.cache_path_index) - - def connect(self, region): - ''' create connection to api server''' - if self.eucalyptus: - conn = boto.connect_euca(host=self.eucalyptus_host, **self.credentials) - conn.APIVersion = '2010-08-31' - else: - conn = self.connect_to_aws(ec2, region) - return conn - - def boto_fix_security_token_in_profile(self, connect_args): - ''' monkey patch for boto issue boto/boto#2100 ''' - profile = 'profile ' + self.boto_profile - if boto.config.has_option(profile, 'aws_security_token'): - connect_args['security_token'] = boto.config.get(profile, 'aws_security_token') - return connect_args - - def connect_to_aws(self, module, region): - connect_args = self.credentials - - # only pass the profile name if it's set (as it is not supported by older boto versions) - if self.boto_profile: - connect_args['profile_name'] = self.boto_profile - self.boto_fix_security_token_in_profile(connect_args) - - if self.iam_role: - sts_conn = sts.connect_to_region(region, **connect_args) - role = sts_conn.assume_role(self.iam_role, 'ansible_dynamic_inventory') - connect_args['aws_access_key_id'] = role.credentials.access_key - connect_args['aws_secret_access_key'] = role.credentials.secret_key - connect_args['security_token'] = role.credentials.session_token - - conn = module.connect_to_region(region, **connect_args) - # connect_to_region will fail "silently" by returning None if the region name is wrong or not supported - if conn is None: - self.fail_with_error("region name: %s likely not supported, or AWS is down. connection to region failed." % region) - return conn - - def get_instances_by_region(self, region): - ''' Makes an AWS EC2 API call to the list of instances in a particular - region ''' - - try: - conn = self.connect(region) - reservations = [] - if self.ec2_instance_filters: - if self.stack_filters: - filters_dict = {} - for filter_key, filter_values in self.ec2_instance_filters.items(): - filters_dict[filter_key] = filter_values - reservations.extend(conn.get_all_instances(filters=filters_dict)) - else: - for filter_key, filter_values in self.ec2_instance_filters.items(): - reservations.extend(conn.get_all_instances(filters={filter_key: filter_values})) - else: - reservations = conn.get_all_instances() - - # Pull the tags back in a second step - # AWS are on record as saying that the tags fetched in the first `get_all_instances` request are not - # reliable and may be missing, and the only way to guarantee they are there is by calling `get_all_tags` - instance_ids = [] - for reservation in reservations: - instance_ids.extend([instance.id for instance in reservation.instances]) - - max_filter_value = 199 - tags = [] - for i in range(0, len(instance_ids), max_filter_value): - tags.extend(conn.get_all_tags(filters={'resource-type': 'instance', 'resource-id': instance_ids[i:i + max_filter_value]})) - - tags_by_instance_id = defaultdict(dict) - for tag in tags: - tags_by_instance_id[tag.res_id][tag.name] = tag.value - - if (not self.aws_account_id) and reservations: - self.aws_account_id = reservations[0].owner_id - - for reservation in reservations: - for instance in reservation.instances: - instance.tags = tags_by_instance_id[instance.id] - self.add_instance(instance, region) - - except boto.exception.BotoServerError as e: - if e.error_code == 'AuthFailure': - error = self.get_auth_error_message() - else: - backend = 'Eucalyptus' if self.eucalyptus else 'AWS' - error = "Error connecting to %s backend.\n%s" % (backend, e.message) - self.fail_with_error(error, 'getting EC2 instances') - - def get_rds_instances_by_region(self, region): - ''' Makes an AWS API call to the list of RDS instances in a particular - region ''' - - if not HAS_BOTO3: - self.fail_with_error("Working with RDS instances requires boto3 - please install boto3 and try again", - "getting RDS instances") - - client = ec2_utils.boto3_inventory_conn('client', 'rds', region, **self.credentials) - db_instances = client.describe_db_instances() - - try: - conn = self.connect_to_aws(rds, region) - if conn: - marker = None - while True: - instances = conn.get_all_dbinstances(marker=marker) - marker = instances.marker - for index, instance in enumerate(instances): - # Add tags to instances. - instance.arn = db_instances['DBInstances'][index]['DBInstanceArn'] - tags = client.list_tags_for_resource(ResourceName=instance.arn)['TagList'] - instance.tags = {} - for tag in tags: - instance.tags[tag['Key']] = tag['Value'] - - self.add_rds_instance(instance, region) - if not marker: - break - except boto.exception.BotoServerError as e: - error = e.reason - - if e.error_code == 'AuthFailure': - error = self.get_auth_error_message() - if not e.reason == "Forbidden": - error = "Looks like AWS RDS is down:\n%s" % e.message - self.fail_with_error(error, 'getting RDS instances') - - def include_rds_clusters_by_region(self, region): - if not HAS_BOTO3: - self.fail_with_error("Working with RDS clusters requires boto3 - please install boto3 and try again", - "getting RDS clusters") - - client = ec2_utils.boto3_inventory_conn('client', 'rds', region, **self.credentials) - - marker, clusters = '', [] - while marker is not None: - resp = client.describe_db_clusters(Marker=marker) - clusters.extend(resp["DBClusters"]) - marker = resp.get('Marker', None) - - account_id = boto.connect_iam().get_user().arn.split(':')[4] - c_dict = {} - for c in clusters: - # remove these datetime objects as there is no serialisation to json - # currently in place and we don't need the data yet - if 'EarliestRestorableTime' in c: - del c['EarliestRestorableTime'] - if 'LatestRestorableTime' in c: - del c['LatestRestorableTime'] - - if self.ec2_instance_filters == {}: - matches_filter = True - else: - matches_filter = False - - try: - # arn:aws:rds:::: - tags = client.list_tags_for_resource( - ResourceName='arn:aws:rds:' + region + ':' + account_id + ':cluster:' + c['DBClusterIdentifier']) - c['Tags'] = tags['TagList'] - - if self.ec2_instance_filters: - for filter_key, filter_values in self.ec2_instance_filters.items(): - # get AWS tag key e.g. tag:env will be 'env' - tag_name = filter_key.split(":", 1)[1] - # Filter values is a list (if you put multiple values for the same tag name) - matches_filter = any(d['Key'] == tag_name and d['Value'] in filter_values for d in c['Tags']) - - if matches_filter: - # it matches a filter, so stop looking for further matches - break - - except Exception as e: - if e.message.find('DBInstanceNotFound') >= 0: - # AWS RDS bug (2016-01-06) means deletion does not fully complete and leave an 'empty' cluster. - # Ignore errors when trying to find tags for these - pass - - # ignore empty clusters caused by AWS bug - if len(c['DBClusterMembers']) == 0: - continue - elif matches_filter: - c_dict[c['DBClusterIdentifier']] = c - - self.inventory['db_clusters'] = c_dict - - def get_elasticache_clusters_by_region(self, region): - ''' Makes an AWS API call to the list of ElastiCache clusters (with - nodes' info) in a particular region.''' - - # ElastiCache boto module doesn't provide a get_all_intances method, - # that's why we need to call describe directly (it would be called by - # the shorthand method anyway...) - try: - conn = self.connect_to_aws(elasticache, region) - if conn: - # show_cache_node_info = True - # because we also want nodes' information - response = conn.describe_cache_clusters(None, None, None, True) - - except boto.exception.BotoServerError as e: - error = e.reason - - if e.error_code == 'AuthFailure': - error = self.get_auth_error_message() - if not e.reason == "Forbidden": - error = "Looks like AWS ElastiCache is down:\n%s" % e.message - self.fail_with_error(error, 'getting ElastiCache clusters') - - try: - # Boto also doesn't provide wrapper classes to CacheClusters or - # CacheNodes. Because of that we can't make use of the get_list - # method in the AWSQueryConnection. Let's do the work manually - clusters = response['DescribeCacheClustersResponse']['DescribeCacheClustersResult']['CacheClusters'] - - except KeyError as e: - error = "ElastiCache query to AWS failed (unexpected format)." - self.fail_with_error(error, 'getting ElastiCache clusters') - - for cluster in clusters: - self.add_elasticache_cluster(cluster, region) - - def get_elasticache_replication_groups_by_region(self, region): - ''' Makes an AWS API call to the list of ElastiCache replication groups - in a particular region.''' - - # ElastiCache boto module doesn't provide a get_all_intances method, - # that's why we need to call describe directly (it would be called by - # the shorthand method anyway...) - try: - conn = self.connect_to_aws(elasticache, region) - if conn: - response = conn.describe_replication_groups() - - except boto.exception.BotoServerError as e: - error = e.reason - - if e.error_code == 'AuthFailure': - error = self.get_auth_error_message() - if not e.reason == "Forbidden": - error = "Looks like AWS ElastiCache [Replication Groups] is down:\n%s" % e.message - self.fail_with_error(error, 'getting ElastiCache clusters') - - try: - # Boto also doesn't provide wrapper classes to ReplicationGroups - # Because of that we can't make use of the get_list method in the - # AWSQueryConnection. Let's do the work manually - replication_groups = response['DescribeReplicationGroupsResponse']['DescribeReplicationGroupsResult']['ReplicationGroups'] - - except KeyError as e: - error = "ElastiCache [Replication Groups] query to AWS failed (unexpected format)." - self.fail_with_error(error, 'getting ElastiCache clusters') - - for replication_group in replication_groups: - self.add_elasticache_replication_group(replication_group, region) - - def get_auth_error_message(self): - ''' create an informative error message if there is an issue authenticating''' - errors = ["Authentication error retrieving ec2 inventory."] - if None in [os.environ.get('AWS_ACCESS_KEY_ID'), os.environ.get('AWS_SECRET_ACCESS_KEY')]: - errors.append(' - No AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY environment vars found') - else: - errors.append(' - AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment vars found but may not be correct') - - boto_paths = ['/etc/boto.cfg', '~/.boto', '~/.aws/credentials'] - boto_config_found = list(p for p in boto_paths if os.path.isfile(os.path.expanduser(p))) - if len(boto_config_found) > 0: - errors.append(" - Boto configs found at '%s', but the credentials contained may not be correct" % ', '.join(boto_config_found)) - else: - errors.append(" - No Boto config found at any expected location '%s'" % ', '.join(boto_paths)) - - return '\n'.join(errors) - - def fail_with_error(self, err_msg, err_operation=None): - '''log an error to std err for ansible-playbook to consume and exit''' - if err_operation: - err_msg = 'ERROR: "{err_msg}", while: {err_operation}'.format( - err_msg=err_msg, err_operation=err_operation) - sys.stderr.write(err_msg) - sys.exit(1) - - def get_instance(self, region, instance_id): - conn = self.connect(region) - - reservations = conn.get_all_instances([instance_id]) - for reservation in reservations: - for instance in reservation.instances: - return instance - - def add_instance(self, instance, region): - ''' Adds an instance to the inventory and index, as long as it is - addressable ''' - - # Only return instances with desired instance states - if instance.state not in self.ec2_instance_states: - return - - # Select the best destination address - if self.destination_format and self.destination_format_tags: - dest = self.destination_format.format(*[getattr(instance, 'tags').get(tag, '') for tag in self.destination_format_tags]) - elif instance.subnet_id: - dest = getattr(instance, self.vpc_destination_variable, None) - if dest is None: - dest = getattr(instance, 'tags').get(self.vpc_destination_variable, None) - else: - dest = getattr(instance, self.destination_variable, None) - if dest is None: - dest = getattr(instance, 'tags').get(self.destination_variable, None) - - if not dest: - # Skip instances we cannot address (e.g. private VPC subnet) - return - - # Set the inventory name - hostname = None - if self.hostname_variable: - if self.hostname_variable.startswith('tag_'): - hostname = instance.tags.get(self.hostname_variable[4:], None) - else: - hostname = getattr(instance, self.hostname_variable) - - # set the hostname from route53 - if self.route53_enabled and self.route53_hostnames: - route53_names = self.get_instance_route53_names(instance) - for name in route53_names: - if name.endswith(self.route53_hostnames): - hostname = name - - # If we can't get a nice hostname, use the destination address - if not hostname: - hostname = dest - # to_safe strips hostname characters like dots, so don't strip route53 hostnames - elif self.route53_enabled and self.route53_hostnames and hostname.endswith(self.route53_hostnames): - hostname = hostname.lower() - else: - hostname = self.to_safe(hostname).lower() - - # if we only want to include hosts that match a pattern, skip those that don't - if self.pattern_include and not self.pattern_include.match(hostname): - return - - # if we need to exclude hosts that match a pattern, skip those - if self.pattern_exclude and self.pattern_exclude.match(hostname): - return - - # Add to index - self.index[hostname] = [region, instance.id] - - # Inventory: Group by instance ID (always a group of 1) - if self.group_by_instance_id: - self.inventory[instance.id] = [hostname] - if self.nested_groups: - self.push_group(self.inventory, 'instances', instance.id) - - # Inventory: Group by region - if self.group_by_region: - self.push(self.inventory, region, hostname) - if self.nested_groups: - self.push_group(self.inventory, 'regions', region) - - # Inventory: Group by availability zone - if self.group_by_availability_zone: - self.push(self.inventory, instance.placement, hostname) - if self.nested_groups: - if self.group_by_region: - self.push_group(self.inventory, region, instance.placement) - self.push_group(self.inventory, 'zones', instance.placement) - - # Inventory: Group by Amazon Machine Image (AMI) ID - if self.group_by_ami_id: - ami_id = self.to_safe(instance.image_id) - self.push(self.inventory, ami_id, hostname) - if self.nested_groups: - self.push_group(self.inventory, 'images', ami_id) - - # Inventory: Group by instance type - if self.group_by_instance_type: - type_name = self.to_safe('type_' + instance.instance_type) - self.push(self.inventory, type_name, hostname) - if self.nested_groups: - self.push_group(self.inventory, 'types', type_name) - - # Inventory: Group by instance state - if self.group_by_instance_state: - state_name = self.to_safe('instance_state_' + instance.state) - self.push(self.inventory, state_name, hostname) - if self.nested_groups: - self.push_group(self.inventory, 'instance_states', state_name) - - # Inventory: Group by key pair - if self.group_by_key_pair and instance.key_name: - key_name = self.to_safe('key_' + instance.key_name) - self.push(self.inventory, key_name, hostname) - if self.nested_groups: - self.push_group(self.inventory, 'keys', key_name) - - # Inventory: Group by VPC - if self.group_by_vpc_id and instance.vpc_id: - vpc_id_name = self.to_safe('vpc_id_' + instance.vpc_id) - self.push(self.inventory, vpc_id_name, hostname) - if self.nested_groups: - self.push_group(self.inventory, 'vpcs', vpc_id_name) - - # Inventory: Group by security group - if self.group_by_security_group: - try: - for group in instance.groups: - key = self.to_safe("security_group_" + group.name) - self.push(self.inventory, key, hostname) - if self.nested_groups: - self.push_group(self.inventory, 'security_groups', key) - except AttributeError: - self.fail_with_error('\n'.join(['Package boto seems a bit older.', - 'Please upgrade boto >= 2.3.0.'])) - - # Inventory: Group by AWS account ID - if self.group_by_aws_account: - self.push(self.inventory, self.aws_account_id, dest) - if self.nested_groups: - self.push_group(self.inventory, 'accounts', self.aws_account_id) - - # Inventory: Group by tag keys - if self.group_by_tag_keys: - for k, v in instance.tags.items(): - if self.expand_csv_tags and v and ',' in v: - values = map(lambda x: x.strip(), v.split(',')) - else: - values = [v] - - for v in values: - if v: - key = self.to_safe("tag_" + k + "=" + v) - else: - key = self.to_safe("tag_" + k) - self.push(self.inventory, key, hostname) - if self.nested_groups: - self.push_group(self.inventory, 'tags', self.to_safe("tag_" + k)) - if v: - self.push_group(self.inventory, self.to_safe("tag_" + k), key) - - # Inventory: Group by Route53 domain names if enabled - if self.route53_enabled and self.group_by_route53_names: - route53_names = self.get_instance_route53_names(instance) - for name in route53_names: - self.push(self.inventory, name, hostname) - if self.nested_groups: - self.push_group(self.inventory, 'route53', name) - - # Global Tag: instances without tags - if self.group_by_tag_none and len(instance.tags) == 0: - self.push(self.inventory, 'tag_none', hostname) - if self.nested_groups: - self.push_group(self.inventory, 'tags', 'tag_none') - - # Global Tag: tag all EC2 instances - self.push(self.inventory, 'ec2', hostname) - - self.inventory["_meta"]["hostvars"][hostname] = self.get_host_info_dict_from_instance(instance) - self.inventory["_meta"]["hostvars"][hostname]['ansible_ssh_host'] = dest - - def add_rds_instance(self, instance, region): - ''' Adds an RDS instance to the inventory and index, as long as it is - addressable ''' - - # Only want available instances unless all_rds_instances is True - if not self.all_rds_instances and instance.status != 'available': - return - - # Select the best destination address - dest = instance.endpoint[0] - - if not dest: - # Skip instances we cannot address (e.g. private VPC subnet) - return - - # Set the inventory name - hostname = None - if self.hostname_variable: - if self.hostname_variable.startswith('tag_'): - hostname = instance.tags.get(self.hostname_variable[4:], None) - else: - hostname = getattr(instance, self.hostname_variable) - - # If we can't get a nice hostname, use the destination address - if not hostname: - hostname = dest - - hostname = self.to_safe(hostname).lower() - - # Add to index - self.index[hostname] = [region, instance.id] - - # Inventory: Group by instance ID (always a group of 1) - if self.group_by_instance_id: - self.inventory[instance.id] = [hostname] - if self.nested_groups: - self.push_group(self.inventory, 'instances', instance.id) - - # Inventory: Group by region - if self.group_by_region: - self.push(self.inventory, region, hostname) - if self.nested_groups: - self.push_group(self.inventory, 'regions', region) - - # Inventory: Group by availability zone - if self.group_by_availability_zone: - self.push(self.inventory, instance.availability_zone, hostname) - if self.nested_groups: - if self.group_by_region: - self.push_group(self.inventory, region, instance.availability_zone) - self.push_group(self.inventory, 'zones', instance.availability_zone) - - # Inventory: Group by instance type - if self.group_by_instance_type: - type_name = self.to_safe('type_' + instance.instance_class) - self.push(self.inventory, type_name, hostname) - if self.nested_groups: - self.push_group(self.inventory, 'types', type_name) - - # Inventory: Group by VPC - if self.group_by_vpc_id and instance.subnet_group and instance.subnet_group.vpc_id: - vpc_id_name = self.to_safe('vpc_id_' + instance.subnet_group.vpc_id) - self.push(self.inventory, vpc_id_name, hostname) - if self.nested_groups: - self.push_group(self.inventory, 'vpcs', vpc_id_name) - - # Inventory: Group by security group - if self.group_by_security_group: - try: - if instance.security_group: - key = self.to_safe("security_group_" + instance.security_group.name) - self.push(self.inventory, key, hostname) - if self.nested_groups: - self.push_group(self.inventory, 'security_groups', key) - - except AttributeError: - self.fail_with_error('\n'.join(['Package boto seems a bit older.', - 'Please upgrade boto >= 2.3.0.'])) - - # Inventory: Group by engine - if self.group_by_rds_engine: - self.push(self.inventory, self.to_safe("rds_" + instance.engine), hostname) - if self.nested_groups: - self.push_group(self.inventory, 'rds_engines', self.to_safe("rds_" + instance.engine)) - - # Inventory: Group by parameter group - if self.group_by_rds_parameter_group: - self.push(self.inventory, self.to_safe("rds_parameter_group_" + instance.parameter_group.name), hostname) - if self.nested_groups: - self.push_group(self.inventory, 'rds_parameter_groups', self.to_safe("rds_parameter_group_" + instance.parameter_group.name)) - - # Global Tag: all RDS instances - self.push(self.inventory, 'rds', hostname) - - self.inventory["_meta"]["hostvars"][hostname] = self.get_host_info_dict_from_instance(instance) - self.inventory["_meta"]["hostvars"][hostname]['ansible_ssh_host'] = dest - - def add_elasticache_cluster(self, cluster, region): - ''' Adds an ElastiCache cluster to the inventory and index, as long as - it's nodes are addressable ''' - - # Only want available clusters unless all_elasticache_clusters is True - if not self.all_elasticache_clusters and cluster['CacheClusterStatus'] != 'available': - return - - # Select the best destination address - if 'ConfigurationEndpoint' in cluster and cluster['ConfigurationEndpoint']: - # Memcached cluster - dest = cluster['ConfigurationEndpoint']['Address'] - is_redis = False - else: - # Redis sigle node cluster - # Because all Redis clusters are single nodes, we'll merge the - # info from the cluster with info about the node - dest = cluster['CacheNodes'][0]['Endpoint']['Address'] - is_redis = True - - if not dest: - # Skip clusters we cannot address (e.g. private VPC subnet) - return - - # Add to index - self.index[dest] = [region, cluster['CacheClusterId']] - - # Inventory: Group by instance ID (always a group of 1) - if self.group_by_instance_id: - self.inventory[cluster['CacheClusterId']] = [dest] - if self.nested_groups: - self.push_group(self.inventory, 'instances', cluster['CacheClusterId']) - - # Inventory: Group by region - if self.group_by_region and not is_redis: - self.push(self.inventory, region, dest) - if self.nested_groups: - self.push_group(self.inventory, 'regions', region) - - # Inventory: Group by availability zone - if self.group_by_availability_zone and not is_redis: - self.push(self.inventory, cluster['PreferredAvailabilityZone'], dest) - if self.nested_groups: - if self.group_by_region: - self.push_group(self.inventory, region, cluster['PreferredAvailabilityZone']) - self.push_group(self.inventory, 'zones', cluster['PreferredAvailabilityZone']) - - # Inventory: Group by node type - if self.group_by_instance_type and not is_redis: - type_name = self.to_safe('type_' + cluster['CacheNodeType']) - self.push(self.inventory, type_name, dest) - if self.nested_groups: - self.push_group(self.inventory, 'types', type_name) - - # Inventory: Group by VPC (information not available in the current - # AWS API version for ElastiCache) - - # Inventory: Group by security group - if self.group_by_security_group and not is_redis: - - # Check for the existence of the 'SecurityGroups' key and also if - # this key has some value. When the cluster is not placed in a SG - # the query can return None here and cause an error. - if 'SecurityGroups' in cluster and cluster['SecurityGroups'] is not None: - for security_group in cluster['SecurityGroups']: - key = self.to_safe("security_group_" + security_group['SecurityGroupId']) - self.push(self.inventory, key, dest) - if self.nested_groups: - self.push_group(self.inventory, 'security_groups', key) - - # Inventory: Group by engine - if self.group_by_elasticache_engine and not is_redis: - self.push(self.inventory, self.to_safe("elasticache_" + cluster['Engine']), dest) - if self.nested_groups: - self.push_group(self.inventory, 'elasticache_engines', self.to_safe(cluster['Engine'])) - - # Inventory: Group by parameter group - if self.group_by_elasticache_parameter_group: - self.push(self.inventory, self.to_safe("elasticache_parameter_group_" + cluster['CacheParameterGroup']['CacheParameterGroupName']), dest) - if self.nested_groups: - self.push_group(self.inventory, 'elasticache_parameter_groups', self.to_safe(cluster['CacheParameterGroup']['CacheParameterGroupName'])) - - # Inventory: Group by replication group - if self.group_by_elasticache_replication_group and 'ReplicationGroupId' in cluster and cluster['ReplicationGroupId']: - self.push(self.inventory, self.to_safe("elasticache_replication_group_" + cluster['ReplicationGroupId']), dest) - if self.nested_groups: - self.push_group(self.inventory, 'elasticache_replication_groups', self.to_safe(cluster['ReplicationGroupId'])) - - # Global Tag: all ElastiCache clusters - self.push(self.inventory, 'elasticache_clusters', cluster['CacheClusterId']) - - host_info = self.get_host_info_dict_from_describe_dict(cluster) - - self.inventory["_meta"]["hostvars"][dest] = host_info - - # Add the nodes - for node in cluster['CacheNodes']: - self.add_elasticache_node(node, cluster, region) - - def add_elasticache_node(self, node, cluster, region): - ''' Adds an ElastiCache node to the inventory and index, as long as - it is addressable ''' - - # Only want available nodes unless all_elasticache_nodes is True - if not self.all_elasticache_nodes and node['CacheNodeStatus'] != 'available': - return - - # Select the best destination address - dest = node['Endpoint']['Address'] - - if not dest: - # Skip nodes we cannot address (e.g. private VPC subnet) - return - - node_id = self.to_safe(cluster['CacheClusterId'] + '_' + node['CacheNodeId']) - - # Add to index - self.index[dest] = [region, node_id] - - # Inventory: Group by node ID (always a group of 1) - if self.group_by_instance_id: - self.inventory[node_id] = [dest] - if self.nested_groups: - self.push_group(self.inventory, 'instances', node_id) - - # Inventory: Group by region - if self.group_by_region: - self.push(self.inventory, region, dest) - if self.nested_groups: - self.push_group(self.inventory, 'regions', region) - - # Inventory: Group by availability zone - if self.group_by_availability_zone: - self.push(self.inventory, cluster['PreferredAvailabilityZone'], dest) - if self.nested_groups: - if self.group_by_region: - self.push_group(self.inventory, region, cluster['PreferredAvailabilityZone']) - self.push_group(self.inventory, 'zones', cluster['PreferredAvailabilityZone']) - - # Inventory: Group by node type - if self.group_by_instance_type: - type_name = self.to_safe('type_' + cluster['CacheNodeType']) - self.push(self.inventory, type_name, dest) - if self.nested_groups: - self.push_group(self.inventory, 'types', type_name) - - # Inventory: Group by VPC (information not available in the current - # AWS API version for ElastiCache) - - # Inventory: Group by security group - if self.group_by_security_group: - - # Check for the existence of the 'SecurityGroups' key and also if - # this key has some value. When the cluster is not placed in a SG - # the query can return None here and cause an error. - if 'SecurityGroups' in cluster and cluster['SecurityGroups'] is not None: - for security_group in cluster['SecurityGroups']: - key = self.to_safe("security_group_" + security_group['SecurityGroupId']) - self.push(self.inventory, key, dest) - if self.nested_groups: - self.push_group(self.inventory, 'security_groups', key) - - # Inventory: Group by engine - if self.group_by_elasticache_engine: - self.push(self.inventory, self.to_safe("elasticache_" + cluster['Engine']), dest) - if self.nested_groups: - self.push_group(self.inventory, 'elasticache_engines', self.to_safe("elasticache_" + cluster['Engine'])) - - # Inventory: Group by parameter group (done at cluster level) - - # Inventory: Group by replication group (done at cluster level) - - # Inventory: Group by ElastiCache Cluster - if self.group_by_elasticache_cluster: - self.push(self.inventory, self.to_safe("elasticache_cluster_" + cluster['CacheClusterId']), dest) - - # Global Tag: all ElastiCache nodes - self.push(self.inventory, 'elasticache_nodes', dest) - - host_info = self.get_host_info_dict_from_describe_dict(node) - - if dest in self.inventory["_meta"]["hostvars"]: - self.inventory["_meta"]["hostvars"][dest].update(host_info) - else: - self.inventory["_meta"]["hostvars"][dest] = host_info - - def add_elasticache_replication_group(self, replication_group, region): - ''' Adds an ElastiCache replication group to the inventory and index ''' - - # Only want available clusters unless all_elasticache_replication_groups is True - if not self.all_elasticache_replication_groups and replication_group['Status'] != 'available': - return - - # Skip clusters we cannot address (e.g. private VPC subnet or clustered redis) - if replication_group['NodeGroups'][0]['PrimaryEndpoint'] is None or \ - replication_group['NodeGroups'][0]['PrimaryEndpoint']['Address'] is None: - return - - # Select the best destination address (PrimaryEndpoint) - dest = replication_group['NodeGroups'][0]['PrimaryEndpoint']['Address'] - - # Add to index - self.index[dest] = [region, replication_group['ReplicationGroupId']] - - # Inventory: Group by ID (always a group of 1) - if self.group_by_instance_id: - self.inventory[replication_group['ReplicationGroupId']] = [dest] - if self.nested_groups: - self.push_group(self.inventory, 'instances', replication_group['ReplicationGroupId']) - - # Inventory: Group by region - if self.group_by_region: - self.push(self.inventory, region, dest) - if self.nested_groups: - self.push_group(self.inventory, 'regions', region) - - # Inventory: Group by availability zone (doesn't apply to replication groups) - - # Inventory: Group by node type (doesn't apply to replication groups) - - # Inventory: Group by VPC (information not available in the current - # AWS API version for replication groups - - # Inventory: Group by security group (doesn't apply to replication groups) - # Check this value in cluster level - - # Inventory: Group by engine (replication groups are always Redis) - if self.group_by_elasticache_engine: - self.push(self.inventory, 'elasticache_redis', dest) - if self.nested_groups: - self.push_group(self.inventory, 'elasticache_engines', 'redis') - - # Global Tag: all ElastiCache clusters - self.push(self.inventory, 'elasticache_replication_groups', replication_group['ReplicationGroupId']) - - host_info = self.get_host_info_dict_from_describe_dict(replication_group) - - self.inventory["_meta"]["hostvars"][dest] = host_info - - def get_route53_records(self): - ''' Get and store the map of resource records to domain names that - point to them. ''' - - if self.boto_profile: - r53_conn = route53.Route53Connection(profile_name=self.boto_profile) - else: - r53_conn = route53.Route53Connection() - all_zones = r53_conn.get_zones() - - route53_zones = [zone for zone in all_zones if zone.name[:-1] not in self.route53_excluded_zones] - - self.route53_records = {} - - for zone in route53_zones: - rrsets = r53_conn.get_all_rrsets(zone.id) - - for record_set in rrsets: - record_name = record_set.name - - if record_name.endswith('.'): - record_name = record_name[:-1] - - for resource in record_set.resource_records: - self.route53_records.setdefault(resource, set()) - self.route53_records[resource].add(record_name) - - def get_instance_route53_names(self, instance): - ''' Check if an instance is referenced in the records we have from - Route53. If it is, return the list of domain names pointing to said - instance. If nothing points to it, return an empty list. ''' - - instance_attributes = ['public_dns_name', 'private_dns_name', - 'ip_address', 'private_ip_address'] - - name_list = set() - - for attrib in instance_attributes: - try: - value = getattr(instance, attrib) - except AttributeError: - continue - - if value in self.route53_records: - name_list.update(self.route53_records[value]) - - return list(name_list) - - def get_host_info_dict_from_instance(self, instance): - instance_vars = {} - for key in vars(instance): - value = getattr(instance, key) - key = self.to_safe('ec2_' + key) - - # Handle complex types - # state/previous_state changed to properties in boto in https://github.com/boto/boto/commit/a23c379837f698212252720d2af8dec0325c9518 - if key == 'ec2__state': - instance_vars['ec2_state'] = instance.state or '' - instance_vars['ec2_state_code'] = instance.state_code - elif key == 'ec2__previous_state': - instance_vars['ec2_previous_state'] = instance.previous_state or '' - instance_vars['ec2_previous_state_code'] = instance.previous_state_code - elif isinstance(value, (int, bool)): - instance_vars[key] = value - elif isinstance(value, six.string_types): - instance_vars[key] = value.strip() - elif value is None: - instance_vars[key] = '' - elif key == 'ec2_region': - instance_vars[key] = value.name - elif key == 'ec2__placement': - instance_vars['ec2_placement'] = value.zone - elif key == 'ec2_tags': - for k, v in value.items(): - if self.expand_csv_tags and ',' in v: - v = list(map(lambda x: x.strip(), v.split(','))) - key = self.to_safe('ec2_tag_' + k) - instance_vars[key] = v - elif key == 'ec2_groups': - group_ids = [] - group_names = [] - for group in value: - group_ids.append(group.id) - group_names.append(group.name) - instance_vars["ec2_security_group_ids"] = ','.join([str(i) for i in group_ids]) - instance_vars["ec2_security_group_names"] = ','.join([str(i) for i in group_names]) - elif key == 'ec2_block_device_mapping': - instance_vars["ec2_block_devices"] = {} - for k, v in value.items(): - instance_vars["ec2_block_devices"][os.path.basename(k)] = v.volume_id - else: - pass - # TODO Product codes if someone finds them useful - # print key - # print type(value) - # print value - - instance_vars[self.to_safe('ec2_account_id')] = self.aws_account_id - - return instance_vars - - def get_host_info_dict_from_describe_dict(self, describe_dict): - ''' Parses the dictionary returned by the API call into a flat list - of parameters. This method should be used only when 'describe' is - used directly because Boto doesn't provide specific classes. ''' - - # I really don't agree with prefixing everything with 'ec2' - # because EC2, RDS and ElastiCache are different services. - # I'm just following the pattern used until now to not break any - # compatibility. - - host_info = {} - for key in describe_dict: - value = describe_dict[key] - key = self.to_safe('ec2_' + self.uncammelize(key)) - - # Handle complex types - - # Target: Memcached Cache Clusters - if key == 'ec2_configuration_endpoint' and value: - host_info['ec2_configuration_endpoint_address'] = value['Address'] - host_info['ec2_configuration_endpoint_port'] = value['Port'] - - # Target: Cache Nodes and Redis Cache Clusters (single node) - if key == 'ec2_endpoint' and value: - host_info['ec2_endpoint_address'] = value['Address'] - host_info['ec2_endpoint_port'] = value['Port'] - - # Target: Redis Replication Groups - if key == 'ec2_node_groups' and value: - host_info['ec2_endpoint_address'] = value[0]['PrimaryEndpoint']['Address'] - host_info['ec2_endpoint_port'] = value[0]['PrimaryEndpoint']['Port'] - replica_count = 0 - for node in value[0]['NodeGroupMembers']: - if node['CurrentRole'] == 'primary': - host_info['ec2_primary_cluster_address'] = node['ReadEndpoint']['Address'] - host_info['ec2_primary_cluster_port'] = node['ReadEndpoint']['Port'] - host_info['ec2_primary_cluster_id'] = node['CacheClusterId'] - elif node['CurrentRole'] == 'replica': - host_info['ec2_replica_cluster_address_' + str(replica_count)] = node['ReadEndpoint']['Address'] - host_info['ec2_replica_cluster_port_' + str(replica_count)] = node['ReadEndpoint']['Port'] - host_info['ec2_replica_cluster_id_' + str(replica_count)] = node['CacheClusterId'] - replica_count += 1 - - # Target: Redis Replication Groups - if key == 'ec2_member_clusters' and value: - host_info['ec2_member_clusters'] = ','.join([str(i) for i in value]) - - # Target: All Cache Clusters - elif key == 'ec2_cache_parameter_group': - host_info["ec2_cache_node_ids_to_reboot"] = ','.join([str(i) for i in value['CacheNodeIdsToReboot']]) - host_info['ec2_cache_parameter_group_name'] = value['CacheParameterGroupName'] - host_info['ec2_cache_parameter_apply_status'] = value['ParameterApplyStatus'] - - # Target: Almost everything - elif key == 'ec2_security_groups': - - # Skip if SecurityGroups is None - # (it is possible to have the key defined but no value in it). - if value is not None: - sg_ids = [] - for sg in value: - sg_ids.append(sg['SecurityGroupId']) - host_info["ec2_security_group_ids"] = ','.join([str(i) for i in sg_ids]) - - # Target: Everything - # Preserve booleans and integers - elif isinstance(value, (int, bool)): - host_info[key] = value - - # Target: Everything - # Sanitize string values - elif isinstance(value, six.string_types): - host_info[key] = value.strip() - - # Target: Everything - # Replace None by an empty string - elif value is None: - host_info[key] = '' - - else: - # Remove non-processed complex types - pass - - return host_info - - def get_host_info(self): - ''' Get variables about a specific host ''' - - if len(self.index) == 0: - # Need to load index from cache - self.load_index_from_cache() - - if self.args.host not in self.index: - # try updating the cache - self.do_api_calls_update_cache() - if self.args.host not in self.index: - # host might not exist anymore - return self.json_format_dict({}, True) - - (region, instance_id) = self.index[self.args.host] - - instance = self.get_instance(region, instance_id) - return self.json_format_dict(self.get_host_info_dict_from_instance(instance), True) - - def push(self, my_dict, key, element): - ''' Push an element onto an array that may not have been defined in - the dict ''' - group_info = my_dict.setdefault(key, []) - if isinstance(group_info, dict): - host_list = group_info.setdefault('hosts', []) - host_list.append(element) - else: - group_info.append(element) - - def push_group(self, my_dict, key, element): - ''' Push a group as a child of another group. ''' - parent_group = my_dict.setdefault(key, {}) - if not isinstance(parent_group, dict): - parent_group = my_dict[key] = {'hosts': parent_group} - child_groups = parent_group.setdefault('children', []) - if element not in child_groups: - child_groups.append(element) - - def get_inventory_from_cache(self): - ''' Reads the inventory from the cache file and returns it as a JSON - object ''' - - with open(self.cache_path_cache, 'r') as f: - json_inventory = f.read() - return json_inventory - - def load_index_from_cache(self): - ''' Reads the index from the cache file sets self.index ''' - - with open(self.cache_path_index, 'rb') as f: - self.index = json.load(f) - - def write_to_cache(self, data, filename): - ''' Writes data in JSON format to a file ''' - - json_data = self.json_format_dict(data, True) - with open(filename, 'w') as f: - f.write(json_data) - - def uncammelize(self, key): - temp = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', key) - return re.sub('([a-z0-9])([A-Z])', r'\1_\2', temp).lower() - - def to_safe(self, word): - ''' Converts 'bad' characters in a string to underscores so they can be used as Ansible groups ''' - regex = "[^A-Za-z0-9\_" - if not self.replace_dash_in_groups: - regex += "\-" - return re.sub(regex + "]", "_", word) - - def json_format_dict(self, data, pretty=False): - ''' Converts a dict to a JSON object and dumps it as a formatted - string ''' - - if pretty: - return json.dumps(data, sort_keys=True, indent=2) - else: - return json.dumps(data) - - -if __name__ == '__main__': - # Run the script - Ec2Inventory() diff --git a/networks/remote/ansible/logzio.yml b/networks/remote/ansible/logzio.yml deleted file mode 100644 index 7ad28193ae..0000000000 --- a/networks/remote/ansible/logzio.yml +++ /dev/null @@ -1,13 +0,0 @@ ---- - -#Note: You need to add LOGZIO_TOKEN variable with your API key. Like this: ansible-playbook -e LOGZIO_TOKEN=ABCXYZ123456 - -- hosts: all - any_errors_fatal: true - gather_facts: no - vars: - - service: gaiad - - JOURNALBEAT_BINARY: "{{lookup('env', 'GOPATH')}}/bin/journalbeat" - roles: - - logzio - diff --git a/networks/remote/ansible/remove-datadog-agent.yml b/networks/remote/ansible/remove-datadog-agent.yml deleted file mode 100644 index 32679c3b28..0000000000 --- a/networks/remote/ansible/remove-datadog-agent.yml +++ /dev/null @@ -1,8 +0,0 @@ ---- - -- hosts: all - any_errors_fatal: true - gather_facts: no - roles: - - remove-datadog-agent - diff --git a/networks/remote/ansible/roles/add-lcd/defaults/main.yml b/networks/remote/ansible/roles/add-lcd/defaults/main.yml deleted file mode 100644 index 16a85e0dd3..0000000000 --- a/networks/remote/ansible/roles/add-lcd/defaults/main.yml +++ /dev/null @@ -1,4 +0,0 @@ ---- - -GAIACLI_ADDRESS: tcp://0.0.0.0:1317 - diff --git a/networks/remote/ansible/roles/add-lcd/handlers/main.yml b/networks/remote/ansible/roles/add-lcd/handlers/main.yml deleted file mode 100644 index 2ce6b83e55..0000000000 --- a/networks/remote/ansible/roles/add-lcd/handlers/main.yml +++ /dev/null @@ -1,9 +0,0 @@ ---- - -- name: systemctl - systemd: name=gaiacli enabled=yes daemon_reload=yes - -- name: restart gaiacli - service: name=gaiacli state=restarted - - diff --git a/networks/remote/ansible/roles/add-lcd/tasks/main.yml b/networks/remote/ansible/roles/add-lcd/tasks/main.yml deleted file mode 100644 index d0fbd81325..0000000000 --- a/networks/remote/ansible/roles/add-lcd/tasks/main.yml +++ /dev/null @@ -1,15 +0,0 @@ ---- - -- name: Copy binary - copy: - src: "{{GAIACLI_BINARY}}" - dest: /usr/bin/gaiacli - mode: 0755 - notify: restart gaiacli - -- name: Copy service - template: - src: gaiacli.service.j2 - dest: /etc/systemd/system/gaiacli.service - notify: systemctl - diff --git a/networks/remote/ansible/roles/add-lcd/templates/gaiacli.service.j2 b/networks/remote/ansible/roles/add-lcd/templates/gaiacli.service.j2 deleted file mode 100644 index 67cbeaee55..0000000000 --- a/networks/remote/ansible/roles/add-lcd/templates/gaiacli.service.j2 +++ /dev/null @@ -1,17 +0,0 @@ -[Unit] -Description=gaiacli -Requires=network-online.target -After=network-online.target - -[Service] -Restart=on-failure -User=gaiad -Group=gaiad -PermissionsStartOnly=true -ExecStart=/usr/bin/gaiacli rest-server --laddr {{GAIACLI_ADDRESS}} -ExecReload=/bin/kill -HUP $MAINPID -KillSignal=SIGTERM - -[Install] -WantedBy=multi-user.target - diff --git a/networks/remote/ansible/roles/clear-config/tasks/main.yml b/networks/remote/ansible/roles/clear-config/tasks/main.yml deleted file mode 100644 index 5b4504cfba..0000000000 --- a/networks/remote/ansible/roles/clear-config/tasks/main.yml +++ /dev/null @@ -1,12 +0,0 @@ ---- - -- 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 - diff --git a/networks/remote/ansible/roles/extract-config/defaults/main.yml b/networks/remote/ansible/roles/extract-config/defaults/main.yml deleted file mode 100644 index a535d201dc..0000000000 --- a/networks/remote/ansible/roles/extract-config/defaults/main.yml +++ /dev/null @@ -1,4 +0,0 @@ ---- - -TESTNET_NAME: remotenet - diff --git a/networks/remote/ansible/roles/extract-config/tasks/main.yml b/networks/remote/ansible/roles/extract-config/tasks/main.yml deleted file mode 100644 index 02f2acf200..0000000000 --- a/networks/remote/ansible/roles/extract-config/tasks/main.yml +++ /dev/null @@ -1,14 +0,0 @@ ---- - -- name: Fetch genesis.json - fetch: "src=/home/gaiad/.gaiad/config/genesis.json dest={{GENESISFILE}} flat=yes" - run_once: yes - become: yes - become_user: gaiad - -- name: Fetch config.toml - fetch: "src=/home/gaiad/.gaiad/config/config.toml dest={{CONFIGFILE}} flat=yes" - run_once: yes - become: yes - become_user: gaiad - diff --git a/networks/remote/ansible/roles/increase-openfiles/files/50-fs.conf b/networks/remote/ansible/roles/increase-openfiles/files/50-fs.conf deleted file mode 100644 index 5193edd22e..0000000000 --- a/networks/remote/ansible/roles/increase-openfiles/files/50-fs.conf +++ /dev/null @@ -1 +0,0 @@ -fs.file-max=262144 diff --git a/networks/remote/ansible/roles/increase-openfiles/files/91-nofiles.conf b/networks/remote/ansible/roles/increase-openfiles/files/91-nofiles.conf deleted file mode 100644 index 929081c6c9..0000000000 --- a/networks/remote/ansible/roles/increase-openfiles/files/91-nofiles.conf +++ /dev/null @@ -1,3 +0,0 @@ -* soft nofile 262144 -* hard nofile 262144 - diff --git a/networks/remote/ansible/roles/increase-openfiles/files/limits.conf b/networks/remote/ansible/roles/increase-openfiles/files/limits.conf deleted file mode 100644 index d3fcd2e867..0000000000 --- a/networks/remote/ansible/roles/increase-openfiles/files/limits.conf +++ /dev/null @@ -1,3 +0,0 @@ -[Service] -LimitNOFILE=infinity -LimitMEMLOCK=infinity diff --git a/networks/remote/ansible/roles/increase-openfiles/handlers/main.yml b/networks/remote/ansible/roles/increase-openfiles/handlers/main.yml deleted file mode 100644 index d496023003..0000000000 --- a/networks/remote/ansible/roles/increase-openfiles/handlers/main.yml +++ /dev/null @@ -1,5 +0,0 @@ ---- - -- name: reload systemctl - systemd: name=systemd daemon_reload=yes - diff --git a/networks/remote/ansible/roles/increase-openfiles/tasks/main.yml b/networks/remote/ansible/roles/increase-openfiles/tasks/main.yml deleted file mode 100644 index 78432f5b5a..0000000000 --- a/networks/remote/ansible/roles/increase-openfiles/tasks/main.yml +++ /dev/null @@ -1,22 +0,0 @@ ---- -# Based on: https://stackoverflow.com/questions/38155108/how-to-increase-limit-for-open-processes-and-files-using-ansible - -- name: Set sysctl File Limits - copy: - src: 50-fs.conf - dest: /etc/sysctl.d - -- name: Set Shell File Limits - copy: - src: 91-nofiles.conf - dest: /etc/security/limits.d - -- name: Set gaia filehandle Limits - copy: - src: limits.conf - dest: "/lib/systemd/system/{{item}}.service.d" - notify: reload systemctl - with_items: - - gaiad - - gaiacli - diff --git a/networks/remote/ansible/roles/install-datadog-agent/handlers/main.yml b/networks/remote/ansible/roles/install-datadog-agent/handlers/main.yml deleted file mode 100644 index 04f72b74da..0000000000 --- a/networks/remote/ansible/roles/install-datadog-agent/handlers/main.yml +++ /dev/null @@ -1,10 +0,0 @@ ---- - -- name: restart datadog-agent - service: name=datadog-agent state=restarted - -- name: restart rsyslog - service: name=rsyslog state=restarted - -- name: restart journald - service: name=systemd-journald state=restarted diff --git a/networks/remote/ansible/roles/install-datadog-agent/tasks/main.yml b/networks/remote/ansible/roles/install-datadog-agent/tasks/main.yml deleted file mode 100644 index 4d5aa1877c..0000000000 --- a/networks/remote/ansible/roles/install-datadog-agent/tasks/main.yml +++ /dev/null @@ -1,15 +0,0 @@ ---- - -- name: Remove old datadog.yaml, if exist - file: path=/etc/datadog-agent/datadog.yaml state=absent - notify: restart datadog-agent - -- name: Download DataDog agent script - get_url: url=https://raw.githubusercontent.com/DataDog/datadog-agent/master/cmd/agent/install_script.sh dest=/tmp/datadog-agent-install.sh mode=0755 - -- name: Install DataDog agent - command: "/tmp/datadog-agent-install.sh" - environment: - DD_API_KEY: "{{DD_API_KEY}}" - DD_HOST_TAGS: "testnet:{{TESTNET_NAME}},cluster:{{CLUSTER_NAME}}" - diff --git a/networks/remote/ansible/roles/logzio/files/journalbeat.service b/networks/remote/ansible/roles/logzio/files/journalbeat.service deleted file mode 100644 index 3cb66a454f..0000000000 --- a/networks/remote/ansible/roles/logzio/files/journalbeat.service +++ /dev/null @@ -1,15 +0,0 @@ -[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 - - diff --git a/networks/remote/ansible/roles/logzio/handlers/main.yml b/networks/remote/ansible/roles/logzio/handlers/main.yml deleted file mode 100644 index 0b371fc517..0000000000 --- a/networks/remote/ansible/roles/logzio/handlers/main.yml +++ /dev/null @@ -1,8 +0,0 @@ ---- - -- name: reload daemon - command: "systemctl daemon-reload" - -- name: restart journalbeat - service: name=journalbeat state=restarted - diff --git a/networks/remote/ansible/roles/logzio/tasks/main.yml b/networks/remote/ansible/roles/logzio/tasks/main.yml deleted file mode 100644 index ab3976f22a..0000000000 --- a/networks/remote/ansible/roles/logzio/tasks/main.yml +++ /dev/null @@ -1,27 +0,0 @@ ---- - -- 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 - diff --git a/networks/remote/ansible/roles/logzio/templates/journalbeat.yml.j2 b/networks/remote/ansible/roles/logzio/templates/journalbeat.yml.j2 deleted file mode 100644 index af2ac4f139..0000000000 --- a/networks/remote/ansible/roles/logzio/templates/journalbeat.yml.j2 +++ /dev/null @@ -1,342 +0,0 @@ -#======================== 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","gaiacli.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 diff --git a/networks/remote/ansible/roles/remove-datadog-agent/tasks/main.yml b/networks/remote/ansible/roles/remove-datadog-agent/tasks/main.yml deleted file mode 100644 index 73b027a22a..0000000000 --- a/networks/remote/ansible/roles/remove-datadog-agent/tasks/main.yml +++ /dev/null @@ -1,12 +0,0 @@ ---- - -- name: Stop datadog service - failed_when: false - service: name=datadog-agent state=stopped - -- name: Uninstall datadg-agent - yum: name=datadog-agent state=absent - -- name: Remove datadog-agent folder - file: path=/etc/datadog-agent state=absent - diff --git a/networks/remote/ansible/roles/set-debug/files/sysconfig/gaiacli b/networks/remote/ansible/roles/set-debug/files/sysconfig/gaiacli deleted file mode 100644 index 8ef3a7e0c7..0000000000 --- a/networks/remote/ansible/roles/set-debug/files/sysconfig/gaiacli +++ /dev/null @@ -1 +0,0 @@ -DAEMON_COREFILE_LIMIT='unlimited' diff --git a/networks/remote/ansible/roles/set-debug/files/sysconfig/gaiad b/networks/remote/ansible/roles/set-debug/files/sysconfig/gaiad deleted file mode 100644 index 8ef3a7e0c7..0000000000 --- a/networks/remote/ansible/roles/set-debug/files/sysconfig/gaiad +++ /dev/null @@ -1 +0,0 @@ -DAEMON_COREFILE_LIMIT='unlimited' diff --git a/networks/remote/ansible/roles/set-debug/files/sysctl.d/10-procdump b/networks/remote/ansible/roles/set-debug/files/sysctl.d/10-procdump deleted file mode 100644 index fbbbe05121..0000000000 --- a/networks/remote/ansible/roles/set-debug/files/sysctl.d/10-procdump +++ /dev/null @@ -1,3 +0,0 @@ -kernel.core_uses_pid = 1 -kernel.core_pattern = /tmp/core-%e-%s-%u-%g-%p-%t -fs.suid_dumpable = 2 diff --git a/networks/remote/ansible/roles/set-debug/handlers/main.yaml b/networks/remote/ansible/roles/set-debug/handlers/main.yaml deleted file mode 100644 index 743ce09bcf..0000000000 --- a/networks/remote/ansible/roles/set-debug/handlers/main.yaml +++ /dev/null @@ -1,4 +0,0 @@ ---- - -- name: reload sysctl - command: "/sbin/sysctl -p" diff --git a/networks/remote/ansible/roles/set-debug/tasks/main.yml b/networks/remote/ansible/roles/set-debug/tasks/main.yml deleted file mode 100644 index 7497dabd8c..0000000000 --- a/networks/remote/ansible/roles/set-debug/tasks/main.yml +++ /dev/null @@ -1,9 +0,0 @@ ---- -# Based on https://www.cyberciti.biz/tips/linux-core-dumps.html - -- name: Copy sysctl and sysconfig files to enable app and daemon core dumps - file: src=. dest=/etc/ - notify: reload sysctl - -- name: Enable debugging for all apps - lineinfile: create=yes line="DAEMON_COREFILE_LIMIT='unlimited'" path=/etc/sysconfig/init regexp=^DAEMON_COREFILE_LIMIT= diff --git a/networks/remote/ansible/roles/setup-fullnodes/defaults/main.yml b/networks/remote/ansible/roles/setup-fullnodes/defaults/main.yml deleted file mode 100644 index a535d201dc..0000000000 --- a/networks/remote/ansible/roles/setup-fullnodes/defaults/main.yml +++ /dev/null @@ -1,4 +0,0 @@ ---- - -TESTNET_NAME: remotenet - diff --git a/networks/remote/ansible/roles/setup-fullnodes/files/gaiad.service b/networks/remote/ansible/roles/setup-fullnodes/files/gaiad.service deleted file mode 100644 index 6971665670..0000000000 --- a/networks/remote/ansible/roles/setup-fullnodes/files/gaiad.service +++ /dev/null @@ -1,17 +0,0 @@ -[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 - diff --git a/networks/remote/ansible/roles/setup-fullnodes/handlers/main.yml b/networks/remote/ansible/roles/setup-fullnodes/handlers/main.yml deleted file mode 100644 index 987e2947bf..0000000000 --- a/networks/remote/ansible/roles/setup-fullnodes/handlers/main.yml +++ /dev/null @@ -1,5 +0,0 @@ ---- - -- name: reload systemd - systemd: name=gaiad enabled=yes daemon_reload=yes - diff --git a/networks/remote/ansible/roles/setup-fullnodes/tasks/main.yml b/networks/remote/ansible/roles/setup-fullnodes/tasks/main.yml deleted file mode 100644 index ba9b22942c..0000000000 --- a/networks/remote/ansible/roles/setup-fullnodes/tasks/main.yml +++ /dev/null @@ -1,61 +0,0 @@ ---- - -- name: Ensure keys folder exists locally - file: path=keys state=directory - connection: local - run_once: true - become: no - -- name: Create gaiad user - user: name=gaiad home=/home/gaiad shell=/bin/bash - -- name: Copy binary - copy: - src: "{{BINARY}}" - dest: /usr/bin - mode: 0755 - -- name: Copy service file - copy: src=gaiad.service dest=/etc/systemd/system/gaiad.service mode=0755 - notify: reload systemd - -- name: Get node ID - command: "cat /etc/nodeid" - changed_when: false - register: nodeid - -- name: gaiad init - command: "/usr/bin/gaiad init --chain-id={{TESTNET_NAME}} --name=fullnode{{nodeid.stdout_lines[0]}}" - become: yes - become_user: gaiad - register: initresult - args: - creates: /home/gaiad/.gaiad/config - -- name: Get wallet word seed from result of initial transaction locally - when: initresult["changed"] - shell: "echo '{{initresult.stdout}}' | python -c 'import json,sys ; print json.loads(\"\".join(sys.stdin.readlines()))[\"app_message\"][\"secret\"]'" - changed_when: false - register: walletkey - connection: local - -- name: Write wallet word seed to local files - when: initresult["changed"] - copy: "content={{walletkey.stdout}} dest=keys/node{{nodeid.stdout_lines[0]}}" - become: no - connection: local - -- name: Copy genesis file - copy: - src: "{{GENESISFILE}}" - dest: /home/gaiad/.gaiad/config/genesis.json - become: yes - become_user: gaiad - -- name: Copy config.toml file - copy: - src: "{{CONFIGFILE}}" - dest: /home/gaiad/.gaiad/config/config.toml - become: yes - become_user: gaiad - diff --git a/networks/remote/ansible/roles/setup-journald/handlers/main.yml b/networks/remote/ansible/roles/setup-journald/handlers/main.yml deleted file mode 100644 index 14f3b3376f..0000000000 --- a/networks/remote/ansible/roles/setup-journald/handlers/main.yml +++ /dev/null @@ -1,5 +0,0 @@ ---- - -- name: restart journald - service: name=systemd-journald state=restarted - diff --git a/networks/remote/ansible/roles/setup-journald/tasks/main.yml b/networks/remote/ansible/roles/setup-journald/tasks/main.yml deleted file mode 100644 index 130da52001..0000000000 --- a/networks/remote/ansible/roles/setup-journald/tasks/main.yml +++ /dev/null @@ -1,26 +0,0 @@ ---- - -- name: Disable journald rate-limiting - lineinfile: "dest=/etc/systemd/journald.conf regexp={{item.regexp}} line='{{item.line}}'" - with_items: - - { regexp: "^#RateLimitInterval", line: "RateLimitInterval=0s" } - - { regexp: "^#RateLimitBurst", line: "RateLimitBurst=0" } - - { regexp: "^#SystemMaxFileSize", line: "SystemMaxFileSize=100M" } - - { regexp: "^#SystemMaxUse", line: "SystemMaxUse=500M" } - - { regexp: "^#SystemMaxFiles", line: "SystemMaxFiles=10" } - notify: restart journald - -- name: Change logrotate to daily - lineinfile: "dest=/etc/logrotate.conf regexp={{item.regexp}} line='{{item.line}}'" - with_items: - - { regexp: "^weekly", line: "daily" } - - { regexp: "^#compress", line: "compress" } - -- name: Create journal directory for permanent logs - file: path=/var/log/journal state=directory - notify: restart journald - -- name: Set journal folder with systemd-tmpfiles - command: "systemd-tmpfiles --create --prefix /var/log/journal" - notify: restart journald - diff --git a/networks/remote/ansible/roles/setup-validators/defaults/main.yml b/networks/remote/ansible/roles/setup-validators/defaults/main.yml deleted file mode 100644 index a535d201dc..0000000000 --- a/networks/remote/ansible/roles/setup-validators/defaults/main.yml +++ /dev/null @@ -1,4 +0,0 @@ ---- - -TESTNET_NAME: remotenet - diff --git a/networks/remote/ansible/roles/setup-validators/files/gaiad.service b/networks/remote/ansible/roles/setup-validators/files/gaiad.service deleted file mode 100644 index 6971665670..0000000000 --- a/networks/remote/ansible/roles/setup-validators/files/gaiad.service +++ /dev/null @@ -1,17 +0,0 @@ -[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 - diff --git a/networks/remote/ansible/roles/setup-validators/handlers/main.yml b/networks/remote/ansible/roles/setup-validators/handlers/main.yml deleted file mode 100644 index 987e2947bf..0000000000 --- a/networks/remote/ansible/roles/setup-validators/handlers/main.yml +++ /dev/null @@ -1,5 +0,0 @@ ---- - -- name: reload systemd - systemd: name=gaiad enabled=yes daemon_reload=yes - diff --git a/networks/remote/ansible/roles/setup-validators/tasks/main.yml b/networks/remote/ansible/roles/setup-validators/tasks/main.yml deleted file mode 100644 index d8cb499135..0000000000 --- a/networks/remote/ansible/roles/setup-validators/tasks/main.yml +++ /dev/null @@ -1,78 +0,0 @@ ---- - -- name: Ensure keys folder exists locally - file: path=keys state=directory - connection: local - run_once: true - become: no - -- name: Create gaiad user - user: name=gaiad home=/home/gaiad shell=/bin/bash - -- name: Copy binary - copy: - src: "{{BINARY}}" - dest: /usr/bin - mode: 0755 - -- name: Copy service file - copy: src=gaiad.service dest=/etc/systemd/system/gaiad.service mode=0755 - notify: reload systemd - -- name: Get node ID - command: "cat /etc/nodeid" - changed_when: false - register: nodeid - -- name: Create initial transaction - command: "/usr/bin/gaiad init gen-tx --name=node{{nodeid.stdout_lines[0]}} --ip={{inventory_hostname}}" - register: gentxresult - become: yes - become_user: gaiad - args: - creates: /home/gaiad/.gaiad/config/gentx - -- name: Get wallet word seed from result of initial transaction locally - when: gentxresult["changed"] - shell: "echo '{{gentxresult.stdout}}' | python -c 'import json,sys ; print json.loads(\"\".join(sys.stdin.readlines()))[\"app_message\"][\"secret\"]'" - changed_when: false - register: walletkey - connection: local - -- name: Write wallet word seed to local files - when: gentxresult["changed"] - copy: "content={{walletkey.stdout}} dest=keys/node{{nodeid.stdout_lines[0]}}" - become: no - connection: local - -- 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 file - fetch: - dest: files/ - src: "/home/gaiad/.gaiad/config/gentx/{{gentxfile.stdout_lines[0]}}" - flat: yes - -- name: Compress gathered gen-tx files locally - archive: path=files/ exclude_path=files/gen-tx.tgz dest=files/gen-tx.tgz - run_once: yes - connection: local - -- name: Unpack gen-tx archive - unarchive: src=files/gen-tx.tgz dest=/home/gaiad/.gaiad/config/gentx owner=gaiad - -- name: Generate genesis.json - command: "/usr/bin/gaiad init --with-txs --name=node{{nodeid.stdout_lines[0]}} --chain-id={{TESTNET_NAME}}" - become: yes - become_user: gaiad - args: - creates: /home/gaiad/.gaiad/config/genesis.json - diff --git a/networks/remote/ansible/roles/start/tasks/main.yml b/networks/remote/ansible/roles/start/tasks/main.yml deleted file mode 100644 index 6bc611c91c..0000000000 --- a/networks/remote/ansible/roles/start/tasks/main.yml +++ /dev/null @@ -1,5 +0,0 @@ ---- - -- name: start service - service: "name={{service}} state=started" - diff --git a/networks/remote/ansible/roles/stop/tasks/main.yml b/networks/remote/ansible/roles/stop/tasks/main.yml deleted file mode 100644 index 7db356f224..0000000000 --- a/networks/remote/ansible/roles/stop/tasks/main.yml +++ /dev/null @@ -1,5 +0,0 @@ ---- - -- name: stop service - service: "name={{service}} state=stopped" - diff --git a/networks/remote/ansible/roles/update-datadog-agent/files/conf.d/http_check.d/conf.yaml b/networks/remote/ansible/roles/update-datadog-agent/files/conf.d/http_check.d/conf.yaml deleted file mode 100644 index 6932ed6f40..0000000000 --- a/networks/remote/ansible/roles/update-datadog-agent/files/conf.d/http_check.d/conf.yaml +++ /dev/null @@ -1,13 +0,0 @@ -init_config: - -instances: - - name: gaiad - url: http://localhost:26657/status - timeout: 1 - content_match: '"latest_block_height": "0",' - reverse_content_match: true - - - name: gaiacli - url: http://localhost:1317/node_version - timeout: 1 - diff --git a/networks/remote/ansible/roles/update-datadog-agent/files/conf.d/network.d/conf.yaml b/networks/remote/ansible/roles/update-datadog-agent/files/conf.d/network.d/conf.yaml deleted file mode 100644 index b174490fc3..0000000000 --- a/networks/remote/ansible/roles/update-datadog-agent/files/conf.d/network.d/conf.yaml +++ /dev/null @@ -1,9 +0,0 @@ -init_config: - -instances: - - collect_connection_state: true - excluded_interfaces: - - lo - - lo0 - collect_rate_metrics: true - collect_count_metrics: true diff --git a/networks/remote/ansible/roles/update-datadog-agent/files/conf.d/process.d/conf.yaml b/networks/remote/ansible/roles/update-datadog-agent/files/conf.d/process.d/conf.yaml deleted file mode 100644 index 465cadad74..0000000000 --- a/networks/remote/ansible/roles/update-datadog-agent/files/conf.d/process.d/conf.yaml +++ /dev/null @@ -1,15 +0,0 @@ -init_config: - -instances: -- name: ssh - search_string: ['ssh', 'sshd'] - thresholds: - critical: [1, 5] -- name: gaiad - search_string: ['gaiad'] - thresholds: - critical: [1, 1] -- name: gaiacli - search_string: ['gaiacli'] - thresholds: - critical: [1, 1] diff --git a/networks/remote/ansible/roles/update-datadog-agent/files/conf.d/prometheus.d/conf.yaml b/networks/remote/ansible/roles/update-datadog-agent/files/conf.d/prometheus.d/conf.yaml deleted file mode 100644 index 20c04ceee3..0000000000 --- a/networks/remote/ansible/roles/update-datadog-agent/files/conf.d/prometheus.d/conf.yaml +++ /dev/null @@ -1,10 +0,0 @@ -init_config: - -instances: - - prometheus_url: http://127.0.0.1:26660 - metrics: - - go* - - mempool* - - p2p* - - process* - - promhttp* diff --git a/networks/remote/ansible/roles/update-datadog-agent/handlers/main.yml b/networks/remote/ansible/roles/update-datadog-agent/handlers/main.yml deleted file mode 100644 index 90e05c17dd..0000000000 --- a/networks/remote/ansible/roles/update-datadog-agent/handlers/main.yml +++ /dev/null @@ -1,5 +0,0 @@ ---- - -- name: restart datadog-agent - service: name=datadog-agent state=restarted - diff --git a/networks/remote/ansible/roles/update-datadog-agent/tasks/main.yml b/networks/remote/ansible/roles/update-datadog-agent/tasks/main.yml deleted file mode 100644 index c6174c6af2..0000000000 --- a/networks/remote/ansible/roles/update-datadog-agent/tasks/main.yml +++ /dev/null @@ -1,10 +0,0 @@ ---- - -- name: Set datadog.yaml config - template: src=datadog.yaml.j2 dest=/etc/datadog-agent/datadog.yaml - notify: restart datadog-agent - -- name: Set metrics config - copy: src=conf.d/ dest=/etc/datadog-agent/conf.d/ - notify: restart datadog-agent - diff --git a/networks/remote/ansible/roles/update-datadog-agent/templates/datadog.yaml.j2 b/networks/remote/ansible/roles/update-datadog-agent/templates/datadog.yaml.j2 deleted file mode 100644 index 3c2e031dde..0000000000 --- a/networks/remote/ansible/roles/update-datadog-agent/templates/datadog.yaml.j2 +++ /dev/null @@ -1,561 +0,0 @@ - -# The host of the Datadog intake server to send Agent data to -dd_url: https://app.datadoghq.com - -# The Datadog api key to associate your Agent's data with your organization. -# Can be found here: -# https://app.datadoghq.com/account/settings -api_key: {{DD_API_KEY}} - -# If you need a proxy to connect to the Internet, provide it here (default: -# disabled). You can use the 'no_proxy' list to specify hosts that should -# bypass the proxy. These settings might impact your checks requests, please -# refer to the specific check documentation for more details. Environment -# variables HTTP_PROXY, HTTPS_PROXY and NO_PROXY (coma-separated string) will -# override the values set here. See https://docs.datadoghq.com/agent/proxy/. -# -# proxy: -# http: http(s)://user:password@proxy_for_http:port -# https: http(s)://user:password@proxy_for_https:port -# no_proxy: -# - host1 -# - host2 - -# Setting this option to "yes" will tell the agent to skip validation of SSL/TLS certificates. -# This may be necessary if the agent is running behind a proxy. See this page for details: -# https://github.com/DataDog/dd-agent/wiki/Proxy-Configuration#using-haproxy-as-a-proxy -# skip_ssl_validation: no - -# Setting this option to "yes" will force the agent to only use TLS 1.2 when -# pushing data to the url specified in "dd_url". -force_tls_12: yes - -# Force the hostname to whatever you want. (default: auto-detected) -hostname: {{inventory_hostname | replace ("_","-")}} - -# Make the agent use "hostname -f" on unix-based systems as a last resort -# way of determining the hostname instead of Golang "os.Hostname()" -# This will be enabled by default in version 6.4 -# More information at https://dtdg.co/flag-hostname-fqdn -# hostname_fqdn: false - -# Set the host's tags (optional) -tags: ['testnet:{{TESTNET_NAME}}','cluster:{{CLUSTER_NAME}}'] -# - mytag -# - env:prod -# - role:database - -# Histogram and Historate configuration -# -# Configure which aggregated value to compute. Possible values are: min, max, -# median, avg, sum and count. -# -# histogram_aggregates: ["max", "median", "avg", "count"] -# -# Configure which percentiles will be computed. Must be a list of float -# between 0 and 1. -# Warning: percentiles must be specified as yaml strings -# -# histogram_percentiles: ["0.95"] -# -# Copy histogram values to distributions for true global distributions (in beta) -# This will increase the number of custom metrics created -# histogram_copy_to_distribution: false -# -# A prefix to add to distribution metrics created when histogram_copy_to_distributions is true -# histogram_copy_to_distribution_prefix: "" - -# Forwarder timeout in seconds -# forwarder_timeout: 20 - -# The forwarder retries failed requests. Use this setting to change the -# maximum length of the forwarder's retry queue (each request in the queue -# takes no more than 2MB in memory) -# forwarder_retry_queue_max_size: 30 - -# The number of workers used by the forwarder. Please note each worker will -# open an outbound HTTP connection towards Datadog's metrics intake at every -# flush. -# forwarder_num_workers: 1 - -# Collect AWS EC2 custom tags as agent tags -collect_ec2_tags: true - -# The path containing check configuration files -# By default, uses the conf.d folder located in the agent configuration folder. -# confd_path: - -# Additional path where to search for Python checks -# By default, uses the checks.d folder located in the agent configuration folder. -# additional_checksd: - -# The port for the go_expvar server -# expvar_port: 5000 - -# The port on which the IPC api listens -# cmd_port: 5001 - -# The port for the browser GUI to be served -# Setting 'GUI_port: -1' turns off the GUI completely -# Default is '5002' on Windows and macOS ; turned off on Linux -# GUI_port: -1 - -# The Agent runs workers in parallel to execute checks. By default the number -# of workers is set to 1. If set to 0 the agent will automatically determine -# the best number of runners needed based on the number of checks running. This -# would optimize the check collection time but may produce CPU spikes. -# check_runners: 1 - -# Metadata collection should always be enabled, except if you are running several -# agents/dsd instances per host. In that case, only one agent should have it on. -# WARNING: disabling it on every agent will lead to display and billing issues -# enable_metadata_collection: true - -# Enable the gohai collection of systems data -# enable_gohai: true - -# IPC api server timeout in seconds -# server_timeout: 15 - -# Some environments may have the procfs file system mounted in a miscellaneous -# location. The procfs_path configuration parameter provides a mechanism to -# override the standard default location: '/proc' - this setting will trickle -# down to integrations and affect their behavior if they rely on the psutil -# python package. -# procfs_path: /proc - -# BETA: Encrypted Secrets (Linux only) -# -# This feature is in beta and its options or behaviour might break between -# minor or bugfix releases of the Agent. -# -# The agent can call an external command to fetch secrets. The command will be -# executed maximum once per instance containing an encrypted password. -# Secrets are cached by the agent, this will avoid executing again the -# secret_backend_command to fetch an already known secret (useful when combine -# with Autodiscovery). This feature is still in beta. -# -# For more information see: https://github.com/DataDog/datadog-agent/blob/master/docs/agent/secrets.md -# -# Path to the script to execute. The script must belong to the same user used -# to run the agent. Executable right must be given to the agent and no rights -# for 'group' or 'other'. -# secret_backend_command: /path/to/command -# -# A list of arguments to give to the command at each run (optional) -# secret_backend_arguments: -# - argument1 -# - argument2 -# -# The size in bytes of the buffer used to store the command answer (apply to -# both stdout and stderr) -# secret_backend_output_max_size: 1024 -# -# The timeout to execute the command in second -# secret_backend_timeout: 5 - - -# Metadata providers, add or remove from the list to enable or disable collection. -# Intervals are expressed in seconds. You can also set a provider's interval to 0 -# to disable it. -# metadata_providers: -# - name: k8s -# interval: 60 - -# DogStatsd -# -# If you don't want to enable the DogStatsd server, set this option to no -# use_dogstatsd: yes -# -# Make sure your client is sending to the same UDP port -# dogstatsd_port: 8125 -# -# The host to bind to receive external metrics (used only by the dogstatsd -# server for now). For dogstatsd this is ignored if -# 'dogstatsd_non_local_traffic' is set to true -# bind_host: localhost -# -# Dogstatsd can also listen for metrics on a Unix Socket (*nix only). -# Set to a valid filesystem path to enable. -# dogstatsd_socket: /var/run/dogstatsd/dsd.sock -# -# When using Unix Socket, dogstatsd can tag metrics with container metadata. -# If running dogstatsd in a container, host PID mode (e.g. with --pid=host) is required. -# dogstatsd_origin_detection: false -# -# The buffer size use to receive statsd packet, in bytes -# dogstatsd_buffer_size: 1024 -# -# Whether dogstatsd should listen to non local UDP traffic -# dogstatsd_non_local_traffic: no -# -# Publish dogstatsd's internal stats as Go expvars -# dogstatsd_stats_enable: no -# -# How many items in the dogstatsd's stats circular buffer -# dogstatsd_stats_buffer: 10 -# -# The port for the go_expvar server -# dogstatsd_stats_port: 5000 -# -# The number of bytes allocated to dogstatsd's socket receive buffer (POSIX -# system only). By default, this value is set by the system. If you need to -# increase the size of this buffer but keep the OS default value the same, you -# can set dogstatsd's receive buffer size here. The maximum accepted value -# might change depending on the OS. -# dogstatsd_so_rcvbuf: -# -# If you want to forward every packet received by the dogstatsd server -# to another statsd server, uncomment these lines. -# WARNING: Make sure that forwarded packets are regular statsd packets and not "dogstatsd" packets, -# as your other statsd server might not be able to handle them. -# statsd_forward_host: address_of_own_statsd_server -# statsd_forward_port: 8125 -# -# If you want all statsd metrics coming from this host to be namespaced -# you can configure the namspace below. Each metric received will be prefixed -# with the namespace before it's sent to Datadog. -# statsd_metric_namespace: - -# Logs agent -# -# Logs agent is disabled by default -#logs_enabled: true -# -# Enable logs collection for all containers, disabled by default -# logs_config: -# container_collect_all: false -# - -# JMX -# -# jmx_pipe_path: -# jmx_pipe_name: dd-auto_discovery -# -# If you only run Autodiscovery tests, jmxfetch might fail to pick up custom_jar_paths -# set in the check templates. If that is the case, you can force custom jars here. -# jmx_custom_jars: -# - /jmx-jars/jboss-cli-client.jar -# -# When running in a memory cgroup, openjdk 8u131 and higher can automatically adjust -# its heap memory usage in accordance to the cgroup/container's memory limit. -# Default is false: we'll set a Xmx of 200MB if none is configured. -# Note: older openjdk versions and other jvms might fail to start if this option is set -# -# jmx_use_cgroup_memory_limit: true -# - -# Autoconfig -# -# Directory containing configuration templates -# autoconf_template_dir: /datadog/check_configs -# -# The providers the Agent should call to collect checks configurations. -# Please note the File Configuration Provider is enabled by default and cannot -# be configured. -# config_providers: - -## The kubelet provider handles templates embedded in pod annotations, see -## https://docs.datadoghq.com/guides/autodiscovery/#template-source-kubernetes-pod-annotations -# - name: kubelet -# polling: true - -## The docker provider handles templates embedded in container labels, see -## https://docs.datadoghq.com/guides/autodiscovery/#template-source-docker-label-annotations -# - name: docker -# polling: true - -# - name: etcd -# polling: true -# template_dir: /datadog/check_configs -# template_url: http://127.0.0.1 -# username: -# password: - -# - name: consul -# polling: true -# template_dir: /datadog/check_configs -# template_url: http://127.0.0.1 -# ca_file: -# ca_path: -# cert_file: -# key_file: -# username: -# password: -# token: - -# - name: zookeeper -# polling: true -# template_dir: /datadog/check_configs -# template_url: 127.0.0.1 -# username: -# password: - -# Logging -# -# log_level: info -# log_file: /var/log/datadog/agent.log - -# Set to 'yes' to output logs in JSON format -# log_format_json: no - -# Set to 'no' to disable logging to stdout -# log_to_console: yes - -# Set to 'yes' to disable logging to the log file -# disable_file_logging: no - -# Set to 'yes' to enable logging to syslog. -# -# log_to_syslog: no -# -# If 'syslog_uri' is left undefined/empty, a local domain socket connection will be attempted -# -# syslog_uri: -# -# Set to 'yes' to output in an RFC 5424-compliant format -# -# syslog_rfc: no -# -# If TLS enabled, you must specify a path to a PEM certificate here -# -# syslog_pem: /path/to/certificate.pem -# -# If TLS enabled, you must specify a path to a private key here -# -# syslog_key: /path/to/key.pem -# -# If TLS enabled, you may enforce TLS verification here (defaults to true) -# -# syslog_tls_verify: yes -# - -# Autodiscovery -# -# Change the root directory to look at to get cgroup statistics. Useful when running inside a -# container with host directories mounted on a different folder. -# Default if environment variable "DOCKER_DD_AGENT" is set to "yes" -# "/host/sys/fs/cgroup" and "/sys/fs/cgroup" if not. -# -# container_cgroup_root: /host/sys/fs/cgroup/ -# -# Change the root directory to look at to get proc statistics. Useful when running inside a -# container with host directories mounted on a different folder. -# Default if environment variable "DOCKER_DD_AGENT" is set to "yes" -# "/host/proc" and "/proc" if not. -# -# container_proc_root: /host/proc -# -# Choose "auto" if you want to let the agent find any relevant listener on your host -# At the moment, the only auto listener supported is docker -# If you have already set docker anywhere in the listeners, the auto listener is ignored -# listeners: -# - name: auto -# - name: docker -# -# Exclude containers from metrics and AD based on their name or image: -# An excluded container will not get any individual container metric reported for it. -# Please note that the `docker.containers.running`, `.stopped`, `.running.total` and -# `.stopped.total` metrics are not affected by these settings and always count all -# containers. This does not affect your per-container billing. -# -# How it works: include first. -# If a container matches an exclude rule, it won't be included unless it first matches an include rule. -# -# Rules are regexp. -# -# Examples: -# exclude all, except containers based on the 'ubuntu' image or the 'debian' image. -# ac_exclude: ["image:.*"] -# ac_include: ["image:ubuntu", "image:debian"] -# -# include all, except containers based on the 'ubuntu' image. -# ac_exclude: ["image:ubuntu"] -# ac_include: [] -# -# exclude all debian images except containers with a name starting with 'frontend'. -# ac_exclude: ["image:debian"] -# ac_include: ["name:frontend.*"] -# -# ac_exclude: [] -# ac_include: [] -# -# -# Exclude default pause containers from orchestrators. -# -# By default the agent will not monitor kubernetes/openshift pause -# container. They will still be counted in the container count (just like -# excluded containers) since ignoring them would give a wrong impression -# about the docker daemon load. -# -# exclude_pause_container: true - -# Exclude default containers from DockerCloud: -# The following configuration will instruct the agent to ignore the containers from Docker Cloud. -# You can remove the ones you want to collect. -# ac_exclude: ["image:dockercloud/network-daemon","image:dockercloud/cleanup","image:dockercloud/logrotate","image:dockercloud/events","image:dockercloud/ntpd"] -# ac_include: [] -# -# You can also use the regex to ignore them all: -# ac_exclude: ["image:dockercloud/*"] -# ac_include: [] -# -# The default timeout value when connecting to the docker daemon -# is 5 seconds. It can be configured with this option. -# docker_query_timeout: 5 -# - -# Docker tag extraction -# -# We can extract container label or environment variables -# as metric tags. If you prefix your tag name with +, it -# will only be added to high cardinality metrics (docker check) -# -# docker_labels_as_tags: -# label_name: tag_name -# high_cardinality_label_name: +tag_name -# docker_env_as_tags: -# ENVVAR_NAME: tag_name -# -# Example: -# docker_labels_as_tags: -# com.docker.compose.service: service_name -# com.docker.compose.project: +project_name -# - -# Kubernetes tag extraction -# -# We can extract pod labels and annotations as metric tags. If you prefix your -# tag name with +, it will only be added to high cardinality metrics -# -# kubernetes_pod_labels_as_tags: -# app: kube_app -# pod-template-hash: +kube_pod-template-hash -# -# kubernetes_pod_annotations_as_tags: -# app: kube_app -# pod-template-hash: +kube_pod-template-hash -# - -# ECS integration -# -# URL where the ECS agent can be found. Standard cases will be autodetected. -# ecs_agent_url: http://localhost:51678 -# - -# Kubernetes kubelet connectivity -# -# The kubelet host and port should be autodetected when running inside a pod. -# If you run into connectivity issues, you can set these options according to -# your cluster setup: -# kubernetes_kubelet_host: autodetected -# kubernetes_http_kubelet_port: 10255 -# kubernetes_https_kubelet_port: 10250 -# -# When using HTTPS, we verify the kubelet's certificate, you can tune this: -# kubelet_tls_verify: true -# kubelet_client_ca: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt -# -# If authentication is needed, the agent will use the pod's serviceaccount's -# credentials. If you want to use a different account, or are running the agent -# on the host, you can set the credentials to use here: -# kubelet_auth_token_path: /path/to/file -# kubelet_client_crt: /path/to/key -# kubelet_client_key: /path/to/key -# - -# Kubernetes apiserver integration -# -# When running in a pod, the agent will automatically use the pod's serviceaccount -# to authenticate with the apiserver. If you wish to install the agent out of a pod -# or customise connection parameters, you can provide the path to a KubeConfig file -# see https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/ -# -# kubernetes_kubeconfig_path: /path/to/file -# -# In order to collect Kubernetes service names, the agent needs certain rights (see RBAC documentation in -# [docker readme](https://github.com/DataDog/datadog-agent/blob/master/Dockerfiles/agent/README.md#kubernetes)). -# You can disable this option or set how often (in seconds) the agent refreshes the internal mapping of services to -# ContainerIDs with the following options: -# kubernetes_collect_metadata_tags: true -# kubernetes_metadata_tag_update_freq: 60 -# kubernetes_apiserver_client_timeout: 10 -# kubernetes_apiserver_poll_freq: 30 -# -# To collect Kubernetes events, leader election must be enabled and collect_kubernetes_events set to true. -# Only the leader will collect events. More details about events [here](https://github.com/DataDog/datadog-agent/blob/master/Dockerfilesagent/README.md#event-collection). -# collect_kubernetes_events: false -# -# -# Leader Election settings, more details about leader election [here](https://github.com/DataDog/datadog-agent/blob/master/Dockerfilesagent/README.md#leader-election) -# To enable the leader election on this node, set the leader_election variable to true. -# leader_election: false -# The leader election lease is an integer in seconds. -# leader_lease_duration: 60 -# -# Node labels that should be collected and their name in host tags. Off by default. -# Some of these labels are redundant with metadata collected by -# cloud provider crawlers (AWS, GCE, Azure) -# -# kubernetes_node_labels_as_tags: -# kubernetes.io/hostname: nodename -# beta.kubernetes.io/os: os - -# Process agent specific settings -# -process_config: -# A string indicating the enabled state of the Process Agent. -# If "false" (the default) it will only collect containers. -# If "true" it will collect containers and processes. -# If "disabled" it will be disabled altogether and won't start. - enabled: "true" -# The full path to the file where process-agent logs will be written. -# log_file: -# The interval, in seconds, at which we will run each check. If you want consistent -# behavior between real-time you may set the Container/ProcessRT intervals to 10. -# Defaults to 10s for normal checks and 2s for others. -# intervals: -# container: -# container_realtime: -# process: -# process_realtime: -# A list of regex patterns that will exclude a process if matched. -# blacklist_patterns: -# How many check results to buffer in memory when POST fails. The default is usually fine. -# queue_size: -# The maximum number of file descriptors to open when collecting net connections. -# Only change if you are running out of file descriptors from the Agent. -# max_proc_fds: -# The maximum number of processes or containers per message. -# Only change if the defaults are causing issues. -# max_per_message: -# Overrides the path to the Agent bin used for getting the hostname. The default is usually fine. -# dd_agent_bin: -# Overrides of the environment we pass to fetch the hostname. The default is usually fine. -# dd_agent_env: - -# Trace Agent Specific Settings -# -# apm_config: -# Whether or not the APM Agent should run -# enabled: true -# The environment tag that Traces should be tagged with -# Will inherit from "env" tag if none is applied here -# env: none -# The port that the Receiver should listen on -# receiver_port: 8126 -# Whether the Trace Agent should listen for non local traffic -# Only enable if Traces are being sent to this Agent from another host/container -# apm_non_local_traffic: false -# Extra global sample rate to apply on all the traces -# This sample rate is combined to the sample rate from the sampler logic, still promoting interesting traces -# From 1 (no extra rate) to 0 (don't sample at all) -# extra_sample_rate: 1.0 -# Maximum number of traces per second to sample. -# The limit is applied over an average over a few minutes ; much bigger spikes are possible. -# Set to 0 to disable the limit. -# max_traces_per_second: 10 -# A blacklist of regular expressions can be provided to disable certain traces based on their resource name -# all entries must be surrounded by double quotes and separated by commas -# Example: ["(GET|POST) /healthcheck", "GET /V1"] -# ignore_resources: [] diff --git a/networks/remote/ansible/roles/upgrade-gaiad/handlers/main.yml b/networks/remote/ansible/roles/upgrade-gaiad/handlers/main.yml deleted file mode 100644 index 8a63ccbf95..0000000000 --- a/networks/remote/ansible/roles/upgrade-gaiad/handlers/main.yml +++ /dev/null @@ -1,5 +0,0 @@ ---- - -- name: restart gaiad - service: name=gaiad state=restarted - diff --git a/networks/remote/ansible/roles/upgrade-gaiad/tasks/main.yml b/networks/remote/ansible/roles/upgrade-gaiad/tasks/main.yml deleted file mode 100644 index 0022199350..0000000000 --- a/networks/remote/ansible/roles/upgrade-gaiad/tasks/main.yml +++ /dev/null @@ -1,29 +0,0 @@ ---- - -- name: Copy binary - copy: - src: "{{BINARY}}" - dest: /usr/bin/gaiad - mode: 0755 - notify: restart gaiad - -- name: Copy new genesis.json file, if available - when: "GENESISFILE is defined and GENESISFILE != ''" - copy: - src: "{{GENESISFILE}}" - dest: /home/gaiad/.gaiad/config/genesis.json - notify: restart gaiad - -- name: Download genesis.json URL, if available - when: "GENESISURL is defined and GENESISURL != ''" - get_url: - url: "{{GENESISURL}}" - dest: /home/gaiad/.gaiad/config/genesis.json - force: yes - notify: restart gaiad - -- name: Reset network - when: UNSAFE_RESET_ALL | default(false) | bool - command: "sudo -u gaiad gaiad unsafe-reset-all" - notify: restart gaiad - diff --git a/networks/remote/ansible/set-debug.yml b/networks/remote/ansible/set-debug.yml deleted file mode 100644 index 76ee1b3574..0000000000 --- a/networks/remote/ansible/set-debug.yml +++ /dev/null @@ -1,8 +0,0 @@ ---- - -- hosts: all - any_errors_fatal: true - gather_facts: no - roles: - - set-debug - diff --git a/networks/remote/ansible/setup-fullnodes.yml b/networks/remote/ansible/setup-fullnodes.yml deleted file mode 100644 index da1810d1d0..0000000000 --- a/networks/remote/ansible/setup-fullnodes.yml +++ /dev/null @@ -1,13 +0,0 @@ ---- - -#GENESISFILE required -#CONFIGFILE required -#BINARY required - -- hosts: all - any_errors_fatal: true - gather_facts: no - roles: - - increase-openfiles - - setup-fullnodes - diff --git a/networks/remote/ansible/setup-journald.yml b/networks/remote/ansible/setup-journald.yml deleted file mode 100644 index 369c483f36..0000000000 --- a/networks/remote/ansible/setup-journald.yml +++ /dev/null @@ -1,10 +0,0 @@ ---- - -#DD_API_KEY - -- hosts: all - any_errors_fatal: true - gather_facts: no - roles: - - setup-journald - diff --git a/networks/remote/ansible/setup-validators.yml b/networks/remote/ansible/setup-validators.yml deleted file mode 100644 index 0e6f2959a0..0000000000 --- a/networks/remote/ansible/setup-validators.yml +++ /dev/null @@ -1,9 +0,0 @@ ---- - -- hosts: all - any_errors_fatal: true - gather_facts: no - roles: - - increase-openfiles - - setup-validators - diff --git a/networks/remote/ansible/start.yml b/networks/remote/ansible/start.yml deleted file mode 100644 index bc29679e03..0000000000 --- a/networks/remote/ansible/start.yml +++ /dev/null @@ -1,10 +0,0 @@ ---- - -- hosts: all - any_errors_fatal: true - gather_facts: no - vars: - - service: gaiad - roles: - - start - diff --git a/networks/remote/ansible/status.yml b/networks/remote/ansible/status.yml deleted file mode 100644 index ebd7f72eed..0000000000 --- a/networks/remote/ansible/status.yml +++ /dev/null @@ -1,17 +0,0 @@ ---- - -- hosts: all - connection: local - any_errors_fatal: true - gather_facts: no - - tasks: - - name: Gather status - uri: - body_format: json - url: "http://{{ansible_host}}:26657/status" - register: status - - - name: Print status - debug: var=status.json.result - diff --git a/networks/remote/ansible/stop.yml b/networks/remote/ansible/stop.yml deleted file mode 100644 index 312cb9cf6c..0000000000 --- a/networks/remote/ansible/stop.yml +++ /dev/null @@ -1,10 +0,0 @@ ---- - -- hosts: all - any_errors_fatal: true - gather_facts: no - vars: - - service: gaiad - roles: - - stop - diff --git a/networks/remote/ansible/update-datadog-agent.yml b/networks/remote/ansible/update-datadog-agent.yml deleted file mode 100644 index 3fe1e0006e..0000000000 --- a/networks/remote/ansible/update-datadog-agent.yml +++ /dev/null @@ -1,10 +0,0 @@ ---- - -#DD_API_KEY,TESTNET_NAME,CLUSTER_NAME required - -- hosts: all - any_errors_fatal: true - gather_facts: no - roles: - - update-datadog-agent - diff --git a/networks/remote/ansible/upgrade-gaia.yml b/networks/remote/ansible/upgrade-gaia.yml deleted file mode 100644 index cde5603484..0000000000 --- a/networks/remote/ansible/upgrade-gaia.yml +++ /dev/null @@ -1,9 +0,0 @@ ---- - -- hosts: all - any_errors_fatal: true - gather_facts: no - roles: - - upgrade-gaiad - - add-lcd - diff --git a/networks/remote/ansible/upgrade-gaiad.yml b/networks/remote/ansible/upgrade-gaiad.yml deleted file mode 100644 index 4e81c74310..0000000000 --- a/networks/remote/ansible/upgrade-gaiad.yml +++ /dev/null @@ -1,11 +0,0 @@ ---- - -# Required: BINARY -# Optional: GENESISFILE, UNSAFE_RESET_ALL - -- hosts: all - any_errors_fatal: true - gather_facts: no - roles: - - upgrade-gaiad - diff --git a/networks/remote/terraform-app/.gitignore b/networks/remote/terraform-app/.gitignore deleted file mode 100644 index d882c9444a..0000000000 --- a/networks/remote/terraform-app/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -.terraform -terraform.tfstate -terraform.tfstate.backup -terraform.tfstate.d -.terraform.tfstate.lock.info diff --git a/networks/remote/terraform-app/files/terraform.sh b/networks/remote/terraform-app/files/terraform.sh deleted file mode 100644 index 60b4dd8e72..0000000000 --- a/networks/remote/terraform-app/files/terraform.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/bin/bash -# Script to initialize a testnet settings on a server - -#Usage: terraform.sh - -#Add gaiad node number for remote identification -echo "$2" > /etc/nodeid - diff --git a/networks/remote/terraform-app/infra/attachment.tf b/networks/remote/terraform-app/infra/attachment.tf deleted file mode 100644 index 1ba5f4fe58..0000000000 --- a/networks/remote/terraform-app/infra/attachment.tf +++ /dev/null @@ -1,21 +0,0 @@ -# This is the reason why we can't separate nodes and load balancer creation into different modules. -# https://github.com/hashicorp/terraform/issues/10857 -# In short: the list of instances coming from the nodes module is a generated variable -# and it should be the input for the load-balancer generation. However when attaching the instances -# to the load-balancer, aws_lb_target_group_attachment.count cannot be a generated value. - -#Instance Attachment (autoscaling is the future) -resource "aws_lb_target_group_attachment" "lb_attach" { - count = "${var.SERVERS*min(length(data.aws_availability_zones.zones.names),var.max_zones)}" - target_group_arn = "${aws_lb_target_group.lb_target_group.arn}" - target_id = "${element(aws_instance.node.*.id,count.index)}" - port = 26657 -} - -resource "aws_lb_target_group_attachment" "lb_attach_lcd" { - count = "${var.SERVERS*min(length(data.aws_availability_zones.zones.names),var.max_zones)}" - target_group_arn = "${aws_lb_target_group.lb_target_group_lcd.arn}" - target_id = "${element(aws_instance.node.*.id,count.index)}" - port = 1317 -} - diff --git a/networks/remote/terraform-app/infra/instance.tf b/networks/remote/terraform-app/infra/instance.tf deleted file mode 100644 index 53b21e62d5..0000000000 --- a/networks/remote/terraform-app/infra/instance.tf +++ /dev/null @@ -1,58 +0,0 @@ -resource "aws_key_pair" "key" { - key_name = "${var.name}" - public_key = "${file(var.ssh_public_file)}" -} - -data "aws_ami" "linux" { - most_recent = true - filter { - name = "name" - values = ["${var.image_name}"] - } -} - -resource "aws_instance" "node" { -# depends_on = ["${element(aws_route_table_association.route_table_association.*,count.index)}"] - count = "${var.SERVERS*min(length(data.aws_availability_zones.zones.names),var.max_zones)}" - ami = "${data.aws_ami.linux.image_id}" - instance_type = "${var.instance_type}" - key_name = "${aws_key_pair.key.key_name}" - associate_public_ip_address = true - vpc_security_group_ids = [ "${aws_security_group.secgroup.id}" ] - subnet_id = "${element(aws_subnet.subnet.*.id,count.index)}" - availability_zone = "${element(data.aws_availability_zones.zones.names,count.index)}" - - tags { - Environment = "${var.name}" - Name = "${var.name}-${element(data.aws_availability_zones.zones.names,count.index)}" - } - - volume_tags { - Environment = "${var.name}" - Name = "${var.name}-${element(data.aws_availability_zones.zones.names,count.index)}-VOLUME" - } - - root_block_device { - volume_size = 40 - } - - connection { - user = "centos" - private_key = "${file(var.ssh_private_file)}" - timeout = "600s" - } - - provisioner "file" { - source = "files/terraform.sh" - destination = "/tmp/terraform.sh" - } - - provisioner "remote-exec" { - inline = [ - "chmod +x /tmp/terraform.sh", - "sudo /tmp/terraform.sh ${var.name} ${count.index}", - ] - } - -} - diff --git a/networks/remote/terraform-app/infra/lb.tf b/networks/remote/terraform-app/infra/lb.tf deleted file mode 100644 index 201a53ffd8..0000000000 --- a/networks/remote/terraform-app/infra/lb.tf +++ /dev/null @@ -1,52 +0,0 @@ -resource "aws_lb" "lb" { - name = "${var.name}" - subnets = ["${aws_subnet.subnet.*.id}"] - security_groups = ["${aws_security_group.secgroup.id}"] - tags { - Name = "${var.name}" - } -# access_logs { -# bucket = "${var.s3_bucket}" -# prefix = "lblogs" -# } -} - -resource "aws_lb_listener" "lb_listener" { - load_balancer_arn = "${aws_lb.lb.arn}" - port = "443" - protocol = "HTTPS" - ssl_policy = "ELBSecurityPolicy-TLS-1-2-Ext-2018-06" - certificate_arn = "${var.certificate_arn}" - - default_action { - target_group_arn = "${aws_lb_target_group.lb_target_group.arn}" - type = "forward" - } -} - -resource "aws_lb_listener_rule" "listener_rule" { - listener_arn = "${aws_lb_listener.lb_listener.arn}" - priority = "100" - action { - type = "forward" - target_group_arn = "${aws_lb_target_group.lb_target_group.id}" - } - condition { - field = "path-pattern" - values = ["/"] - } -} - -resource "aws_lb_target_group" "lb_target_group" { - name = "${var.name}" - port = "26657" - protocol = "HTTP" - vpc_id = "${aws_vpc.vpc.id}" - tags { - name = "${var.name}" - } - health_check { - path = "/health" - } -} - diff --git a/networks/remote/terraform-app/infra/lcd.tf b/networks/remote/terraform-app/infra/lcd.tf deleted file mode 100644 index 5d09903d0f..0000000000 --- a/networks/remote/terraform-app/infra/lcd.tf +++ /dev/null @@ -1,39 +0,0 @@ -resource "aws_lb_listener" "lb_listener_lcd" { - load_balancer_arn = "${aws_lb.lb.arn}" - port = "1317" - protocol = "HTTPS" - ssl_policy = "ELBSecurityPolicy-TLS-1-2-Ext-2018-06" - certificate_arn = "${var.certificate_arn}" - - default_action { - target_group_arn = "${aws_lb_target_group.lb_target_group_lcd.arn}" - type = "forward" - } -} - -resource "aws_lb_listener_rule" "listener_rule_lcd" { - listener_arn = "${aws_lb_listener.lb_listener_lcd.arn}" - priority = "100" - action { - type = "forward" - target_group_arn = "${aws_lb_target_group.lb_target_group_lcd.id}" - } - condition { - field = "path-pattern" - values = ["/"] - } -} - -resource "aws_lb_target_group" "lb_target_group_lcd" { - name = "${var.name}lcd" - port = "1317" - protocol = "HTTP" - vpc_id = "${aws_vpc.vpc.id}" - tags { - name = "${var.name}" - } - health_check { - path = "/node_version" - } -} - diff --git a/networks/remote/terraform-app/infra/outputs.tf b/networks/remote/terraform-app/infra/outputs.tf deleted file mode 100644 index fdb32611c3..0000000000 --- a/networks/remote/terraform-app/infra/outputs.tf +++ /dev/null @@ -1,24 +0,0 @@ -// The cluster name -output "name" { - value = "${var.name}" -} - -// The list of cluster instance IDs -output "instances" { - value = ["${aws_instance.node.*.id}"] -} - -#output "instances_count" { -# value = "${length(aws_instance.node.*)}" -#} - -// The list of cluster instance public IPs -output "public_ips" { - value = ["${aws_instance.node.*.public_ip}"] -} - -// Name of the ALB -output "lb_name" { - value = "${aws_lb.lb.dns_name}" -} - diff --git a/networks/remote/terraform-app/infra/variables.tf b/networks/remote/terraform-app/infra/variables.tf deleted file mode 100644 index 0a96f14432..0000000000 --- a/networks/remote/terraform-app/infra/variables.tf +++ /dev/null @@ -1,39 +0,0 @@ -variable "name" { - description = "The testnet name, e.g cdn" -} - -variable "image_name" { - description = "Image name" - default = "CentOS Linux 7 x86_64 HVM EBS 1704_01" -} - -variable "instance_type" { - description = "The instance size to use" - default = "t2.small" -} - -variable "SERVERS" { - description = "Number of servers in an availability zone" - default = "1" -} - -variable "max_zones" { - description = "Maximum number of availability zones to use" - default = "1" -} - -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 "certificate_arn" { - description = "Load-balancer SSL certificate AWS ARN" - type = "string" -} - diff --git a/networks/remote/terraform-app/infra/vpc.tf b/networks/remote/terraform-app/infra/vpc.tf deleted file mode 100644 index 638ccfe0b3..0000000000 --- a/networks/remote/terraform-app/infra/vpc.tf +++ /dev/null @@ -1,104 +0,0 @@ -resource "aws_vpc" "vpc" { - cidr_block = "10.0.0.0/16" - - tags { - Name = "${var.name}" - } - -} - -resource "aws_internet_gateway" "internet_gateway" { - vpc_id = "${aws_vpc.vpc.id}" - - tags { - Name = "${var.name}" - } -} - -resource "aws_route_table" "route_table" { - vpc_id = "${aws_vpc.vpc.id}" - - route { - cidr_block = "0.0.0.0/0" - gateway_id = "${aws_internet_gateway.internet_gateway.id}" - } - - tags { - Name = "${var.name}" - } -} - -data "aws_availability_zones" "zones" { - state = "available" -} - -resource "aws_subnet" "subnet" { - count = "${min(length(data.aws_availability_zones.zones.names),var.max_zones)}" - vpc_id = "${aws_vpc.vpc.id}" - availability_zone = "${element(data.aws_availability_zones.zones.names,count.index)}" - cidr_block = "${cidrsubnet(aws_vpc.vpc.cidr_block, 8, count.index)}" - map_public_ip_on_launch = "true" - - tags { - Name = "${var.name}-${element(data.aws_availability_zones.zones.names,count.index)}" - } -} - -resource "aws_route_table_association" "route_table_association" { - count = "${min(length(data.aws_availability_zones.zones.names),var.max_zones)}" - subnet_id = "${element(aws_subnet.subnet.*.id,count.index)}" - route_table_id = "${aws_route_table.route_table.id}" -} - -resource "aws_security_group" "secgroup" { - name = "${var.name}" - vpc_id = "${aws_vpc.vpc.id}" - description = "Automated security group for application instances" - tags { - Name = "${var.name}" - } - - ingress { - from_port = 22 - to_port = 22 - protocol = "tcp" - cidr_blocks = ["0.0.0.0/0"] - } - - ingress { - from_port = 443 - to_port = 443 - protocol = "tcp" - cidr_blocks = ["0.0.0.0/0"] - } - - ingress { - from_port = 1317 - to_port = 1317 - protocol = "tcp" - cidr_blocks = ["0.0.0.0/0"] - } - - ingress { - from_port = 26656 - to_port = 26657 - protocol = "tcp" - cidr_blocks = ["0.0.0.0/0"] - } - - ingress { - from_port = 26660 - to_port = 26660 - protocol = "tcp" - cidr_blocks = ["0.0.0.0/0"] - } - - egress { - from_port = 0 - to_port = 0 - protocol = "-1" - cidr_blocks = ["0.0.0.0/0"] - - } -} - diff --git a/networks/remote/terraform-app/main.tf b/networks/remote/terraform-app/main.tf deleted file mode 100644 index 687e3b5b7c..0000000000 --- a/networks/remote/terraform-app/main.tf +++ /dev/null @@ -1,73 +0,0 @@ -#Terraform Configuration - -variable "APP_NAME" { - description = "Name of the application" -} - -variable "SERVERS" { - description = "Number of servers in an availability zone" - default = "1" -} - -variable "MAX_ZONES" { - description = "Maximum number of availability zones to use" - default = "4" -} - -#See https://docs.aws.amazon.com/general/latest/gr/rande.html#ec2_region -#eu-west-3 does not contain CentOS images -variable "REGION" { - description = "AWS Regions" - default = "us-east-1" -} - -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 "CERTIFICATE_ARN" { - description = "Load-balancer certificate AWS ARN" - type = "string" -} - -# ap-southeast-1 and ap-southeast-2 does not contain the newer CentOS 1704 image -variable "image" { - description = "AWS image name" - default = "CentOS Linux 7 x86_64 HVM EBS 1703_01" -} - -variable "instance_type" { - description = "AWS instance type" - default = "t2.large" -} - -provider "aws" { - region = "${var.REGION}" -} - -module "nodes" { - source = "infra" - name = "${var.APP_NAME}" - image_name = "${var.image}" - instance_type = "${var.instance_type}" - ssh_public_file = "${var.SSH_PUBLIC_FILE}" - ssh_private_file = "${var.SSH_PRIVATE_FILE}" - certificate_arn = "${var.CERTIFICATE_ARN}" - SERVERS = "${var.SERVERS}" - max_zones = "${var.MAX_ZONES}" -} - -output "public_ips" { - value = "${module.nodes.public_ips}", -} - -output "lb_name" { - value = "${module.nodes.lb_name}" -} - diff --git a/networks/remote/terraform-aws/.gitignore b/networks/remote/terraform-aws/.gitignore deleted file mode 100644 index d882c9444a..0000000000 --- a/networks/remote/terraform-aws/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -.terraform -terraform.tfstate -terraform.tfstate.backup -terraform.tfstate.d -.terraform.tfstate.lock.info diff --git a/networks/remote/terraform-aws/files/terraform.sh b/networks/remote/terraform-aws/files/terraform.sh deleted file mode 100644 index 47363b37dd..0000000000 --- a/networks/remote/terraform-aws/files/terraform.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/bash -# Script to initialize a testnet settings on a server - -#Usage: terraform.sh - -#Add gaiad node number for remote identification -REGION="$(($2 + 1))" -RNODE="$(($3 + 1))" -ID="$((${REGION} * 100 + ${RNODE}))" -echo "$ID" > /etc/nodeid - diff --git a/networks/remote/terraform-aws/main.tf b/networks/remote/terraform-aws/main.tf deleted file mode 100644 index 41e05995e5..0000000000 --- a/networks/remote/terraform-aws/main.tf +++ /dev/null @@ -1,249 +0,0 @@ -#Terraform Configuration - -#See https://docs.aws.amazon.com/general/latest/gr/rande.html#ec2_region -#eu-west-3 does not contain CentOS images -#us-east-1 usually contains other infrastructure and creating keys and security groups might conflict with that -variable "REGIONS" { - description = "AWS Regions" - type = "list" - default = ["us-east-2", "us-west-1", "us-west-2", "ap-south-1", "ap-northeast-2", "ap-southeast-1", "ap-southeast-2", "ap-northeast-1", "ca-central-1", "eu-central-1", "eu-west-1", "eu-west-2", "sa-east-1"] -} - -variable "TESTNET_NAME" { - description = "Name of the testnet" - default = "remotenet" -} - -variable "REGION_LIMIT" { - description = "Number of regions to populate" - default = "1" -} - -variable "SERVERS" { - description = "Number of servers in an availability zone" - default = "1" -} - -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" -} - - -# ap-southeast-1 and ap-southeast-2 does not contain the newer CentOS 1704 image -variable "image" { - description = "AWS image name" - default = "CentOS Linux 7 x86_64 HVM EBS 1703_01" -} - -variable "instance_type" { - description = "AWS instance type" - default = "t2.large" -} - -module "nodes-0" { - source = "nodes" - name = "${var.TESTNET_NAME}" - image_name = "${var.image}" - instance_type = "${var.instance_type}" - region = "${element(var.REGIONS,0)}" - multiplier = "0" - execute = "${var.REGION_LIMIT > 0}" - ssh_public_file = "${var.SSH_PUBLIC_FILE}" - ssh_private_file = "${var.SSH_PRIVATE_FILE}" - SERVERS = "${var.SERVERS}" -} - -module "nodes-1" { - source = "nodes" - name = "${var.TESTNET_NAME}" - image_name = "${var.image}" - instance_type = "${var.instance_type}" - region = "${element(var.REGIONS,1)}" - multiplier = "1" - execute = "${var.REGION_LIMIT > 1}" - ssh_public_file = "${var.SSH_PUBLIC_FILE}" - ssh_private_file = "${var.SSH_PRIVATE_FILE}" - SERVERS = "${var.SERVERS}" -} - -module "nodes-2" { - source = "nodes" - name = "${var.TESTNET_NAME}" - image_name = "${var.image}" - instance_type = "${var.instance_type}" - region = "${element(var.REGIONS,2)}" - multiplier = "2" - execute = "${var.REGION_LIMIT > 2}" - ssh_public_file = "${var.SSH_PUBLIC_FILE}" - ssh_private_file = "${var.SSH_PRIVATE_FILE}" - SERVERS = "${var.SERVERS}" -} - -module "nodes-3" { - source = "nodes" - name = "${var.TESTNET_NAME}" - image_name = "${var.image}" - instance_type = "${var.instance_type}" - region = "${element(var.REGIONS,3)}" - multiplier = "3" - execute = "${var.REGION_LIMIT > 3}" - ssh_public_file = "${var.SSH_PUBLIC_FILE}" - ssh_private_file = "${var.SSH_PRIVATE_FILE}" - SERVERS = "${var.SERVERS}" -} - -module "nodes-4" { - source = "nodes" - name = "${var.TESTNET_NAME}" - image_name = "${var.image}" - instance_type = "${var.instance_type}" - region = "${element(var.REGIONS,4)}" - multiplier = "4" - execute = "${var.REGION_LIMIT > 4}" - ssh_public_file = "${var.SSH_PUBLIC_FILE}" - ssh_private_file = "${var.SSH_PRIVATE_FILE}" - SERVERS = "${var.SERVERS}" -} - -module "nodes-5" { - source = "nodes" - name = "${var.TESTNET_NAME}" - image_name = "${var.image}" - instance_type = "${var.instance_type}" - region = "${element(var.REGIONS,5)}" - multiplier = "5" - execute = "${var.REGION_LIMIT > 5}" - ssh_public_file = "${var.SSH_PUBLIC_FILE}" - ssh_private_file = "${var.SSH_PRIVATE_FILE}" - SERVERS = "${var.SERVERS}" -} - -module "nodes-6" { - source = "nodes" - name = "${var.TESTNET_NAME}" - image_name = "${var.image}" - instance_type = "${var.instance_type}" - region = "${element(var.REGIONS,6)}" - multiplier = "6" - execute = "${var.REGION_LIMIT > 6}" - ssh_public_file = "${var.SSH_PUBLIC_FILE}" - ssh_private_file = "${var.SSH_PRIVATE_FILE}" - SERVERS = "${var.SERVERS}" -} - -module "nodes-7" { - source = "nodes" - name = "${var.TESTNET_NAME}" - image_name = "${var.image}" - instance_type = "${var.instance_type}" - region = "${element(var.REGIONS,7)}" - multiplier = "7" - execute = "${var.REGION_LIMIT > 7}" - ssh_public_file = "${var.SSH_PUBLIC_FILE}" - ssh_private_file = "${var.SSH_PRIVATE_FILE}" - SERVERS = "${var.SERVERS}" -} - -module "nodes-8" { - source = "nodes" - name = "${var.TESTNET_NAME}" - image_name = "${var.image}" - instance_type = "${var.instance_type}" - region = "${element(var.REGIONS,8)}" - multiplier = "8" - execute = "${var.REGION_LIMIT > 8}" - ssh_public_file = "${var.SSH_PUBLIC_FILE}" - ssh_private_file = "${var.SSH_PRIVATE_FILE}" - SERVERS = "${var.SERVERS}" -} - -module "nodes-9" { - source = "nodes" - name = "${var.TESTNET_NAME}" - image_name = "${var.image}" - instance_type = "${var.instance_type}" - region = "${element(var.REGIONS,9)}" - multiplier = "9" - execute = "${var.REGION_LIMIT > 9}" - ssh_public_file = "${var.SSH_PUBLIC_FILE}" - ssh_private_file = "${var.SSH_PRIVATE_FILE}" - SERVERS = "${var.SERVERS}" -} - -module "nodes-10" { - source = "nodes" - name = "${var.TESTNET_NAME}" - image_name = "${var.image}" - instance_type = "${var.instance_type}" - region = "${element(var.REGIONS,10)}" - multiplier = "10" - execute = "${var.REGION_LIMIT > 10}" - ssh_public_file = "${var.SSH_PUBLIC_FILE}" - ssh_private_file = "${var.SSH_PRIVATE_FILE}" - SERVERS = "${var.SERVERS}" -} - -module "nodes-11" { - source = "nodes" - name = "${var.TESTNET_NAME}" - image_name = "${var.image}" - instance_type = "${var.instance_type}" - region = "${element(var.REGIONS,11)}" - multiplier = "11" - execute = "${var.REGION_LIMIT > 11}" - ssh_public_file = "${var.SSH_PUBLIC_FILE}" - ssh_private_file = "${var.SSH_PRIVATE_FILE}" - SERVERS = "${var.SERVERS}" -} - -module "nodes-12" { - source = "nodes" - name = "${var.TESTNET_NAME}" - image_name = "${var.image}" - instance_type = "${var.instance_type}" - region = "${element(var.REGIONS,12)}" - multiplier = "12" - execute = "${var.REGION_LIMIT > 12}" - ssh_public_file = "${var.SSH_PUBLIC_FILE}" - ssh_private_file = "${var.SSH_PRIVATE_FILE}" - SERVERS = "${var.SERVERS}" -} - -module "nodes-13" { - source = "nodes" - name = "${var.TESTNET_NAME}" - image_name = "${var.image}" - instance_type = "${var.instance_type}" - region = "${element(var.REGIONS,13)}" - multiplier = "13" - execute = "${var.REGION_LIMIT > 13}" - ssh_public_file = "${var.SSH_PUBLIC_FILE}" - ssh_private_file = "${var.SSH_PRIVATE_FILE}" - SERVERS = "${var.SERVERS}" -} - -output "public_ips" { - value = "${concat( - module.nodes-0.public_ips, - module.nodes-1.public_ips, - module.nodes-2.public_ips, - module.nodes-3.public_ips, - module.nodes-4.public_ips, - module.nodes-5.public_ips, - module.nodes-6.public_ips, - module.nodes-7.public_ips, - module.nodes-8.public_ips, - module.nodes-9.public_ips, - module.nodes-10.public_ips, - module.nodes-11.public_ips, - module.nodes-12.public_ips, - module.nodes-13.public_ips - )}", -} - diff --git a/networks/remote/terraform-aws/nodes/main.tf b/networks/remote/terraform-aws/nodes/main.tf deleted file mode 100644 index 825be4af62..0000000000 --- a/networks/remote/terraform-aws/nodes/main.tf +++ /dev/null @@ -1,104 +0,0 @@ - -provider "aws" { - region = "${var.region}" -} - -resource "aws_key_pair" "testnets" { - count = "${var.execute?1:0}" - key_name = "testnets-${var.name}" - public_key = "${file(var.ssh_public_file)}" -} - -data "aws_ami" "linux" { - most_recent = true - filter { - name = "name" - values = ["${var.image_name}"] - } -} - -data "aws_availability_zones" "zones" { - state = "available" -} - -resource "aws_security_group" "secgroup" { - count = "${var.execute?1:0}" - name = "${var.name}" - description = "Automated security group for performance testing testnets" - tags { - Name = "testnets-${var.name}" - } - - ingress { - from_port = 22 - to_port = 22 - protocol = "tcp" - cidr_blocks = ["0.0.0.0/0"] - } - - ingress { - from_port = 26656 - to_port = 26657 - protocol = "tcp" - cidr_blocks = ["0.0.0.0/0"] - } - - ingress { - from_port = 26660 - to_port = 26660 - protocol = "tcp" - cidr_blocks = ["0.0.0.0/0"] - } - - egress { - from_port = 0 - to_port = 0 - protocol = "-1" - cidr_blocks = ["0.0.0.0/0"] - - } -} - -resource "aws_instance" "node" { - count = "${var.execute?var.SERVERS*length(data.aws_availability_zones.zones.names):0}" - ami = "${data.aws_ami.linux.image_id}" - instance_type = "${var.instance_type}" - key_name = "${aws_key_pair.testnets.key_name}" - associate_public_ip_address = true - security_groups = [ "${aws_security_group.secgroup.name}" ] - availability_zone = "${element(data.aws_availability_zones.zones.names,count.index)}" - - tags { - Environment = "${var.name}" - Name = "${var.name}-${element(data.aws_availability_zones.zones.names,count.index)}" - } - - volume_tags { - Environment = "${var.name}" - Name = "${var.name}-${element(data.aws_availability_zones.zones.names,count.index)}-VOLUME" - } - - root_block_device { - volume_size = 40 - } - - connection { - user = "centos" - private_key = "${file(var.ssh_private_file)}" - timeout = "600s" - } - - provisioner "file" { - source = "files/terraform.sh" - destination = "/tmp/terraform.sh" - } - - provisioner "remote-exec" { - inline = [ - "chmod +x /tmp/terraform.sh", - "sudo /tmp/terraform.sh ${var.name} ${var.multiplier} ${count.index}", - ] - } - -} - diff --git a/networks/remote/terraform-aws/nodes/outputs.tf b/networks/remote/terraform-aws/nodes/outputs.tf deleted file mode 100644 index 2a4451d69f..0000000000 --- a/networks/remote/terraform-aws/nodes/outputs.tf +++ /dev/null @@ -1,15 +0,0 @@ -// The cluster name -output "name" { - value = "${var.name}" -} - -// The list of cluster instance IDs -output "instances" { - value = ["${aws_instance.node.*.id}"] -} - -// The list of cluster instance public IPs -output "public_ips" { - value = ["${aws_instance.node.*.public_ip}"] -} - diff --git a/networks/remote/terraform-aws/nodes/variables.tf b/networks/remote/terraform-aws/nodes/variables.tf deleted file mode 100644 index ef540e697a..0000000000 --- a/networks/remote/terraform-aws/nodes/variables.tf +++ /dev/null @@ -1,42 +0,0 @@ -variable "name" { - description = "The testnet name, e.g cdn" -} - -variable "image_name" { - description = "Image name" - default = "CentOS Linux 7 x86_64 HVM EBS 1704_01" -} - -variable "instance_type" { - description = "The instance size to use" - default = "t2.small" -} - -variable "region" { - description = "AWS region to use" -} - -variable "multiplier" { - description = "Multiplier for node identification" -} - -variable "execute" { - description = "Set to false to disable the module" - default = true -} - -variable "SERVERS" { - description = "Number of servers in an availability zone" - default = "1" -} - -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" -} - diff --git a/networks/remote/terraform-do/.gitignore b/networks/remote/terraform-do/.gitignore deleted file mode 100644 index 798052367b..0000000000 --- a/networks/remote/terraform-do/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -.terraform -terraform.tfstate -terraform.tfstate.backup -terraform.tfstate.d -.terraform.tfstate.lock.info - diff --git a/networks/remote/terraform-do/Makefile b/networks/remote/terraform-do/Makefile deleted file mode 100644 index 76040e2080..0000000000 --- a/networks/remote/terraform-do/Makefile +++ /dev/null @@ -1,100 +0,0 @@ -######################################## -### WARNING: The DigitalOcean scripts are deprecated. They are still here because -### they might be useful for developers. - -# Name of the testnet. Used in chain-id. -TESTNET_NAME?=remotenet - -# Name of the servers grouped together for management purposes. Used in tagging the servers in the cloud. -CLUSTER_NAME?=$(TESTNET_NAME) - -# Number of servers deployed in Digital Ocean. -# Number of servers to put in one availability zone in AWS. -SERVERS?=1 - -# Path to gaiad for deployment. Must be a Linux binary. -BINARY?=$(CURDIR)/../build/gaiad - -# Path to the genesis.json and config.toml files to deploy on full nodes. -GENESISFILE?=$(CURDIR)/../build/genesis.json -CONFIGFILE?=$(CURDIR)/../build/config.toml - -all: - @echo "There is no all. Only sum of the ones." - - -######################################## -### Extract genesis.json and config.toml from a node in a cluster - -extract-config: - @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 - cd remote/ansible && ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook -i inventory/digital_ocean.py -l "$(CLUSTER_NAME)" -e TESTNET_NAME="$(TESTNET_NAME)" -e GENESISFILE="$(GENESISFILE)" -e CONFIGFILE="$(CONFIGFILE)" extract-config.yml - - -######################################## -### Remote validator nodes using terraform and ansible in Digital Ocean - -validators-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 remote/terraform-do && terraform init && (terraform workspace new "$(CLUSTER_NAME)" || terraform workspace select "$(CLUSTER_NAME)") && terraform apply -auto-approve -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="$(CLUSTER_NAME)" -var SERVERS="$(SERVERS)" - cd remote/ansible && ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook -i inventory/digital_ocean.py -l "$(CLUSTER_NAME)" -u root -e BINARY=$(BINARY) -e TESTNET_NAME="$(TESTNET_NAME)" setup-validators.yml - cd remote/ansible && ansible-playbook -i inventory/digital_ocean.py -l "$(CLUSTER_NAME)" -u root start.yml - -validators-stop: - @if [ -z "$(DO_API_TOKEN)" ]; then echo "DO_API_TOKEN environment variable not set." ; false ; fi - cd remote/terraform-do && terraform workspace select "$(CLUSTER_NAME)" && terraform destroy -force -var DO_API_TOKEN="$(DO_API_TOKEN)" -var SSH_PUBLIC_FILE="$(HOME)/.ssh/id_rsa.pub" -var SSH_PRIVATE_FILE="$(HOME)/.ssh/id_rsa" && terraform workspace select default && terraform workspace delete "$(CLUSTER_NAME)" - rm -rf remote/ansible/keys/ - -validators-status: - cd remote/ansible && ansible-playbook -i inventory/digital_ocean.py -l "$(CLUSTER_NAME)" status.yml - - -######################################## -### Remote full nodes using terraform and ansible in Digital Ocean - -fullnodes-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 remote/terraform-do && terraform init && (terraform workspace new "$(CLUSTER_NAME)" || terraform workspace select "$(CLUSTER_NAME)") && 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="$(CLUSTER_NAME)" -var SERVERS="$(SERVERS)" - cd remote/ansible && ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook -i inventory/digital_ocean.py -l "$(CLUSTER_NAME)" -e BINARY=$(BINARY) -e TESTNET_NAME="$(TESTNET_NAME)" -e GENESISFILE="$(GENESISFILE)" -e CONFIGFILE="$(CONFIGFILE)" setup-fullnodes.yml - cd remote/ansible && ansible-playbook -i inventory/digital_ocean.py -l "$(CLUSTER_NAME)" -u root start.yml - -fullnodes-stop: - @if [ -z "$(DO_API_TOKEN)" ]; then echo "DO_API_TOKEN environment variable not set." ; false ; fi - cd remote/terraform-do && terraform workspace select "$(CLUSTER_NAME)" && terraform destroy -force -var DO_API_TOKEN="$(DO_API_TOKEN)" -var SSH_PUBLIC_FILE="$(HOME)/.ssh/id_rsa.pub" -var SSH_PRIVATE_FILE="$(HOME)/.ssh/id_rsa" && terraform workspace select default && terraform workspace delete "$(CLUSTER_NAME)" - -fullnodes-status: - cd remote/ansible && ansible-playbook -i inventory/digital_ocean.py -l "$(CLUSTER_NAME)" status.yml - - -######################################## -### Other calls - -upgrade-gaiad: - @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 remote/ansible && ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook -i inventory/digital_ocean.py -l "$(CLUSTER_NAME)" -e BINARY=$(BINARY) upgrade-gaiad.yml - -list: - remote/ansible/inventory/digital_ocean.py | python -c 'import json,sys ; print "\n".join(json.loads("".join(sys.stdin.readlines()))["$(CLUSTER_NAME)"]["hosts"])' - -install-datadog: - @if [ -z "$(DO_API_TOKEN)" ]; then echo "DO_API_TOKEN environment variable not set." ; false ; fi - @if [ -z "$(DD_API_KEY)" ]; then echo "DD_API_KEY environment variable not set." ; false ; fi - cd remote/ansible && ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook -i inventory/digital_ocean.py -l "$(CLUSTER_NAME)" -u root -e DD_API_KEY="$(DD_API_KEY)" -e TESTNET_NAME=$(TESTNET_NAME) -e CLUSTER_NAME=$(CLUSTER_NAME) install-datadog-agent.yml - -remove-datadog: - @if [ -z "$(DO_API_TOKEN)" ]; then echo "DO_API_TOKEN environment variable not set." ; false ; fi - cd remote/ansible && ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook -i inventory/digital_ocean.py -l "$(CLUSTER_NAME)" -u root remove-datadog-agent.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: all extract-config validators-start validators-stop validators-status fullnodes-start fullnodes-stop fullnodes-status upgrade-gaiad list-do install-datadog remove-datadog - diff --git a/networks/remote/terraform-do/README.md b/networks/remote/terraform-do/README.md deleted file mode 100644 index 0486a8bc4d..0000000000 --- a/networks/remote/terraform-do/README.md +++ /dev/null @@ -1,58 +0,0 @@ -# Terraform & Ansible - -WARNING: The Digital Ocean scripts are obsolete. They are here because they might still be useful for developers. - -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 -``` diff --git a/networks/remote/terraform-do/cluster/main.tf b/networks/remote/terraform-do/cluster/main.tf deleted file mode 100644 index 07331ff3d6..0000000000 --- a/networks/remote/terraform-do/cluster/main.tf +++ /dev/null @@ -1,40 +0,0 @@ -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)}" - } - - provisioner "file" { - source = "files/terraform.sh" - destination = "/tmp/terraform.sh" - } - - provisioner "remote-exec" { - inline = [ - "chmod +x /tmp/terraform.sh", - "/tmp/terraform.sh ${var.name} ${count.index}", - ] - } - -} - diff --git a/networks/remote/terraform-do/cluster/outputs.tf b/networks/remote/terraform-do/cluster/outputs.tf deleted file mode 100644 index 78291b6a97..0000000000 --- a/networks/remote/terraform-do/cluster/outputs.tf +++ /dev/null @@ -1,15 +0,0 @@ -// 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}"] -} - diff --git a/networks/remote/terraform-do/cluster/variables.tf b/networks/remote/terraform-do/cluster/variables.tf deleted file mode 100644 index e2654b11db..0000000000 --- a/networks/remote/terraform-do/cluster/variables.tf +++ /dev/null @@ -1,30 +0,0 @@ -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 -} - diff --git a/networks/remote/terraform-do/files/terraform.sh b/networks/remote/terraform-do/files/terraform.sh deleted file mode 100644 index 60b4dd8e72..0000000000 --- a/networks/remote/terraform-do/files/terraform.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/bin/bash -# Script to initialize a testnet settings on a server - -#Usage: terraform.sh - -#Add gaiad node number for remote identification -echo "$2" > /etc/nodeid - diff --git a/networks/remote/terraform-do/main.tf b/networks/remote/terraform-do/main.tf deleted file mode 100644 index fb78a37851..0000000000 --- a/networks/remote/terraform-do/main.tf +++ /dev/null @@ -1,43 +0,0 @@ -#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}" -} - diff --git a/networks/upgrade-gaiad.sh b/networks/upgrade-gaiad.sh deleted file mode 100755 index 1f920c02b1..0000000000 --- a/networks/upgrade-gaiad.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/sh -# upgrade-gaiad - example make call to upgrade gaiad on a set of nodes in AWS -# WARNING: Run it from the current directory - it uses relative paths to ship the binary and the genesis.json,config.toml files - -if [ $# -ne 1 ]; then - echo "Usage: ./upgrade-gaiad.sh " - exit 1 -fi -set -eux - -export CLUSTER_NAME=$1 - -make upgrade-gaiad - diff --git a/scripts/linkify_changelog.py b/scripts/linkify_changelog.py deleted file mode 100644 index 3423506e7e..0000000000 --- a/scripts/linkify_changelog.py +++ /dev/null @@ -1,13 +0,0 @@ -import fileinput -import re - -# This script goes through the provided file, and replaces any " \#", -# with the valid mark down formatted link to it. e.g. -# " [\#number](https://github.com/cosmos/cosmos-sdk/issues/) -# Note that if the number is for a PR, github will auto-redirect you when you click the link. -# It is safe to run the script multiple times in succession. -# -# Example usage $ python3 linkify_changelog.py ../PENDING.md -for line in fileinput.input(inplace=1): - line = re.sub(r"\s\\#([0-9]*)", r" [\\#\1](https://github.com/cosmos/cosmos-sdk/issues/\1)", line.rstrip()) - print(line) \ No newline at end of file diff --git a/scripts/localnet-blocks-test.sh b/scripts/localnet-blocks-test.sh deleted file mode 100755 index 53df090ff7..0000000000 --- a/scripts/localnet-blocks-test.sh +++ /dev/null @@ -1,41 +0,0 @@ -#!/bin/bash - -CNT=0 -ITER=$1 -SLEEP=$2 -NUMBLOCKS=$3 -NODEADDR=$4 - -if [ -z "$1" ]; then - echo "Need to input number of iterations to run..." - exit 1 -fi - -if [ -z "$2" ]; then - echo "Need to input number of seconds to sleep between iterations" - exit 1 -fi - -if [ -z "$3" ]; then - echo "Need to input block height to declare completion..." - exit 1 -fi - -if [ -z "$4" ]; then - echo "Need to input node address to poll..." - exit 1 -fi - -while [ ${CNT} -lt $ITER ]; do - var=$(curl -s $NODEADDR:26657/status | jq -r '.result.sync_info.latest_block_height') - echo "Number of Blocks: ${var}" - if [ ! -z ${var} ] && [ ${var} -gt ${NUMBLOCKS} ]; then - echo "Number of blocks reached, exiting success..." - exit 0 - fi - let CNT=CNT+1 - sleep $SLEEP -done - -echo "Timeout reached, exiting failure..." -exit 1 diff --git a/server/config/toml.go b/server/config/toml.go index 7f585b981f..e381ee204a 100644 --- a/server/config/toml.go +++ b/server/config/toml.go @@ -27,13 +27,14 @@ var configTemplate *template.Template func init() { var err error - tmpl := template.New("gaiaConfigFileTemplate") + tmpl := template.New("appConfigFileTemplate") if configTemplate, err = tmpl.Parse(defaultConfigTemplate); err != nil { panic(err) } } -// ParseConfig retrieves the default environment configuration for Gaia. +// ParseConfig retrieves the default environment configuration for the +// application. func ParseConfig() (*Config, error) { conf := DefaultConfig() err := viper.Unmarshal(conf) diff --git a/server/util.go b/server/util.go index 6fc4e5323c..8874c50459 100644 --- a/server/util.go +++ b/server/util.go @@ -105,17 +105,13 @@ func interceptLoadConfig() (conf *cfg.Config, err error) { conf, err = tcmd.ParseConfig() // NOTE: ParseConfig() creates dir/files as necessary. } - // create a default Gaia config file if it does not exist - // - // TODO: Rename config file to server.toml as it's not particular to Gaia - // (REF: https://github.com/cosmos/cosmos-sdk/issues/4125). - gaiaConfigFilePath := filepath.Join(rootDir, "config/gaiad.toml") - if _, err := os.Stat(gaiaConfigFilePath); os.IsNotExist(err) { - gaiaConf, _ := config.ParseConfig() - config.WriteConfigFile(gaiaConfigFilePath, gaiaConf) + appConfigFilePath := filepath.Join(rootDir, "config/app.toml") + if _, err := os.Stat(appConfigFilePath); os.IsNotExist(err) { + appConf, _ := config.ParseConfig() + config.WriteConfigFile(appConfigFilePath, appConf) } - viper.SetConfigName("gaiad") + viper.SetConfigName("app") err = viper.MergeInConfig() return diff --git a/cmd/gaia/app/app.go b/simapp/app.go similarity index 90% rename from cmd/gaia/app/app.go rename to simapp/app.go index 1cd5e797db..2ebd16dafd 100644 --- a/cmd/gaia/app/app.go +++ b/simapp/app.go @@ -1,4 +1,4 @@ -package app +package simapp import ( "io" @@ -26,14 +26,14 @@ import ( "github.com/tendermint/tendermint/libs/log" ) -const appName = "GaiaApp" +const appName = "SimApp" var ( - // default home directories for gaiacli - DefaultCLIHome = os.ExpandEnv("$HOME/.gaiacli") + // default home directories for the application CLI + DefaultCLIHome = os.ExpandEnv("$HOME/.simapp") - // default home directories for gaiad - DefaultNodeHome = os.ExpandEnv("$HOME/.gaiad") + // default home directories for the application daemon + DefaultNodeHome = os.ExpandEnv("$HOME/.simapp") // The ModuleBasicManager is in charge of setting up basic, // non-dependant module elements, such as codec registration @@ -67,7 +67,7 @@ func MakeCodec() *codec.Codec { } // Extended ABCI application -type GaiaApp struct { +type SimApp struct { *bam.BaseApp cdc *codec.Codec @@ -103,9 +103,9 @@ type GaiaApp struct { mm *sdk.ModuleManager } -// NewGaiaApp returns a reference to an initialized GaiaApp. -func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bool, - invCheckPeriod uint, baseAppOptions ...func(*bam.BaseApp)) *GaiaApp { +// NewSimApp returns a reference to an initialized SimApp. +func NewSimApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bool, + invCheckPeriod uint, baseAppOptions ...func(*bam.BaseApp)) *SimApp { cdc := MakeCodec() @@ -113,7 +113,7 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest b bApp.SetCommitMultiStoreTracer(traceStore) bApp.SetAppVersion(version.Version) - var app = &GaiaApp{ + var app = &SimApp{ BaseApp: bApp, cdc: cdc, invCheckPeriod: invCheckPeriod, @@ -218,23 +218,23 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest b } // application updates every begin block -func (app *GaiaApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { +func (app *SimApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { return app.mm.BeginBlock(ctx, req) } // application updates every end block -func (app *GaiaApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { +func (app *SimApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { return app.mm.EndBlock(ctx, req) } // application update at chain initialization -func (app *GaiaApp) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { +func (app *SimApp) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { var genesisState GenesisState app.cdc.MustUnmarshalJSON(req.AppStateBytes, &genesisState) return app.mm.InitGenesis(ctx, genesisState) } // load a particular height -func (app *GaiaApp) LoadHeight(height int64) error { +func (app *SimApp) LoadHeight(height int64) error { return app.LoadVersion(height, app.keyMain) } diff --git a/cmd/gaia/app/app_test.go b/simapp/app_test.go similarity index 59% rename from cmd/gaia/app/app_test.go rename to simapp/app_test.go index 1e880cd944..d93a807342 100644 --- a/cmd/gaia/app/app_test.go +++ b/simapp/app_test.go @@ -1,4 +1,4 @@ -package app +package simapp import ( "os" @@ -13,32 +13,32 @@ import ( abci "github.com/tendermint/tendermint/abci/types" ) -func TestGaiadExport(t *testing.T) { +func TestSimAppExport(t *testing.T) { db := db.NewMemDB() - gapp := NewGaiaApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, 0) - setGenesis(gapp) + app := NewSimApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, 0) + setGenesis(app) // Making a new app object with the db, so that initchain hasn't been called - newGapp := NewGaiaApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, 0) - _, _, err := newGapp.ExportAppStateAndValidators(false, []string{}) + app2 := NewSimApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, 0) + _, _, err := app2.ExportAppStateAndValidators(false, []string{}) require.NoError(t, err, "ExportAppStateAndValidators should not have an error") } -func setGenesis(gapp *GaiaApp) error { - +func setGenesis(app *SimApp) error { genesisState := NewDefaultGenesisState() - stateBytes, err := codec.MarshalJSONIndent(gapp.cdc, genesisState) + stateBytes, err := codec.MarshalJSONIndent(app.cdc, genesisState) if err != nil { return err } // Initialize the chain - gapp.InitChain( + app.InitChain( abci.RequestInitChain{ Validators: []abci.ValidatorUpdate{}, AppStateBytes: stateBytes, }, ) - gapp.Commit() + + app.Commit() return nil } diff --git a/cmd/gaia/app/export.go b/simapp/export.go similarity index 94% rename from cmd/gaia/app/export.go rename to simapp/export.go index b9fc3366f2..1447750901 100644 --- a/cmd/gaia/app/export.go +++ b/simapp/export.go @@ -1,4 +1,4 @@ -package app +package simapp import ( "encoding/json" @@ -13,8 +13,10 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking" ) -// export the state of gaia for a genesis file -func (app *GaiaApp) ExportAppStateAndValidators(forZeroHeight bool, jailWhiteList []string, +// ExportAppStateAndValidators exports the state of the application for a genesis +// file. +func (app *SimApp) ExportAppStateAndValidators( + forZeroHeight bool, jailWhiteList []string, ) (appState json.RawMessage, validators []tmtypes.GenesisValidator, err error) { // as if they could withdraw from the start of the next block @@ -29,6 +31,7 @@ func (app *GaiaApp) ExportAppStateAndValidators(forZeroHeight bool, jailWhiteLis if err != nil { return nil, nil, err } + validators = staking.WriteValidators(ctx, app.stakingKeeper) return appState, validators, nil } @@ -36,7 +39,7 @@ func (app *GaiaApp) ExportAppStateAndValidators(forZeroHeight bool, jailWhiteLis // prepare for fresh start at zero height // NOTE zero height genesis is a temporary feature which will be deprecated // in favour of export at a block height -func (app *GaiaApp) prepForZeroHeightGenesis(ctx sdk.Context, jailWhiteList []string) { +func (app *SimApp) prepForZeroHeightGenesis(ctx sdk.Context, jailWhiteList []string) { applyWhiteList := false //Check if there is a whitelist diff --git a/cmd/gaia/app/genesis.go b/simapp/genesis.go similarity index 86% rename from cmd/gaia/app/genesis.go rename to simapp/genesis.go index d4e99dd4f9..d96c6feec9 100644 --- a/cmd/gaia/app/genesis.go +++ b/simapp/genesis.go @@ -1,4 +1,4 @@ -package app +package simapp import ( "encoding/json" @@ -13,7 +13,7 @@ import ( // object provided to it during init. type GenesisState map[string]json.RawMessage -// NewDefaultGenesisState generates the default state for gaia. +// NewDefaultGenesisState generates the default state for the application. func NewDefaultGenesisState() GenesisState { return ModuleBasics.DefaultGenesis() } diff --git a/cmd/gaia/app/sim_test.go b/simapp/sim_test.go similarity index 90% rename from cmd/gaia/app/sim_test.go rename to simapp/sim_test.go index 2beb339668..640e3eec9e 100644 --- a/cmd/gaia/app/sim_test.go +++ b/simapp/sim_test.go @@ -1,4 +1,4 @@ -package app +package simapp import ( "encoding/json" @@ -64,7 +64,7 @@ func init() { } // helper function for populating input for SimulateFromSeed -func getSimulateFromSeedInput(tb testing.TB, w io.Writer, app *GaiaApp) ( +func getSimulateFromSeedInput(tb testing.TB, w io.Writer, app *SimApp) ( testing.TB, io.Writer, *baseapp.BaseApp, simulation.AppStateFn, int64, simulation.WeightedOperations, sdk.Invariants, int, int, bool, bool) { @@ -292,7 +292,7 @@ func appStateFn(r *rand.Rand, accs []simulation.Account, genesisTimestamp time.T return appStateRandomizedFn(r, accs, genesisTimestamp) } -func testAndRunTxs(app *GaiaApp) []simulation.WeightedOperation { +func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { return []simulation.WeightedOperation{ {5, authsim.SimulateDeductFee(app.accountKeeper, app.feeCollectionKeeper)}, {100, banksim.SimulateMsgSend(app.accountKeeper, app.bankKeeper)}, @@ -312,7 +312,7 @@ func testAndRunTxs(app *GaiaApp) []simulation.WeightedOperation { } } -func invariants(app *GaiaApp) []sdk.Invariant { +func invariants(app *SimApp) []sdk.Invariant { return simulation.PeriodicInvariants(app.crisisKeeper.Invariants(), period, 0) } @@ -322,19 +322,18 @@ func fauxMerkleModeOpt(bapp *baseapp.BaseApp) { } // Profile with: -// /usr/local/go/bin/go test -benchmem -run=^$ github.com/cosmos/cosmos-sdk/cmd/gaia/app -bench ^BenchmarkFullGaiaSimulation$ -SimulationCommit=true -cpuprofile cpu.out -func BenchmarkFullGaiaSimulation(b *testing.B) { - // Setup Gaia application +// /usr/local/go/bin/go test -benchmem -run=^$ github.com/cosmos/cosmos-sdk/simapp -bench ^BenchmarkFullAppSimulation$ -SimulationCommit=true -cpuprofile cpu.out +func BenchmarkFullAppSimulation(b *testing.B) { logger := log.NewNopLogger() var db dbm.DB - dir, _ := ioutil.TempDir("", "goleveldb-gaia-sim") + dir, _ := ioutil.TempDir("", "goleveldb-app-sim") db, _ = sdk.NewLevelDB("Simulation", dir) defer func() { db.Close() os.RemoveAll(dir) }() - app := NewGaiaApp(logger, db, nil, true, 0) + app := NewSimApp(logger, db, nil, true, 0) // Run randomized simulation // TODO parameterize numbers, save for a later PR @@ -350,27 +349,30 @@ func BenchmarkFullGaiaSimulation(b *testing.B) { } } -func TestFullGaiaSimulation(t *testing.T) { +func TestFullAppSimulation(t *testing.T) { if !enabled { - t.Skip("Skipping Gaia simulation") + t.Skip("Skipping application simulation") } - // Setup Gaia application var logger log.Logger + if verbose { logger = log.TestingLogger() } else { logger = log.NewNopLogger() } + var db dbm.DB - dir, _ := ioutil.TempDir("", "goleveldb-gaia-sim") + dir, _ := ioutil.TempDir("", "goleveldb-app-sim") db, _ = sdk.NewLevelDB("Simulation", dir) + defer func() { db.Close() os.RemoveAll(dir) }() - app := NewGaiaApp(logger, db, nil, true, 0, fauxMerkleModeOpt) - require.Equal(t, "GaiaApp", app.Name()) + + app := NewSimApp(logger, db, nil, true, 0, fauxMerkleModeOpt) + require.Equal(t, "SimApp", app.Name()) // Run randomized simulation _, err := simulation.SimulateFromSeed(getSimulateFromSeedInput(t, os.Stdout, app)) @@ -381,30 +383,33 @@ func TestFullGaiaSimulation(t *testing.T) { fmt.Println(db.Stats()["leveldb.stats"]) fmt.Println("GoLevelDB cached block size", db.Stats()["leveldb.cachedblock"]) } + require.Nil(t, err) } -func TestGaiaImportExport(t *testing.T) { +func TestAppImportExport(t *testing.T) { if !enabled { - t.Skip("Skipping Gaia import/export simulation") + t.Skip("Skipping application import/export simulation") } - // Setup Gaia application var logger log.Logger if verbose { logger = log.TestingLogger() } else { logger = log.NewNopLogger() } + var db dbm.DB - dir, _ := ioutil.TempDir("", "goleveldb-gaia-sim") + dir, _ := ioutil.TempDir("", "goleveldb-app-sim") db, _ = sdk.NewLevelDB("Simulation", dir) + defer func() { db.Close() os.RemoveAll(dir) }() - app := NewGaiaApp(logger, db, nil, true, 0, fauxMerkleModeOpt) - require.Equal(t, "GaiaApp", app.Name()) + + app := NewSimApp(logger, db, nil, true, 0, fauxMerkleModeOpt) + require.Equal(t, "SimApp", app.Name()) // Run randomized simulation _, err := simulation.SimulateFromSeed(getSimulateFromSeedInput(t, os.Stdout, app)) @@ -416,37 +421,43 @@ func TestGaiaImportExport(t *testing.T) { fmt.Println(db.Stats()["leveldb.stats"]) fmt.Println("GoLevelDB cached block size", db.Stats()["leveldb.cachedblock"]) } - require.Nil(t, err) + require.Nil(t, err) fmt.Printf("Exporting genesis...\n") appState, _, err := app.ExportAppStateAndValidators(false, []string{}) require.NoError(t, err) fmt.Printf("Importing genesis...\n") - newDir, _ := ioutil.TempDir("", "goleveldb-gaia-sim-2") + newDir, _ := ioutil.TempDir("", "goleveldb-app-sim-2") newDB, _ := sdk.NewLevelDB("Simulation-2", dir) + defer func() { newDB.Close() os.RemoveAll(newDir) }() - newApp := NewGaiaApp(log.NewNopLogger(), newDB, nil, true, 0, fauxMerkleModeOpt) - require.Equal(t, "GaiaApp", newApp.Name()) + + newApp := NewSimApp(log.NewNopLogger(), newDB, nil, true, 0, fauxMerkleModeOpt) + require.Equal(t, "SimApp", newApp.Name()) + var genesisState GenesisState err = app.cdc.UnmarshalJSON(appState, &genesisState) if err != nil { panic(err) } + ctxB := newApp.NewContext(true, abci.Header{}) newApp.mm.InitGenesis(ctxB, genesisState) fmt.Printf("Comparing stores...\n") ctxA := app.NewContext(true, abci.Header{}) + type StoreKeysPrefixes struct { A sdk.StoreKey B sdk.StoreKey Prefixes [][]byte } + storeKeysPrefixes := []StoreKeysPrefixes{ {app.keyMain, newApp.keyMain, [][]byte{}}, {app.keyAccount, newApp.keyAccount, [][]byte{}}, @@ -459,6 +470,7 @@ func TestGaiaImportExport(t *testing.T) { {app.keyParams, newApp.keyParams, [][]byte{}}, {app.keyGov, newApp.keyGov, [][]byte{}}, } + for _, storeKeysPrefix := range storeKeysPrefixes { storeKeyA := storeKeysPrefix.A storeKeyB := storeKeysPrefix.B @@ -475,26 +487,28 @@ func TestGaiaImportExport(t *testing.T) { } -func TestGaiaSimulationAfterImport(t *testing.T) { +func TestAppSimulationAfterImport(t *testing.T) { if !enabled { - t.Skip("Skipping Gaia simulation after import") + t.Skip("Skipping application simulation after import") } - // Setup Gaia application var logger log.Logger if verbose { logger = log.TestingLogger() } else { logger = log.NewNopLogger() } - dir, _ := ioutil.TempDir("", "goleveldb-gaia-sim") + + dir, _ := ioutil.TempDir("", "goleveldb-app-sim") db, _ := sdk.NewLevelDB("Simulation", dir) + defer func() { db.Close() os.RemoveAll(dir) }() - app := NewGaiaApp(logger, db, nil, true, 0, fauxMerkleModeOpt) - require.Equal(t, "GaiaApp", app.Name()) + + app := NewSimApp(logger, db, nil, true, 0, fauxMerkleModeOpt) + require.Equal(t, "SimApp", app.Name()) // Run randomized simulation stopEarly, err := simulation.SimulateFromSeed(getSimulateFromSeedInput(t, os.Stdout, app)) @@ -506,6 +520,7 @@ func TestGaiaSimulationAfterImport(t *testing.T) { fmt.Println(db.Stats()["leveldb.stats"]) fmt.Println("GoLevelDB cached block size", db.Stats()["leveldb.cachedblock"]) } + require.Nil(t, err) if stopEarly { @@ -523,14 +538,16 @@ func TestGaiaSimulationAfterImport(t *testing.T) { fmt.Printf("Importing genesis...\n") - newDir, _ := ioutil.TempDir("", "goleveldb-gaia-sim-2") + newDir, _ := ioutil.TempDir("", "goleveldb-app-sim-2") newDB, _ := sdk.NewLevelDB("Simulation-2", dir) + defer func() { newDB.Close() os.RemoveAll(newDir) }() - newApp := NewGaiaApp(log.NewNopLogger(), newDB, nil, true, 0, fauxMerkleModeOpt) - require.Equal(t, "GaiaApp", newApp.Name()) + + newApp := NewSimApp(log.NewNopLogger(), newDB, nil, true, 0, fauxMerkleModeOpt) + require.Equal(t, "SimApp", newApp.Name()) newApp.InitChain(abci.RequestInitChain{ AppStateBytes: appState, }) @@ -538,14 +555,13 @@ func TestGaiaSimulationAfterImport(t *testing.T) { // Run randomized simulation on imported app _, err = simulation.SimulateFromSeed(getSimulateFromSeedInput(t, os.Stdout, newApp)) require.Nil(t, err) - } // TODO: Make another test for the fuzzer itself, which just has noOp txs -// and doesn't depend on gaia +// and doesn't depend on the application. func TestAppStateDeterminism(t *testing.T) { if !enabled { - t.Skip("Skipping Gaia simulation") + t.Skip("Skipping application simulation") } numSeeds := 3 @@ -557,7 +573,7 @@ func TestAppStateDeterminism(t *testing.T) { for j := 0; j < numTimesToRunPerSeed; j++ { logger := log.NewNopLogger() db := dbm.NewMemDB() - app := NewGaiaApp(logger, db, nil, true, 0) + app := NewSimApp(logger, db, nil, true, 0) // Run randomized simulation simulation.SimulateFromSeed( @@ -579,9 +595,8 @@ func TestAppStateDeterminism(t *testing.T) { } func BenchmarkInvariants(b *testing.B) { - // 1. Setup a simulated Gaia application logger := log.NewNopLogger() - dir, _ := ioutil.TempDir("", "goleveldb-gaia-invariant-bench") + dir, _ := ioutil.TempDir("", "goleveldb-app-invariant-bench") db, _ := sdk.NewLevelDB("simulation", dir) defer func() { @@ -589,7 +604,7 @@ func BenchmarkInvariants(b *testing.B) { os.RemoveAll(dir) }() - app := NewGaiaApp(logger, db, nil, true, 0) + app := NewSimApp(logger, db, nil, true, 0) // 2. Run parameterized simulation (w/o invariants) _, err := simulation.SimulateFromSeed( diff --git a/simapp/test_util.go b/simapp/test_util.go new file mode 100644 index 0000000000..8b79e757a9 --- /dev/null +++ b/simapp/test_util.go @@ -0,0 +1,23 @@ +package simapp + +import ( + "io" + + "github.com/tendermint/tendermint/libs/log" + + bam "github.com/cosmos/cosmos-sdk/baseapp" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/staking" + dbm "github.com/tendermint/tendermint/libs/db" +) + +// NewSimAppUNSAFE is used for debugging purposes only. +// +// NOTE: to not use this function with non-test code +func NewSimAppUNSAFE(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bool, + invCheckPeriod uint, baseAppOptions ...func(*bam.BaseApp), +) (gapp *SimApp, keyMain, keyStaking *sdk.KVStoreKey, stakingKeeper staking.Keeper) { + + gapp = NewSimApp(logger, db, traceStore, loadLatest, invCheckPeriod, baseAppOptions...) + return gapp, gapp.keyMain, gapp.keyStaking, gapp.stakingKeeper +} diff --git a/tests/test_cover.sh b/tests/test_cover.sh index e7629d6238..208de4ee0a 100644 --- a/tests/test_cover.sh +++ b/tests/test_cover.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -e -PKGS=$(go list ./... | grep -v /vendor/ | grep -v github.com/cosmos/cosmos-sdk/cmd/gaia/cli_test | grep -v '/simulation') +PKGS=$(go list ./... | grep -v '/simulation') set -e echo "mode: atomic" > coverage.txt diff --git a/x/auth/client/cli/multisign.go b/x/auth/client/cli/multisign.go index ec9613554b..5b3b6450b6 100644 --- a/x/auth/client/cli/multisign.go +++ b/x/auth/client/cli/multisign.go @@ -30,7 +30,7 @@ func GetMultiSignCommand(codec *amino.Codec) *cobra.Command { Read signature(s) from [signature] file(s), generate a multisig signature compliant to the multisig key [name], and attach it to the transaction read from [file]. Example: - gaiacli multisign transaction.json k1k2k3 k1sig.json k2sig.json k3sig.json + multisign transaction.json k1k2k3 k1sig.json k2sig.json k3sig.json If the flag --signature-only flag is on, it outputs a JSON representation of the generated signature only. diff --git a/x/crisis/keeper.go b/x/crisis/keeper.go index 5a25934d3b..51a5abf6ec 100644 --- a/x/crisis/keeper.go +++ b/x/crisis/keeper.go @@ -64,17 +64,18 @@ func (k Keeper) AssertInvariants(ctx sdk.Context, logger log.Logger) { for _, ir := range invarRoutes { if err := ir.Invar(ctx); err != nil { - // TODO make "gaiacli" app name a part of context to allow for this to be variable + // TODO: Include app name as part of context to allow for this to be + // variable. panic(fmt.Errorf("invariant broken: %s\n"+ "\tCRITICAL please submit the following transaction:\n"+ - "\t\t gaiacli tx crisis invariant-broken %v %v", err, ir.ModuleName, ir.Route)) + "\t\t tx crisis invariant-broken %v %v", err, ir.ModuleName, ir.Route)) } } + end := time.Now() diff := end.Sub(start) - logger.With("module", "x/crisis").Info( - "Asserted all invariants", "duration", diff, "height", ctx.BlockHeight()) + logger.With("module", "x/crisis").Info("asserted all invariants", "duration", diff, "height", ctx.BlockHeight()) } // DONTCOVER diff --git a/x/distribution/client/cli/query.go b/x/distribution/client/cli/query.go index bc5777ac07..455f7d12d3 100644 --- a/x/distribution/client/cli/query.go +++ b/x/distribution/client/cli/query.go @@ -62,7 +62,7 @@ func GetCmdQueryValidatorCommission(queryRoute string, cdc *codec.Codec) *cobra. Short: "Query distribution validator commission", Long: strings.TrimSpace(`Query validator commission rewards from delegators to that validator: -$ gaiacli query distr commission cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj +$ query distr commission cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj `), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) @@ -92,7 +92,7 @@ func GetCmdQueryValidatorSlashes(queryRoute string, cdc *codec.Codec) *cobra.Com Short: "Query distribution validator slashes", Long: strings.TrimSpace(`Query all slashes of a validator for a given block range: -$ gaiacli query distr slashes cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj 0 100 +$ query distr slashes cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj 0 100 `), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) @@ -138,8 +138,8 @@ func GetCmdQueryDelegatorRewards(queryRoute string, cdc *codec.Codec) *cobra.Com Short: "Query all distribution delegator rewards or rewards from a particular validator", Long: strings.TrimSpace(`Query all rewards earned by a delegator, optionally restrict to rewards from a single validator: -$ gaiacli query distr rewards cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p -$ gaiacli query distr rewards cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj +$ query distr rewards cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p +$ query distr rewards cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj `), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) @@ -177,7 +177,7 @@ func GetCmdQueryCommunityPool(queryRoute string, cdc *codec.Codec) *cobra.Comman Short: "Query the amount of coins in the community pool", Long: strings.TrimSpace(`Query all coins in the community pool which is under Governance control. -$ gaiacli query distr community-pool +$ query distr community-pool `), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) diff --git a/x/distribution/client/cli/tx.go b/x/distribution/client/cli/tx.go index a51394568e..d69556d423 100644 --- a/x/distribution/client/cli/tx.go +++ b/x/distribution/client/cli/tx.go @@ -47,8 +47,8 @@ func GetCmdWithdrawRewards(cdc *codec.Codec) *cobra.Command { Short: "witdraw rewards from a given delegation address, and optionally withdraw validator commission if the delegation address given is a validator operator", Long: strings.TrimSpace(`witdraw rewards from a given delegation address, and optionally withdraw validator commission if the delegation address given is a validator operator: -$ gaiacli tx distr withdraw-rewards cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj --from mykey -$ gaiacli tx distr withdraw-rewards cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj --from mykey --commission +$ tx distr withdraw-rewards cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj --from mykey +$ tx distr withdraw-rewards cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj --from mykey --commission `), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { @@ -82,7 +82,7 @@ func GetCmdWithdrawAllRewards(cdc *codec.Codec, queryRoute string) *cobra.Comman Short: "withdraw all delegations rewards for a delegator", Long: strings.TrimSpace(`Withdraw all rewards for a single delegator: -$ gaiacli tx distr withdraw-all-rewards --from mykey +$ tx distr withdraw-all-rewards --from mykey `), Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { @@ -110,7 +110,7 @@ func GetCmdSetWithdrawAddr(cdc *codec.Codec) *cobra.Command { Short: "change the default withdraw address for rewards associated with an address", Long: strings.TrimSpace(`Set the withdraw address for rewards associated with a delegator address: -$ gaiacli tx set-withdraw-addr cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p --from mykey +$ tx set-withdraw-addr cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p --from mykey `), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { diff --git a/x/genutil/client/cli/gentx.go b/x/genutil/client/cli/gentx.go index 2cdac84778..94cbe53e66 100644 --- a/x/genutil/client/cli/gentx.go +++ b/x/genutil/client/cli/gentx.go @@ -42,7 +42,7 @@ var ( defaultMinSelfDelegation = "1" ) -// GenTxCmd builds the gaiad gentx command. +// GenTxCmd builds the application's gentx command. // nolint: errcheck func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm sdk.ModuleBasicManager, genAccIterator genutil.GenesisAccountsIterator, defaultNodeHome, defaultCLIHome string) *cobra.Command { @@ -51,7 +51,7 @@ func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm sdk.ModuleBasicManager, Use: "gentx", Short: "Generate a genesis tx carrying a self delegation", Args: cobra.NoArgs, - Long: fmt.Sprintf(`This command is an alias of the 'gaiad tx create-validator' command'. + Long: fmt.Sprintf(`This command is an alias of the 'tx create-validator' command'. It creates a genesis piece carrying a self delegation with the following delegation and commission default parameters: @@ -156,7 +156,7 @@ following delegation and commission default parameters: } if info.GetType() == kbkeys.TypeOffline || info.GetType() == kbkeys.TypeMulti { - fmt.Println("Offline key passed in. Use `gaiacli tx sign` command to sign:") + fmt.Println("Offline key passed in. Use `tx sign` command to sign:") return utils.PrintUnsignedStdTx(txBldr, cliCtx, []sdk.Msg{msg}) } diff --git a/x/genutil/client/cli/init_test.go b/x/genutil/client/cli/init_test.go index 41e02ac134..f2f911db91 100644 --- a/x/genutil/client/cli/init_test.go +++ b/x/genutil/client/cli/init_test.go @@ -39,7 +39,7 @@ func TestInitCmd(t *testing.T) { cdc := makeCodec() cmd := InitCmd(ctx, cdc, testMbm, home) - require.NoError(t, cmd.RunE(nil, []string{"gaianode-test"})) + require.NoError(t, cmd.RunE(nil, []string{"appnode-test"})) } func setupClientHome(t *testing.T) func() { @@ -63,7 +63,7 @@ func TestEmptyState(t *testing.T) { cdc := makeCodec() cmd := InitCmd(ctx, cdc, testMbm, home) - require.NoError(t, cmd.RunE(nil, []string{"gaianode-test"})) + require.NoError(t, cmd.RunE(nil, []string{"appnode-test"})) old := os.Stdout r, w, _ := os.Pipe() @@ -103,7 +103,7 @@ func TestStartStandAlone(t *testing.T) { ctx := server.NewContext(cfg, logger) cdc := makeCodec() initCmd := InitCmd(ctx, cdc, testMbm, home) - require.NoError(t, initCmd.RunE(nil, []string{"gaianode-test"})) + require.NoError(t, initCmd.RunE(nil, []string{"appnode-test"})) app, err := mock.NewApp(home, logger) require.Nil(t, err) diff --git a/x/genutil/client/cli/validate_genesis.go b/x/genutil/client/cli/validate_genesis.go index 7609db8cc6..e7a1f850f5 100644 --- a/x/genutil/client/cli/validate_genesis.go +++ b/x/genutil/client/cli/validate_genesis.go @@ -47,7 +47,7 @@ func ValidateGenesisCmd(ctx *server.Context, cdc *codec.Codec, mbm sdk.ModuleBas // TODO test to make sure initchain doesn't panic - fmt.Printf("File at %s is a valid genesis file for gaiad\n", genesis) + fmt.Printf("File at %s is a valid genesis file\n", genesis) return nil }, } diff --git a/x/genutil/genesis_state.go b/x/genutil/genesis_state.go index b5f2d36dbf..ef1d27ba16 100644 --- a/x/genutil/genesis_state.go +++ b/x/genutil/genesis_state.go @@ -54,8 +54,9 @@ func SetGenesisStateInAppState(cdc *codec.Codec, return appState } -// Create the core parameters for genesis initialization for gaia -// note that the pubkey input is this machines pubkey +// Create the core parameters for genesis initialization for the application. +// +// NOTE: The pubkey input is this machines pubkey. func GenesisStateFromGenDoc(cdc *codec.Codec, genDoc tmtypes.GenesisDoc, ) (genesisState map[string]json.RawMessage, err error) { @@ -65,14 +66,15 @@ func GenesisStateFromGenDoc(cdc *codec.Codec, genDoc tmtypes.GenesisDoc, return genesisState, nil } -// Create the core parameters for genesis initialization for gaia -// note that the pubkey input is this machines pubkey +// Create the core parameters for genesis initialization for the application. +// +// NOTE: The pubkey input is this machines pubkey. func GenesisStateFromGenFile(cdc *codec.Codec, genFile string, ) (genesisState map[string]json.RawMessage, genDoc *tmtypes.GenesisDoc, err error) { if !common.FileExists(genFile) { return genesisState, genDoc, - fmt.Errorf("%s does not exist, run `gaiad init` first", genFile) + fmt.Errorf("%s does not exist, run `init` first", genFile) } genDoc, err = tmtypes.GenesisDocFromFile(genFile) if err != nil { diff --git a/x/gov/client/cli/query.go b/x/gov/client/cli/query.go index 8c95595fec..e782eec1c9 100644 --- a/x/gov/client/cli/query.go +++ b/x/gov/client/cli/query.go @@ -22,9 +22,9 @@ func GetCmdQueryProposal(queryRoute string, cdc *codec.Codec) *cobra.Command { Args: cobra.ExactArgs(1), Short: "Query details of a single proposal", Long: strings.TrimSpace(` -Query details for a proposal. You can find the proposal-id by running gaiacli query gov proposals: +Query details for a proposal. You can find the proposal-id by running query gov proposals: -$ gaiacli query gov proposal 1 +$ query gov proposal 1 `), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) @@ -56,9 +56,9 @@ func GetCmdQueryProposals(queryRoute string, cdc *codec.Codec) *cobra.Command { Long: strings.TrimSpace(` Query for a all proposals. You can filter the returns with the following flags: -$ gaiacli query gov proposals --depositor cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk -$ gaiacli query gov proposals --voter cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk -$ gaiacli query gov proposals --status (DepositPeriod|VotingPeriod|Passed|Rejected) +$ query gov proposals --depositor cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk +$ query gov proposals --voter cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk +$ query gov proposals --status (DepositPeriod|VotingPeriod|Passed|Rejected) `), RunE: func(cmd *cobra.Command, args []string) error { bechDepositorAddr := viper.GetString(flagDepositor) @@ -141,7 +141,7 @@ func GetCmdQueryVote(queryRoute string, cdc *codec.Codec) *cobra.Command { Query details for a single vote on a proposal given its identifier. Example: -$ gaiacli query gov vote 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk +$ query gov vote 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk `), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) @@ -204,7 +204,7 @@ func GetCmdQueryVotes(queryRoute string, cdc *codec.Codec) *cobra.Command { Query vote details for a single proposal by its identifier. Example: -$ gaiacli query gov votes 1 +$ query gov votes 1 `), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) @@ -259,7 +259,7 @@ func GetCmdQueryDeposit(queryRoute string, cdc *codec.Codec) *cobra.Command { Query details for a single proposal deposit on a proposal by its identifier. Example: -$ gaiacli query gov deposit 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk +$ query gov deposit 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk `), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) @@ -315,9 +315,9 @@ func GetCmdQueryDeposits(queryRoute string, cdc *codec.Codec) *cobra.Command { Args: cobra.ExactArgs(1), Short: "Query deposits on a proposal", Long: strings.TrimSpace(` -Query details for all deposits on a proposal. You can find the proposal-id by running gaiacli query gov proposals: +Query details for all deposits on a proposal. You can find the proposal-id by running query gov proposals: -$ gaiacli query gov deposits 1 +$ query gov deposits 1 `), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) @@ -368,9 +368,9 @@ func GetCmdQueryTally(queryRoute string, cdc *codec.Codec) *cobra.Command { Args: cobra.ExactArgs(1), Short: "Get the tally of a proposal vote", Long: strings.TrimSpace(` -Query tally of votes on a proposal. You can find the proposal-id by running gaiacli query gov proposals: +Query tally of votes on a proposal. You can find the proposal-id by running query gov proposals: -$ gaiacli query gov tally 1 +$ query gov tally 1 `), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) @@ -414,7 +414,7 @@ func GetCmdQueryParams(queryRoute string, cdc *codec.Codec) *cobra.Command { Short: "Query the parameters of the governance process", Long: strings.TrimSpace(`Query the all the parameters for the governance process: -$ gaiacli query gov params +$ query gov params `), Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { @@ -452,9 +452,9 @@ func GetCmdQueryParam(queryRoute string, cdc *codec.Codec) *cobra.Command { Short: "Query the parameters (voting|tallying|deposit) of the governance process", Long: strings.TrimSpace(`Query the all the parameters for the governance process: -$ gaiacli query gov param voting -$ gaiacli query gov param tallying -$ gaiacli query gov param deposit +$ query gov param voting +$ query gov param tallying +$ query gov param deposit `), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) @@ -495,7 +495,7 @@ func GetCmdQueryProposer(queryRoute string, cdc *codec.Codec) *cobra.Command { Short: "Query the proposer of a governance proposal", Long: strings.TrimSpace(`Query which address proposed a proposal with a given ID: -$ gaiacli query gov proposer 1 +$ query gov proposer 1 `), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) diff --git a/x/gov/client/cli/tx.go b/x/gov/client/cli/tx.go index 63e22b8fcb..ad7108abb5 100644 --- a/x/gov/client/cli/tx.go +++ b/x/gov/client/cli/tx.go @@ -56,7 +56,7 @@ func GetCmdSubmitProposal(cdc *codec.Codec) *cobra.Command { Long: strings.TrimSpace(` Submit a proposal along with an initial deposit. Proposal title, description, type and deposit can be given directly or through a proposal JSON file. For example: -$ gaiacli gov submit-proposal --proposal="path/to/proposal.json" --from mykey +$ gov submit-proposal --proposal="path/to/proposal.json" --from mykey where proposal.json contains: @@ -69,7 +69,7 @@ where proposal.json contains: is equivalent to -$ gaiacli gov submit-proposal --title="Test Proposal" --description="My awesome proposal" --type="Text" --deposit="10test" --from mykey +$ gov submit-proposal --title="Test Proposal" --description="My awesome proposal" --type="Text" --deposit="10test" --from mykey `), RunE: func(cmd *cobra.Command, args []string) error { txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) @@ -114,10 +114,10 @@ func GetCmdDeposit(cdc *codec.Codec) *cobra.Command { Args: cobra.ExactArgs(2), Short: "Deposit tokens for an active proposal", Long: strings.TrimSpace(` -Submit a deposit for an active proposal. You can find the proposal-id by running "gaiacli query gov proposals": +Submit a deposit for an active proposal. You can find the proposal-id by running " query gov proposals": Example: -$ gaiacli tx gov deposit 1 10stake --from mykey +$ tx gov deposit 1 10stake --from mykey `), RunE: func(cmd *cobra.Command, args []string) error { txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) @@ -158,10 +158,10 @@ func GetCmdVote(cdc *codec.Codec) *cobra.Command { Args: cobra.ExactArgs(2), Short: "Vote for an active proposal, options: yes/no/no_with_veto/abstain", Long: strings.TrimSpace(` -Submit a vote for an active proposal. You can find the proposal-id by running "gaiacli query gov proposals": +Submit a vote for an active proposal. You can find the proposal-id by running " query gov proposals": Example: -$ gaiacli tx gov vote 1 yes --from mykey +$ tx gov vote 1 yes --from mykey `), RunE: func(cmd *cobra.Command, args []string) error { txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) diff --git a/x/params/client/cli/tx.go b/x/params/client/cli/tx.go index ae4717a83e..7924fff457 100644 --- a/x/params/client/cli/tx.go +++ b/x/params/client/cli/tx.go @@ -35,7 +35,7 @@ Proper vetting of a parameter change proposal should prevent this from happening regardless. Example: -$ gaiacli tx gov submit-proposal param-change --from= +$ tx gov submit-proposal param-change --from= where proposal.json contains: { "title": "Staking Param Change", diff --git a/x/simulation/log.go b/x/simulation/log.go index 9bdb76fded..c145b5c713 100644 --- a/x/simulation/log.go +++ b/x/simulation/log.go @@ -47,7 +47,7 @@ func createLogFile() *os.File { var f *os.File fileName := fmt.Sprintf("%s.log", time.Now().Format("2006-01-02_15:04:05")) - folderPath := os.ExpandEnv("$HOME/.gaiad/simulations") + folderPath := os.ExpandEnv("$HOME/.simapp/simulations") filePath := path.Join(folderPath, fileName) err := os.MkdirAll(folderPath, os.ModePerm) diff --git a/x/slashing/client/cli/query.go b/x/slashing/client/cli/query.go index 0396e8ab91..a92c5525d0 100644 --- a/x/slashing/client/cli/query.go +++ b/x/slashing/client/cli/query.go @@ -19,7 +19,7 @@ func GetCmdQuerySigningInfo(storeName string, cdc *codec.Codec) *cobra.Command { Short: "Query a validator's signing information", Long: strings.TrimSpace(`Use a validators' consensus public key to find the signing-info for that validator: -$ gaiacli query slashing signing-info cosmosvalconspub1zcjduepqfhvwcmt7p06fvdgexxhmz0l8c7sgswl7ulv7aulk364x4g5xsw7sr0k2g5 +$ query slashing signing-info cosmosvalconspub1zcjduepqfhvwcmt7p06fvdgexxhmz0l8c7sgswl7ulv7aulk364x4g5xsw7sr0k2g5 `), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { @@ -57,7 +57,7 @@ func GetCmdQueryParams(cdc *codec.Codec) *cobra.Command { Args: cobra.NoArgs, Long: strings.TrimSpace(`Query genesis parameters for the slashing module: -$ gaiacli query slashing params +$ query slashing params `), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) diff --git a/x/slashing/client/cli/tx.go b/x/slashing/client/cli/tx.go index 9097975f95..c049ca3afa 100644 --- a/x/slashing/client/cli/tx.go +++ b/x/slashing/client/cli/tx.go @@ -19,7 +19,7 @@ func GetCmdUnjail(cdc *codec.Codec) *cobra.Command { Short: "unjail validator previously jailed for downtime", Long: `unjail a jailed validator: -$ gaiacli tx slashing unjail --from mykey +$ tx slashing unjail --from mykey `, RunE: func(cmd *cobra.Command, args []string) error { txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) diff --git a/x/staking/client/cli/query.go b/x/staking/client/cli/query.go index 94f2fff5e6..3b46ded5a2 100644 --- a/x/staking/client/cli/query.go +++ b/x/staking/client/cli/query.go @@ -20,7 +20,7 @@ func GetCmdQueryValidator(storeName string, cdc *codec.Codec) *cobra.Command { Short: "Query a validator", Long: strings.TrimSpace(`Query details about an individual validator: -$ gaiacli query staking validator cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj +$ query staking validator cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj `), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { @@ -53,7 +53,7 @@ func GetCmdQueryValidators(storeName string, cdc *codec.Codec) *cobra.Command { Args: cobra.NoArgs, Long: strings.TrimSpace(`Query details about all validators on a network: -$ gaiacli query staking validators +$ query staking validators `), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) @@ -80,7 +80,7 @@ func GetCmdQueryValidatorUnbondingDelegations(storeKey string, cdc *codec.Codec) Short: "Query all unbonding delegatations from a validator", Long: strings.TrimSpace(`Query delegations that are unbonding _from_ a validator: -$ gaiacli query staking unbonding-delegations-from cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj +$ query staking unbonding-delegations-from cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj `), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { @@ -117,7 +117,7 @@ func GetCmdQueryValidatorRedelegations(storeKey string, cdc *codec.Codec) *cobra Short: "Query all outgoing redelegatations from a validator", Long: strings.TrimSpace(`Query delegations that are redelegating _from_ a validator: -$ gaiacli query staking redelegations-from cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj +$ query staking redelegations-from cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj `), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { @@ -156,7 +156,7 @@ func GetCmdQueryDelegation(storeKey string, cdc *codec.Codec) *cobra.Command { Short: "Query a delegation based on address and validator address", Long: strings.TrimSpace(`Query delegations for an individual delegator on an individual validator: -$ gaiacli query staking delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj +$ query staking delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj `), Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { @@ -201,7 +201,7 @@ func GetCmdQueryDelegations(storeKey string, cdc *codec.Codec) *cobra.Command { Short: "Query all delegations made by one delegator", Long: strings.TrimSpace(`Query delegations for an individual delegator on all validators: -$ gaiacli query staking delegations cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p +$ query staking delegations cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p `), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { @@ -241,7 +241,7 @@ func GetCmdQueryValidatorDelegations(storeKey string, cdc *codec.Codec) *cobra.C Short: "Query all delegations made to one validator", Long: strings.TrimSpace(`Query delegations on an individual validator: -$ gaiacli query staking delegations-to cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj +$ query staking delegations-to cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj `), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { @@ -281,7 +281,7 @@ func GetCmdQueryUnbondingDelegation(storeName string, cdc *codec.Codec) *cobra.C Short: "Query an unbonding-delegation record based on delegator and validator address", Long: strings.TrimSpace(`Query unbonding delegations for an individual delegator on an individual validator: -$ gaiacli query staking unbonding-delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj +$ query staking unbonding-delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj `), Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { @@ -316,7 +316,7 @@ func GetCmdQueryUnbondingDelegations(storeName string, cdc *codec.Codec) *cobra. Short: "Query all unbonding-delegations records for one delegator", Long: strings.TrimSpace(`Query unbonding delegations for an individual delegator: -$ gaiacli query staking unbonding-delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p +$ query staking unbonding-delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p `), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { @@ -350,7 +350,7 @@ func GetCmdQueryRedelegation(storeKey string, cdc *codec.Codec) *cobra.Command { Short: "Query a redelegation record based on delegator and a source and destination validator address", Long: strings.TrimSpace(`Query a redelegation record for an individual delegator between a source and destination validator: -$ gaiacli query staking redelegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj +$ query staking redelegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj `), Args: cobra.ExactArgs(3), RunE: func(cmd *cobra.Command, args []string) error { @@ -401,7 +401,7 @@ func GetCmdQueryRedelegations(storeKey string, cdc *codec.Codec) *cobra.Command Short: "Query all redelegations records for one delegator", Long: strings.TrimSpace(`Query all redelegation records for an individual delegator: -$ gaiacli query staking redelegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p +$ query staking redelegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p `), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) @@ -440,7 +440,7 @@ func GetCmdQueryPool(storeName string, cdc *codec.Codec) *cobra.Command { Short: "Query the current staking pool values", Long: strings.TrimSpace(`Query values for amounts stored in the staking pool: -$ gaiacli query staking pool +$ query staking pool `), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) @@ -463,7 +463,7 @@ func GetCmdQueryParams(storeName string, cdc *codec.Codec) *cobra.Command { Short: "Query the current staking parameters information", Long: strings.TrimSpace(`Query values set as staking parameters: -$ gaiacli query staking params +$ query staking params `), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) diff --git a/x/staking/client/cli/tx.go b/x/staking/client/cli/tx.go index d58b8bfb22..6ad826b12d 100644 --- a/x/staking/client/cli/tx.go +++ b/x/staking/client/cli/tx.go @@ -120,7 +120,7 @@ func GetCmdDelegate(cdc *codec.Codec) *cobra.Command { Short: "delegate liquid tokens to a validator", Long: strings.TrimSpace(`Delegate an amount of liquid coins to a validator from your wallet: -$ gaiacli tx staking delegate cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm 1000stake --from mykey +$ $ tx staking delegate cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm 1000stake --from mykey `), RunE: func(cmd *cobra.Command, args []string) error { txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(auth.DefaultTxEncoder(cdc)) @@ -153,7 +153,7 @@ func GetCmdRedelegate(storeName string, cdc *codec.Codec) *cobra.Command { Args: cobra.ExactArgs(3), Long: strings.TrimSpace(`Redelegate an amount of illiquid staking tokens from one validator to another: -$ gaiacli tx staking redelegate cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm 100stake --from mykey +$ $ tx staking redelegate cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm 100stake --from mykey `), RunE: func(cmd *cobra.Command, args []string) error { txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(auth.DefaultTxEncoder(cdc)) @@ -191,7 +191,7 @@ func GetCmdUnbond(storeName string, cdc *codec.Codec) *cobra.Command { Args: cobra.ExactArgs(2), Long: strings.TrimSpace(`Unbond an amount of bonded shares from a validator: -$ gaiacli tx staking unbond cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj 100stake --from mykey +$ $ tx staking unbond cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj 100stake --from mykey `), RunE: func(cmd *cobra.Command, args []string) error { txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(auth.DefaultTxEncoder(cdc))