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.

1374 lines
48 KiB

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