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.

1278 lines
44 KiB

deps: update gogo/protobuf version from v1.2.1 to v1.3.0 (#3947) * update gogo/protobuf version from v1.2.1 to v1.3.0 Also errcheck from v1.1.0 to v1.2.0 See full diff in - https://github.com/gogo/protobuf/compare/v1.2.1...v1.3.0 - https://github.com/kisielk/errcheck/compare/v1.1.0...v1.2.0 Changelog: Tested versions: go 1.12.9 protoc 3.7.1 Improvements: plugin/stringer - Handle repeated and/or nullable types a bit better now. plugin/size - Remove the loop in sovXXX by using bit twiddling. Thanks: https://github.com/apelisse plugin/marshalto - Implemented a reverse marshal strategy which allows for faster marshalling. This now avoids a recursive (and repeated) call to Size(). Thanks: https://github.com/apelisse plugin/compare - Added support for for oneof types. Bug fixes: protoc-gen-gogo/generator - Fix assignment to entry in nil map. Thanks: https://github.com/tgulacsi protoc-gen-gogo/generator - Allows plugins to call RecordTypeUse without panicking. Thanks: https://github.com/fedenusy proto/extensions - Fixed set extension regression. We did not clear the extensions before setting. io/uint32 - fix uint32reader bug that causes ReadMsg to recreate buffer when lengths are the same. Thanks: https://github.com/SebiSujar proto/table_merge: Fix merge of non-nullable slices. Thanks: https://github.com/euroelessar Upstream commits: merged in golang/protobuf commit 318d17de72747ed1c16502681db4b2bb709a92d0 - Add UnimplementedServer for server interface merged in golang/protobuf commit b85cd75de734650db18a99a943fe351d41387800 - protoc-gen-go/grpc: inline errUnimplemented function merged in golang/protobuf commit d3c38a4eb4970272b87a425ae00ccc4548e2f9bb - protoc-gen-go/grpc: use status and code packages only if needed merged in golang/protobuf commit e91709a02e0e8ff8b86b7aa913fdc9ae9498e825 - fix indentation in jsonpb with Any messages merged in golang/protobuf commit 8d0c54c1246661d9a51ca0ba455d22116d485eaa - protoc-gen-go: generate XXX_OneofWrappers instead of XXX_OneofFuncs Misc: extensions.md - Markdown update. Thanks: https://github.com/TennyZhuang Readme.md - Added user. go/protoc update - Updated to go1.12.x and protoc 3.7.1 Makefile update - fix go vet shadow tool reference test/mixbench - Update mixbench tool. Expose runnable benchmarks via flags. * update certstrap * update golangci-lint from v1.13.2 to v1.17.1 * update gox as well * test * comment out golangci temporary * comment out go-deadlock deps
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
limit number of /subscribe clients and queries per client (#3269) * limit number of /subscribe clients and queries per client Add the following config variables (under [rpc] section): * max_subscription_clients * max_subscriptions_per_client * timeout_broadcast_tx_commit Fixes #2826 new HTTPClient interface for subscriptions finalize HTTPClient events interface remove EventSubscriber fix data race ``` WARNING: DATA RACE Read at 0x00c000a36060 by goroutine 129: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe.func1() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:168 +0x1f0 Previous write at 0x00c000a36060 by goroutine 132: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:191 +0x4e0 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 129 (running) created at: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:164 +0x4b7 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 132 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:119 +0x186 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ================== ``` lite client works (tested manually) godoc comments httpclient: do not close the out channel use TimeoutBroadcastTxCommit no timeout for unsubscribe but 1s Local (5s HTTP) timeout for resubscribe format code change Subscribe#out cap to 1 and replace config vars with RPCConfig TimeoutBroadcastTxCommit can't be greater than rpcserver.WriteTimeout rpc: Context as first parameter to all functions reformat code fixes after my own review fixes after Ethan's review add test stubs fix config.toml * fixes after manual testing - rpc: do not recommend to use BroadcastTxCommit because it's slow and wastes Tendermint resources (pubsub) - rpc: better error in Subscribe and BroadcastTxCommit - HTTPClient: do not resubscribe if err = ErrAlreadySubscribed * fixes after Ismail's review * Update rpc/grpc/grpc_test.go Co-Authored-By: melekes <anton.kalyaev@gmail.com>
6 years ago
limit number of /subscribe clients and queries per client (#3269) * limit number of /subscribe clients and queries per client Add the following config variables (under [rpc] section): * max_subscription_clients * max_subscriptions_per_client * timeout_broadcast_tx_commit Fixes #2826 new HTTPClient interface for subscriptions finalize HTTPClient events interface remove EventSubscriber fix data race ``` WARNING: DATA RACE Read at 0x00c000a36060 by goroutine 129: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe.func1() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:168 +0x1f0 Previous write at 0x00c000a36060 by goroutine 132: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:191 +0x4e0 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 129 (running) created at: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:164 +0x4b7 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 132 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:119 +0x186 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ================== ``` lite client works (tested manually) godoc comments httpclient: do not close the out channel use TimeoutBroadcastTxCommit no timeout for unsubscribe but 1s Local (5s HTTP) timeout for resubscribe format code change Subscribe#out cap to 1 and replace config vars with RPCConfig TimeoutBroadcastTxCommit can't be greater than rpcserver.WriteTimeout rpc: Context as first parameter to all functions reformat code fixes after my own review fixes after Ethan's review add test stubs fix config.toml * fixes after manual testing - rpc: do not recommend to use BroadcastTxCommit because it's slow and wastes Tendermint resources (pubsub) - rpc: better error in Subscribe and BroadcastTxCommit - HTTPClient: do not resubscribe if err = ErrAlreadySubscribed * fixes after Ismail's review * Update rpc/grpc/grpc_test.go Co-Authored-By: melekes <anton.kalyaev@gmail.com>
6 years ago
limit number of /subscribe clients and queries per client (#3269) * limit number of /subscribe clients and queries per client Add the following config variables (under [rpc] section): * max_subscription_clients * max_subscriptions_per_client * timeout_broadcast_tx_commit Fixes #2826 new HTTPClient interface for subscriptions finalize HTTPClient events interface remove EventSubscriber fix data race ``` WARNING: DATA RACE Read at 0x00c000a36060 by goroutine 129: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe.func1() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:168 +0x1f0 Previous write at 0x00c000a36060 by goroutine 132: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:191 +0x4e0 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 129 (running) created at: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:164 +0x4b7 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 132 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:119 +0x186 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ================== ``` lite client works (tested manually) godoc comments httpclient: do not close the out channel use TimeoutBroadcastTxCommit no timeout for unsubscribe but 1s Local (5s HTTP) timeout for resubscribe format code change Subscribe#out cap to 1 and replace config vars with RPCConfig TimeoutBroadcastTxCommit can't be greater than rpcserver.WriteTimeout rpc: Context as first parameter to all functions reformat code fixes after my own review fixes after Ethan's review add test stubs fix config.toml * fixes after manual testing - rpc: do not recommend to use BroadcastTxCommit because it's slow and wastes Tendermint resources (pubsub) - rpc: better error in Subscribe and BroadcastTxCommit - HTTPClient: do not resubscribe if err = ErrAlreadySubscribed * fixes after Ismail's review * Update rpc/grpc/grpc_test.go Co-Authored-By: melekes <anton.kalyaev@gmail.com>
6 years ago
deps: update gogo/protobuf version from v1.2.1 to v1.3.0 (#3947) * update gogo/protobuf version from v1.2.1 to v1.3.0 Also errcheck from v1.1.0 to v1.2.0 See full diff in - https://github.com/gogo/protobuf/compare/v1.2.1...v1.3.0 - https://github.com/kisielk/errcheck/compare/v1.1.0...v1.2.0 Changelog: Tested versions: go 1.12.9 protoc 3.7.1 Improvements: plugin/stringer - Handle repeated and/or nullable types a bit better now. plugin/size - Remove the loop in sovXXX by using bit twiddling. Thanks: https://github.com/apelisse plugin/marshalto - Implemented a reverse marshal strategy which allows for faster marshalling. This now avoids a recursive (and repeated) call to Size(). Thanks: https://github.com/apelisse plugin/compare - Added support for for oneof types. Bug fixes: protoc-gen-gogo/generator - Fix assignment to entry in nil map. Thanks: https://github.com/tgulacsi protoc-gen-gogo/generator - Allows plugins to call RecordTypeUse without panicking. Thanks: https://github.com/fedenusy proto/extensions - Fixed set extension regression. We did not clear the extensions before setting. io/uint32 - fix uint32reader bug that causes ReadMsg to recreate buffer when lengths are the same. Thanks: https://github.com/SebiSujar proto/table_merge: Fix merge of non-nullable slices. Thanks: https://github.com/euroelessar Upstream commits: merged in golang/protobuf commit 318d17de72747ed1c16502681db4b2bb709a92d0 - Add UnimplementedServer for server interface merged in golang/protobuf commit b85cd75de734650db18a99a943fe351d41387800 - protoc-gen-go/grpc: inline errUnimplemented function merged in golang/protobuf commit d3c38a4eb4970272b87a425ae00ccc4548e2f9bb - protoc-gen-go/grpc: use status and code packages only if needed merged in golang/protobuf commit e91709a02e0e8ff8b86b7aa913fdc9ae9498e825 - fix indentation in jsonpb with Any messages merged in golang/protobuf commit 8d0c54c1246661d9a51ca0ba455d22116d485eaa - protoc-gen-go: generate XXX_OneofWrappers instead of XXX_OneofFuncs Misc: extensions.md - Markdown update. Thanks: https://github.com/TennyZhuang Readme.md - Added user. go/protoc update - Updated to go1.12.x and protoc 3.7.1 Makefile update - fix go vet shadow tool reference test/mixbench - Update mixbench tool. Expose runnable benchmarks via flags. * update certstrap * update golangci-lint from v1.13.2 to v1.17.1 * update gox as well * test * comment out golangci temporary * comment out go-deadlock deps
5 years ago
limit number of /subscribe clients and queries per client (#3269) * limit number of /subscribe clients and queries per client Add the following config variables (under [rpc] section): * max_subscription_clients * max_subscriptions_per_client * timeout_broadcast_tx_commit Fixes #2826 new HTTPClient interface for subscriptions finalize HTTPClient events interface remove EventSubscriber fix data race ``` WARNING: DATA RACE Read at 0x00c000a36060 by goroutine 129: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe.func1() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:168 +0x1f0 Previous write at 0x00c000a36060 by goroutine 132: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:191 +0x4e0 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 129 (running) created at: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:164 +0x4b7 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 132 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:119 +0x186 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ================== ``` lite client works (tested manually) godoc comments httpclient: do not close the out channel use TimeoutBroadcastTxCommit no timeout for unsubscribe but 1s Local (5s HTTP) timeout for resubscribe format code change Subscribe#out cap to 1 and replace config vars with RPCConfig TimeoutBroadcastTxCommit can't be greater than rpcserver.WriteTimeout rpc: Context as first parameter to all functions reformat code fixes after my own review fixes after Ethan's review add test stubs fix config.toml * fixes after manual testing - rpc: do not recommend to use BroadcastTxCommit because it's slow and wastes Tendermint resources (pubsub) - rpc: better error in Subscribe and BroadcastTxCommit - HTTPClient: do not resubscribe if err = ErrAlreadySubscribed * fixes after Ismail's review * Update rpc/grpc/grpc_test.go Co-Authored-By: melekes <anton.kalyaev@gmail.com>
6 years ago
limit number of /subscribe clients and queries per client (#3269) * limit number of /subscribe clients and queries per client Add the following config variables (under [rpc] section): * max_subscription_clients * max_subscriptions_per_client * timeout_broadcast_tx_commit Fixes #2826 new HTTPClient interface for subscriptions finalize HTTPClient events interface remove EventSubscriber fix data race ``` WARNING: DATA RACE Read at 0x00c000a36060 by goroutine 129: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe.func1() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:168 +0x1f0 Previous write at 0x00c000a36060 by goroutine 132: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:191 +0x4e0 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 129 (running) created at: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:164 +0x4b7 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 132 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:119 +0x186 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ================== ``` lite client works (tested manually) godoc comments httpclient: do not close the out channel use TimeoutBroadcastTxCommit no timeout for unsubscribe but 1s Local (5s HTTP) timeout for resubscribe format code change Subscribe#out cap to 1 and replace config vars with RPCConfig TimeoutBroadcastTxCommit can't be greater than rpcserver.WriteTimeout rpc: Context as first parameter to all functions reformat code fixes after my own review fixes after Ethan's review add test stubs fix config.toml * fixes after manual testing - rpc: do not recommend to use BroadcastTxCommit because it's slow and wastes Tendermint resources (pubsub) - rpc: better error in Subscribe and BroadcastTxCommit - HTTPClient: do not resubscribe if err = ErrAlreadySubscribed * fixes after Ismail's review * Update rpc/grpc/grpc_test.go Co-Authored-By: melekes <anton.kalyaev@gmail.com>
6 years ago
limit number of /subscribe clients and queries per client (#3269) * limit number of /subscribe clients and queries per client Add the following config variables (under [rpc] section): * max_subscription_clients * max_subscriptions_per_client * timeout_broadcast_tx_commit Fixes #2826 new HTTPClient interface for subscriptions finalize HTTPClient events interface remove EventSubscriber fix data race ``` WARNING: DATA RACE Read at 0x00c000a36060 by goroutine 129: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe.func1() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:168 +0x1f0 Previous write at 0x00c000a36060 by goroutine 132: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:191 +0x4e0 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 129 (running) created at: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:164 +0x4b7 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 132 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:119 +0x186 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ================== ``` lite client works (tested manually) godoc comments httpclient: do not close the out channel use TimeoutBroadcastTxCommit no timeout for unsubscribe but 1s Local (5s HTTP) timeout for resubscribe format code change Subscribe#out cap to 1 and replace config vars with RPCConfig TimeoutBroadcastTxCommit can't be greater than rpcserver.WriteTimeout rpc: Context as first parameter to all functions reformat code fixes after my own review fixes after Ethan's review add test stubs fix config.toml * fixes after manual testing - rpc: do not recommend to use BroadcastTxCommit because it's slow and wastes Tendermint resources (pubsub) - rpc: better error in Subscribe and BroadcastTxCommit - HTTPClient: do not resubscribe if err = ErrAlreadySubscribed * fixes after Ismail's review * Update rpc/grpc/grpc_test.go Co-Authored-By: melekes <anton.kalyaev@gmail.com>
6 years ago
limit number of /subscribe clients and queries per client (#3269) * limit number of /subscribe clients and queries per client Add the following config variables (under [rpc] section): * max_subscription_clients * max_subscriptions_per_client * timeout_broadcast_tx_commit Fixes #2826 new HTTPClient interface for subscriptions finalize HTTPClient events interface remove EventSubscriber fix data race ``` WARNING: DATA RACE Read at 0x00c000a36060 by goroutine 129: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe.func1() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:168 +0x1f0 Previous write at 0x00c000a36060 by goroutine 132: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:191 +0x4e0 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 129 (running) created at: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:164 +0x4b7 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 132 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:119 +0x186 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ================== ``` lite client works (tested manually) godoc comments httpclient: do not close the out channel use TimeoutBroadcastTxCommit no timeout for unsubscribe but 1s Local (5s HTTP) timeout for resubscribe format code change Subscribe#out cap to 1 and replace config vars with RPCConfig TimeoutBroadcastTxCommit can't be greater than rpcserver.WriteTimeout rpc: Context as first parameter to all functions reformat code fixes after my own review fixes after Ethan's review add test stubs fix config.toml * fixes after manual testing - rpc: do not recommend to use BroadcastTxCommit because it's slow and wastes Tendermint resources (pubsub) - rpc: better error in Subscribe and BroadcastTxCommit - HTTPClient: do not resubscribe if err = ErrAlreadySubscribed * fixes after Ismail's review * Update rpc/grpc/grpc_test.go Co-Authored-By: melekes <anton.kalyaev@gmail.com>
6 years ago
limit number of /subscribe clients and queries per client (#3269) * limit number of /subscribe clients and queries per client Add the following config variables (under [rpc] section): * max_subscription_clients * max_subscriptions_per_client * timeout_broadcast_tx_commit Fixes #2826 new HTTPClient interface for subscriptions finalize HTTPClient events interface remove EventSubscriber fix data race ``` WARNING: DATA RACE Read at 0x00c000a36060 by goroutine 129: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe.func1() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:168 +0x1f0 Previous write at 0x00c000a36060 by goroutine 132: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:191 +0x4e0 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 129 (running) created at: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:164 +0x4b7 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 132 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:119 +0x186 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ================== ``` lite client works (tested manually) godoc comments httpclient: do not close the out channel use TimeoutBroadcastTxCommit no timeout for unsubscribe but 1s Local (5s HTTP) timeout for resubscribe format code change Subscribe#out cap to 1 and replace config vars with RPCConfig TimeoutBroadcastTxCommit can't be greater than rpcserver.WriteTimeout rpc: Context as first parameter to all functions reformat code fixes after my own review fixes after Ethan's review add test stubs fix config.toml * fixes after manual testing - rpc: do not recommend to use BroadcastTxCommit because it's slow and wastes Tendermint resources (pubsub) - rpc: better error in Subscribe and BroadcastTxCommit - HTTPClient: do not resubscribe if err = ErrAlreadySubscribed * fixes after Ismail's review * Update rpc/grpc/grpc_test.go Co-Authored-By: melekes <anton.kalyaev@gmail.com>
6 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
  1. package config
  2. import (
  3. "encoding/hex"
  4. "errors"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "os"
  9. "path/filepath"
  10. "time"
  11. tmjson "github.com/tendermint/tendermint/libs/json"
  12. "github.com/tendermint/tendermint/libs/log"
  13. tmos "github.com/tendermint/tendermint/libs/os"
  14. "github.com/tendermint/tendermint/types"
  15. )
  16. const (
  17. // FuzzModeDrop is a mode in which we randomly drop reads/writes, connections or sleep
  18. FuzzModeDrop = iota
  19. // FuzzModeDelay is a mode in which we randomly sleep
  20. FuzzModeDelay
  21. // DefaultLogLevel defines a default log level as INFO.
  22. DefaultLogLevel = "info"
  23. ModeFull = "full"
  24. ModeValidator = "validator"
  25. ModeSeed = "seed"
  26. BlockSyncV0 = "v0"
  27. BlockSyncV2 = "v2"
  28. MempoolV0 = "v0"
  29. MempoolV1 = "v1"
  30. )
  31. // NOTE: Most of the structs & relevant comments + the
  32. // default configuration options were used to manually
  33. // generate the config.toml. Please reflect any changes
  34. // made here in the defaultConfigTemplate constant in
  35. // config/toml.go
  36. // NOTE: libs/cli must know to look in the config dir!
  37. var (
  38. DefaultTendermintDir = ".tendermint"
  39. defaultConfigDir = "config"
  40. defaultDataDir = "data"
  41. defaultConfigFileName = "config.toml"
  42. defaultGenesisJSONName = "genesis.json"
  43. defaultMode = ModeFull
  44. defaultPrivValKeyName = "priv_validator_key.json"
  45. defaultPrivValStateName = "priv_validator_state.json"
  46. defaultNodeKeyName = "node_key.json"
  47. defaultAddrBookName = "addrbook.json"
  48. defaultConfigFilePath = filepath.Join(defaultConfigDir, defaultConfigFileName)
  49. defaultGenesisJSONPath = filepath.Join(defaultConfigDir, defaultGenesisJSONName)
  50. defaultPrivValKeyPath = filepath.Join(defaultConfigDir, defaultPrivValKeyName)
  51. defaultPrivValStatePath = filepath.Join(defaultDataDir, defaultPrivValStateName)
  52. defaultNodeKeyPath = filepath.Join(defaultConfigDir, defaultNodeKeyName)
  53. defaultAddrBookPath = filepath.Join(defaultConfigDir, defaultAddrBookName)
  54. )
  55. // Config defines the top level configuration for a Tendermint node
  56. type Config struct {
  57. // Top level options use an anonymous struct
  58. BaseConfig `mapstructure:",squash"`
  59. // Options for services
  60. RPC *RPCConfig `mapstructure:"rpc"`
  61. P2P *P2PConfig `mapstructure:"p2p"`
  62. Mempool *MempoolConfig `mapstructure:"mempool"`
  63. StateSync *StateSyncConfig `mapstructure:"statesync"`
  64. BlockSync *BlockSyncConfig `mapstructure:"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. Enable bool `mapstructure:"enable"`
  747. TempDir string `mapstructure:"temp-dir"`
  748. RPCServers []string `mapstructure:"rpc-servers"`
  749. TrustPeriod time.Duration `mapstructure:"trust-period"`
  750. TrustHeight int64 `mapstructure:"trust-height"`
  751. TrustHash string `mapstructure:"trust-hash"`
  752. DiscoveryTime time.Duration `mapstructure:"discovery-time"`
  753. ChunkRequestTimeout time.Duration `mapstructure:"chunk-request-timeout"`
  754. Fetchers int32 `mapstructure:"fetchers"`
  755. }
  756. func (cfg *StateSyncConfig) TrustHashBytes() []byte {
  757. // validated in ValidateBasic, so we can safely panic here
  758. bytes, err := hex.DecodeString(cfg.TrustHash)
  759. if err != nil {
  760. panic(err)
  761. }
  762. return bytes
  763. }
  764. // DefaultStateSyncConfig returns a default configuration for the state sync service
  765. func DefaultStateSyncConfig() *StateSyncConfig {
  766. return &StateSyncConfig{
  767. TrustPeriod: 168 * time.Hour,
  768. DiscoveryTime: 15 * time.Second,
  769. ChunkRequestTimeout: 15 * time.Second,
  770. Fetchers: 4,
  771. }
  772. }
  773. // TestStateSyncConfig returns a default configuration for the state sync service
  774. func TestStateSyncConfig() *StateSyncConfig {
  775. return DefaultStateSyncConfig()
  776. }
  777. // ValidateBasic performs basic validation.
  778. func (cfg *StateSyncConfig) ValidateBasic() error {
  779. if cfg.Enable {
  780. if len(cfg.RPCServers) == 0 {
  781. return errors.New("rpc-servers is required")
  782. }
  783. if len(cfg.RPCServers) < 2 {
  784. return errors.New("at least two rpc-servers entries is required")
  785. }
  786. for _, server := range cfg.RPCServers {
  787. if len(server) == 0 {
  788. return errors.New("found empty rpc-servers entry")
  789. }
  790. }
  791. if cfg.DiscoveryTime != 0 && cfg.DiscoveryTime < 5*time.Second {
  792. return errors.New("discovery time must be 0s or greater than five seconds")
  793. }
  794. if cfg.TrustPeriod <= 0 {
  795. return errors.New("trusted-period is required")
  796. }
  797. if cfg.TrustHeight <= 0 {
  798. return errors.New("trusted-height is required")
  799. }
  800. if len(cfg.TrustHash) == 0 {
  801. return errors.New("trusted-hash is required")
  802. }
  803. _, err := hex.DecodeString(cfg.TrustHash)
  804. if err != nil {
  805. return fmt.Errorf("invalid trusted-hash: %w", err)
  806. }
  807. if cfg.ChunkRequestTimeout < 5*time.Second {
  808. return errors.New("chunk-request-timeout must be at least 5 seconds")
  809. }
  810. if cfg.Fetchers <= 0 {
  811. return errors.New("fetchers is required")
  812. }
  813. }
  814. return nil
  815. }
  816. //-----------------------------------------------------------------------------
  817. // BlockSyncConfig (formerly known as FastSync) defines the configuration for the Tendermint block sync service
  818. type BlockSyncConfig struct {
  819. Version string `mapstructure:"version"`
  820. }
  821. // DefaultBlockSyncConfig returns a default configuration for the block sync service
  822. func DefaultBlockSyncConfig() *BlockSyncConfig {
  823. return &BlockSyncConfig{
  824. Version: BlockSyncV0,
  825. }
  826. }
  827. // TestBlockSyncConfig returns a default configuration for the block sync.
  828. func TestBlockSyncConfig() *BlockSyncConfig {
  829. return DefaultBlockSyncConfig()
  830. }
  831. // ValidateBasic performs basic validation.
  832. func (cfg *BlockSyncConfig) ValidateBasic() error {
  833. switch cfg.Version {
  834. case BlockSyncV0:
  835. return nil
  836. case BlockSyncV2:
  837. return errors.New("blocksync version v2 is no longer supported. Please use v0")
  838. default:
  839. return fmt.Errorf("unknown blocksync version %s", cfg.Version)
  840. }
  841. }
  842. //-----------------------------------------------------------------------------
  843. // ConsensusConfig
  844. // ConsensusConfig defines the configuration for the Tendermint consensus service,
  845. // including timeouts and details about the WAL and the block structure.
  846. type ConsensusConfig struct {
  847. RootDir string `mapstructure:"home"`
  848. WalPath string `mapstructure:"wal-file"`
  849. walFile string // overrides WalPath if set
  850. // TODO: remove timeout configs, these should be global not local
  851. // How long we wait for a proposal block before prevoting nil
  852. TimeoutPropose time.Duration `mapstructure:"timeout-propose"`
  853. // How much timeout-propose increases with each round
  854. TimeoutProposeDelta time.Duration `mapstructure:"timeout-propose-delta"`
  855. // How long we wait after receiving +2/3 prevotes for “anything” (ie. not a single block or nil)
  856. TimeoutPrevote time.Duration `mapstructure:"timeout-prevote"`
  857. // How much the timeout-prevote increases with each round
  858. TimeoutPrevoteDelta time.Duration `mapstructure:"timeout-prevote-delta"`
  859. // How long we wait after receiving +2/3 precommits for “anything” (ie. not a single block or nil)
  860. TimeoutPrecommit time.Duration `mapstructure:"timeout-precommit"`
  861. // How much the timeout-precommit increases with each round
  862. TimeoutPrecommitDelta time.Duration `mapstructure:"timeout-precommit-delta"`
  863. // How long we wait after committing a block, before starting on the new
  864. // height (this gives us a chance to receive some more precommits, even
  865. // though we already have +2/3).
  866. TimeoutCommit time.Duration `mapstructure:"timeout-commit"`
  867. // Make progress as soon as we have all the precommits (as if TimeoutCommit = 0)
  868. SkipTimeoutCommit bool `mapstructure:"skip-timeout-commit"`
  869. // EmptyBlocks mode and possible interval between empty blocks
  870. CreateEmptyBlocks bool `mapstructure:"create-empty-blocks"`
  871. CreateEmptyBlocksInterval time.Duration `mapstructure:"create-empty-blocks-interval"`
  872. // Reactor sleep duration parameters
  873. PeerGossipSleepDuration time.Duration `mapstructure:"peer-gossip-sleep-duration"`
  874. PeerQueryMaj23SleepDuration time.Duration `mapstructure:"peer-query-maj23-sleep-duration"`
  875. DoubleSignCheckHeight int64 `mapstructure:"double-sign-check-height"`
  876. }
  877. // DefaultConsensusConfig returns a default configuration for the consensus service
  878. func DefaultConsensusConfig() *ConsensusConfig {
  879. return &ConsensusConfig{
  880. WalPath: filepath.Join(defaultDataDir, "cs.wal", "wal"),
  881. TimeoutPropose: 3000 * time.Millisecond,
  882. TimeoutProposeDelta: 500 * time.Millisecond,
  883. TimeoutPrevote: 1000 * time.Millisecond,
  884. TimeoutPrevoteDelta: 500 * time.Millisecond,
  885. TimeoutPrecommit: 1000 * time.Millisecond,
  886. TimeoutPrecommitDelta: 500 * time.Millisecond,
  887. TimeoutCommit: 1000 * time.Millisecond,
  888. SkipTimeoutCommit: false,
  889. CreateEmptyBlocks: true,
  890. CreateEmptyBlocksInterval: 0 * time.Second,
  891. PeerGossipSleepDuration: 100 * time.Millisecond,
  892. PeerQueryMaj23SleepDuration: 2000 * time.Millisecond,
  893. DoubleSignCheckHeight: int64(0),
  894. }
  895. }
  896. // TestConsensusConfig returns a configuration for testing the consensus service
  897. func TestConsensusConfig() *ConsensusConfig {
  898. cfg := DefaultConsensusConfig()
  899. cfg.TimeoutPropose = 40 * time.Millisecond
  900. cfg.TimeoutProposeDelta = 1 * time.Millisecond
  901. cfg.TimeoutPrevote = 10 * time.Millisecond
  902. cfg.TimeoutPrevoteDelta = 1 * time.Millisecond
  903. cfg.TimeoutPrecommit = 10 * time.Millisecond
  904. cfg.TimeoutPrecommitDelta = 1 * time.Millisecond
  905. cfg.TimeoutCommit = 10 * time.Millisecond
  906. cfg.SkipTimeoutCommit = true
  907. cfg.PeerGossipSleepDuration = 5 * time.Millisecond
  908. cfg.PeerQueryMaj23SleepDuration = 250 * time.Millisecond
  909. cfg.DoubleSignCheckHeight = int64(0)
  910. return cfg
  911. }
  912. // WaitForTxs returns true if the consensus should wait for transactions before entering the propose step
  913. func (cfg *ConsensusConfig) WaitForTxs() bool {
  914. return !cfg.CreateEmptyBlocks || cfg.CreateEmptyBlocksInterval > 0
  915. }
  916. // Propose returns the amount of time to wait for a proposal
  917. func (cfg *ConsensusConfig) Propose(round int32) time.Duration {
  918. return time.Duration(
  919. cfg.TimeoutPropose.Nanoseconds()+cfg.TimeoutProposeDelta.Nanoseconds()*int64(round),
  920. ) * time.Nanosecond
  921. }
  922. // Prevote returns the amount of time to wait for straggler votes after receiving any +2/3 prevotes
  923. func (cfg *ConsensusConfig) Prevote(round int32) time.Duration {
  924. return time.Duration(
  925. cfg.TimeoutPrevote.Nanoseconds()+cfg.TimeoutPrevoteDelta.Nanoseconds()*int64(round),
  926. ) * time.Nanosecond
  927. }
  928. // Precommit returns the amount of time to wait for straggler votes after receiving any +2/3 precommits
  929. func (cfg *ConsensusConfig) Precommit(round int32) time.Duration {
  930. return time.Duration(
  931. cfg.TimeoutPrecommit.Nanoseconds()+cfg.TimeoutPrecommitDelta.Nanoseconds()*int64(round),
  932. ) * time.Nanosecond
  933. }
  934. // Commit returns the amount of time to wait for straggler votes after receiving +2/3 precommits
  935. // for a single block (ie. a commit).
  936. func (cfg *ConsensusConfig) Commit(t time.Time) time.Time {
  937. return t.Add(cfg.TimeoutCommit)
  938. }
  939. // WalFile returns the full path to the write-ahead log file
  940. func (cfg *ConsensusConfig) WalFile() string {
  941. if cfg.walFile != "" {
  942. return cfg.walFile
  943. }
  944. return rootify(cfg.WalPath, cfg.RootDir)
  945. }
  946. // SetWalFile sets the path to the write-ahead log file
  947. func (cfg *ConsensusConfig) SetWalFile(walFile string) {
  948. cfg.walFile = walFile
  949. }
  950. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  951. // returns an error if any check fails.
  952. func (cfg *ConsensusConfig) ValidateBasic() error {
  953. if cfg.TimeoutPropose < 0 {
  954. return errors.New("timeout-propose can't be negative")
  955. }
  956. if cfg.TimeoutProposeDelta < 0 {
  957. return errors.New("timeout-propose-delta can't be negative")
  958. }
  959. if cfg.TimeoutPrevote < 0 {
  960. return errors.New("timeout-prevote can't be negative")
  961. }
  962. if cfg.TimeoutPrevoteDelta < 0 {
  963. return errors.New("timeout-prevote-delta can't be negative")
  964. }
  965. if cfg.TimeoutPrecommit < 0 {
  966. return errors.New("timeout-precommit can't be negative")
  967. }
  968. if cfg.TimeoutPrecommitDelta < 0 {
  969. return errors.New("timeout-precommit-delta can't be negative")
  970. }
  971. if cfg.TimeoutCommit < 0 {
  972. return errors.New("timeout-commit can't be negative")
  973. }
  974. if cfg.CreateEmptyBlocksInterval < 0 {
  975. return errors.New("create-empty-blocks-interval can't be negative")
  976. }
  977. if cfg.PeerGossipSleepDuration < 0 {
  978. return errors.New("peer-gossip-sleep-duration can't be negative")
  979. }
  980. if cfg.PeerQueryMaj23SleepDuration < 0 {
  981. return errors.New("peer-query-maj23-sleep-duration can't be negative")
  982. }
  983. if cfg.DoubleSignCheckHeight < 0 {
  984. return errors.New("double-sign-check-height can't be negative")
  985. }
  986. return nil
  987. }
  988. //-----------------------------------------------------------------------------
  989. // TxIndexConfig
  990. // Remember that Event has the following structure:
  991. // type: [
  992. // key: value,
  993. // ...
  994. // ]
  995. //
  996. // CompositeKeys are constructed by `type.key`
  997. // TxIndexConfig defines the configuration for the transaction indexer,
  998. // including composite keys to index.
  999. type TxIndexConfig struct {
  1000. // The backend database list to back the indexer.
  1001. // If list contains `null`, meaning no indexer service will be used.
  1002. //
  1003. // Options:
  1004. // 1) "null" - no indexer services.
  1005. // 2) "kv" (default) - the simplest possible indexer,
  1006. // backed by key-value storage (defaults to levelDB; see DBBackend).
  1007. // 3) "psql" - the indexer services backed by PostgreSQL.
  1008. Indexer []string `mapstructure:"indexer"`
  1009. // The PostgreSQL connection configuration, the connection format:
  1010. // postgresql://<user>:<password>@<host>:<port>/<db>?<opts>
  1011. PsqlConn string `mapstructure:"psql-conn"`
  1012. }
  1013. // DefaultTxIndexConfig returns a default configuration for the transaction indexer.
  1014. func DefaultTxIndexConfig() *TxIndexConfig {
  1015. return &TxIndexConfig{
  1016. Indexer: []string{"kv"},
  1017. }
  1018. }
  1019. // TestTxIndexConfig returns a default configuration for the transaction indexer.
  1020. func TestTxIndexConfig() *TxIndexConfig {
  1021. return DefaultTxIndexConfig()
  1022. }
  1023. //-----------------------------------------------------------------------------
  1024. // InstrumentationConfig
  1025. // InstrumentationConfig defines the configuration for metrics reporting.
  1026. type InstrumentationConfig struct {
  1027. // When true, Prometheus metrics are served under /metrics on
  1028. // PrometheusListenAddr.
  1029. // Check out the documentation for the list of available metrics.
  1030. Prometheus bool `mapstructure:"prometheus"`
  1031. // Address to listen for Prometheus collector(s) connections.
  1032. PrometheusListenAddr string `mapstructure:"prometheus-listen-addr"`
  1033. // Maximum number of simultaneous connections.
  1034. // If you want to accept a larger number than the default, make sure
  1035. // you increase your OS limits.
  1036. // 0 - unlimited.
  1037. MaxOpenConnections int `mapstructure:"max-open-connections"`
  1038. // Instrumentation namespace.
  1039. Namespace string `mapstructure:"namespace"`
  1040. }
  1041. // DefaultInstrumentationConfig returns a default configuration for metrics
  1042. // reporting.
  1043. func DefaultInstrumentationConfig() *InstrumentationConfig {
  1044. return &InstrumentationConfig{
  1045. Prometheus: false,
  1046. PrometheusListenAddr: ":26660",
  1047. MaxOpenConnections: 3,
  1048. Namespace: "tendermint",
  1049. }
  1050. }
  1051. // TestInstrumentationConfig returns a default configuration for metrics
  1052. // reporting.
  1053. func TestInstrumentationConfig() *InstrumentationConfig {
  1054. return DefaultInstrumentationConfig()
  1055. }
  1056. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  1057. // returns an error if any check fails.
  1058. func (cfg *InstrumentationConfig) ValidateBasic() error {
  1059. if cfg.MaxOpenConnections < 0 {
  1060. return errors.New("max-open-connections can't be negative")
  1061. }
  1062. return nil
  1063. }
  1064. //-----------------------------------------------------------------------------
  1065. // Utils
  1066. // helper function to make config creation independent of root dir
  1067. func rootify(path, root string) string {
  1068. if filepath.IsAbs(path) {
  1069. return path
  1070. }
  1071. return filepath.Join(root, path)
  1072. }
  1073. //-----------------------------------------------------------------------------
  1074. // Moniker
  1075. var defaultMoniker = getDefaultMoniker()
  1076. // getDefaultMoniker returns a default moniker, which is the host name. If runtime
  1077. // fails to get the host name, "anonymous" will be returned.
  1078. func getDefaultMoniker() string {
  1079. moniker, err := os.Hostname()
  1080. if err != nil {
  1081. moniker = "anonymous"
  1082. }
  1083. return moniker
  1084. }