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.

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