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.

1276 lines
44 KiB

deps: update gogo/protobuf version from v1.2.1 to v1.3.0 (#3947) * update gogo/protobuf version from v1.2.1 to v1.3.0 Also errcheck from v1.1.0 to v1.2.0 See full diff in - https://github.com/gogo/protobuf/compare/v1.2.1...v1.3.0 - https://github.com/kisielk/errcheck/compare/v1.1.0...v1.2.0 Changelog: Tested versions: go 1.12.9 protoc 3.7.1 Improvements: plugin/stringer - Handle repeated and/or nullable types a bit better now. plugin/size - Remove the loop in sovXXX by using bit twiddling. Thanks: https://github.com/apelisse plugin/marshalto - Implemented a reverse marshal strategy which allows for faster marshalling. This now avoids a recursive (and repeated) call to Size(). Thanks: https://github.com/apelisse plugin/compare - Added support for for oneof types. Bug fixes: protoc-gen-gogo/generator - Fix assignment to entry in nil map. Thanks: https://github.com/tgulacsi protoc-gen-gogo/generator - Allows plugins to call RecordTypeUse without panicking. Thanks: https://github.com/fedenusy proto/extensions - Fixed set extension regression. We did not clear the extensions before setting. io/uint32 - fix uint32reader bug that causes ReadMsg to recreate buffer when lengths are the same. Thanks: https://github.com/SebiSujar proto/table_merge: Fix merge of non-nullable slices. Thanks: https://github.com/euroelessar Upstream commits: merged in golang/protobuf commit 318d17de72747ed1c16502681db4b2bb709a92d0 - Add UnimplementedServer for server interface merged in golang/protobuf commit b85cd75de734650db18a99a943fe351d41387800 - protoc-gen-go/grpc: inline errUnimplemented function merged in golang/protobuf commit d3c38a4eb4970272b87a425ae00ccc4548e2f9bb - protoc-gen-go/grpc: use status and code packages only if needed merged in golang/protobuf commit e91709a02e0e8ff8b86b7aa913fdc9ae9498e825 - fix indentation in jsonpb with Any messages merged in golang/protobuf commit 8d0c54c1246661d9a51ca0ba455d22116d485eaa - protoc-gen-go: generate XXX_OneofWrappers instead of XXX_OneofFuncs Misc: extensions.md - Markdown update. Thanks: https://github.com/TennyZhuang Readme.md - Added user. go/protoc update - Updated to go1.12.x and protoc 3.7.1 Makefile update - fix go vet shadow tool reference test/mixbench - Update mixbench tool. Expose runnable benchmarks via flags. * update certstrap * update golangci-lint from v1.13.2 to v1.17.1 * update gox as well * test * comment out golangci temporary * comment out go-deadlock deps
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
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. // Deprecated: gRPC in the RPC layer of Tendermint will be removed in 0.36.
  378. GRPCListenAddress string `mapstructure:"grpc-laddr"`
  379. // Maximum number of simultaneous connections.
  380. // Does not include RPC (HTTP&WebSocket) connections. See max-open-connections
  381. // If you want to accept a larger number than the default, make sure
  382. // you increase your OS limits.
  383. // 0 - unlimited.
  384. // Deprecated: gRPC in the RPC layer of Tendermint will be removed in 0.36.
  385. GRPCMaxOpenConnections int `mapstructure:"grpc-max-open-connections"`
  386. // Activate unsafe RPC commands like /dial-persistent-peers and /unsafe-flush-mempool
  387. Unsafe bool `mapstructure:"unsafe"`
  388. // Maximum number of simultaneous connections (including WebSocket).
  389. // Does not include gRPC connections. See grpc-max-open-connections
  390. // If you want to accept a larger number than the default, make sure
  391. // you increase your OS limits.
  392. // 0 - unlimited.
  393. // Should be < {ulimit -Sn} - {MaxNumInboundPeers} - {MaxNumOutboundPeers} - {N of wal, db and other open files}
  394. // 1024 - 40 - 10 - 50 = 924 = ~900
  395. MaxOpenConnections int `mapstructure:"max-open-connections"`
  396. // Maximum number of unique clientIDs that can /subscribe
  397. // If you're using /broadcast_tx_commit, set to the estimated maximum number
  398. // of broadcast_tx_commit calls per block.
  399. MaxSubscriptionClients int `mapstructure:"max-subscription-clients"`
  400. // Maximum number of unique queries a given client can /subscribe to
  401. // If you're using GRPC (or Local RPC client) and /broadcast_tx_commit, set
  402. // to the estimated maximum number of broadcast_tx_commit calls per block.
  403. MaxSubscriptionsPerClient int `mapstructure:"max-subscriptions-per-client"`
  404. // How long to wait for a tx to be committed during /broadcast_tx_commit
  405. // WARNING: Using a value larger than 10s will result in increasing the
  406. // global HTTP write timeout, which applies to all connections and endpoints.
  407. // See https://github.com/tendermint/tendermint/issues/3435
  408. TimeoutBroadcastTxCommit time.Duration `mapstructure:"timeout-broadcast-tx-commit"`
  409. // Maximum size of request body, in bytes
  410. MaxBodyBytes int64 `mapstructure:"max-body-bytes"`
  411. // Maximum size of request header, in bytes
  412. MaxHeaderBytes int `mapstructure:"max-header-bytes"`
  413. // The path to a file containing certificate that is used to create the HTTPS server.
  414. // Might be either absolute path or path related to Tendermint's config directory.
  415. //
  416. // If the certificate is signed by a certificate authority,
  417. // the certFile should be the concatenation of the server's certificate, any intermediates,
  418. // and the CA's certificate.
  419. //
  420. // NOTE: both tls-cert-file and tls-key-file must be present for Tendermint to create HTTPS server.
  421. // Otherwise, HTTP server is run.
  422. TLSCertFile string `mapstructure:"tls-cert-file"`
  423. // The path to a file containing matching private key that is used to create the HTTPS server.
  424. // Might be either absolute path or path related to tendermint's config directory.
  425. //
  426. // NOTE: both tls-cert-file and tls-key-file must be present for Tendermint to create HTTPS server.
  427. // Otherwise, HTTP server is run.
  428. TLSKeyFile string `mapstructure:"tls-key-file"`
  429. // pprof listen address (https://golang.org/pkg/net/http/pprof)
  430. PprofListenAddress string `mapstructure:"pprof-laddr"`
  431. }
  432. // DefaultRPCConfig returns a default configuration for the RPC server
  433. func DefaultRPCConfig() *RPCConfig {
  434. return &RPCConfig{
  435. ListenAddress: "tcp://127.0.0.1:26657",
  436. CORSAllowedOrigins: []string{},
  437. CORSAllowedMethods: []string{http.MethodHead, http.MethodGet, http.MethodPost},
  438. CORSAllowedHeaders: []string{"Origin", "Accept", "Content-Type", "X-Requested-With", "X-Server-Time"},
  439. GRPCListenAddress: "",
  440. GRPCMaxOpenConnections: 900,
  441. Unsafe: false,
  442. MaxOpenConnections: 900,
  443. MaxSubscriptionClients: 100,
  444. MaxSubscriptionsPerClient: 5,
  445. TimeoutBroadcastTxCommit: 10 * time.Second,
  446. MaxBodyBytes: int64(1000000), // 1MB
  447. MaxHeaderBytes: 1 << 20, // same as the net/http default
  448. TLSCertFile: "",
  449. TLSKeyFile: "",
  450. }
  451. }
  452. // TestRPCConfig returns a configuration for testing the RPC server
  453. func TestRPCConfig() *RPCConfig {
  454. cfg := DefaultRPCConfig()
  455. cfg.ListenAddress = "tcp://127.0.0.1:36657"
  456. cfg.GRPCListenAddress = "tcp://127.0.0.1:36658"
  457. cfg.Unsafe = true
  458. return cfg
  459. }
  460. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  461. // returns an error if any check fails.
  462. func (cfg *RPCConfig) ValidateBasic() error {
  463. if cfg.GRPCMaxOpenConnections < 0 {
  464. return errors.New("grpc-max-open-connections can't be negative")
  465. }
  466. if cfg.MaxOpenConnections < 0 {
  467. return errors.New("max-open-connections can't be negative")
  468. }
  469. if cfg.MaxSubscriptionClients < 0 {
  470. return errors.New("max-subscription-clients can't be negative")
  471. }
  472. if cfg.MaxSubscriptionsPerClient < 0 {
  473. return errors.New("max-subscriptions-per-client can't be negative")
  474. }
  475. if cfg.TimeoutBroadcastTxCommit < 0 {
  476. return errors.New("timeout-broadcast-tx-commit can't be negative")
  477. }
  478. if cfg.MaxBodyBytes < 0 {
  479. return errors.New("max-body-bytes can't be negative")
  480. }
  481. if cfg.MaxHeaderBytes < 0 {
  482. return errors.New("max-header-bytes can't be negative")
  483. }
  484. return nil
  485. }
  486. // IsCorsEnabled returns true if cross-origin resource sharing is enabled.
  487. func (cfg *RPCConfig) IsCorsEnabled() bool {
  488. return len(cfg.CORSAllowedOrigins) != 0
  489. }
  490. func (cfg RPCConfig) KeyFile() string {
  491. path := cfg.TLSKeyFile
  492. if filepath.IsAbs(path) {
  493. return path
  494. }
  495. return rootify(filepath.Join(defaultConfigDir, path), cfg.RootDir)
  496. }
  497. func (cfg RPCConfig) CertFile() string {
  498. path := cfg.TLSCertFile
  499. if filepath.IsAbs(path) {
  500. return path
  501. }
  502. return rootify(filepath.Join(defaultConfigDir, path), cfg.RootDir)
  503. }
  504. func (cfg RPCConfig) IsTLSEnabled() bool {
  505. return cfg.TLSCertFile != "" && cfg.TLSKeyFile != ""
  506. }
  507. //-----------------------------------------------------------------------------
  508. // P2PConfig
  509. // P2PConfig defines the configuration options for the Tendermint peer-to-peer networking layer
  510. type P2PConfig struct { //nolint: maligned
  511. RootDir string `mapstructure:"home"`
  512. // Address to listen for incoming connections
  513. ListenAddress string `mapstructure:"laddr"`
  514. // Address to advertise to peers for them to dial
  515. ExternalAddress string `mapstructure:"external-address"`
  516. // Comma separated list of seed nodes to connect to
  517. // We only use these if we can’t connect to peers in the addrbook
  518. // NOTE: not used by the new PEX reactor. Please use BootstrapPeers instead.
  519. // TODO: Remove once p2p refactor is complete
  520. // ref: https://github.com/tendermint/tendermint/issues/5670
  521. Seeds string `mapstructure:"seeds"`
  522. // Comma separated list of peers to be added to the peer store
  523. // on startup. Either BootstrapPeers or PersistentPeers are
  524. // needed for peer discovery
  525. BootstrapPeers string `mapstructure:"bootstrap-peers"`
  526. // Comma separated list of nodes to keep persistent connections to
  527. PersistentPeers string `mapstructure:"persistent-peers"`
  528. // UPNP port forwarding
  529. UPNP bool `mapstructure:"upnp"`
  530. // Path to address book
  531. AddrBook string `mapstructure:"addr-book-file"`
  532. // Set true for strict address routability rules
  533. // Set false for private or local networks
  534. AddrBookStrict bool `mapstructure:"addr-book-strict"`
  535. // Maximum number of inbound peers
  536. //
  537. // TODO: Remove once p2p refactor is complete in favor of MaxConnections.
  538. // ref: https://github.com/tendermint/tendermint/issues/5670
  539. MaxNumInboundPeers int `mapstructure:"max-num-inbound-peers"`
  540. // Maximum number of outbound peers to connect to, excluding persistent peers.
  541. //
  542. // TODO: Remove once p2p refactor is complete in favor of MaxConnections.
  543. // ref: https://github.com/tendermint/tendermint/issues/5670
  544. MaxNumOutboundPeers int `mapstructure:"max-num-outbound-peers"`
  545. // MaxConnections defines the maximum number of connected peers (inbound and
  546. // outbound).
  547. MaxConnections uint16 `mapstructure:"max-connections"`
  548. // MaxIncomingConnectionAttempts rate limits the number of incoming connection
  549. // attempts per IP address.
  550. MaxIncomingConnectionAttempts uint `mapstructure:"max-incoming-connection-attempts"`
  551. // List of node IDs, to which a connection will be (re)established ignoring any existing limits
  552. UnconditionalPeerIDs string `mapstructure:"unconditional-peer-ids"`
  553. // Maximum pause when redialing a persistent peer (if zero, exponential backoff is used)
  554. PersistentPeersMaxDialPeriod time.Duration `mapstructure:"persistent-peers-max-dial-period"`
  555. // Time to wait before flushing messages out on the connection
  556. FlushThrottleTimeout time.Duration `mapstructure:"flush-throttle-timeout"`
  557. // Maximum size of a message packet payload, in bytes
  558. MaxPacketMsgPayloadSize int `mapstructure:"max-packet-msg-payload-size"`
  559. // Rate at which packets can be sent, in bytes/second
  560. SendRate int64 `mapstructure:"send-rate"`
  561. // Rate at which packets can be received, in bytes/second
  562. RecvRate int64 `mapstructure:"recv-rate"`
  563. // Set true to enable the peer-exchange reactor
  564. PexReactor bool `mapstructure:"pex"`
  565. // Comma separated list of peer IDs to keep private (will not be gossiped to
  566. // other peers)
  567. PrivatePeerIDs string `mapstructure:"private-peer-ids"`
  568. // Toggle to disable guard against peers connecting from the same ip.
  569. AllowDuplicateIP bool `mapstructure:"allow-duplicate-ip"`
  570. // Peer connection configuration.
  571. HandshakeTimeout time.Duration `mapstructure:"handshake-timeout"`
  572. DialTimeout time.Duration `mapstructure:"dial-timeout"`
  573. // Testing params.
  574. // Force dial to fail
  575. TestDialFail bool `mapstructure:"test-dial-fail"`
  576. // DisableLegacy is used mostly for testing to enable or disable the legacy
  577. // P2P stack.
  578. DisableLegacy bool `mapstructure:"disable-legacy"`
  579. // Makes it possible to configure which queue backend the p2p
  580. // layer uses. Options are: "fifo", "priority" and "wdrr",
  581. // with the default being "fifo".
  582. QueueType string `mapstructure:"queue-type"`
  583. }
  584. // DefaultP2PConfig returns a default configuration for the peer-to-peer layer
  585. func DefaultP2PConfig() *P2PConfig {
  586. return &P2PConfig{
  587. ListenAddress: "tcp://0.0.0.0:26656",
  588. ExternalAddress: "",
  589. UPNP: false,
  590. AddrBook: defaultAddrBookPath,
  591. AddrBookStrict: true,
  592. MaxNumInboundPeers: 40,
  593. MaxNumOutboundPeers: 10,
  594. MaxConnections: 64,
  595. MaxIncomingConnectionAttempts: 100,
  596. PersistentPeersMaxDialPeriod: 0 * time.Second,
  597. FlushThrottleTimeout: 100 * time.Millisecond,
  598. // The MTU (Maximum Transmission Unit) for Ethernet is 1500 bytes.
  599. // The IP header and the TCP header take up 20 bytes each at least (unless
  600. // optional header fields are used) and thus the max for (non-Jumbo frame)
  601. // Ethernet is 1500 - 20 -20 = 1460
  602. // Source: https://stackoverflow.com/a/3074427/820520
  603. MaxPacketMsgPayloadSize: 1400,
  604. SendRate: 5120000, // 5 mB/s
  605. RecvRate: 5120000, // 5 mB/s
  606. PexReactor: true,
  607. AllowDuplicateIP: false,
  608. HandshakeTimeout: 20 * time.Second,
  609. DialTimeout: 3 * time.Second,
  610. TestDialFail: false,
  611. QueueType: "priority",
  612. }
  613. }
  614. // TestP2PConfig returns a configuration for testing the peer-to-peer layer
  615. func TestP2PConfig() *P2PConfig {
  616. cfg := DefaultP2PConfig()
  617. cfg.ListenAddress = "tcp://127.0.0.1:36656"
  618. cfg.FlushThrottleTimeout = 10 * time.Millisecond
  619. cfg.AllowDuplicateIP = true
  620. return cfg
  621. }
  622. // AddrBookFile returns the full path to the address book
  623. func (cfg *P2PConfig) AddrBookFile() string {
  624. return rootify(cfg.AddrBook, cfg.RootDir)
  625. }
  626. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  627. // returns an error if any check fails.
  628. func (cfg *P2PConfig) ValidateBasic() error {
  629. if cfg.MaxNumInboundPeers < 0 {
  630. return errors.New("max-num-inbound-peers can't be negative")
  631. }
  632. if cfg.MaxNumOutboundPeers < 0 {
  633. return errors.New("max-num-outbound-peers can't be negative")
  634. }
  635. if cfg.FlushThrottleTimeout < 0 {
  636. return errors.New("flush-throttle-timeout can't be negative")
  637. }
  638. if cfg.PersistentPeersMaxDialPeriod < 0 {
  639. return errors.New("persistent-peers-max-dial-period can't be negative")
  640. }
  641. if cfg.MaxPacketMsgPayloadSize < 0 {
  642. return errors.New("max-packet-msg-payload-size can't be negative")
  643. }
  644. if cfg.SendRate < 0 {
  645. return errors.New("send-rate can't be negative")
  646. }
  647. if cfg.RecvRate < 0 {
  648. return errors.New("recv-rate can't be negative")
  649. }
  650. return nil
  651. }
  652. //-----------------------------------------------------------------------------
  653. // MempoolConfig
  654. // MempoolConfig defines the configuration options for the Tendermint mempool.
  655. type MempoolConfig struct {
  656. Version string `mapstructure:"version"`
  657. RootDir string `mapstructure:"home"`
  658. Recheck bool `mapstructure:"recheck"`
  659. Broadcast bool `mapstructure:"broadcast"`
  660. // Maximum number of transactions in the mempool
  661. Size int `mapstructure:"size"`
  662. // Limit the total size of all txs in the mempool.
  663. // This only accounts for raw transactions (e.g. given 1MB transactions and
  664. // max-txs-bytes=5MB, mempool will only accept 5 transactions).
  665. MaxTxsBytes int64 `mapstructure:"max-txs-bytes"`
  666. // Size of the cache (used to filter transactions we saw earlier) in transactions
  667. CacheSize int `mapstructure:"cache-size"`
  668. // Do not remove invalid transactions from the cache (default: false)
  669. // Set to true if it's not possible for any invalid transaction to become
  670. // valid again in the future.
  671. KeepInvalidTxsInCache bool `mapstructure:"keep-invalid-txs-in-cache"`
  672. // Maximum size of a single transaction
  673. // NOTE: the max size of a tx transmitted over the network is {max-tx-bytes}.
  674. MaxTxBytes int `mapstructure:"max-tx-bytes"`
  675. // Maximum size of a batch of transactions to send to a peer
  676. // Including space needed by encoding (one varint per transaction).
  677. // XXX: Unused due to https://github.com/tendermint/tendermint/issues/5796
  678. MaxBatchBytes int `mapstructure:"max-batch-bytes"`
  679. // TTLDuration, if non-zero, defines the maximum amount of time a transaction
  680. // can exist for in the mempool.
  681. //
  682. // Note, if TTLNumBlocks is also defined, a transaction will be removed if it
  683. // has existed in the mempool at least TTLNumBlocks number of blocks or if it's
  684. // insertion time into the mempool is beyond TTLDuration.
  685. TTLDuration time.Duration `mapstructure:"ttl-duration"`
  686. // TTLNumBlocks, if non-zero, defines the maximum number of blocks a transaction
  687. // can exist for in the mempool.
  688. //
  689. // Note, if TTLDuration is also defined, a transaction will be removed if it
  690. // has existed in the mempool at least TTLNumBlocks number of blocks or if
  691. // it's insertion time into the mempool is beyond TTLDuration.
  692. TTLNumBlocks int64 `mapstructure:"ttl-num-blocks"`
  693. }
  694. // DefaultMempoolConfig returns a default configuration for the Tendermint mempool.
  695. func DefaultMempoolConfig() *MempoolConfig {
  696. return &MempoolConfig{
  697. Version: MempoolV1,
  698. Recheck: true,
  699. Broadcast: true,
  700. // Each signature verification takes .5ms, Size reduced until we implement
  701. // ABCI Recheck
  702. Size: 5000,
  703. MaxTxsBytes: 1024 * 1024 * 1024, // 1GB
  704. CacheSize: 10000,
  705. MaxTxBytes: 1024 * 1024, // 1MB
  706. TTLDuration: 0 * time.Second,
  707. TTLNumBlocks: 0,
  708. }
  709. }
  710. // TestMempoolConfig returns a configuration for testing the Tendermint mempool
  711. func TestMempoolConfig() *MempoolConfig {
  712. cfg := DefaultMempoolConfig()
  713. cfg.CacheSize = 1000
  714. return cfg
  715. }
  716. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  717. // returns an error if any check fails.
  718. func (cfg *MempoolConfig) ValidateBasic() error {
  719. if cfg.Size < 0 {
  720. return errors.New("size can't be negative")
  721. }
  722. if cfg.MaxTxsBytes < 0 {
  723. return errors.New("max-txs-bytes can't be negative")
  724. }
  725. if cfg.CacheSize < 0 {
  726. return errors.New("cache-size can't be negative")
  727. }
  728. if cfg.MaxTxBytes < 0 {
  729. return errors.New("max-tx-bytes can't be negative")
  730. }
  731. if cfg.TTLDuration < 0 {
  732. return errors.New("ttl-duration can't be negative")
  733. }
  734. if cfg.TTLNumBlocks < 0 {
  735. return errors.New("ttl-num-blocks can't be negative")
  736. }
  737. return nil
  738. }
  739. //-----------------------------------------------------------------------------
  740. // StateSyncConfig
  741. // StateSyncConfig defines the configuration for the Tendermint state sync service
  742. type StateSyncConfig struct {
  743. Enable bool `mapstructure:"enable"`
  744. TempDir string `mapstructure:"temp-dir"`
  745. RPCServers []string `mapstructure:"rpc-servers"`
  746. TrustPeriod time.Duration `mapstructure:"trust-period"`
  747. TrustHeight int64 `mapstructure:"trust-height"`
  748. TrustHash string `mapstructure:"trust-hash"`
  749. DiscoveryTime time.Duration `mapstructure:"discovery-time"`
  750. ChunkRequestTimeout time.Duration `mapstructure:"chunk-request-timeout"`
  751. Fetchers int32 `mapstructure:"fetchers"`
  752. }
  753. func (cfg *StateSyncConfig) TrustHashBytes() []byte {
  754. // validated in ValidateBasic, so we can safely panic here
  755. bytes, err := hex.DecodeString(cfg.TrustHash)
  756. if err != nil {
  757. panic(err)
  758. }
  759. return bytes
  760. }
  761. // DefaultStateSyncConfig returns a default configuration for the state sync service
  762. func DefaultStateSyncConfig() *StateSyncConfig {
  763. return &StateSyncConfig{
  764. TrustPeriod: 168 * time.Hour,
  765. DiscoveryTime: 15 * time.Second,
  766. ChunkRequestTimeout: 15 * time.Second,
  767. Fetchers: 4,
  768. }
  769. }
  770. // TestFastSyncConfig returns a default configuration for the state sync service
  771. func TestStateSyncConfig() *StateSyncConfig {
  772. return DefaultStateSyncConfig()
  773. }
  774. // ValidateBasic performs basic validation.
  775. func (cfg *StateSyncConfig) ValidateBasic() error {
  776. if cfg.Enable {
  777. if len(cfg.RPCServers) == 0 {
  778. return errors.New("rpc-servers is required")
  779. }
  780. if len(cfg.RPCServers) < 2 {
  781. return errors.New("at least two rpc-servers entries is required")
  782. }
  783. for _, server := range cfg.RPCServers {
  784. if len(server) == 0 {
  785. return errors.New("found empty rpc-servers entry")
  786. }
  787. }
  788. if cfg.DiscoveryTime != 0 && cfg.DiscoveryTime < 5*time.Second {
  789. return errors.New("discovery time must be 0s or greater than five seconds")
  790. }
  791. if cfg.TrustPeriod <= 0 {
  792. return errors.New("trusted-period is required")
  793. }
  794. if cfg.TrustHeight <= 0 {
  795. return errors.New("trusted-height is required")
  796. }
  797. if len(cfg.TrustHash) == 0 {
  798. return errors.New("trusted-hash is required")
  799. }
  800. _, err := hex.DecodeString(cfg.TrustHash)
  801. if err != nil {
  802. return fmt.Errorf("invalid trusted-hash: %w", err)
  803. }
  804. if cfg.ChunkRequestTimeout < 5*time.Second {
  805. return errors.New("chunk-request-timeout must be at least 5 seconds")
  806. }
  807. if cfg.Fetchers <= 0 {
  808. return errors.New("fetchers is required")
  809. }
  810. }
  811. return nil
  812. }
  813. //-----------------------------------------------------------------------------
  814. // FastSyncConfig
  815. // FastSyncConfig defines the configuration for the Tendermint fast sync service
  816. type FastSyncConfig struct {
  817. Version string `mapstructure:"version"`
  818. }
  819. // DefaultFastSyncConfig returns a default configuration for the fast sync service
  820. func DefaultFastSyncConfig() *FastSyncConfig {
  821. return &FastSyncConfig{
  822. Version: BlockchainV0,
  823. }
  824. }
  825. // TestFastSyncConfig returns a default configuration for the fast sync.
  826. func TestFastSyncConfig() *FastSyncConfig {
  827. return DefaultFastSyncConfig()
  828. }
  829. // ValidateBasic performs basic validation.
  830. func (cfg *FastSyncConfig) ValidateBasic() error {
  831. switch cfg.Version {
  832. case BlockchainV0:
  833. return nil
  834. case BlockchainV2:
  835. return errors.New("fastsync version v2 is no longer supported. Please use v0")
  836. default:
  837. return fmt.Errorf("unknown fastsync version %s", cfg.Version)
  838. }
  839. }
  840. //-----------------------------------------------------------------------------
  841. // ConsensusConfig
  842. // ConsensusConfig defines the configuration for the Tendermint consensus service,
  843. // including timeouts and details about the WAL and the block structure.
  844. type ConsensusConfig struct {
  845. RootDir string `mapstructure:"home"`
  846. WalPath string `mapstructure:"wal-file"`
  847. walFile string // overrides WalPath if set
  848. // TODO: remove timeout configs, these should be global not local
  849. // How long we wait for a proposal block before prevoting nil
  850. TimeoutPropose time.Duration `mapstructure:"timeout-propose"`
  851. // How much timeout-propose increases with each round
  852. TimeoutProposeDelta time.Duration `mapstructure:"timeout-propose-delta"`
  853. // How long we wait after receiving +2/3 prevotes for “anything” (ie. not a single block or nil)
  854. TimeoutPrevote time.Duration `mapstructure:"timeout-prevote"`
  855. // How much the timeout-prevote increases with each round
  856. TimeoutPrevoteDelta time.Duration `mapstructure:"timeout-prevote-delta"`
  857. // How long we wait after receiving +2/3 precommits for “anything” (ie. not a single block or nil)
  858. TimeoutPrecommit time.Duration `mapstructure:"timeout-precommit"`
  859. // How much the timeout-precommit increases with each round
  860. TimeoutPrecommitDelta time.Duration `mapstructure:"timeout-precommit-delta"`
  861. // How long we wait after committing a block, before starting on the new
  862. // height (this gives us a chance to receive some more precommits, even
  863. // though we already have +2/3).
  864. TimeoutCommit time.Duration `mapstructure:"timeout-commit"`
  865. // Make progress as soon as we have all the precommits (as if TimeoutCommit = 0)
  866. SkipTimeoutCommit bool `mapstructure:"skip-timeout-commit"`
  867. // EmptyBlocks mode and possible interval between empty blocks
  868. CreateEmptyBlocks bool `mapstructure:"create-empty-blocks"`
  869. CreateEmptyBlocksInterval time.Duration `mapstructure:"create-empty-blocks-interval"`
  870. // Reactor sleep duration parameters
  871. PeerGossipSleepDuration time.Duration `mapstructure:"peer-gossip-sleep-duration"`
  872. PeerQueryMaj23SleepDuration time.Duration `mapstructure:"peer-query-maj23-sleep-duration"`
  873. DoubleSignCheckHeight int64 `mapstructure:"double-sign-check-height"`
  874. }
  875. // DefaultConsensusConfig returns a default configuration for the consensus service
  876. func DefaultConsensusConfig() *ConsensusConfig {
  877. return &ConsensusConfig{
  878. WalPath: filepath.Join(defaultDataDir, "cs.wal", "wal"),
  879. TimeoutPropose: 3000 * time.Millisecond,
  880. TimeoutProposeDelta: 500 * time.Millisecond,
  881. TimeoutPrevote: 1000 * time.Millisecond,
  882. TimeoutPrevoteDelta: 500 * time.Millisecond,
  883. TimeoutPrecommit: 1000 * time.Millisecond,
  884. TimeoutPrecommitDelta: 500 * time.Millisecond,
  885. TimeoutCommit: 1000 * time.Millisecond,
  886. SkipTimeoutCommit: false,
  887. CreateEmptyBlocks: true,
  888. CreateEmptyBlocksInterval: 0 * time.Second,
  889. PeerGossipSleepDuration: 100 * time.Millisecond,
  890. PeerQueryMaj23SleepDuration: 2000 * time.Millisecond,
  891. DoubleSignCheckHeight: int64(0),
  892. }
  893. }
  894. // TestConsensusConfig returns a configuration for testing the consensus service
  895. func TestConsensusConfig() *ConsensusConfig {
  896. cfg := DefaultConsensusConfig()
  897. cfg.TimeoutPropose = 40 * time.Millisecond
  898. cfg.TimeoutProposeDelta = 1 * time.Millisecond
  899. cfg.TimeoutPrevote = 10 * time.Millisecond
  900. cfg.TimeoutPrevoteDelta = 1 * time.Millisecond
  901. cfg.TimeoutPrecommit = 10 * time.Millisecond
  902. cfg.TimeoutPrecommitDelta = 1 * time.Millisecond
  903. cfg.TimeoutCommit = 10 * time.Millisecond
  904. cfg.SkipTimeoutCommit = true
  905. cfg.PeerGossipSleepDuration = 5 * time.Millisecond
  906. cfg.PeerQueryMaj23SleepDuration = 250 * time.Millisecond
  907. cfg.DoubleSignCheckHeight = int64(0)
  908. return cfg
  909. }
  910. // WaitForTxs returns true if the consensus should wait for transactions before entering the propose step
  911. func (cfg *ConsensusConfig) WaitForTxs() bool {
  912. return !cfg.CreateEmptyBlocks || cfg.CreateEmptyBlocksInterval > 0
  913. }
  914. // Propose returns the amount of time to wait for a proposal
  915. func (cfg *ConsensusConfig) Propose(round int32) time.Duration {
  916. return time.Duration(
  917. cfg.TimeoutPropose.Nanoseconds()+cfg.TimeoutProposeDelta.Nanoseconds()*int64(round),
  918. ) * time.Nanosecond
  919. }
  920. // Prevote returns the amount of time to wait for straggler votes after receiving any +2/3 prevotes
  921. func (cfg *ConsensusConfig) Prevote(round int32) time.Duration {
  922. return time.Duration(
  923. cfg.TimeoutPrevote.Nanoseconds()+cfg.TimeoutPrevoteDelta.Nanoseconds()*int64(round),
  924. ) * time.Nanosecond
  925. }
  926. // Precommit returns the amount of time to wait for straggler votes after receiving any +2/3 precommits
  927. func (cfg *ConsensusConfig) Precommit(round int32) time.Duration {
  928. return time.Duration(
  929. cfg.TimeoutPrecommit.Nanoseconds()+cfg.TimeoutPrecommitDelta.Nanoseconds()*int64(round),
  930. ) * time.Nanosecond
  931. }
  932. // Commit returns the amount of time to wait for straggler votes after receiving +2/3 precommits
  933. // for a single block (ie. a commit).
  934. func (cfg *ConsensusConfig) Commit(t time.Time) time.Time {
  935. return t.Add(cfg.TimeoutCommit)
  936. }
  937. // WalFile returns the full path to the write-ahead log file
  938. func (cfg *ConsensusConfig) WalFile() string {
  939. if cfg.walFile != "" {
  940. return cfg.walFile
  941. }
  942. return rootify(cfg.WalPath, cfg.RootDir)
  943. }
  944. // SetWalFile sets the path to the write-ahead log file
  945. func (cfg *ConsensusConfig) SetWalFile(walFile string) {
  946. cfg.walFile = walFile
  947. }
  948. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  949. // returns an error if any check fails.
  950. func (cfg *ConsensusConfig) ValidateBasic() error {
  951. if cfg.TimeoutPropose < 0 {
  952. return errors.New("timeout-propose can't be negative")
  953. }
  954. if cfg.TimeoutProposeDelta < 0 {
  955. return errors.New("timeout-propose-delta can't be negative")
  956. }
  957. if cfg.TimeoutPrevote < 0 {
  958. return errors.New("timeout-prevote can't be negative")
  959. }
  960. if cfg.TimeoutPrevoteDelta < 0 {
  961. return errors.New("timeout-prevote-delta can't be negative")
  962. }
  963. if cfg.TimeoutPrecommit < 0 {
  964. return errors.New("timeout-precommit can't be negative")
  965. }
  966. if cfg.TimeoutPrecommitDelta < 0 {
  967. return errors.New("timeout-precommit-delta can't be negative")
  968. }
  969. if cfg.TimeoutCommit < 0 {
  970. return errors.New("timeout-commit can't be negative")
  971. }
  972. if cfg.CreateEmptyBlocksInterval < 0 {
  973. return errors.New("create-empty-blocks-interval can't be negative")
  974. }
  975. if cfg.PeerGossipSleepDuration < 0 {
  976. return errors.New("peer-gossip-sleep-duration can't be negative")
  977. }
  978. if cfg.PeerQueryMaj23SleepDuration < 0 {
  979. return errors.New("peer-query-maj23-sleep-duration can't be negative")
  980. }
  981. if cfg.DoubleSignCheckHeight < 0 {
  982. return errors.New("double-sign-check-height can't be negative")
  983. }
  984. return nil
  985. }
  986. //-----------------------------------------------------------------------------
  987. // TxIndexConfig
  988. // Remember that Event has the following structure:
  989. // type: [
  990. // key: value,
  991. // ...
  992. // ]
  993. //
  994. // CompositeKeys are constructed by `type.key`
  995. // TxIndexConfig defines the configuration for the transaction indexer,
  996. // including composite keys to index.
  997. type TxIndexConfig struct {
  998. // The backend database list to back the indexer.
  999. // If list contains `null`, meaning no indexer service will be used.
  1000. //
  1001. // Options:
  1002. // 1) "null" - no indexer services.
  1003. // 2) "kv" (default) - the simplest possible indexer,
  1004. // backed by key-value storage (defaults to levelDB; see DBBackend).
  1005. // 3) "psql" - the indexer services backed by PostgreSQL.
  1006. Indexer []string `mapstructure:"indexer"`
  1007. // The PostgreSQL connection configuration, the connection format:
  1008. // postgresql://<user>:<password>@<host>:<port>/<db>?<opts>
  1009. PsqlConn string `mapstructure:"psql-conn"`
  1010. }
  1011. // DefaultTxIndexConfig returns a default configuration for the transaction indexer.
  1012. func DefaultTxIndexConfig() *TxIndexConfig {
  1013. return &TxIndexConfig{
  1014. Indexer: []string{"kv"},
  1015. }
  1016. }
  1017. // TestTxIndexConfig returns a default configuration for the transaction indexer.
  1018. func TestTxIndexConfig() *TxIndexConfig {
  1019. return DefaultTxIndexConfig()
  1020. }
  1021. //-----------------------------------------------------------------------------
  1022. // InstrumentationConfig
  1023. // InstrumentationConfig defines the configuration for metrics reporting.
  1024. type InstrumentationConfig struct {
  1025. // When true, Prometheus metrics are served under /metrics on
  1026. // PrometheusListenAddr.
  1027. // Check out the documentation for the list of available metrics.
  1028. Prometheus bool `mapstructure:"prometheus"`
  1029. // Address to listen for Prometheus collector(s) connections.
  1030. PrometheusListenAddr string `mapstructure:"prometheus-listen-addr"`
  1031. // Maximum number of simultaneous connections.
  1032. // If you want to accept a larger number than the default, make sure
  1033. // you increase your OS limits.
  1034. // 0 - unlimited.
  1035. MaxOpenConnections int `mapstructure:"max-open-connections"`
  1036. // Instrumentation namespace.
  1037. Namespace string `mapstructure:"namespace"`
  1038. }
  1039. // DefaultInstrumentationConfig returns a default configuration for metrics
  1040. // reporting.
  1041. func DefaultInstrumentationConfig() *InstrumentationConfig {
  1042. return &InstrumentationConfig{
  1043. Prometheus: false,
  1044. PrometheusListenAddr: ":26660",
  1045. MaxOpenConnections: 3,
  1046. Namespace: "tendermint",
  1047. }
  1048. }
  1049. // TestInstrumentationConfig returns a default configuration for metrics
  1050. // reporting.
  1051. func TestInstrumentationConfig() *InstrumentationConfig {
  1052. return DefaultInstrumentationConfig()
  1053. }
  1054. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  1055. // returns an error if any check fails.
  1056. func (cfg *InstrumentationConfig) ValidateBasic() error {
  1057. if cfg.MaxOpenConnections < 0 {
  1058. return errors.New("max-open-connections can't be negative")
  1059. }
  1060. return nil
  1061. }
  1062. //-----------------------------------------------------------------------------
  1063. // Utils
  1064. // helper function to make config creation independent of root dir
  1065. func rootify(path, root string) string {
  1066. if filepath.IsAbs(path) {
  1067. return path
  1068. }
  1069. return filepath.Join(root, path)
  1070. }
  1071. //-----------------------------------------------------------------------------
  1072. // Moniker
  1073. var defaultMoniker = getDefaultMoniker()
  1074. // getDefaultMoniker returns a default moniker, which is the host name. If runtime
  1075. // fails to get the host name, "anonymous" will be returned.
  1076. func getDefaultMoniker() string {
  1077. moniker, err := os.Hostname()
  1078. if err != nil {
  1079. moniker = "anonymous"
  1080. }
  1081. return moniker
  1082. }