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.

2591 lines
81 KiB

3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
10 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
8 years ago
8 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
10 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
abci: localClient improvements & bugfixes & pubsub Unsubscribe issues (#2748) * use READ lock/unlock in ConsensusState#GetLastHeight Refs #2721 * do not use defers when there's no need * fix peer formatting (output its address instead of the pointer) ``` [54310]: E[11-02|11:59:39.851] Connection failed @ sendRoutine module=p2p peer=0xb78f00 conn=MConn{74.207.236.148:26656} err="pong timeout" ``` https://github.com/tendermint/tendermint/issues/2721#issuecomment-435326581 * panic if peer has no state https://github.com/tendermint/tendermint/issues/2721#issuecomment-435347165 It's confusing that sometimes we check if peer has a state, but most of the times we expect it to be there 1. https://github.com/tendermint/tendermint/blob/add79700b5fe84417538202b6c927c8cc5383672/mempool/reactor.go#L138 2. https://github.com/tendermint/tendermint/blob/add79700b5fe84417538202b6c927c8cc5383672/rpc/core/consensus.go#L196 (edited) I will change everything to always assume peer has a state and panic otherwise that should help identify issues earlier * abci/localclient: extend lock on app callback App callback should be protected by lock as well (note this was already done for InitChainAsync, why not for others???). Otherwise, when we execute the block, tx might come in and call the callback in the same time we're updating it in execBlockOnProxyApp => DATA RACE Fixes #2721 Consensus state is locked ``` goroutine 113333 [semacquire, 309 minutes]: sync.runtime_SemacquireMutex(0xc00180009c, 0xc0000c7e00) /usr/local/go/src/runtime/sema.go:71 +0x3d sync.(*RWMutex).RLock(0xc001800090) /usr/local/go/src/sync/rwmutex.go:50 +0x4e github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).GetRoundState(0xc001800000, 0x0) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:218 +0x46 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusReactor).queryMaj23Routine(0xc0017def80, 0x11104a0, 0xc0072488f0, 0xc007248 9c0) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/reactor.go:735 +0x16d created by github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusReactor).AddPeer /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/reactor.go:172 +0x236 ``` because localClient is locked ``` goroutine 1899 [semacquire, 309 minutes]: sync.runtime_SemacquireMutex(0xc00003363c, 0xc0000cb500) /usr/local/go/src/runtime/sema.go:71 +0x3d sync.(*Mutex).Lock(0xc000033638) /usr/local/go/src/sync/mutex.go:134 +0xff github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/abci/client.(*localClient).SetResponseCallback(0xc0001fb560, 0xc007868540) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/abci/client/local_client.go:32 +0x33 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/proxy.(*appConnConsensus).SetResponseCallback(0xc00002f750, 0xc007868540) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/proxy/app_conn.go:57 +0x40 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/state.execBlockOnProxyApp(0x1104e20, 0xc002ca0ba0, 0x11092a0, 0xc00002f750, 0xc0001fe960, 0xc000bfc660, 0x110cfe0, 0xc000090330, 0xc9d12, 0xc000d9d5a0, ...) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/state/execution.go:230 +0x1fd github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/state.(*BlockExecutor).ApplyBlock(0xc002c2a230, 0x7, 0x0, 0xc000eae880, 0x6, 0xc002e52c60, 0x16, 0x1f927, 0xc9d12, 0xc000d9d5a0, ...) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/state/execution.go:96 +0x142 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).finalizeCommit(0xc001800000, 0x1f928) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:1339 +0xa3e github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).tryFinalizeCommit(0xc001800000, 0x1f928) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:1270 +0x451 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).enterCommit.func1(0xc001800000, 0x0, 0x1f928) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:1218 +0x90 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).enterCommit(0xc001800000, 0x1f928, 0x0) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:1247 +0x6b8 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).addVote(0xc001800000, 0xc003d8dea0, 0xc000cf4cc0, 0x28, 0xf1, 0xc003bc7ad0, 0xc003bc7b10) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:1659 +0xbad github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).tryAddVote(0xc001800000, 0xc003d8dea0, 0xc000cf4cc0, 0x28, 0xf1, 0xf1, 0xf1) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:1517 +0x59 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).handleMsg(0xc001800000, 0xd98200, 0xc0070dbed0, 0xc000cf4cc0, 0x28) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:660 +0x64b github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine(0xc001800000, 0x0) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:617 +0x670 created by github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).OnStart /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:311 +0x132 ``` tx comes in and CheckTx is executed right when we execute the block ``` goroutine 111044 [semacquire, 309 minutes]: sync.runtime_SemacquireMutex(0xc00003363c, 0x0) /usr/local/go/src/runtime/sema.go:71 +0x3d sync.(*Mutex).Lock(0xc000033638) /usr/local/go/src/sync/mutex.go:134 +0xff github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/abci/client.(*localClient).CheckTxAsync(0xc0001fb0e0, 0xc002d94500, 0x13f, 0x280, 0x0) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/abci/client/local_client.go:85 +0x47 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/proxy.(*appConnMempool).CheckTxAsync(0xc00002f720, 0xc002d94500, 0x13f, 0x280, 0x1) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/proxy/app_conn.go:114 +0x51 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/mempool.(*Mempool).CheckTx(0xc002d3a320, 0xc002d94500, 0x13f, 0x280, 0xc0072355f0, 0x0, 0x0) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/mempool/mempool.go:316 +0x17b github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/rpc/core.BroadcastTxSync(0xc002d94500, 0x13f, 0x280, 0x0, 0x0, 0x0) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/rpc/core/mempool.go:93 +0xb8 reflect.Value.call(0xd85560, 0x10326c0, 0x13, 0xec7b8b, 0x4, 0xc00663f180, 0x1, 0x1, 0xc00663f180, 0xc00663f188, ...) /usr/local/go/src/reflect/value.go:447 +0x449 reflect.Value.Call(0xd85560, 0x10326c0, 0x13, 0xc00663f180, 0x1, 0x1, 0x0, 0x0, 0xc005cc9344) /usr/local/go/src/reflect/value.go:308 +0xa4 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/rpc/lib/server.makeHTTPHandler.func2(0x1102060, 0xc00663f100, 0xc0082d7900) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/rpc/lib/server/handlers.go:269 +0x188 net/http.HandlerFunc.ServeHTTP(0xc002c81f20, 0x1102060, 0xc00663f100, 0xc0082d7900) /usr/local/go/src/net/http/server.go:1964 +0x44 net/http.(*ServeMux).ServeHTTP(0xc002c81b60, 0x1102060, 0xc00663f100, 0xc0082d7900) /usr/local/go/src/net/http/server.go:2361 +0x127 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/rpc/lib/server.maxBytesHandler.ServeHTTP(0x10f8a40, 0xc002c81b60, 0xf4240, 0x1102060, 0xc00663f100, 0xc0082d7900) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/rpc/lib/server/http_server.go:219 +0xcf github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/rpc/lib/server.RecoverAndLogHandler.func1(0x1103220, 0xc00121e620, 0xc0082d7900) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/rpc/lib/server/http_server.go:192 +0x394 net/http.HandlerFunc.ServeHTTP(0xc002c06ea0, 0x1103220, 0xc00121e620, 0xc0082d7900) /usr/local/go/src/net/http/server.go:1964 +0x44 net/http.serverHandler.ServeHTTP(0xc001a1aa90, 0x1103220, 0xc00121e620, 0xc0082d7900) /usr/local/go/src/net/http/server.go:2741 +0xab net/http.(*conn).serve(0xc00785a3c0, 0x11041a0, 0xc000f844c0) /usr/local/go/src/net/http/server.go:1847 +0x646 created by net/http.(*Server).Serve /usr/local/go/src/net/http/server.go:2851 +0x2f5 ``` * consensus: use read lock in Receive#VoteMessage * use defer to unlock mutex because application might panic * use defer in every method of the localClient * add a changelog entry * drain channels before Unsubscribe(All) Read https://github.com/tendermint/tendermint/blob/55362ed76630f3e1ebec159a598f6a9fb5892cb1/libs/pubsub/pubsub.go#L13 for the detailed explanation of the issue. We'll need to fix it someday. Make sure to keep an eye on https://github.com/tendermint/tendermint/blob/master/docs/architecture/adr-033-pubsub.md * retry instead of panic when peer has no state in reactors other than consensus in /dump_consensus_state RPC endpoint, skip a peer with no state * rpc/core/mempool: simplify error messages * rpc/core/mempool: use time.After instead of timer also, do not log DeliverTx result (to be consistent with other memthods) * unlock before calling the callback in reqRes#SetCallback
6 years ago
fix data race Closes #1442 ``` WARNING: DATA RACE Write at 0x00c4209de7c8 by goroutine 23: github.com/tendermint/tendermint/types.(*Block).fillHeader() /home/vagrant/go/src/github.com/tendermint/tendermint/types/block.go:88 +0x157 github.com/tendermint/tendermint/types.(*Block).Hash() /home/vagrant/go/src/github.com/tendermint/tendermint/types/block.go:104 +0x121 github.com/tendermint/tendermint/types.(*Block).HashesTo() /home/vagrant/go/src/github.com/tendermint/tendermint/types/block.go:135 +0x4f github.com/tendermint/tendermint/consensus.(*ConsensusState).enterPrecommit() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:1037 +0x182d github.com/tendermint/tendermint/consensus.(*ConsensusState).addVote() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:1425 +0x1a6c github.com/tendermint/tendermint/consensus.(*ConsensusState).tryAddVote() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:1318 +0x77 github.com/tendermint/tendermint/consensus.(*ConsensusState).handleMsg() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:581 +0x7a9 github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:539 +0x6c3 Previous read at 0x00c4209de7c8 by goroutine 47: github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*HexBytes).MarshalJSON() <autogenerated>:1 +0x52 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.invokeMarshalJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:433 +0x88 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:82 +0x8d2 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).MarshalJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/amino.go:296 +0x182 github.com/tendermint/tendermint/rpc/lib/types.NewRPCSuccessResponse() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/types/types.go:100 +0x12c github.com/tendermint/tendermint/rpc/lib/server.makeJSONRPCHandler.func1() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/server/handlers.go:152 +0xab7 net/http.HandlerFunc.ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:1918 +0x51 net/http.(*ServeMux).ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:2254 +0xa2 github.com/tendermint/tendermint/rpc/lib/server.RecoverAndLogHandler.func1() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/server/http_server.go:138 +0x4fa net/http.HandlerFunc.ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:1918 +0x51 net/http.serverHandler.ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:2619 +0xbc net/http.(*conn).serve() /usr/lib/go-1.9/src/net/http/server.go:1801 +0x83b Goroutine 23 (running) created at: github.com/tendermint/tendermint/consensus.(*ConsensusState).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:250 +0x35b github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/consensus.(*ConsensusReactor).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/reactor.go:69 +0x1b4 github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/consensus.(*ConsensusReactor).Start() <autogenerated>:1 +0x43 github.com/tendermint/tendermint/p2p.(*Switch).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/switch.go:177 +0x124 github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/node.(*Node).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/node/node.go:416 +0xa1b github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/rpc/test.StartTendermint() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/test/helpers.go:100 +0x5b github.com/tendermint/tendermint/rpc/client_test.TestMain() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/client/main_test.go:17 +0x4c main.main() github.com/tendermint/tendermint/rpc/client/_test/_testmain.go:76 +0x1cd Goroutine 47 (running) created at: net/http.(*Server).Serve() /usr/lib/go-1.9/src/net/http/server.go:2720 +0x37c net/http.Serve() /usr/lib/go-1.9/src/net/http/server.go:2323 +0xe2 github.com/tendermint/tendermint/rpc/lib/server.StartHTTPServer.func1() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/server/http_server.go:35 +0xb3 ```
7 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
10 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
fix data race Closes #1442 ``` WARNING: DATA RACE Write at 0x00c4209de7c8 by goroutine 23: github.com/tendermint/tendermint/types.(*Block).fillHeader() /home/vagrant/go/src/github.com/tendermint/tendermint/types/block.go:88 +0x157 github.com/tendermint/tendermint/types.(*Block).Hash() /home/vagrant/go/src/github.com/tendermint/tendermint/types/block.go:104 +0x121 github.com/tendermint/tendermint/types.(*Block).HashesTo() /home/vagrant/go/src/github.com/tendermint/tendermint/types/block.go:135 +0x4f github.com/tendermint/tendermint/consensus.(*ConsensusState).enterPrecommit() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:1037 +0x182d github.com/tendermint/tendermint/consensus.(*ConsensusState).addVote() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:1425 +0x1a6c github.com/tendermint/tendermint/consensus.(*ConsensusState).tryAddVote() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:1318 +0x77 github.com/tendermint/tendermint/consensus.(*ConsensusState).handleMsg() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:581 +0x7a9 github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:539 +0x6c3 Previous read at 0x00c4209de7c8 by goroutine 47: github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*HexBytes).MarshalJSON() <autogenerated>:1 +0x52 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.invokeMarshalJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:433 +0x88 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:82 +0x8d2 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).MarshalJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/amino.go:296 +0x182 github.com/tendermint/tendermint/rpc/lib/types.NewRPCSuccessResponse() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/types/types.go:100 +0x12c github.com/tendermint/tendermint/rpc/lib/server.makeJSONRPCHandler.func1() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/server/handlers.go:152 +0xab7 net/http.HandlerFunc.ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:1918 +0x51 net/http.(*ServeMux).ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:2254 +0xa2 github.com/tendermint/tendermint/rpc/lib/server.RecoverAndLogHandler.func1() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/server/http_server.go:138 +0x4fa net/http.HandlerFunc.ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:1918 +0x51 net/http.serverHandler.ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:2619 +0xbc net/http.(*conn).serve() /usr/lib/go-1.9/src/net/http/server.go:1801 +0x83b Goroutine 23 (running) created at: github.com/tendermint/tendermint/consensus.(*ConsensusState).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:250 +0x35b github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/consensus.(*ConsensusReactor).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/reactor.go:69 +0x1b4 github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/consensus.(*ConsensusReactor).Start() <autogenerated>:1 +0x43 github.com/tendermint/tendermint/p2p.(*Switch).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/switch.go:177 +0x124 github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/node.(*Node).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/node/node.go:416 +0xa1b github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/rpc/test.StartTendermint() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/test/helpers.go:100 +0x5b github.com/tendermint/tendermint/rpc/client_test.TestMain() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/client/main_test.go:17 +0x4c main.main() github.com/tendermint/tendermint/rpc/client/_test/_testmain.go:76 +0x1cd Goroutine 47 (running) created at: net/http.(*Server).Serve() /usr/lib/go-1.9/src/net/http/server.go:2720 +0x37c net/http.Serve() /usr/lib/go-1.9/src/net/http/server.go:2323 +0xe2 github.com/tendermint/tendermint/rpc/lib/server.StartHTTPServer.func1() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/server/http_server.go:35 +0xb3 ```
7 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
abci: localClient improvements & bugfixes & pubsub Unsubscribe issues (#2748) * use READ lock/unlock in ConsensusState#GetLastHeight Refs #2721 * do not use defers when there's no need * fix peer formatting (output its address instead of the pointer) ``` [54310]: E[11-02|11:59:39.851] Connection failed @ sendRoutine module=p2p peer=0xb78f00 conn=MConn{74.207.236.148:26656} err="pong timeout" ``` https://github.com/tendermint/tendermint/issues/2721#issuecomment-435326581 * panic if peer has no state https://github.com/tendermint/tendermint/issues/2721#issuecomment-435347165 It's confusing that sometimes we check if peer has a state, but most of the times we expect it to be there 1. https://github.com/tendermint/tendermint/blob/add79700b5fe84417538202b6c927c8cc5383672/mempool/reactor.go#L138 2. https://github.com/tendermint/tendermint/blob/add79700b5fe84417538202b6c927c8cc5383672/rpc/core/consensus.go#L196 (edited) I will change everything to always assume peer has a state and panic otherwise that should help identify issues earlier * abci/localclient: extend lock on app callback App callback should be protected by lock as well (note this was already done for InitChainAsync, why not for others???). Otherwise, when we execute the block, tx might come in and call the callback in the same time we're updating it in execBlockOnProxyApp => DATA RACE Fixes #2721 Consensus state is locked ``` goroutine 113333 [semacquire, 309 minutes]: sync.runtime_SemacquireMutex(0xc00180009c, 0xc0000c7e00) /usr/local/go/src/runtime/sema.go:71 +0x3d sync.(*RWMutex).RLock(0xc001800090) /usr/local/go/src/sync/rwmutex.go:50 +0x4e github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).GetRoundState(0xc001800000, 0x0) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:218 +0x46 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusReactor).queryMaj23Routine(0xc0017def80, 0x11104a0, 0xc0072488f0, 0xc007248 9c0) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/reactor.go:735 +0x16d created by github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusReactor).AddPeer /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/reactor.go:172 +0x236 ``` because localClient is locked ``` goroutine 1899 [semacquire, 309 minutes]: sync.runtime_SemacquireMutex(0xc00003363c, 0xc0000cb500) /usr/local/go/src/runtime/sema.go:71 +0x3d sync.(*Mutex).Lock(0xc000033638) /usr/local/go/src/sync/mutex.go:134 +0xff github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/abci/client.(*localClient).SetResponseCallback(0xc0001fb560, 0xc007868540) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/abci/client/local_client.go:32 +0x33 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/proxy.(*appConnConsensus).SetResponseCallback(0xc00002f750, 0xc007868540) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/proxy/app_conn.go:57 +0x40 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/state.execBlockOnProxyApp(0x1104e20, 0xc002ca0ba0, 0x11092a0, 0xc00002f750, 0xc0001fe960, 0xc000bfc660, 0x110cfe0, 0xc000090330, 0xc9d12, 0xc000d9d5a0, ...) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/state/execution.go:230 +0x1fd github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/state.(*BlockExecutor).ApplyBlock(0xc002c2a230, 0x7, 0x0, 0xc000eae880, 0x6, 0xc002e52c60, 0x16, 0x1f927, 0xc9d12, 0xc000d9d5a0, ...) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/state/execution.go:96 +0x142 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).finalizeCommit(0xc001800000, 0x1f928) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:1339 +0xa3e github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).tryFinalizeCommit(0xc001800000, 0x1f928) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:1270 +0x451 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).enterCommit.func1(0xc001800000, 0x0, 0x1f928) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:1218 +0x90 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).enterCommit(0xc001800000, 0x1f928, 0x0) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:1247 +0x6b8 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).addVote(0xc001800000, 0xc003d8dea0, 0xc000cf4cc0, 0x28, 0xf1, 0xc003bc7ad0, 0xc003bc7b10) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:1659 +0xbad github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).tryAddVote(0xc001800000, 0xc003d8dea0, 0xc000cf4cc0, 0x28, 0xf1, 0xf1, 0xf1) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:1517 +0x59 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).handleMsg(0xc001800000, 0xd98200, 0xc0070dbed0, 0xc000cf4cc0, 0x28) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:660 +0x64b github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine(0xc001800000, 0x0) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:617 +0x670 created by github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).OnStart /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:311 +0x132 ``` tx comes in and CheckTx is executed right when we execute the block ``` goroutine 111044 [semacquire, 309 minutes]: sync.runtime_SemacquireMutex(0xc00003363c, 0x0) /usr/local/go/src/runtime/sema.go:71 +0x3d sync.(*Mutex).Lock(0xc000033638) /usr/local/go/src/sync/mutex.go:134 +0xff github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/abci/client.(*localClient).CheckTxAsync(0xc0001fb0e0, 0xc002d94500, 0x13f, 0x280, 0x0) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/abci/client/local_client.go:85 +0x47 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/proxy.(*appConnMempool).CheckTxAsync(0xc00002f720, 0xc002d94500, 0x13f, 0x280, 0x1) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/proxy/app_conn.go:114 +0x51 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/mempool.(*Mempool).CheckTx(0xc002d3a320, 0xc002d94500, 0x13f, 0x280, 0xc0072355f0, 0x0, 0x0) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/mempool/mempool.go:316 +0x17b github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/rpc/core.BroadcastTxSync(0xc002d94500, 0x13f, 0x280, 0x0, 0x0, 0x0) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/rpc/core/mempool.go:93 +0xb8 reflect.Value.call(0xd85560, 0x10326c0, 0x13, 0xec7b8b, 0x4, 0xc00663f180, 0x1, 0x1, 0xc00663f180, 0xc00663f188, ...) /usr/local/go/src/reflect/value.go:447 +0x449 reflect.Value.Call(0xd85560, 0x10326c0, 0x13, 0xc00663f180, 0x1, 0x1, 0x0, 0x0, 0xc005cc9344) /usr/local/go/src/reflect/value.go:308 +0xa4 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/rpc/lib/server.makeHTTPHandler.func2(0x1102060, 0xc00663f100, 0xc0082d7900) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/rpc/lib/server/handlers.go:269 +0x188 net/http.HandlerFunc.ServeHTTP(0xc002c81f20, 0x1102060, 0xc00663f100, 0xc0082d7900) /usr/local/go/src/net/http/server.go:1964 +0x44 net/http.(*ServeMux).ServeHTTP(0xc002c81b60, 0x1102060, 0xc00663f100, 0xc0082d7900) /usr/local/go/src/net/http/server.go:2361 +0x127 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/rpc/lib/server.maxBytesHandler.ServeHTTP(0x10f8a40, 0xc002c81b60, 0xf4240, 0x1102060, 0xc00663f100, 0xc0082d7900) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/rpc/lib/server/http_server.go:219 +0xcf github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/rpc/lib/server.RecoverAndLogHandler.func1(0x1103220, 0xc00121e620, 0xc0082d7900) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/rpc/lib/server/http_server.go:192 +0x394 net/http.HandlerFunc.ServeHTTP(0xc002c06ea0, 0x1103220, 0xc00121e620, 0xc0082d7900) /usr/local/go/src/net/http/server.go:1964 +0x44 net/http.serverHandler.ServeHTTP(0xc001a1aa90, 0x1103220, 0xc00121e620, 0xc0082d7900) /usr/local/go/src/net/http/server.go:2741 +0xab net/http.(*conn).serve(0xc00785a3c0, 0x11041a0, 0xc000f844c0) /usr/local/go/src/net/http/server.go:1847 +0x646 created by net/http.(*Server).Serve /usr/local/go/src/net/http/server.go:2851 +0x2f5 ``` * consensus: use read lock in Receive#VoteMessage * use defer to unlock mutex because application might panic * use defer in every method of the localClient * add a changelog entry * drain channels before Unsubscribe(All) Read https://github.com/tendermint/tendermint/blob/55362ed76630f3e1ebec159a598f6a9fb5892cb1/libs/pubsub/pubsub.go#L13 for the detailed explanation of the issue. We'll need to fix it someday. Make sure to keep an eye on https://github.com/tendermint/tendermint/blob/master/docs/architecture/adr-033-pubsub.md * retry instead of panic when peer has no state in reactors other than consensus in /dump_consensus_state RPC endpoint, skip a peer with no state * rpc/core/mempool: simplify error messages * rpc/core/mempool: use time.After instead of timer also, do not log DeliverTx result (to be consistent with other memthods) * unlock before calling the callback in reqRes#SetCallback
6 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
10 years ago
8 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
9 years ago
9 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
9 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
cs: check for SkipTimeoutCommit or wait timeout in handleTxsAvailable (#3928) * cs: check for SkipTimeoutCommit or wait timeout in handleTxsAvailable Previously, if create_empty_blocks was set to false, TM sometimes could create 2 consecutive blocks without actually waiting for timeoutCommit (1 sec. by default). ``` I[2019-08-29|07:32:43.874] Executed block module=state height=47 validTxs=10 invalidTxs=0 I[2019-08-29|07:32:43.876] Committed state module=state height=47 txs=10 appHash=F88C010000000000 I[2019-08-29|07:32:44.885] Executed block module=state height=48 validTxs=2 invalidTxs=0 I[2019-08-29|07:32:44.887] Committed state module=state height=48 txs=2 appHash=FC8C010000000000 I[2019-08-29|07:32:44.908] Executed block module=state height=49 validTxs=8 invalidTxs=0 I[2019-08-29|07:32:44.909] Committed state module=state height=49 txs=8 appHash=8C8D010000000000 I[2019-08-29|07:32:45.886] Executed block module=state height=50 validTxs=2 invalidTxs=0 I[2019-08-29|07:32:45.895] Committed state module=state height=50 txs=2 appHash=908D010000000000 I[2019-08-29|07:32:45.908] Executed block module=state height=51 validTxs=8 invalidTxs=0 I[2019-08-29|07:32:45.909] Committed state module=state height=51 txs=8 appHash=A08D010000000000 ``` This commit fixes that by adding a check to handleTxsAvailable. Fixes #3908 * update changelog * schedule timeoutCommit if StartTime is in the future or SkipTimeoutCommit=true && we DON'T have all the votes * fix TestReactorCreatesBlockWhenEmptyBlocksFalse by checking if we have LastCommit or not * address Ethan's comments
5 years ago
cs: reset triggered timeout precommit (#3310) * Reset TriggeredTimeoutPrecommit as part of updateToState * Add failing test and fix * fix DATA RACE in TestResetTimeoutPrecommitUponNewHeight ``` WARNING: DATA RACE Read at 0x00c001691d28 by goroutine 691: github.com/tendermint/tendermint/consensus.decideProposal() /go/src/github.com/tendermint/tendermint/consensus/common_test.go:133 +0x121 github.com/tendermint/tendermint/consensus.TestResetTimeoutPrecommitUponNewHeight() /go/src/github.com/tendermint/tendermint/consensus/state_test.go:1389 +0x958 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Previous write at 0x00c001691d28 by goroutine 931: github.com/tendermint/tendermint/consensus.(*ConsensusState).updateToState() /go/src/github.com/tendermint/tendermint/consensus/state.go:562 +0x5b2 github.com/tendermint/tendermint/consensus.(*ConsensusState).finalizeCommit() /go/src/github.com/tendermint/tendermint/consensus/state.go:1340 +0x141e github.com/tendermint/tendermint/consensus.(*ConsensusState).tryFinalizeCommit() /go/src/github.com/tendermint/tendermint/consensus/state.go:1255 +0x66e github.com/tendermint/tendermint/consensus.(*ConsensusState).enterCommit.func1() /go/src/github.com/tendermint/tendermint/consensus/state.go:1201 +0x135 github.com/tendermint/tendermint/consensus.(*ConsensusState).enterCommit() /go/src/github.com/tendermint/tendermint/consensus/state.go:1232 +0x94b github.com/tendermint/tendermint/consensus.(*ConsensusState).addVote() /go/src/github.com/tendermint/tendermint/consensus/state.go:1657 +0x132e github.com/tendermint/tendermint/consensus.(*ConsensusState).tryAddVote() /go/src/github.com/tendermint/tendermint/consensus/state.go:1503 +0x8f github.com/tendermint/tendermint/consensus.(*ConsensusState).handleMsg() /go/src/github.com/tendermint/tendermint/consensus/state.go:694 +0xa1e github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine() /go/src/github.com/tendermint/tendermint/consensus/state.go:642 +0x948 github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine() /go/src/github.com/tendermint/tendermint/consensus/state.go:642 +0x948 github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine() /go/src/github.com/tendermint/tendermint/consensus/state.go:642 +0x948 github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine() /go/src/github.com/tendermint/tendermint/consensus/state.go:655 +0x7dd github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine() /go/src/github.com/tendermint/tendermint/consensus/state.go:642 +0x948 github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine() /go/src/github.com/tendermint/tendermint/consensus/state.go:655 +0x7dd Goroutine 691 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 testing.runTests.func1() /usr/local/go/src/testing/testing.go:1119 +0xa8 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 testing.runTests() testing.(*M).Run() /usr/local/go/src/testing/testing.go:1034 +0x2ee main.main() _testmain.go:216 +0x332 ``` * fix another DATA RACE by locking consensus ``` WARNING: DATA RACE Read at 0x00c009b835a8 by goroutine 871: github.com/tendermint/tendermint/consensus.(*ConsensusState).createProposalBlock() /go/src/github.com/tendermint/tendermint/consensus/state.go:955 +0x7c github.com/tendermint/tendermint/consensus.decideProposal() /go/src/github.com/tendermint/tendermint/consensus/common_test.go:127 +0x53 github.com/tendermint/tendermint/consensus.TestResetTimeoutPrecommitUponNewHeight() /go/src/github.com/tendermint/tendermint/consensus/state_test.go:1389 +0x958 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Previous write at 0x00c009b835a8 by goroutine 931: github.com/tendermint/tendermint/consensus.(*ConsensusState).updateHeight() /go/src/github.com/tendermint/tendermint/consensus/state.go:446 +0xb7 github.com/tendermint/tendermint/consensus.(*ConsensusState).updateToState() /go/src/github.com/tendermint/tendermint/consensus/state.go:542 +0x22f github.com/tendermint/tendermint/consensus.(*ConsensusState).finalizeCommit() /go/src/github.com/tendermint/tendermint/consensus/state.go:1340 +0x141e github.com/tendermint/tendermint/consensus.(*ConsensusState).tryFinalizeCommit() /go/src/github.com/tendermint/tendermint/consensus/state.go:1255 +0x66e github.com/tendermint/tendermint/consensus.(*ConsensusState).enterCommit.func1() /go/src/github.com/tendermint/tendermint/consensus/state.go:1201 +0x135 github.com/tendermint/tendermint/consensus.(*ConsensusState).enterCommit() /go/src/github.com/tendermint/tendermint/consensus/state.go:1232 +0x94b github.com/tendermint/tendermint/consensus.(*ConsensusState).addVote() /go/src/github.com/tendermint/tendermint/consensus/state.go:1657 +0x132e github.com/tendermint/tendermint/consensus.(*ConsensusState).tryAddVote() /go/src/github.com/tendermint/tendermint/consensus/state.go:1503 +0x8f github.com/tendermint/tendermint/consensus.(*ConsensusState).handleMsg() /go/src/github.com/tendermint/tendermint/consensus/state.go:694 +0xa1e github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine() /go/src/github.com/tendermint/tendermint/consensus/state.go:642 +0x948 github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine() /go/src/github.com/tendermint/tendermint/consensus/state.go:642 +0x948 github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine() /go/src/github.com/tendermint/tendermint/consensus/state.go:642 +0x948 github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine() /go/src/github.com/tendermint/tendermint/consensus/state.go:655 +0x7dd github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine() /go/src/github.com/tendermint/tendermint/consensus/state.go:642 +0x948 github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine() /go/src/github.com/tendermint/tendermint/consensus/state.go:655 +0x7dd ``` * Fix failing test * Delete profile.out * fix data races
6 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
WAL: better errors and new fail point (#3246) * privval: more info in errors * wal: change Debug logs to Info * wal: log and return error on corrupted wal instead of panicing * fail: Exit right away instead of sending interupt * consensus: FAIL before handling our own vote allows to replicate #3089: - run using `FAIL_TEST_INDEX=0` - delete some bytes from the end of the WAL - start normally Results in logs like: ``` I[2019-02-03|18:12:58.225] Searching for height module=consensus wal=/Users/ethanbuchman/.tendermint/data/cs.wal/wal height=1 min=0 max=0 E[2019-02-03|18:12:58.225] Error on catchup replay. Proceeding to start ConsensusState anyway module=consensus err="failed to read data: EOF" I[2019-02-03|18:12:58.225] Started node module=main nodeInfo="{ProtocolVersion:{P2P:6 Block:9 App:1} ID_:35e87e93f2e31f305b65a5517fd2102331b56002 ListenAddr:tcp://0.0.0.0:26656 Network:test-chain-J8JvJH Version:0.29.1 Channels:4020212223303800 Moniker:Ethans-MacBook-Pro.local Other:{TxIndex:on RPCAddress:tcp://0.0.0.0:26657}}" E[2019-02-03|18:12:58.226] Couldn't connect to any seeds module=p2p I[2019-02-03|18:12:59.229] Timed out module=consensus dur=998.568ms height=1 round=0 step=RoundStepNewHeight I[2019-02-03|18:12:59.230] enterNewRound(1/0). Current: 1/0/RoundStepNewHeight module=consensus height=1 round=0 I[2019-02-03|18:12:59.230] enterPropose(1/0). Current: 1/0/RoundStepNewRound module=consensus height=1 round=0 I[2019-02-03|18:12:59.230] enterPropose: Our turn to propose module=consensus height=1 round=0 proposer=AD278B7767B05D7FBEB76207024C650988FA77D5 privValidator="PrivValidator{AD278B7767B05D7FBEB76207024C650988FA77D5 LH:1, LR:0, LS:2}" E[2019-02-03|18:12:59.230] enterPropose: Error signing proposal module=consensus height=1 round=0 err="Error signing proposal: Step regression at height 1 round 0. Got 1, last step 2" I[2019-02-03|18:13:02.233] Timed out module=consensus dur=3s height=1 round=0 step=RoundStepPropose I[2019-02-03|18:13:02.233] enterPrevote(1/0). Current: 1/0/RoundStepPropose module=consensus I[2019-02-03|18:13:02.233] enterPrevote: ProposalBlock is nil module=consensus height=1 round=0 E[2019-02-03|18:13:02.234] Error signing vote module=consensus height=1 round=0 vote="Vote{0:AD278B7767B0 1/00/1(Prevote) 000000000000 000000000000 @ 2019-02-04T02:13:02.233897Z}" err="Error signing vote: Conflicting data" ``` Notice the EOF, the step regression, and the conflicting data. * wal: change errors to be DataCorruptionError * exit on corrupt WAL * fix log * fix new line
6 years ago
cs: check for SkipTimeoutCommit or wait timeout in handleTxsAvailable (#3928) * cs: check for SkipTimeoutCommit or wait timeout in handleTxsAvailable Previously, if create_empty_blocks was set to false, TM sometimes could create 2 consecutive blocks without actually waiting for timeoutCommit (1 sec. by default). ``` I[2019-08-29|07:32:43.874] Executed block module=state height=47 validTxs=10 invalidTxs=0 I[2019-08-29|07:32:43.876] Committed state module=state height=47 txs=10 appHash=F88C010000000000 I[2019-08-29|07:32:44.885] Executed block module=state height=48 validTxs=2 invalidTxs=0 I[2019-08-29|07:32:44.887] Committed state module=state height=48 txs=2 appHash=FC8C010000000000 I[2019-08-29|07:32:44.908] Executed block module=state height=49 validTxs=8 invalidTxs=0 I[2019-08-29|07:32:44.909] Committed state module=state height=49 txs=8 appHash=8C8D010000000000 I[2019-08-29|07:32:45.886] Executed block module=state height=50 validTxs=2 invalidTxs=0 I[2019-08-29|07:32:45.895] Committed state module=state height=50 txs=2 appHash=908D010000000000 I[2019-08-29|07:32:45.908] Executed block module=state height=51 validTxs=8 invalidTxs=0 I[2019-08-29|07:32:45.909] Committed state module=state height=51 txs=8 appHash=A08D010000000000 ``` This commit fixes that by adding a check to handleTxsAvailable. Fixes #3908 * update changelog * schedule timeoutCommit if StartTime is in the future or SkipTimeoutCommit=true && we DON'T have all the votes * fix TestReactorCreatesBlockWhenEmptyBlocksFalse by checking if we have LastCommit or not * address Ethan's comments
5 years ago
cs: check for SkipTimeoutCommit or wait timeout in handleTxsAvailable (#3928) * cs: check for SkipTimeoutCommit or wait timeout in handleTxsAvailable Previously, if create_empty_blocks was set to false, TM sometimes could create 2 consecutive blocks without actually waiting for timeoutCommit (1 sec. by default). ``` I[2019-08-29|07:32:43.874] Executed block module=state height=47 validTxs=10 invalidTxs=0 I[2019-08-29|07:32:43.876] Committed state module=state height=47 txs=10 appHash=F88C010000000000 I[2019-08-29|07:32:44.885] Executed block module=state height=48 validTxs=2 invalidTxs=0 I[2019-08-29|07:32:44.887] Committed state module=state height=48 txs=2 appHash=FC8C010000000000 I[2019-08-29|07:32:44.908] Executed block module=state height=49 validTxs=8 invalidTxs=0 I[2019-08-29|07:32:44.909] Committed state module=state height=49 txs=8 appHash=8C8D010000000000 I[2019-08-29|07:32:45.886] Executed block module=state height=50 validTxs=2 invalidTxs=0 I[2019-08-29|07:32:45.895] Committed state module=state height=50 txs=2 appHash=908D010000000000 I[2019-08-29|07:32:45.908] Executed block module=state height=51 validTxs=8 invalidTxs=0 I[2019-08-29|07:32:45.909] Committed state module=state height=51 txs=8 appHash=A08D010000000000 ``` This commit fixes that by adding a check to handleTxsAvailable. Fixes #3908 * update changelog * schedule timeoutCommit if StartTime is in the future or SkipTimeoutCommit=true && we DON'T have all the votes * fix TestReactorCreatesBlockWhenEmptyBlocksFalse by checking if we have LastCommit or not * address Ethan's comments
5 years ago
cs: check for SkipTimeoutCommit or wait timeout in handleTxsAvailable (#3928) * cs: check for SkipTimeoutCommit or wait timeout in handleTxsAvailable Previously, if create_empty_blocks was set to false, TM sometimes could create 2 consecutive blocks without actually waiting for timeoutCommit (1 sec. by default). ``` I[2019-08-29|07:32:43.874] Executed block module=state height=47 validTxs=10 invalidTxs=0 I[2019-08-29|07:32:43.876] Committed state module=state height=47 txs=10 appHash=F88C010000000000 I[2019-08-29|07:32:44.885] Executed block module=state height=48 validTxs=2 invalidTxs=0 I[2019-08-29|07:32:44.887] Committed state module=state height=48 txs=2 appHash=FC8C010000000000 I[2019-08-29|07:32:44.908] Executed block module=state height=49 validTxs=8 invalidTxs=0 I[2019-08-29|07:32:44.909] Committed state module=state height=49 txs=8 appHash=8C8D010000000000 I[2019-08-29|07:32:45.886] Executed block module=state height=50 validTxs=2 invalidTxs=0 I[2019-08-29|07:32:45.895] Committed state module=state height=50 txs=2 appHash=908D010000000000 I[2019-08-29|07:32:45.908] Executed block module=state height=51 validTxs=8 invalidTxs=0 I[2019-08-29|07:32:45.909] Committed state module=state height=51 txs=8 appHash=A08D010000000000 ``` This commit fixes that by adding a check to handleTxsAvailable. Fixes #3908 * update changelog * schedule timeoutCommit if StartTime is in the future or SkipTimeoutCommit=true && we DON'T have all the votes * fix TestReactorCreatesBlockWhenEmptyBlocksFalse by checking if we have LastCommit or not * address Ethan's comments
5 years ago
10 years ago
10 years ago
10 years ago
10 years ago
7 years ago
7 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
10 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
10 years ago
cs: sync WAL more frequently (#3300) As per #3043, this adds a ticker to sync the WAL every 2s while the WAL is running. * Flush WAL every 2s This adds a ticker that flushes the WAL every 2s while the WAL is running. This is related to #3043. * Fix spelling * Increase timeout to 2mins for slower build environments * Make WAL sync interval configurable * Add TODO to replace testChan with more comprehensive testBus * Remove extraneous debug statement * Remove testChan in favour of using system time As per https://github.com/tendermint/tendermint/pull/3300#discussion_r255886586, this removes the `testChan` WAL member and replaces the approach with a system time-oriented one. In this new approach, we keep track of the system time at which each flush and periodic flush successfully occurred. The naming of the various functions is also updated here to be more consistent with "flushing" as opposed to "sync'ing". * Update naming convention and ensure lock for timestamp update * Add Flush method as part of WAL interface Adds a `Flush` method as part of the WAL interface to enforce the idea that we can manually trigger a WAL flush from outside of the WAL. This is employed in the consensus state management to flush the WAL prior to signing votes/proposals, as per https://github.com/tendermint/tendermint/issues/3043#issuecomment-453853630 * Update CHANGELOG_PENDING * Remove mutex approach and replace with DI The dependency injection approach to dealing with testing concerns could allow similar effects to some kind of "testing bus"-based approach. This commit introduces an example of this, where instead of relying on (potentially fragile) timing of things between the code and the test, we inject code into the function under test that can signal the test through a channel. This allows us to avoid the `time.Sleep()`-based approach previously employed. * Update comment on WAL flushing during vote signing Co-Authored-By: thanethomson <connect@thanethomson.com> * Simplify flush interval definition Co-Authored-By: thanethomson <connect@thanethomson.com> * Expand commentary on WAL disk flushing Co-Authored-By: thanethomson <connect@thanethomson.com> * Add broken test to illustrate WAL sync test problem Removes test-related state (dependency injection code) from the WAL data structure and adds test code to illustrate the problem with using `WALGenerateNBlocks` and `wal.SearchForEndHeight` to test periodic sync'ing. * Fix test error messages * Use WAL group buffer size to check for flush A function is added to `libs/autofile/group.go#Group` in order to return the size of the buffered data (i.e. data that has not yet been flushed to disk). The test now checks that, prior to a `time.Sleep`, the group buffer has data in it. After the `time.Sleep` (during which time the periodic flush should have been called), the buffer should be empty. * Remove config root dir removal from #3291 * Add godoc for NewWAL mentioning periodic sync
6 years ago
10 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
3 years ago
10 years ago
10 years ago
8 years ago
7 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
7 years ago
7 years ago
7 years ago
10 years ago
10 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
7 years ago
10 years ago
10 years ago
9 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
10 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
cs: sync WAL more frequently (#3300) As per #3043, this adds a ticker to sync the WAL every 2s while the WAL is running. * Flush WAL every 2s This adds a ticker that flushes the WAL every 2s while the WAL is running. This is related to #3043. * Fix spelling * Increase timeout to 2mins for slower build environments * Make WAL sync interval configurable * Add TODO to replace testChan with more comprehensive testBus * Remove extraneous debug statement * Remove testChan in favour of using system time As per https://github.com/tendermint/tendermint/pull/3300#discussion_r255886586, this removes the `testChan` WAL member and replaces the approach with a system time-oriented one. In this new approach, we keep track of the system time at which each flush and periodic flush successfully occurred. The naming of the various functions is also updated here to be more consistent with "flushing" as opposed to "sync'ing". * Update naming convention and ensure lock for timestamp update * Add Flush method as part of WAL interface Adds a `Flush` method as part of the WAL interface to enforce the idea that we can manually trigger a WAL flush from outside of the WAL. This is employed in the consensus state management to flush the WAL prior to signing votes/proposals, as per https://github.com/tendermint/tendermint/issues/3043#issuecomment-453853630 * Update CHANGELOG_PENDING * Remove mutex approach and replace with DI The dependency injection approach to dealing with testing concerns could allow similar effects to some kind of "testing bus"-based approach. This commit introduces an example of this, where instead of relying on (potentially fragile) timing of things between the code and the test, we inject code into the function under test that can signal the test through a channel. This allows us to avoid the `time.Sleep()`-based approach previously employed. * Update comment on WAL flushing during vote signing Co-Authored-By: thanethomson <connect@thanethomson.com> * Simplify flush interval definition Co-Authored-By: thanethomson <connect@thanethomson.com> * Expand commentary on WAL disk flushing Co-Authored-By: thanethomson <connect@thanethomson.com> * Add broken test to illustrate WAL sync test problem Removes test-related state (dependency injection code) from the WAL data structure and adds test code to illustrate the problem with using `WALGenerateNBlocks` and `wal.SearchForEndHeight` to test periodic sync'ing. * Fix test error messages * Use WAL group buffer size to check for flush A function is added to `libs/autofile/group.go#Group` in order to return the size of the buffered data (i.e. data that has not yet been flushed to disk). The test now checks that, prior to a `time.Sleep`, the group buffer has data in it. After the `time.Sleep` (during which time the periodic flush should have been called), the buffer should be empty. * Remove config root dir removal from #3291 * Add godoc for NewWAL mentioning periodic sync
6 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
10 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. package consensus
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "os"
  10. "runtime/debug"
  11. "sort"
  12. "sync"
  13. "time"
  14. "github.com/gogo/protobuf/proto"
  15. "github.com/tendermint/tendermint/config"
  16. "github.com/tendermint/tendermint/crypto"
  17. cstypes "github.com/tendermint/tendermint/internal/consensus/types"
  18. "github.com/tendermint/tendermint/internal/eventbus"
  19. "github.com/tendermint/tendermint/internal/jsontypes"
  20. sm "github.com/tendermint/tendermint/internal/state"
  21. tmevents "github.com/tendermint/tendermint/libs/events"
  22. "github.com/tendermint/tendermint/libs/log"
  23. tmmath "github.com/tendermint/tendermint/libs/math"
  24. tmos "github.com/tendermint/tendermint/libs/os"
  25. "github.com/tendermint/tendermint/libs/service"
  26. tmtime "github.com/tendermint/tendermint/libs/time"
  27. "github.com/tendermint/tendermint/privval"
  28. tmgrpc "github.com/tendermint/tendermint/privval/grpc"
  29. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  30. "github.com/tendermint/tendermint/types"
  31. )
  32. // Consensus sentinel errors
  33. var (
  34. ErrInvalidProposalSignature = errors.New("error invalid proposal signature")
  35. ErrInvalidProposalPOLRound = errors.New("error invalid proposal POL round")
  36. ErrAddingVote = errors.New("error adding vote")
  37. ErrSignatureFoundInPastBlocks = errors.New("found signature from the same key")
  38. errPubKeyIsNotSet = errors.New("pubkey is not set. Look for \"Can't get private validator pubkey\" errors")
  39. )
  40. var msgQueueSize = 1000
  41. // msgs from the reactor which may update the state
  42. type msgInfo struct {
  43. Msg Message
  44. PeerID types.NodeID
  45. ReceiveTime time.Time
  46. }
  47. func (msgInfo) TypeTag() string { return "tendermint/wal/MsgInfo" }
  48. type msgInfoJSON struct {
  49. Msg json.RawMessage `json:"msg"`
  50. PeerID types.NodeID `json:"peer_key"`
  51. ReceiveTime time.Time `json:"receive_time"`
  52. }
  53. func (m msgInfo) MarshalJSON() ([]byte, error) {
  54. msg, err := jsontypes.Marshal(m.Msg)
  55. if err != nil {
  56. return nil, err
  57. }
  58. return json.Marshal(msgInfoJSON{Msg: msg, PeerID: m.PeerID, ReceiveTime: m.ReceiveTime})
  59. }
  60. func (m *msgInfo) UnmarshalJSON(data []byte) error {
  61. var msg msgInfoJSON
  62. if err := json.Unmarshal(data, &msg); err != nil {
  63. return err
  64. }
  65. if err := jsontypes.Unmarshal(msg.Msg, &m.Msg); err != nil {
  66. return err
  67. }
  68. m.PeerID = msg.PeerID
  69. return nil
  70. }
  71. // internally generated messages which may update the state
  72. type timeoutInfo struct {
  73. Duration time.Duration `json:"duration,string"`
  74. Height int64 `json:"height,string"`
  75. Round int32 `json:"round"`
  76. Step cstypes.RoundStepType `json:"step"`
  77. }
  78. func (timeoutInfo) TypeTag() string { return "tendermint/wal/TimeoutInfo" }
  79. func (ti *timeoutInfo) String() string {
  80. return fmt.Sprintf("%v ; %d/%d %v", ti.Duration, ti.Height, ti.Round, ti.Step)
  81. }
  82. // interface to the mempool
  83. type txNotifier interface {
  84. TxsAvailable() <-chan struct{}
  85. }
  86. // interface to the evidence pool
  87. type evidencePool interface {
  88. // reports conflicting votes to the evidence pool to be processed into evidence
  89. ReportConflictingVotes(voteA, voteB *types.Vote)
  90. }
  91. // State handles execution of the consensus algorithm.
  92. // It processes votes and proposals, and upon reaching agreement,
  93. // commits blocks to the chain and executes them against the application.
  94. // The internal state machine receives input from peers, the internal validator, and from a timer.
  95. type State struct {
  96. service.BaseService
  97. logger log.Logger
  98. // config details
  99. config *config.ConsensusConfig
  100. privValidator types.PrivValidator // for signing votes
  101. privValidatorType types.PrivValidatorType
  102. // store blocks and commits
  103. blockStore sm.BlockStore
  104. // create and execute blocks
  105. blockExec *sm.BlockExecutor
  106. // notify us if txs are available
  107. txNotifier txNotifier
  108. // add evidence to the pool
  109. // when it's detected
  110. evpool evidencePool
  111. // internal state
  112. mtx sync.RWMutex
  113. cstypes.RoundState
  114. state sm.State // State until height-1.
  115. // privValidator pubkey, memoized for the duration of one block
  116. // to avoid extra requests to HSM
  117. privValidatorPubKey crypto.PubKey
  118. // state changes may be triggered by: msgs from peers,
  119. // msgs from ourself, or by timeouts
  120. peerMsgQueue chan msgInfo
  121. internalMsgQueue chan msgInfo
  122. timeoutTicker TimeoutTicker
  123. // information about about added votes and block parts are written on this channel
  124. // so statistics can be computed by reactor
  125. statsMsgQueue chan msgInfo
  126. // we use eventBus to trigger msg broadcasts in the reactor,
  127. // and to notify external subscribers, eg. through a websocket
  128. eventBus *eventbus.EventBus
  129. // a Write-Ahead Log ensures we can recover from any kind of crash
  130. // and helps us avoid signing conflicting votes
  131. wal WAL
  132. replayMode bool // so we don't log signing errors during replay
  133. doWALCatchup bool // determines if we even try to do the catchup
  134. // for tests where we want to limit the number of transitions the state makes
  135. nSteps int
  136. // some functions can be overwritten for testing
  137. decideProposal func(ctx context.Context, height int64, round int32)
  138. doPrevote func(ctx context.Context, height int64, round int32)
  139. setProposal func(proposal *types.Proposal, t time.Time) error
  140. // closed when we finish shutting down
  141. done chan struct{}
  142. // synchronous pubsub between consensus state and reactor.
  143. // state only emits EventNewRoundStep, EventValidBlock, and EventVote
  144. evsw tmevents.EventSwitch
  145. // for reporting metrics
  146. metrics *Metrics
  147. // wait the channel event happening for shutting down the state gracefully
  148. onStopCh chan *cstypes.RoundState
  149. }
  150. // StateOption sets an optional parameter on the State.
  151. type StateOption func(*State)
  152. // NewState returns a new State.
  153. func NewState(
  154. ctx context.Context,
  155. logger log.Logger,
  156. cfg *config.ConsensusConfig,
  157. state sm.State,
  158. blockExec *sm.BlockExecutor,
  159. blockStore sm.BlockStore,
  160. txNotifier txNotifier,
  161. evpool evidencePool,
  162. options ...StateOption,
  163. ) *State {
  164. cs := &State{
  165. logger: logger,
  166. config: cfg,
  167. blockExec: blockExec,
  168. blockStore: blockStore,
  169. txNotifier: txNotifier,
  170. peerMsgQueue: make(chan msgInfo, msgQueueSize),
  171. internalMsgQueue: make(chan msgInfo, msgQueueSize),
  172. timeoutTicker: NewTimeoutTicker(logger),
  173. statsMsgQueue: make(chan msgInfo, msgQueueSize),
  174. done: make(chan struct{}),
  175. doWALCatchup: true,
  176. wal: nilWAL{},
  177. evpool: evpool,
  178. evsw: tmevents.NewEventSwitch(logger),
  179. metrics: NopMetrics(),
  180. onStopCh: make(chan *cstypes.RoundState),
  181. }
  182. // set function defaults (may be overwritten before calling Start)
  183. cs.decideProposal = cs.defaultDecideProposal
  184. cs.doPrevote = cs.defaultDoPrevote
  185. cs.setProposal = cs.defaultSetProposal
  186. // We have no votes, so reconstruct LastCommit from SeenCommit.
  187. if state.LastBlockHeight > 0 {
  188. cs.reconstructLastCommit(state)
  189. }
  190. cs.updateToState(ctx, state)
  191. // NOTE: we do not call scheduleRound0 yet, we do that upon Start()
  192. cs.BaseService = *service.NewBaseService(logger, "State", cs)
  193. for _, option := range options {
  194. option(cs)
  195. }
  196. return cs
  197. }
  198. // SetEventBus sets event bus.
  199. func (cs *State) SetEventBus(b *eventbus.EventBus) {
  200. cs.eventBus = b
  201. cs.blockExec.SetEventBus(b)
  202. }
  203. // StateMetrics sets the metrics.
  204. func StateMetrics(metrics *Metrics) StateOption {
  205. return func(cs *State) { cs.metrics = metrics }
  206. }
  207. // String returns a string.
  208. func (cs *State) String() string {
  209. // better not to access shared variables
  210. return "ConsensusState"
  211. }
  212. // GetState returns a copy of the chain state.
  213. func (cs *State) GetState() sm.State {
  214. cs.mtx.RLock()
  215. defer cs.mtx.RUnlock()
  216. return cs.state.Copy()
  217. }
  218. // GetLastHeight returns the last height committed.
  219. // If there were no blocks, returns 0.
  220. func (cs *State) GetLastHeight() int64 {
  221. cs.mtx.RLock()
  222. defer cs.mtx.RUnlock()
  223. return cs.RoundState.Height - 1
  224. }
  225. // GetRoundState returns a shallow copy of the internal consensus state.
  226. func (cs *State) GetRoundState() *cstypes.RoundState {
  227. cs.mtx.RLock()
  228. defer cs.mtx.RUnlock()
  229. // NOTE: this might be dodgy, as RoundState itself isn't thread
  230. // safe as it contains a number of pointers and is explicitly
  231. // not thread safe.
  232. rs := cs.RoundState // copy
  233. return &rs
  234. }
  235. // GetRoundStateJSON returns a json of RoundState.
  236. func (cs *State) GetRoundStateJSON() ([]byte, error) {
  237. cs.mtx.RLock()
  238. defer cs.mtx.RUnlock()
  239. return json.Marshal(cs.RoundState)
  240. }
  241. // GetRoundStateSimpleJSON returns a json of RoundStateSimple
  242. func (cs *State) GetRoundStateSimpleJSON() ([]byte, error) {
  243. cs.mtx.RLock()
  244. defer cs.mtx.RUnlock()
  245. return json.Marshal(cs.RoundState.RoundStateSimple())
  246. }
  247. // GetValidators returns a copy of the current validators.
  248. func (cs *State) GetValidators() (int64, []*types.Validator) {
  249. cs.mtx.RLock()
  250. defer cs.mtx.RUnlock()
  251. return cs.state.LastBlockHeight, cs.state.Validators.Copy().Validators
  252. }
  253. // SetPrivValidator sets the private validator account for signing votes. It
  254. // immediately requests pubkey and caches it.
  255. func (cs *State) SetPrivValidator(ctx context.Context, priv types.PrivValidator) {
  256. cs.mtx.Lock()
  257. defer cs.mtx.Unlock()
  258. cs.privValidator = priv
  259. if priv != nil {
  260. switch t := priv.(type) {
  261. case *privval.RetrySignerClient:
  262. cs.privValidatorType = types.RetrySignerClient
  263. case *privval.FilePV:
  264. cs.privValidatorType = types.FileSignerClient
  265. case *privval.SignerClient:
  266. cs.privValidatorType = types.SignerSocketClient
  267. case *tmgrpc.SignerClient:
  268. cs.privValidatorType = types.SignerGRPCClient
  269. case types.MockPV:
  270. cs.privValidatorType = types.MockSignerClient
  271. case *types.ErroringMockPV:
  272. cs.privValidatorType = types.ErrorMockSignerClient
  273. default:
  274. cs.logger.Error("unsupported priv validator type", "err",
  275. fmt.Errorf("error privValidatorType %s", t))
  276. }
  277. }
  278. if err := cs.updatePrivValidatorPubKey(ctx); err != nil {
  279. cs.logger.Error("failed to get private validator pubkey", "err", err)
  280. }
  281. }
  282. // SetTimeoutTicker sets the local timer. It may be useful to overwrite for
  283. // testing.
  284. func (cs *State) SetTimeoutTicker(timeoutTicker TimeoutTicker) {
  285. cs.mtx.Lock()
  286. cs.timeoutTicker = timeoutTicker
  287. cs.mtx.Unlock()
  288. }
  289. // LoadCommit loads the commit for a given height.
  290. func (cs *State) LoadCommit(height int64) *types.Commit {
  291. cs.mtx.RLock()
  292. defer cs.mtx.RUnlock()
  293. if height == cs.blockStore.Height() {
  294. commit := cs.blockStore.LoadSeenCommit()
  295. // NOTE: Retrieving the height of the most recent block and retrieving
  296. // the most recent commit does not currently occur as an atomic
  297. // operation. We check the height and commit here in case a more recent
  298. // commit has arrived since retrieving the latest height.
  299. if commit != nil && commit.Height == height {
  300. return commit
  301. }
  302. }
  303. return cs.blockStore.LoadBlockCommit(height)
  304. }
  305. // OnStart loads the latest state via the WAL, and starts the timeout and
  306. // receive routines.
  307. func (cs *State) OnStart(ctx context.Context) error {
  308. // We may set the WAL in testing before calling Start, so only OpenWAL if its
  309. // still the nilWAL.
  310. if _, ok := cs.wal.(nilWAL); ok {
  311. if err := cs.loadWalFile(ctx); err != nil {
  312. return err
  313. }
  314. }
  315. // We may have lost some votes if the process crashed reload from consensus
  316. // log to catchup.
  317. if cs.doWALCatchup {
  318. repairAttempted := false
  319. LOOP:
  320. for {
  321. err := cs.catchupReplay(ctx, cs.Height)
  322. switch {
  323. case err == nil:
  324. break LOOP
  325. case !IsDataCorruptionError(err):
  326. cs.logger.Error("error on catchup replay; proceeding to start state anyway", "err", err)
  327. break LOOP
  328. case repairAttempted:
  329. return err
  330. }
  331. cs.logger.Error("the WAL file is corrupted; attempting repair", "err", err)
  332. // 1) prep work
  333. if err := cs.wal.Stop(); err != nil {
  334. return err
  335. }
  336. repairAttempted = true
  337. // 2) backup original WAL file
  338. corruptedFile := fmt.Sprintf("%s.CORRUPTED", cs.config.WalFile())
  339. if err := tmos.CopyFile(cs.config.WalFile(), corruptedFile); err != nil {
  340. return err
  341. }
  342. cs.logger.Debug("backed up WAL file", "src", cs.config.WalFile(), "dst", corruptedFile)
  343. // 3) try to repair (WAL file will be overwritten!)
  344. if err := repairWalFile(corruptedFile, cs.config.WalFile()); err != nil {
  345. cs.logger.Error("the WAL repair failed", "err", err)
  346. return err
  347. }
  348. cs.logger.Info("successful WAL repair")
  349. // reload WAL file
  350. if err := cs.loadWalFile(ctx); err != nil {
  351. return err
  352. }
  353. }
  354. }
  355. if err := cs.evsw.Start(ctx); err != nil {
  356. return err
  357. }
  358. // we need the timeoutRoutine for replay so
  359. // we don't block on the tick chan.
  360. // NOTE: we will get a build up of garbage go routines
  361. // firing on the tockChan until the receiveRoutine is started
  362. // to deal with them (by that point, at most one will be valid)
  363. if err := cs.timeoutTicker.Start(ctx); err != nil {
  364. return err
  365. }
  366. // Double Signing Risk Reduction
  367. if err := cs.checkDoubleSigningRisk(cs.Height); err != nil {
  368. return err
  369. }
  370. // now start the receiveRoutine
  371. go cs.receiveRoutine(ctx, 0)
  372. // schedule the first round!
  373. // use GetRoundState so we don't race the receiveRoutine for access
  374. cs.scheduleRound0(cs.GetRoundState())
  375. return nil
  376. }
  377. // timeoutRoutine: receive requests for timeouts on tickChan and fire timeouts on tockChan
  378. // receiveRoutine: serializes processing of proposoals, block parts, votes; coordinates state transitions
  379. //
  380. // this is only used in tests.
  381. func (cs *State) startRoutines(ctx context.Context, maxSteps int) {
  382. err := cs.timeoutTicker.Start(ctx)
  383. if err != nil {
  384. cs.logger.Error("failed to start timeout ticker", "err", err)
  385. return
  386. }
  387. go cs.receiveRoutine(ctx, maxSteps)
  388. }
  389. // loadWalFile loads WAL data from file. It overwrites cs.wal.
  390. func (cs *State) loadWalFile(ctx context.Context) error {
  391. wal, err := cs.OpenWAL(ctx, cs.config.WalFile())
  392. if err != nil {
  393. cs.logger.Error("failed to load state WAL", "err", err)
  394. return err
  395. }
  396. cs.wal = wal
  397. return nil
  398. }
  399. // OnStop implements service.Service.
  400. func (cs *State) OnStop() {
  401. // If the node is committing a new block, wait until it is finished!
  402. if cs.GetRoundState().Step == cstypes.RoundStepCommit {
  403. select {
  404. case <-cs.onStopCh:
  405. case <-time.After(cs.config.TimeoutCommit):
  406. cs.logger.Error("OnStop: timeout waiting for commit to finish", "time", cs.config.TimeoutCommit)
  407. }
  408. }
  409. close(cs.onStopCh)
  410. if cs.evsw.IsRunning() {
  411. if err := cs.evsw.Stop(); err != nil {
  412. if !errors.Is(err, service.ErrAlreadyStopped) {
  413. cs.logger.Error("failed trying to stop eventSwitch", "error", err)
  414. }
  415. }
  416. }
  417. if cs.timeoutTicker.IsRunning() {
  418. if err := cs.timeoutTicker.Stop(); err != nil {
  419. if !errors.Is(err, service.ErrAlreadyStopped) {
  420. cs.logger.Error("failed trying to stop timeoutTicket", "error", err)
  421. }
  422. }
  423. }
  424. // WAL is stopped in receiveRoutine.
  425. }
  426. // Wait waits for the the main routine to return.
  427. // NOTE: be sure to Stop() the event switch and drain
  428. // any event channels or this may deadlock
  429. func (cs *State) Wait() {
  430. <-cs.done
  431. }
  432. // OpenWAL opens a file to log all consensus messages and timeouts for
  433. // deterministic accountability.
  434. func (cs *State) OpenWAL(ctx context.Context, walFile string) (WAL, error) {
  435. wal, err := NewWAL(ctx, cs.logger.With("wal", walFile), walFile)
  436. if err != nil {
  437. cs.logger.Error("failed to open WAL", "file", walFile, "err", err)
  438. return nil, err
  439. }
  440. if err := wal.Start(ctx); err != nil {
  441. cs.logger.Error("failed to start WAL", "err", err)
  442. return nil, err
  443. }
  444. return wal, nil
  445. }
  446. //------------------------------------------------------------
  447. // Public interface for passing messages into the consensus state, possibly causing a state transition.
  448. // If peerID == "", the msg is considered internal.
  449. // Messages are added to the appropriate queue (peer or internal).
  450. // If the queue is full, the function may block.
  451. // TODO: should these return anything or let callers just use events?
  452. // AddVote inputs a vote.
  453. func (cs *State) AddVote(ctx context.Context, vote *types.Vote, peerID types.NodeID) error {
  454. if peerID == "" {
  455. select {
  456. case <-ctx.Done():
  457. return ctx.Err()
  458. case cs.internalMsgQueue <- msgInfo{&VoteMessage{vote}, "", tmtime.Now()}:
  459. return nil
  460. }
  461. } else {
  462. select {
  463. case <-ctx.Done():
  464. return ctx.Err()
  465. case cs.peerMsgQueue <- msgInfo{&VoteMessage{vote}, peerID, tmtime.Now()}:
  466. return nil
  467. }
  468. }
  469. // TODO: wait for event?!
  470. }
  471. // SetProposal inputs a proposal.
  472. func (cs *State) SetProposal(ctx context.Context, proposal *types.Proposal, peerID types.NodeID) error {
  473. if peerID == "" {
  474. select {
  475. case <-ctx.Done():
  476. return ctx.Err()
  477. case cs.internalMsgQueue <- msgInfo{&ProposalMessage{proposal}, "", tmtime.Now()}:
  478. return nil
  479. }
  480. } else {
  481. select {
  482. case <-ctx.Done():
  483. return ctx.Err()
  484. case cs.peerMsgQueue <- msgInfo{&ProposalMessage{proposal}, peerID, tmtime.Now()}:
  485. return nil
  486. }
  487. }
  488. // TODO: wait for event?!
  489. }
  490. // AddProposalBlockPart inputs a part of the proposal block.
  491. func (cs *State) AddProposalBlockPart(ctx context.Context, height int64, round int32, part *types.Part, peerID types.NodeID) error {
  492. if peerID == "" {
  493. select {
  494. case <-ctx.Done():
  495. return ctx.Err()
  496. case cs.internalMsgQueue <- msgInfo{&BlockPartMessage{height, round, part}, "", tmtime.Now()}:
  497. return nil
  498. }
  499. } else {
  500. select {
  501. case <-ctx.Done():
  502. return ctx.Err()
  503. case cs.peerMsgQueue <- msgInfo{&BlockPartMessage{height, round, part}, peerID, tmtime.Now()}:
  504. return nil
  505. }
  506. }
  507. // TODO: wait for event?!
  508. }
  509. // SetProposalAndBlock inputs the proposal and all block parts.
  510. func (cs *State) SetProposalAndBlock(
  511. ctx context.Context,
  512. proposal *types.Proposal,
  513. block *types.Block,
  514. parts *types.PartSet,
  515. peerID types.NodeID,
  516. ) error {
  517. if err := cs.SetProposal(ctx, proposal, peerID); err != nil {
  518. return err
  519. }
  520. for i := 0; i < int(parts.Total()); i++ {
  521. part := parts.GetPart(i)
  522. if err := cs.AddProposalBlockPart(ctx, proposal.Height, proposal.Round, part, peerID); err != nil {
  523. return err
  524. }
  525. }
  526. return nil
  527. }
  528. //------------------------------------------------------------
  529. // internal functions for managing the state
  530. func (cs *State) updateHeight(height int64) {
  531. cs.metrics.Height.Set(float64(height))
  532. cs.Height = height
  533. }
  534. func (cs *State) updateRoundStep(round int32, step cstypes.RoundStepType) {
  535. cs.Round = round
  536. cs.Step = step
  537. }
  538. // enterNewRound(height, 0) at cs.StartTime.
  539. func (cs *State) scheduleRound0(rs *cstypes.RoundState) {
  540. // cs.logger.Info("scheduleRound0", "now", tmtime.Now(), "startTime", cs.StartTime)
  541. sleepDuration := rs.StartTime.Sub(tmtime.Now())
  542. cs.scheduleTimeout(sleepDuration, rs.Height, 0, cstypes.RoundStepNewHeight)
  543. }
  544. // Attempt to schedule a timeout (by sending timeoutInfo on the tickChan)
  545. func (cs *State) scheduleTimeout(duration time.Duration, height int64, round int32, step cstypes.RoundStepType) {
  546. cs.timeoutTicker.ScheduleTimeout(timeoutInfo{duration, height, round, step})
  547. }
  548. // send a msg into the receiveRoutine regarding our own proposal, block part, or vote
  549. func (cs *State) sendInternalMessage(ctx context.Context, mi msgInfo) {
  550. select {
  551. case <-ctx.Done():
  552. case cs.internalMsgQueue <- mi:
  553. default:
  554. // NOTE: using the go-routine means our votes can
  555. // be processed out of order.
  556. // TODO: use CList here for strict determinism and
  557. // attempt push to internalMsgQueue in receiveRoutine
  558. cs.logger.Debug("internal msg queue is full; using a go-routine")
  559. go func() {
  560. select {
  561. case <-ctx.Done():
  562. case cs.internalMsgQueue <- mi:
  563. }
  564. }()
  565. }
  566. }
  567. // Reconstruct LastCommit from SeenCommit, which we saved along with the block,
  568. // (which happens even before saving the state)
  569. func (cs *State) reconstructLastCommit(state sm.State) {
  570. commit := cs.blockStore.LoadSeenCommit()
  571. if commit == nil || commit.Height != state.LastBlockHeight {
  572. commit = cs.blockStore.LoadBlockCommit(state.LastBlockHeight)
  573. }
  574. if commit == nil {
  575. panic(fmt.Sprintf(
  576. "failed to reconstruct last commit; commit for height %v not found",
  577. state.LastBlockHeight,
  578. ))
  579. }
  580. lastPrecommits := types.CommitToVoteSet(state.ChainID, commit, state.LastValidators)
  581. if !lastPrecommits.HasTwoThirdsMajority() {
  582. panic("failed to reconstruct last commit; does not have +2/3 maj")
  583. }
  584. cs.LastCommit = lastPrecommits
  585. }
  586. // Updates State and increments height to match that of state.
  587. // The round becomes 0 and cs.Step becomes cstypes.RoundStepNewHeight.
  588. func (cs *State) updateToState(ctx context.Context, state sm.State) {
  589. if cs.CommitRound > -1 && 0 < cs.Height && cs.Height != state.LastBlockHeight {
  590. panic(fmt.Sprintf(
  591. "updateToState() expected state height of %v but found %v",
  592. cs.Height, state.LastBlockHeight,
  593. ))
  594. }
  595. if !cs.state.IsEmpty() {
  596. if cs.state.LastBlockHeight > 0 && cs.state.LastBlockHeight+1 != cs.Height {
  597. // This might happen when someone else is mutating cs.state.
  598. // Someone forgot to pass in state.Copy() somewhere?!
  599. panic(fmt.Sprintf(
  600. "inconsistent cs.state.LastBlockHeight+1 %v vs cs.Height %v",
  601. cs.state.LastBlockHeight+1, cs.Height,
  602. ))
  603. }
  604. if cs.state.LastBlockHeight > 0 && cs.Height == cs.state.InitialHeight {
  605. panic(fmt.Sprintf(
  606. "inconsistent cs.state.LastBlockHeight %v, expected 0 for initial height %v",
  607. cs.state.LastBlockHeight, cs.state.InitialHeight,
  608. ))
  609. }
  610. // If state isn't further out than cs.state, just ignore.
  611. // This happens when SwitchToConsensus() is called in the reactor.
  612. // We don't want to reset e.g. the Votes, but we still want to
  613. // signal the new round step, because other services (eg. txNotifier)
  614. // depend on having an up-to-date peer state!
  615. if state.LastBlockHeight <= cs.state.LastBlockHeight {
  616. cs.logger.Debug(
  617. "ignoring updateToState()",
  618. "new_height", state.LastBlockHeight+1,
  619. "old_height", cs.state.LastBlockHeight+1,
  620. )
  621. cs.newStep(ctx)
  622. return
  623. }
  624. }
  625. // Reset fields based on state.
  626. validators := state.Validators
  627. switch {
  628. case state.LastBlockHeight == 0: // Very first commit should be empty.
  629. cs.LastCommit = (*types.VoteSet)(nil)
  630. case cs.CommitRound > -1 && cs.Votes != nil: // Otherwise, use cs.Votes
  631. if !cs.Votes.Precommits(cs.CommitRound).HasTwoThirdsMajority() {
  632. panic(fmt.Sprintf(
  633. "wanted to form a commit, but precommits (H/R: %d/%d) didn't have 2/3+: %v",
  634. state.LastBlockHeight, cs.CommitRound, cs.Votes.Precommits(cs.CommitRound),
  635. ))
  636. }
  637. cs.LastCommit = cs.Votes.Precommits(cs.CommitRound)
  638. case cs.LastCommit == nil:
  639. // NOTE: when Tendermint starts, it has no votes. reconstructLastCommit
  640. // must be called to reconstruct LastCommit from SeenCommit.
  641. panic(fmt.Sprintf(
  642. "last commit cannot be empty after initial block (H:%d)",
  643. state.LastBlockHeight+1,
  644. ))
  645. }
  646. // Next desired block height
  647. height := state.LastBlockHeight + 1
  648. if height == 1 {
  649. height = state.InitialHeight
  650. }
  651. // RoundState fields
  652. cs.updateHeight(height)
  653. cs.updateRoundStep(0, cstypes.RoundStepNewHeight)
  654. if cs.CommitTime.IsZero() {
  655. // "Now" makes it easier to sync up dev nodes.
  656. // We add timeoutCommit to allow transactions
  657. // to be gathered for the first block.
  658. // And alternative solution that relies on clocks:
  659. // cs.StartTime = state.LastBlockTime.Add(timeoutCommit)
  660. cs.StartTime = cs.config.Commit(tmtime.Now())
  661. } else {
  662. cs.StartTime = cs.config.Commit(cs.CommitTime)
  663. }
  664. cs.Validators = validators
  665. cs.Proposal = nil
  666. cs.ProposalReceiveTime = time.Time{}
  667. cs.ProposalBlock = nil
  668. cs.ProposalBlockParts = nil
  669. cs.LockedRound = -1
  670. cs.LockedBlock = nil
  671. cs.LockedBlockParts = nil
  672. cs.ValidRound = -1
  673. cs.ValidBlock = nil
  674. cs.ValidBlockParts = nil
  675. cs.Votes = cstypes.NewHeightVoteSet(state.ChainID, height, validators)
  676. cs.CommitRound = -1
  677. cs.LastValidators = state.LastValidators
  678. cs.TriggeredTimeoutPrecommit = false
  679. cs.state = state
  680. // Finally, broadcast RoundState
  681. cs.newStep(ctx)
  682. }
  683. func (cs *State) newStep(ctx context.Context) {
  684. rs := cs.RoundStateEvent()
  685. if err := cs.wal.Write(rs); err != nil {
  686. cs.logger.Error("failed writing to WAL", "err", err)
  687. }
  688. cs.nSteps++
  689. // newStep is called by updateToState in NewState before the eventBus is set!
  690. if cs.eventBus != nil {
  691. if err := cs.eventBus.PublishEventNewRoundStep(ctx, rs); err != nil {
  692. cs.logger.Error("failed publishing new round step", "err", err)
  693. }
  694. cs.evsw.FireEvent(ctx, types.EventNewRoundStepValue, &cs.RoundState)
  695. }
  696. }
  697. //-----------------------------------------
  698. // the main go routines
  699. // receiveRoutine handles messages which may cause state transitions.
  700. // it's argument (n) is the number of messages to process before exiting - use 0 to run forever
  701. // It keeps the RoundState and is the only thing that updates it.
  702. // Updates (state transitions) happen on timeouts, complete proposals, and 2/3 majorities.
  703. // State must be locked before any internal state is updated.
  704. func (cs *State) receiveRoutine(ctx context.Context, maxSteps int) {
  705. onExit := func(cs *State) {
  706. // NOTE: the internalMsgQueue may have signed messages from our
  707. // priv_val that haven't hit the WAL, but its ok because
  708. // priv_val tracks LastSig
  709. // close wal now that we're done writing to it
  710. if err := cs.wal.Stop(); err != nil {
  711. if !errors.Is(err, service.ErrAlreadyStopped) {
  712. cs.logger.Error("failed trying to stop WAL", "error", err)
  713. }
  714. }
  715. cs.wal.Wait()
  716. close(cs.done)
  717. }
  718. defer func() {
  719. if r := recover(); r != nil {
  720. cs.logger.Error("CONSENSUS FAILURE!!!", "err", r, "stack", string(debug.Stack()))
  721. // stop gracefully
  722. //
  723. // NOTE: We most probably shouldn't be running any further when there is
  724. // some unexpected panic. Some unknown error happened, and so we don't
  725. // know if that will result in the validator signing an invalid thing. It
  726. // might be worthwhile to explore a mechanism for manual resuming via
  727. // some console or secure RPC system, but for now, halting the chain upon
  728. // unexpected consensus bugs sounds like the better option.
  729. onExit(cs)
  730. }
  731. }()
  732. for {
  733. if maxSteps > 0 {
  734. if cs.nSteps >= maxSteps {
  735. cs.logger.Debug("reached max steps; exiting receive routine")
  736. cs.nSteps = 0
  737. return
  738. }
  739. }
  740. rs := cs.RoundState
  741. var mi msgInfo
  742. select {
  743. case <-cs.txNotifier.TxsAvailable():
  744. cs.handleTxsAvailable(ctx)
  745. case mi = <-cs.peerMsgQueue:
  746. if err := cs.wal.Write(mi); err != nil {
  747. cs.logger.Error("failed writing to WAL", "err", err)
  748. }
  749. // handles proposals, block parts, votes
  750. // may generate internal events (votes, complete proposals, 2/3 majorities)
  751. cs.handleMsg(ctx, mi)
  752. case mi = <-cs.internalMsgQueue:
  753. err := cs.wal.WriteSync(mi) // NOTE: fsync
  754. if err != nil {
  755. panic(fmt.Sprintf(
  756. "failed to write %v msg to consensus WAL due to %v; check your file system and restart the node",
  757. mi, err,
  758. ))
  759. }
  760. // handles proposals, block parts, votes
  761. cs.handleMsg(ctx, mi)
  762. case ti := <-cs.timeoutTicker.Chan(): // tockChan:
  763. if err := cs.wal.Write(ti); err != nil {
  764. cs.logger.Error("failed writing to WAL", "err", err)
  765. }
  766. // if the timeout is relevant to the rs
  767. // go to the next step
  768. cs.handleTimeout(ctx, ti, rs)
  769. case <-ctx.Done():
  770. onExit(cs)
  771. return
  772. }
  773. // TODO should we handle context cancels here?
  774. }
  775. }
  776. // state transitions on complete-proposal, 2/3-any, 2/3-one
  777. func (cs *State) handleMsg(ctx context.Context, mi msgInfo) {
  778. cs.mtx.Lock()
  779. defer cs.mtx.Unlock()
  780. var (
  781. added bool
  782. err error
  783. )
  784. msg, peerID := mi.Msg, mi.PeerID
  785. switch msg := msg.(type) {
  786. case *ProposalMessage:
  787. // will not cause transition.
  788. // once proposal is set, we can receive block parts
  789. err = cs.setProposal(msg.Proposal, mi.ReceiveTime)
  790. case *BlockPartMessage:
  791. // if the proposal is complete, we'll enterPrevote or tryFinalizeCommit
  792. added, err = cs.addProposalBlockPart(ctx, msg, peerID)
  793. if added {
  794. select {
  795. case cs.statsMsgQueue <- mi:
  796. case <-ctx.Done():
  797. return
  798. }
  799. }
  800. if err != nil && msg.Round != cs.Round {
  801. cs.logger.Debug(
  802. "received block part from wrong round",
  803. "height", cs.Height,
  804. "cs_round", cs.Round,
  805. "block_round", msg.Round,
  806. )
  807. err = nil
  808. }
  809. case *VoteMessage:
  810. // attempt to add the vote and dupeout the validator if its a duplicate signature
  811. // if the vote gives us a 2/3-any or 2/3-one, we transition
  812. added, err = cs.tryAddVote(ctx, msg.Vote, peerID)
  813. if added {
  814. select {
  815. case cs.statsMsgQueue <- mi:
  816. case <-ctx.Done():
  817. return
  818. }
  819. }
  820. // if err == ErrAddingVote {
  821. // TODO: punish peer
  822. // We probably don't want to stop the peer here. The vote does not
  823. // necessarily comes from a malicious peer but can be just broadcasted by
  824. // a typical peer.
  825. // https://github.com/tendermint/tendermint/issues/1281
  826. // }
  827. // NOTE: the vote is broadcast to peers by the reactor listening
  828. // for vote events
  829. // TODO: If rs.Height == vote.Height && rs.Round < vote.Round,
  830. // the peer is sending us CatchupCommit precommits.
  831. // We could make note of this and help filter in broadcastHasVoteMessage().
  832. default:
  833. cs.logger.Error("unknown msg type", "type", fmt.Sprintf("%T", msg))
  834. return
  835. }
  836. if err != nil {
  837. cs.logger.Error(
  838. "failed to process message",
  839. "height", cs.Height,
  840. "round", cs.Round,
  841. "peer", peerID,
  842. "msg_type", fmt.Sprintf("%T", msg),
  843. "err", err,
  844. )
  845. }
  846. }
  847. func (cs *State) handleTimeout(
  848. ctx context.Context,
  849. ti timeoutInfo,
  850. rs cstypes.RoundState,
  851. ) {
  852. cs.logger.Debug("received tock", "timeout", ti.Duration, "height", ti.Height, "round", ti.Round, "step", ti.Step)
  853. // timeouts must be for current height, round, step
  854. if ti.Height != rs.Height || ti.Round < rs.Round || (ti.Round == rs.Round && ti.Step < rs.Step) {
  855. cs.logger.Debug("ignoring tock because we are ahead", "height", rs.Height, "round", rs.Round, "step", rs.Step)
  856. return
  857. }
  858. // the timeout will now cause a state transition
  859. cs.mtx.Lock()
  860. defer cs.mtx.Unlock()
  861. switch ti.Step {
  862. case cstypes.RoundStepNewHeight:
  863. // NewRound event fired from enterNewRound.
  864. // XXX: should we fire timeout here (for timeout commit)?
  865. cs.enterNewRound(ctx, ti.Height, 0)
  866. case cstypes.RoundStepNewRound:
  867. cs.enterPropose(ctx, ti.Height, 0)
  868. case cstypes.RoundStepPropose:
  869. if err := cs.eventBus.PublishEventTimeoutPropose(ctx, cs.RoundStateEvent()); err != nil {
  870. cs.logger.Error("failed publishing timeout propose", "err", err)
  871. }
  872. cs.enterPrevote(ctx, ti.Height, ti.Round)
  873. case cstypes.RoundStepPrevoteWait:
  874. if err := cs.eventBus.PublishEventTimeoutWait(ctx, cs.RoundStateEvent()); err != nil {
  875. cs.logger.Error("failed publishing timeout wait", "err", err)
  876. }
  877. cs.enterPrecommit(ctx, ti.Height, ti.Round)
  878. case cstypes.RoundStepPrecommitWait:
  879. if err := cs.eventBus.PublishEventTimeoutWait(ctx, cs.RoundStateEvent()); err != nil {
  880. cs.logger.Error("failed publishing timeout wait", "err", err)
  881. }
  882. cs.enterPrecommit(ctx, ti.Height, ti.Round)
  883. cs.enterNewRound(ctx, ti.Height, ti.Round+1)
  884. default:
  885. panic(fmt.Sprintf("invalid timeout step: %v", ti.Step))
  886. }
  887. }
  888. func (cs *State) handleTxsAvailable(ctx context.Context) {
  889. cs.mtx.Lock()
  890. defer cs.mtx.Unlock()
  891. // We only need to do this for round 0.
  892. if cs.Round != 0 {
  893. return
  894. }
  895. switch cs.Step {
  896. case cstypes.RoundStepNewHeight: // timeoutCommit phase
  897. if cs.needProofBlock(cs.Height) {
  898. // enterPropose will be called by enterNewRound
  899. return
  900. }
  901. // +1ms to ensure RoundStepNewRound timeout always happens after RoundStepNewHeight
  902. timeoutCommit := cs.StartTime.Sub(tmtime.Now()) + 1*time.Millisecond
  903. cs.scheduleTimeout(timeoutCommit, cs.Height, 0, cstypes.RoundStepNewRound)
  904. case cstypes.RoundStepNewRound: // after timeoutCommit
  905. cs.enterPropose(ctx, cs.Height, 0)
  906. }
  907. }
  908. //-----------------------------------------------------------------------------
  909. // State functions
  910. // Used internally by handleTimeout and handleMsg to make state transitions
  911. // Enter: `timeoutNewHeight` by startTime (commitTime+timeoutCommit),
  912. // or, if SkipTimeoutCommit==true, after receiving all precommits from (height,round-1)
  913. // Enter: `timeoutPrecommits` after any +2/3 precommits from (height,round-1)
  914. // Enter: +2/3 precommits for nil at (height,round-1)
  915. // Enter: +2/3 prevotes any or +2/3 precommits for block or any from (height, round)
  916. // NOTE: cs.StartTime was already set for height.
  917. func (cs *State) enterNewRound(ctx context.Context, height int64, round int32) {
  918. logger := cs.logger.With("height", height, "round", round)
  919. if cs.Height != height || round < cs.Round || (cs.Round == round && cs.Step != cstypes.RoundStepNewHeight) {
  920. logger.Debug(
  921. "entering new round with invalid args",
  922. "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step),
  923. )
  924. return
  925. }
  926. if now := tmtime.Now(); cs.StartTime.After(now) {
  927. logger.Debug("need to set a buffer and log message here for sanity", "start_time", cs.StartTime, "now", now)
  928. }
  929. logger.Debug("entering new round", "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step))
  930. // increment validators if necessary
  931. validators := cs.Validators
  932. if cs.Round < round {
  933. validators = validators.Copy()
  934. validators.IncrementProposerPriority(tmmath.SafeSubInt32(round, cs.Round))
  935. }
  936. // Setup new round
  937. // we don't fire newStep for this step,
  938. // but we fire an event, so update the round step first
  939. cs.updateRoundStep(round, cstypes.RoundStepNewRound)
  940. cs.Validators = validators
  941. if round == 0 {
  942. // We've already reset these upon new height,
  943. // and meanwhile we might have received a proposal
  944. // for round 0.
  945. } else {
  946. logger.Debug("resetting proposal info")
  947. cs.Proposal = nil
  948. cs.ProposalReceiveTime = time.Time{}
  949. cs.ProposalBlock = nil
  950. cs.ProposalBlockParts = nil
  951. }
  952. cs.Votes.SetRound(tmmath.SafeAddInt32(round, 1)) // also track next round (round+1) to allow round-skipping
  953. cs.TriggeredTimeoutPrecommit = false
  954. if err := cs.eventBus.PublishEventNewRound(ctx, cs.NewRoundEvent()); err != nil {
  955. cs.logger.Error("failed publishing new round", "err", err)
  956. }
  957. cs.metrics.Rounds.Set(float64(round))
  958. // Wait for txs to be available in the mempool
  959. // before we enterPropose in round 0. If the last block changed the app hash,
  960. // we may need an empty "proof" block, and enterPropose immediately.
  961. waitForTxs := cs.config.WaitForTxs() && round == 0 && !cs.needProofBlock(height)
  962. if waitForTxs {
  963. if cs.config.CreateEmptyBlocksInterval > 0 {
  964. cs.scheduleTimeout(cs.config.CreateEmptyBlocksInterval, height, round,
  965. cstypes.RoundStepNewRound)
  966. }
  967. return
  968. }
  969. cs.enterPropose(ctx, height, round)
  970. }
  971. // needProofBlock returns true on the first height (so the genesis app hash is signed right away)
  972. // and where the last block (height-1) caused the app hash to change
  973. func (cs *State) needProofBlock(height int64) bool {
  974. if height == cs.state.InitialHeight {
  975. return true
  976. }
  977. lastBlockMeta := cs.blockStore.LoadBlockMeta(height - 1)
  978. if lastBlockMeta == nil {
  979. panic(fmt.Sprintf("needProofBlock: last block meta for height %d not found", height-1))
  980. }
  981. return !bytes.Equal(cs.state.AppHash, lastBlockMeta.Header.AppHash)
  982. }
  983. // Enter (CreateEmptyBlocks): from enterNewRound(height,round)
  984. // Enter (CreateEmptyBlocks, CreateEmptyBlocksInterval > 0 ):
  985. // after enterNewRound(height,round), after timeout of CreateEmptyBlocksInterval
  986. // Enter (!CreateEmptyBlocks) : after enterNewRound(height,round), once txs are in the mempool
  987. func (cs *State) enterPropose(ctx context.Context, height int64, round int32) {
  988. logger := cs.logger.With("height", height, "round", round)
  989. if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPropose <= cs.Step) {
  990. logger.Debug(
  991. "entering propose step with invalid args",
  992. "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step),
  993. )
  994. return
  995. }
  996. // If this validator is the proposer of this round, and the previous block time is later than
  997. // our local clock time, wait to propose until our local clock time has passed the block time.
  998. if cs.privValidatorPubKey != nil && cs.isProposer(cs.privValidatorPubKey.Address()) {
  999. proposerWaitTime := proposerWaitTime(tmtime.DefaultSource{}, cs.state.LastBlockTime)
  1000. if proposerWaitTime > 0 {
  1001. cs.scheduleTimeout(proposerWaitTime, height, round, cstypes.RoundStepNewRound)
  1002. return
  1003. }
  1004. }
  1005. logger.Debug("entering propose step", "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step))
  1006. defer func() {
  1007. // Done enterPropose:
  1008. cs.updateRoundStep(round, cstypes.RoundStepPropose)
  1009. cs.newStep(ctx)
  1010. // If we have the whole proposal + POL, then goto Prevote now.
  1011. // else, we'll enterPrevote when the rest of the proposal is received (in AddProposalBlockPart),
  1012. // or else after timeoutPropose
  1013. if cs.isProposalComplete() {
  1014. cs.enterPrevote(ctx, height, cs.Round)
  1015. }
  1016. }()
  1017. // If we don't get the proposal and all block parts quick enough, enterPrevote
  1018. cs.scheduleTimeout(cs.config.Propose(round), height, round, cstypes.RoundStepPropose)
  1019. // Nothing more to do if we're not a validator
  1020. if cs.privValidator == nil {
  1021. logger.Debug("propose step; not proposing since node is not a validator")
  1022. return
  1023. }
  1024. if cs.privValidatorPubKey == nil {
  1025. // If this node is a validator & proposer in the current round, it will
  1026. // miss the opportunity to create a block.
  1027. logger.Error("propose step; empty priv validator public key", "err", errPubKeyIsNotSet)
  1028. return
  1029. }
  1030. addr := cs.privValidatorPubKey.Address()
  1031. // if not a validator, we're done
  1032. if !cs.Validators.HasAddress(addr) {
  1033. logger.Debug("propose step; not proposing since node is not in the validator set",
  1034. "addr", addr,
  1035. "vals", cs.Validators)
  1036. return
  1037. }
  1038. if cs.isProposer(addr) {
  1039. logger.Debug(
  1040. "propose step; our turn to propose",
  1041. "proposer", addr,
  1042. )
  1043. cs.decideProposal(ctx, height, round)
  1044. } else {
  1045. logger.Debug(
  1046. "propose step; not our turn to propose",
  1047. "proposer", cs.Validators.GetProposer().Address,
  1048. )
  1049. }
  1050. }
  1051. func (cs *State) isProposer(address []byte) bool {
  1052. return bytes.Equal(cs.Validators.GetProposer().Address, address)
  1053. }
  1054. func (cs *State) defaultDecideProposal(ctx context.Context, height int64, round int32) {
  1055. var block *types.Block
  1056. var blockParts *types.PartSet
  1057. // Decide on block
  1058. if cs.ValidBlock != nil {
  1059. // If there is valid block, choose that.
  1060. block, blockParts = cs.ValidBlock, cs.ValidBlockParts
  1061. } else {
  1062. // Create a new proposal block from state/txs from the mempool.
  1063. var err error
  1064. block, blockParts, err = cs.createProposalBlock()
  1065. if block == nil || err != nil {
  1066. return
  1067. }
  1068. }
  1069. // Flush the WAL. Otherwise, we may not recompute the same proposal to sign,
  1070. // and the privValidator will refuse to sign anything.
  1071. if err := cs.wal.FlushAndSync(); err != nil {
  1072. cs.logger.Error("failed flushing WAL to disk")
  1073. }
  1074. // Make proposal
  1075. propBlockID := types.BlockID{Hash: block.Hash(), PartSetHeader: blockParts.Header()}
  1076. proposal := types.NewProposal(height, round, cs.ValidRound, propBlockID, block.Header.Time)
  1077. p := proposal.ToProto()
  1078. // wait the max amount we would wait for a proposal
  1079. ctxto, cancel := context.WithTimeout(ctx, cs.config.TimeoutPropose)
  1080. defer cancel()
  1081. if err := cs.privValidator.SignProposal(ctxto, cs.state.ChainID, p); err == nil {
  1082. proposal.Signature = p.Signature
  1083. // send proposal and block parts on internal msg queue
  1084. cs.sendInternalMessage(ctx, msgInfo{&ProposalMessage{proposal}, "", tmtime.Now()})
  1085. for i := 0; i < int(blockParts.Total()); i++ {
  1086. part := blockParts.GetPart(i)
  1087. cs.sendInternalMessage(ctx, msgInfo{&BlockPartMessage{cs.Height, cs.Round, part}, "", tmtime.Now()})
  1088. }
  1089. cs.logger.Debug("signed proposal", "height", height, "round", round, "proposal", proposal)
  1090. } else if !cs.replayMode {
  1091. cs.logger.Error("propose step; failed signing proposal", "height", height, "round", round, "err", err)
  1092. }
  1093. }
  1094. // Returns true if the proposal block is complete &&
  1095. // (if POLRound was proposed, we have +2/3 prevotes from there).
  1096. func (cs *State) isProposalComplete() bool {
  1097. if cs.Proposal == nil || cs.ProposalBlock == nil {
  1098. return false
  1099. }
  1100. // we have the proposal. if there's a POLRound,
  1101. // make sure we have the prevotes from it too
  1102. if cs.Proposal.POLRound < 0 {
  1103. return true
  1104. }
  1105. // if this is false the proposer is lying or we haven't received the POL yet
  1106. return cs.Votes.Prevotes(cs.Proposal.POLRound).HasTwoThirdsMajority()
  1107. }
  1108. // Create the next block to propose and return it. Returns nil block upon error.
  1109. //
  1110. // We really only need to return the parts, but the block is returned for
  1111. // convenience so we can log the proposal block.
  1112. //
  1113. // NOTE: keep it side-effect free for clarity.
  1114. // CONTRACT: cs.privValidator is not nil.
  1115. func (cs *State) createProposalBlock() (block *types.Block, blockParts *types.PartSet, err error) {
  1116. if cs.privValidator == nil {
  1117. return nil, nil, errors.New("entered createProposalBlock with privValidator being nil")
  1118. }
  1119. var commit *types.Commit
  1120. switch {
  1121. case cs.Height == cs.state.InitialHeight:
  1122. // We're creating a proposal for the first block.
  1123. // The commit is empty, but not nil.
  1124. commit = types.NewCommit(0, 0, types.BlockID{}, nil)
  1125. case cs.LastCommit.HasTwoThirdsMajority():
  1126. // Make the commit from LastCommit
  1127. commit = cs.LastCommit.MakeCommit()
  1128. default: // This shouldn't happen.
  1129. cs.logger.Error("propose step; cannot propose anything without commit for the previous block")
  1130. return
  1131. }
  1132. if cs.privValidatorPubKey == nil {
  1133. // If this node is a validator & proposer in the current round, it will
  1134. // miss the opportunity to create a block.
  1135. cs.logger.Error("propose step; empty priv validator public key", "err", errPubKeyIsNotSet)
  1136. return
  1137. }
  1138. proposerAddr := cs.privValidatorPubKey.Address()
  1139. return cs.blockExec.CreateProposalBlock(cs.Height, cs.state, commit, proposerAddr)
  1140. }
  1141. // Enter: `timeoutPropose` after entering Propose.
  1142. // Enter: proposal block and POL is ready.
  1143. // If we received a valid proposal within this round and we are not locked on a block,
  1144. // we will prevote for block.
  1145. // Otherwise, if we receive a valid proposal that matches the block we are
  1146. // locked on or matches a block that received a POL in a round later than our
  1147. // locked round, prevote for the proposal, otherwise vote nil.
  1148. func (cs *State) enterPrevote(ctx context.Context, height int64, round int32) {
  1149. logger := cs.logger.With("height", height, "round", round)
  1150. if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPrevote <= cs.Step) {
  1151. logger.Debug(
  1152. "entering prevote step with invalid args",
  1153. "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step),
  1154. )
  1155. return
  1156. }
  1157. defer func() {
  1158. // Done enterPrevote:
  1159. cs.updateRoundStep(round, cstypes.RoundStepPrevote)
  1160. cs.newStep(ctx)
  1161. }()
  1162. logger.Debug("entering prevote step", "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step))
  1163. // Sign and broadcast vote as necessary
  1164. cs.doPrevote(ctx, height, round)
  1165. // Once `addVote` hits any +2/3 prevotes, we will go to PrevoteWait
  1166. // (so we have more time to try and collect +2/3 prevotes for a single block)
  1167. }
  1168. func (cs *State) proposalIsTimely() bool {
  1169. sp := types.SynchronyParams{
  1170. Precision: cs.state.ConsensusParams.Synchrony.Precision,
  1171. MessageDelay: cs.state.ConsensusParams.Synchrony.MessageDelay,
  1172. }
  1173. return cs.Proposal.IsTimely(cs.ProposalReceiveTime, sp, cs.state.InitialHeight)
  1174. }
  1175. func (cs *State) defaultDoPrevote(ctx context.Context, height int64, round int32) {
  1176. logger := cs.logger.With("height", height, "round", round)
  1177. // Check that a proposed block was not received within this round (and thus executing this from a timeout).
  1178. if cs.ProposalBlock == nil {
  1179. logger.Debug("prevote step: ProposalBlock is nil; prevoting nil")
  1180. cs.signAddVote(ctx, tmproto.PrevoteType, nil, types.PartSetHeader{})
  1181. return
  1182. }
  1183. if cs.Proposal == nil {
  1184. logger.Debug("prevote step: did not receive proposal; prevoting nil")
  1185. cs.signAddVote(ctx, tmproto.PrevoteType, nil, types.PartSetHeader{})
  1186. return
  1187. }
  1188. if !cs.Proposal.Timestamp.Equal(cs.ProposalBlock.Header.Time) {
  1189. logger.Debug("prevote step: proposal timestamp not equal; prevoting nil")
  1190. cs.signAddVote(ctx, tmproto.PrevoteType, nil, types.PartSetHeader{})
  1191. return
  1192. }
  1193. if cs.Proposal.POLRound == -1 && cs.LockedRound == -1 && !cs.proposalIsTimely() {
  1194. logger.Debug("prevote step: Proposal is not timely; prevoting nil",
  1195. "proposed",
  1196. tmtime.Canonical(cs.Proposal.Timestamp).Format(time.RFC3339Nano),
  1197. "received",
  1198. tmtime.Canonical(cs.ProposalReceiveTime).Format(time.RFC3339Nano),
  1199. "msg_delay",
  1200. cs.state.ConsensusParams.Synchrony.MessageDelay,
  1201. "precision",
  1202. cs.state.ConsensusParams.Synchrony.Precision)
  1203. cs.signAddVote(ctx, tmproto.PrevoteType, nil, types.PartSetHeader{})
  1204. return
  1205. }
  1206. // Validate proposal block
  1207. err := cs.blockExec.ValidateBlock(cs.state, cs.ProposalBlock)
  1208. if err != nil {
  1209. // ProposalBlock is invalid, prevote nil.
  1210. logger.Error("prevote step: ProposalBlock is invalid; prevoting nil", "err", err)
  1211. cs.signAddVote(ctx, tmproto.PrevoteType, nil, types.PartSetHeader{})
  1212. return
  1213. }
  1214. /*
  1215. 22: upon <PROPOSAL, h_p, round_p, v, 1> from proposer(h_p, round_p) while step_p = propose do
  1216. 23: if valid(v) && (lockedRound_p = 1 || lockedValue_p = v) then
  1217. 24: broadcast <PREVOTE, h_p, round_p, id(v)>
  1218. Here, cs.Proposal.POLRound corresponds to the -1 in the above algorithm rule.
  1219. This means that the proposer is producing a new proposal that has not previously
  1220. seen a 2/3 majority by the network.
  1221. If we have already locked on a different value that is different from the proposed value,
  1222. we prevote nil since we are locked on a different value. Otherwise, if we're not locked on a block
  1223. or the proposal matches our locked block, we prevote the proposal.
  1224. */
  1225. if cs.Proposal.POLRound == -1 {
  1226. if cs.LockedRound == -1 {
  1227. logger.Debug("prevote step: ProposalBlock is valid and there is no locked block; prevoting the proposal")
  1228. cs.signAddVote(ctx, tmproto.PrevoteType, cs.ProposalBlock.Hash(), cs.ProposalBlockParts.Header())
  1229. return
  1230. }
  1231. if cs.ProposalBlock.HashesTo(cs.LockedBlock.Hash()) {
  1232. logger.Debug("prevote step: ProposalBlock is valid and matches our locked block; prevoting the proposal")
  1233. cs.signAddVote(ctx, tmproto.PrevoteType, cs.ProposalBlock.Hash(), cs.ProposalBlockParts.Header())
  1234. return
  1235. }
  1236. }
  1237. /*
  1238. 28: upon <PROPOSAL, h_p, round_p, v, v_r> from proposer(h_p, round_p) AND 2f + 1 <PREVOTE, h_p, v_r, id(v)> while
  1239. step_p = propose && (v_r 0 && v_r < round_p) do
  1240. 29: if valid(v) && (lockedRound_p v_r || lockedValue_p = v) then
  1241. 30: broadcast <PREVOTE, h_p, round_p, id(v)>
  1242. This rule is a bit confusing but breaks down as follows:
  1243. If we see a proposal in the current round for value 'v' that lists its valid round as 'v_r'
  1244. AND this validator saw a 2/3 majority of the voting power prevote 'v' in round 'v_r', then we will
  1245. issue a prevote for 'v' in this round if 'v' is valid and either matches our locked value OR
  1246. 'v_r' is a round greater than or equal to our current locked round.
  1247. 'v_r' can be a round greater than to our current locked round if a 2/3 majority of
  1248. the network prevoted a value in round 'v_r' but we did not lock on it, possibly because we
  1249. missed the proposal in round 'v_r'.
  1250. */
  1251. blockID, ok := cs.Votes.Prevotes(cs.Proposal.POLRound).TwoThirdsMajority()
  1252. if ok && cs.ProposalBlock.HashesTo(blockID.Hash) && cs.Proposal.POLRound >= 0 && cs.Proposal.POLRound < cs.Round {
  1253. if cs.LockedRound <= cs.Proposal.POLRound {
  1254. logger.Debug("prevote step: ProposalBlock is valid and received a 2/3" +
  1255. "majority in a round later than the locked round; prevoting the proposal")
  1256. cs.signAddVote(ctx, tmproto.PrevoteType, cs.ProposalBlock.Hash(), cs.ProposalBlockParts.Header())
  1257. return
  1258. }
  1259. if cs.ProposalBlock.HashesTo(cs.LockedBlock.Hash()) {
  1260. logger.Debug("prevote step: ProposalBlock is valid and matches our locked block; prevoting the proposal")
  1261. cs.signAddVote(ctx, tmproto.PrevoteType, cs.ProposalBlock.Hash(), cs.ProposalBlockParts.Header())
  1262. return
  1263. }
  1264. }
  1265. logger.Debug("prevote step: ProposalBlock is valid but was not our locked block or" +
  1266. "did not receive a more recent majority; prevoting nil")
  1267. cs.signAddVote(ctx, tmproto.PrevoteType, nil, types.PartSetHeader{})
  1268. }
  1269. // Enter: any +2/3 prevotes at next round.
  1270. func (cs *State) enterPrevoteWait(ctx context.Context, height int64, round int32) {
  1271. logger := cs.logger.With("height", height, "round", round)
  1272. if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPrevoteWait <= cs.Step) {
  1273. logger.Debug(
  1274. "entering prevote wait step with invalid args",
  1275. "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step),
  1276. )
  1277. return
  1278. }
  1279. if !cs.Votes.Prevotes(round).HasTwoThirdsAny() {
  1280. panic(fmt.Sprintf(
  1281. "entering prevote wait step (%v/%v), but prevotes does not have any +2/3 votes",
  1282. height, round,
  1283. ))
  1284. }
  1285. logger.Debug("entering prevote wait step", "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step))
  1286. defer func() {
  1287. // Done enterPrevoteWait:
  1288. cs.updateRoundStep(round, cstypes.RoundStepPrevoteWait)
  1289. cs.newStep(ctx)
  1290. }()
  1291. // Wait for some more prevotes; enterPrecommit
  1292. cs.scheduleTimeout(cs.config.Prevote(round), height, round, cstypes.RoundStepPrevoteWait)
  1293. }
  1294. // Enter: `timeoutPrevote` after any +2/3 prevotes.
  1295. // Enter: `timeoutPrecommit` after any +2/3 precommits.
  1296. // Enter: +2/3 precomits for block or nil.
  1297. // Lock & precommit the ProposalBlock if we have enough prevotes for it (a POL in this round)
  1298. // else, precommit nil otherwise.
  1299. func (cs *State) enterPrecommit(ctx context.Context, height int64, round int32) {
  1300. logger := cs.logger.With("height", height, "round", round)
  1301. if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPrecommit <= cs.Step) {
  1302. logger.Debug(
  1303. "entering precommit step with invalid args",
  1304. "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step),
  1305. )
  1306. return
  1307. }
  1308. logger.Debug("entering precommit step", "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step))
  1309. defer func() {
  1310. // Done enterPrecommit:
  1311. cs.updateRoundStep(round, cstypes.RoundStepPrecommit)
  1312. cs.newStep(ctx)
  1313. }()
  1314. // check for a polka
  1315. blockID, ok := cs.Votes.Prevotes(round).TwoThirdsMajority()
  1316. // If we don't have a polka, we must precommit nil.
  1317. if !ok {
  1318. if cs.LockedBlock != nil {
  1319. logger.Debug("precommit step; no +2/3 prevotes during enterPrecommit while we are locked; precommitting nil")
  1320. } else {
  1321. logger.Debug("precommit step; no +2/3 prevotes during enterPrecommit; precommitting nil")
  1322. }
  1323. cs.signAddVote(ctx, tmproto.PrecommitType, nil, types.PartSetHeader{})
  1324. return
  1325. }
  1326. // At this point +2/3 prevoted for a particular block or nil.
  1327. if err := cs.eventBus.PublishEventPolka(ctx, cs.RoundStateEvent()); err != nil {
  1328. logger.Error("failed publishing polka", "err", err)
  1329. }
  1330. // the latest POLRound should be this round.
  1331. polRound, _ := cs.Votes.POLInfo()
  1332. if polRound < round {
  1333. panic(fmt.Sprintf("this POLRound should be %v but got %v", round, polRound))
  1334. }
  1335. // +2/3 prevoted nil. Precommit nil.
  1336. if blockID.IsNil() {
  1337. logger.Debug("precommit step: +2/3 prevoted for nil; precommitting nil")
  1338. cs.signAddVote(ctx, tmproto.PrecommitType, nil, types.PartSetHeader{})
  1339. return
  1340. }
  1341. // At this point, +2/3 prevoted for a particular block.
  1342. // If we never received a proposal for this block, we must precommit nil
  1343. if cs.Proposal == nil || cs.ProposalBlock == nil {
  1344. logger.Debug("precommit step; did not receive proposal, precommitting nil")
  1345. cs.signAddVote(ctx, tmproto.PrecommitType, nil, types.PartSetHeader{})
  1346. return
  1347. }
  1348. // If the proposal time does not match the block time, precommit nil.
  1349. if !cs.Proposal.Timestamp.Equal(cs.ProposalBlock.Header.Time) {
  1350. logger.Debug("precommit step: proposal timestamp not equal; precommitting nil")
  1351. cs.signAddVote(ctx, tmproto.PrecommitType, nil, types.PartSetHeader{})
  1352. return
  1353. }
  1354. // If we're already locked on that block, precommit it, and update the LockedRound
  1355. if cs.LockedBlock.HashesTo(blockID.Hash) {
  1356. logger.Debug("precommit step: +2/3 prevoted locked block; relocking")
  1357. cs.LockedRound = round
  1358. if err := cs.eventBus.PublishEventRelock(ctx, cs.RoundStateEvent()); err != nil {
  1359. logger.Error("precommit step: failed publishing event relock", "err", err)
  1360. }
  1361. cs.signAddVote(ctx, tmproto.PrecommitType, blockID.Hash, blockID.PartSetHeader)
  1362. return
  1363. }
  1364. // If greater than 2/3 of the voting power on the network prevoted for
  1365. // the proposed block, update our locked block to this block and issue a
  1366. // precommit vote for it.
  1367. if cs.ProposalBlock.HashesTo(blockID.Hash) {
  1368. logger.Debug("precommit step: +2/3 prevoted proposal block; locking", "hash", blockID.Hash)
  1369. // Validate the block.
  1370. if err := cs.blockExec.ValidateBlock(cs.state, cs.ProposalBlock); err != nil {
  1371. panic(fmt.Sprintf("precommit step: +2/3 prevoted for an invalid block %v; relocking", err))
  1372. }
  1373. cs.LockedRound = round
  1374. cs.LockedBlock = cs.ProposalBlock
  1375. cs.LockedBlockParts = cs.ProposalBlockParts
  1376. if err := cs.eventBus.PublishEventLock(ctx, cs.RoundStateEvent()); err != nil {
  1377. logger.Error("precommit step: failed publishing event lock", "err", err)
  1378. }
  1379. cs.signAddVote(ctx, tmproto.PrecommitType, blockID.Hash, blockID.PartSetHeader)
  1380. return
  1381. }
  1382. // There was a polka in this round for a block we don't have.
  1383. // Fetch that block, and precommit nil.
  1384. logger.Debug("precommit step: +2/3 prevotes for a block we do not have; voting nil", "block_id", blockID)
  1385. if !cs.ProposalBlockParts.HasHeader(blockID.PartSetHeader) {
  1386. cs.ProposalBlock = nil
  1387. cs.ProposalBlockParts = types.NewPartSetFromHeader(blockID.PartSetHeader)
  1388. }
  1389. cs.signAddVote(ctx, tmproto.PrecommitType, nil, types.PartSetHeader{})
  1390. }
  1391. // Enter: any +2/3 precommits for next round.
  1392. func (cs *State) enterPrecommitWait(ctx context.Context, height int64, round int32) {
  1393. logger := cs.logger.With("height", height, "round", round)
  1394. if cs.Height != height || round < cs.Round || (cs.Round == round && cs.TriggeredTimeoutPrecommit) {
  1395. logger.Debug(
  1396. "entering precommit wait step with invalid args",
  1397. "triggered_timeout", cs.TriggeredTimeoutPrecommit,
  1398. "current", fmt.Sprintf("%v/%v", cs.Height, cs.Round),
  1399. )
  1400. return
  1401. }
  1402. if !cs.Votes.Precommits(round).HasTwoThirdsAny() {
  1403. panic(fmt.Sprintf(
  1404. "entering precommit wait step (%v/%v), but precommits does not have any +2/3 votes",
  1405. height, round,
  1406. ))
  1407. }
  1408. logger.Debug("entering precommit wait step", "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step))
  1409. defer func() {
  1410. // Done enterPrecommitWait:
  1411. cs.TriggeredTimeoutPrecommit = true
  1412. cs.newStep(ctx)
  1413. }()
  1414. // wait for some more precommits; enterNewRound
  1415. cs.scheduleTimeout(cs.config.Precommit(round), height, round, cstypes.RoundStepPrecommitWait)
  1416. }
  1417. // Enter: +2/3 precommits for block
  1418. func (cs *State) enterCommit(ctx context.Context, height int64, commitRound int32) {
  1419. logger := cs.logger.With("height", height, "commit_round", commitRound)
  1420. if cs.Height != height || cstypes.RoundStepCommit <= cs.Step {
  1421. logger.Debug(
  1422. "entering commit step with invalid args",
  1423. "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step),
  1424. )
  1425. return
  1426. }
  1427. logger.Debug("entering commit step", "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step))
  1428. defer func() {
  1429. // Done enterCommit:
  1430. // keep cs.Round the same, commitRound points to the right Precommits set.
  1431. cs.updateRoundStep(cs.Round, cstypes.RoundStepCommit)
  1432. cs.CommitRound = commitRound
  1433. cs.CommitTime = tmtime.Now()
  1434. cs.newStep(ctx)
  1435. // Maybe finalize immediately.
  1436. cs.tryFinalizeCommit(ctx, height)
  1437. }()
  1438. blockID, ok := cs.Votes.Precommits(commitRound).TwoThirdsMajority()
  1439. if !ok {
  1440. panic("RunActionCommit() expects +2/3 precommits")
  1441. }
  1442. // The Locked* fields no longer matter.
  1443. // Move them over to ProposalBlock if they match the commit hash,
  1444. // otherwise they'll be cleared in updateToState.
  1445. if cs.LockedBlock.HashesTo(blockID.Hash) {
  1446. logger.Debug("commit is for a locked block; set ProposalBlock=LockedBlock", "block_hash", blockID.Hash)
  1447. cs.ProposalBlock = cs.LockedBlock
  1448. cs.ProposalBlockParts = cs.LockedBlockParts
  1449. }
  1450. // If we don't have the block being committed, set up to get it.
  1451. if !cs.ProposalBlock.HashesTo(blockID.Hash) {
  1452. if !cs.ProposalBlockParts.HasHeader(blockID.PartSetHeader) {
  1453. logger.Info(
  1454. "commit is for a block we do not know about; set ProposalBlock=nil",
  1455. "proposal", cs.ProposalBlock.Hash(),
  1456. "commit", blockID.Hash,
  1457. )
  1458. // We're getting the wrong block.
  1459. // Set up ProposalBlockParts and keep waiting.
  1460. cs.ProposalBlock = nil
  1461. cs.ProposalBlockParts = types.NewPartSetFromHeader(blockID.PartSetHeader)
  1462. if err := cs.eventBus.PublishEventValidBlock(ctx, cs.RoundStateEvent()); err != nil {
  1463. logger.Error("failed publishing valid block", "err", err)
  1464. }
  1465. cs.evsw.FireEvent(ctx, types.EventValidBlockValue, &cs.RoundState)
  1466. }
  1467. }
  1468. }
  1469. // If we have the block AND +2/3 commits for it, finalize.
  1470. func (cs *State) tryFinalizeCommit(ctx context.Context, height int64) {
  1471. logger := cs.logger.With("height", height)
  1472. if cs.Height != height {
  1473. panic(fmt.Sprintf("tryFinalizeCommit() cs.Height: %v vs height: %v", cs.Height, height))
  1474. }
  1475. blockID, ok := cs.Votes.Precommits(cs.CommitRound).TwoThirdsMajority()
  1476. if !ok || blockID.IsNil() {
  1477. logger.Error("failed attempt to finalize commit; there was no +2/3 majority or +2/3 was for nil")
  1478. return
  1479. }
  1480. if !cs.ProposalBlock.HashesTo(blockID.Hash) {
  1481. // TODO: this happens every time if we're not a validator (ugly logs)
  1482. // TODO: ^^ wait, why does it matter that we're a validator?
  1483. logger.Debug(
  1484. "failed attempt to finalize commit; we do not have the commit block",
  1485. "proposal_block", cs.ProposalBlock.Hash(),
  1486. "commit_block", blockID.Hash,
  1487. )
  1488. return
  1489. }
  1490. cs.finalizeCommit(ctx, height)
  1491. }
  1492. // Increment height and goto cstypes.RoundStepNewHeight
  1493. func (cs *State) finalizeCommit(ctx context.Context, height int64) {
  1494. logger := cs.logger.With("height", height)
  1495. if cs.Height != height || cs.Step != cstypes.RoundStepCommit {
  1496. logger.Debug(
  1497. "entering finalize commit step",
  1498. "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step),
  1499. )
  1500. return
  1501. }
  1502. cs.calculatePrevoteMessageDelayMetrics()
  1503. blockID, ok := cs.Votes.Precommits(cs.CommitRound).TwoThirdsMajority()
  1504. block, blockParts := cs.ProposalBlock, cs.ProposalBlockParts
  1505. if !ok {
  1506. panic("cannot finalize commit; commit does not have 2/3 majority")
  1507. }
  1508. if !blockParts.HasHeader(blockID.PartSetHeader) {
  1509. panic("expected ProposalBlockParts header to be commit header")
  1510. }
  1511. if !block.HashesTo(blockID.Hash) {
  1512. panic("cannot finalize commit; proposal block does not hash to commit hash")
  1513. }
  1514. if err := cs.blockExec.ValidateBlock(cs.state, block); err != nil {
  1515. panic(fmt.Errorf("+2/3 committed an invalid block: %w", err))
  1516. }
  1517. logger.Info(
  1518. "finalizing commit of block",
  1519. "hash", block.Hash(),
  1520. "root", block.AppHash,
  1521. "num_txs", len(block.Txs),
  1522. )
  1523. logger.Debug(fmt.Sprintf("%v", block))
  1524. // Save to blockStore.
  1525. if cs.blockStore.Height() < block.Height {
  1526. // NOTE: the seenCommit is local justification to commit this block,
  1527. // but may differ from the LastCommit included in the next block
  1528. precommits := cs.Votes.Precommits(cs.CommitRound)
  1529. seenCommit := precommits.MakeCommit()
  1530. cs.blockStore.SaveBlock(block, blockParts, seenCommit)
  1531. } else {
  1532. // Happens during replay if we already saved the block but didn't commit
  1533. logger.Debug("calling finalizeCommit on already stored block", "height", block.Height)
  1534. }
  1535. // Write EndHeightMessage{} for this height, implying that the blockstore
  1536. // has saved the block.
  1537. //
  1538. // If we crash before writing this EndHeightMessage{}, we will recover by
  1539. // running ApplyBlock during the ABCI handshake when we restart. If we
  1540. // didn't save the block to the blockstore before writing
  1541. // EndHeightMessage{}, we'd have to change WAL replay -- currently it
  1542. // complains about replaying for heights where an #ENDHEIGHT entry already
  1543. // exists.
  1544. //
  1545. // Either way, the State should not be resumed until we
  1546. // successfully call ApplyBlock (ie. later here, or in Handshake after
  1547. // restart).
  1548. endMsg := EndHeightMessage{height}
  1549. if err := cs.wal.WriteSync(endMsg); err != nil { // NOTE: fsync
  1550. panic(fmt.Sprintf(
  1551. "failed to write %v msg to consensus WAL due to %v; check your file system and restart the node",
  1552. endMsg, err,
  1553. ))
  1554. }
  1555. // Create a copy of the state for staging and an event cache for txs.
  1556. stateCopy := cs.state.Copy()
  1557. // Execute and commit the block, update and save the state, and update the mempool.
  1558. // NOTE The block.AppHash wont reflect these txs until the next block.
  1559. stateCopy, err := cs.blockExec.ApplyBlock(ctx,
  1560. stateCopy,
  1561. types.BlockID{
  1562. Hash: block.Hash(),
  1563. PartSetHeader: blockParts.Header(),
  1564. },
  1565. block,
  1566. )
  1567. if err != nil {
  1568. logger.Error("failed to apply block", "err", err)
  1569. return
  1570. }
  1571. // must be called before we update state
  1572. cs.RecordMetrics(height, block)
  1573. // NewHeightStep!
  1574. cs.updateToState(ctx, stateCopy)
  1575. // Private validator might have changed it's key pair => refetch pubkey.
  1576. if err := cs.updatePrivValidatorPubKey(ctx); err != nil {
  1577. logger.Error("failed to get private validator pubkey", "err", err)
  1578. }
  1579. // cs.StartTime is already set.
  1580. // Schedule Round0 to start soon.
  1581. cs.scheduleRound0(&cs.RoundState)
  1582. // By here,
  1583. // * cs.Height has been increment to height+1
  1584. // * cs.Step is now cstypes.RoundStepNewHeight
  1585. // * cs.StartTime is set to when we will start round0.
  1586. }
  1587. func (cs *State) RecordMetrics(height int64, block *types.Block) {
  1588. cs.metrics.Validators.Set(float64(cs.Validators.Size()))
  1589. cs.metrics.ValidatorsPower.Set(float64(cs.Validators.TotalVotingPower()))
  1590. var (
  1591. missingValidators int
  1592. missingValidatorsPower int64
  1593. )
  1594. // height=0 -> MissingValidators and MissingValidatorsPower are both 0.
  1595. // Remember that the first LastCommit is intentionally empty, so it's not
  1596. // fair to increment missing validators number.
  1597. if height > cs.state.InitialHeight {
  1598. // Sanity check that commit size matches validator set size - only applies
  1599. // after first block.
  1600. var (
  1601. commitSize = block.LastCommit.Size()
  1602. valSetLen = len(cs.LastValidators.Validators)
  1603. address types.Address
  1604. )
  1605. if commitSize != valSetLen {
  1606. cs.logger.Error(fmt.Sprintf("commit size (%d) doesn't match valset length (%d) at height %d\n\n%v\n\n%v",
  1607. commitSize, valSetLen, block.Height, block.LastCommit.Signatures, cs.LastValidators.Validators))
  1608. return
  1609. }
  1610. if cs.privValidator != nil {
  1611. if cs.privValidatorPubKey == nil {
  1612. // Metrics won't be updated, but it's not critical.
  1613. cs.logger.Error("recordMetrics", "err", errPubKeyIsNotSet)
  1614. } else {
  1615. address = cs.privValidatorPubKey.Address()
  1616. }
  1617. }
  1618. for i, val := range cs.LastValidators.Validators {
  1619. commitSig := block.LastCommit.Signatures[i]
  1620. if commitSig.Absent() {
  1621. missingValidators++
  1622. missingValidatorsPower += val.VotingPower
  1623. }
  1624. if bytes.Equal(val.Address, address) {
  1625. label := []string{
  1626. "validator_address", val.Address.String(),
  1627. }
  1628. cs.metrics.ValidatorPower.With(label...).Set(float64(val.VotingPower))
  1629. if commitSig.ForBlock() {
  1630. cs.metrics.ValidatorLastSignedHeight.With(label...).Set(float64(height))
  1631. } else {
  1632. cs.metrics.ValidatorMissedBlocks.With(label...).Add(float64(1))
  1633. }
  1634. }
  1635. }
  1636. }
  1637. cs.metrics.MissingValidators.Set(float64(missingValidators))
  1638. cs.metrics.MissingValidatorsPower.Set(float64(missingValidatorsPower))
  1639. // NOTE: byzantine validators power and count is only for consensus evidence i.e. duplicate vote
  1640. var (
  1641. byzantineValidatorsPower int64
  1642. byzantineValidatorsCount int64
  1643. )
  1644. for _, ev := range block.Evidence.Evidence {
  1645. if dve, ok := ev.(*types.DuplicateVoteEvidence); ok {
  1646. if _, val := cs.Validators.GetByAddress(dve.VoteA.ValidatorAddress); val != nil {
  1647. byzantineValidatorsCount++
  1648. byzantineValidatorsPower += val.VotingPower
  1649. }
  1650. }
  1651. }
  1652. cs.metrics.ByzantineValidators.Set(float64(byzantineValidatorsCount))
  1653. cs.metrics.ByzantineValidatorsPower.Set(float64(byzantineValidatorsPower))
  1654. if height > 1 {
  1655. lastBlockMeta := cs.blockStore.LoadBlockMeta(height - 1)
  1656. if lastBlockMeta != nil {
  1657. cs.metrics.BlockIntervalSeconds.Observe(
  1658. block.Time.Sub(lastBlockMeta.Header.Time).Seconds(),
  1659. )
  1660. }
  1661. }
  1662. cs.metrics.NumTxs.Set(float64(len(block.Data.Txs)))
  1663. cs.metrics.TotalTxs.Add(float64(len(block.Data.Txs)))
  1664. cs.metrics.BlockSizeBytes.Observe(float64(block.Size()))
  1665. cs.metrics.CommittedHeight.Set(float64(block.Height))
  1666. }
  1667. //-----------------------------------------------------------------------------
  1668. func (cs *State) defaultSetProposal(proposal *types.Proposal, recvTime time.Time) error {
  1669. // Already have one
  1670. // TODO: possibly catch double proposals
  1671. if cs.Proposal != nil || proposal == nil {
  1672. return nil
  1673. }
  1674. // Does not apply
  1675. if proposal.Height != cs.Height || proposal.Round != cs.Round {
  1676. return nil
  1677. }
  1678. // Verify POLRound, which must be -1 or in range [0, proposal.Round).
  1679. if proposal.POLRound < -1 ||
  1680. (proposal.POLRound >= 0 && proposal.POLRound >= proposal.Round) {
  1681. return ErrInvalidProposalPOLRound
  1682. }
  1683. p := proposal.ToProto()
  1684. // Verify signature
  1685. if !cs.Validators.GetProposer().PubKey.VerifySignature(
  1686. types.ProposalSignBytes(cs.state.ChainID, p), proposal.Signature,
  1687. ) {
  1688. return ErrInvalidProposalSignature
  1689. }
  1690. proposal.Signature = p.Signature
  1691. cs.Proposal = proposal
  1692. cs.ProposalReceiveTime = recvTime
  1693. cs.calculateProposalTimestampDifferenceMetric()
  1694. // We don't update cs.ProposalBlockParts if it is already set.
  1695. // This happens if we're already in cstypes.RoundStepCommit or if there is a valid block in the current round.
  1696. // TODO: We can check if Proposal is for a different block as this is a sign of misbehavior!
  1697. if cs.ProposalBlockParts == nil {
  1698. cs.ProposalBlockParts = types.NewPartSetFromHeader(proposal.BlockID.PartSetHeader)
  1699. }
  1700. cs.logger.Info("received proposal", "proposal", proposal)
  1701. return nil
  1702. }
  1703. // NOTE: block is not necessarily valid.
  1704. // Asynchronously triggers either enterPrevote (before we timeout of propose) or tryFinalizeCommit,
  1705. // once we have the full block.
  1706. func (cs *State) addProposalBlockPart(
  1707. ctx context.Context,
  1708. msg *BlockPartMessage,
  1709. peerID types.NodeID,
  1710. ) (added bool, err error) {
  1711. height, round, part := msg.Height, msg.Round, msg.Part
  1712. // Blocks might be reused, so round mismatch is OK
  1713. if cs.Height != height {
  1714. cs.logger.Debug("received block part from wrong height", "height", height, "round", round)
  1715. return false, nil
  1716. }
  1717. // We're not expecting a block part.
  1718. if cs.ProposalBlockParts == nil {
  1719. // NOTE: this can happen when we've gone to a higher round and
  1720. // then receive parts from the previous round - not necessarily a bad peer.
  1721. cs.logger.Debug(
  1722. "received a block part when we are not expecting any",
  1723. "height", height,
  1724. "round", round,
  1725. "index", part.Index,
  1726. "peer", peerID,
  1727. )
  1728. return false, nil
  1729. }
  1730. added, err = cs.ProposalBlockParts.AddPart(part)
  1731. if err != nil {
  1732. return added, err
  1733. }
  1734. if cs.ProposalBlockParts.ByteSize() > cs.state.ConsensusParams.Block.MaxBytes {
  1735. return added, fmt.Errorf("total size of proposal block parts exceeds maximum block bytes (%d > %d)",
  1736. cs.ProposalBlockParts.ByteSize(), cs.state.ConsensusParams.Block.MaxBytes,
  1737. )
  1738. }
  1739. if added && cs.ProposalBlockParts.IsComplete() {
  1740. bz, err := io.ReadAll(cs.ProposalBlockParts.GetReader())
  1741. if err != nil {
  1742. return added, err
  1743. }
  1744. var pbb = new(tmproto.Block)
  1745. err = proto.Unmarshal(bz, pbb)
  1746. if err != nil {
  1747. return added, err
  1748. }
  1749. block, err := types.BlockFromProto(pbb)
  1750. if err != nil {
  1751. return added, err
  1752. }
  1753. cs.ProposalBlock = block
  1754. // NOTE: it's possible to receive complete proposal blocks for future rounds without having the proposal
  1755. cs.logger.Info("received complete proposal block", "height", cs.ProposalBlock.Height, "hash", cs.ProposalBlock.Hash())
  1756. if err := cs.eventBus.PublishEventCompleteProposal(ctx, cs.CompleteProposalEvent()); err != nil {
  1757. cs.logger.Error("failed publishing event complete proposal", "err", err)
  1758. }
  1759. // Update Valid* if we can.
  1760. prevotes := cs.Votes.Prevotes(cs.Round)
  1761. blockID, hasTwoThirds := prevotes.TwoThirdsMajority()
  1762. if hasTwoThirds && !blockID.IsNil() && (cs.ValidRound < cs.Round) {
  1763. if cs.ProposalBlock.HashesTo(blockID.Hash) {
  1764. cs.logger.Debug(
  1765. "updating valid block to new proposal block",
  1766. "valid_round", cs.Round,
  1767. "valid_block_hash", cs.ProposalBlock.Hash(),
  1768. )
  1769. cs.ValidRound = cs.Round
  1770. cs.ValidBlock = cs.ProposalBlock
  1771. cs.ValidBlockParts = cs.ProposalBlockParts
  1772. }
  1773. // TODO: In case there is +2/3 majority in Prevotes set for some
  1774. // block and cs.ProposalBlock contains different block, either
  1775. // proposer is faulty or voting power of faulty processes is more
  1776. // than 1/3. We should trigger in the future accountability
  1777. // procedure at this point.
  1778. }
  1779. if cs.Step <= cstypes.RoundStepPropose && cs.isProposalComplete() {
  1780. // Move onto the next step
  1781. cs.enterPrevote(ctx, height, cs.Round)
  1782. if hasTwoThirds { // this is optimisation as this will be triggered when prevote is added
  1783. cs.enterPrecommit(ctx, height, cs.Round)
  1784. }
  1785. } else if cs.Step == cstypes.RoundStepCommit {
  1786. // If we're waiting on the proposal block...
  1787. cs.tryFinalizeCommit(ctx, height)
  1788. }
  1789. return added, nil
  1790. }
  1791. return added, nil
  1792. }
  1793. // Attempt to add the vote. if its a duplicate signature, dupeout the validator
  1794. func (cs *State) tryAddVote(ctx context.Context, vote *types.Vote, peerID types.NodeID) (bool, error) {
  1795. added, err := cs.addVote(ctx, vote, peerID)
  1796. if err != nil {
  1797. // If the vote height is off, we'll just ignore it,
  1798. // But if it's a conflicting sig, add it to the cs.evpool.
  1799. // If it's otherwise invalid, punish peer.
  1800. // nolint: gocritic
  1801. if voteErr, ok := err.(*types.ErrVoteConflictingVotes); ok {
  1802. if cs.privValidatorPubKey == nil {
  1803. return false, errPubKeyIsNotSet
  1804. }
  1805. if bytes.Equal(vote.ValidatorAddress, cs.privValidatorPubKey.Address()) {
  1806. cs.logger.Error(
  1807. "found conflicting vote from ourselves; did you unsafe_reset a validator?",
  1808. "height", vote.Height,
  1809. "round", vote.Round,
  1810. "type", vote.Type,
  1811. )
  1812. return added, err
  1813. }
  1814. // report conflicting votes to the evidence pool
  1815. cs.evpool.ReportConflictingVotes(voteErr.VoteA, voteErr.VoteB)
  1816. cs.logger.Debug(
  1817. "found and sent conflicting votes to the evidence pool",
  1818. "vote_a", voteErr.VoteA,
  1819. "vote_b", voteErr.VoteB,
  1820. )
  1821. return added, err
  1822. } else if errors.Is(err, types.ErrVoteNonDeterministicSignature) {
  1823. cs.logger.Debug("vote has non-deterministic signature", "err", err)
  1824. } else {
  1825. // Either
  1826. // 1) bad peer OR
  1827. // 2) not a bad peer? this can also err sometimes with "Unexpected step" OR
  1828. // 3) tmkms use with multiple validators connecting to a single tmkms instance
  1829. // (https://github.com/tendermint/tendermint/issues/3839).
  1830. cs.logger.Info("failed attempting to add vote", "err", err)
  1831. return added, ErrAddingVote
  1832. }
  1833. }
  1834. return added, nil
  1835. }
  1836. func (cs *State) addVote(
  1837. ctx context.Context,
  1838. vote *types.Vote,
  1839. peerID types.NodeID,
  1840. ) (added bool, err error) {
  1841. cs.logger.Debug(
  1842. "adding vote",
  1843. "vote_height", vote.Height,
  1844. "vote_type", vote.Type,
  1845. "val_index", vote.ValidatorIndex,
  1846. "cs_height", cs.Height,
  1847. )
  1848. // A precommit for the previous height?
  1849. // These come in while we wait timeoutCommit
  1850. if vote.Height+1 == cs.Height && vote.Type == tmproto.PrecommitType {
  1851. if cs.Step != cstypes.RoundStepNewHeight {
  1852. // Late precommit at prior height is ignored
  1853. cs.logger.Debug("precommit vote came in after commit timeout and has been ignored", "vote", vote)
  1854. return
  1855. }
  1856. added, err = cs.LastCommit.AddVote(vote)
  1857. if !added {
  1858. return
  1859. }
  1860. cs.logger.Debug("added vote to last precommits", "last_commit", cs.LastCommit.StringShort())
  1861. if err := cs.eventBus.PublishEventVote(ctx, types.EventDataVote{Vote: vote}); err != nil {
  1862. return added, err
  1863. }
  1864. cs.evsw.FireEvent(ctx, types.EventVoteValue, vote)
  1865. // if we can skip timeoutCommit and have all the votes now,
  1866. if cs.config.SkipTimeoutCommit && cs.LastCommit.HasAll() {
  1867. // go straight to new round (skip timeout commit)
  1868. // cs.scheduleTimeout(time.Duration(0), cs.Height, 0, cstypes.RoundStepNewHeight)
  1869. cs.enterNewRound(ctx, cs.Height, 0)
  1870. }
  1871. return
  1872. }
  1873. // Height mismatch is ignored.
  1874. // Not necessarily a bad peer, but not favorable behavior.
  1875. if vote.Height != cs.Height {
  1876. cs.logger.Debug("vote ignored and not added", "vote_height", vote.Height, "cs_height", cs.Height, "peer", peerID)
  1877. return
  1878. }
  1879. height := cs.Height
  1880. added, err = cs.Votes.AddVote(vote, peerID)
  1881. if !added {
  1882. // Either duplicate, or error upon cs.Votes.AddByIndex()
  1883. return
  1884. }
  1885. if err := cs.eventBus.PublishEventVote(ctx, types.EventDataVote{Vote: vote}); err != nil {
  1886. return added, err
  1887. }
  1888. cs.evsw.FireEvent(ctx, types.EventVoteValue, vote)
  1889. switch vote.Type {
  1890. case tmproto.PrevoteType:
  1891. prevotes := cs.Votes.Prevotes(vote.Round)
  1892. cs.logger.Debug("added vote to prevote", "vote", vote, "prevotes", prevotes.StringShort())
  1893. // Check to see if >2/3 of the voting power on the network voted for any non-nil block.
  1894. if blockID, ok := prevotes.TwoThirdsMajority(); ok && !blockID.IsNil() {
  1895. // Greater than 2/3 of the voting power on the network voted for some
  1896. // non-nil block
  1897. // Update Valid* if we can.
  1898. if cs.ValidRound < vote.Round && vote.Round == cs.Round {
  1899. if cs.ProposalBlock.HashesTo(blockID.Hash) {
  1900. cs.logger.Debug("updating valid block because of POL", "valid_round", cs.ValidRound, "pol_round", vote.Round)
  1901. cs.ValidRound = vote.Round
  1902. cs.ValidBlock = cs.ProposalBlock
  1903. cs.ValidBlockParts = cs.ProposalBlockParts
  1904. } else {
  1905. cs.logger.Debug(
  1906. "valid block we do not know about; set ProposalBlock=nil",
  1907. "proposal", cs.ProposalBlock.Hash(),
  1908. "block_id", blockID.Hash,
  1909. )
  1910. // we're getting the wrong block
  1911. cs.ProposalBlock = nil
  1912. }
  1913. if !cs.ProposalBlockParts.HasHeader(blockID.PartSetHeader) {
  1914. cs.ProposalBlockParts = types.NewPartSetFromHeader(blockID.PartSetHeader)
  1915. }
  1916. cs.evsw.FireEvent(ctx, types.EventValidBlockValue, &cs.RoundState)
  1917. if err := cs.eventBus.PublishEventValidBlock(ctx, cs.RoundStateEvent()); err != nil {
  1918. return added, err
  1919. }
  1920. }
  1921. }
  1922. // If +2/3 prevotes for *anything* for future round:
  1923. switch {
  1924. case cs.Round < vote.Round && prevotes.HasTwoThirdsAny():
  1925. // Round-skip if there is any 2/3+ of votes ahead of us
  1926. cs.enterNewRound(ctx, height, vote.Round)
  1927. case cs.Round == vote.Round && cstypes.RoundStepPrevote <= cs.Step: // current round
  1928. blockID, ok := prevotes.TwoThirdsMajority()
  1929. if ok && (cs.isProposalComplete() || blockID.IsNil()) {
  1930. cs.enterPrecommit(ctx, height, vote.Round)
  1931. } else if prevotes.HasTwoThirdsAny() {
  1932. cs.enterPrevoteWait(ctx, height, vote.Round)
  1933. }
  1934. case cs.Proposal != nil && 0 <= cs.Proposal.POLRound && cs.Proposal.POLRound == vote.Round:
  1935. // If the proposal is now complete, enter prevote of cs.Round.
  1936. if cs.isProposalComplete() {
  1937. cs.enterPrevote(ctx, height, cs.Round)
  1938. }
  1939. }
  1940. case tmproto.PrecommitType:
  1941. precommits := cs.Votes.Precommits(vote.Round)
  1942. cs.logger.Debug("added vote to precommit",
  1943. "height", vote.Height,
  1944. "round", vote.Round,
  1945. "validator", vote.ValidatorAddress.String(),
  1946. "vote_timestamp", vote.Timestamp,
  1947. "data", precommits.LogString())
  1948. blockID, ok := precommits.TwoThirdsMajority()
  1949. if ok {
  1950. // Executed as TwoThirdsMajority could be from a higher round
  1951. cs.enterNewRound(ctx, height, vote.Round)
  1952. cs.enterPrecommit(ctx, height, vote.Round)
  1953. if !blockID.IsNil() {
  1954. cs.enterCommit(ctx, height, vote.Round)
  1955. if cs.config.SkipTimeoutCommit && precommits.HasAll() {
  1956. cs.enterNewRound(ctx, cs.Height, 0)
  1957. }
  1958. } else {
  1959. cs.enterPrecommitWait(ctx, height, vote.Round)
  1960. }
  1961. } else if cs.Round <= vote.Round && precommits.HasTwoThirdsAny() {
  1962. cs.enterNewRound(ctx, height, vote.Round)
  1963. cs.enterPrecommitWait(ctx, height, vote.Round)
  1964. }
  1965. default:
  1966. panic(fmt.Sprintf("unexpected vote type %v", vote.Type))
  1967. }
  1968. return added, err
  1969. }
  1970. // CONTRACT: cs.privValidator is not nil.
  1971. func (cs *State) signVote(
  1972. ctx context.Context,
  1973. msgType tmproto.SignedMsgType,
  1974. hash []byte,
  1975. header types.PartSetHeader,
  1976. ) (*types.Vote, error) {
  1977. // Flush the WAL. Otherwise, we may not recompute the same vote to sign,
  1978. // and the privValidator will refuse to sign anything.
  1979. if err := cs.wal.FlushAndSync(); err != nil {
  1980. return nil, err
  1981. }
  1982. if cs.privValidatorPubKey == nil {
  1983. return nil, errPubKeyIsNotSet
  1984. }
  1985. addr := cs.privValidatorPubKey.Address()
  1986. valIdx, _ := cs.Validators.GetByAddress(addr)
  1987. vote := &types.Vote{
  1988. ValidatorAddress: addr,
  1989. ValidatorIndex: valIdx,
  1990. Height: cs.Height,
  1991. Round: cs.Round,
  1992. Timestamp: tmtime.Now(),
  1993. Type: msgType,
  1994. BlockID: types.BlockID{Hash: hash, PartSetHeader: header},
  1995. }
  1996. v := vote.ToProto()
  1997. // If the signedMessageType is for precommit,
  1998. // use our local precommit Timeout as the max wait time for getting a singed commit. The same goes for prevote.
  1999. var timeout time.Duration
  2000. switch msgType {
  2001. case tmproto.PrecommitType:
  2002. timeout = cs.config.TimeoutPrecommit
  2003. case tmproto.PrevoteType:
  2004. timeout = cs.config.TimeoutPrevote
  2005. default:
  2006. timeout = time.Second
  2007. }
  2008. ctxto, cancel := context.WithTimeout(ctx, timeout)
  2009. defer cancel()
  2010. err := cs.privValidator.SignVote(ctxto, cs.state.ChainID, v)
  2011. vote.Signature = v.Signature
  2012. vote.Timestamp = v.Timestamp
  2013. return vote, err
  2014. }
  2015. // sign the vote and publish on internalMsgQueue
  2016. func (cs *State) signAddVote(ctx context.Context, msgType tmproto.SignedMsgType, hash []byte, header types.PartSetHeader) *types.Vote {
  2017. if cs.privValidator == nil { // the node does not have a key
  2018. return nil
  2019. }
  2020. if cs.privValidatorPubKey == nil {
  2021. // Vote won't be signed, but it's not critical.
  2022. cs.logger.Error("signAddVote", "err", errPubKeyIsNotSet)
  2023. return nil
  2024. }
  2025. // If the node not in the validator set, do nothing.
  2026. if !cs.Validators.HasAddress(cs.privValidatorPubKey.Address()) {
  2027. return nil
  2028. }
  2029. // TODO: pass pubKey to signVote
  2030. vote, err := cs.signVote(ctx, msgType, hash, header)
  2031. if err == nil {
  2032. cs.sendInternalMessage(ctx, msgInfo{&VoteMessage{vote}, "", tmtime.Now()})
  2033. cs.logger.Debug("signed and pushed vote", "height", cs.Height, "round", cs.Round, "vote", vote)
  2034. return vote
  2035. }
  2036. cs.logger.Error("failed signing vote", "height", cs.Height, "round", cs.Round, "vote", vote, "err", err)
  2037. return nil
  2038. }
  2039. // updatePrivValidatorPubKey get's the private validator public key and
  2040. // memoizes it. This func returns an error if the private validator is not
  2041. // responding or responds with an error.
  2042. func (cs *State) updatePrivValidatorPubKey(rctx context.Context) error {
  2043. if cs.privValidator == nil {
  2044. return nil
  2045. }
  2046. var timeout time.Duration
  2047. if cs.config.TimeoutPrecommit > cs.config.TimeoutPrevote {
  2048. timeout = cs.config.TimeoutPrecommit
  2049. } else {
  2050. timeout = cs.config.TimeoutPrevote
  2051. }
  2052. // no GetPubKey retry beyond the proposal/voting in RetrySignerClient
  2053. if cs.Step >= cstypes.RoundStepPrecommit && cs.privValidatorType == types.RetrySignerClient {
  2054. timeout = 0
  2055. }
  2056. // set context timeout depending on the configuration and the State step,
  2057. // this helps in avoiding blocking of the remote signer connection.
  2058. ctxto, cancel := context.WithTimeout(rctx, timeout)
  2059. defer cancel()
  2060. pubKey, err := cs.privValidator.GetPubKey(ctxto)
  2061. if err != nil {
  2062. return err
  2063. }
  2064. cs.privValidatorPubKey = pubKey
  2065. return nil
  2066. }
  2067. // look back to check existence of the node's consensus votes before joining consensus
  2068. func (cs *State) checkDoubleSigningRisk(height int64) error {
  2069. if cs.privValidator != nil && cs.privValidatorPubKey != nil && cs.config.DoubleSignCheckHeight > 0 && height > 0 {
  2070. valAddr := cs.privValidatorPubKey.Address()
  2071. doubleSignCheckHeight := cs.config.DoubleSignCheckHeight
  2072. if doubleSignCheckHeight > height {
  2073. doubleSignCheckHeight = height
  2074. }
  2075. for i := int64(1); i < doubleSignCheckHeight; i++ {
  2076. lastCommit := cs.LoadCommit(height - i)
  2077. if lastCommit != nil {
  2078. for sigIdx, s := range lastCommit.Signatures {
  2079. if s.BlockIDFlag == types.BlockIDFlagCommit && bytes.Equal(s.ValidatorAddress, valAddr) {
  2080. cs.logger.Info("found signature from the same key", "sig", s, "idx", sigIdx, "height", height-i)
  2081. return ErrSignatureFoundInPastBlocks
  2082. }
  2083. }
  2084. }
  2085. }
  2086. }
  2087. return nil
  2088. }
  2089. func (cs *State) calculatePrevoteMessageDelayMetrics() {
  2090. if cs.Proposal == nil {
  2091. return
  2092. }
  2093. ps := cs.Votes.Prevotes(cs.Round)
  2094. pl := ps.List()
  2095. sort.Slice(pl, func(i, j int) bool {
  2096. return pl[i].Timestamp.Before(pl[j].Timestamp)
  2097. })
  2098. var votingPowerSeen int64
  2099. for _, v := range pl {
  2100. _, val := cs.Validators.GetByAddress(v.ValidatorAddress)
  2101. votingPowerSeen += val.VotingPower
  2102. if votingPowerSeen >= cs.Validators.TotalVotingPower()*2/3+1 {
  2103. cs.metrics.QuorumPrevoteMessageDelay.Set(v.Timestamp.Sub(cs.Proposal.Timestamp).Seconds())
  2104. break
  2105. }
  2106. }
  2107. if ps.HasAll() {
  2108. cs.metrics.FullPrevoteMessageDelay.Set(pl[len(pl)-1].Timestamp.Sub(cs.Proposal.Timestamp).Seconds())
  2109. }
  2110. }
  2111. //---------------------------------------------------------
  2112. func CompareHRS(h1 int64, r1 int32, s1 cstypes.RoundStepType, h2 int64, r2 int32, s2 cstypes.RoundStepType) int {
  2113. if h1 < h2 {
  2114. return -1
  2115. } else if h1 > h2 {
  2116. return 1
  2117. }
  2118. if r1 < r2 {
  2119. return -1
  2120. } else if r1 > r2 {
  2121. return 1
  2122. }
  2123. if s1 < s2 {
  2124. return -1
  2125. } else if s1 > s2 {
  2126. return 1
  2127. }
  2128. return 0
  2129. }
  2130. // repairWalFile decodes messages from src (until the decoder errors) and
  2131. // writes them to dst.
  2132. func repairWalFile(src, dst string) error {
  2133. in, err := os.Open(src)
  2134. if err != nil {
  2135. return err
  2136. }
  2137. defer in.Close()
  2138. out, err := os.Create(dst)
  2139. if err != nil {
  2140. return err
  2141. }
  2142. defer out.Close()
  2143. var (
  2144. dec = NewWALDecoder(in)
  2145. enc = NewWALEncoder(out)
  2146. )
  2147. // best-case repair (until first error is encountered)
  2148. for {
  2149. msg, err := dec.Decode()
  2150. if err != nil {
  2151. break
  2152. }
  2153. err = enc.Encode(msg)
  2154. if err != nil {
  2155. return fmt.Errorf("failed to encode msg: %w", err)
  2156. }
  2157. }
  2158. return nil
  2159. }
  2160. func (cs *State) calculateProposalTimestampDifferenceMetric() {
  2161. if cs.Proposal != nil && cs.Proposal.POLRound == -1 {
  2162. tp := types.SynchronyParams{
  2163. Precision: cs.state.ConsensusParams.Synchrony.Precision,
  2164. MessageDelay: cs.state.ConsensusParams.Synchrony.MessageDelay,
  2165. }
  2166. isTimely := cs.Proposal.IsTimely(cs.ProposalReceiveTime, tp, cs.state.InitialHeight)
  2167. cs.metrics.ProposalTimestampDifference.With("is_timely", fmt.Sprintf("%t", isTimely)).
  2168. Observe(cs.ProposalReceiveTime.Sub(cs.Proposal.Timestamp).Seconds())
  2169. }
  2170. }
  2171. // proposerWaitTime determines how long the proposer should wait to propose its next block.
  2172. // If the result is zero, a block can be proposed immediately.
  2173. //
  2174. // Block times must be monotonically increasing, so if the block time of the previous
  2175. // block is larger than the proposer's current time, then the proposer will sleep
  2176. // until its local clock exceeds the previous block time.
  2177. func proposerWaitTime(lt tmtime.Source, bt time.Time) time.Duration {
  2178. t := lt.Now()
  2179. if bt.After(t) {
  2180. return bt.Sub(t)
  2181. }
  2182. return 0
  2183. }