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.

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