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.

1073 lines
37 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
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
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
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. "net/http"
  7. "os"
  8. "path/filepath"
  9. "time"
  10. )
  11. const (
  12. // FuzzModeDrop is a mode in which we randomly drop reads/writes, connections or sleep
  13. FuzzModeDrop = iota
  14. // FuzzModeDelay is a mode in which we randomly sleep
  15. FuzzModeDelay
  16. // LogFormatPlain is a format for colored text
  17. LogFormatPlain = "plain"
  18. // LogFormatJSON is a format for json output
  19. LogFormatJSON = "json"
  20. )
  21. // NOTE: Most of the structs & relevant comments + the
  22. // default configuration options were used to manually
  23. // generate the config.toml. Please reflect any changes
  24. // made here in the defaultConfigTemplate constant in
  25. // config/toml.go
  26. // NOTE: libs/cli must know to look in the config dir!
  27. var (
  28. DefaultTendermintDir = ".tendermint"
  29. defaultConfigDir = "config"
  30. defaultDataDir = "data"
  31. defaultConfigFileName = "config.toml"
  32. defaultGenesisJSONName = "genesis.json"
  33. defaultPrivValKeyName = "priv_validator_key.json"
  34. defaultPrivValStateName = "priv_validator_state.json"
  35. defaultNodeKeyName = "node_key.json"
  36. defaultAddrBookName = "addrbook.json"
  37. defaultConfigFilePath = filepath.Join(defaultConfigDir, defaultConfigFileName)
  38. defaultGenesisJSONPath = filepath.Join(defaultConfigDir, defaultGenesisJSONName)
  39. defaultPrivValKeyPath = filepath.Join(defaultConfigDir, defaultPrivValKeyName)
  40. defaultPrivValStatePath = filepath.Join(defaultDataDir, defaultPrivValStateName)
  41. defaultNodeKeyPath = filepath.Join(defaultConfigDir, defaultNodeKeyName)
  42. defaultAddrBookPath = filepath.Join(defaultConfigDir, defaultAddrBookName)
  43. )
  44. // Config defines the top level configuration for a Tendermint node
  45. type Config struct {
  46. // Top level options use an anonymous struct
  47. BaseConfig `mapstructure:",squash"`
  48. // Options for services
  49. RPC *RPCConfig `mapstructure:"rpc"`
  50. P2P *P2PConfig `mapstructure:"p2p"`
  51. Mempool *MempoolConfig `mapstructure:"mempool"`
  52. StateSync *StateSyncConfig `mapstructure:"statesync"`
  53. FastSync *FastSyncConfig `mapstructure:"fastsync"`
  54. Consensus *ConsensusConfig `mapstructure:"consensus"`
  55. TxIndex *TxIndexConfig `mapstructure:"tx_index"`
  56. Instrumentation *InstrumentationConfig `mapstructure:"instrumentation"`
  57. }
  58. // DefaultConfig returns a default configuration for a Tendermint node
  59. func DefaultConfig() *Config {
  60. return &Config{
  61. BaseConfig: DefaultBaseConfig(),
  62. RPC: DefaultRPCConfig(),
  63. P2P: DefaultP2PConfig(),
  64. Mempool: DefaultMempoolConfig(),
  65. StateSync: DefaultStateSyncConfig(),
  66. FastSync: DefaultFastSyncConfig(),
  67. Consensus: DefaultConsensusConfig(),
  68. TxIndex: DefaultTxIndexConfig(),
  69. Instrumentation: DefaultInstrumentationConfig(),
  70. }
  71. }
  72. // TestConfig returns a configuration that can be used for testing
  73. func TestConfig() *Config {
  74. return &Config{
  75. BaseConfig: TestBaseConfig(),
  76. RPC: TestRPCConfig(),
  77. P2P: TestP2PConfig(),
  78. Mempool: TestMempoolConfig(),
  79. StateSync: TestStateSyncConfig(),
  80. FastSync: TestFastSyncConfig(),
  81. Consensus: TestConsensusConfig(),
  82. TxIndex: TestTxIndexConfig(),
  83. Instrumentation: TestInstrumentationConfig(),
  84. }
  85. }
  86. // SetRoot sets the RootDir for all Config structs
  87. func (cfg *Config) SetRoot(root string) *Config {
  88. cfg.BaseConfig.RootDir = root
  89. cfg.RPC.RootDir = root
  90. cfg.P2P.RootDir = root
  91. cfg.Mempool.RootDir = root
  92. cfg.Consensus.RootDir = root
  93. return cfg
  94. }
  95. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  96. // returns an error if any check fails.
  97. func (cfg *Config) ValidateBasic() error {
  98. if err := cfg.BaseConfig.ValidateBasic(); err != nil {
  99. return err
  100. }
  101. if err := cfg.RPC.ValidateBasic(); err != nil {
  102. return fmt.Errorf("error in [rpc] section: %w", err)
  103. }
  104. if err := cfg.P2P.ValidateBasic(); err != nil {
  105. return fmt.Errorf("error in [p2p] section: %w", err)
  106. }
  107. if err := cfg.Mempool.ValidateBasic(); err != nil {
  108. return fmt.Errorf("error in [mempool] section: %w", err)
  109. }
  110. if err := cfg.StateSync.ValidateBasic(); err != nil {
  111. return fmt.Errorf("error in [statesync] section: %w", err)
  112. }
  113. if err := cfg.FastSync.ValidateBasic(); err != nil {
  114. return fmt.Errorf("error in [fastsync] section: %w", err)
  115. }
  116. if err := cfg.Consensus.ValidateBasic(); err != nil {
  117. return fmt.Errorf("error in [consensus] section: %w", err)
  118. }
  119. if err := cfg.Instrumentation.ValidateBasic(); err != nil {
  120. return fmt.Errorf("error in [instrumentation] section: %w", err)
  121. }
  122. return nil
  123. }
  124. //-----------------------------------------------------------------------------
  125. // BaseConfig
  126. // BaseConfig defines the base configuration for a Tendermint node
  127. type BaseConfig struct { //nolint: maligned
  128. // chainID is unexposed and immutable but here for convenience
  129. chainID string
  130. // The root directory for all data.
  131. // This should be set in viper so it can unmarshal into this struct
  132. RootDir string `mapstructure:"home"`
  133. // TCP or UNIX socket address of the ABCI application,
  134. // or the name of an ABCI application compiled in with the Tendermint binary
  135. ProxyApp string `mapstructure:"proxy_app"`
  136. // A custom human readable name for this node
  137. Moniker string `mapstructure:"moniker"`
  138. // If this node is many blocks behind the tip of the chain, FastSync
  139. // allows them to catchup quickly by downloading blocks in parallel
  140. // and verifying their commits
  141. FastSyncMode bool `mapstructure:"fast_sync"`
  142. // Database backend: goleveldb | cleveldb | boltdb | rocksdb
  143. // * goleveldb (github.com/syndtr/goleveldb - most popular implementation)
  144. // - pure go
  145. // - stable
  146. // * cleveldb (uses levigo wrapper)
  147. // - fast
  148. // - requires gcc
  149. // - use cleveldb build tag (go build -tags cleveldb)
  150. // * boltdb (uses etcd's fork of bolt - github.com/etcd-io/bbolt)
  151. // - EXPERIMENTAL
  152. // - may be faster is some use-cases (random reads - indexer)
  153. // - use boltdb build tag (go build -tags boltdb)
  154. // * rocksdb (uses github.com/tecbot/gorocksdb)
  155. // - EXPERIMENTAL
  156. // - requires gcc
  157. // - use rocksdb build tag (go build -tags rocksdb)
  158. DBBackend string `mapstructure:"db_backend"`
  159. // Database directory
  160. DBPath string `mapstructure:"db_dir"`
  161. // Output level for logging
  162. LogLevel string `mapstructure:"log_level"`
  163. // Output format: 'plain' (colored text) or 'json'
  164. LogFormat string `mapstructure:"log_format"`
  165. // Path to the JSON file containing the initial validator set and other meta data
  166. Genesis string `mapstructure:"genesis_file"`
  167. // Path to the JSON file containing the private key to use as a validator in the consensus protocol
  168. PrivValidatorKey string `mapstructure:"priv_validator_key_file"`
  169. // Path to the JSON file containing the last sign state of a validator
  170. PrivValidatorState string `mapstructure:"priv_validator_state_file"`
  171. // TCP or UNIX socket address for Tendermint to listen on for
  172. // connections from an external PrivValidator process
  173. PrivValidatorListenAddr string `mapstructure:"priv_validator_laddr"`
  174. // A JSON file containing the private key to use for p2p authenticated encryption
  175. NodeKey string `mapstructure:"node_key_file"`
  176. // Mechanism to connect to the ABCI application: socket | grpc
  177. ABCI string `mapstructure:"abci"`
  178. // TCP or UNIX socket address for the profiling server to listen on
  179. ProfListenAddress string `mapstructure:"prof_laddr"`
  180. // If true, query the ABCI app on connecting to a new peer
  181. // so the app can decide if we should keep the connection or not
  182. FilterPeers bool `mapstructure:"filter_peers"` // false
  183. }
  184. // DefaultBaseConfig returns a default base configuration for a Tendermint node
  185. func DefaultBaseConfig() BaseConfig {
  186. return BaseConfig{
  187. Genesis: defaultGenesisJSONPath,
  188. PrivValidatorKey: defaultPrivValKeyPath,
  189. PrivValidatorState: defaultPrivValStatePath,
  190. NodeKey: defaultNodeKeyPath,
  191. Moniker: defaultMoniker,
  192. ProxyApp: "tcp://127.0.0.1:26658",
  193. ABCI: "socket",
  194. LogLevel: DefaultPackageLogLevels(),
  195. LogFormat: LogFormatPlain,
  196. ProfListenAddress: "",
  197. FastSyncMode: true,
  198. FilterPeers: false,
  199. DBBackend: "goleveldb",
  200. DBPath: "data",
  201. }
  202. }
  203. // TestBaseConfig returns a base configuration for testing a Tendermint node
  204. func TestBaseConfig() BaseConfig {
  205. cfg := DefaultBaseConfig()
  206. cfg.chainID = "tendermint_test"
  207. cfg.ProxyApp = "kvstore"
  208. cfg.FastSyncMode = false
  209. cfg.DBBackend = "memdb"
  210. return cfg
  211. }
  212. func (cfg BaseConfig) ChainID() string {
  213. return cfg.chainID
  214. }
  215. // GenesisFile returns the full path to the genesis.json file
  216. func (cfg BaseConfig) GenesisFile() string {
  217. return rootify(cfg.Genesis, cfg.RootDir)
  218. }
  219. // PrivValidatorKeyFile returns the full path to the priv_validator_key.json file
  220. func (cfg BaseConfig) PrivValidatorKeyFile() string {
  221. return rootify(cfg.PrivValidatorKey, cfg.RootDir)
  222. }
  223. // PrivValidatorFile returns the full path to the priv_validator_state.json file
  224. func (cfg BaseConfig) PrivValidatorStateFile() string {
  225. return rootify(cfg.PrivValidatorState, cfg.RootDir)
  226. }
  227. // NodeKeyFile returns the full path to the node_key.json file
  228. func (cfg BaseConfig) NodeKeyFile() string {
  229. return rootify(cfg.NodeKey, cfg.RootDir)
  230. }
  231. // DBDir returns the full path to the database directory
  232. func (cfg BaseConfig) DBDir() string {
  233. return rootify(cfg.DBPath, cfg.RootDir)
  234. }
  235. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  236. // returns an error if any check fails.
  237. func (cfg BaseConfig) ValidateBasic() error {
  238. switch cfg.LogFormat {
  239. case LogFormatPlain, LogFormatJSON:
  240. default:
  241. return errors.New("unknown log_format (must be 'plain' or 'json')")
  242. }
  243. return nil
  244. }
  245. // DefaultLogLevel returns a default log level of "error"
  246. func DefaultLogLevel() string {
  247. return "error"
  248. }
  249. // DefaultPackageLogLevels returns a default log level setting so all packages
  250. // log at "error", while the `state` and `main` packages log at "info"
  251. func DefaultPackageLogLevels() string {
  252. return fmt.Sprintf("main:info,state:info,statesync:info,*:%s", DefaultLogLevel())
  253. }
  254. //-----------------------------------------------------------------------------
  255. // RPCConfig
  256. // RPCConfig defines the configuration options for the Tendermint RPC server
  257. type RPCConfig struct {
  258. RootDir string `mapstructure:"home"`
  259. // TCP or UNIX socket address for the RPC server to listen on
  260. ListenAddress string `mapstructure:"laddr"`
  261. // A list of origins a cross-domain request can be executed from.
  262. // If the special '*' value is present in the list, all origins will be allowed.
  263. // An origin may contain a wildcard (*) to replace 0 or more characters (i.e.: http://*.domain.com).
  264. // Only one wildcard can be used per origin.
  265. CORSAllowedOrigins []string `mapstructure:"cors_allowed_origins"`
  266. // A list of methods the client is allowed to use with cross-domain requests.
  267. CORSAllowedMethods []string `mapstructure:"cors_allowed_methods"`
  268. // A list of non simple headers the client is allowed to use with cross-domain requests.
  269. CORSAllowedHeaders []string `mapstructure:"cors_allowed_headers"`
  270. // TCP or UNIX socket address for the gRPC server to listen on
  271. // NOTE: This server only supports /broadcast_tx_commit
  272. GRPCListenAddress string `mapstructure:"grpc_laddr"`
  273. // Maximum number of simultaneous connections.
  274. // Does not include RPC (HTTP&WebSocket) connections. See max_open_connections
  275. // If you want to accept a larger number than the default, make sure
  276. // you increase your OS limits.
  277. // 0 - unlimited.
  278. GRPCMaxOpenConnections int `mapstructure:"grpc_max_open_connections"`
  279. // Activate unsafe RPC commands like /dial_persistent_peers and /unsafe_flush_mempool
  280. Unsafe bool `mapstructure:"unsafe"`
  281. // Maximum number of simultaneous connections (including WebSocket).
  282. // Does not include gRPC connections. See grpc_max_open_connections
  283. // If you want to accept a larger number than the default, make sure
  284. // you increase your OS limits.
  285. // 0 - unlimited.
  286. // Should be < {ulimit -Sn} - {MaxNumInboundPeers} - {MaxNumOutboundPeers} - {N of wal, db and other open files}
  287. // 1024 - 40 - 10 - 50 = 924 = ~900
  288. MaxOpenConnections int `mapstructure:"max_open_connections"`
  289. // Maximum number of unique clientIDs that can /subscribe
  290. // If you're using /broadcast_tx_commit, set to the estimated maximum number
  291. // of broadcast_tx_commit calls per block.
  292. MaxSubscriptionClients int `mapstructure:"max_subscription_clients"`
  293. // Maximum number of unique queries a given client can /subscribe to
  294. // If you're using GRPC (or Local RPC client) and /broadcast_tx_commit, set
  295. // to the estimated maximum number of broadcast_tx_commit calls per block.
  296. MaxSubscriptionsPerClient int `mapstructure:"max_subscriptions_per_client"`
  297. // How long to wait for a tx to be committed during /broadcast_tx_commit
  298. // WARNING: Using a value larger than 10s will result in increasing the
  299. // global HTTP write timeout, which applies to all connections and endpoints.
  300. // See https://github.com/tendermint/tendermint/issues/3435
  301. TimeoutBroadcastTxCommit time.Duration `mapstructure:"timeout_broadcast_tx_commit"`
  302. // Maximum size of request body, in bytes
  303. MaxBodyBytes int64 `mapstructure:"max_body_bytes"`
  304. // Maximum size of request header, in bytes
  305. MaxHeaderBytes int `mapstructure:"max_header_bytes"`
  306. // The path to a file containing certificate that is used to create the HTTPS server.
  307. // Migth be either absolute path or path related to tendermint's config directory.
  308. //
  309. // If the certificate is signed by a certificate authority,
  310. // the certFile should be the concatenation of the server's certificate, any intermediates,
  311. // and the CA's certificate.
  312. //
  313. // NOTE: both tls_cert_file and tls_key_file must be present for Tendermint to create HTTPS server.
  314. // Otherwise, HTTP server is run.
  315. TLSCertFile string `mapstructure:"tls_cert_file"`
  316. // The path to a file containing matching private key that is used to create the HTTPS server.
  317. // Migth be either absolute path or path related to tendermint's config directory.
  318. //
  319. // NOTE: both tls_cert_file and tls_key_file must be present for Tendermint to create HTTPS server.
  320. // Otherwise, HTTP server is run.
  321. TLSKeyFile string `mapstructure:"tls_key_file"`
  322. }
  323. // DefaultRPCConfig returns a default configuration for the RPC server
  324. func DefaultRPCConfig() *RPCConfig {
  325. return &RPCConfig{
  326. ListenAddress: "tcp://127.0.0.1:26657",
  327. CORSAllowedOrigins: []string{},
  328. CORSAllowedMethods: []string{http.MethodHead, http.MethodGet, http.MethodPost},
  329. CORSAllowedHeaders: []string{"Origin", "Accept", "Content-Type", "X-Requested-With", "X-Server-Time"},
  330. GRPCListenAddress: "",
  331. GRPCMaxOpenConnections: 900,
  332. Unsafe: false,
  333. MaxOpenConnections: 900,
  334. MaxSubscriptionClients: 100,
  335. MaxSubscriptionsPerClient: 5,
  336. TimeoutBroadcastTxCommit: 10 * time.Second,
  337. MaxBodyBytes: int64(1000000), // 1MB
  338. MaxHeaderBytes: 1 << 20, // same as the net/http default
  339. TLSCertFile: "",
  340. TLSKeyFile: "",
  341. }
  342. }
  343. // TestRPCConfig returns a configuration for testing the RPC server
  344. func TestRPCConfig() *RPCConfig {
  345. cfg := DefaultRPCConfig()
  346. cfg.ListenAddress = "tcp://127.0.0.1:36657"
  347. cfg.GRPCListenAddress = "tcp://127.0.0.1:36658"
  348. cfg.Unsafe = true
  349. return cfg
  350. }
  351. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  352. // returns an error if any check fails.
  353. func (cfg *RPCConfig) ValidateBasic() error {
  354. if cfg.GRPCMaxOpenConnections < 0 {
  355. return errors.New("grpc_max_open_connections can't be negative")
  356. }
  357. if cfg.MaxOpenConnections < 0 {
  358. return errors.New("max_open_connections can't be negative")
  359. }
  360. if cfg.MaxSubscriptionClients < 0 {
  361. return errors.New("max_subscription_clients can't be negative")
  362. }
  363. if cfg.MaxSubscriptionsPerClient < 0 {
  364. return errors.New("max_subscriptions_per_client can't be negative")
  365. }
  366. if cfg.TimeoutBroadcastTxCommit < 0 {
  367. return errors.New("timeout_broadcast_tx_commit can't be negative")
  368. }
  369. if cfg.MaxBodyBytes < 0 {
  370. return errors.New("max_body_bytes can't be negative")
  371. }
  372. if cfg.MaxHeaderBytes < 0 {
  373. return errors.New("max_header_bytes can't be negative")
  374. }
  375. return nil
  376. }
  377. // IsCorsEnabled returns true if cross-origin resource sharing is enabled.
  378. func (cfg *RPCConfig) IsCorsEnabled() bool {
  379. return len(cfg.CORSAllowedOrigins) != 0
  380. }
  381. func (cfg RPCConfig) KeyFile() string {
  382. path := cfg.TLSKeyFile
  383. if filepath.IsAbs(path) {
  384. return path
  385. }
  386. return rootify(filepath.Join(defaultConfigDir, path), cfg.RootDir)
  387. }
  388. func (cfg RPCConfig) CertFile() string {
  389. path := cfg.TLSCertFile
  390. if filepath.IsAbs(path) {
  391. return path
  392. }
  393. return rootify(filepath.Join(defaultConfigDir, path), cfg.RootDir)
  394. }
  395. func (cfg RPCConfig) IsTLSEnabled() bool {
  396. return cfg.TLSCertFile != "" && cfg.TLSKeyFile != ""
  397. }
  398. //-----------------------------------------------------------------------------
  399. // P2PConfig
  400. // P2PConfig defines the configuration options for the Tendermint peer-to-peer networking layer
  401. type P2PConfig struct { //nolint: maligned
  402. RootDir string `mapstructure:"home"`
  403. // Address to listen for incoming connections
  404. ListenAddress string `mapstructure:"laddr"`
  405. // Address to advertise to peers for them to dial
  406. ExternalAddress string `mapstructure:"external_address"`
  407. // Comma separated list of seed nodes to connect to
  408. // We only use these if we can’t connect to peers in the addrbook
  409. Seeds string `mapstructure:"seeds"`
  410. // Comma separated list of nodes to keep persistent connections to
  411. PersistentPeers string `mapstructure:"persistent_peers"`
  412. // UPNP port forwarding
  413. UPNP bool `mapstructure:"upnp"`
  414. // Path to address book
  415. AddrBook string `mapstructure:"addr_book_file"`
  416. // Set true for strict address routability rules
  417. // Set false for private or local networks
  418. AddrBookStrict bool `mapstructure:"addr_book_strict"`
  419. // Maximum number of inbound peers
  420. MaxNumInboundPeers int `mapstructure:"max_num_inbound_peers"`
  421. // Maximum number of outbound peers to connect to, excluding persistent peers
  422. MaxNumOutboundPeers int `mapstructure:"max_num_outbound_peers"`
  423. // List of node IDs, to which a connection will be (re)established ignoring any existing limits
  424. UnconditionalPeerIDs string `mapstructure:"unconditional_peer_ids"`
  425. // Maximum pause when redialing a persistent peer (if zero, exponential backoff is used)
  426. PersistentPeersMaxDialPeriod time.Duration `mapstructure:"persistent_peers_max_dial_period"`
  427. // Time to wait before flushing messages out on the connection
  428. FlushThrottleTimeout time.Duration `mapstructure:"flush_throttle_timeout"`
  429. // Maximum size of a message packet payload, in bytes
  430. MaxPacketMsgPayloadSize int `mapstructure:"max_packet_msg_payload_size"`
  431. // Rate at which packets can be sent, in bytes/second
  432. SendRate int64 `mapstructure:"send_rate"`
  433. // Rate at which packets can be received, in bytes/second
  434. RecvRate int64 `mapstructure:"recv_rate"`
  435. // Set true to enable the peer-exchange reactor
  436. PexReactor bool `mapstructure:"pex"`
  437. // Seed mode, in which node constantly crawls the network and looks for
  438. // peers. If another node asks it for addresses, it responds and disconnects.
  439. //
  440. // Does not work if the peer-exchange reactor is disabled.
  441. SeedMode bool `mapstructure:"seed_mode"`
  442. // Comma separated list of peer IDs to keep private (will not be gossiped to
  443. // other peers)
  444. PrivatePeerIDs string `mapstructure:"private_peer_ids"`
  445. // Toggle to disable guard against peers connecting from the same ip.
  446. AllowDuplicateIP bool `mapstructure:"allow_duplicate_ip"`
  447. // Peer connection configuration.
  448. HandshakeTimeout time.Duration `mapstructure:"handshake_timeout"`
  449. DialTimeout time.Duration `mapstructure:"dial_timeout"`
  450. // Testing params.
  451. // Force dial to fail
  452. TestDialFail bool `mapstructure:"test_dial_fail"`
  453. // FUzz connection
  454. TestFuzz bool `mapstructure:"test_fuzz"`
  455. TestFuzzConfig *FuzzConnConfig `mapstructure:"test_fuzz_config"`
  456. }
  457. // DefaultP2PConfig returns a default configuration for the peer-to-peer layer
  458. func DefaultP2PConfig() *P2PConfig {
  459. return &P2PConfig{
  460. ListenAddress: "tcp://0.0.0.0:26656",
  461. ExternalAddress: "",
  462. UPNP: false,
  463. AddrBook: defaultAddrBookPath,
  464. AddrBookStrict: true,
  465. MaxNumInboundPeers: 40,
  466. MaxNumOutboundPeers: 10,
  467. PersistentPeersMaxDialPeriod: 0 * time.Second,
  468. FlushThrottleTimeout: 100 * time.Millisecond,
  469. MaxPacketMsgPayloadSize: 1024, // 1 kB
  470. SendRate: 5120000, // 5 mB/s
  471. RecvRate: 5120000, // 5 mB/s
  472. PexReactor: true,
  473. SeedMode: false,
  474. AllowDuplicateIP: false,
  475. HandshakeTimeout: 20 * time.Second,
  476. DialTimeout: 3 * time.Second,
  477. TestDialFail: false,
  478. TestFuzz: false,
  479. TestFuzzConfig: DefaultFuzzConnConfig(),
  480. }
  481. }
  482. // TestP2PConfig returns a configuration for testing the peer-to-peer layer
  483. func TestP2PConfig() *P2PConfig {
  484. cfg := DefaultP2PConfig()
  485. cfg.ListenAddress = "tcp://127.0.0.1:36656"
  486. cfg.FlushThrottleTimeout = 10 * time.Millisecond
  487. cfg.AllowDuplicateIP = true
  488. return cfg
  489. }
  490. // AddrBookFile returns the full path to the address book
  491. func (cfg *P2PConfig) AddrBookFile() string {
  492. return rootify(cfg.AddrBook, cfg.RootDir)
  493. }
  494. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  495. // returns an error if any check fails.
  496. func (cfg *P2PConfig) ValidateBasic() error {
  497. if cfg.MaxNumInboundPeers < 0 {
  498. return errors.New("max_num_inbound_peers can't be negative")
  499. }
  500. if cfg.MaxNumOutboundPeers < 0 {
  501. return errors.New("max_num_outbound_peers can't be negative")
  502. }
  503. if cfg.FlushThrottleTimeout < 0 {
  504. return errors.New("flush_throttle_timeout can't be negative")
  505. }
  506. if cfg.PersistentPeersMaxDialPeriod < 0 {
  507. return errors.New("persistent_peers_max_dial_period can't be negative")
  508. }
  509. if cfg.MaxPacketMsgPayloadSize < 0 {
  510. return errors.New("max_packet_msg_payload_size can't be negative")
  511. }
  512. if cfg.SendRate < 0 {
  513. return errors.New("send_rate can't be negative")
  514. }
  515. if cfg.RecvRate < 0 {
  516. return errors.New("recv_rate can't be negative")
  517. }
  518. return nil
  519. }
  520. // FuzzConnConfig is a FuzzedConnection configuration.
  521. type FuzzConnConfig struct {
  522. Mode int
  523. MaxDelay time.Duration
  524. ProbDropRW float64
  525. ProbDropConn float64
  526. ProbSleep float64
  527. }
  528. // DefaultFuzzConnConfig returns the default config.
  529. func DefaultFuzzConnConfig() *FuzzConnConfig {
  530. return &FuzzConnConfig{
  531. Mode: FuzzModeDrop,
  532. MaxDelay: 3 * time.Second,
  533. ProbDropRW: 0.2,
  534. ProbDropConn: 0.00,
  535. ProbSleep: 0.00,
  536. }
  537. }
  538. //-----------------------------------------------------------------------------
  539. // MempoolConfig
  540. // MempoolConfig defines the configuration options for the Tendermint mempool
  541. type MempoolConfig struct {
  542. RootDir string `mapstructure:"home"`
  543. Recheck bool `mapstructure:"recheck"`
  544. Broadcast bool `mapstructure:"broadcast"`
  545. WalPath string `mapstructure:"wal_dir"`
  546. Size int `mapstructure:"size"`
  547. MaxTxsBytes int64 `mapstructure:"max_txs_bytes"`
  548. CacheSize int `mapstructure:"cache_size"`
  549. MaxTxBytes int `mapstructure:"max_tx_bytes"`
  550. }
  551. // DefaultMempoolConfig returns a default configuration for the Tendermint mempool
  552. func DefaultMempoolConfig() *MempoolConfig {
  553. return &MempoolConfig{
  554. Recheck: true,
  555. Broadcast: true,
  556. WalPath: "",
  557. // Each signature verification takes .5ms, Size reduced until we implement
  558. // ABCI Recheck
  559. Size: 5000,
  560. MaxTxsBytes: 1024 * 1024 * 1024, // 1GB
  561. CacheSize: 10000,
  562. MaxTxBytes: 1024 * 1024, // 1MB
  563. }
  564. }
  565. // TestMempoolConfig returns a configuration for testing the Tendermint mempool
  566. func TestMempoolConfig() *MempoolConfig {
  567. cfg := DefaultMempoolConfig()
  568. cfg.CacheSize = 1000
  569. return cfg
  570. }
  571. // WalDir returns the full path to the mempool's write-ahead log
  572. func (cfg *MempoolConfig) WalDir() string {
  573. return rootify(cfg.WalPath, cfg.RootDir)
  574. }
  575. // WalEnabled returns true if the WAL is enabled.
  576. func (cfg *MempoolConfig) WalEnabled() bool {
  577. return cfg.WalPath != ""
  578. }
  579. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  580. // returns an error if any check fails.
  581. func (cfg *MempoolConfig) ValidateBasic() error {
  582. if cfg.Size < 0 {
  583. return errors.New("size can't be negative")
  584. }
  585. if cfg.MaxTxsBytes < 0 {
  586. return errors.New("max_txs_bytes can't be negative")
  587. }
  588. if cfg.CacheSize < 0 {
  589. return errors.New("cache_size can't be negative")
  590. }
  591. if cfg.MaxTxBytes < 0 {
  592. return errors.New("max_tx_bytes can't be negative")
  593. }
  594. return nil
  595. }
  596. //-----------------------------------------------------------------------------
  597. // StateSyncConfig
  598. // StateSyncConfig defines the configuration for the Tendermint state sync service
  599. type StateSyncConfig struct {
  600. Enable bool `mapstructure:"enable"`
  601. TempDir string `mapstructure:"temp_dir"`
  602. RPCServers []string `mapstructure:"rpc_servers"`
  603. TrustPeriod time.Duration `mapstructure:"trust_period"`
  604. TrustHeight int64 `mapstructure:"trust_height"`
  605. TrustHash string `mapstructure:"trust_hash"`
  606. }
  607. func (cfg *StateSyncConfig) TrustHashBytes() []byte {
  608. // validated in ValidateBasic, so we can safely panic here
  609. bytes, err := hex.DecodeString(cfg.TrustHash)
  610. if err != nil {
  611. panic(err)
  612. }
  613. return bytes
  614. }
  615. // DefaultStateSyncConfig returns a default configuration for the state sync service
  616. func DefaultStateSyncConfig() *StateSyncConfig {
  617. return &StateSyncConfig{}
  618. }
  619. // TestFastSyncConfig returns a default configuration for the state sync service
  620. func TestStateSyncConfig() *StateSyncConfig {
  621. return DefaultStateSyncConfig()
  622. }
  623. // ValidateBasic performs basic validation.
  624. func (cfg *StateSyncConfig) ValidateBasic() error {
  625. if cfg.Enable {
  626. if len(cfg.RPCServers) == 0 {
  627. return errors.New("rpc_servers is required")
  628. }
  629. if len(cfg.RPCServers) < 2 {
  630. return errors.New("at least two rpc_servers entries is required")
  631. }
  632. for _, server := range cfg.RPCServers {
  633. if len(server) == 0 {
  634. return errors.New("found empty rpc_servers entry")
  635. }
  636. }
  637. if cfg.TrustPeriod <= 0 {
  638. return errors.New("trusted_period is required")
  639. }
  640. if cfg.TrustHeight <= 0 {
  641. return errors.New("trusted_height is required")
  642. }
  643. if len(cfg.TrustHash) == 0 {
  644. return errors.New("trusted_hash is required")
  645. }
  646. _, err := hex.DecodeString(cfg.TrustHash)
  647. if err != nil {
  648. return fmt.Errorf("invalid trusted_hash: %w", err)
  649. }
  650. }
  651. return nil
  652. }
  653. //-----------------------------------------------------------------------------
  654. // FastSyncConfig
  655. // FastSyncConfig defines the configuration for the Tendermint fast sync service
  656. type FastSyncConfig struct {
  657. Version string `mapstructure:"version"`
  658. }
  659. // DefaultFastSyncConfig returns a default configuration for the fast sync service
  660. func DefaultFastSyncConfig() *FastSyncConfig {
  661. return &FastSyncConfig{
  662. Version: "v0",
  663. }
  664. }
  665. // TestFastSyncConfig returns a default configuration for the fast sync.
  666. func TestFastSyncConfig() *FastSyncConfig {
  667. return DefaultFastSyncConfig()
  668. }
  669. // ValidateBasic performs basic validation.
  670. func (cfg *FastSyncConfig) ValidateBasic() error {
  671. switch cfg.Version {
  672. case "v0":
  673. return nil
  674. case "v1":
  675. return nil
  676. case "v2":
  677. return nil
  678. default:
  679. return fmt.Errorf("unknown fastsync version %s", cfg.Version)
  680. }
  681. }
  682. //-----------------------------------------------------------------------------
  683. // ConsensusConfig
  684. // ConsensusConfig defines the configuration for the Tendermint consensus service,
  685. // including timeouts and details about the WAL and the block structure.
  686. type ConsensusConfig struct {
  687. RootDir string `mapstructure:"home"`
  688. WalPath string `mapstructure:"wal_file"`
  689. walFile string // overrides WalPath if set
  690. TimeoutPropose time.Duration `mapstructure:"timeout_propose"`
  691. TimeoutProposeDelta time.Duration `mapstructure:"timeout_propose_delta"`
  692. TimeoutPrevote time.Duration `mapstructure:"timeout_prevote"`
  693. TimeoutPrevoteDelta time.Duration `mapstructure:"timeout_prevote_delta"`
  694. TimeoutPrecommit time.Duration `mapstructure:"timeout_precommit"`
  695. TimeoutPrecommitDelta time.Duration `mapstructure:"timeout_precommit_delta"`
  696. TimeoutCommit time.Duration `mapstructure:"timeout_commit"`
  697. // Make progress as soon as we have all the precommits (as if TimeoutCommit = 0)
  698. SkipTimeoutCommit bool `mapstructure:"skip_timeout_commit"`
  699. // EmptyBlocks mode and possible interval between empty blocks
  700. CreateEmptyBlocks bool `mapstructure:"create_empty_blocks"`
  701. CreateEmptyBlocksInterval time.Duration `mapstructure:"create_empty_blocks_interval"`
  702. // Reactor sleep duration parameters
  703. PeerGossipSleepDuration time.Duration `mapstructure:"peer_gossip_sleep_duration"`
  704. PeerQueryMaj23SleepDuration time.Duration `mapstructure:"peer_query_maj23_sleep_duration"`
  705. }
  706. // DefaultConsensusConfig returns a default configuration for the consensus service
  707. func DefaultConsensusConfig() *ConsensusConfig {
  708. return &ConsensusConfig{
  709. WalPath: filepath.Join(defaultDataDir, "cs.wal", "wal"),
  710. TimeoutPropose: 3000 * time.Millisecond,
  711. TimeoutProposeDelta: 500 * time.Millisecond,
  712. TimeoutPrevote: 1000 * time.Millisecond,
  713. TimeoutPrevoteDelta: 500 * time.Millisecond,
  714. TimeoutPrecommit: 1000 * time.Millisecond,
  715. TimeoutPrecommitDelta: 500 * time.Millisecond,
  716. TimeoutCommit: 1000 * time.Millisecond,
  717. SkipTimeoutCommit: false,
  718. CreateEmptyBlocks: true,
  719. CreateEmptyBlocksInterval: 0 * time.Second,
  720. PeerGossipSleepDuration: 100 * time.Millisecond,
  721. PeerQueryMaj23SleepDuration: 2000 * time.Millisecond,
  722. }
  723. }
  724. // TestConsensusConfig returns a configuration for testing the consensus service
  725. func TestConsensusConfig() *ConsensusConfig {
  726. cfg := DefaultConsensusConfig()
  727. cfg.TimeoutPropose = 40 * time.Millisecond
  728. cfg.TimeoutProposeDelta = 1 * time.Millisecond
  729. cfg.TimeoutPrevote = 10 * time.Millisecond
  730. cfg.TimeoutPrevoteDelta = 1 * time.Millisecond
  731. cfg.TimeoutPrecommit = 10 * time.Millisecond
  732. cfg.TimeoutPrecommitDelta = 1 * time.Millisecond
  733. cfg.TimeoutCommit = 10 * time.Millisecond
  734. cfg.SkipTimeoutCommit = true
  735. cfg.PeerGossipSleepDuration = 5 * time.Millisecond
  736. cfg.PeerQueryMaj23SleepDuration = 250 * time.Millisecond
  737. return cfg
  738. }
  739. // WaitForTxs returns true if the consensus should wait for transactions before entering the propose step
  740. func (cfg *ConsensusConfig) WaitForTxs() bool {
  741. return !cfg.CreateEmptyBlocks || cfg.CreateEmptyBlocksInterval > 0
  742. }
  743. // Propose returns the amount of time to wait for a proposal
  744. func (cfg *ConsensusConfig) Propose(round int) time.Duration {
  745. return time.Duration(
  746. cfg.TimeoutPropose.Nanoseconds()+cfg.TimeoutProposeDelta.Nanoseconds()*int64(round),
  747. ) * time.Nanosecond
  748. }
  749. // Prevote returns the amount of time to wait for straggler votes after receiving any +2/3 prevotes
  750. func (cfg *ConsensusConfig) Prevote(round int) time.Duration {
  751. return time.Duration(
  752. cfg.TimeoutPrevote.Nanoseconds()+cfg.TimeoutPrevoteDelta.Nanoseconds()*int64(round),
  753. ) * time.Nanosecond
  754. }
  755. // Precommit returns the amount of time to wait for straggler votes after receiving any +2/3 precommits
  756. func (cfg *ConsensusConfig) Precommit(round int) time.Duration {
  757. return time.Duration(
  758. cfg.TimeoutPrecommit.Nanoseconds()+cfg.TimeoutPrecommitDelta.Nanoseconds()*int64(round),
  759. ) * time.Nanosecond
  760. }
  761. // Commit returns the amount of time to wait for straggler votes after receiving +2/3 precommits
  762. // for a single block (ie. a commit).
  763. func (cfg *ConsensusConfig) Commit(t time.Time) time.Time {
  764. return t.Add(cfg.TimeoutCommit)
  765. }
  766. // WalFile returns the full path to the write-ahead log file
  767. func (cfg *ConsensusConfig) WalFile() string {
  768. if cfg.walFile != "" {
  769. return cfg.walFile
  770. }
  771. return rootify(cfg.WalPath, cfg.RootDir)
  772. }
  773. // SetWalFile sets the path to the write-ahead log file
  774. func (cfg *ConsensusConfig) SetWalFile(walFile string) {
  775. cfg.walFile = walFile
  776. }
  777. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  778. // returns an error if any check fails.
  779. func (cfg *ConsensusConfig) ValidateBasic() error {
  780. if cfg.TimeoutPropose < 0 {
  781. return errors.New("timeout_propose can't be negative")
  782. }
  783. if cfg.TimeoutProposeDelta < 0 {
  784. return errors.New("timeout_propose_delta can't be negative")
  785. }
  786. if cfg.TimeoutPrevote < 0 {
  787. return errors.New("timeout_prevote can't be negative")
  788. }
  789. if cfg.TimeoutPrevoteDelta < 0 {
  790. return errors.New("timeout_prevote_delta can't be negative")
  791. }
  792. if cfg.TimeoutPrecommit < 0 {
  793. return errors.New("timeout_precommit can't be negative")
  794. }
  795. if cfg.TimeoutPrecommitDelta < 0 {
  796. return errors.New("timeout_precommit_delta can't be negative")
  797. }
  798. if cfg.TimeoutCommit < 0 {
  799. return errors.New("timeout_commit can't be negative")
  800. }
  801. if cfg.CreateEmptyBlocksInterval < 0 {
  802. return errors.New("create_empty_blocks_interval can't be negative")
  803. }
  804. if cfg.PeerGossipSleepDuration < 0 {
  805. return errors.New("peer_gossip_sleep_duration can't be negative")
  806. }
  807. if cfg.PeerQueryMaj23SleepDuration < 0 {
  808. return errors.New("peer_query_maj23_sleep_duration can't be negative")
  809. }
  810. return nil
  811. }
  812. //-----------------------------------------------------------------------------
  813. // TxIndexConfig
  814. // Remember that Event has the following structure:
  815. // type: [
  816. // key: value,
  817. // ...
  818. // ]
  819. //
  820. // CompositeKeys are constructed by `type.key`
  821. // TxIndexConfig defines the configuration for the transaction indexer,
  822. // including composite keys to index.
  823. type TxIndexConfig struct {
  824. // What indexer to use for transactions
  825. //
  826. // Options:
  827. // 1) "null"
  828. // 2) "kv" (default) - the simplest possible indexer,
  829. // backed by key-value storage (defaults to levelDB; see DBBackend).
  830. Indexer string `mapstructure:"indexer"`
  831. // Comma-separated list of compositeKeys to index (by default the only key is "tx.hash")
  832. //
  833. // You can also index transactions by height by adding "tx.height" key here.
  834. //
  835. // It's recommended to index only a subset of keys due to possible memory
  836. // bloat. This is, of course, depends on the indexer's DB and the volume of
  837. // transactions.
  838. IndexKeys string `mapstructure:"index_keys"`
  839. // When set to true, tells indexer to index all compositeKeys (predefined keys:
  840. // "tx.hash", "tx.height" and all keys from DeliverTx responses).
  841. //
  842. // Note this may be not desirable (see the comment above). IndexKeys has a
  843. // precedence over IndexAllKeys (i.e. when given both, IndexKeys will be
  844. // indexed).
  845. IndexAllKeys bool `mapstructure:"index_all_keys"`
  846. }
  847. // DefaultTxIndexConfig returns a default configuration for the transaction indexer.
  848. func DefaultTxIndexConfig() *TxIndexConfig {
  849. return &TxIndexConfig{
  850. Indexer: "kv",
  851. IndexKeys: "",
  852. IndexAllKeys: false,
  853. }
  854. }
  855. // TestTxIndexConfig returns a default configuration for the transaction indexer.
  856. func TestTxIndexConfig() *TxIndexConfig {
  857. return DefaultTxIndexConfig()
  858. }
  859. //-----------------------------------------------------------------------------
  860. // InstrumentationConfig
  861. // InstrumentationConfig defines the configuration for metrics reporting.
  862. type InstrumentationConfig struct {
  863. // When true, Prometheus metrics are served under /metrics on
  864. // PrometheusListenAddr.
  865. // Check out the documentation for the list of available metrics.
  866. Prometheus bool `mapstructure:"prometheus"`
  867. // Address to listen for Prometheus collector(s) connections.
  868. PrometheusListenAddr string `mapstructure:"prometheus_listen_addr"`
  869. // Maximum number of simultaneous connections.
  870. // If you want to accept a larger number than the default, make sure
  871. // you increase your OS limits.
  872. // 0 - unlimited.
  873. MaxOpenConnections int `mapstructure:"max_open_connections"`
  874. // Instrumentation namespace.
  875. Namespace string `mapstructure:"namespace"`
  876. }
  877. // DefaultInstrumentationConfig returns a default configuration for metrics
  878. // reporting.
  879. func DefaultInstrumentationConfig() *InstrumentationConfig {
  880. return &InstrumentationConfig{
  881. Prometheus: false,
  882. PrometheusListenAddr: ":26660",
  883. MaxOpenConnections: 3,
  884. Namespace: "tendermint",
  885. }
  886. }
  887. // TestInstrumentationConfig returns a default configuration for metrics
  888. // reporting.
  889. func TestInstrumentationConfig() *InstrumentationConfig {
  890. return DefaultInstrumentationConfig()
  891. }
  892. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  893. // returns an error if any check fails.
  894. func (cfg *InstrumentationConfig) ValidateBasic() error {
  895. if cfg.MaxOpenConnections < 0 {
  896. return errors.New("max_open_connections can't be negative")
  897. }
  898. return nil
  899. }
  900. //-----------------------------------------------------------------------------
  901. // Utils
  902. // helper function to make config creation independent of root dir
  903. func rootify(path, root string) string {
  904. if filepath.IsAbs(path) {
  905. return path
  906. }
  907. return filepath.Join(root, path)
  908. }
  909. //-----------------------------------------------------------------------------
  910. // Moniker
  911. var defaultMoniker = getDefaultMoniker()
  912. // getDefaultMoniker returns a default moniker, which is the host name. If runtime
  913. // fails to get the host name, "anonymous" will be returned.
  914. func getDefaultMoniker() string {
  915. moniker, err := os.Hostname()
  916. if err != nil {
  917. moniker = "anonymous"
  918. }
  919. return moniker
  920. }