You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1225 lines
43 KiB

deps: update gogo/protobuf version from v1.2.1 to v1.3.0 (#3947) * update gogo/protobuf version from v1.2.1 to v1.3.0 Also errcheck from v1.1.0 to v1.2.0 See full diff in - https://github.com/gogo/protobuf/compare/v1.2.1...v1.3.0 - https://github.com/kisielk/errcheck/compare/v1.1.0...v1.2.0 Changelog: Tested versions: go 1.12.9 protoc 3.7.1 Improvements: plugin/stringer - Handle repeated and/or nullable types a bit better now. plugin/size - Remove the loop in sovXXX by using bit twiddling. Thanks: https://github.com/apelisse plugin/marshalto - Implemented a reverse marshal strategy which allows for faster marshalling. This now avoids a recursive (and repeated) call to Size(). Thanks: https://github.com/apelisse plugin/compare - Added support for for oneof types. Bug fixes: protoc-gen-gogo/generator - Fix assignment to entry in nil map. Thanks: https://github.com/tgulacsi protoc-gen-gogo/generator - Allows plugins to call RecordTypeUse without panicking. Thanks: https://github.com/fedenusy proto/extensions - Fixed set extension regression. We did not clear the extensions before setting. io/uint32 - fix uint32reader bug that causes ReadMsg to recreate buffer when lengths are the same. Thanks: https://github.com/SebiSujar proto/table_merge: Fix merge of non-nullable slices. Thanks: https://github.com/euroelessar Upstream commits: merged in golang/protobuf commit 318d17de72747ed1c16502681db4b2bb709a92d0 - Add UnimplementedServer for server interface merged in golang/protobuf commit b85cd75de734650db18a99a943fe351d41387800 - protoc-gen-go/grpc: inline errUnimplemented function merged in golang/protobuf commit d3c38a4eb4970272b87a425ae00ccc4548e2f9bb - protoc-gen-go/grpc: use status and code packages only if needed merged in golang/protobuf commit e91709a02e0e8ff8b86b7aa913fdc9ae9498e825 - fix indentation in jsonpb with Any messages merged in golang/protobuf commit 8d0c54c1246661d9a51ca0ba455d22116d485eaa - protoc-gen-go: generate XXX_OneofWrappers instead of XXX_OneofFuncs Misc: extensions.md - Markdown update. Thanks: https://github.com/TennyZhuang Readme.md - Added user. go/protoc update - Updated to go1.12.x and protoc 3.7.1 Makefile update - fix go vet shadow tool reference test/mixbench - Update mixbench tool. Expose runnable benchmarks via flags. * update certstrap * update golangci-lint from v1.13.2 to v1.17.1 * update gox as well * test * comment out golangci temporary * comment out go-deadlock deps
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
limit number of /subscribe clients and queries per client (#3269) * limit number of /subscribe clients and queries per client Add the following config variables (under [rpc] section): * max_subscription_clients * max_subscriptions_per_client * timeout_broadcast_tx_commit Fixes #2826 new HTTPClient interface for subscriptions finalize HTTPClient events interface remove EventSubscriber fix data race ``` WARNING: DATA RACE Read at 0x00c000a36060 by goroutine 129: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe.func1() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:168 +0x1f0 Previous write at 0x00c000a36060 by goroutine 132: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:191 +0x4e0 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 129 (running) created at: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:164 +0x4b7 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 132 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:119 +0x186 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ================== ``` lite client works (tested manually) godoc comments httpclient: do not close the out channel use TimeoutBroadcastTxCommit no timeout for unsubscribe but 1s Local (5s HTTP) timeout for resubscribe format code change Subscribe#out cap to 1 and replace config vars with RPCConfig TimeoutBroadcastTxCommit can't be greater than rpcserver.WriteTimeout rpc: Context as first parameter to all functions reformat code fixes after my own review fixes after Ethan's review add test stubs fix config.toml * fixes after manual testing - rpc: do not recommend to use BroadcastTxCommit because it's slow and wastes Tendermint resources (pubsub) - rpc: better error in Subscribe and BroadcastTxCommit - HTTPClient: do not resubscribe if err = ErrAlreadySubscribed * fixes after Ismail's review * Update rpc/grpc/grpc_test.go Co-Authored-By: melekes <anton.kalyaev@gmail.com>
5 years ago
limit number of /subscribe clients and queries per client (#3269) * limit number of /subscribe clients and queries per client Add the following config variables (under [rpc] section): * max_subscription_clients * max_subscriptions_per_client * timeout_broadcast_tx_commit Fixes #2826 new HTTPClient interface for subscriptions finalize HTTPClient events interface remove EventSubscriber fix data race ``` WARNING: DATA RACE Read at 0x00c000a36060 by goroutine 129: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe.func1() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:168 +0x1f0 Previous write at 0x00c000a36060 by goroutine 132: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:191 +0x4e0 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 129 (running) created at: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:164 +0x4b7 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 132 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:119 +0x186 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ================== ``` lite client works (tested manually) godoc comments httpclient: do not close the out channel use TimeoutBroadcastTxCommit no timeout for unsubscribe but 1s Local (5s HTTP) timeout for resubscribe format code change Subscribe#out cap to 1 and replace config vars with RPCConfig TimeoutBroadcastTxCommit can't be greater than rpcserver.WriteTimeout rpc: Context as first parameter to all functions reformat code fixes after my own review fixes after Ethan's review add test stubs fix config.toml * fixes after manual testing - rpc: do not recommend to use BroadcastTxCommit because it's slow and wastes Tendermint resources (pubsub) - rpc: better error in Subscribe and BroadcastTxCommit - HTTPClient: do not resubscribe if err = ErrAlreadySubscribed * fixes after Ismail's review * Update rpc/grpc/grpc_test.go Co-Authored-By: melekes <anton.kalyaev@gmail.com>
5 years ago
limit number of /subscribe clients and queries per client (#3269) * limit number of /subscribe clients and queries per client Add the following config variables (under [rpc] section): * max_subscription_clients * max_subscriptions_per_client * timeout_broadcast_tx_commit Fixes #2826 new HTTPClient interface for subscriptions finalize HTTPClient events interface remove EventSubscriber fix data race ``` WARNING: DATA RACE Read at 0x00c000a36060 by goroutine 129: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe.func1() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:168 +0x1f0 Previous write at 0x00c000a36060 by goroutine 132: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:191 +0x4e0 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 129 (running) created at: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:164 +0x4b7 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 132 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:119 +0x186 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ================== ``` lite client works (tested manually) godoc comments httpclient: do not close the out channel use TimeoutBroadcastTxCommit no timeout for unsubscribe but 1s Local (5s HTTP) timeout for resubscribe format code change Subscribe#out cap to 1 and replace config vars with RPCConfig TimeoutBroadcastTxCommit can't be greater than rpcserver.WriteTimeout rpc: Context as first parameter to all functions reformat code fixes after my own review fixes after Ethan's review add test stubs fix config.toml * fixes after manual testing - rpc: do not recommend to use BroadcastTxCommit because it's slow and wastes Tendermint resources (pubsub) - rpc: better error in Subscribe and BroadcastTxCommit - HTTPClient: do not resubscribe if err = ErrAlreadySubscribed * fixes after Ismail's review * Update rpc/grpc/grpc_test.go Co-Authored-By: melekes <anton.kalyaev@gmail.com>
5 years ago
deps: update gogo/protobuf version from v1.2.1 to v1.3.0 (#3947) * update gogo/protobuf version from v1.2.1 to v1.3.0 Also errcheck from v1.1.0 to v1.2.0 See full diff in - https://github.com/gogo/protobuf/compare/v1.2.1...v1.3.0 - https://github.com/kisielk/errcheck/compare/v1.1.0...v1.2.0 Changelog: Tested versions: go 1.12.9 protoc 3.7.1 Improvements: plugin/stringer - Handle repeated and/or nullable types a bit better now. plugin/size - Remove the loop in sovXXX by using bit twiddling. Thanks: https://github.com/apelisse plugin/marshalto - Implemented a reverse marshal strategy which allows for faster marshalling. This now avoids a recursive (and repeated) call to Size(). Thanks: https://github.com/apelisse plugin/compare - Added support for for oneof types. Bug fixes: protoc-gen-gogo/generator - Fix assignment to entry in nil map. Thanks: https://github.com/tgulacsi protoc-gen-gogo/generator - Allows plugins to call RecordTypeUse without panicking. Thanks: https://github.com/fedenusy proto/extensions - Fixed set extension regression. We did not clear the extensions before setting. io/uint32 - fix uint32reader bug that causes ReadMsg to recreate buffer when lengths are the same. Thanks: https://github.com/SebiSujar proto/table_merge: Fix merge of non-nullable slices. Thanks: https://github.com/euroelessar Upstream commits: merged in golang/protobuf commit 318d17de72747ed1c16502681db4b2bb709a92d0 - Add UnimplementedServer for server interface merged in golang/protobuf commit b85cd75de734650db18a99a943fe351d41387800 - protoc-gen-go/grpc: inline errUnimplemented function merged in golang/protobuf commit d3c38a4eb4970272b87a425ae00ccc4548e2f9bb - protoc-gen-go/grpc: use status and code packages only if needed merged in golang/protobuf commit e91709a02e0e8ff8b86b7aa913fdc9ae9498e825 - fix indentation in jsonpb with Any messages merged in golang/protobuf commit 8d0c54c1246661d9a51ca0ba455d22116d485eaa - protoc-gen-go: generate XXX_OneofWrappers instead of XXX_OneofFuncs Misc: extensions.md - Markdown update. Thanks: https://github.com/TennyZhuang Readme.md - Added user. go/protoc update - Updated to go1.12.x and protoc 3.7.1 Makefile update - fix go vet shadow tool reference test/mixbench - Update mixbench tool. Expose runnable benchmarks via flags. * update certstrap * update golangci-lint from v1.13.2 to v1.17.1 * update gox as well * test * comment out golangci temporary * comment out go-deadlock deps
5 years ago
limit number of /subscribe clients and queries per client (#3269) * limit number of /subscribe clients and queries per client Add the following config variables (under [rpc] section): * max_subscription_clients * max_subscriptions_per_client * timeout_broadcast_tx_commit Fixes #2826 new HTTPClient interface for subscriptions finalize HTTPClient events interface remove EventSubscriber fix data race ``` WARNING: DATA RACE Read at 0x00c000a36060 by goroutine 129: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe.func1() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:168 +0x1f0 Previous write at 0x00c000a36060 by goroutine 132: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:191 +0x4e0 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 129 (running) created at: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:164 +0x4b7 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 132 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:119 +0x186 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ================== ``` lite client works (tested manually) godoc comments httpclient: do not close the out channel use TimeoutBroadcastTxCommit no timeout for unsubscribe but 1s Local (5s HTTP) timeout for resubscribe format code change Subscribe#out cap to 1 and replace config vars with RPCConfig TimeoutBroadcastTxCommit can't be greater than rpcserver.WriteTimeout rpc: Context as first parameter to all functions reformat code fixes after my own review fixes after Ethan's review add test stubs fix config.toml * fixes after manual testing - rpc: do not recommend to use BroadcastTxCommit because it's slow and wastes Tendermint resources (pubsub) - rpc: better error in Subscribe and BroadcastTxCommit - HTTPClient: do not resubscribe if err = ErrAlreadySubscribed * fixes after Ismail's review * Update rpc/grpc/grpc_test.go Co-Authored-By: melekes <anton.kalyaev@gmail.com>
5 years ago
limit number of /subscribe clients and queries per client (#3269) * limit number of /subscribe clients and queries per client Add the following config variables (under [rpc] section): * max_subscription_clients * max_subscriptions_per_client * timeout_broadcast_tx_commit Fixes #2826 new HTTPClient interface for subscriptions finalize HTTPClient events interface remove EventSubscriber fix data race ``` WARNING: DATA RACE Read at 0x00c000a36060 by goroutine 129: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe.func1() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:168 +0x1f0 Previous write at 0x00c000a36060 by goroutine 132: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:191 +0x4e0 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 129 (running) created at: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:164 +0x4b7 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 132 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:119 +0x186 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ================== ``` lite client works (tested manually) godoc comments httpclient: do not close the out channel use TimeoutBroadcastTxCommit no timeout for unsubscribe but 1s Local (5s HTTP) timeout for resubscribe format code change Subscribe#out cap to 1 and replace config vars with RPCConfig TimeoutBroadcastTxCommit can't be greater than rpcserver.WriteTimeout rpc: Context as first parameter to all functions reformat code fixes after my own review fixes after Ethan's review add test stubs fix config.toml * fixes after manual testing - rpc: do not recommend to use BroadcastTxCommit because it's slow and wastes Tendermint resources (pubsub) - rpc: better error in Subscribe and BroadcastTxCommit - HTTPClient: do not resubscribe if err = ErrAlreadySubscribed * fixes after Ismail's review * Update rpc/grpc/grpc_test.go Co-Authored-By: melekes <anton.kalyaev@gmail.com>
5 years ago
limit number of /subscribe clients and queries per client (#3269) * limit number of /subscribe clients and queries per client Add the following config variables (under [rpc] section): * max_subscription_clients * max_subscriptions_per_client * timeout_broadcast_tx_commit Fixes #2826 new HTTPClient interface for subscriptions finalize HTTPClient events interface remove EventSubscriber fix data race ``` WARNING: DATA RACE Read at 0x00c000a36060 by goroutine 129: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe.func1() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:168 +0x1f0 Previous write at 0x00c000a36060 by goroutine 132: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:191 +0x4e0 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 129 (running) created at: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:164 +0x4b7 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 132 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:119 +0x186 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ================== ``` lite client works (tested manually) godoc comments httpclient: do not close the out channel use TimeoutBroadcastTxCommit no timeout for unsubscribe but 1s Local (5s HTTP) timeout for resubscribe format code change Subscribe#out cap to 1 and replace config vars with RPCConfig TimeoutBroadcastTxCommit can't be greater than rpcserver.WriteTimeout rpc: Context as first parameter to all functions reformat code fixes after my own review fixes after Ethan's review add test stubs fix config.toml * fixes after manual testing - rpc: do not recommend to use BroadcastTxCommit because it's slow and wastes Tendermint resources (pubsub) - rpc: better error in Subscribe and BroadcastTxCommit - HTTPClient: do not resubscribe if err = ErrAlreadySubscribed * fixes after Ismail's review * Update rpc/grpc/grpc_test.go Co-Authored-By: melekes <anton.kalyaev@gmail.com>
5 years ago
limit number of /subscribe clients and queries per client (#3269) * limit number of /subscribe clients and queries per client Add the following config variables (under [rpc] section): * max_subscription_clients * max_subscriptions_per_client * timeout_broadcast_tx_commit Fixes #2826 new HTTPClient interface for subscriptions finalize HTTPClient events interface remove EventSubscriber fix data race ``` WARNING: DATA RACE Read at 0x00c000a36060 by goroutine 129: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe.func1() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:168 +0x1f0 Previous write at 0x00c000a36060 by goroutine 132: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:191 +0x4e0 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 129 (running) created at: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:164 +0x4b7 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 132 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:119 +0x186 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ================== ``` lite client works (tested manually) godoc comments httpclient: do not close the out channel use TimeoutBroadcastTxCommit no timeout for unsubscribe but 1s Local (5s HTTP) timeout for resubscribe format code change Subscribe#out cap to 1 and replace config vars with RPCConfig TimeoutBroadcastTxCommit can't be greater than rpcserver.WriteTimeout rpc: Context as first parameter to all functions reformat code fixes after my own review fixes after Ethan's review add test stubs fix config.toml * fixes after manual testing - rpc: do not recommend to use BroadcastTxCommit because it's slow and wastes Tendermint resources (pubsub) - rpc: better error in Subscribe and BroadcastTxCommit - HTTPClient: do not resubscribe if err = ErrAlreadySubscribed * fixes after Ismail's review * Update rpc/grpc/grpc_test.go Co-Authored-By: melekes <anton.kalyaev@gmail.com>
5 years ago
limit number of /subscribe clients and queries per client (#3269) * limit number of /subscribe clients and queries per client Add the following config variables (under [rpc] section): * max_subscription_clients * max_subscriptions_per_client * timeout_broadcast_tx_commit Fixes #2826 new HTTPClient interface for subscriptions finalize HTTPClient events interface remove EventSubscriber fix data race ``` WARNING: DATA RACE Read at 0x00c000a36060 by goroutine 129: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe.func1() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:168 +0x1f0 Previous write at 0x00c000a36060 by goroutine 132: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:191 +0x4e0 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 129 (running) created at: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:164 +0x4b7 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 132 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:119 +0x186 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ================== ``` lite client works (tested manually) godoc comments httpclient: do not close the out channel use TimeoutBroadcastTxCommit no timeout for unsubscribe but 1s Local (5s HTTP) timeout for resubscribe format code change Subscribe#out cap to 1 and replace config vars with RPCConfig TimeoutBroadcastTxCommit can't be greater than rpcserver.WriteTimeout rpc: Context as first parameter to all functions reformat code fixes after my own review fixes after Ethan's review add test stubs fix config.toml * fixes after manual testing - rpc: do not recommend to use BroadcastTxCommit because it's slow and wastes Tendermint resources (pubsub) - rpc: better error in Subscribe and BroadcastTxCommit - HTTPClient: do not resubscribe if err = ErrAlreadySubscribed * fixes after Ismail's review * Update rpc/grpc/grpc_test.go Co-Authored-By: melekes <anton.kalyaev@gmail.com>
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
  1. package config
  2. import (
  3. "encoding/hex"
  4. "errors"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "os"
  9. "path/filepath"
  10. "time"
  11. tmjson "github.com/tendermint/tendermint/libs/json"
  12. "github.com/tendermint/tendermint/libs/log"
  13. tmos "github.com/tendermint/tendermint/libs/os"
  14. "github.com/tendermint/tendermint/types"
  15. )
  16. const (
  17. // FuzzModeDrop is a mode in which we randomly drop reads/writes, connections or sleep
  18. FuzzModeDrop = iota
  19. // FuzzModeDelay is a mode in which we randomly sleep
  20. FuzzModeDelay
  21. // DefaultLogLevel defines a default log level as INFO.
  22. DefaultLogLevel = "info"
  23. ModeFull = "full"
  24. ModeValidator = "validator"
  25. ModeSeed = "seed"
  26. BlockSyncV0 = "v0"
  27. MempoolV0 = "v0"
  28. MempoolV1 = "v1"
  29. )
  30. // NOTE: Most of the structs & relevant comments + the
  31. // default configuration options were used to manually
  32. // generate the config.toml. Please reflect any changes
  33. // made here in the defaultConfigTemplate constant in
  34. // config/toml.go
  35. // NOTE: libs/cli must know to look in the config dir!
  36. var (
  37. DefaultTendermintDir = ".tendermint"
  38. defaultConfigDir = "config"
  39. defaultDataDir = "data"
  40. defaultConfigFileName = "config.toml"
  41. defaultGenesisJSONName = "genesis.json"
  42. defaultMode = ModeFull
  43. defaultPrivValKeyName = "priv_validator_key.json"
  44. defaultPrivValStateName = "priv_validator_state.json"
  45. defaultNodeKeyName = "node_key.json"
  46. defaultConfigFilePath = filepath.Join(defaultConfigDir, defaultConfigFileName)
  47. defaultGenesisJSONPath = filepath.Join(defaultConfigDir, defaultGenesisJSONName)
  48. defaultPrivValKeyPath = filepath.Join(defaultConfigDir, defaultPrivValKeyName)
  49. defaultPrivValStatePath = filepath.Join(defaultDataDir, defaultPrivValStateName)
  50. defaultNodeKeyPath = filepath.Join(defaultConfigDir, defaultNodeKeyName)
  51. )
  52. // Config defines the top level configuration for a Tendermint node
  53. type Config struct {
  54. // Top level options use an anonymous struct
  55. BaseConfig `mapstructure:",squash"`
  56. // Options for services
  57. RPC *RPCConfig `mapstructure:"rpc"`
  58. P2P *P2PConfig `mapstructure:"p2p"`
  59. Mempool *MempoolConfig `mapstructure:"mempool"`
  60. StateSync *StateSyncConfig `mapstructure:"statesync"`
  61. BlockSync *BlockSyncConfig `mapstructure:"blocksync"`
  62. Consensus *ConsensusConfig `mapstructure:"consensus"`
  63. TxIndex *TxIndexConfig `mapstructure:"tx-index"`
  64. Instrumentation *InstrumentationConfig `mapstructure:"instrumentation"`
  65. PrivValidator *PrivValidatorConfig `mapstructure:"priv-validator"`
  66. }
  67. // DefaultConfig returns a default configuration for a Tendermint node
  68. func DefaultConfig() *Config {
  69. return &Config{
  70. BaseConfig: DefaultBaseConfig(),
  71. RPC: DefaultRPCConfig(),
  72. P2P: DefaultP2PConfig(),
  73. Mempool: DefaultMempoolConfig(),
  74. StateSync: DefaultStateSyncConfig(),
  75. BlockSync: DefaultBlockSyncConfig(),
  76. Consensus: DefaultConsensusConfig(),
  77. TxIndex: DefaultTxIndexConfig(),
  78. Instrumentation: DefaultInstrumentationConfig(),
  79. PrivValidator: DefaultPrivValidatorConfig(),
  80. }
  81. }
  82. // DefaultValidatorConfig returns default config with mode as validator
  83. func DefaultValidatorConfig() *Config {
  84. cfg := DefaultConfig()
  85. cfg.Mode = ModeValidator
  86. return cfg
  87. }
  88. // TestConfig returns a configuration that can be used for testing
  89. func TestConfig() *Config {
  90. return &Config{
  91. BaseConfig: TestBaseConfig(),
  92. RPC: TestRPCConfig(),
  93. P2P: TestP2PConfig(),
  94. Mempool: TestMempoolConfig(),
  95. StateSync: TestStateSyncConfig(),
  96. BlockSync: TestBlockSyncConfig(),
  97. Consensus: TestConsensusConfig(),
  98. TxIndex: TestTxIndexConfig(),
  99. Instrumentation: TestInstrumentationConfig(),
  100. PrivValidator: DefaultPrivValidatorConfig(),
  101. }
  102. }
  103. // SetRoot sets the RootDir for all Config structs
  104. func (cfg *Config) SetRoot(root string) *Config {
  105. cfg.BaseConfig.RootDir = root
  106. cfg.RPC.RootDir = root
  107. cfg.P2P.RootDir = root
  108. cfg.Mempool.RootDir = root
  109. cfg.Consensus.RootDir = root
  110. cfg.PrivValidator.RootDir = root
  111. return cfg
  112. }
  113. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  114. // returns an error if any check fails.
  115. func (cfg *Config) ValidateBasic() error {
  116. if err := cfg.BaseConfig.ValidateBasic(); err != nil {
  117. return err
  118. }
  119. if err := cfg.RPC.ValidateBasic(); err != nil {
  120. return fmt.Errorf("error in [rpc] section: %w", err)
  121. }
  122. if err := cfg.Mempool.ValidateBasic(); err != nil {
  123. return fmt.Errorf("error in [mempool] section: %w", err)
  124. }
  125. if err := cfg.StateSync.ValidateBasic(); err != nil {
  126. return fmt.Errorf("error in [statesync] section: %w", err)
  127. }
  128. if err := cfg.BlockSync.ValidateBasic(); err != nil {
  129. return fmt.Errorf("error in [blocksync] section: %w", err)
  130. }
  131. if err := cfg.Consensus.ValidateBasic(); err != nil {
  132. return fmt.Errorf("error in [consensus] section: %w", err)
  133. }
  134. if err := cfg.Instrumentation.ValidateBasic(); err != nil {
  135. return fmt.Errorf("error in [instrumentation] section: %w", err)
  136. }
  137. return nil
  138. }
  139. //-----------------------------------------------------------------------------
  140. // BaseConfig
  141. // BaseConfig defines the base configuration for a Tendermint node
  142. type BaseConfig struct { //nolint: maligned
  143. // chainID is unexposed and immutable but here for convenience
  144. chainID string
  145. // The root directory for all data.
  146. // This should be set in viper so it can unmarshal into this struct
  147. RootDir string `mapstructure:"home"`
  148. // TCP or UNIX socket address of the ABCI application,
  149. // or the name of an ABCI application compiled in with the Tendermint binary
  150. ProxyApp string `mapstructure:"proxy-app"`
  151. // A custom human readable name for this node
  152. Moniker string `mapstructure:"moniker"`
  153. // Mode of Node: full | validator | seed
  154. // * validator
  155. // - all reactors
  156. // - with priv_validator_key.json, priv_validator_state.json
  157. // * full
  158. // - all reactors
  159. // - No priv_validator_key.json, priv_validator_state.json
  160. // * seed
  161. // - only P2P, PEX Reactor
  162. // - No priv_validator_key.json, priv_validator_state.json
  163. Mode string `mapstructure:"mode"`
  164. // Database backend: goleveldb | cleveldb | boltdb | rocksdb
  165. // * goleveldb (github.com/syndtr/goleveldb - most popular implementation)
  166. // - pure go
  167. // - stable
  168. // * cleveldb (uses levigo wrapper)
  169. // - fast
  170. // - requires gcc
  171. // - use cleveldb build tag (go build -tags cleveldb)
  172. // * boltdb (uses etcd's fork of bolt - github.com/etcd-io/bbolt)
  173. // - EXPERIMENTAL
  174. // - may be faster is some use-cases (random reads - indexer)
  175. // - use boltdb build tag (go build -tags boltdb)
  176. // * rocksdb (uses github.com/tecbot/gorocksdb)
  177. // - EXPERIMENTAL
  178. // - requires gcc
  179. // - use rocksdb build tag (go build -tags rocksdb)
  180. // * badgerdb (uses github.com/dgraph-io/badger)
  181. // - EXPERIMENTAL
  182. // - use badgerdb build tag (go build -tags badgerdb)
  183. DBBackend string `mapstructure:"db-backend"`
  184. // Database directory
  185. DBPath string `mapstructure:"db-dir"`
  186. // Output level for logging
  187. LogLevel string `mapstructure:"log-level"`
  188. // Output format: 'plain' (colored text) or 'json'
  189. LogFormat string `mapstructure:"log-format"`
  190. // Path to the JSON file containing the initial validator set and other meta data
  191. Genesis string `mapstructure:"genesis-file"`
  192. // A JSON file containing the private key to use for p2p authenticated encryption
  193. NodeKey string `mapstructure:"node-key-file"`
  194. // Mechanism to connect to the ABCI application: socket | grpc
  195. ABCI string `mapstructure:"abci"`
  196. // If true, query the ABCI app on connecting to a new peer
  197. // so the app can decide if we should keep the connection or not
  198. FilterPeers bool `mapstructure:"filter-peers"` // false
  199. Other map[string]interface{} `mapstructure:",remain"`
  200. }
  201. // DefaultBaseConfig returns a default base configuration for a Tendermint node
  202. func DefaultBaseConfig() BaseConfig {
  203. return BaseConfig{
  204. Genesis: defaultGenesisJSONPath,
  205. NodeKey: defaultNodeKeyPath,
  206. Mode: defaultMode,
  207. Moniker: defaultMoniker,
  208. ProxyApp: "tcp://127.0.0.1:26658",
  209. ABCI: "socket",
  210. LogLevel: DefaultLogLevel,
  211. LogFormat: log.LogFormatPlain,
  212. FilterPeers: false,
  213. DBBackend: "goleveldb",
  214. DBPath: "data",
  215. }
  216. }
  217. // TestBaseConfig returns a base configuration for testing a Tendermint node
  218. func TestBaseConfig() BaseConfig {
  219. cfg := DefaultBaseConfig()
  220. cfg.chainID = "tendermint_test"
  221. cfg.Mode = ModeValidator
  222. cfg.ProxyApp = "kvstore"
  223. cfg.DBBackend = "memdb"
  224. return cfg
  225. }
  226. func (cfg BaseConfig) ChainID() string {
  227. return cfg.chainID
  228. }
  229. // GenesisFile returns the full path to the genesis.json file
  230. func (cfg BaseConfig) GenesisFile() string {
  231. return rootify(cfg.Genesis, cfg.RootDir)
  232. }
  233. // NodeKeyFile returns the full path to the node_key.json file
  234. func (cfg BaseConfig) NodeKeyFile() string {
  235. return rootify(cfg.NodeKey, cfg.RootDir)
  236. }
  237. // LoadNodeKey loads NodeKey located in filePath.
  238. func (cfg BaseConfig) LoadNodeKeyID() (types.NodeID, error) {
  239. jsonBytes, err := ioutil.ReadFile(cfg.NodeKeyFile())
  240. if err != nil {
  241. return "", err
  242. }
  243. nodeKey := types.NodeKey{}
  244. err = tmjson.Unmarshal(jsonBytes, &nodeKey)
  245. if err != nil {
  246. return "", err
  247. }
  248. nodeKey.ID = types.NodeIDFromPubKey(nodeKey.PubKey())
  249. return nodeKey.ID, nil
  250. }
  251. // LoadOrGenNodeKey attempts to load the NodeKey from the given filePath. If
  252. // the file does not exist, it generates and saves a new NodeKey.
  253. func (cfg BaseConfig) LoadOrGenNodeKeyID() (types.NodeID, error) {
  254. if tmos.FileExists(cfg.NodeKeyFile()) {
  255. nodeKey, err := cfg.LoadNodeKeyID()
  256. if err != nil {
  257. return "", err
  258. }
  259. return nodeKey, nil
  260. }
  261. nodeKey := types.GenNodeKey()
  262. if err := nodeKey.SaveAs(cfg.NodeKeyFile()); err != nil {
  263. return "", err
  264. }
  265. return nodeKey.ID, nil
  266. }
  267. // DBDir returns the full path to the database directory
  268. func (cfg BaseConfig) DBDir() string {
  269. return rootify(cfg.DBPath, cfg.RootDir)
  270. }
  271. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  272. // returns an error if any check fails.
  273. func (cfg BaseConfig) ValidateBasic() error {
  274. switch cfg.LogFormat {
  275. case log.LogFormatJSON, log.LogFormatText, log.LogFormatPlain:
  276. default:
  277. return errors.New("unknown log format (must be 'plain', 'text' or 'json')")
  278. }
  279. switch cfg.Mode {
  280. case ModeFull, ModeValidator, ModeSeed:
  281. case "":
  282. return errors.New("no mode has been set")
  283. default:
  284. return fmt.Errorf("unknown mode: %v", cfg.Mode)
  285. }
  286. // TODO (https://github.com/tendermint/tendermint/issues/6908) remove this check after the v0.35 release cycle.
  287. // This check was added to give users an upgrade prompt to use the new
  288. // configuration option in v0.35. In future release cycles they should no longer
  289. // be using this configuration parameter so the check can be removed.
  290. // The cfg.Other field can likely be removed at the same time if it is not referenced
  291. // elsewhere as it was added to service this check.
  292. if fs, ok := cfg.Other["fastsync"]; ok {
  293. if _, ok := fs.(map[string]interface{}); ok {
  294. return fmt.Errorf("a configuration section named 'fastsync' was found in the " +
  295. "configuration file. The 'fastsync' section has been renamed to " +
  296. "'blocksync', please update the 'fastsync' field in your configuration file to 'blocksync'")
  297. }
  298. }
  299. if fs, ok := cfg.Other["fast-sync"]; ok {
  300. if fs != "" {
  301. return fmt.Errorf("a parameter named 'fast-sync' was found in the " +
  302. "configuration file. The parameter to enable or disable quickly syncing with a blockchain" +
  303. "has moved to the [blocksync] section of the configuration file as blocksync.enable. " +
  304. "Please move the 'fast-sync' field in your configuration file to 'blocksync.enable'")
  305. }
  306. }
  307. return nil
  308. }
  309. //-----------------------------------------------------------------------------
  310. // PrivValidatorConfig
  311. // PrivValidatorConfig defines the configuration parameters for running a validator
  312. type PrivValidatorConfig struct {
  313. RootDir string `mapstructure:"home"`
  314. // Path to the JSON file containing the private key to use as a validator in the consensus protocol
  315. Key string `mapstructure:"key-file"`
  316. // Path to the JSON file containing the last sign state of a validator
  317. State string `mapstructure:"state-file"`
  318. // TCP or UNIX socket address for Tendermint to listen on for
  319. // connections from an external PrivValidator process
  320. ListenAddr string `mapstructure:"laddr"`
  321. // Client certificate generated while creating needed files for secure connection.
  322. // If a remote validator address is provided but no certificate, the connection will be insecure
  323. ClientCertificate string `mapstructure:"client-certificate-file"`
  324. // Client key generated while creating certificates for secure connection
  325. ClientKey string `mapstructure:"client-key-file"`
  326. // Path Root Certificate Authority used to sign both client and server certificates
  327. RootCA string `mapstructure:"root-ca-file"`
  328. }
  329. // DefaultBaseConfig returns a default private validator configuration
  330. // for a Tendermint node.
  331. func DefaultPrivValidatorConfig() *PrivValidatorConfig {
  332. return &PrivValidatorConfig{
  333. Key: defaultPrivValKeyPath,
  334. State: defaultPrivValStatePath,
  335. }
  336. }
  337. // ClientKeyFile returns the full path to the priv_validator_key.json file
  338. func (cfg *PrivValidatorConfig) ClientKeyFile() string {
  339. return rootify(cfg.ClientKey, cfg.RootDir)
  340. }
  341. // ClientCertificateFile returns the full path to the priv_validator_key.json file
  342. func (cfg *PrivValidatorConfig) ClientCertificateFile() string {
  343. return rootify(cfg.ClientCertificate, cfg.RootDir)
  344. }
  345. // CertificateAuthorityFile returns the full path to the priv_validator_key.json file
  346. func (cfg *PrivValidatorConfig) RootCAFile() string {
  347. return rootify(cfg.RootCA, cfg.RootDir)
  348. }
  349. // KeyFile returns the full path to the priv_validator_key.json file
  350. func (cfg *PrivValidatorConfig) KeyFile() string {
  351. return rootify(cfg.Key, cfg.RootDir)
  352. }
  353. // StateFile returns the full path to the priv_validator_state.json file
  354. func (cfg *PrivValidatorConfig) StateFile() string {
  355. return rootify(cfg.State, cfg.RootDir)
  356. }
  357. func (cfg *PrivValidatorConfig) AreSecurityOptionsPresent() bool {
  358. switch {
  359. case cfg.RootCA == "":
  360. return false
  361. case cfg.ClientKey == "":
  362. return false
  363. case cfg.ClientCertificate == "":
  364. return false
  365. default:
  366. return true
  367. }
  368. }
  369. //-----------------------------------------------------------------------------
  370. // RPCConfig
  371. // RPCConfig defines the configuration options for the Tendermint RPC server
  372. type RPCConfig struct {
  373. RootDir string `mapstructure:"home"`
  374. // TCP or UNIX socket address for the RPC server to listen on
  375. ListenAddress string `mapstructure:"laddr"`
  376. // A list of origins a cross-domain request can be executed from.
  377. // If the special '*' value is present in the list, all origins will be allowed.
  378. // An origin may contain a wildcard (*) to replace 0 or more characters (i.e.: http://*.domain.com).
  379. // Only one wildcard can be used per origin.
  380. CORSAllowedOrigins []string `mapstructure:"cors-allowed-origins"`
  381. // A list of methods the client is allowed to use with cross-domain requests.
  382. CORSAllowedMethods []string `mapstructure:"cors-allowed-methods"`
  383. // A list of non simple headers the client is allowed to use with cross-domain requests.
  384. CORSAllowedHeaders []string `mapstructure:"cors-allowed-headers"`
  385. // TCP or UNIX socket address for the gRPC server to listen on
  386. // NOTE: This server only supports /broadcast_tx_commit
  387. // Deprecated: gRPC in the RPC layer of Tendermint will be removed in 0.36.
  388. GRPCListenAddress string `mapstructure:"grpc-laddr"`
  389. // Maximum number of simultaneous connections.
  390. // Does not include RPC (HTTP&WebSocket) connections. See max-open-connections
  391. // If you want to accept a larger number than the default, make sure
  392. // you increase your OS limits.
  393. // 0 - unlimited.
  394. // Deprecated: gRPC in the RPC layer of Tendermint will be removed in 0.36.
  395. GRPCMaxOpenConnections int `mapstructure:"grpc-max-open-connections"`
  396. // Activate unsafe RPC commands like /dial-persistent-peers and /unsafe-flush-mempool
  397. Unsafe bool `mapstructure:"unsafe"`
  398. // Maximum number of simultaneous connections (including WebSocket).
  399. // Does not include gRPC connections. See grpc-max-open-connections
  400. // If you want to accept a larger number than the default, make sure
  401. // you increase your OS limits.
  402. // 0 - unlimited.
  403. // Should be < {ulimit -Sn} - {MaxNumInboundPeers} - {MaxNumOutboundPeers} - {N of wal, db and other open files}
  404. // 1024 - 40 - 10 - 50 = 924 = ~900
  405. MaxOpenConnections int `mapstructure:"max-open-connections"`
  406. // Maximum number of unique clientIDs that can /subscribe
  407. // If you're using /broadcast_tx_commit, set to the estimated maximum number
  408. // of broadcast_tx_commit calls per block.
  409. MaxSubscriptionClients int `mapstructure:"max-subscription-clients"`
  410. // Maximum number of unique queries a given client can /subscribe to
  411. // If you're using GRPC (or Local RPC client) and /broadcast_tx_commit, set
  412. // to the estimated maximum number of broadcast_tx_commit calls per block.
  413. MaxSubscriptionsPerClient int `mapstructure:"max-subscriptions-per-client"`
  414. // How long to wait for a tx to be committed during /broadcast_tx_commit
  415. // WARNING: Using a value larger than 10s will result in increasing the
  416. // global HTTP write timeout, which applies to all connections and endpoints.
  417. // See https://github.com/tendermint/tendermint/issues/3435
  418. TimeoutBroadcastTxCommit time.Duration `mapstructure:"timeout-broadcast-tx-commit"`
  419. // Maximum size of request body, in bytes
  420. MaxBodyBytes int64 `mapstructure:"max-body-bytes"`
  421. // Maximum size of request header, in bytes
  422. MaxHeaderBytes int `mapstructure:"max-header-bytes"`
  423. // The path to a file containing certificate that is used to create the HTTPS server.
  424. // Might be either absolute path or path related to Tendermint's config directory.
  425. //
  426. // If the certificate is signed by a certificate authority,
  427. // the certFile should be the concatenation of the server's certificate, any intermediates,
  428. // and the CA's certificate.
  429. //
  430. // NOTE: both tls-cert-file and tls-key-file must be present for Tendermint to create HTTPS server.
  431. // Otherwise, HTTP server is run.
  432. TLSCertFile string `mapstructure:"tls-cert-file"`
  433. // The path to a file containing matching private key that is used to create the HTTPS server.
  434. // Might be either absolute path or path related to tendermint's config directory.
  435. //
  436. // NOTE: both tls-cert-file and tls-key-file must be present for Tendermint to create HTTPS server.
  437. // Otherwise, HTTP server is run.
  438. TLSKeyFile string `mapstructure:"tls-key-file"`
  439. // pprof listen address (https://golang.org/pkg/net/http/pprof)
  440. PprofListenAddress string `mapstructure:"pprof-laddr"`
  441. }
  442. // DefaultRPCConfig returns a default configuration for the RPC server
  443. func DefaultRPCConfig() *RPCConfig {
  444. return &RPCConfig{
  445. ListenAddress: "tcp://127.0.0.1:26657",
  446. CORSAllowedOrigins: []string{},
  447. CORSAllowedMethods: []string{http.MethodHead, http.MethodGet, http.MethodPost},
  448. CORSAllowedHeaders: []string{"Origin", "Accept", "Content-Type", "X-Requested-With", "X-Server-Time"},
  449. GRPCListenAddress: "",
  450. GRPCMaxOpenConnections: 900,
  451. Unsafe: false,
  452. MaxOpenConnections: 900,
  453. MaxSubscriptionClients: 100,
  454. MaxSubscriptionsPerClient: 5,
  455. TimeoutBroadcastTxCommit: 10 * time.Second,
  456. MaxBodyBytes: int64(1000000), // 1MB
  457. MaxHeaderBytes: 1 << 20, // same as the net/http default
  458. TLSCertFile: "",
  459. TLSKeyFile: "",
  460. }
  461. }
  462. // TestRPCConfig returns a configuration for testing the RPC server
  463. func TestRPCConfig() *RPCConfig {
  464. cfg := DefaultRPCConfig()
  465. cfg.ListenAddress = "tcp://127.0.0.1:36657"
  466. cfg.GRPCListenAddress = "tcp://127.0.0.1:36658"
  467. cfg.Unsafe = true
  468. return cfg
  469. }
  470. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  471. // returns an error if any check fails.
  472. func (cfg *RPCConfig) ValidateBasic() error {
  473. if cfg.GRPCMaxOpenConnections < 0 {
  474. return errors.New("grpc-max-open-connections can't be negative")
  475. }
  476. if cfg.MaxOpenConnections < 0 {
  477. return errors.New("max-open-connections can't be negative")
  478. }
  479. if cfg.MaxSubscriptionClients < 0 {
  480. return errors.New("max-subscription-clients can't be negative")
  481. }
  482. if cfg.MaxSubscriptionsPerClient < 0 {
  483. return errors.New("max-subscriptions-per-client can't be negative")
  484. }
  485. if cfg.TimeoutBroadcastTxCommit < 0 {
  486. return errors.New("timeout-broadcast-tx-commit can't be negative")
  487. }
  488. if cfg.MaxBodyBytes < 0 {
  489. return errors.New("max-body-bytes can't be negative")
  490. }
  491. if cfg.MaxHeaderBytes < 0 {
  492. return errors.New("max-header-bytes can't be negative")
  493. }
  494. return nil
  495. }
  496. // IsCorsEnabled returns true if cross-origin resource sharing is enabled.
  497. func (cfg *RPCConfig) IsCorsEnabled() bool {
  498. return len(cfg.CORSAllowedOrigins) != 0
  499. }
  500. func (cfg RPCConfig) KeyFile() string {
  501. path := cfg.TLSKeyFile
  502. if filepath.IsAbs(path) {
  503. return path
  504. }
  505. return rootify(filepath.Join(defaultConfigDir, path), cfg.RootDir)
  506. }
  507. func (cfg RPCConfig) CertFile() string {
  508. path := cfg.TLSCertFile
  509. if filepath.IsAbs(path) {
  510. return path
  511. }
  512. return rootify(filepath.Join(defaultConfigDir, path), cfg.RootDir)
  513. }
  514. func (cfg RPCConfig) IsTLSEnabled() bool {
  515. return cfg.TLSCertFile != "" && cfg.TLSKeyFile != ""
  516. }
  517. //-----------------------------------------------------------------------------
  518. // P2PConfig
  519. // P2PConfig defines the configuration options for the Tendermint peer-to-peer networking layer
  520. type P2PConfig struct { //nolint: maligned
  521. RootDir string `mapstructure:"home"`
  522. // Address to listen for incoming connections
  523. ListenAddress string `mapstructure:"laddr"`
  524. // Address to advertise to peers for them to dial
  525. ExternalAddress string `mapstructure:"external-address"`
  526. // Comma separated list of seed nodes to connect to
  527. // We only use these if we can’t connect to peers in the addrbook
  528. // NOTE: not used by the new PEX reactor. Please use BootstrapPeers instead.
  529. // TODO: Remove once p2p refactor is complete
  530. // ref: https://github.com/tendermint/tendermint/issues/5670
  531. Seeds string `mapstructure:"seeds"`
  532. // Comma separated list of peers to be added to the peer store
  533. // on startup. Either BootstrapPeers or PersistentPeers are
  534. // needed for peer discovery
  535. BootstrapPeers string `mapstructure:"bootstrap-peers"`
  536. // Comma separated list of nodes to keep persistent connections to
  537. PersistentPeers string `mapstructure:"persistent-peers"`
  538. // UPNP port forwarding
  539. UPNP bool `mapstructure:"upnp"`
  540. // MaxConnections defines the maximum number of connected peers (inbound and
  541. // outbound).
  542. MaxConnections uint16 `mapstructure:"max-connections"`
  543. // MaxIncomingConnectionAttempts rate limits the number of incoming connection
  544. // attempts per IP address.
  545. MaxIncomingConnectionAttempts uint `mapstructure:"max-incoming-connection-attempts"`
  546. // Set true to enable the peer-exchange reactor
  547. PexReactor bool `mapstructure:"pex"`
  548. // Comma separated list of peer IDs to keep private (will not be gossiped to
  549. // other peers)
  550. PrivatePeerIDs string `mapstructure:"private-peer-ids"`
  551. // Toggle to disable guard against peers connecting from the same ip.
  552. AllowDuplicateIP bool `mapstructure:"allow-duplicate-ip"`
  553. // Peer connection configuration.
  554. HandshakeTimeout time.Duration `mapstructure:"handshake-timeout"`
  555. DialTimeout time.Duration `mapstructure:"dial-timeout"`
  556. // Testing params.
  557. // Force dial to fail
  558. TestDialFail bool `mapstructure:"test-dial-fail"`
  559. // Makes it possible to configure which queue backend the p2p
  560. // layer uses. Options are: "fifo" and "priority",
  561. // with the default being "priority".
  562. QueueType string `mapstructure:"queue-type"`
  563. }
  564. // DefaultP2PConfig returns a default configuration for the peer-to-peer layer
  565. func DefaultP2PConfig() *P2PConfig {
  566. return &P2PConfig{
  567. ListenAddress: "tcp://0.0.0.0:26656",
  568. ExternalAddress: "",
  569. UPNP: false,
  570. MaxConnections: 64,
  571. MaxIncomingConnectionAttempts: 100,
  572. PexReactor: true,
  573. AllowDuplicateIP: false,
  574. HandshakeTimeout: 20 * time.Second,
  575. DialTimeout: 3 * time.Second,
  576. TestDialFail: false,
  577. QueueType: "priority",
  578. }
  579. }
  580. // TestP2PConfig returns a configuration for testing the peer-to-peer layer
  581. func TestP2PConfig() *P2PConfig {
  582. cfg := DefaultP2PConfig()
  583. cfg.ListenAddress = "tcp://127.0.0.1:36656"
  584. cfg.AllowDuplicateIP = true
  585. return cfg
  586. }
  587. //-----------------------------------------------------------------------------
  588. // MempoolConfig
  589. // MempoolConfig defines the configuration options for the Tendermint mempool.
  590. type MempoolConfig struct {
  591. Version string `mapstructure:"version"`
  592. RootDir string `mapstructure:"home"`
  593. Recheck bool `mapstructure:"recheck"`
  594. Broadcast bool `mapstructure:"broadcast"`
  595. // Maximum number of transactions in the mempool
  596. Size int `mapstructure:"size"`
  597. // Limit the total size of all txs in the mempool.
  598. // This only accounts for raw transactions (e.g. given 1MB transactions and
  599. // max-txs-bytes=5MB, mempool will only accept 5 transactions).
  600. MaxTxsBytes int64 `mapstructure:"max-txs-bytes"`
  601. // Size of the cache (used to filter transactions we saw earlier) in transactions
  602. CacheSize int `mapstructure:"cache-size"`
  603. // Do not remove invalid transactions from the cache (default: false)
  604. // Set to true if it's not possible for any invalid transaction to become
  605. // valid again in the future.
  606. KeepInvalidTxsInCache bool `mapstructure:"keep-invalid-txs-in-cache"`
  607. // Maximum size of a single transaction
  608. // NOTE: the max size of a tx transmitted over the network is {max-tx-bytes}.
  609. MaxTxBytes int `mapstructure:"max-tx-bytes"`
  610. // Maximum size of a batch of transactions to send to a peer
  611. // Including space needed by encoding (one varint per transaction).
  612. // XXX: Unused due to https://github.com/tendermint/tendermint/issues/5796
  613. MaxBatchBytes int `mapstructure:"max-batch-bytes"`
  614. // TTLDuration, if non-zero, defines the maximum amount of time a transaction
  615. // can exist for in the mempool.
  616. //
  617. // Note, if TTLNumBlocks is also defined, a transaction will be removed if it
  618. // has existed in the mempool at least TTLNumBlocks number of blocks or if it's
  619. // insertion time into the mempool is beyond TTLDuration.
  620. TTLDuration time.Duration `mapstructure:"ttl-duration"`
  621. // TTLNumBlocks, if non-zero, defines the maximum number of blocks a transaction
  622. // can exist for in the mempool.
  623. //
  624. // Note, if TTLDuration is also defined, a transaction will be removed if it
  625. // has existed in the mempool at least TTLNumBlocks number of blocks or if
  626. // it's insertion time into the mempool is beyond TTLDuration.
  627. TTLNumBlocks int64 `mapstructure:"ttl-num-blocks"`
  628. }
  629. // DefaultMempoolConfig returns a default configuration for the Tendermint mempool.
  630. func DefaultMempoolConfig() *MempoolConfig {
  631. return &MempoolConfig{
  632. Version: MempoolV1,
  633. Recheck: true,
  634. Broadcast: true,
  635. // Each signature verification takes .5ms, Size reduced until we implement
  636. // ABCI Recheck
  637. Size: 5000,
  638. MaxTxsBytes: 1024 * 1024 * 1024, // 1GB
  639. CacheSize: 10000,
  640. MaxTxBytes: 1024 * 1024, // 1MB
  641. TTLDuration: 0 * time.Second,
  642. TTLNumBlocks: 0,
  643. }
  644. }
  645. // TestMempoolConfig returns a configuration for testing the Tendermint mempool
  646. func TestMempoolConfig() *MempoolConfig {
  647. cfg := DefaultMempoolConfig()
  648. cfg.CacheSize = 1000
  649. return cfg
  650. }
  651. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  652. // returns an error if any check fails.
  653. func (cfg *MempoolConfig) ValidateBasic() error {
  654. if cfg.Size < 0 {
  655. return errors.New("size can't be negative")
  656. }
  657. if cfg.MaxTxsBytes < 0 {
  658. return errors.New("max-txs-bytes can't be negative")
  659. }
  660. if cfg.CacheSize < 0 {
  661. return errors.New("cache-size can't be negative")
  662. }
  663. if cfg.MaxTxBytes < 0 {
  664. return errors.New("max-tx-bytes can't be negative")
  665. }
  666. if cfg.TTLDuration < 0 {
  667. return errors.New("ttl-duration can't be negative")
  668. }
  669. if cfg.TTLNumBlocks < 0 {
  670. return errors.New("ttl-num-blocks can't be negative")
  671. }
  672. return nil
  673. }
  674. //-----------------------------------------------------------------------------
  675. // StateSyncConfig
  676. // StateSyncConfig defines the configuration for the Tendermint state sync service
  677. type StateSyncConfig struct {
  678. // State sync rapidly bootstraps a new node by discovering, fetching, and restoring a
  679. // state machine snapshot from peers instead of fetching and replaying historical
  680. // blocks. Requires some peers in the network to take and serve state machine
  681. // snapshots. State sync is not attempted if the node has any local state
  682. // (LastBlockHeight > 0). The node will have a truncated block history, starting from
  683. // the height of the snapshot.
  684. Enable bool `mapstructure:"enable"`
  685. // State sync uses light client verification to verify state. This can be done either
  686. // through the P2P layer or the RPC layer. Set this to true to use the P2P layer. If
  687. // false (default), the RPC layer will be used.
  688. UseP2P bool `mapstructure:"use-p2p"`
  689. // If using RPC, at least two addresses need to be provided. They should be compatible
  690. // with net.Dial, for example: "host.example.com:2125".
  691. RPCServers []string `mapstructure:"rpc-servers"`
  692. // The hash and height of a trusted block. Must be within the trust-period.
  693. TrustHeight int64 `mapstructure:"trust-height"`
  694. TrustHash string `mapstructure:"trust-hash"`
  695. // The trust period should be set so that Tendermint can detect and gossip
  696. // misbehavior before it is considered expired. For chains based on the Cosmos SDK,
  697. // one day less than the unbonding period should suffice.
  698. TrustPeriod time.Duration `mapstructure:"trust-period"`
  699. // Time to spend discovering snapshots before initiating a restore.
  700. DiscoveryTime time.Duration `mapstructure:"discovery-time"`
  701. // Temporary directory for state sync snapshot chunks, defaults to os.TempDir().
  702. // The synchronizer will create a new, randomly named directory within this directory
  703. // and remove it when the sync is complete.
  704. TempDir string `mapstructure:"temp-dir"`
  705. // The timeout duration before re-requesting a chunk, possibly from a different
  706. // peer (default: 15 seconds).
  707. ChunkRequestTimeout time.Duration `mapstructure:"chunk-request-timeout"`
  708. // The number of concurrent chunk and block fetchers to run (default: 4).
  709. Fetchers int32 `mapstructure:"fetchers"`
  710. }
  711. func (cfg *StateSyncConfig) TrustHashBytes() []byte {
  712. // validated in ValidateBasic, so we can safely panic here
  713. bytes, err := hex.DecodeString(cfg.TrustHash)
  714. if err != nil {
  715. panic(err)
  716. }
  717. return bytes
  718. }
  719. // DefaultStateSyncConfig returns a default configuration for the state sync service
  720. func DefaultStateSyncConfig() *StateSyncConfig {
  721. return &StateSyncConfig{
  722. TrustPeriod: 168 * time.Hour,
  723. DiscoveryTime: 15 * time.Second,
  724. ChunkRequestTimeout: 15 * time.Second,
  725. Fetchers: 4,
  726. }
  727. }
  728. // TestStateSyncConfig returns a default configuration for the state sync service
  729. func TestStateSyncConfig() *StateSyncConfig {
  730. return DefaultStateSyncConfig()
  731. }
  732. // ValidateBasic performs basic validation.
  733. func (cfg *StateSyncConfig) ValidateBasic() error {
  734. if !cfg.Enable {
  735. return nil
  736. }
  737. // If we're not using the P2P stack then we need to validate the
  738. // RPCServers
  739. if !cfg.UseP2P {
  740. if len(cfg.RPCServers) < 2 {
  741. return errors.New("at least two rpc-servers must be specified")
  742. }
  743. for _, server := range cfg.RPCServers {
  744. if server == "" {
  745. return errors.New("found empty rpc-servers entry")
  746. }
  747. }
  748. }
  749. if cfg.DiscoveryTime != 0 && cfg.DiscoveryTime < 5*time.Second {
  750. return errors.New("discovery time must be 0s or greater than five seconds")
  751. }
  752. if cfg.TrustPeriod <= 0 {
  753. return errors.New("trusted-period is required")
  754. }
  755. if cfg.TrustHeight <= 0 {
  756. return errors.New("trusted-height is required")
  757. }
  758. if len(cfg.TrustHash) == 0 {
  759. return errors.New("trusted-hash is required")
  760. }
  761. _, err := hex.DecodeString(cfg.TrustHash)
  762. if err != nil {
  763. return fmt.Errorf("invalid trusted-hash: %w", err)
  764. }
  765. if cfg.ChunkRequestTimeout < 5*time.Second {
  766. return errors.New("chunk-request-timeout must be at least 5 seconds")
  767. }
  768. if cfg.Fetchers <= 0 {
  769. return errors.New("fetchers is required")
  770. }
  771. return nil
  772. }
  773. //-----------------------------------------------------------------------------
  774. // BlockSyncConfig (formerly known as FastSync) defines the configuration for the Tendermint block sync service
  775. // If this node is many blocks behind the tip of the chain, BlockSync
  776. // allows them to catchup quickly by downloading blocks in parallel
  777. // and verifying their commits.
  778. type BlockSyncConfig struct {
  779. Enable bool `mapstructure:"enable"`
  780. }
  781. // DefaultBlockSyncConfig returns a default configuration for the block sync service
  782. func DefaultBlockSyncConfig() *BlockSyncConfig {
  783. return &BlockSyncConfig{
  784. Enable: true,
  785. }
  786. }
  787. // TestBlockSyncConfig returns a default configuration for the block sync.
  788. func TestBlockSyncConfig() *BlockSyncConfig {
  789. return DefaultBlockSyncConfig()
  790. }
  791. // ValidateBasic performs basic validation.
  792. func (cfg *BlockSyncConfig) ValidateBasic() error { return nil }
  793. //-----------------------------------------------------------------------------
  794. // ConsensusConfig
  795. // ConsensusConfig defines the configuration for the Tendermint consensus service,
  796. // including timeouts and details about the WAL and the block structure.
  797. type ConsensusConfig struct {
  798. RootDir string `mapstructure:"home"`
  799. WalPath string `mapstructure:"wal-file"`
  800. walFile string // overrides WalPath if set
  801. // TODO: remove timeout configs, these should be global not local
  802. // How long we wait for a proposal block before prevoting nil
  803. TimeoutPropose time.Duration `mapstructure:"timeout-propose"`
  804. // How much timeout-propose increases with each round
  805. TimeoutProposeDelta time.Duration `mapstructure:"timeout-propose-delta"`
  806. // How long we wait after receiving +2/3 prevotes for “anything” (ie. not a single block or nil)
  807. TimeoutPrevote time.Duration `mapstructure:"timeout-prevote"`
  808. // How much the timeout-prevote increases with each round
  809. TimeoutPrevoteDelta time.Duration `mapstructure:"timeout-prevote-delta"`
  810. // How long we wait after receiving +2/3 precommits for “anything” (ie. not a single block or nil)
  811. TimeoutPrecommit time.Duration `mapstructure:"timeout-precommit"`
  812. // How much the timeout-precommit increases with each round
  813. TimeoutPrecommitDelta time.Duration `mapstructure:"timeout-precommit-delta"`
  814. // How long we wait after committing a block, before starting on the new
  815. // height (this gives us a chance to receive some more precommits, even
  816. // though we already have +2/3).
  817. TimeoutCommit time.Duration `mapstructure:"timeout-commit"`
  818. // Make progress as soon as we have all the precommits (as if TimeoutCommit = 0)
  819. SkipTimeoutCommit bool `mapstructure:"skip-timeout-commit"`
  820. // EmptyBlocks mode and possible interval between empty blocks
  821. CreateEmptyBlocks bool `mapstructure:"create-empty-blocks"`
  822. CreateEmptyBlocksInterval time.Duration `mapstructure:"create-empty-blocks-interval"`
  823. // Reactor sleep duration parameters
  824. PeerGossipSleepDuration time.Duration `mapstructure:"peer-gossip-sleep-duration"`
  825. PeerQueryMaj23SleepDuration time.Duration `mapstructure:"peer-query-maj23-sleep-duration"`
  826. DoubleSignCheckHeight int64 `mapstructure:"double-sign-check-height"`
  827. }
  828. // DefaultConsensusConfig returns a default configuration for the consensus service
  829. func DefaultConsensusConfig() *ConsensusConfig {
  830. return &ConsensusConfig{
  831. WalPath: filepath.Join(defaultDataDir, "cs.wal", "wal"),
  832. TimeoutPropose: 3000 * time.Millisecond,
  833. TimeoutProposeDelta: 500 * time.Millisecond,
  834. TimeoutPrevote: 1000 * time.Millisecond,
  835. TimeoutPrevoteDelta: 500 * time.Millisecond,
  836. TimeoutPrecommit: 1000 * time.Millisecond,
  837. TimeoutPrecommitDelta: 500 * time.Millisecond,
  838. TimeoutCommit: 1000 * time.Millisecond,
  839. SkipTimeoutCommit: false,
  840. CreateEmptyBlocks: true,
  841. CreateEmptyBlocksInterval: 0 * time.Second,
  842. PeerGossipSleepDuration: 100 * time.Millisecond,
  843. PeerQueryMaj23SleepDuration: 2000 * time.Millisecond,
  844. DoubleSignCheckHeight: int64(0),
  845. }
  846. }
  847. // TestConsensusConfig returns a configuration for testing the consensus service
  848. func TestConsensusConfig() *ConsensusConfig {
  849. cfg := DefaultConsensusConfig()
  850. cfg.TimeoutPropose = 40 * time.Millisecond
  851. cfg.TimeoutProposeDelta = 1 * time.Millisecond
  852. cfg.TimeoutPrevote = 10 * time.Millisecond
  853. cfg.TimeoutPrevoteDelta = 1 * time.Millisecond
  854. cfg.TimeoutPrecommit = 10 * time.Millisecond
  855. cfg.TimeoutPrecommitDelta = 1 * time.Millisecond
  856. cfg.TimeoutCommit = 10 * time.Millisecond
  857. cfg.SkipTimeoutCommit = true
  858. cfg.PeerGossipSleepDuration = 5 * time.Millisecond
  859. cfg.PeerQueryMaj23SleepDuration = 250 * time.Millisecond
  860. cfg.DoubleSignCheckHeight = int64(0)
  861. return cfg
  862. }
  863. // WaitForTxs returns true if the consensus should wait for transactions before entering the propose step
  864. func (cfg *ConsensusConfig) WaitForTxs() bool {
  865. return !cfg.CreateEmptyBlocks || cfg.CreateEmptyBlocksInterval > 0
  866. }
  867. // Propose returns the amount of time to wait for a proposal
  868. func (cfg *ConsensusConfig) Propose(round int32) time.Duration {
  869. return time.Duration(
  870. cfg.TimeoutPropose.Nanoseconds()+cfg.TimeoutProposeDelta.Nanoseconds()*int64(round),
  871. ) * time.Nanosecond
  872. }
  873. // Prevote returns the amount of time to wait for straggler votes after receiving any +2/3 prevotes
  874. func (cfg *ConsensusConfig) Prevote(round int32) time.Duration {
  875. return time.Duration(
  876. cfg.TimeoutPrevote.Nanoseconds()+cfg.TimeoutPrevoteDelta.Nanoseconds()*int64(round),
  877. ) * time.Nanosecond
  878. }
  879. // Precommit returns the amount of time to wait for straggler votes after receiving any +2/3 precommits
  880. func (cfg *ConsensusConfig) Precommit(round int32) time.Duration {
  881. return time.Duration(
  882. cfg.TimeoutPrecommit.Nanoseconds()+cfg.TimeoutPrecommitDelta.Nanoseconds()*int64(round),
  883. ) * time.Nanosecond
  884. }
  885. // Commit returns the amount of time to wait for straggler votes after receiving +2/3 precommits
  886. // for a single block (ie. a commit).
  887. func (cfg *ConsensusConfig) Commit(t time.Time) time.Time {
  888. return t.Add(cfg.TimeoutCommit)
  889. }
  890. // WalFile returns the full path to the write-ahead log file
  891. func (cfg *ConsensusConfig) WalFile() string {
  892. if cfg.walFile != "" {
  893. return cfg.walFile
  894. }
  895. return rootify(cfg.WalPath, cfg.RootDir)
  896. }
  897. // SetWalFile sets the path to the write-ahead log file
  898. func (cfg *ConsensusConfig) SetWalFile(walFile string) {
  899. cfg.walFile = walFile
  900. }
  901. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  902. // returns an error if any check fails.
  903. func (cfg *ConsensusConfig) ValidateBasic() error {
  904. if cfg.TimeoutPropose < 0 {
  905. return errors.New("timeout-propose can't be negative")
  906. }
  907. if cfg.TimeoutProposeDelta < 0 {
  908. return errors.New("timeout-propose-delta can't be negative")
  909. }
  910. if cfg.TimeoutPrevote < 0 {
  911. return errors.New("timeout-prevote can't be negative")
  912. }
  913. if cfg.TimeoutPrevoteDelta < 0 {
  914. return errors.New("timeout-prevote-delta can't be negative")
  915. }
  916. if cfg.TimeoutPrecommit < 0 {
  917. return errors.New("timeout-precommit can't be negative")
  918. }
  919. if cfg.TimeoutPrecommitDelta < 0 {
  920. return errors.New("timeout-precommit-delta can't be negative")
  921. }
  922. if cfg.TimeoutCommit < 0 {
  923. return errors.New("timeout-commit can't be negative")
  924. }
  925. if cfg.CreateEmptyBlocksInterval < 0 {
  926. return errors.New("create-empty-blocks-interval can't be negative")
  927. }
  928. if cfg.PeerGossipSleepDuration < 0 {
  929. return errors.New("peer-gossip-sleep-duration can't be negative")
  930. }
  931. if cfg.PeerQueryMaj23SleepDuration < 0 {
  932. return errors.New("peer-query-maj23-sleep-duration can't be negative")
  933. }
  934. if cfg.DoubleSignCheckHeight < 0 {
  935. return errors.New("double-sign-check-height can't be negative")
  936. }
  937. return nil
  938. }
  939. //-----------------------------------------------------------------------------
  940. // TxIndexConfig
  941. // Remember that Event has the following structure:
  942. // type: [
  943. // key: value,
  944. // ...
  945. // ]
  946. //
  947. // CompositeKeys are constructed by `type.key`
  948. // TxIndexConfig defines the configuration for the transaction indexer,
  949. // including composite keys to index.
  950. type TxIndexConfig struct {
  951. // The backend database list to back the indexer.
  952. // If list contains `null`, meaning no indexer service will be used.
  953. //
  954. // Options:
  955. // 1) "null" - no indexer services.
  956. // 2) "kv" (default) - the simplest possible indexer,
  957. // backed by key-value storage (defaults to levelDB; see DBBackend).
  958. // 3) "psql" - the indexer services backed by PostgreSQL.
  959. Indexer []string `mapstructure:"indexer"`
  960. // The PostgreSQL connection configuration, the connection format:
  961. // postgresql://<user>:<password>@<host>:<port>/<db>?<opts>
  962. PsqlConn string `mapstructure:"psql-conn"`
  963. }
  964. // DefaultTxIndexConfig returns a default configuration for the transaction indexer.
  965. func DefaultTxIndexConfig() *TxIndexConfig {
  966. return &TxIndexConfig{
  967. Indexer: []string{"kv"},
  968. }
  969. }
  970. // TestTxIndexConfig returns a default configuration for the transaction indexer.
  971. func TestTxIndexConfig() *TxIndexConfig {
  972. return DefaultTxIndexConfig()
  973. }
  974. //-----------------------------------------------------------------------------
  975. // InstrumentationConfig
  976. // InstrumentationConfig defines the configuration for metrics reporting.
  977. type InstrumentationConfig struct {
  978. // When true, Prometheus metrics are served under /metrics on
  979. // PrometheusListenAddr.
  980. // Check out the documentation for the list of available metrics.
  981. Prometheus bool `mapstructure:"prometheus"`
  982. // Address to listen for Prometheus collector(s) connections.
  983. PrometheusListenAddr string `mapstructure:"prometheus-listen-addr"`
  984. // Maximum number of simultaneous connections.
  985. // If you want to accept a larger number than the default, make sure
  986. // you increase your OS limits.
  987. // 0 - unlimited.
  988. MaxOpenConnections int `mapstructure:"max-open-connections"`
  989. // Instrumentation namespace.
  990. Namespace string `mapstructure:"namespace"`
  991. }
  992. // DefaultInstrumentationConfig returns a default configuration for metrics
  993. // reporting.
  994. func DefaultInstrumentationConfig() *InstrumentationConfig {
  995. return &InstrumentationConfig{
  996. Prometheus: false,
  997. PrometheusListenAddr: ":26660",
  998. MaxOpenConnections: 3,
  999. Namespace: "tendermint",
  1000. }
  1001. }
  1002. // TestInstrumentationConfig returns a default configuration for metrics
  1003. // reporting.
  1004. func TestInstrumentationConfig() *InstrumentationConfig {
  1005. return DefaultInstrumentationConfig()
  1006. }
  1007. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  1008. // returns an error if any check fails.
  1009. func (cfg *InstrumentationConfig) ValidateBasic() error {
  1010. if cfg.MaxOpenConnections < 0 {
  1011. return errors.New("max-open-connections can't be negative")
  1012. }
  1013. return nil
  1014. }
  1015. //-----------------------------------------------------------------------------
  1016. // Utils
  1017. // helper function to make config creation independent of root dir
  1018. func rootify(path, root string) string {
  1019. if filepath.IsAbs(path) {
  1020. return path
  1021. }
  1022. return filepath.Join(root, path)
  1023. }
  1024. //-----------------------------------------------------------------------------
  1025. // Moniker
  1026. var defaultMoniker = getDefaultMoniker()
  1027. // getDefaultMoniker returns a default moniker, which is the host name. If runtime
  1028. // fails to get the host name, "anonymous" will be returned.
  1029. func getDefaultMoniker() string {
  1030. moniker, err := os.Hostname()
  1031. if err != nil {
  1032. moniker = "anonymous"
  1033. }
  1034. return moniker
  1035. }