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.

1113 lines
39 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. ChunkRequestTimeout time.Duration `mapstructure:"chunk_request_timeout"`
  618. ChunkFetchers int32 `mapstructure:"chunk_fetchers"`
  619. }
  620. func (cfg *StateSyncConfig) TrustHashBytes() []byte {
  621. // validated in ValidateBasic, so we can safely panic here
  622. bytes, err := hex.DecodeString(cfg.TrustHash)
  623. if err != nil {
  624. panic(err)
  625. }
  626. return bytes
  627. }
  628. // DefaultStateSyncConfig returns a default configuration for the state sync service
  629. func DefaultStateSyncConfig() *StateSyncConfig {
  630. return &StateSyncConfig{
  631. TrustPeriod: 168 * time.Hour,
  632. DiscoveryTime: 15 * time.Second,
  633. ChunkRequestTimeout: 10 * time.Second,
  634. ChunkFetchers: 4,
  635. }
  636. }
  637. // TestFastSyncConfig returns a default configuration for the state sync service
  638. func TestStateSyncConfig() *StateSyncConfig {
  639. return DefaultStateSyncConfig()
  640. }
  641. // ValidateBasic performs basic validation.
  642. func (cfg *StateSyncConfig) ValidateBasic() error {
  643. if cfg.Enable {
  644. if len(cfg.RPCServers) == 0 {
  645. return errors.New("rpc_servers is required")
  646. }
  647. if len(cfg.RPCServers) < 2 {
  648. return errors.New("at least two rpc_servers entries is required")
  649. }
  650. for _, server := range cfg.RPCServers {
  651. if len(server) == 0 {
  652. return errors.New("found empty rpc_servers entry")
  653. }
  654. }
  655. if cfg.DiscoveryTime != 0 && cfg.DiscoveryTime < 5*time.Second {
  656. return errors.New("discovery time must be 0s or greater than five seconds")
  657. }
  658. if cfg.TrustPeriod <= 0 {
  659. return errors.New("trusted_period is required")
  660. }
  661. if cfg.TrustHeight <= 0 {
  662. return errors.New("trusted_height is required")
  663. }
  664. if len(cfg.TrustHash) == 0 {
  665. return errors.New("trusted_hash is required")
  666. }
  667. _, err := hex.DecodeString(cfg.TrustHash)
  668. if err != nil {
  669. return fmt.Errorf("invalid trusted_hash: %w", err)
  670. }
  671. if cfg.ChunkRequestTimeout < 5*time.Second {
  672. return errors.New("chunk_request_timeout must be at least 5 seconds")
  673. }
  674. if cfg.ChunkFetchers <= 0 {
  675. return errors.New("chunk_fetchers is required")
  676. }
  677. }
  678. return nil
  679. }
  680. //-----------------------------------------------------------------------------
  681. // FastSyncConfig
  682. // FastSyncConfig defines the configuration for the Tendermint fast sync service
  683. type FastSyncConfig struct {
  684. Version string `mapstructure:"version"`
  685. }
  686. // DefaultFastSyncConfig returns a default configuration for the fast sync service
  687. func DefaultFastSyncConfig() *FastSyncConfig {
  688. return &FastSyncConfig{
  689. Version: "v0",
  690. }
  691. }
  692. // TestFastSyncConfig returns a default configuration for the fast sync.
  693. func TestFastSyncConfig() *FastSyncConfig {
  694. return DefaultFastSyncConfig()
  695. }
  696. // ValidateBasic performs basic validation.
  697. func (cfg *FastSyncConfig) ValidateBasic() error {
  698. switch cfg.Version {
  699. case "v0":
  700. return nil
  701. case "v1":
  702. return nil
  703. case "v2":
  704. return nil
  705. default:
  706. return fmt.Errorf("unknown fastsync version %s", cfg.Version)
  707. }
  708. }
  709. //-----------------------------------------------------------------------------
  710. // ConsensusConfig
  711. // ConsensusConfig defines the configuration for the Tendermint consensus service,
  712. // including timeouts and details about the WAL and the block structure.
  713. type ConsensusConfig struct {
  714. RootDir string `mapstructure:"home"`
  715. WalPath string `mapstructure:"wal_file"`
  716. walFile string // overrides WalPath if set
  717. // How long we wait for a proposal block before prevoting nil
  718. TimeoutPropose time.Duration `mapstructure:"timeout_propose"`
  719. // How much timeout_propose increases with each round
  720. TimeoutProposeDelta time.Duration `mapstructure:"timeout_propose_delta"`
  721. // How long we wait after receiving +2/3 prevotes for “anything” (ie. not a single block or nil)
  722. TimeoutPrevote time.Duration `mapstructure:"timeout_prevote"`
  723. // How much the timeout_prevote increases with each round
  724. TimeoutPrevoteDelta time.Duration `mapstructure:"timeout_prevote_delta"`
  725. // How long we wait after receiving +2/3 precommits for “anything” (ie. not a single block or nil)
  726. TimeoutPrecommit time.Duration `mapstructure:"timeout_precommit"`
  727. // How much the timeout_precommit increases with each round
  728. TimeoutPrecommitDelta time.Duration `mapstructure:"timeout_precommit_delta"`
  729. // How long we wait after committing a block, before starting on the new
  730. // height (this gives us a chance to receive some more precommits, even
  731. // though we already have +2/3).
  732. // NOTE: when modifying, make sure to update time_iota_ms genesis parameter
  733. TimeoutCommit time.Duration `mapstructure:"timeout_commit"`
  734. // Make progress as soon as we have all the precommits (as if TimeoutCommit = 0)
  735. SkipTimeoutCommit bool `mapstructure:"skip_timeout_commit"`
  736. // EmptyBlocks mode and possible interval between empty blocks
  737. CreateEmptyBlocks bool `mapstructure:"create_empty_blocks"`
  738. CreateEmptyBlocksInterval time.Duration `mapstructure:"create_empty_blocks_interval"`
  739. // Reactor sleep duration parameters
  740. PeerGossipSleepDuration time.Duration `mapstructure:"peer_gossip_sleep_duration"`
  741. PeerQueryMaj23SleepDuration time.Duration `mapstructure:"peer_query_maj23_sleep_duration"`
  742. DoubleSignCheckHeight int64 `mapstructure:"double_sign_check_height"`
  743. }
  744. // DefaultConsensusConfig returns a default configuration for the consensus service
  745. func DefaultConsensusConfig() *ConsensusConfig {
  746. return &ConsensusConfig{
  747. WalPath: filepath.Join(defaultDataDir, "cs.wal", "wal"),
  748. TimeoutPropose: 3000 * time.Millisecond,
  749. TimeoutProposeDelta: 500 * time.Millisecond,
  750. TimeoutPrevote: 1000 * time.Millisecond,
  751. TimeoutPrevoteDelta: 500 * time.Millisecond,
  752. TimeoutPrecommit: 1000 * time.Millisecond,
  753. TimeoutPrecommitDelta: 500 * time.Millisecond,
  754. TimeoutCommit: 1000 * time.Millisecond,
  755. SkipTimeoutCommit: false,
  756. CreateEmptyBlocks: true,
  757. CreateEmptyBlocksInterval: 0 * time.Second,
  758. PeerGossipSleepDuration: 100 * time.Millisecond,
  759. PeerQueryMaj23SleepDuration: 2000 * time.Millisecond,
  760. DoubleSignCheckHeight: int64(0),
  761. }
  762. }
  763. // TestConsensusConfig returns a configuration for testing the consensus service
  764. func TestConsensusConfig() *ConsensusConfig {
  765. cfg := DefaultConsensusConfig()
  766. cfg.TimeoutPropose = 40 * time.Millisecond
  767. cfg.TimeoutProposeDelta = 1 * time.Millisecond
  768. cfg.TimeoutPrevote = 10 * time.Millisecond
  769. cfg.TimeoutPrevoteDelta = 1 * time.Millisecond
  770. cfg.TimeoutPrecommit = 10 * time.Millisecond
  771. cfg.TimeoutPrecommitDelta = 1 * time.Millisecond
  772. // NOTE: when modifying, make sure to update time_iota_ms (testGenesisFmt) in toml.go
  773. cfg.TimeoutCommit = 10 * time.Millisecond
  774. cfg.SkipTimeoutCommit = true
  775. cfg.PeerGossipSleepDuration = 5 * time.Millisecond
  776. cfg.PeerQueryMaj23SleepDuration = 250 * time.Millisecond
  777. cfg.DoubleSignCheckHeight = int64(0)
  778. return cfg
  779. }
  780. // WaitForTxs returns true if the consensus should wait for transactions before entering the propose step
  781. func (cfg *ConsensusConfig) WaitForTxs() bool {
  782. return !cfg.CreateEmptyBlocks || cfg.CreateEmptyBlocksInterval > 0
  783. }
  784. // Propose returns the amount of time to wait for a proposal
  785. func (cfg *ConsensusConfig) Propose(round int32) time.Duration {
  786. return time.Duration(
  787. cfg.TimeoutPropose.Nanoseconds()+cfg.TimeoutProposeDelta.Nanoseconds()*int64(round),
  788. ) * time.Nanosecond
  789. }
  790. // Prevote returns the amount of time to wait for straggler votes after receiving any +2/3 prevotes
  791. func (cfg *ConsensusConfig) Prevote(round int32) time.Duration {
  792. return time.Duration(
  793. cfg.TimeoutPrevote.Nanoseconds()+cfg.TimeoutPrevoteDelta.Nanoseconds()*int64(round),
  794. ) * time.Nanosecond
  795. }
  796. // Precommit returns the amount of time to wait for straggler votes after receiving any +2/3 precommits
  797. func (cfg *ConsensusConfig) Precommit(round int32) time.Duration {
  798. return time.Duration(
  799. cfg.TimeoutPrecommit.Nanoseconds()+cfg.TimeoutPrecommitDelta.Nanoseconds()*int64(round),
  800. ) * time.Nanosecond
  801. }
  802. // Commit returns the amount of time to wait for straggler votes after receiving +2/3 precommits
  803. // for a single block (ie. a commit).
  804. func (cfg *ConsensusConfig) Commit(t time.Time) time.Time {
  805. return t.Add(cfg.TimeoutCommit)
  806. }
  807. // WalFile returns the full path to the write-ahead log file
  808. func (cfg *ConsensusConfig) WalFile() string {
  809. if cfg.walFile != "" {
  810. return cfg.walFile
  811. }
  812. return rootify(cfg.WalPath, cfg.RootDir)
  813. }
  814. // SetWalFile sets the path to the write-ahead log file
  815. func (cfg *ConsensusConfig) SetWalFile(walFile string) {
  816. cfg.walFile = walFile
  817. }
  818. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  819. // returns an error if any check fails.
  820. func (cfg *ConsensusConfig) ValidateBasic() error {
  821. if cfg.TimeoutPropose < 0 {
  822. return errors.New("timeout_propose can't be negative")
  823. }
  824. if cfg.TimeoutProposeDelta < 0 {
  825. return errors.New("timeout_propose_delta can't be negative")
  826. }
  827. if cfg.TimeoutPrevote < 0 {
  828. return errors.New("timeout_prevote can't be negative")
  829. }
  830. if cfg.TimeoutPrevoteDelta < 0 {
  831. return errors.New("timeout_prevote_delta can't be negative")
  832. }
  833. if cfg.TimeoutPrecommit < 0 {
  834. return errors.New("timeout_precommit can't be negative")
  835. }
  836. if cfg.TimeoutPrecommitDelta < 0 {
  837. return errors.New("timeout_precommit_delta can't be negative")
  838. }
  839. if cfg.TimeoutCommit < 0 {
  840. return errors.New("timeout_commit can't be negative")
  841. }
  842. if cfg.CreateEmptyBlocksInterval < 0 {
  843. return errors.New("create_empty_blocks_interval can't be negative")
  844. }
  845. if cfg.PeerGossipSleepDuration < 0 {
  846. return errors.New("peer_gossip_sleep_duration can't be negative")
  847. }
  848. if cfg.PeerQueryMaj23SleepDuration < 0 {
  849. return errors.New("peer_query_maj23_sleep_duration can't be negative")
  850. }
  851. if cfg.DoubleSignCheckHeight < 0 {
  852. return errors.New("double_sign_check_height can't be negative")
  853. }
  854. return nil
  855. }
  856. //-----------------------------------------------------------------------------
  857. // TxIndexConfig
  858. // Remember that Event has the following structure:
  859. // type: [
  860. // key: value,
  861. // ...
  862. // ]
  863. //
  864. // CompositeKeys are constructed by `type.key`
  865. // TxIndexConfig defines the configuration for the transaction indexer,
  866. // including composite keys to index.
  867. type TxIndexConfig struct {
  868. // What indexer to use for transactions
  869. //
  870. // Options:
  871. // 1) "null"
  872. // 2) "kv" (default) - the simplest possible indexer,
  873. // backed by key-value storage (defaults to levelDB; see DBBackend).
  874. // 3) "psql" - the indexer services backed by PostgreSQL.
  875. Indexer string `mapstructure:"indexer"`
  876. // The PostgreSQL connection configuration, the connection format:
  877. // postgresql://<user>:<password>@<host>:<port>/<db>?<opts>
  878. PsqlConn string `mapstructure:"psql-conn"`
  879. }
  880. // DefaultTxIndexConfig returns a default configuration for the transaction indexer.
  881. func DefaultTxIndexConfig() *TxIndexConfig {
  882. return &TxIndexConfig{
  883. Indexer: "kv",
  884. }
  885. }
  886. // TestTxIndexConfig returns a default configuration for the transaction indexer.
  887. func TestTxIndexConfig() *TxIndexConfig {
  888. return DefaultTxIndexConfig()
  889. }
  890. //-----------------------------------------------------------------------------
  891. // InstrumentationConfig
  892. // InstrumentationConfig defines the configuration for metrics reporting.
  893. type InstrumentationConfig struct {
  894. // When true, Prometheus metrics are served under /metrics on
  895. // PrometheusListenAddr.
  896. // Check out the documentation for the list of available metrics.
  897. Prometheus bool `mapstructure:"prometheus"`
  898. // Address to listen for Prometheus collector(s) connections.
  899. PrometheusListenAddr string `mapstructure:"prometheus_listen_addr"`
  900. // Maximum number of simultaneous connections.
  901. // If you want to accept a larger number than the default, make sure
  902. // you increase your OS limits.
  903. // 0 - unlimited.
  904. MaxOpenConnections int `mapstructure:"max_open_connections"`
  905. // Instrumentation namespace.
  906. Namespace string `mapstructure:"namespace"`
  907. }
  908. // DefaultInstrumentationConfig returns a default configuration for metrics
  909. // reporting.
  910. func DefaultInstrumentationConfig() *InstrumentationConfig {
  911. return &InstrumentationConfig{
  912. Prometheus: false,
  913. PrometheusListenAddr: ":26660",
  914. MaxOpenConnections: 3,
  915. Namespace: "tendermint",
  916. }
  917. }
  918. // TestInstrumentationConfig returns a default configuration for metrics
  919. // reporting.
  920. func TestInstrumentationConfig() *InstrumentationConfig {
  921. return DefaultInstrumentationConfig()
  922. }
  923. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  924. // returns an error if any check fails.
  925. func (cfg *InstrumentationConfig) ValidateBasic() error {
  926. if cfg.MaxOpenConnections < 0 {
  927. return errors.New("max_open_connections can't be negative")
  928. }
  929. return nil
  930. }
  931. //-----------------------------------------------------------------------------
  932. // Utils
  933. // helper function to make config creation independent of root dir
  934. func rootify(path, root string) string {
  935. if filepath.IsAbs(path) {
  936. return path
  937. }
  938. return filepath.Join(root, path)
  939. }
  940. //-----------------------------------------------------------------------------
  941. // Moniker
  942. var defaultMoniker = getDefaultMoniker()
  943. // getDefaultMoniker returns a default moniker, which is the host name. If runtime
  944. // fails to get the host name, "anonymous" will be returned.
  945. func getDefaultMoniker() string {
  946. moniker, err := os.Hostname()
  947. if err != nil {
  948. moniker = "anonymous"
  949. }
  950. return moniker
  951. }