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.

1243 lines
43 KiB

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