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.

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