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.

2453 lines
75 KiB

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
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
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
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
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
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
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
  1. package consensus
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "os"
  10. "runtime/debug"
  11. "sync"
  12. "time"
  13. "github.com/gogo/protobuf/proto"
  14. "github.com/tendermint/tendermint/config"
  15. "github.com/tendermint/tendermint/crypto"
  16. cstypes "github.com/tendermint/tendermint/internal/consensus/types"
  17. "github.com/tendermint/tendermint/internal/eventbus"
  18. sm "github.com/tendermint/tendermint/internal/state"
  19. tmevents "github.com/tendermint/tendermint/libs/events"
  20. "github.com/tendermint/tendermint/libs/log"
  21. tmmath "github.com/tendermint/tendermint/libs/math"
  22. tmos "github.com/tendermint/tendermint/libs/os"
  23. "github.com/tendermint/tendermint/libs/service"
  24. tmtime "github.com/tendermint/tendermint/libs/time"
  25. "github.com/tendermint/tendermint/privval"
  26. tmgrpc "github.com/tendermint/tendermint/privval/grpc"
  27. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  28. "github.com/tendermint/tendermint/types"
  29. )
  30. // Consensus sentinel errors
  31. var (
  32. ErrInvalidProposalSignature = errors.New("error invalid proposal signature")
  33. ErrInvalidProposalPOLRound = errors.New("error invalid proposal POL round")
  34. ErrAddingVote = errors.New("error adding vote")
  35. ErrSignatureFoundInPastBlocks = errors.New("found signature from the same key")
  36. errPubKeyIsNotSet = errors.New("pubkey is not set. Look for \"Can't get private validator pubkey\" errors")
  37. )
  38. var msgQueueSize = 1000
  39. // msgs from the reactor which may update the state
  40. type msgInfo struct {
  41. Msg Message `json:"msg"`
  42. PeerID types.NodeID `json:"peer_key"`
  43. }
  44. // internally generated messages which may update the state
  45. type timeoutInfo struct {
  46. Duration time.Duration `json:"duration"`
  47. Height int64 `json:"height"`
  48. Round int32 `json:"round"`
  49. Step cstypes.RoundStepType `json:"step"`
  50. }
  51. func (ti *timeoutInfo) String() string {
  52. return fmt.Sprintf("%v ; %d/%d %v", ti.Duration, ti.Height, ti.Round, ti.Step)
  53. }
  54. // interface to the mempool
  55. type txNotifier interface {
  56. TxsAvailable() <-chan struct{}
  57. }
  58. // interface to the evidence pool
  59. type evidencePool interface {
  60. // reports conflicting votes to the evidence pool to be processed into evidence
  61. ReportConflictingVotes(voteA, voteB *types.Vote)
  62. }
  63. // State handles execution of the consensus algorithm.
  64. // It processes votes and proposals, and upon reaching agreement,
  65. // commits blocks to the chain and executes them against the application.
  66. // The internal state machine receives input from peers, the internal validator, and from a timer.
  67. type State struct {
  68. service.BaseService
  69. logger log.Logger
  70. // config details
  71. config *config.ConsensusConfig
  72. privValidator types.PrivValidator // for signing votes
  73. privValidatorType types.PrivValidatorType
  74. // store blocks and commits
  75. blockStore sm.BlockStore
  76. // create and execute blocks
  77. blockExec *sm.BlockExecutor
  78. // notify us if txs are available
  79. txNotifier txNotifier
  80. // add evidence to the pool
  81. // when it's detected
  82. evpool evidencePool
  83. // internal state
  84. mtx sync.RWMutex
  85. cstypes.RoundState
  86. state sm.State // State until height-1.
  87. // privValidator pubkey, memoized for the duration of one block
  88. // to avoid extra requests to HSM
  89. privValidatorPubKey crypto.PubKey
  90. // state changes may be triggered by: msgs from peers,
  91. // msgs from ourself, or by timeouts
  92. peerMsgQueue chan msgInfo
  93. internalMsgQueue chan msgInfo
  94. timeoutTicker TimeoutTicker
  95. // information about about added votes and block parts are written on this channel
  96. // so statistics can be computed by reactor
  97. statsMsgQueue chan msgInfo
  98. // we use eventBus to trigger msg broadcasts in the reactor,
  99. // and to notify external subscribers, eg. through a websocket
  100. eventBus *eventbus.EventBus
  101. // a Write-Ahead Log ensures we can recover from any kind of crash
  102. // and helps us avoid signing conflicting votes
  103. wal WAL
  104. replayMode bool // so we don't log signing errors during replay
  105. doWALCatchup bool // determines if we even try to do the catchup
  106. // for tests where we want to limit the number of transitions the state makes
  107. nSteps int
  108. // some functions can be overwritten for testing
  109. decideProposal func(ctx context.Context, height int64, round int32)
  110. doPrevote func(ctx context.Context, height int64, round int32)
  111. setProposal func(proposal *types.Proposal) error
  112. // closed when we finish shutting down
  113. done chan struct{}
  114. // synchronous pubsub between consensus state and reactor.
  115. // state only emits EventNewRoundStep, EventValidBlock, and EventVote
  116. evsw tmevents.EventSwitch
  117. // for reporting metrics
  118. metrics *Metrics
  119. // wait the channel event happening for shutting down the state gracefully
  120. onStopCh chan *cstypes.RoundState
  121. }
  122. // StateOption sets an optional parameter on the State.
  123. type StateOption func(*State)
  124. // NewState returns a new State.
  125. func NewState(
  126. ctx context.Context,
  127. logger log.Logger,
  128. cfg *config.ConsensusConfig,
  129. state sm.State,
  130. blockExec *sm.BlockExecutor,
  131. blockStore sm.BlockStore,
  132. txNotifier txNotifier,
  133. evpool evidencePool,
  134. options ...StateOption,
  135. ) *State {
  136. cs := &State{
  137. logger: logger,
  138. config: cfg,
  139. blockExec: blockExec,
  140. blockStore: blockStore,
  141. txNotifier: txNotifier,
  142. peerMsgQueue: make(chan msgInfo, msgQueueSize),
  143. internalMsgQueue: make(chan msgInfo, msgQueueSize),
  144. timeoutTicker: NewTimeoutTicker(logger),
  145. statsMsgQueue: make(chan msgInfo, msgQueueSize),
  146. done: make(chan struct{}),
  147. doWALCatchup: true,
  148. wal: nilWAL{},
  149. evpool: evpool,
  150. evsw: tmevents.NewEventSwitch(logger),
  151. metrics: NopMetrics(),
  152. onStopCh: make(chan *cstypes.RoundState),
  153. }
  154. // set function defaults (may be overwritten before calling Start)
  155. cs.decideProposal = cs.defaultDecideProposal
  156. cs.doPrevote = cs.defaultDoPrevote
  157. cs.setProposal = cs.defaultSetProposal
  158. // We have no votes, so reconstruct LastCommit from SeenCommit.
  159. if state.LastBlockHeight > 0 {
  160. cs.reconstructLastCommit(state)
  161. }
  162. cs.updateToState(ctx, state)
  163. // NOTE: we do not call scheduleRound0 yet, we do that upon Start()
  164. cs.BaseService = *service.NewBaseService(logger, "State", cs)
  165. for _, option := range options {
  166. option(cs)
  167. }
  168. return cs
  169. }
  170. // SetEventBus sets event bus.
  171. func (cs *State) SetEventBus(b *eventbus.EventBus) {
  172. cs.eventBus = b
  173. cs.blockExec.SetEventBus(b)
  174. }
  175. // StateMetrics sets the metrics.
  176. func StateMetrics(metrics *Metrics) StateOption {
  177. return func(cs *State) { cs.metrics = metrics }
  178. }
  179. // String returns a string.
  180. func (cs *State) String() string {
  181. // better not to access shared variables
  182. return "ConsensusState"
  183. }
  184. // GetState returns a copy of the chain state.
  185. func (cs *State) GetState() sm.State {
  186. cs.mtx.RLock()
  187. defer cs.mtx.RUnlock()
  188. return cs.state.Copy()
  189. }
  190. // GetLastHeight returns the last height committed.
  191. // If there were no blocks, returns 0.
  192. func (cs *State) GetLastHeight() int64 {
  193. cs.mtx.RLock()
  194. defer cs.mtx.RUnlock()
  195. return cs.RoundState.Height - 1
  196. }
  197. // GetRoundState returns a shallow copy of the internal consensus state.
  198. func (cs *State) GetRoundState() *cstypes.RoundState {
  199. cs.mtx.RLock()
  200. defer cs.mtx.RUnlock()
  201. // NOTE: this might be dodgy, as RoundState itself isn't thread
  202. // safe as it contains a number of pointers and is explicitly
  203. // not thread safe.
  204. rs := cs.RoundState // copy
  205. return &rs
  206. }
  207. // GetRoundStateJSON returns a json of RoundState.
  208. func (cs *State) GetRoundStateJSON() ([]byte, error) {
  209. cs.mtx.RLock()
  210. defer cs.mtx.RUnlock()
  211. return json.Marshal(cs.RoundState)
  212. }
  213. // GetRoundStateSimpleJSON returns a json of RoundStateSimple
  214. func (cs *State) GetRoundStateSimpleJSON() ([]byte, error) {
  215. cs.mtx.RLock()
  216. defer cs.mtx.RUnlock()
  217. return json.Marshal(cs.RoundState.RoundStateSimple())
  218. }
  219. // GetValidators returns a copy of the current validators.
  220. func (cs *State) GetValidators() (int64, []*types.Validator) {
  221. cs.mtx.RLock()
  222. defer cs.mtx.RUnlock()
  223. return cs.state.LastBlockHeight, cs.state.Validators.Copy().Validators
  224. }
  225. // SetPrivValidator sets the private validator account for signing votes. It
  226. // immediately requests pubkey and caches it.
  227. func (cs *State) SetPrivValidator(ctx context.Context, priv types.PrivValidator) {
  228. cs.mtx.Lock()
  229. defer cs.mtx.Unlock()
  230. cs.privValidator = priv
  231. if priv != nil {
  232. switch t := priv.(type) {
  233. case *privval.RetrySignerClient:
  234. cs.privValidatorType = types.RetrySignerClient
  235. case *privval.FilePV:
  236. cs.privValidatorType = types.FileSignerClient
  237. case *privval.SignerClient:
  238. cs.privValidatorType = types.SignerSocketClient
  239. case *tmgrpc.SignerClient:
  240. cs.privValidatorType = types.SignerGRPCClient
  241. case types.MockPV:
  242. cs.privValidatorType = types.MockSignerClient
  243. case *types.ErroringMockPV:
  244. cs.privValidatorType = types.ErrorMockSignerClient
  245. default:
  246. cs.logger.Error("unsupported priv validator type", "err",
  247. fmt.Errorf("error privValidatorType %s", t))
  248. }
  249. }
  250. if err := cs.updatePrivValidatorPubKey(ctx); err != nil {
  251. cs.logger.Error("failed to get private validator pubkey", "err", err)
  252. }
  253. }
  254. // SetTimeoutTicker sets the local timer. It may be useful to overwrite for
  255. // testing.
  256. func (cs *State) SetTimeoutTicker(timeoutTicker TimeoutTicker) {
  257. cs.mtx.Lock()
  258. cs.timeoutTicker = timeoutTicker
  259. cs.mtx.Unlock()
  260. }
  261. // LoadCommit loads the commit for a given height.
  262. func (cs *State) LoadCommit(height int64) *types.Commit {
  263. cs.mtx.RLock()
  264. defer cs.mtx.RUnlock()
  265. if height == cs.blockStore.Height() {
  266. commit := cs.blockStore.LoadSeenCommit()
  267. // NOTE: Retrieving the height of the most recent block and retrieving
  268. // the most recent commit does not currently occur as an atomic
  269. // operation. We check the height and commit here in case a more recent
  270. // commit has arrived since retrieving the latest height.
  271. if commit != nil && commit.Height == height {
  272. return commit
  273. }
  274. }
  275. return cs.blockStore.LoadBlockCommit(height)
  276. }
  277. // OnStart loads the latest state via the WAL, and starts the timeout and
  278. // receive routines.
  279. func (cs *State) OnStart(ctx context.Context) error {
  280. // We may set the WAL in testing before calling Start, so only OpenWAL if its
  281. // still the nilWAL.
  282. if _, ok := cs.wal.(nilWAL); ok {
  283. if err := cs.loadWalFile(ctx); err != nil {
  284. return err
  285. }
  286. }
  287. // We may have lost some votes if the process crashed reload from consensus
  288. // log to catchup.
  289. if cs.doWALCatchup {
  290. repairAttempted := false
  291. LOOP:
  292. for {
  293. err := cs.catchupReplay(ctx, cs.Height)
  294. switch {
  295. case err == nil:
  296. break LOOP
  297. case !IsDataCorruptionError(err):
  298. cs.logger.Error("error on catchup replay; proceeding to start state anyway", "err", err)
  299. break LOOP
  300. case repairAttempted:
  301. return err
  302. }
  303. cs.logger.Error("the WAL file is corrupted; attempting repair", "err", err)
  304. // 1) prep work
  305. if err := cs.wal.Stop(); err != nil {
  306. return err
  307. }
  308. repairAttempted = true
  309. // 2) backup original WAL file
  310. corruptedFile := fmt.Sprintf("%s.CORRUPTED", cs.config.WalFile())
  311. if err := tmos.CopyFile(cs.config.WalFile(), corruptedFile); err != nil {
  312. return err
  313. }
  314. cs.logger.Debug("backed up WAL file", "src", cs.config.WalFile(), "dst", corruptedFile)
  315. // 3) try to repair (WAL file will be overwritten!)
  316. if err := repairWalFile(corruptedFile, cs.config.WalFile()); err != nil {
  317. cs.logger.Error("the WAL repair failed", "err", err)
  318. return err
  319. }
  320. cs.logger.Info("successful WAL repair")
  321. // reload WAL file
  322. if err := cs.loadWalFile(ctx); err != nil {
  323. return err
  324. }
  325. }
  326. }
  327. if err := cs.evsw.Start(ctx); err != nil {
  328. return err
  329. }
  330. // we need the timeoutRoutine for replay so
  331. // we don't block on the tick chan.
  332. // NOTE: we will get a build up of garbage go routines
  333. // firing on the tockChan until the receiveRoutine is started
  334. // to deal with them (by that point, at most one will be valid)
  335. if err := cs.timeoutTicker.Start(ctx); err != nil {
  336. return err
  337. }
  338. // Double Signing Risk Reduction
  339. if err := cs.checkDoubleSigningRisk(cs.Height); err != nil {
  340. return err
  341. }
  342. // now start the receiveRoutine
  343. go cs.receiveRoutine(ctx, 0)
  344. // schedule the first round!
  345. // use GetRoundState so we don't race the receiveRoutine for access
  346. cs.scheduleRound0(cs.GetRoundState())
  347. return nil
  348. }
  349. // timeoutRoutine: receive requests for timeouts on tickChan and fire timeouts on tockChan
  350. // receiveRoutine: serializes processing of proposoals, block parts, votes; coordinates state transitions
  351. //
  352. // this is only used in tests.
  353. func (cs *State) startRoutines(ctx context.Context, maxSteps int) {
  354. err := cs.timeoutTicker.Start(ctx)
  355. if err != nil {
  356. cs.logger.Error("failed to start timeout ticker", "err", err)
  357. return
  358. }
  359. go cs.receiveRoutine(ctx, maxSteps)
  360. }
  361. // loadWalFile loads WAL data from file. It overwrites cs.wal.
  362. func (cs *State) loadWalFile(ctx context.Context) error {
  363. wal, err := cs.OpenWAL(ctx, cs.config.WalFile())
  364. if err != nil {
  365. cs.logger.Error("failed to load state WAL", "err", err)
  366. return err
  367. }
  368. cs.wal = wal
  369. return nil
  370. }
  371. // OnStop implements service.Service.
  372. func (cs *State) OnStop() {
  373. // If the node is committing a new block, wait until it is finished!
  374. if cs.GetRoundState().Step == cstypes.RoundStepCommit {
  375. select {
  376. case <-cs.onStopCh:
  377. case <-time.After(cs.config.TimeoutCommit):
  378. cs.logger.Error("OnStop: timeout waiting for commit to finish", "time", cs.config.TimeoutCommit)
  379. }
  380. }
  381. close(cs.onStopCh)
  382. if cs.evsw.IsRunning() {
  383. if err := cs.evsw.Stop(); err != nil {
  384. if !errors.Is(err, service.ErrAlreadyStopped) {
  385. cs.logger.Error("failed trying to stop eventSwitch", "error", err)
  386. }
  387. }
  388. }
  389. if cs.timeoutTicker.IsRunning() {
  390. if err := cs.timeoutTicker.Stop(); err != nil {
  391. if !errors.Is(err, service.ErrAlreadyStopped) {
  392. cs.logger.Error("failed trying to stop timeoutTicket", "error", err)
  393. }
  394. }
  395. }
  396. // WAL is stopped in receiveRoutine.
  397. }
  398. // Wait waits for the the main routine to return.
  399. // NOTE: be sure to Stop() the event switch and drain
  400. // any event channels or this may deadlock
  401. func (cs *State) Wait() {
  402. <-cs.done
  403. }
  404. // OpenWAL opens a file to log all consensus messages and timeouts for
  405. // deterministic accountability.
  406. func (cs *State) OpenWAL(ctx context.Context, walFile string) (WAL, error) {
  407. wal, err := NewWAL(ctx, cs.logger.With("wal", walFile), walFile)
  408. if err != nil {
  409. cs.logger.Error("failed to open WAL", "file", walFile, "err", err)
  410. return nil, err
  411. }
  412. if err := wal.Start(ctx); err != nil {
  413. cs.logger.Error("failed to start WAL", "err", err)
  414. return nil, err
  415. }
  416. return wal, nil
  417. }
  418. //------------------------------------------------------------
  419. // Public interface for passing messages into the consensus state, possibly causing a state transition.
  420. // If peerID == "", the msg is considered internal.
  421. // Messages are added to the appropriate queue (peer or internal).
  422. // If the queue is full, the function may block.
  423. // TODO: should these return anything or let callers just use events?
  424. // AddVote inputs a vote.
  425. func (cs *State) AddVote(ctx context.Context, vote *types.Vote, peerID types.NodeID) error {
  426. if peerID == "" {
  427. select {
  428. case <-ctx.Done():
  429. return ctx.Err()
  430. case cs.internalMsgQueue <- msgInfo{&VoteMessage{vote}, ""}:
  431. return nil
  432. }
  433. } else {
  434. select {
  435. case <-ctx.Done():
  436. return ctx.Err()
  437. case cs.peerMsgQueue <- msgInfo{&VoteMessage{vote}, peerID}:
  438. return nil
  439. }
  440. }
  441. // TODO: wait for event?!
  442. }
  443. // SetProposal inputs a proposal.
  444. func (cs *State) SetProposal(ctx context.Context, proposal *types.Proposal, peerID types.NodeID) error {
  445. if peerID == "" {
  446. select {
  447. case <-ctx.Done():
  448. return ctx.Err()
  449. case cs.internalMsgQueue <- msgInfo{&ProposalMessage{proposal}, ""}:
  450. return nil
  451. }
  452. } else {
  453. select {
  454. case <-ctx.Done():
  455. return ctx.Err()
  456. case cs.peerMsgQueue <- msgInfo{&ProposalMessage{proposal}, peerID}:
  457. return nil
  458. }
  459. }
  460. // TODO: wait for event?!
  461. }
  462. // AddProposalBlockPart inputs a part of the proposal block.
  463. func (cs *State) AddProposalBlockPart(ctx context.Context, height int64, round int32, part *types.Part, peerID types.NodeID) error {
  464. if peerID == "" {
  465. select {
  466. case <-ctx.Done():
  467. return ctx.Err()
  468. case cs.internalMsgQueue <- msgInfo{&BlockPartMessage{height, round, part}, ""}:
  469. return nil
  470. }
  471. } else {
  472. select {
  473. case <-ctx.Done():
  474. return ctx.Err()
  475. case cs.peerMsgQueue <- msgInfo{&BlockPartMessage{height, round, part}, peerID}:
  476. return nil
  477. }
  478. }
  479. // TODO: wait for event?!
  480. }
  481. // SetProposalAndBlock inputs the proposal and all block parts.
  482. func (cs *State) SetProposalAndBlock(
  483. ctx context.Context,
  484. proposal *types.Proposal,
  485. block *types.Block,
  486. parts *types.PartSet,
  487. peerID types.NodeID,
  488. ) error {
  489. if err := cs.SetProposal(ctx, proposal, peerID); err != nil {
  490. return err
  491. }
  492. for i := 0; i < int(parts.Total()); i++ {
  493. part := parts.GetPart(i)
  494. if err := cs.AddProposalBlockPart(ctx, proposal.Height, proposal.Round, part, peerID); err != nil {
  495. return err
  496. }
  497. }
  498. return nil
  499. }
  500. //------------------------------------------------------------
  501. // internal functions for managing the state
  502. func (cs *State) updateHeight(height int64) {
  503. cs.metrics.Height.Set(float64(height))
  504. cs.Height = height
  505. }
  506. func (cs *State) updateRoundStep(round int32, step cstypes.RoundStepType) {
  507. cs.Round = round
  508. cs.Step = step
  509. }
  510. // enterNewRound(height, 0) at cs.StartTime.
  511. func (cs *State) scheduleRound0(rs *cstypes.RoundState) {
  512. // cs.logger.Info("scheduleRound0", "now", tmtime.Now(), "startTime", cs.StartTime)
  513. sleepDuration := rs.StartTime.Sub(tmtime.Now())
  514. cs.scheduleTimeout(sleepDuration, rs.Height, 0, cstypes.RoundStepNewHeight)
  515. }
  516. // Attempt to schedule a timeout (by sending timeoutInfo on the tickChan)
  517. func (cs *State) scheduleTimeout(duration time.Duration, height int64, round int32, step cstypes.RoundStepType) {
  518. cs.timeoutTicker.ScheduleTimeout(timeoutInfo{duration, height, round, step})
  519. }
  520. // send a msg into the receiveRoutine regarding our own proposal, block part, or vote
  521. func (cs *State) sendInternalMessage(ctx context.Context, mi msgInfo) {
  522. select {
  523. case <-ctx.Done():
  524. case cs.internalMsgQueue <- mi:
  525. default:
  526. // NOTE: using the go-routine means our votes can
  527. // be processed out of order.
  528. // TODO: use CList here for strict determinism and
  529. // attempt push to internalMsgQueue in receiveRoutine
  530. cs.logger.Debug("internal msg queue is full; using a go-routine")
  531. go func() {
  532. select {
  533. case <-ctx.Done():
  534. case cs.internalMsgQueue <- mi:
  535. }
  536. }()
  537. }
  538. }
  539. // Reconstruct LastCommit from SeenCommit, which we saved along with the block,
  540. // (which happens even before saving the state)
  541. func (cs *State) reconstructLastCommit(state sm.State) {
  542. commit := cs.blockStore.LoadSeenCommit()
  543. if commit == nil || commit.Height != state.LastBlockHeight {
  544. commit = cs.blockStore.LoadBlockCommit(state.LastBlockHeight)
  545. }
  546. if commit == nil {
  547. panic(fmt.Sprintf(
  548. "failed to reconstruct last commit; commit for height %v not found",
  549. state.LastBlockHeight,
  550. ))
  551. }
  552. lastPrecommits := types.CommitToVoteSet(state.ChainID, commit, state.LastValidators)
  553. if !lastPrecommits.HasTwoThirdsMajority() {
  554. panic("failed to reconstruct last commit; does not have +2/3 maj")
  555. }
  556. cs.LastCommit = lastPrecommits
  557. }
  558. // Updates State and increments height to match that of state.
  559. // The round becomes 0 and cs.Step becomes cstypes.RoundStepNewHeight.
  560. func (cs *State) updateToState(ctx context.Context, state sm.State) {
  561. if cs.CommitRound > -1 && 0 < cs.Height && cs.Height != state.LastBlockHeight {
  562. panic(fmt.Sprintf(
  563. "updateToState() expected state height of %v but found %v",
  564. cs.Height, state.LastBlockHeight,
  565. ))
  566. }
  567. if !cs.state.IsEmpty() {
  568. if cs.state.LastBlockHeight > 0 && cs.state.LastBlockHeight+1 != cs.Height {
  569. // This might happen when someone else is mutating cs.state.
  570. // Someone forgot to pass in state.Copy() somewhere?!
  571. panic(fmt.Sprintf(
  572. "inconsistent cs.state.LastBlockHeight+1 %v vs cs.Height %v",
  573. cs.state.LastBlockHeight+1, cs.Height,
  574. ))
  575. }
  576. if cs.state.LastBlockHeight > 0 && cs.Height == cs.state.InitialHeight {
  577. panic(fmt.Sprintf(
  578. "inconsistent cs.state.LastBlockHeight %v, expected 0 for initial height %v",
  579. cs.state.LastBlockHeight, cs.state.InitialHeight,
  580. ))
  581. }
  582. // If state isn't further out than cs.state, just ignore.
  583. // This happens when SwitchToConsensus() is called in the reactor.
  584. // We don't want to reset e.g. the Votes, but we still want to
  585. // signal the new round step, because other services (eg. txNotifier)
  586. // depend on having an up-to-date peer state!
  587. if state.LastBlockHeight <= cs.state.LastBlockHeight {
  588. cs.logger.Debug(
  589. "ignoring updateToState()",
  590. "new_height", state.LastBlockHeight+1,
  591. "old_height", cs.state.LastBlockHeight+1,
  592. )
  593. cs.newStep(ctx)
  594. return
  595. }
  596. }
  597. // Reset fields based on state.
  598. validators := state.Validators
  599. switch {
  600. case state.LastBlockHeight == 0: // Very first commit should be empty.
  601. cs.LastCommit = (*types.VoteSet)(nil)
  602. case cs.CommitRound > -1 && cs.Votes != nil: // Otherwise, use cs.Votes
  603. if !cs.Votes.Precommits(cs.CommitRound).HasTwoThirdsMajority() {
  604. panic(fmt.Sprintf(
  605. "wanted to form a commit, but precommits (H/R: %d/%d) didn't have 2/3+: %v",
  606. state.LastBlockHeight, cs.CommitRound, cs.Votes.Precommits(cs.CommitRound),
  607. ))
  608. }
  609. cs.LastCommit = cs.Votes.Precommits(cs.CommitRound)
  610. case cs.LastCommit == nil:
  611. // NOTE: when Tendermint starts, it has no votes. reconstructLastCommit
  612. // must be called to reconstruct LastCommit from SeenCommit.
  613. panic(fmt.Sprintf(
  614. "last commit cannot be empty after initial block (H:%d)",
  615. state.LastBlockHeight+1,
  616. ))
  617. }
  618. // Next desired block height
  619. height := state.LastBlockHeight + 1
  620. if height == 1 {
  621. height = state.InitialHeight
  622. }
  623. // RoundState fields
  624. cs.updateHeight(height)
  625. cs.updateRoundStep(0, cstypes.RoundStepNewHeight)
  626. if cs.CommitTime.IsZero() {
  627. // "Now" makes it easier to sync up dev nodes.
  628. // We add timeoutCommit to allow transactions
  629. // to be gathered for the first block.
  630. // And alternative solution that relies on clocks:
  631. // cs.StartTime = state.LastBlockTime.Add(timeoutCommit)
  632. cs.StartTime = cs.config.Commit(tmtime.Now())
  633. } else {
  634. cs.StartTime = cs.config.Commit(cs.CommitTime)
  635. }
  636. cs.Validators = validators
  637. cs.Proposal = nil
  638. cs.ProposalBlock = nil
  639. cs.ProposalBlockParts = nil
  640. cs.LockedRound = -1
  641. cs.LockedBlock = nil
  642. cs.LockedBlockParts = nil
  643. cs.ValidRound = -1
  644. cs.ValidBlock = nil
  645. cs.ValidBlockParts = nil
  646. cs.Votes = cstypes.NewHeightVoteSet(state.ChainID, height, validators)
  647. cs.CommitRound = -1
  648. cs.LastValidators = state.LastValidators
  649. cs.TriggeredTimeoutPrecommit = false
  650. cs.state = state
  651. // Finally, broadcast RoundState
  652. cs.newStep(ctx)
  653. }
  654. func (cs *State) newStep(ctx context.Context) {
  655. rs := cs.RoundStateEvent()
  656. if err := cs.wal.Write(rs); err != nil {
  657. cs.logger.Error("failed writing to WAL", "err", err)
  658. }
  659. cs.nSteps++
  660. // newStep is called by updateToState in NewState before the eventBus is set!
  661. if cs.eventBus != nil {
  662. if err := cs.eventBus.PublishEventNewRoundStep(ctx, rs); err != nil {
  663. cs.logger.Error("failed publishing new round step", "err", err)
  664. }
  665. cs.evsw.FireEvent(ctx, types.EventNewRoundStepValue, &cs.RoundState)
  666. }
  667. }
  668. //-----------------------------------------
  669. // the main go routines
  670. // receiveRoutine handles messages which may cause state transitions.
  671. // it's argument (n) is the number of messages to process before exiting - use 0 to run forever
  672. // It keeps the RoundState and is the only thing that updates it.
  673. // Updates (state transitions) happen on timeouts, complete proposals, and 2/3 majorities.
  674. // State must be locked before any internal state is updated.
  675. func (cs *State) receiveRoutine(ctx context.Context, maxSteps int) {
  676. onExit := func(cs *State) {
  677. // NOTE: the internalMsgQueue may have signed messages from our
  678. // priv_val that haven't hit the WAL, but its ok because
  679. // priv_val tracks LastSig
  680. // close wal now that we're done writing to it
  681. if err := cs.wal.Stop(); err != nil {
  682. if !errors.Is(err, service.ErrAlreadyStopped) {
  683. cs.logger.Error("failed trying to stop WAL", "error", err)
  684. }
  685. }
  686. cs.wal.Wait()
  687. close(cs.done)
  688. }
  689. defer func() {
  690. if r := recover(); r != nil {
  691. cs.logger.Error("CONSENSUS FAILURE!!!", "err", r, "stack", string(debug.Stack()))
  692. // stop gracefully
  693. //
  694. // NOTE: We most probably shouldn't be running any further when there is
  695. // some unexpected panic. Some unknown error happened, and so we don't
  696. // know if that will result in the validator signing an invalid thing. It
  697. // might be worthwhile to explore a mechanism for manual resuming via
  698. // some console or secure RPC system, but for now, halting the chain upon
  699. // unexpected consensus bugs sounds like the better option.
  700. onExit(cs)
  701. }
  702. }()
  703. for {
  704. if maxSteps > 0 {
  705. if cs.nSteps >= maxSteps {
  706. cs.logger.Debug("reached max steps; exiting receive routine")
  707. cs.nSteps = 0
  708. return
  709. }
  710. }
  711. rs := cs.RoundState
  712. var mi msgInfo
  713. select {
  714. case <-cs.txNotifier.TxsAvailable():
  715. cs.handleTxsAvailable(ctx)
  716. case mi = <-cs.peerMsgQueue:
  717. if err := cs.wal.Write(mi); err != nil {
  718. cs.logger.Error("failed writing to WAL", "err", err)
  719. }
  720. // handles proposals, block parts, votes
  721. // may generate internal events (votes, complete proposals, 2/3 majorities)
  722. cs.handleMsg(ctx, mi)
  723. case mi = <-cs.internalMsgQueue:
  724. err := cs.wal.WriteSync(mi) // NOTE: fsync
  725. if err != nil {
  726. panic(fmt.Sprintf(
  727. "failed to write %v msg to consensus WAL due to %v; check your file system and restart the node",
  728. mi, err,
  729. ))
  730. }
  731. // handles proposals, block parts, votes
  732. cs.handleMsg(ctx, mi)
  733. case ti := <-cs.timeoutTicker.Chan(): // tockChan:
  734. if err := cs.wal.Write(ti); err != nil {
  735. cs.logger.Error("failed writing to WAL", "err", err)
  736. }
  737. // if the timeout is relevant to the rs
  738. // go to the next step
  739. cs.handleTimeout(ctx, ti, rs)
  740. case <-ctx.Done():
  741. onExit(cs)
  742. return
  743. }
  744. // TODO should we handle context cancels here?
  745. }
  746. }
  747. // state transitions on complete-proposal, 2/3-any, 2/3-one
  748. func (cs *State) handleMsg(ctx context.Context, mi msgInfo) {
  749. cs.mtx.Lock()
  750. defer cs.mtx.Unlock()
  751. var (
  752. added bool
  753. err error
  754. )
  755. msg, peerID := mi.Msg, mi.PeerID
  756. switch msg := msg.(type) {
  757. case *ProposalMessage:
  758. // will not cause transition.
  759. // once proposal is set, we can receive block parts
  760. err = cs.setProposal(msg.Proposal)
  761. case *BlockPartMessage:
  762. // if the proposal is complete, we'll enterPrevote or tryFinalizeCommit
  763. added, err = cs.addProposalBlockPart(ctx, msg, peerID)
  764. if added {
  765. select {
  766. case cs.statsMsgQueue <- mi:
  767. case <-ctx.Done():
  768. return
  769. }
  770. }
  771. if err != nil && msg.Round != cs.Round {
  772. cs.logger.Debug(
  773. "received block part from wrong round",
  774. "height", cs.Height,
  775. "cs_round", cs.Round,
  776. "block_round", msg.Round,
  777. )
  778. err = nil
  779. }
  780. case *VoteMessage:
  781. // attempt to add the vote and dupeout the validator if its a duplicate signature
  782. // if the vote gives us a 2/3-any or 2/3-one, we transition
  783. added, err = cs.tryAddVote(ctx, msg.Vote, peerID)
  784. if added {
  785. select {
  786. case cs.statsMsgQueue <- mi:
  787. case <-ctx.Done():
  788. return
  789. }
  790. }
  791. // if err == ErrAddingVote {
  792. // TODO: punish peer
  793. // We probably don't want to stop the peer here. The vote does not
  794. // necessarily comes from a malicious peer but can be just broadcasted by
  795. // a typical peer.
  796. // https://github.com/tendermint/tendermint/issues/1281
  797. // }
  798. // NOTE: the vote is broadcast to peers by the reactor listening
  799. // for vote events
  800. // TODO: If rs.Height == vote.Height && rs.Round < vote.Round,
  801. // the peer is sending us CatchupCommit precommits.
  802. // We could make note of this and help filter in broadcastHasVoteMessage().
  803. default:
  804. cs.logger.Error("unknown msg type", "type", fmt.Sprintf("%T", msg))
  805. return
  806. }
  807. if err != nil {
  808. cs.logger.Error(
  809. "failed to process message",
  810. "height", cs.Height,
  811. "round", cs.Round,
  812. "peer", peerID,
  813. "msg_type", fmt.Sprintf("%T", msg),
  814. "err", err,
  815. )
  816. }
  817. }
  818. func (cs *State) handleTimeout(
  819. ctx context.Context,
  820. ti timeoutInfo,
  821. rs cstypes.RoundState,
  822. ) {
  823. cs.logger.Debug("received tock", "timeout", ti.Duration, "height", ti.Height, "round", ti.Round, "step", ti.Step)
  824. // timeouts must be for current height, round, step
  825. if ti.Height != rs.Height || ti.Round < rs.Round || (ti.Round == rs.Round && ti.Step < rs.Step) {
  826. cs.logger.Debug("ignoring tock because we are ahead", "height", rs.Height, "round", rs.Round, "step", rs.Step)
  827. return
  828. }
  829. // the timeout will now cause a state transition
  830. cs.mtx.Lock()
  831. defer cs.mtx.Unlock()
  832. switch ti.Step {
  833. case cstypes.RoundStepNewHeight:
  834. // NewRound event fired from enterNewRound.
  835. // XXX: should we fire timeout here (for timeout commit)?
  836. cs.enterNewRound(ctx, ti.Height, 0)
  837. case cstypes.RoundStepNewRound:
  838. cs.enterPropose(ctx, ti.Height, 0)
  839. case cstypes.RoundStepPropose:
  840. if err := cs.eventBus.PublishEventTimeoutPropose(ctx, cs.RoundStateEvent()); err != nil {
  841. cs.logger.Error("failed publishing timeout propose", "err", err)
  842. }
  843. cs.enterPrevote(ctx, ti.Height, ti.Round)
  844. case cstypes.RoundStepPrevoteWait:
  845. if err := cs.eventBus.PublishEventTimeoutWait(ctx, cs.RoundStateEvent()); err != nil {
  846. cs.logger.Error("failed publishing timeout wait", "err", err)
  847. }
  848. cs.enterPrecommit(ctx, ti.Height, ti.Round)
  849. case cstypes.RoundStepPrecommitWait:
  850. if err := cs.eventBus.PublishEventTimeoutWait(ctx, cs.RoundStateEvent()); err != nil {
  851. cs.logger.Error("failed publishing timeout wait", "err", err)
  852. }
  853. cs.enterPrecommit(ctx, ti.Height, ti.Round)
  854. cs.enterNewRound(ctx, ti.Height, ti.Round+1)
  855. default:
  856. panic(fmt.Sprintf("invalid timeout step: %v", ti.Step))
  857. }
  858. }
  859. func (cs *State) handleTxsAvailable(ctx context.Context) {
  860. cs.mtx.Lock()
  861. defer cs.mtx.Unlock()
  862. // We only need to do this for round 0.
  863. if cs.Round != 0 {
  864. return
  865. }
  866. switch cs.Step {
  867. case cstypes.RoundStepNewHeight: // timeoutCommit phase
  868. if cs.needProofBlock(cs.Height) {
  869. // enterPropose will be called by enterNewRound
  870. return
  871. }
  872. // +1ms to ensure RoundStepNewRound timeout always happens after RoundStepNewHeight
  873. timeoutCommit := cs.StartTime.Sub(tmtime.Now()) + 1*time.Millisecond
  874. cs.scheduleTimeout(timeoutCommit, cs.Height, 0, cstypes.RoundStepNewRound)
  875. case cstypes.RoundStepNewRound: // after timeoutCommit
  876. cs.enterPropose(ctx, cs.Height, 0)
  877. }
  878. }
  879. //-----------------------------------------------------------------------------
  880. // State functions
  881. // Used internally by handleTimeout and handleMsg to make state transitions
  882. // Enter: `timeoutNewHeight` by startTime (commitTime+timeoutCommit),
  883. // or, if SkipTimeoutCommit==true, after receiving all precommits from (height,round-1)
  884. // Enter: `timeoutPrecommits` after any +2/3 precommits from (height,round-1)
  885. // Enter: +2/3 precommits for nil at (height,round-1)
  886. // Enter: +2/3 prevotes any or +2/3 precommits for block or any from (height, round)
  887. // NOTE: cs.StartTime was already set for height.
  888. func (cs *State) enterNewRound(ctx context.Context, height int64, round int32) {
  889. logger := cs.logger.With("height", height, "round", round)
  890. if cs.Height != height || round < cs.Round || (cs.Round == round && cs.Step != cstypes.RoundStepNewHeight) {
  891. logger.Debug(
  892. "entering new round with invalid args",
  893. "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step),
  894. )
  895. return
  896. }
  897. if now := tmtime.Now(); cs.StartTime.After(now) {
  898. logger.Debug("need to set a buffer and log message here for sanity", "start_time", cs.StartTime, "now", now)
  899. }
  900. logger.Debug("entering new round", "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step))
  901. // increment validators if necessary
  902. validators := cs.Validators
  903. if cs.Round < round {
  904. validators = validators.Copy()
  905. validators.IncrementProposerPriority(tmmath.SafeSubInt32(round, cs.Round))
  906. }
  907. // Setup new round
  908. // we don't fire newStep for this step,
  909. // but we fire an event, so update the round step first
  910. cs.updateRoundStep(round, cstypes.RoundStepNewRound)
  911. cs.Validators = validators
  912. if round == 0 {
  913. // We've already reset these upon new height,
  914. // and meanwhile we might have received a proposal
  915. // for round 0.
  916. } else {
  917. logger.Debug("resetting proposal info")
  918. cs.Proposal = nil
  919. cs.ProposalBlock = nil
  920. cs.ProposalBlockParts = nil
  921. }
  922. cs.Votes.SetRound(tmmath.SafeAddInt32(round, 1)) // also track next round (round+1) to allow round-skipping
  923. cs.TriggeredTimeoutPrecommit = false
  924. if err := cs.eventBus.PublishEventNewRound(ctx, cs.NewRoundEvent()); err != nil {
  925. cs.logger.Error("failed publishing new round", "err", err)
  926. }
  927. cs.metrics.Rounds.Set(float64(round))
  928. // Wait for txs to be available in the mempool
  929. // before we enterPropose in round 0. If the last block changed the app hash,
  930. // we may need an empty "proof" block, and enterPropose immediately.
  931. waitForTxs := cs.config.WaitForTxs() && round == 0 && !cs.needProofBlock(height)
  932. if waitForTxs {
  933. if cs.config.CreateEmptyBlocksInterval > 0 {
  934. cs.scheduleTimeout(cs.config.CreateEmptyBlocksInterval, height, round,
  935. cstypes.RoundStepNewRound)
  936. }
  937. } else {
  938. cs.enterPropose(ctx, height, round)
  939. }
  940. }
  941. // needProofBlock returns true on the first height (so the genesis app hash is signed right away)
  942. // and where the last block (height-1) caused the app hash to change
  943. func (cs *State) needProofBlock(height int64) bool {
  944. if height == cs.state.InitialHeight {
  945. return true
  946. }
  947. lastBlockMeta := cs.blockStore.LoadBlockMeta(height - 1)
  948. if lastBlockMeta == nil {
  949. panic(fmt.Sprintf("needProofBlock: last block meta for height %d not found", height-1))
  950. }
  951. return !bytes.Equal(cs.state.AppHash, lastBlockMeta.Header.AppHash)
  952. }
  953. // Enter (CreateEmptyBlocks): from enterNewRound(height,round)
  954. // Enter (CreateEmptyBlocks, CreateEmptyBlocksInterval > 0 ):
  955. // after enterNewRound(height,round), after timeout of CreateEmptyBlocksInterval
  956. // Enter (!CreateEmptyBlocks) : after enterNewRound(height,round), once txs are in the mempool
  957. func (cs *State) enterPropose(ctx context.Context, height int64, round int32) {
  958. logger := cs.logger.With("height", height, "round", round)
  959. if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPropose <= cs.Step) {
  960. logger.Debug(
  961. "entering propose step with invalid args",
  962. "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step),
  963. )
  964. return
  965. }
  966. logger.Debug("entering propose step", "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step))
  967. defer func() {
  968. // Done enterPropose:
  969. cs.updateRoundStep(round, cstypes.RoundStepPropose)
  970. cs.newStep(ctx)
  971. // If we have the whole proposal + POL, then goto Prevote now.
  972. // else, we'll enterPrevote when the rest of the proposal is received (in AddProposalBlockPart),
  973. // or else after timeoutPropose
  974. if cs.isProposalComplete() {
  975. cs.enterPrevote(ctx, height, cs.Round)
  976. }
  977. }()
  978. // If we don't get the proposal and all block parts quick enough, enterPrevote
  979. cs.scheduleTimeout(cs.config.Propose(round), height, round, cstypes.RoundStepPropose)
  980. // Nothing more to do if we're not a validator
  981. if cs.privValidator == nil {
  982. logger.Debug("node is not a validator")
  983. return
  984. }
  985. logger.Debug("node is a validator")
  986. if cs.privValidatorPubKey == nil {
  987. // If this node is a validator & proposer in the current round, it will
  988. // miss the opportunity to create a block.
  989. logger.Error("propose step; empty priv validator public key", "err", errPubKeyIsNotSet)
  990. return
  991. }
  992. address := cs.privValidatorPubKey.Address()
  993. // if not a validator, we're done
  994. if !cs.Validators.HasAddress(address) {
  995. logger.Debug("node is not a validator", "addr", address, "vals", cs.Validators)
  996. return
  997. }
  998. if cs.isProposer(address) {
  999. logger.Debug(
  1000. "propose step; our turn to propose",
  1001. "proposer", address,
  1002. )
  1003. cs.decideProposal(ctx, height, round)
  1004. } else {
  1005. logger.Debug(
  1006. "propose step; not our turn to propose",
  1007. "proposer", cs.Validators.GetProposer().Address,
  1008. )
  1009. }
  1010. }
  1011. func (cs *State) isProposer(address []byte) bool {
  1012. return bytes.Equal(cs.Validators.GetProposer().Address, address)
  1013. }
  1014. func (cs *State) defaultDecideProposal(ctx context.Context, height int64, round int32) {
  1015. var block *types.Block
  1016. var blockParts *types.PartSet
  1017. // Decide on block
  1018. if cs.ValidBlock != nil {
  1019. // If there is valid block, choose that.
  1020. block, blockParts = cs.ValidBlock, cs.ValidBlockParts
  1021. } else {
  1022. // Create a new proposal block from state/txs from the mempool.
  1023. var err error
  1024. block, blockParts, err = cs.createProposalBlock()
  1025. if block == nil || err != nil {
  1026. return
  1027. }
  1028. }
  1029. // Flush the WAL. Otherwise, we may not recompute the same proposal to sign,
  1030. // and the privValidator will refuse to sign anything.
  1031. if err := cs.wal.FlushAndSync(); err != nil {
  1032. cs.logger.Error("failed flushing WAL to disk")
  1033. }
  1034. // Make proposal
  1035. propBlockID := types.BlockID{Hash: block.Hash(), PartSetHeader: blockParts.Header()}
  1036. proposal := types.NewProposal(height, round, cs.ValidRound, propBlockID)
  1037. p := proposal.ToProto()
  1038. // wait the max amount we would wait for a proposal
  1039. ctxto, cancel := context.WithTimeout(ctx, cs.config.TimeoutPropose)
  1040. defer cancel()
  1041. if err := cs.privValidator.SignProposal(ctxto, cs.state.ChainID, p); err == nil {
  1042. proposal.Signature = p.Signature
  1043. // send proposal and block parts on internal msg queue
  1044. cs.sendInternalMessage(ctx, msgInfo{&ProposalMessage{proposal}, ""})
  1045. for i := 0; i < int(blockParts.Total()); i++ {
  1046. part := blockParts.GetPart(i)
  1047. cs.sendInternalMessage(ctx, msgInfo{&BlockPartMessage{cs.Height, cs.Round, part}, ""})
  1048. }
  1049. cs.logger.Debug("signed proposal", "height", height, "round", round, "proposal", proposal)
  1050. } else if !cs.replayMode {
  1051. cs.logger.Error("propose step; failed signing proposal", "height", height, "round", round, "err", err)
  1052. }
  1053. }
  1054. // Returns true if the proposal block is complete &&
  1055. // (if POLRound was proposed, we have +2/3 prevotes from there).
  1056. func (cs *State) isProposalComplete() bool {
  1057. if cs.Proposal == nil || cs.ProposalBlock == nil {
  1058. return false
  1059. }
  1060. // we have the proposal. if there's a POLRound,
  1061. // make sure we have the prevotes from it too
  1062. if cs.Proposal.POLRound < 0 {
  1063. return true
  1064. }
  1065. // if this is false the proposer is lying or we haven't received the POL yet
  1066. return cs.Votes.Prevotes(cs.Proposal.POLRound).HasTwoThirdsMajority()
  1067. }
  1068. // Create the next block to propose and return it. Returns nil block upon error.
  1069. //
  1070. // We really only need to return the parts, but the block is returned for
  1071. // convenience so we can log the proposal block.
  1072. //
  1073. // NOTE: keep it side-effect free for clarity.
  1074. // CONTRACT: cs.privValidator is not nil.
  1075. func (cs *State) createProposalBlock() (block *types.Block, blockParts *types.PartSet, err error) {
  1076. if cs.privValidator == nil {
  1077. return nil, nil, errors.New("entered createProposalBlock with privValidator being nil")
  1078. }
  1079. var commit *types.Commit
  1080. switch {
  1081. case cs.Height == cs.state.InitialHeight:
  1082. // We're creating a proposal for the first block.
  1083. // The commit is empty, but not nil.
  1084. commit = types.NewCommit(0, 0, types.BlockID{}, nil)
  1085. case cs.LastCommit.HasTwoThirdsMajority():
  1086. // Make the commit from LastCommit
  1087. commit = cs.LastCommit.MakeCommit()
  1088. default: // This shouldn't happen.
  1089. cs.logger.Error("propose step; cannot propose anything without commit for the previous block")
  1090. return
  1091. }
  1092. if cs.privValidatorPubKey == nil {
  1093. // If this node is a validator & proposer in the current round, it will
  1094. // miss the opportunity to create a block.
  1095. cs.logger.Error("propose step; empty priv validator public key", "err", errPubKeyIsNotSet)
  1096. return
  1097. }
  1098. proposerAddr := cs.privValidatorPubKey.Address()
  1099. return cs.blockExec.CreateProposalBlock(cs.Height, cs.state, commit, proposerAddr)
  1100. }
  1101. // Enter: `timeoutPropose` after entering Propose.
  1102. // Enter: proposal block and POL is ready.
  1103. // Prevote for LockedBlock if we're locked, or ProposalBlock if valid.
  1104. // Otherwise vote nil.
  1105. func (cs *State) enterPrevote(ctx context.Context, height int64, round int32) {
  1106. logger := cs.logger.With("height", height, "round", round)
  1107. if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPrevote <= cs.Step) {
  1108. logger.Debug(
  1109. "entering prevote step with invalid args",
  1110. "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step),
  1111. )
  1112. return
  1113. }
  1114. defer func() {
  1115. // Done enterPrevote:
  1116. cs.updateRoundStep(round, cstypes.RoundStepPrevote)
  1117. cs.newStep(ctx)
  1118. }()
  1119. logger.Debug("entering prevote step", "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step))
  1120. // Sign and broadcast vote as necessary
  1121. cs.doPrevote(ctx, height, round)
  1122. // Once `addVote` hits any +2/3 prevotes, we will go to PrevoteWait
  1123. // (so we have more time to try and collect +2/3 prevotes for a single block)
  1124. }
  1125. func (cs *State) defaultDoPrevote(ctx context.Context, height int64, round int32) {
  1126. logger := cs.logger.With("height", height, "round", round)
  1127. // If a block is locked, prevote that.
  1128. if cs.LockedBlock != nil {
  1129. logger.Debug("prevote step; already locked on a block; prevoting locked block")
  1130. cs.signAddVote(ctx, tmproto.PrevoteType, cs.LockedBlock.Hash(), cs.LockedBlockParts.Header())
  1131. return
  1132. }
  1133. // If ProposalBlock is nil, prevote nil.
  1134. if cs.ProposalBlock == nil {
  1135. logger.Debug("prevote step: ProposalBlock is nil")
  1136. cs.signAddVote(ctx, tmproto.PrevoteType, nil, types.PartSetHeader{})
  1137. return
  1138. }
  1139. // Validate proposal block
  1140. err := cs.blockExec.ValidateBlock(cs.state, cs.ProposalBlock)
  1141. if err != nil {
  1142. // ProposalBlock is invalid, prevote nil.
  1143. logger.Error("prevote step: ProposalBlock is invalid", "err", err)
  1144. cs.signAddVote(ctx, tmproto.PrevoteType, nil, types.PartSetHeader{})
  1145. return
  1146. }
  1147. // Prevote cs.ProposalBlock
  1148. // NOTE: the proposal signature is validated when it is received,
  1149. // and the proposal block parts are validated as they are received (against the merkle hash in the proposal)
  1150. logger.Debug("prevote step: ProposalBlock is valid")
  1151. cs.signAddVote(ctx, tmproto.PrevoteType, cs.ProposalBlock.Hash(), cs.ProposalBlockParts.Header())
  1152. }
  1153. // Enter: any +2/3 prevotes at next round.
  1154. func (cs *State) enterPrevoteWait(ctx context.Context, height int64, round int32) {
  1155. logger := cs.logger.With("height", height, "round", round)
  1156. if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPrevoteWait <= cs.Step) {
  1157. logger.Debug(
  1158. "entering prevote wait step with invalid args",
  1159. "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step),
  1160. )
  1161. return
  1162. }
  1163. if !cs.Votes.Prevotes(round).HasTwoThirdsAny() {
  1164. panic(fmt.Sprintf(
  1165. "entering prevote wait step (%v/%v), but prevotes does not have any +2/3 votes",
  1166. height, round,
  1167. ))
  1168. }
  1169. logger.Debug("entering prevote wait step", "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step))
  1170. defer func() {
  1171. // Done enterPrevoteWait:
  1172. cs.updateRoundStep(round, cstypes.RoundStepPrevoteWait)
  1173. cs.newStep(ctx)
  1174. }()
  1175. // Wait for some more prevotes; enterPrecommit
  1176. cs.scheduleTimeout(cs.config.Prevote(round), height, round, cstypes.RoundStepPrevoteWait)
  1177. }
  1178. // Enter: `timeoutPrevote` after any +2/3 prevotes.
  1179. // Enter: `timeoutPrecommit` after any +2/3 precommits.
  1180. // Enter: +2/3 precomits for block or nil.
  1181. // Lock & precommit the ProposalBlock if we have enough prevotes for it (a POL in this round)
  1182. // else, unlock an existing lock and precommit nil if +2/3 of prevotes were nil,
  1183. // else, precommit nil otherwise.
  1184. func (cs *State) enterPrecommit(ctx context.Context, height int64, round int32) {
  1185. logger := cs.logger.With("height", height, "round", round)
  1186. if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPrecommit <= cs.Step) {
  1187. logger.Debug(
  1188. "entering precommit step with invalid args",
  1189. "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step),
  1190. )
  1191. return
  1192. }
  1193. logger.Debug("entering precommit step", "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step))
  1194. defer func() {
  1195. // Done enterPrecommit:
  1196. cs.updateRoundStep(round, cstypes.RoundStepPrecommit)
  1197. cs.newStep(ctx)
  1198. }()
  1199. // check for a polka
  1200. blockID, ok := cs.Votes.Prevotes(round).TwoThirdsMajority()
  1201. // If we don't have a polka, we must precommit nil.
  1202. if !ok {
  1203. if cs.LockedBlock != nil {
  1204. logger.Debug("precommit step; no +2/3 prevotes during enterPrecommit while we are locked; precommitting nil")
  1205. } else {
  1206. logger.Debug("precommit step; no +2/3 prevotes during enterPrecommit; precommitting nil")
  1207. }
  1208. cs.signAddVote(ctx, tmproto.PrecommitType, nil, types.PartSetHeader{})
  1209. return
  1210. }
  1211. // At this point +2/3 prevoted for a particular block or nil.
  1212. if err := cs.eventBus.PublishEventPolka(ctx, cs.RoundStateEvent()); err != nil {
  1213. logger.Error("failed publishing polka", "err", err)
  1214. }
  1215. // the latest POLRound should be this round.
  1216. polRound, _ := cs.Votes.POLInfo()
  1217. if polRound < round {
  1218. panic(fmt.Sprintf("this POLRound should be %v but got %v", round, polRound))
  1219. }
  1220. // +2/3 prevoted nil. Unlock and precommit nil.
  1221. if len(blockID.Hash) == 0 {
  1222. if cs.LockedBlock == nil {
  1223. logger.Debug("precommit step; +2/3 prevoted for nil")
  1224. } else {
  1225. logger.Debug("precommit step; +2/3 prevoted for nil; unlocking")
  1226. cs.LockedRound = -1
  1227. cs.LockedBlock = nil
  1228. cs.LockedBlockParts = nil
  1229. if err := cs.eventBus.PublishEventUnlock(ctx, cs.RoundStateEvent()); err != nil {
  1230. logger.Error("failed publishing event unlock", "err", err)
  1231. }
  1232. }
  1233. cs.signAddVote(ctx, tmproto.PrecommitType, nil, types.PartSetHeader{})
  1234. return
  1235. }
  1236. // At this point, +2/3 prevoted for a particular block.
  1237. // If we're already locked on that block, precommit it, and update the LockedRound
  1238. if cs.LockedBlock.HashesTo(blockID.Hash) {
  1239. logger.Debug("precommit step; +2/3 prevoted locked block; relocking")
  1240. cs.LockedRound = round
  1241. if err := cs.eventBus.PublishEventRelock(ctx, cs.RoundStateEvent()); err != nil {
  1242. logger.Error("failed publishing event relock", "err", err)
  1243. }
  1244. cs.signAddVote(ctx, tmproto.PrecommitType, blockID.Hash, blockID.PartSetHeader)
  1245. return
  1246. }
  1247. // If +2/3 prevoted for proposal block, stage and precommit it
  1248. if cs.ProposalBlock.HashesTo(blockID.Hash) {
  1249. logger.Debug("precommit step; +2/3 prevoted proposal block; locking", "hash", blockID.Hash)
  1250. // Validate the block.
  1251. if err := cs.blockExec.ValidateBlock(cs.state, cs.ProposalBlock); err != nil {
  1252. panic(fmt.Errorf("precommit step; +2/3 prevoted for an invalid block: %w", err))
  1253. }
  1254. cs.LockedRound = round
  1255. cs.LockedBlock = cs.ProposalBlock
  1256. cs.LockedBlockParts = cs.ProposalBlockParts
  1257. if err := cs.eventBus.PublishEventLock(ctx, cs.RoundStateEvent()); err != nil {
  1258. logger.Error("failed publishing event lock", "err", err)
  1259. }
  1260. cs.signAddVote(ctx, tmproto.PrecommitType, blockID.Hash, blockID.PartSetHeader)
  1261. return
  1262. }
  1263. // There was a polka in this round for a block we don't have.
  1264. // Fetch that block, unlock, and precommit nil.
  1265. // The +2/3 prevotes for this round is the POL for our unlock.
  1266. logger.Debug("precommit step; +2/3 prevotes for a block we do not have; voting nil", "block_id", blockID)
  1267. cs.LockedRound = -1
  1268. cs.LockedBlock = nil
  1269. cs.LockedBlockParts = nil
  1270. if !cs.ProposalBlockParts.HasHeader(blockID.PartSetHeader) {
  1271. cs.ProposalBlock = nil
  1272. cs.ProposalBlockParts = types.NewPartSetFromHeader(blockID.PartSetHeader)
  1273. }
  1274. if err := cs.eventBus.PublishEventUnlock(ctx, cs.RoundStateEvent()); err != nil {
  1275. logger.Error("failed publishing event unlock", "err", err)
  1276. }
  1277. cs.signAddVote(ctx, tmproto.PrecommitType, nil, types.PartSetHeader{})
  1278. }
  1279. // Enter: any +2/3 precommits for next round.
  1280. func (cs *State) enterPrecommitWait(ctx context.Context, height int64, round int32) {
  1281. logger := cs.logger.With("height", height, "round", round)
  1282. if cs.Height != height || round < cs.Round || (cs.Round == round && cs.TriggeredTimeoutPrecommit) {
  1283. logger.Debug(
  1284. "entering precommit wait step with invalid args",
  1285. "triggered_timeout", cs.TriggeredTimeoutPrecommit,
  1286. "current", fmt.Sprintf("%v/%v", cs.Height, cs.Round),
  1287. )
  1288. return
  1289. }
  1290. if !cs.Votes.Precommits(round).HasTwoThirdsAny() {
  1291. panic(fmt.Sprintf(
  1292. "entering precommit wait step (%v/%v), but precommits does not have any +2/3 votes",
  1293. height, round,
  1294. ))
  1295. }
  1296. logger.Debug("entering precommit wait step", "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step))
  1297. defer func() {
  1298. // Done enterPrecommitWait:
  1299. cs.TriggeredTimeoutPrecommit = true
  1300. cs.newStep(ctx)
  1301. }()
  1302. // wait for some more precommits; enterNewRound
  1303. cs.scheduleTimeout(cs.config.Precommit(round), height, round, cstypes.RoundStepPrecommitWait)
  1304. }
  1305. // Enter: +2/3 precommits for block
  1306. func (cs *State) enterCommit(ctx context.Context, height int64, commitRound int32) {
  1307. logger := cs.logger.With("height", height, "commit_round", commitRound)
  1308. if cs.Height != height || cstypes.RoundStepCommit <= cs.Step {
  1309. logger.Debug(
  1310. "entering commit step with invalid args",
  1311. "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step),
  1312. )
  1313. return
  1314. }
  1315. logger.Debug("entering commit step", "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step))
  1316. defer func() {
  1317. // Done enterCommit:
  1318. // keep cs.Round the same, commitRound points to the right Precommits set.
  1319. cs.updateRoundStep(cs.Round, cstypes.RoundStepCommit)
  1320. cs.CommitRound = commitRound
  1321. cs.CommitTime = tmtime.Now()
  1322. cs.newStep(ctx)
  1323. // Maybe finalize immediately.
  1324. cs.tryFinalizeCommit(ctx, height)
  1325. }()
  1326. blockID, ok := cs.Votes.Precommits(commitRound).TwoThirdsMajority()
  1327. if !ok {
  1328. panic("RunActionCommit() expects +2/3 precommits")
  1329. }
  1330. // The Locked* fields no longer matter.
  1331. // Move them over to ProposalBlock if they match the commit hash,
  1332. // otherwise they'll be cleared in updateToState.
  1333. if cs.LockedBlock.HashesTo(blockID.Hash) {
  1334. logger.Debug("commit is for a locked block; set ProposalBlock=LockedBlock", "block_hash", blockID.Hash)
  1335. cs.ProposalBlock = cs.LockedBlock
  1336. cs.ProposalBlockParts = cs.LockedBlockParts
  1337. }
  1338. // If we don't have the block being committed, set up to get it.
  1339. if !cs.ProposalBlock.HashesTo(blockID.Hash) {
  1340. if !cs.ProposalBlockParts.HasHeader(blockID.PartSetHeader) {
  1341. logger.Info(
  1342. "commit is for a block we do not know about; set ProposalBlock=nil",
  1343. "proposal", cs.ProposalBlock.Hash(),
  1344. "commit", blockID.Hash,
  1345. )
  1346. // We're getting the wrong block.
  1347. // Set up ProposalBlockParts and keep waiting.
  1348. cs.ProposalBlock = nil
  1349. cs.ProposalBlockParts = types.NewPartSetFromHeader(blockID.PartSetHeader)
  1350. if err := cs.eventBus.PublishEventValidBlock(ctx, cs.RoundStateEvent()); err != nil {
  1351. logger.Error("failed publishing valid block", "err", err)
  1352. }
  1353. cs.evsw.FireEvent(ctx, types.EventValidBlockValue, &cs.RoundState)
  1354. }
  1355. }
  1356. }
  1357. // If we have the block AND +2/3 commits for it, finalize.
  1358. func (cs *State) tryFinalizeCommit(ctx context.Context, height int64) {
  1359. logger := cs.logger.With("height", height)
  1360. if cs.Height != height {
  1361. panic(fmt.Sprintf("tryFinalizeCommit() cs.Height: %v vs height: %v", cs.Height, height))
  1362. }
  1363. blockID, ok := cs.Votes.Precommits(cs.CommitRound).TwoThirdsMajority()
  1364. if !ok || len(blockID.Hash) == 0 {
  1365. logger.Error("failed attempt to finalize commit; there was no +2/3 majority or +2/3 was for nil")
  1366. return
  1367. }
  1368. if !cs.ProposalBlock.HashesTo(blockID.Hash) {
  1369. // TODO: this happens every time if we're not a validator (ugly logs)
  1370. // TODO: ^^ wait, why does it matter that we're a validator?
  1371. logger.Debug(
  1372. "failed attempt to finalize commit; we do not have the commit block",
  1373. "proposal_block", cs.ProposalBlock.Hash(),
  1374. "commit_block", blockID.Hash,
  1375. )
  1376. return
  1377. }
  1378. cs.finalizeCommit(ctx, height)
  1379. }
  1380. // Increment height and goto cstypes.RoundStepNewHeight
  1381. func (cs *State) finalizeCommit(ctx context.Context, height int64) {
  1382. logger := cs.logger.With("height", height)
  1383. if cs.Height != height || cs.Step != cstypes.RoundStepCommit {
  1384. logger.Debug(
  1385. "entering finalize commit step",
  1386. "current", fmt.Sprintf("%v/%v/%v", cs.Height, cs.Round, cs.Step),
  1387. )
  1388. return
  1389. }
  1390. blockID, ok := cs.Votes.Precommits(cs.CommitRound).TwoThirdsMajority()
  1391. block, blockParts := cs.ProposalBlock, cs.ProposalBlockParts
  1392. if !ok {
  1393. panic("cannot finalize commit; commit does not have 2/3 majority")
  1394. }
  1395. if !blockParts.HasHeader(blockID.PartSetHeader) {
  1396. panic("expected ProposalBlockParts header to be commit header")
  1397. }
  1398. if !block.HashesTo(blockID.Hash) {
  1399. panic("cannot finalize commit; proposal block does not hash to commit hash")
  1400. }
  1401. if err := cs.blockExec.ValidateBlock(cs.state, block); err != nil {
  1402. panic(fmt.Errorf("+2/3 committed an invalid block: %w", err))
  1403. }
  1404. logger.Info(
  1405. "finalizing commit of block",
  1406. "hash", block.Hash(),
  1407. "root", block.AppHash,
  1408. "num_txs", len(block.Txs),
  1409. )
  1410. logger.Debug(fmt.Sprintf("%v", block))
  1411. // Save to blockStore.
  1412. if cs.blockStore.Height() < block.Height {
  1413. // NOTE: the seenCommit is local justification to commit this block,
  1414. // but may differ from the LastCommit included in the next block
  1415. precommits := cs.Votes.Precommits(cs.CommitRound)
  1416. seenCommit := precommits.MakeCommit()
  1417. cs.blockStore.SaveBlock(block, blockParts, seenCommit)
  1418. } else {
  1419. // Happens during replay if we already saved the block but didn't commit
  1420. logger.Debug("calling finalizeCommit on already stored block", "height", block.Height)
  1421. }
  1422. // Write EndHeightMessage{} for this height, implying that the blockstore
  1423. // has saved the block.
  1424. //
  1425. // If we crash before writing this EndHeightMessage{}, we will recover by
  1426. // running ApplyBlock during the ABCI handshake when we restart. If we
  1427. // didn't save the block to the blockstore before writing
  1428. // EndHeightMessage{}, we'd have to change WAL replay -- currently it
  1429. // complains about replaying for heights where an #ENDHEIGHT entry already
  1430. // exists.
  1431. //
  1432. // Either way, the State should not be resumed until we
  1433. // successfully call ApplyBlock (ie. later here, or in Handshake after
  1434. // restart).
  1435. endMsg := EndHeightMessage{height}
  1436. if err := cs.wal.WriteSync(endMsg); err != nil { // NOTE: fsync
  1437. panic(fmt.Sprintf(
  1438. "failed to write %v msg to consensus WAL due to %v; check your file system and restart the node",
  1439. endMsg, err,
  1440. ))
  1441. }
  1442. // Create a copy of the state for staging and an event cache for txs.
  1443. stateCopy := cs.state.Copy()
  1444. // Execute and commit the block, update and save the state, and update the mempool.
  1445. // NOTE The block.AppHash wont reflect these txs until the next block.
  1446. stateCopy, err := cs.blockExec.ApplyBlock(ctx,
  1447. stateCopy,
  1448. types.BlockID{
  1449. Hash: block.Hash(),
  1450. PartSetHeader: blockParts.Header(),
  1451. },
  1452. block,
  1453. )
  1454. if err != nil {
  1455. logger.Error("failed to apply block", "err", err)
  1456. return
  1457. }
  1458. // must be called before we update state
  1459. cs.RecordMetrics(height, block)
  1460. // NewHeightStep!
  1461. cs.updateToState(ctx, stateCopy)
  1462. // Private validator might have changed it's key pair => refetch pubkey.
  1463. if err := cs.updatePrivValidatorPubKey(ctx); err != nil {
  1464. logger.Error("failed to get private validator pubkey", "err", err)
  1465. }
  1466. // cs.StartTime is already set.
  1467. // Schedule Round0 to start soon.
  1468. cs.scheduleRound0(&cs.RoundState)
  1469. // By here,
  1470. // * cs.Height has been increment to height+1
  1471. // * cs.Step is now cstypes.RoundStepNewHeight
  1472. // * cs.StartTime is set to when we will start round0.
  1473. }
  1474. func (cs *State) RecordMetrics(height int64, block *types.Block) {
  1475. cs.metrics.Validators.Set(float64(cs.Validators.Size()))
  1476. cs.metrics.ValidatorsPower.Set(float64(cs.Validators.TotalVotingPower()))
  1477. var (
  1478. missingValidators int
  1479. missingValidatorsPower int64
  1480. )
  1481. // height=0 -> MissingValidators and MissingValidatorsPower are both 0.
  1482. // Remember that the first LastCommit is intentionally empty, so it's not
  1483. // fair to increment missing validators number.
  1484. if height > cs.state.InitialHeight {
  1485. // Sanity check that commit size matches validator set size - only applies
  1486. // after first block.
  1487. var (
  1488. commitSize = block.LastCommit.Size()
  1489. valSetLen = len(cs.LastValidators.Validators)
  1490. address types.Address
  1491. )
  1492. if commitSize != valSetLen {
  1493. cs.logger.Error(fmt.Sprintf("commit size (%d) doesn't match valset length (%d) at height %d\n\n%v\n\n%v",
  1494. commitSize, valSetLen, block.Height, block.LastCommit.Signatures, cs.LastValidators.Validators))
  1495. return
  1496. }
  1497. if cs.privValidator != nil {
  1498. if cs.privValidatorPubKey == nil {
  1499. // Metrics won't be updated, but it's not critical.
  1500. cs.logger.Error("recordMetrics", "err", errPubKeyIsNotSet)
  1501. } else {
  1502. address = cs.privValidatorPubKey.Address()
  1503. }
  1504. }
  1505. for i, val := range cs.LastValidators.Validators {
  1506. commitSig := block.LastCommit.Signatures[i]
  1507. if commitSig.Absent() {
  1508. missingValidators++
  1509. missingValidatorsPower += val.VotingPower
  1510. }
  1511. if bytes.Equal(val.Address, address) {
  1512. label := []string{
  1513. "validator_address", val.Address.String(),
  1514. }
  1515. cs.metrics.ValidatorPower.With(label...).Set(float64(val.VotingPower))
  1516. if commitSig.ForBlock() {
  1517. cs.metrics.ValidatorLastSignedHeight.With(label...).Set(float64(height))
  1518. } else {
  1519. cs.metrics.ValidatorMissedBlocks.With(label...).Add(float64(1))
  1520. }
  1521. }
  1522. }
  1523. }
  1524. cs.metrics.MissingValidators.Set(float64(missingValidators))
  1525. cs.metrics.MissingValidatorsPower.Set(float64(missingValidatorsPower))
  1526. // NOTE: byzantine validators power and count is only for consensus evidence i.e. duplicate vote
  1527. var (
  1528. byzantineValidatorsPower int64
  1529. byzantineValidatorsCount int64
  1530. )
  1531. for _, ev := range block.Evidence.Evidence {
  1532. if dve, ok := ev.(*types.DuplicateVoteEvidence); ok {
  1533. if _, val := cs.Validators.GetByAddress(dve.VoteA.ValidatorAddress); val != nil {
  1534. byzantineValidatorsCount++
  1535. byzantineValidatorsPower += val.VotingPower
  1536. }
  1537. }
  1538. }
  1539. cs.metrics.ByzantineValidators.Set(float64(byzantineValidatorsCount))
  1540. cs.metrics.ByzantineValidatorsPower.Set(float64(byzantineValidatorsPower))
  1541. if height > 1 {
  1542. lastBlockMeta := cs.blockStore.LoadBlockMeta(height - 1)
  1543. if lastBlockMeta != nil {
  1544. cs.metrics.BlockIntervalSeconds.Observe(
  1545. block.Time.Sub(lastBlockMeta.Header.Time).Seconds(),
  1546. )
  1547. }
  1548. }
  1549. cs.metrics.NumTxs.Set(float64(len(block.Data.Txs)))
  1550. cs.metrics.TotalTxs.Add(float64(len(block.Data.Txs)))
  1551. cs.metrics.BlockSizeBytes.Observe(float64(block.Size()))
  1552. cs.metrics.CommittedHeight.Set(float64(block.Height))
  1553. }
  1554. //-----------------------------------------------------------------------------
  1555. func (cs *State) defaultSetProposal(proposal *types.Proposal) error {
  1556. // Already have one
  1557. // TODO: possibly catch double proposals
  1558. if cs.Proposal != nil {
  1559. return nil
  1560. }
  1561. // Does not apply
  1562. if proposal.Height != cs.Height || proposal.Round != cs.Round {
  1563. return nil
  1564. }
  1565. // Verify POLRound, which must be -1 or in range [0, proposal.Round).
  1566. if proposal.POLRound < -1 ||
  1567. (proposal.POLRound >= 0 && proposal.POLRound >= proposal.Round) {
  1568. return ErrInvalidProposalPOLRound
  1569. }
  1570. p := proposal.ToProto()
  1571. // Verify signature
  1572. if !cs.Validators.GetProposer().PubKey.VerifySignature(
  1573. types.ProposalSignBytes(cs.state.ChainID, p), proposal.Signature,
  1574. ) {
  1575. return ErrInvalidProposalSignature
  1576. }
  1577. proposal.Signature = p.Signature
  1578. cs.Proposal = proposal
  1579. // We don't update cs.ProposalBlockParts if it is already set.
  1580. // This happens if we're already in cstypes.RoundStepCommit or if there is a valid block in the current round.
  1581. // TODO: We can check if Proposal is for a different block as this is a sign of misbehavior!
  1582. if cs.ProposalBlockParts == nil {
  1583. cs.ProposalBlockParts = types.NewPartSetFromHeader(proposal.BlockID.PartSetHeader)
  1584. }
  1585. cs.logger.Info("received proposal", "proposal", proposal)
  1586. return nil
  1587. }
  1588. // NOTE: block is not necessarily valid.
  1589. // Asynchronously triggers either enterPrevote (before we timeout of propose) or tryFinalizeCommit,
  1590. // once we have the full block.
  1591. func (cs *State) addProposalBlockPart(
  1592. ctx context.Context,
  1593. msg *BlockPartMessage,
  1594. peerID types.NodeID,
  1595. ) (added bool, err error) {
  1596. height, round, part := msg.Height, msg.Round, msg.Part
  1597. // Blocks might be reused, so round mismatch is OK
  1598. if cs.Height != height {
  1599. cs.logger.Debug("received block part from wrong height", "height", height, "round", round)
  1600. return false, nil
  1601. }
  1602. // We're not expecting a block part.
  1603. if cs.ProposalBlockParts == nil {
  1604. // NOTE: this can happen when we've gone to a higher round and
  1605. // then receive parts from the previous round - not necessarily a bad peer.
  1606. cs.logger.Debug(
  1607. "received a block part when we are not expecting any",
  1608. "height", height,
  1609. "round", round,
  1610. "index", part.Index,
  1611. "peer", peerID,
  1612. )
  1613. return false, nil
  1614. }
  1615. added, err = cs.ProposalBlockParts.AddPart(part)
  1616. if err != nil {
  1617. return added, err
  1618. }
  1619. if cs.ProposalBlockParts.ByteSize() > cs.state.ConsensusParams.Block.MaxBytes {
  1620. return added, fmt.Errorf("total size of proposal block parts exceeds maximum block bytes (%d > %d)",
  1621. cs.ProposalBlockParts.ByteSize(), cs.state.ConsensusParams.Block.MaxBytes,
  1622. )
  1623. }
  1624. if added && cs.ProposalBlockParts.IsComplete() {
  1625. bz, err := io.ReadAll(cs.ProposalBlockParts.GetReader())
  1626. if err != nil {
  1627. return added, err
  1628. }
  1629. var pbb = new(tmproto.Block)
  1630. err = proto.Unmarshal(bz, pbb)
  1631. if err != nil {
  1632. return added, err
  1633. }
  1634. block, err := types.BlockFromProto(pbb)
  1635. if err != nil {
  1636. return added, err
  1637. }
  1638. cs.ProposalBlock = block
  1639. // NOTE: it's possible to receive complete proposal blocks for future rounds without having the proposal
  1640. cs.logger.Info("received complete proposal block", "height", cs.ProposalBlock.Height, "hash", cs.ProposalBlock.Hash())
  1641. if err := cs.eventBus.PublishEventCompleteProposal(ctx, cs.CompleteProposalEvent()); err != nil {
  1642. cs.logger.Error("failed publishing event complete proposal", "err", err)
  1643. }
  1644. // Update Valid* if we can.
  1645. prevotes := cs.Votes.Prevotes(cs.Round)
  1646. blockID, hasTwoThirds := prevotes.TwoThirdsMajority()
  1647. if hasTwoThirds && !blockID.IsZero() && (cs.ValidRound < cs.Round) {
  1648. if cs.ProposalBlock.HashesTo(blockID.Hash) {
  1649. cs.logger.Debug(
  1650. "updating valid block to new proposal block",
  1651. "valid_round", cs.Round,
  1652. "valid_block_hash", cs.ProposalBlock.Hash(),
  1653. )
  1654. cs.ValidRound = cs.Round
  1655. cs.ValidBlock = cs.ProposalBlock
  1656. cs.ValidBlockParts = cs.ProposalBlockParts
  1657. }
  1658. // TODO: In case there is +2/3 majority in Prevotes set for some
  1659. // block and cs.ProposalBlock contains different block, either
  1660. // proposer is faulty or voting power of faulty processes is more
  1661. // than 1/3. We should trigger in the future accountability
  1662. // procedure at this point.
  1663. }
  1664. if cs.Step <= cstypes.RoundStepPropose && cs.isProposalComplete() {
  1665. // Move onto the next step
  1666. cs.enterPrevote(ctx, height, cs.Round)
  1667. if hasTwoThirds { // this is optimisation as this will be triggered when prevote is added
  1668. cs.enterPrecommit(ctx, height, cs.Round)
  1669. }
  1670. } else if cs.Step == cstypes.RoundStepCommit {
  1671. // If we're waiting on the proposal block...
  1672. cs.tryFinalizeCommit(ctx, height)
  1673. }
  1674. return added, nil
  1675. }
  1676. return added, nil
  1677. }
  1678. // Attempt to add the vote. if its a duplicate signature, dupeout the validator
  1679. func (cs *State) tryAddVote(ctx context.Context, vote *types.Vote, peerID types.NodeID) (bool, error) {
  1680. added, err := cs.addVote(ctx, vote, peerID)
  1681. if err != nil {
  1682. // If the vote height is off, we'll just ignore it,
  1683. // But if it's a conflicting sig, add it to the cs.evpool.
  1684. // If it's otherwise invalid, punish peer.
  1685. // nolint: gocritic
  1686. if voteErr, ok := err.(*types.ErrVoteConflictingVotes); ok {
  1687. if cs.privValidatorPubKey == nil {
  1688. return false, errPubKeyIsNotSet
  1689. }
  1690. if bytes.Equal(vote.ValidatorAddress, cs.privValidatorPubKey.Address()) {
  1691. cs.logger.Error(
  1692. "found conflicting vote from ourselves; did you unsafe_reset a validator?",
  1693. "height", vote.Height,
  1694. "round", vote.Round,
  1695. "type", vote.Type,
  1696. )
  1697. return added, err
  1698. }
  1699. // report conflicting votes to the evidence pool
  1700. cs.evpool.ReportConflictingVotes(voteErr.VoteA, voteErr.VoteB)
  1701. cs.logger.Debug(
  1702. "found and sent conflicting votes to the evidence pool",
  1703. "vote_a", voteErr.VoteA,
  1704. "vote_b", voteErr.VoteB,
  1705. )
  1706. return added, err
  1707. } else if errors.Is(err, types.ErrVoteNonDeterministicSignature) {
  1708. cs.logger.Debug("vote has non-deterministic signature", "err", err)
  1709. } else {
  1710. // Either
  1711. // 1) bad peer OR
  1712. // 2) not a bad peer? this can also err sometimes with "Unexpected step" OR
  1713. // 3) tmkms use with multiple validators connecting to a single tmkms instance
  1714. // (https://github.com/tendermint/tendermint/issues/3839).
  1715. cs.logger.Info("failed attempting to add vote", "err", err)
  1716. return added, ErrAddingVote
  1717. }
  1718. }
  1719. return added, nil
  1720. }
  1721. func (cs *State) addVote(
  1722. ctx context.Context,
  1723. vote *types.Vote,
  1724. peerID types.NodeID,
  1725. ) (added bool, err error) {
  1726. cs.logger.Debug(
  1727. "adding vote",
  1728. "vote_height", vote.Height,
  1729. "vote_type", vote.Type,
  1730. "val_index", vote.ValidatorIndex,
  1731. "cs_height", cs.Height,
  1732. )
  1733. // A precommit for the previous height?
  1734. // These come in while we wait timeoutCommit
  1735. if vote.Height+1 == cs.Height && vote.Type == tmproto.PrecommitType {
  1736. if cs.Step != cstypes.RoundStepNewHeight {
  1737. // Late precommit at prior height is ignored
  1738. cs.logger.Debug("precommit vote came in after commit timeout and has been ignored", "vote", vote)
  1739. return
  1740. }
  1741. added, err = cs.LastCommit.AddVote(vote)
  1742. if !added {
  1743. return
  1744. }
  1745. cs.logger.Debug("added vote to last precommits", "last_commit", cs.LastCommit.StringShort())
  1746. if err := cs.eventBus.PublishEventVote(ctx, types.EventDataVote{Vote: vote}); err != nil {
  1747. return added, err
  1748. }
  1749. cs.evsw.FireEvent(ctx, types.EventVoteValue, vote)
  1750. // if we can skip timeoutCommit and have all the votes now,
  1751. if cs.config.SkipTimeoutCommit && cs.LastCommit.HasAll() {
  1752. // go straight to new round (skip timeout commit)
  1753. // cs.scheduleTimeout(time.Duration(0), cs.Height, 0, cstypes.RoundStepNewHeight)
  1754. cs.enterNewRound(ctx, cs.Height, 0)
  1755. }
  1756. return
  1757. }
  1758. // Height mismatch is ignored.
  1759. // Not necessarily a bad peer, but not favorable behavior.
  1760. if vote.Height != cs.Height {
  1761. cs.logger.Debug("vote ignored and not added", "vote_height", vote.Height, "cs_height", cs.Height, "peer", peerID)
  1762. return
  1763. }
  1764. height := cs.Height
  1765. added, err = cs.Votes.AddVote(vote, peerID)
  1766. if !added {
  1767. // Either duplicate, or error upon cs.Votes.AddByIndex()
  1768. return
  1769. }
  1770. if err := cs.eventBus.PublishEventVote(ctx, types.EventDataVote{Vote: vote}); err != nil {
  1771. return added, err
  1772. }
  1773. cs.evsw.FireEvent(ctx, types.EventVoteValue, vote)
  1774. switch vote.Type {
  1775. case tmproto.PrevoteType:
  1776. prevotes := cs.Votes.Prevotes(vote.Round)
  1777. cs.logger.Debug("added vote to prevote", "vote", vote, "prevotes", prevotes.StringShort())
  1778. // If +2/3 prevotes for a block or nil for *any* round:
  1779. if blockID, ok := prevotes.TwoThirdsMajority(); ok {
  1780. // There was a polka!
  1781. // If we're locked but this is a recent polka, unlock.
  1782. // If it matches our ProposalBlock, update the ValidBlock
  1783. // Unlock if `cs.LockedRound < vote.Round <= cs.Round`
  1784. // NOTE: If vote.Round > cs.Round, we'll deal with it when we get to vote.Round
  1785. if (cs.LockedBlock != nil) &&
  1786. (cs.LockedRound < vote.Round) &&
  1787. (vote.Round <= cs.Round) &&
  1788. !cs.LockedBlock.HashesTo(blockID.Hash) {
  1789. cs.logger.Debug("unlocking because of POL", "locked_round", cs.LockedRound, "pol_round", vote.Round)
  1790. cs.LockedRound = -1
  1791. cs.LockedBlock = nil
  1792. cs.LockedBlockParts = nil
  1793. if err := cs.eventBus.PublishEventUnlock(ctx, cs.RoundStateEvent()); err != nil {
  1794. return added, err
  1795. }
  1796. }
  1797. // Update Valid* if we can.
  1798. // NOTE: our proposal block may be nil or not what received a polka..
  1799. if len(blockID.Hash) != 0 && (cs.ValidRound < vote.Round) && (vote.Round == cs.Round) {
  1800. if cs.ProposalBlock.HashesTo(blockID.Hash) {
  1801. cs.logger.Debug("updating valid block because of POL", "valid_round", cs.ValidRound, "pol_round", vote.Round)
  1802. cs.ValidRound = vote.Round
  1803. cs.ValidBlock = cs.ProposalBlock
  1804. cs.ValidBlockParts = cs.ProposalBlockParts
  1805. } else {
  1806. cs.logger.Debug(
  1807. "valid block we do not know about; set ProposalBlock=nil",
  1808. "proposal", cs.ProposalBlock.Hash(),
  1809. "block_id", blockID.Hash,
  1810. )
  1811. // we're getting the wrong block
  1812. cs.ProposalBlock = nil
  1813. }
  1814. if !cs.ProposalBlockParts.HasHeader(blockID.PartSetHeader) {
  1815. cs.ProposalBlockParts = types.NewPartSetFromHeader(blockID.PartSetHeader)
  1816. }
  1817. cs.evsw.FireEvent(ctx, types.EventValidBlockValue, &cs.RoundState)
  1818. if err := cs.eventBus.PublishEventValidBlock(ctx, cs.RoundStateEvent()); err != nil {
  1819. return added, err
  1820. }
  1821. }
  1822. }
  1823. // If +2/3 prevotes for *anything* for future round:
  1824. switch {
  1825. case cs.Round < vote.Round && prevotes.HasTwoThirdsAny():
  1826. // Round-skip if there is any 2/3+ of votes ahead of us
  1827. cs.enterNewRound(ctx, height, vote.Round)
  1828. case cs.Round == vote.Round && cstypes.RoundStepPrevote <= cs.Step: // current round
  1829. blockID, ok := prevotes.TwoThirdsMajority()
  1830. if ok && (cs.isProposalComplete() || len(blockID.Hash) == 0) {
  1831. cs.enterPrecommit(ctx, height, vote.Round)
  1832. } else if prevotes.HasTwoThirdsAny() {
  1833. cs.enterPrevoteWait(ctx, height, vote.Round)
  1834. }
  1835. case cs.Proposal != nil && 0 <= cs.Proposal.POLRound && cs.Proposal.POLRound == vote.Round:
  1836. // If the proposal is now complete, enter prevote of cs.Round.
  1837. if cs.isProposalComplete() {
  1838. cs.enterPrevote(ctx, height, cs.Round)
  1839. }
  1840. }
  1841. case tmproto.PrecommitType:
  1842. precommits := cs.Votes.Precommits(vote.Round)
  1843. cs.logger.Debug("added vote to precommit",
  1844. "height", vote.Height,
  1845. "round", vote.Round,
  1846. "validator", vote.ValidatorAddress.String(),
  1847. "vote_timestamp", vote.Timestamp,
  1848. "data", precommits.LogString())
  1849. blockID, ok := precommits.TwoThirdsMajority()
  1850. if ok {
  1851. // Executed as TwoThirdsMajority could be from a higher round
  1852. cs.enterNewRound(ctx, height, vote.Round)
  1853. cs.enterPrecommit(ctx, height, vote.Round)
  1854. if len(blockID.Hash) != 0 {
  1855. cs.enterCommit(ctx, height, vote.Round)
  1856. if cs.config.SkipTimeoutCommit && precommits.HasAll() {
  1857. cs.enterNewRound(ctx, cs.Height, 0)
  1858. }
  1859. } else {
  1860. cs.enterPrecommitWait(ctx, height, vote.Round)
  1861. }
  1862. } else if cs.Round <= vote.Round && precommits.HasTwoThirdsAny() {
  1863. cs.enterNewRound(ctx, height, vote.Round)
  1864. cs.enterPrecommitWait(ctx, height, vote.Round)
  1865. }
  1866. default:
  1867. panic(fmt.Sprintf("unexpected vote type %v", vote.Type))
  1868. }
  1869. return added, err
  1870. }
  1871. // CONTRACT: cs.privValidator is not nil.
  1872. func (cs *State) signVote(
  1873. ctx context.Context,
  1874. msgType tmproto.SignedMsgType,
  1875. hash []byte,
  1876. header types.PartSetHeader,
  1877. ) (*types.Vote, error) {
  1878. // Flush the WAL. Otherwise, we may not recompute the same vote to sign,
  1879. // and the privValidator will refuse to sign anything.
  1880. if err := cs.wal.FlushAndSync(); err != nil {
  1881. return nil, err
  1882. }
  1883. if cs.privValidatorPubKey == nil {
  1884. return nil, errPubKeyIsNotSet
  1885. }
  1886. addr := cs.privValidatorPubKey.Address()
  1887. valIdx, _ := cs.Validators.GetByAddress(addr)
  1888. vote := &types.Vote{
  1889. ValidatorAddress: addr,
  1890. ValidatorIndex: valIdx,
  1891. Height: cs.Height,
  1892. Round: cs.Round,
  1893. Timestamp: cs.voteTime(),
  1894. Type: msgType,
  1895. BlockID: types.BlockID{Hash: hash, PartSetHeader: header},
  1896. }
  1897. v := vote.ToProto()
  1898. // If the signedMessageType is for precommit,
  1899. // use our local precommit Timeout as the max wait time for getting a singed commit. The same goes for prevote.
  1900. var timeout time.Duration
  1901. switch msgType {
  1902. case tmproto.PrecommitType:
  1903. timeout = cs.config.TimeoutPrecommit
  1904. case tmproto.PrevoteType:
  1905. timeout = cs.config.TimeoutPrevote
  1906. default:
  1907. timeout = time.Second
  1908. }
  1909. ctxto, cancel := context.WithTimeout(ctx, timeout)
  1910. defer cancel()
  1911. err := cs.privValidator.SignVote(ctxto, cs.state.ChainID, v)
  1912. vote.Signature = v.Signature
  1913. vote.Timestamp = v.Timestamp
  1914. return vote, err
  1915. }
  1916. // voteTime ensures monotonicity of the time a validator votes on.
  1917. // It ensures that for a prior block with a BFT-timestamp of T,
  1918. // any vote from this validator will have time at least time T + 1ms.
  1919. // This is needed, as monotonicity of time is a guarantee that BFT time provides.
  1920. func (cs *State) voteTime() time.Time {
  1921. now := tmtime.Now()
  1922. minVoteTime := now
  1923. // Minimum time increment between blocks
  1924. const timeIota = time.Millisecond
  1925. // TODO: We should remove next line in case we don't vote for v in case cs.ProposalBlock == nil,
  1926. // even if cs.LockedBlock != nil. See https://docs.tendermint.com/master/spec/.
  1927. if cs.LockedBlock != nil {
  1928. // See the BFT time spec https://docs.tendermint.com/master/spec/consensus/bft-time.html
  1929. minVoteTime = cs.LockedBlock.Time.Add(timeIota)
  1930. } else if cs.ProposalBlock != nil {
  1931. minVoteTime = cs.ProposalBlock.Time.Add(timeIota)
  1932. }
  1933. if now.After(minVoteTime) {
  1934. return now
  1935. }
  1936. return minVoteTime
  1937. }
  1938. // sign the vote and publish on internalMsgQueue
  1939. func (cs *State) signAddVote(ctx context.Context, msgType tmproto.SignedMsgType, hash []byte, header types.PartSetHeader) *types.Vote {
  1940. if cs.privValidator == nil { // the node does not have a key
  1941. return nil
  1942. }
  1943. if cs.privValidatorPubKey == nil {
  1944. // Vote won't be signed, but it's not critical.
  1945. cs.logger.Error("signAddVote", "err", errPubKeyIsNotSet)
  1946. return nil
  1947. }
  1948. // If the node not in the validator set, do nothing.
  1949. if !cs.Validators.HasAddress(cs.privValidatorPubKey.Address()) {
  1950. return nil
  1951. }
  1952. // TODO: pass pubKey to signVote
  1953. vote, err := cs.signVote(ctx, msgType, hash, header)
  1954. if err == nil {
  1955. cs.sendInternalMessage(ctx, msgInfo{&VoteMessage{vote}, ""})
  1956. cs.logger.Debug("signed and pushed vote", "height", cs.Height, "round", cs.Round, "vote", vote)
  1957. return vote
  1958. }
  1959. cs.logger.Error("failed signing vote", "height", cs.Height, "round", cs.Round, "vote", vote, "err", err)
  1960. return nil
  1961. }
  1962. // updatePrivValidatorPubKey get's the private validator public key and
  1963. // memoizes it. This func returns an error if the private validator is not
  1964. // responding or responds with an error.
  1965. func (cs *State) updatePrivValidatorPubKey(rctx context.Context) error {
  1966. if cs.privValidator == nil {
  1967. return nil
  1968. }
  1969. var timeout time.Duration
  1970. if cs.config.TimeoutPrecommit > cs.config.TimeoutPrevote {
  1971. timeout = cs.config.TimeoutPrecommit
  1972. } else {
  1973. timeout = cs.config.TimeoutPrevote
  1974. }
  1975. // no GetPubKey retry beyond the proposal/voting in RetrySignerClient
  1976. if cs.Step >= cstypes.RoundStepPrecommit && cs.privValidatorType == types.RetrySignerClient {
  1977. timeout = 0
  1978. }
  1979. // set context timeout depending on the configuration and the State step,
  1980. // this helps in avoiding blocking of the remote signer connection.
  1981. ctxto, cancel := context.WithTimeout(rctx, timeout)
  1982. defer cancel()
  1983. pubKey, err := cs.privValidator.GetPubKey(ctxto)
  1984. if err != nil {
  1985. return err
  1986. }
  1987. cs.privValidatorPubKey = pubKey
  1988. return nil
  1989. }
  1990. // look back to check existence of the node's consensus votes before joining consensus
  1991. func (cs *State) checkDoubleSigningRisk(height int64) error {
  1992. if cs.privValidator != nil && cs.privValidatorPubKey != nil && cs.config.DoubleSignCheckHeight > 0 && height > 0 {
  1993. valAddr := cs.privValidatorPubKey.Address()
  1994. doubleSignCheckHeight := cs.config.DoubleSignCheckHeight
  1995. if doubleSignCheckHeight > height {
  1996. doubleSignCheckHeight = height
  1997. }
  1998. for i := int64(1); i < doubleSignCheckHeight; i++ {
  1999. lastCommit := cs.LoadCommit(height - i)
  2000. if lastCommit != nil {
  2001. for sigIdx, s := range lastCommit.Signatures {
  2002. if s.BlockIDFlag == types.BlockIDFlagCommit && bytes.Equal(s.ValidatorAddress, valAddr) {
  2003. cs.logger.Info("found signature from the same key", "sig", s, "idx", sigIdx, "height", height-i)
  2004. return ErrSignatureFoundInPastBlocks
  2005. }
  2006. }
  2007. }
  2008. }
  2009. }
  2010. return nil
  2011. }
  2012. //---------------------------------------------------------
  2013. func CompareHRS(h1 int64, r1 int32, s1 cstypes.RoundStepType, h2 int64, r2 int32, s2 cstypes.RoundStepType) int {
  2014. if h1 < h2 {
  2015. return -1
  2016. } else if h1 > h2 {
  2017. return 1
  2018. }
  2019. if r1 < r2 {
  2020. return -1
  2021. } else if r1 > r2 {
  2022. return 1
  2023. }
  2024. if s1 < s2 {
  2025. return -1
  2026. } else if s1 > s2 {
  2027. return 1
  2028. }
  2029. return 0
  2030. }
  2031. // repairWalFile decodes messages from src (until the decoder errors) and
  2032. // writes them to dst.
  2033. func repairWalFile(src, dst string) error {
  2034. in, err := os.Open(src)
  2035. if err != nil {
  2036. return err
  2037. }
  2038. defer in.Close()
  2039. out, err := os.Create(dst)
  2040. if err != nil {
  2041. return err
  2042. }
  2043. defer out.Close()
  2044. var (
  2045. dec = NewWALDecoder(in)
  2046. enc = NewWALEncoder(out)
  2047. )
  2048. // best-case repair (until first error is encountered)
  2049. for {
  2050. msg, err := dec.Decode()
  2051. if err != nil {
  2052. break
  2053. }
  2054. err = enc.Encode(msg)
  2055. if err != nil {
  2056. return fmt.Errorf("failed to encode msg: %w", err)
  2057. }
  2058. }
  2059. return nil
  2060. }