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.

1391 lines
41 KiB

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
7 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
7 years ago
7 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
7 years ago
10 years ago
7 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
7 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
7 years ago
7 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
7 years ago
7 years ago
10 years ago
7 years ago
10 years ago
10 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
10 years ago
7 years ago
10 years ago
7 years ago
7 years ago
10 years ago
10 years ago
7 years ago
7 years ago
10 years ago
10 years ago
7 years ago
7 years ago
7 years ago
7 years ago
10 years ago
10 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
7 years ago
7 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
7 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
7 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
7 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
7 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
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
10 years ago
10 years ago
7 years ago
10 years ago
10 years ago
9 years ago
7 years ago
10 years ago
10 years ago
10 years ago
10 years ago
7 years ago
7 years ago
10 years ago
7 years ago
10 years ago
10 years ago
7 years ago
9 years ago
10 years ago
10 years ago
7 years ago
10 years ago
10 years ago
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
10 years ago
7 years ago
7 years ago
7 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
7 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
7 years ago
  1. package consensus
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "reflect"
  7. "sync"
  8. "time"
  9. "github.com/pkg/errors"
  10. wire "github.com/tendermint/go-wire"
  11. cmn "github.com/tendermint/tmlibs/common"
  12. "github.com/tendermint/tmlibs/log"
  13. cstypes "github.com/tendermint/tendermint/consensus/types"
  14. "github.com/tendermint/tendermint/p2p"
  15. sm "github.com/tendermint/tendermint/state"
  16. "github.com/tendermint/tendermint/types"
  17. )
  18. const (
  19. StateChannel = byte(0x20)
  20. DataChannel = byte(0x21)
  21. VoteChannel = byte(0x22)
  22. VoteSetBitsChannel = byte(0x23)
  23. maxConsensusMessageSize = 1048576 // 1MB; NOTE/TODO: keep in sync with types.PartSet sizes.
  24. )
  25. //-----------------------------------------------------------------------------
  26. // ConsensusReactor defines a reactor for the consensus service.
  27. type ConsensusReactor struct {
  28. p2p.BaseReactor // BaseService + p2p.Switch
  29. conS *ConsensusState
  30. mtx sync.RWMutex
  31. fastSync bool
  32. eventBus *types.EventBus
  33. }
  34. // NewConsensusReactor returns a new ConsensusReactor with the given consensusState.
  35. func NewConsensusReactor(consensusState *ConsensusState, fastSync bool) *ConsensusReactor {
  36. conR := &ConsensusReactor{
  37. conS: consensusState,
  38. fastSync: fastSync,
  39. }
  40. conR.BaseReactor = *p2p.NewBaseReactor("ConsensusReactor", conR)
  41. return conR
  42. }
  43. // OnStart implements BaseService.
  44. func (conR *ConsensusReactor) OnStart() error {
  45. conR.Logger.Info("ConsensusReactor ", "fastSync", conR.FastSync())
  46. if err := conR.BaseReactor.OnStart(); err != nil {
  47. return err
  48. }
  49. err := conR.startBroadcastRoutine()
  50. if err != nil {
  51. return err
  52. }
  53. if !conR.FastSync() {
  54. err := conR.conS.Start()
  55. if err != nil {
  56. return err
  57. }
  58. }
  59. return nil
  60. }
  61. // OnStop implements BaseService
  62. func (conR *ConsensusReactor) OnStop() {
  63. conR.BaseReactor.OnStop()
  64. conR.conS.Stop()
  65. }
  66. // SwitchToConsensus switches from fast_sync mode to consensus mode.
  67. // It resets the state, turns off fast_sync, and starts the consensus state-machine
  68. func (conR *ConsensusReactor) SwitchToConsensus(state *sm.State, blocksSynced int) {
  69. conR.Logger.Info("SwitchToConsensus")
  70. conR.conS.reconstructLastCommit(state)
  71. // NOTE: The line below causes broadcastNewRoundStepRoutine() to
  72. // broadcast a NewRoundStepMessage.
  73. conR.conS.updateToState(state)
  74. conR.mtx.Lock()
  75. conR.fastSync = false
  76. conR.mtx.Unlock()
  77. if blocksSynced > 0 {
  78. // dont bother with the WAL if we fast synced
  79. conR.conS.doWALCatchup = false
  80. }
  81. err := conR.conS.Start()
  82. if err != nil {
  83. conR.Logger.Error("Error starting conS", "err", err)
  84. }
  85. }
  86. // GetChannels implements Reactor
  87. func (conR *ConsensusReactor) GetChannels() []*p2p.ChannelDescriptor {
  88. // TODO optimize
  89. return []*p2p.ChannelDescriptor{
  90. {
  91. ID: StateChannel,
  92. Priority: 5,
  93. SendQueueCapacity: 100,
  94. },
  95. {
  96. ID: DataChannel, // maybe split between gossiping current block and catchup stuff
  97. Priority: 10, // once we gossip the whole block there's nothing left to send until next height or round
  98. SendQueueCapacity: 100,
  99. RecvBufferCapacity: 50 * 4096,
  100. },
  101. {
  102. ID: VoteChannel,
  103. Priority: 5,
  104. SendQueueCapacity: 100,
  105. RecvBufferCapacity: 100 * 100,
  106. },
  107. {
  108. ID: VoteSetBitsChannel,
  109. Priority: 1,
  110. SendQueueCapacity: 2,
  111. RecvBufferCapacity: 1024,
  112. },
  113. }
  114. }
  115. // AddPeer implements Reactor
  116. func (conR *ConsensusReactor) AddPeer(peer p2p.Peer) {
  117. if !conR.IsRunning() {
  118. return
  119. }
  120. // Create peerState for peer
  121. peerState := NewPeerState(peer).SetLogger(conR.Logger)
  122. peer.Set(types.PeerStateKey, peerState)
  123. // Begin routines for this peer.
  124. go conR.gossipDataRoutine(peer, peerState)
  125. go conR.gossipVotesRoutine(peer, peerState)
  126. go conR.queryMaj23Routine(peer, peerState)
  127. // Send our state to peer.
  128. // If we're fast_syncing, broadcast a RoundStepMessage later upon SwitchToConsensus().
  129. if !conR.FastSync() {
  130. conR.sendNewRoundStepMessages(peer)
  131. }
  132. }
  133. // RemovePeer implements Reactor
  134. func (conR *ConsensusReactor) RemovePeer(peer p2p.Peer, reason interface{}) {
  135. if !conR.IsRunning() {
  136. return
  137. }
  138. // TODO
  139. //peer.Get(PeerStateKey).(*PeerState).Disconnect()
  140. }
  141. // Receive implements Reactor
  142. // NOTE: We process these messages even when we're fast_syncing.
  143. // Messages affect either a peer state or the consensus state.
  144. // Peer state updates can happen in parallel, but processing of
  145. // proposals, block parts, and votes are ordered by the receiveRoutine
  146. // NOTE: blocks on consensus state for proposals, block parts, and votes
  147. func (conR *ConsensusReactor) Receive(chID byte, src p2p.Peer, msgBytes []byte) {
  148. if !conR.IsRunning() {
  149. conR.Logger.Debug("Receive", "src", src, "chId", chID, "bytes", msgBytes)
  150. return
  151. }
  152. _, msg, err := DecodeMessage(msgBytes)
  153. if err != nil {
  154. conR.Logger.Error("Error decoding message", "src", src, "chId", chID, "msg", msg, "err", err, "bytes", msgBytes)
  155. // TODO punish peer?
  156. return
  157. }
  158. conR.Logger.Debug("Receive", "src", src, "chId", chID, "msg", msg)
  159. // Get peer states
  160. ps := src.Get(types.PeerStateKey).(*PeerState)
  161. switch chID {
  162. case StateChannel:
  163. switch msg := msg.(type) {
  164. case *NewRoundStepMessage:
  165. ps.ApplyNewRoundStepMessage(msg)
  166. case *CommitStepMessage:
  167. ps.ApplyCommitStepMessage(msg)
  168. case *HasVoteMessage:
  169. ps.ApplyHasVoteMessage(msg)
  170. case *VoteSetMaj23Message:
  171. cs := conR.conS
  172. cs.mtx.Lock()
  173. height, votes := cs.Height, cs.Votes
  174. cs.mtx.Unlock()
  175. if height != msg.Height {
  176. return
  177. }
  178. // Peer claims to have a maj23 for some BlockID at H,R,S,
  179. votes.SetPeerMaj23(msg.Round, msg.Type, ps.Peer.Key(), msg.BlockID)
  180. // Respond with a VoteSetBitsMessage showing which votes we have.
  181. // (and consequently shows which we don't have)
  182. var ourVotes *cmn.BitArray
  183. switch msg.Type {
  184. case types.VoteTypePrevote:
  185. ourVotes = votes.Prevotes(msg.Round).BitArrayByBlockID(msg.BlockID)
  186. case types.VoteTypePrecommit:
  187. ourVotes = votes.Precommits(msg.Round).BitArrayByBlockID(msg.BlockID)
  188. default:
  189. conR.Logger.Error("Bad VoteSetBitsMessage field Type")
  190. return
  191. }
  192. src.TrySend(VoteSetBitsChannel, struct{ ConsensusMessage }{&VoteSetBitsMessage{
  193. Height: msg.Height,
  194. Round: msg.Round,
  195. Type: msg.Type,
  196. BlockID: msg.BlockID,
  197. Votes: ourVotes,
  198. }})
  199. case *ProposalHeartbeatMessage:
  200. hb := msg.Heartbeat
  201. conR.Logger.Debug("Received proposal heartbeat message",
  202. "height", hb.Height, "round", hb.Round, "sequence", hb.Sequence,
  203. "valIdx", hb.ValidatorIndex, "valAddr", hb.ValidatorAddress)
  204. default:
  205. conR.Logger.Error(cmn.Fmt("Unknown message type %v", reflect.TypeOf(msg)))
  206. }
  207. case DataChannel:
  208. if conR.FastSync() {
  209. conR.Logger.Info("Ignoring message received during fastSync", "msg", msg)
  210. return
  211. }
  212. switch msg := msg.(type) {
  213. case *ProposalMessage:
  214. ps.SetHasProposal(msg.Proposal)
  215. conR.conS.peerMsgQueue <- msgInfo{msg, src.Key()}
  216. case *ProposalPOLMessage:
  217. ps.ApplyProposalPOLMessage(msg)
  218. case *BlockPartMessage:
  219. ps.SetHasProposalBlockPart(msg.Height, msg.Round, msg.Part.Index)
  220. conR.conS.peerMsgQueue <- msgInfo{msg, src.Key()}
  221. default:
  222. conR.Logger.Error(cmn.Fmt("Unknown message type %v", reflect.TypeOf(msg)))
  223. }
  224. case VoteChannel:
  225. if conR.FastSync() {
  226. conR.Logger.Info("Ignoring message received during fastSync", "msg", msg)
  227. return
  228. }
  229. switch msg := msg.(type) {
  230. case *VoteMessage:
  231. cs := conR.conS
  232. cs.mtx.Lock()
  233. height, valSize, lastCommitSize := cs.Height, cs.Validators.Size(), cs.LastCommit.Size()
  234. cs.mtx.Unlock()
  235. ps.EnsureVoteBitArrays(height, valSize)
  236. ps.EnsureVoteBitArrays(height-1, lastCommitSize)
  237. ps.SetHasVote(msg.Vote)
  238. cs.peerMsgQueue <- msgInfo{msg, src.Key()}
  239. default:
  240. // don't punish (leave room for soft upgrades)
  241. conR.Logger.Error(cmn.Fmt("Unknown message type %v", reflect.TypeOf(msg)))
  242. }
  243. case VoteSetBitsChannel:
  244. if conR.FastSync() {
  245. conR.Logger.Info("Ignoring message received during fastSync", "msg", msg)
  246. return
  247. }
  248. switch msg := msg.(type) {
  249. case *VoteSetBitsMessage:
  250. cs := conR.conS
  251. cs.mtx.Lock()
  252. height, votes := cs.Height, cs.Votes
  253. cs.mtx.Unlock()
  254. if height == msg.Height {
  255. var ourVotes *cmn.BitArray
  256. switch msg.Type {
  257. case types.VoteTypePrevote:
  258. ourVotes = votes.Prevotes(msg.Round).BitArrayByBlockID(msg.BlockID)
  259. case types.VoteTypePrecommit:
  260. ourVotes = votes.Precommits(msg.Round).BitArrayByBlockID(msg.BlockID)
  261. default:
  262. conR.Logger.Error("Bad VoteSetBitsMessage field Type")
  263. return
  264. }
  265. ps.ApplyVoteSetBitsMessage(msg, ourVotes)
  266. } else {
  267. ps.ApplyVoteSetBitsMessage(msg, nil)
  268. }
  269. default:
  270. // don't punish (leave room for soft upgrades)
  271. conR.Logger.Error(cmn.Fmt("Unknown message type %v", reflect.TypeOf(msg)))
  272. }
  273. default:
  274. conR.Logger.Error(cmn.Fmt("Unknown chId %X", chID))
  275. }
  276. if err != nil {
  277. conR.Logger.Error("Error in Receive()", "err", err)
  278. }
  279. }
  280. // SetEventBus sets event bus.
  281. func (conR *ConsensusReactor) SetEventBus(b *types.EventBus) {
  282. conR.eventBus = b
  283. conR.conS.SetEventBus(b)
  284. }
  285. // FastSync returns whether the consensus reactor is in fast-sync mode.
  286. func (conR *ConsensusReactor) FastSync() bool {
  287. conR.mtx.RLock()
  288. defer conR.mtx.RUnlock()
  289. return conR.fastSync
  290. }
  291. //--------------------------------------
  292. // startBroadcastRoutine subscribes for new round steps, votes and proposal
  293. // heartbeats using the event bus and starts a go routine to broadcasts events
  294. // to peers upon receiving them.
  295. func (conR *ConsensusReactor) startBroadcastRoutine() error {
  296. const subscriber = "consensus-reactor"
  297. ctx := context.Background()
  298. // new round steps
  299. stepsCh := make(chan interface{})
  300. err := conR.eventBus.Subscribe(ctx, subscriber, types.EventQueryNewRoundStep, stepsCh)
  301. if err != nil {
  302. return errors.Wrapf(err, "failed to subscribe %s to %s", subscriber, types.EventQueryNewRoundStep)
  303. }
  304. // votes
  305. votesCh := make(chan interface{})
  306. err = conR.eventBus.Subscribe(ctx, subscriber, types.EventQueryVote, votesCh)
  307. if err != nil {
  308. return errors.Wrapf(err, "failed to subscribe %s to %s", subscriber, types.EventQueryVote)
  309. }
  310. // proposal heartbeats
  311. heartbeatsCh := make(chan interface{})
  312. err = conR.eventBus.Subscribe(ctx, subscriber, types.EventQueryProposalHeartbeat, heartbeatsCh)
  313. if err != nil {
  314. return errors.Wrapf(err, "failed to subscribe %s to %s", subscriber, types.EventQueryProposalHeartbeat)
  315. }
  316. go func() {
  317. for {
  318. select {
  319. case data, ok := <-stepsCh:
  320. if ok { // a receive from a closed channel returns the zero value immediately
  321. edrs := data.(types.TMEventData).Unwrap().(types.EventDataRoundState)
  322. conR.broadcastNewRoundStep(edrs.RoundState.(*cstypes.RoundState))
  323. }
  324. case data, ok := <-votesCh:
  325. if ok {
  326. edv := data.(types.TMEventData).Unwrap().(types.EventDataVote)
  327. conR.broadcastHasVoteMessage(edv.Vote)
  328. }
  329. case data, ok := <-heartbeatsCh:
  330. if ok {
  331. edph := data.(types.TMEventData).Unwrap().(types.EventDataProposalHeartbeat)
  332. conR.broadcastProposalHeartbeatMessage(edph)
  333. }
  334. case <-conR.Quit:
  335. conR.eventBus.UnsubscribeAll(ctx, subscriber)
  336. return
  337. }
  338. }
  339. }()
  340. return nil
  341. }
  342. func (conR *ConsensusReactor) broadcastProposalHeartbeatMessage(heartbeat types.EventDataProposalHeartbeat) {
  343. hb := heartbeat.Heartbeat
  344. conR.Logger.Debug("Broadcasting proposal heartbeat message",
  345. "height", hb.Height, "round", hb.Round, "sequence", hb.Sequence)
  346. msg := &ProposalHeartbeatMessage{hb}
  347. conR.Switch.Broadcast(StateChannel, struct{ ConsensusMessage }{msg})
  348. }
  349. func (conR *ConsensusReactor) broadcastNewRoundStep(rs *cstypes.RoundState) {
  350. nrsMsg, csMsg := makeRoundStepMessages(rs)
  351. if nrsMsg != nil {
  352. conR.Switch.Broadcast(StateChannel, struct{ ConsensusMessage }{nrsMsg})
  353. }
  354. if csMsg != nil {
  355. conR.Switch.Broadcast(StateChannel, struct{ ConsensusMessage }{csMsg})
  356. }
  357. }
  358. // Broadcasts HasVoteMessage to peers that care.
  359. func (conR *ConsensusReactor) broadcastHasVoteMessage(vote *types.Vote) {
  360. msg := &HasVoteMessage{
  361. Height: vote.Height,
  362. Round: vote.Round,
  363. Type: vote.Type,
  364. Index: vote.ValidatorIndex,
  365. }
  366. conR.Switch.Broadcast(StateChannel, struct{ ConsensusMessage }{msg})
  367. /*
  368. // TODO: Make this broadcast more selective.
  369. for _, peer := range conR.Switch.Peers().List() {
  370. ps := peer.Get(PeerStateKey).(*PeerState)
  371. prs := ps.GetRoundState()
  372. if prs.Height == vote.Height {
  373. // TODO: Also filter on round?
  374. peer.TrySend(StateChannel, struct{ ConsensusMessage }{msg})
  375. } else {
  376. // Height doesn't match
  377. // TODO: check a field, maybe CatchupCommitRound?
  378. // TODO: But that requires changing the struct field comment.
  379. }
  380. }
  381. */
  382. }
  383. func makeRoundStepMessages(rs *cstypes.RoundState) (nrsMsg *NewRoundStepMessage, csMsg *CommitStepMessage) {
  384. nrsMsg = &NewRoundStepMessage{
  385. Height: rs.Height,
  386. Round: rs.Round,
  387. Step: rs.Step,
  388. SecondsSinceStartTime: int(time.Since(rs.StartTime).Seconds()),
  389. LastCommitRound: rs.LastCommit.Round(),
  390. }
  391. if rs.Step == cstypes.RoundStepCommit {
  392. csMsg = &CommitStepMessage{
  393. Height: rs.Height,
  394. BlockPartsHeader: rs.ProposalBlockParts.Header(),
  395. BlockParts: rs.ProposalBlockParts.BitArray(),
  396. }
  397. }
  398. return
  399. }
  400. func (conR *ConsensusReactor) sendNewRoundStepMessages(peer p2p.Peer) {
  401. rs := conR.conS.GetRoundState()
  402. nrsMsg, csMsg := makeRoundStepMessages(rs)
  403. if nrsMsg != nil {
  404. peer.Send(StateChannel, struct{ ConsensusMessage }{nrsMsg})
  405. }
  406. if csMsg != nil {
  407. peer.Send(StateChannel, struct{ ConsensusMessage }{csMsg})
  408. }
  409. }
  410. func (conR *ConsensusReactor) gossipDataRoutine(peer p2p.Peer, ps *PeerState) {
  411. logger := conR.Logger.With("peer", peer)
  412. OUTER_LOOP:
  413. for {
  414. // Manage disconnects from self or peer.
  415. if !peer.IsRunning() || !conR.IsRunning() {
  416. logger.Info("Stopping gossipDataRoutine for peer")
  417. return
  418. }
  419. rs := conR.conS.GetRoundState()
  420. prs := ps.GetRoundState()
  421. // Send proposal Block parts?
  422. if rs.ProposalBlockParts.HasHeader(prs.ProposalBlockPartsHeader) {
  423. if index, ok := rs.ProposalBlockParts.BitArray().Sub(prs.ProposalBlockParts.Copy()).PickRandom(); ok {
  424. part := rs.ProposalBlockParts.GetPart(index)
  425. msg := &BlockPartMessage{
  426. Height: rs.Height, // This tells peer that this part applies to us.
  427. Round: rs.Round, // This tells peer that this part applies to us.
  428. Part: part,
  429. }
  430. logger.Debug("Sending block part", "height", prs.Height, "round", prs.Round)
  431. if peer.Send(DataChannel, struct{ ConsensusMessage }{msg}) {
  432. ps.SetHasProposalBlockPart(prs.Height, prs.Round, index)
  433. }
  434. continue OUTER_LOOP
  435. }
  436. }
  437. // If the peer is on a previous height, help catch up.
  438. if (0 < prs.Height) && (prs.Height < rs.Height) {
  439. heightLogger := logger.With("height", prs.Height)
  440. // if we never received the commit message from the peer, the block parts wont be initialized
  441. if prs.ProposalBlockParts == nil {
  442. blockMeta := conR.conS.blockStore.LoadBlockMeta(prs.Height)
  443. if blockMeta == nil {
  444. cmn.PanicCrisis(cmn.Fmt("Failed to load block %d when blockStore is at %d",
  445. prs.Height, conR.conS.blockStore.Height()))
  446. }
  447. ps.InitProposalBlockParts(blockMeta.BlockID.PartsHeader)
  448. // continue the loop since prs is a copy and not effected by this initialization
  449. continue OUTER_LOOP
  450. }
  451. conR.gossipDataForCatchup(heightLogger, rs, prs, ps, peer)
  452. continue OUTER_LOOP
  453. }
  454. // If height and round don't match, sleep.
  455. if (rs.Height != prs.Height) || (rs.Round != prs.Round) {
  456. //logger.Info("Peer Height|Round mismatch, sleeping", "peerHeight", prs.Height, "peerRound", prs.Round, "peer", peer)
  457. time.Sleep(conR.conS.config.PeerGossipSleep())
  458. continue OUTER_LOOP
  459. }
  460. // By here, height and round match.
  461. // Proposal block parts were already matched and sent if any were wanted.
  462. // (These can match on hash so the round doesn't matter)
  463. // Now consider sending other things, like the Proposal itself.
  464. // Send Proposal && ProposalPOL BitArray?
  465. if rs.Proposal != nil && !prs.Proposal {
  466. // Proposal: share the proposal metadata with peer.
  467. {
  468. msg := &ProposalMessage{Proposal: rs.Proposal}
  469. logger.Debug("Sending proposal", "height", prs.Height, "round", prs.Round)
  470. if peer.Send(DataChannel, struct{ ConsensusMessage }{msg}) {
  471. ps.SetHasProposal(rs.Proposal)
  472. }
  473. }
  474. // ProposalPOL: lets peer know which POL votes we have so far.
  475. // Peer must receive ProposalMessage first.
  476. // rs.Proposal was validated, so rs.Proposal.POLRound <= rs.Round,
  477. // so we definitely have rs.Votes.Prevotes(rs.Proposal.POLRound).
  478. if 0 <= rs.Proposal.POLRound {
  479. msg := &ProposalPOLMessage{
  480. Height: rs.Height,
  481. ProposalPOLRound: rs.Proposal.POLRound,
  482. ProposalPOL: rs.Votes.Prevotes(rs.Proposal.POLRound).BitArray(),
  483. }
  484. logger.Debug("Sending POL", "height", prs.Height, "round", prs.Round)
  485. peer.Send(DataChannel, struct{ ConsensusMessage }{msg})
  486. }
  487. continue OUTER_LOOP
  488. }
  489. // Nothing to do. Sleep.
  490. time.Sleep(conR.conS.config.PeerGossipSleep())
  491. continue OUTER_LOOP
  492. }
  493. }
  494. func (conR *ConsensusReactor) gossipDataForCatchup(logger log.Logger, rs *cstypes.RoundState,
  495. prs *cstypes.PeerRoundState, ps *PeerState, peer p2p.Peer) {
  496. if index, ok := prs.ProposalBlockParts.Not().PickRandom(); ok {
  497. // Ensure that the peer's PartSetHeader is correct
  498. blockMeta := conR.conS.blockStore.LoadBlockMeta(prs.Height)
  499. if blockMeta == nil {
  500. logger.Error("Failed to load block meta",
  501. "ourHeight", rs.Height, "blockstoreHeight", conR.conS.blockStore.Height())
  502. time.Sleep(conR.conS.config.PeerGossipSleep())
  503. return
  504. } else if !blockMeta.BlockID.PartsHeader.Equals(prs.ProposalBlockPartsHeader) {
  505. logger.Info("Peer ProposalBlockPartsHeader mismatch, sleeping",
  506. "blockPartsHeader", blockMeta.BlockID.PartsHeader, "peerBlockPartsHeader", prs.ProposalBlockPartsHeader)
  507. time.Sleep(conR.conS.config.PeerGossipSleep())
  508. return
  509. }
  510. // Load the part
  511. part := conR.conS.blockStore.LoadBlockPart(prs.Height, index)
  512. if part == nil {
  513. logger.Error("Could not load part", "index", index,
  514. "blockPartsHeader", blockMeta.BlockID.PartsHeader, "peerBlockPartsHeader", prs.ProposalBlockPartsHeader)
  515. time.Sleep(conR.conS.config.PeerGossipSleep())
  516. return
  517. }
  518. // Send the part
  519. msg := &BlockPartMessage{
  520. Height: prs.Height, // Not our height, so it doesn't matter.
  521. Round: prs.Round, // Not our height, so it doesn't matter.
  522. Part: part,
  523. }
  524. logger.Debug("Sending block part for catchup", "round", prs.Round, "index", index)
  525. if peer.Send(DataChannel, struct{ ConsensusMessage }{msg}) {
  526. ps.SetHasProposalBlockPart(prs.Height, prs.Round, index)
  527. } else {
  528. logger.Debug("Sending block part for catchup failed")
  529. }
  530. return
  531. } else {
  532. //logger.Info("No parts to send in catch-up, sleeping")
  533. time.Sleep(conR.conS.config.PeerGossipSleep())
  534. return
  535. }
  536. }
  537. func (conR *ConsensusReactor) gossipVotesRoutine(peer p2p.Peer, ps *PeerState) {
  538. logger := conR.Logger.With("peer", peer)
  539. // Simple hack to throttle logs upon sleep.
  540. var sleeping = 0
  541. OUTER_LOOP:
  542. for {
  543. // Manage disconnects from self or peer.
  544. if !peer.IsRunning() || !conR.IsRunning() {
  545. logger.Info("Stopping gossipVotesRoutine for peer")
  546. return
  547. }
  548. rs := conR.conS.GetRoundState()
  549. prs := ps.GetRoundState()
  550. switch sleeping {
  551. case 1: // First sleep
  552. sleeping = 2
  553. case 2: // No more sleep
  554. sleeping = 0
  555. }
  556. //logger.Debug("gossipVotesRoutine", "rsHeight", rs.Height, "rsRound", rs.Round,
  557. // "prsHeight", prs.Height, "prsRound", prs.Round, "prsStep", prs.Step)
  558. // If height matches, then send LastCommit, Prevotes, Precommits.
  559. if rs.Height == prs.Height {
  560. heightLogger := logger.With("height", prs.Height)
  561. if conR.gossipVotesForHeight(heightLogger, rs, prs, ps) {
  562. continue OUTER_LOOP
  563. }
  564. }
  565. // Special catchup logic.
  566. // If peer is lagging by height 1, send LastCommit.
  567. if prs.Height != 0 && rs.Height == prs.Height+1 {
  568. if ps.PickSendVote(rs.LastCommit) {
  569. logger.Debug("Picked rs.LastCommit to send", "height", prs.Height)
  570. continue OUTER_LOOP
  571. }
  572. }
  573. // Catchup logic
  574. // If peer is lagging by more than 1, send Commit.
  575. if prs.Height != 0 && rs.Height >= prs.Height+2 {
  576. // Load the block commit for prs.Height,
  577. // which contains precommit signatures for prs.Height.
  578. commit := conR.conS.blockStore.LoadBlockCommit(prs.Height)
  579. logger.Info("Loaded BlockCommit for catch-up", "height", prs.Height, "commit", commit)
  580. if ps.PickSendVote(commit) {
  581. logger.Debug("Picked Catchup commit to send", "height", prs.Height)
  582. continue OUTER_LOOP
  583. }
  584. }
  585. if sleeping == 0 {
  586. // We sent nothing. Sleep...
  587. sleeping = 1
  588. logger.Debug("No votes to send, sleeping", "rs.Height", rs.Height, "prs.Height", prs.Height,
  589. "localPV", rs.Votes.Prevotes(rs.Round).BitArray(), "peerPV", prs.Prevotes,
  590. "localPC", rs.Votes.Precommits(rs.Round).BitArray(), "peerPC", prs.Precommits)
  591. } else if sleeping == 2 {
  592. // Continued sleep...
  593. sleeping = 1
  594. }
  595. time.Sleep(conR.conS.config.PeerGossipSleep())
  596. continue OUTER_LOOP
  597. }
  598. }
  599. func (conR *ConsensusReactor) gossipVotesForHeight(logger log.Logger, rs *cstypes.RoundState, prs *cstypes.PeerRoundState, ps *PeerState) bool {
  600. // If there are lastCommits to send...
  601. if prs.Step == cstypes.RoundStepNewHeight {
  602. if ps.PickSendVote(rs.LastCommit) {
  603. logger.Debug("Picked rs.LastCommit to send")
  604. return true
  605. }
  606. }
  607. // If there are prevotes to send...
  608. if prs.Step <= cstypes.RoundStepPrevote && prs.Round != -1 && prs.Round <= rs.Round {
  609. if ps.PickSendVote(rs.Votes.Prevotes(prs.Round)) {
  610. logger.Debug("Picked rs.Prevotes(prs.Round) to send", "round", prs.Round)
  611. return true
  612. }
  613. }
  614. // If there are precommits to send...
  615. if prs.Step <= cstypes.RoundStepPrecommit && prs.Round != -1 && prs.Round <= rs.Round {
  616. if ps.PickSendVote(rs.Votes.Precommits(prs.Round)) {
  617. logger.Debug("Picked rs.Precommits(prs.Round) to send", "round", prs.Round)
  618. return true
  619. }
  620. }
  621. // If there are POLPrevotes to send...
  622. if prs.ProposalPOLRound != -1 {
  623. if polPrevotes := rs.Votes.Prevotes(prs.ProposalPOLRound); polPrevotes != nil {
  624. if ps.PickSendVote(polPrevotes) {
  625. logger.Debug("Picked rs.Prevotes(prs.ProposalPOLRound) to send",
  626. "round", prs.ProposalPOLRound)
  627. return true
  628. }
  629. }
  630. }
  631. return false
  632. }
  633. // NOTE: `queryMaj23Routine` has a simple crude design since it only comes
  634. // into play for liveness when there's a signature DDoS attack happening.
  635. func (conR *ConsensusReactor) queryMaj23Routine(peer p2p.Peer, ps *PeerState) {
  636. logger := conR.Logger.With("peer", peer)
  637. OUTER_LOOP:
  638. for {
  639. // Manage disconnects from self or peer.
  640. if !peer.IsRunning() || !conR.IsRunning() {
  641. logger.Info("Stopping queryMaj23Routine for peer")
  642. return
  643. }
  644. // Maybe send Height/Round/Prevotes
  645. {
  646. rs := conR.conS.GetRoundState()
  647. prs := ps.GetRoundState()
  648. if rs.Height == prs.Height {
  649. if maj23, ok := rs.Votes.Prevotes(prs.Round).TwoThirdsMajority(); ok {
  650. peer.TrySend(StateChannel, struct{ ConsensusMessage }{&VoteSetMaj23Message{
  651. Height: prs.Height,
  652. Round: prs.Round,
  653. Type: types.VoteTypePrevote,
  654. BlockID: maj23,
  655. }})
  656. time.Sleep(conR.conS.config.PeerQueryMaj23Sleep())
  657. }
  658. }
  659. }
  660. // Maybe send Height/Round/Precommits
  661. {
  662. rs := conR.conS.GetRoundState()
  663. prs := ps.GetRoundState()
  664. if rs.Height == prs.Height {
  665. if maj23, ok := rs.Votes.Precommits(prs.Round).TwoThirdsMajority(); ok {
  666. peer.TrySend(StateChannel, struct{ ConsensusMessage }{&VoteSetMaj23Message{
  667. Height: prs.Height,
  668. Round: prs.Round,
  669. Type: types.VoteTypePrecommit,
  670. BlockID: maj23,
  671. }})
  672. time.Sleep(conR.conS.config.PeerQueryMaj23Sleep())
  673. }
  674. }
  675. }
  676. // Maybe send Height/Round/ProposalPOL
  677. {
  678. rs := conR.conS.GetRoundState()
  679. prs := ps.GetRoundState()
  680. if rs.Height == prs.Height && prs.ProposalPOLRound >= 0 {
  681. if maj23, ok := rs.Votes.Prevotes(prs.ProposalPOLRound).TwoThirdsMajority(); ok {
  682. peer.TrySend(StateChannel, struct{ ConsensusMessage }{&VoteSetMaj23Message{
  683. Height: prs.Height,
  684. Round: prs.ProposalPOLRound,
  685. Type: types.VoteTypePrevote,
  686. BlockID: maj23,
  687. }})
  688. time.Sleep(conR.conS.config.PeerQueryMaj23Sleep())
  689. }
  690. }
  691. }
  692. // Little point sending LastCommitRound/LastCommit,
  693. // These are fleeting and non-blocking.
  694. // Maybe send Height/CatchupCommitRound/CatchupCommit.
  695. {
  696. prs := ps.GetRoundState()
  697. if prs.CatchupCommitRound != -1 && 0 < prs.Height && prs.Height <= conR.conS.blockStore.Height() {
  698. commit := conR.conS.LoadCommit(prs.Height)
  699. peer.TrySend(StateChannel, struct{ ConsensusMessage }{&VoteSetMaj23Message{
  700. Height: prs.Height,
  701. Round: commit.Round(),
  702. Type: types.VoteTypePrecommit,
  703. BlockID: commit.BlockID,
  704. }})
  705. time.Sleep(conR.conS.config.PeerQueryMaj23Sleep())
  706. }
  707. }
  708. time.Sleep(conR.conS.config.PeerQueryMaj23Sleep())
  709. continue OUTER_LOOP
  710. }
  711. }
  712. // String returns a string representation of the ConsensusReactor.
  713. // NOTE: For now, it is just a hard-coded string to avoid accessing unprotected shared variables.
  714. // TODO: improve!
  715. func (conR *ConsensusReactor) String() string {
  716. // better not to access shared variables
  717. return "ConsensusReactor" // conR.StringIndented("")
  718. }
  719. // StringIndented returns an indented string representation of the ConsensusReactor
  720. func (conR *ConsensusReactor) StringIndented(indent string) string {
  721. s := "ConsensusReactor{\n"
  722. s += indent + " " + conR.conS.StringIndented(indent+" ") + "\n"
  723. for _, peer := range conR.Switch.Peers().List() {
  724. ps := peer.Get(types.PeerStateKey).(*PeerState)
  725. s += indent + " " + ps.StringIndented(indent+" ") + "\n"
  726. }
  727. s += indent + "}"
  728. return s
  729. }
  730. //-----------------------------------------------------------------------------
  731. var (
  732. ErrPeerStateHeightRegression = errors.New("Error peer state height regression")
  733. ErrPeerStateInvalidStartTime = errors.New("Error peer state invalid startTime")
  734. )
  735. // PeerState contains the known state of a peer, including its connection
  736. // and threadsafe access to its PeerRoundState.
  737. type PeerState struct {
  738. Peer p2p.Peer
  739. logger log.Logger
  740. mtx sync.Mutex
  741. cstypes.PeerRoundState
  742. }
  743. // NewPeerState returns a new PeerState for the given Peer
  744. func NewPeerState(peer p2p.Peer) *PeerState {
  745. return &PeerState{
  746. Peer: peer,
  747. logger: log.NewNopLogger(),
  748. PeerRoundState: cstypes.PeerRoundState{
  749. Round: -1,
  750. ProposalPOLRound: -1,
  751. LastCommitRound: -1,
  752. CatchupCommitRound: -1,
  753. },
  754. }
  755. }
  756. func (ps *PeerState) SetLogger(logger log.Logger) *PeerState {
  757. ps.logger = logger
  758. return ps
  759. }
  760. // GetRoundState returns an atomic snapshot of the PeerRoundState.
  761. // There's no point in mutating it since it won't change PeerState.
  762. func (ps *PeerState) GetRoundState() *cstypes.PeerRoundState {
  763. ps.mtx.Lock()
  764. defer ps.mtx.Unlock()
  765. prs := ps.PeerRoundState // copy
  766. return &prs
  767. }
  768. // GetHeight returns an atomic snapshot of the PeerRoundState's height
  769. // used by the mempool to ensure peers are caught up before broadcasting new txs
  770. func (ps *PeerState) GetHeight() int64 {
  771. ps.mtx.Lock()
  772. defer ps.mtx.Unlock()
  773. return ps.PeerRoundState.Height
  774. }
  775. // SetHasProposal sets the given proposal as known for the peer.
  776. func (ps *PeerState) SetHasProposal(proposal *types.Proposal) {
  777. ps.mtx.Lock()
  778. defer ps.mtx.Unlock()
  779. if ps.Height != proposal.Height || ps.Round != proposal.Round {
  780. return
  781. }
  782. if ps.Proposal {
  783. return
  784. }
  785. ps.Proposal = true
  786. ps.ProposalBlockPartsHeader = proposal.BlockPartsHeader
  787. ps.ProposalBlockParts = cmn.NewBitArray(proposal.BlockPartsHeader.Total)
  788. ps.ProposalPOLRound = proposal.POLRound
  789. ps.ProposalPOL = nil // Nil until ProposalPOLMessage received.
  790. }
  791. // InitProposalBlockParts initializes the peer's proposal block parts header and bit array.
  792. func (ps *PeerState) InitProposalBlockParts(partsHeader types.PartSetHeader) {
  793. ps.mtx.Lock()
  794. defer ps.mtx.Unlock()
  795. if ps.ProposalBlockParts != nil {
  796. return
  797. }
  798. ps.ProposalBlockPartsHeader = partsHeader
  799. ps.ProposalBlockParts = cmn.NewBitArray(partsHeader.Total)
  800. }
  801. // SetHasProposalBlockPart sets the given block part index as known for the peer.
  802. func (ps *PeerState) SetHasProposalBlockPart(height int64, round int, index int) {
  803. ps.mtx.Lock()
  804. defer ps.mtx.Unlock()
  805. if ps.Height != height || ps.Round != round {
  806. return
  807. }
  808. ps.ProposalBlockParts.SetIndex(index, true)
  809. }
  810. // PickSendVote picks a vote and sends it to the peer.
  811. // Returns true if vote was sent.
  812. func (ps *PeerState) PickSendVote(votes types.VoteSetReader) bool {
  813. if vote, ok := ps.PickVoteToSend(votes); ok {
  814. msg := &VoteMessage{vote}
  815. return ps.Peer.Send(VoteChannel, struct{ ConsensusMessage }{msg})
  816. }
  817. return false
  818. }
  819. // PickVoteToSend picks a vote to send to the peer.
  820. // Returns true if a vote was picked.
  821. // NOTE: `votes` must be the correct Size() for the Height().
  822. func (ps *PeerState) PickVoteToSend(votes types.VoteSetReader) (vote *types.Vote, ok bool) {
  823. ps.mtx.Lock()
  824. defer ps.mtx.Unlock()
  825. if votes.Size() == 0 {
  826. return nil, false
  827. }
  828. height, round, type_, size := votes.Height(), votes.Round(), votes.Type(), votes.Size()
  829. // Lazily set data using 'votes'.
  830. if votes.IsCommit() {
  831. ps.ensureCatchupCommitRound(height, round, size)
  832. }
  833. ps.ensureVoteBitArrays(height, size)
  834. psVotes := ps.getVoteBitArray(height, round, type_)
  835. if psVotes == nil {
  836. return nil, false // Not something worth sending
  837. }
  838. if index, ok := votes.BitArray().Sub(psVotes).PickRandom(); ok {
  839. ps.setHasVote(height, round, type_, index)
  840. return votes.GetByIndex(index), true
  841. }
  842. return nil, false
  843. }
  844. func (ps *PeerState) getVoteBitArray(height int64, round int, type_ byte) *cmn.BitArray {
  845. if !types.IsVoteTypeValid(type_) {
  846. return nil
  847. }
  848. if ps.Height == height {
  849. if ps.Round == round {
  850. switch type_ {
  851. case types.VoteTypePrevote:
  852. return ps.Prevotes
  853. case types.VoteTypePrecommit:
  854. return ps.Precommits
  855. }
  856. }
  857. if ps.CatchupCommitRound == round {
  858. switch type_ {
  859. case types.VoteTypePrevote:
  860. return nil
  861. case types.VoteTypePrecommit:
  862. return ps.CatchupCommit
  863. }
  864. }
  865. if ps.ProposalPOLRound == round {
  866. switch type_ {
  867. case types.VoteTypePrevote:
  868. return ps.ProposalPOL
  869. case types.VoteTypePrecommit:
  870. return nil
  871. }
  872. }
  873. return nil
  874. }
  875. if ps.Height == height+1 {
  876. if ps.LastCommitRound == round {
  877. switch type_ {
  878. case types.VoteTypePrevote:
  879. return nil
  880. case types.VoteTypePrecommit:
  881. return ps.LastCommit
  882. }
  883. }
  884. return nil
  885. }
  886. return nil
  887. }
  888. // 'round': A round for which we have a +2/3 commit.
  889. func (ps *PeerState) ensureCatchupCommitRound(height int64, round int, numValidators int) {
  890. if ps.Height != height {
  891. return
  892. }
  893. /*
  894. NOTE: This is wrong, 'round' could change.
  895. e.g. if orig round is not the same as block LastCommit round.
  896. if ps.CatchupCommitRound != -1 && ps.CatchupCommitRound != round {
  897. cmn.PanicSanity(cmn.Fmt("Conflicting CatchupCommitRound. Height: %v, Orig: %v, New: %v", height, ps.CatchupCommitRound, round))
  898. }
  899. */
  900. if ps.CatchupCommitRound == round {
  901. return // Nothing to do!
  902. }
  903. ps.CatchupCommitRound = round
  904. if round == ps.Round {
  905. ps.CatchupCommit = ps.Precommits
  906. } else {
  907. ps.CatchupCommit = cmn.NewBitArray(numValidators)
  908. }
  909. }
  910. // EnsureVoteVitArrays ensures the bit-arrays have been allocated for tracking
  911. // what votes this peer has received.
  912. // NOTE: It's important to make sure that numValidators actually matches
  913. // what the node sees as the number of validators for height.
  914. func (ps *PeerState) EnsureVoteBitArrays(height int64, numValidators int) {
  915. ps.mtx.Lock()
  916. defer ps.mtx.Unlock()
  917. ps.ensureVoteBitArrays(height, numValidators)
  918. }
  919. func (ps *PeerState) ensureVoteBitArrays(height int64, numValidators int) {
  920. if ps.Height == height {
  921. if ps.Prevotes == nil {
  922. ps.Prevotes = cmn.NewBitArray(numValidators)
  923. }
  924. if ps.Precommits == nil {
  925. ps.Precommits = cmn.NewBitArray(numValidators)
  926. }
  927. if ps.CatchupCommit == nil {
  928. ps.CatchupCommit = cmn.NewBitArray(numValidators)
  929. }
  930. if ps.ProposalPOL == nil {
  931. ps.ProposalPOL = cmn.NewBitArray(numValidators)
  932. }
  933. } else if ps.Height == height+1 {
  934. if ps.LastCommit == nil {
  935. ps.LastCommit = cmn.NewBitArray(numValidators)
  936. }
  937. }
  938. }
  939. // SetHasVote sets the given vote as known by the peer
  940. func (ps *PeerState) SetHasVote(vote *types.Vote) {
  941. ps.mtx.Lock()
  942. defer ps.mtx.Unlock()
  943. ps.setHasVote(vote.Height, vote.Round, vote.Type, vote.ValidatorIndex)
  944. }
  945. func (ps *PeerState) setHasVote(height int64, round int, type_ byte, index int) {
  946. logger := ps.logger.With("peerH/R", cmn.Fmt("%d/%d", ps.Height, ps.Round), "H/R", cmn.Fmt("%d/%d", height, round))
  947. logger.Debug("setHasVote", "type", type_, "index", index)
  948. // NOTE: some may be nil BitArrays -> no side effects.
  949. psVotes := ps.getVoteBitArray(height, round, type_)
  950. if psVotes != nil {
  951. psVotes.SetIndex(index, true)
  952. }
  953. }
  954. // ApplyNewRoundStepMessage updates the peer state for the new round.
  955. func (ps *PeerState) ApplyNewRoundStepMessage(msg *NewRoundStepMessage) {
  956. ps.mtx.Lock()
  957. defer ps.mtx.Unlock()
  958. // Ignore duplicates or decreases
  959. if CompareHRS(msg.Height, msg.Round, msg.Step, ps.Height, ps.Round, ps.Step) <= 0 {
  960. return
  961. }
  962. // Just remember these values.
  963. psHeight := ps.Height
  964. psRound := ps.Round
  965. //psStep := ps.Step
  966. psCatchupCommitRound := ps.CatchupCommitRound
  967. psCatchupCommit := ps.CatchupCommit
  968. startTime := time.Now().Add(-1 * time.Duration(msg.SecondsSinceStartTime) * time.Second)
  969. ps.Height = msg.Height
  970. ps.Round = msg.Round
  971. ps.Step = msg.Step
  972. ps.StartTime = startTime
  973. if psHeight != msg.Height || psRound != msg.Round {
  974. ps.Proposal = false
  975. ps.ProposalBlockPartsHeader = types.PartSetHeader{}
  976. ps.ProposalBlockParts = nil
  977. ps.ProposalPOLRound = -1
  978. ps.ProposalPOL = nil
  979. // We'll update the BitArray capacity later.
  980. ps.Prevotes = nil
  981. ps.Precommits = nil
  982. }
  983. if psHeight == msg.Height && psRound != msg.Round && msg.Round == psCatchupCommitRound {
  984. // Peer caught up to CatchupCommitRound.
  985. // Preserve psCatchupCommit!
  986. // NOTE: We prefer to use prs.Precommits if
  987. // pr.Round matches pr.CatchupCommitRound.
  988. ps.Precommits = psCatchupCommit
  989. }
  990. if psHeight != msg.Height {
  991. // Shift Precommits to LastCommit.
  992. if psHeight+1 == msg.Height && psRound == msg.LastCommitRound {
  993. ps.LastCommitRound = msg.LastCommitRound
  994. ps.LastCommit = ps.Precommits
  995. } else {
  996. ps.LastCommitRound = msg.LastCommitRound
  997. ps.LastCommit = nil
  998. }
  999. // We'll update the BitArray capacity later.
  1000. ps.CatchupCommitRound = -1
  1001. ps.CatchupCommit = nil
  1002. }
  1003. }
  1004. // ApplyCommitStepMessage updates the peer state for the new commit.
  1005. func (ps *PeerState) ApplyCommitStepMessage(msg *CommitStepMessage) {
  1006. ps.mtx.Lock()
  1007. defer ps.mtx.Unlock()
  1008. if ps.Height != msg.Height {
  1009. return
  1010. }
  1011. ps.ProposalBlockPartsHeader = msg.BlockPartsHeader
  1012. ps.ProposalBlockParts = msg.BlockParts
  1013. }
  1014. // ApplyProposalPOLMessage updates the peer state for the new proposal POL.
  1015. func (ps *PeerState) ApplyProposalPOLMessage(msg *ProposalPOLMessage) {
  1016. ps.mtx.Lock()
  1017. defer ps.mtx.Unlock()
  1018. if ps.Height != msg.Height {
  1019. return
  1020. }
  1021. if ps.ProposalPOLRound != msg.ProposalPOLRound {
  1022. return
  1023. }
  1024. // TODO: Merge onto existing ps.ProposalPOL?
  1025. // We might have sent some prevotes in the meantime.
  1026. ps.ProposalPOL = msg.ProposalPOL
  1027. }
  1028. // ApplyHasVoteMessage updates the peer state for the new vote.
  1029. func (ps *PeerState) ApplyHasVoteMessage(msg *HasVoteMessage) {
  1030. ps.mtx.Lock()
  1031. defer ps.mtx.Unlock()
  1032. if ps.Height != msg.Height {
  1033. return
  1034. }
  1035. ps.setHasVote(msg.Height, msg.Round, msg.Type, msg.Index)
  1036. }
  1037. // ApplyVoteSetBitsMessage updates the peer state for the bit-array of votes
  1038. // it claims to have for the corresponding BlockID.
  1039. // `ourVotes` is a BitArray of votes we have for msg.BlockID
  1040. // NOTE: if ourVotes is nil (e.g. msg.Height < rs.Height),
  1041. // we conservatively overwrite ps's votes w/ msg.Votes.
  1042. func (ps *PeerState) ApplyVoteSetBitsMessage(msg *VoteSetBitsMessage, ourVotes *cmn.BitArray) {
  1043. ps.mtx.Lock()
  1044. defer ps.mtx.Unlock()
  1045. votes := ps.getVoteBitArray(msg.Height, msg.Round, msg.Type)
  1046. if votes != nil {
  1047. if ourVotes == nil {
  1048. votes.Update(msg.Votes)
  1049. } else {
  1050. otherVotes := votes.Sub(ourVotes)
  1051. hasVotes := otherVotes.Or(msg.Votes)
  1052. votes.Update(hasVotes)
  1053. }
  1054. }
  1055. }
  1056. // String returns a string representation of the PeerState
  1057. func (ps *PeerState) String() string {
  1058. return ps.StringIndented("")
  1059. }
  1060. // StringIndented returns a string representation of the PeerState
  1061. func (ps *PeerState) StringIndented(indent string) string {
  1062. return fmt.Sprintf(`PeerState{
  1063. %s Key %v
  1064. %s PRS %v
  1065. %s}`,
  1066. indent, ps.Peer.Key(),
  1067. indent, ps.PeerRoundState.StringIndented(indent+" "),
  1068. indent)
  1069. }
  1070. //-----------------------------------------------------------------------------
  1071. // Messages
  1072. const (
  1073. msgTypeNewRoundStep = byte(0x01)
  1074. msgTypeCommitStep = byte(0x02)
  1075. msgTypeProposal = byte(0x11)
  1076. msgTypeProposalPOL = byte(0x12)
  1077. msgTypeBlockPart = byte(0x13) // both block & POL
  1078. msgTypeVote = byte(0x14)
  1079. msgTypeHasVote = byte(0x15)
  1080. msgTypeVoteSetMaj23 = byte(0x16)
  1081. msgTypeVoteSetBits = byte(0x17)
  1082. msgTypeProposalHeartbeat = byte(0x20)
  1083. )
  1084. // ConsensusMessage is a message that can be sent and received on the ConsensusReactor
  1085. type ConsensusMessage interface{}
  1086. var _ = wire.RegisterInterface(
  1087. struct{ ConsensusMessage }{},
  1088. wire.ConcreteType{&NewRoundStepMessage{}, msgTypeNewRoundStep},
  1089. wire.ConcreteType{&CommitStepMessage{}, msgTypeCommitStep},
  1090. wire.ConcreteType{&ProposalMessage{}, msgTypeProposal},
  1091. wire.ConcreteType{&ProposalPOLMessage{}, msgTypeProposalPOL},
  1092. wire.ConcreteType{&BlockPartMessage{}, msgTypeBlockPart},
  1093. wire.ConcreteType{&VoteMessage{}, msgTypeVote},
  1094. wire.ConcreteType{&HasVoteMessage{}, msgTypeHasVote},
  1095. wire.ConcreteType{&VoteSetMaj23Message{}, msgTypeVoteSetMaj23},
  1096. wire.ConcreteType{&VoteSetBitsMessage{}, msgTypeVoteSetBits},
  1097. wire.ConcreteType{&ProposalHeartbeatMessage{}, msgTypeProposalHeartbeat},
  1098. )
  1099. // DecodeMessage decodes the given bytes into a ConsensusMessage.
  1100. // TODO: check for unnecessary extra bytes at the end.
  1101. func DecodeMessage(bz []byte) (msgType byte, msg ConsensusMessage, err error) {
  1102. msgType = bz[0]
  1103. n := new(int)
  1104. r := bytes.NewReader(bz)
  1105. msgI := wire.ReadBinary(struct{ ConsensusMessage }{}, r, maxConsensusMessageSize, n, &err)
  1106. msg = msgI.(struct{ ConsensusMessage }).ConsensusMessage
  1107. return
  1108. }
  1109. //-------------------------------------
  1110. // NewRoundStepMessage is sent for every step taken in the ConsensusState.
  1111. // For every height/round/step transition
  1112. type NewRoundStepMessage struct {
  1113. Height int64
  1114. Round int
  1115. Step cstypes.RoundStepType
  1116. SecondsSinceStartTime int
  1117. LastCommitRound int
  1118. }
  1119. // String returns a string representation.
  1120. func (m *NewRoundStepMessage) String() string {
  1121. return fmt.Sprintf("[NewRoundStep H:%v R:%v S:%v LCR:%v]",
  1122. m.Height, m.Round, m.Step, m.LastCommitRound)
  1123. }
  1124. //-------------------------------------
  1125. // CommitStepMessage is sent when a block is committed.
  1126. type CommitStepMessage struct {
  1127. Height int64
  1128. BlockPartsHeader types.PartSetHeader
  1129. BlockParts *cmn.BitArray
  1130. }
  1131. // String returns a string representation.
  1132. func (m *CommitStepMessage) String() string {
  1133. return fmt.Sprintf("[CommitStep H:%v BP:%v BA:%v]", m.Height, m.BlockPartsHeader, m.BlockParts)
  1134. }
  1135. //-------------------------------------
  1136. // ProposalMessage is sent when a new block is proposed.
  1137. type ProposalMessage struct {
  1138. Proposal *types.Proposal
  1139. }
  1140. // String returns a string representation.
  1141. func (m *ProposalMessage) String() string {
  1142. return fmt.Sprintf("[Proposal %v]", m.Proposal)
  1143. }
  1144. //-------------------------------------
  1145. // ProposalPOLMessage is sent when a previous proposal is re-proposed.
  1146. type ProposalPOLMessage struct {
  1147. Height int64
  1148. ProposalPOLRound int
  1149. ProposalPOL *cmn.BitArray
  1150. }
  1151. // String returns a string representation.
  1152. func (m *ProposalPOLMessage) String() string {
  1153. return fmt.Sprintf("[ProposalPOL H:%v POLR:%v POL:%v]", m.Height, m.ProposalPOLRound, m.ProposalPOL)
  1154. }
  1155. //-------------------------------------
  1156. // BlockPartMessage is sent when gossipping a piece of the proposed block.
  1157. type BlockPartMessage struct {
  1158. Height int64
  1159. Round int
  1160. Part *types.Part
  1161. }
  1162. // String returns a string representation.
  1163. func (m *BlockPartMessage) String() string {
  1164. return fmt.Sprintf("[BlockPart H:%v R:%v P:%v]", m.Height, m.Round, m.Part)
  1165. }
  1166. //-------------------------------------
  1167. // VoteMessage is sent when voting for a proposal (or lack thereof).
  1168. type VoteMessage struct {
  1169. Vote *types.Vote
  1170. }
  1171. // String returns a string representation.
  1172. func (m *VoteMessage) String() string {
  1173. return fmt.Sprintf("[Vote %v]", m.Vote)
  1174. }
  1175. //-------------------------------------
  1176. // HasVoteMessage is sent to indicate that a particular vote has been received.
  1177. type HasVoteMessage struct {
  1178. Height int64
  1179. Round int
  1180. Type byte
  1181. Index int
  1182. }
  1183. // String returns a string representation.
  1184. func (m *HasVoteMessage) String() string {
  1185. return fmt.Sprintf("[HasVote VI:%v V:{%v/%02d/%v} VI:%v]", m.Index, m.Height, m.Round, m.Type, m.Index)
  1186. }
  1187. //-------------------------------------
  1188. // VoteSetMaj23Message is sent to indicate that a given BlockID has seen +2/3 votes.
  1189. type VoteSetMaj23Message struct {
  1190. Height int64
  1191. Round int
  1192. Type byte
  1193. BlockID types.BlockID
  1194. }
  1195. // String returns a string representation.
  1196. func (m *VoteSetMaj23Message) String() string {
  1197. return fmt.Sprintf("[VSM23 %v/%02d/%v %v]", m.Height, m.Round, m.Type, m.BlockID)
  1198. }
  1199. //-------------------------------------
  1200. // VoteSetBitsMessage is sent to communicate the bit-array of votes seen for the BlockID.
  1201. type VoteSetBitsMessage struct {
  1202. Height int64
  1203. Round int
  1204. Type byte
  1205. BlockID types.BlockID
  1206. Votes *cmn.BitArray
  1207. }
  1208. // String returns a string representation.
  1209. func (m *VoteSetBitsMessage) String() string {
  1210. return fmt.Sprintf("[VSB %v/%02d/%v %v %v]", m.Height, m.Round, m.Type, m.BlockID, m.Votes)
  1211. }
  1212. //-------------------------------------
  1213. // ProposalHeartbeatMessage is sent to signal that a node is alive and waiting for transactions for a proposal.
  1214. type ProposalHeartbeatMessage struct {
  1215. Heartbeat *types.Heartbeat
  1216. }
  1217. // String returns a string representation.
  1218. func (m *ProposalHeartbeatMessage) String() string {
  1219. return fmt.Sprintf("[HEARTBEAT %v]", m.Heartbeat)
  1220. }