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.

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