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.

1393 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
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
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
10 years ago
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
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
8 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
8 years ago
8 years ago
10 years ago
7 years ago
10 years ago
7 years ago
8 years ago
10 years ago
10 years ago
7 years ago
7 years ago
10 years ago
10 years ago
8 years ago
7 years ago
8 years ago
8 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
8 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
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
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
7 years ago
7 years ago
7 years ago
8 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
7 years ago
8 years ago
10 years ago
8 years ago
10 years ago
10 years ago
8 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
7 years ago
8 years ago
8 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
10 years ago
10 years ago
10 years ago
10 years ago
10 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. if ps.PickSendVote(commit) {
  580. logger.Debug("Picked Catchup commit to send", "height", prs.Height)
  581. continue OUTER_LOOP
  582. }
  583. }
  584. if sleeping == 0 {
  585. // We sent nothing. Sleep...
  586. sleeping = 1
  587. logger.Debug("No votes to send, sleeping", "rs.Height", rs.Height, "prs.Height", prs.Height,
  588. "localPV", rs.Votes.Prevotes(rs.Round).BitArray(), "peerPV", prs.Prevotes,
  589. "localPC", rs.Votes.Precommits(rs.Round).BitArray(), "peerPC", prs.Precommits)
  590. } else if sleeping == 2 {
  591. // Continued sleep...
  592. sleeping = 1
  593. }
  594. time.Sleep(conR.conS.config.PeerGossipSleep())
  595. continue OUTER_LOOP
  596. }
  597. }
  598. func (conR *ConsensusReactor) gossipVotesForHeight(logger log.Logger, rs *cstypes.RoundState, prs *cstypes.PeerRoundState, ps *PeerState) bool {
  599. // If there are lastCommits to send...
  600. if prs.Step == cstypes.RoundStepNewHeight {
  601. if ps.PickSendVote(rs.LastCommit) {
  602. logger.Debug("Picked rs.LastCommit to send")
  603. return true
  604. }
  605. }
  606. // If there are prevotes to send...
  607. if prs.Step <= cstypes.RoundStepPrevote && prs.Round != -1 && prs.Round <= rs.Round {
  608. if ps.PickSendVote(rs.Votes.Prevotes(prs.Round)) {
  609. logger.Debug("Picked rs.Prevotes(prs.Round) to send", "round", prs.Round)
  610. return true
  611. }
  612. }
  613. // If there are precommits to send...
  614. if prs.Step <= cstypes.RoundStepPrecommit && prs.Round != -1 && prs.Round <= rs.Round {
  615. if ps.PickSendVote(rs.Votes.Precommits(prs.Round)) {
  616. logger.Debug("Picked rs.Precommits(prs.Round) to send", "round", prs.Round)
  617. return true
  618. }
  619. }
  620. // If there are POLPrevotes to send...
  621. if prs.ProposalPOLRound != -1 {
  622. if polPrevotes := rs.Votes.Prevotes(prs.ProposalPOLRound); polPrevotes != nil {
  623. if ps.PickSendVote(polPrevotes) {
  624. logger.Debug("Picked rs.Prevotes(prs.ProposalPOLRound) to send",
  625. "round", prs.ProposalPOLRound)
  626. return true
  627. }
  628. }
  629. }
  630. return false
  631. }
  632. // NOTE: `queryMaj23Routine` has a simple crude design since it only comes
  633. // into play for liveness when there's a signature DDoS attack happening.
  634. func (conR *ConsensusReactor) queryMaj23Routine(peer p2p.Peer, ps *PeerState) {
  635. logger := conR.Logger.With("peer", peer)
  636. OUTER_LOOP:
  637. for {
  638. // Manage disconnects from self or peer.
  639. if !peer.IsRunning() || !conR.IsRunning() {
  640. logger.Info("Stopping queryMaj23Routine for peer")
  641. return
  642. }
  643. // Maybe send Height/Round/Prevotes
  644. {
  645. rs := conR.conS.GetRoundState()
  646. prs := ps.GetRoundState()
  647. if rs.Height == prs.Height {
  648. if maj23, ok := rs.Votes.Prevotes(prs.Round).TwoThirdsMajority(); ok {
  649. peer.TrySend(StateChannel, struct{ ConsensusMessage }{&VoteSetMaj23Message{
  650. Height: prs.Height,
  651. Round: prs.Round,
  652. Type: types.VoteTypePrevote,
  653. BlockID: maj23,
  654. }})
  655. time.Sleep(conR.conS.config.PeerQueryMaj23Sleep())
  656. }
  657. }
  658. }
  659. // Maybe send Height/Round/Precommits
  660. {
  661. rs := conR.conS.GetRoundState()
  662. prs := ps.GetRoundState()
  663. if rs.Height == prs.Height {
  664. if maj23, ok := rs.Votes.Precommits(prs.Round).TwoThirdsMajority(); ok {
  665. peer.TrySend(StateChannel, struct{ ConsensusMessage }{&VoteSetMaj23Message{
  666. Height: prs.Height,
  667. Round: prs.Round,
  668. Type: types.VoteTypePrecommit,
  669. BlockID: maj23,
  670. }})
  671. time.Sleep(conR.conS.config.PeerQueryMaj23Sleep())
  672. }
  673. }
  674. }
  675. // Maybe send Height/Round/ProposalPOL
  676. {
  677. rs := conR.conS.GetRoundState()
  678. prs := ps.GetRoundState()
  679. if rs.Height == prs.Height && prs.ProposalPOLRound >= 0 {
  680. if maj23, ok := rs.Votes.Prevotes(prs.ProposalPOLRound).TwoThirdsMajority(); ok {
  681. peer.TrySend(StateChannel, struct{ ConsensusMessage }{&VoteSetMaj23Message{
  682. Height: prs.Height,
  683. Round: prs.ProposalPOLRound,
  684. Type: types.VoteTypePrevote,
  685. BlockID: maj23,
  686. }})
  687. time.Sleep(conR.conS.config.PeerQueryMaj23Sleep())
  688. }
  689. }
  690. }
  691. // Little point sending LastCommitRound/LastCommit,
  692. // These are fleeting and non-blocking.
  693. // Maybe send Height/CatchupCommitRound/CatchupCommit.
  694. {
  695. prs := ps.GetRoundState()
  696. if prs.CatchupCommitRound != -1 && 0 < prs.Height && prs.Height <= conR.conS.blockStore.Height() {
  697. commit := conR.conS.LoadCommit(prs.Height)
  698. peer.TrySend(StateChannel, struct{ ConsensusMessage }{&VoteSetMaj23Message{
  699. Height: prs.Height,
  700. Round: commit.Round(),
  701. Type: types.VoteTypePrecommit,
  702. BlockID: commit.BlockID,
  703. }})
  704. time.Sleep(conR.conS.config.PeerQueryMaj23Sleep())
  705. }
  706. }
  707. time.Sleep(conR.conS.config.PeerQueryMaj23Sleep())
  708. continue OUTER_LOOP
  709. }
  710. }
  711. // String returns a string representation of the ConsensusReactor.
  712. // NOTE: For now, it is just a hard-coded string to avoid accessing unprotected shared variables.
  713. // TODO: improve!
  714. func (conR *ConsensusReactor) String() string {
  715. // better not to access shared variables
  716. return "ConsensusReactor" // conR.StringIndented("")
  717. }
  718. // StringIndented returns an indented string representation of the ConsensusReactor
  719. func (conR *ConsensusReactor) StringIndented(indent string) string {
  720. s := "ConsensusReactor{\n"
  721. s += indent + " " + conR.conS.StringIndented(indent+" ") + "\n"
  722. for _, peer := range conR.Switch.Peers().List() {
  723. ps := peer.Get(types.PeerStateKey).(*PeerState)
  724. s += indent + " " + ps.StringIndented(indent+" ") + "\n"
  725. }
  726. s += indent + "}"
  727. return s
  728. }
  729. //-----------------------------------------------------------------------------
  730. var (
  731. ErrPeerStateHeightRegression = errors.New("Error peer state height regression")
  732. ErrPeerStateInvalidStartTime = errors.New("Error peer state invalid startTime")
  733. )
  734. // PeerState contains the known state of a peer, including its connection
  735. // and threadsafe access to its PeerRoundState.
  736. type PeerState struct {
  737. Peer p2p.Peer
  738. logger log.Logger
  739. mtx sync.Mutex
  740. cstypes.PeerRoundState
  741. }
  742. // NewPeerState returns a new PeerState for the given Peer
  743. func NewPeerState(peer p2p.Peer) *PeerState {
  744. return &PeerState{
  745. Peer: peer,
  746. logger: log.NewNopLogger(),
  747. PeerRoundState: cstypes.PeerRoundState{
  748. Round: -1,
  749. ProposalPOLRound: -1,
  750. LastCommitRound: -1,
  751. CatchupCommitRound: -1,
  752. },
  753. }
  754. }
  755. func (ps *PeerState) SetLogger(logger log.Logger) *PeerState {
  756. ps.logger = logger
  757. return ps
  758. }
  759. // GetRoundState returns an atomic snapshot of the PeerRoundState.
  760. // There's no point in mutating it since it won't change PeerState.
  761. func (ps *PeerState) GetRoundState() *cstypes.PeerRoundState {
  762. ps.mtx.Lock()
  763. defer ps.mtx.Unlock()
  764. prs := ps.PeerRoundState // copy
  765. return &prs
  766. }
  767. // GetHeight returns an atomic snapshot of the PeerRoundState's height
  768. // used by the mempool to ensure peers are caught up before broadcasting new txs
  769. func (ps *PeerState) GetHeight() int64 {
  770. ps.mtx.Lock()
  771. defer ps.mtx.Unlock()
  772. return ps.PeerRoundState.Height
  773. }
  774. // SetHasProposal sets the given proposal as known for the peer.
  775. func (ps *PeerState) SetHasProposal(proposal *types.Proposal) {
  776. ps.mtx.Lock()
  777. defer ps.mtx.Unlock()
  778. if ps.Height != proposal.Height || ps.Round != proposal.Round {
  779. return
  780. }
  781. if ps.Proposal {
  782. return
  783. }
  784. ps.Proposal = true
  785. ps.ProposalBlockPartsHeader = proposal.BlockPartsHeader
  786. ps.ProposalBlockParts = cmn.NewBitArray(proposal.BlockPartsHeader.Total)
  787. ps.ProposalPOLRound = proposal.POLRound
  788. ps.ProposalPOL = nil // Nil until ProposalPOLMessage received.
  789. }
  790. // InitProposalBlockParts initializes the peer's proposal block parts header and bit array.
  791. func (ps *PeerState) InitProposalBlockParts(partsHeader types.PartSetHeader) {
  792. ps.mtx.Lock()
  793. defer ps.mtx.Unlock()
  794. if ps.ProposalBlockParts != nil {
  795. return
  796. }
  797. ps.ProposalBlockPartsHeader = partsHeader
  798. ps.ProposalBlockParts = cmn.NewBitArray(partsHeader.Total)
  799. }
  800. // SetHasProposalBlockPart sets the given block part index as known for the peer.
  801. func (ps *PeerState) SetHasProposalBlockPart(height int64, round int, index int) {
  802. ps.mtx.Lock()
  803. defer ps.mtx.Unlock()
  804. if ps.Height != height || ps.Round != round {
  805. return
  806. }
  807. ps.ProposalBlockParts.SetIndex(index, true)
  808. }
  809. // PickSendVote picks a vote and sends it to the peer.
  810. // Returns true if vote was sent.
  811. func (ps *PeerState) PickSendVote(votes types.VoteSetReader) bool {
  812. if vote, ok := ps.PickVoteToSend(votes); ok {
  813. msg := &VoteMessage{vote}
  814. ps.logger.Debug("Sending vote message", "ps", ps, "vote", 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. ps.mtx.Lock()
  1063. defer ps.mtx.Unlock()
  1064. return fmt.Sprintf(`PeerState{
  1065. %s Key %v
  1066. %s PRS %v
  1067. %s}`,
  1068. indent, ps.Peer.Key(),
  1069. indent, ps.PeerRoundState.StringIndented(indent+" "),
  1070. indent)
  1071. }
  1072. //-----------------------------------------------------------------------------
  1073. // Messages
  1074. const (
  1075. msgTypeNewRoundStep = byte(0x01)
  1076. msgTypeCommitStep = byte(0x02)
  1077. msgTypeProposal = byte(0x11)
  1078. msgTypeProposalPOL = byte(0x12)
  1079. msgTypeBlockPart = byte(0x13) // both block & POL
  1080. msgTypeVote = byte(0x14)
  1081. msgTypeHasVote = byte(0x15)
  1082. msgTypeVoteSetMaj23 = byte(0x16)
  1083. msgTypeVoteSetBits = byte(0x17)
  1084. msgTypeProposalHeartbeat = byte(0x20)
  1085. )
  1086. // ConsensusMessage is a message that can be sent and received on the ConsensusReactor
  1087. type ConsensusMessage interface{}
  1088. var _ = wire.RegisterInterface(
  1089. struct{ ConsensusMessage }{},
  1090. wire.ConcreteType{&NewRoundStepMessage{}, msgTypeNewRoundStep},
  1091. wire.ConcreteType{&CommitStepMessage{}, msgTypeCommitStep},
  1092. wire.ConcreteType{&ProposalMessage{}, msgTypeProposal},
  1093. wire.ConcreteType{&ProposalPOLMessage{}, msgTypeProposalPOL},
  1094. wire.ConcreteType{&BlockPartMessage{}, msgTypeBlockPart},
  1095. wire.ConcreteType{&VoteMessage{}, msgTypeVote},
  1096. wire.ConcreteType{&HasVoteMessage{}, msgTypeHasVote},
  1097. wire.ConcreteType{&VoteSetMaj23Message{}, msgTypeVoteSetMaj23},
  1098. wire.ConcreteType{&VoteSetBitsMessage{}, msgTypeVoteSetBits},
  1099. wire.ConcreteType{&ProposalHeartbeatMessage{}, msgTypeProposalHeartbeat},
  1100. )
  1101. // DecodeMessage decodes the given bytes into a ConsensusMessage.
  1102. // TODO: check for unnecessary extra bytes at the end.
  1103. func DecodeMessage(bz []byte) (msgType byte, msg ConsensusMessage, err error) {
  1104. msgType = bz[0]
  1105. n := new(int)
  1106. r := bytes.NewReader(bz)
  1107. msgI := wire.ReadBinary(struct{ ConsensusMessage }{}, r, maxConsensusMessageSize, n, &err)
  1108. msg = msgI.(struct{ ConsensusMessage }).ConsensusMessage
  1109. return
  1110. }
  1111. //-------------------------------------
  1112. // NewRoundStepMessage is sent for every step taken in the ConsensusState.
  1113. // For every height/round/step transition
  1114. type NewRoundStepMessage struct {
  1115. Height int64
  1116. Round int
  1117. Step cstypes.RoundStepType
  1118. SecondsSinceStartTime int
  1119. LastCommitRound int
  1120. }
  1121. // String returns a string representation.
  1122. func (m *NewRoundStepMessage) String() string {
  1123. return fmt.Sprintf("[NewRoundStep H:%v R:%v S:%v LCR:%v]",
  1124. m.Height, m.Round, m.Step, m.LastCommitRound)
  1125. }
  1126. //-------------------------------------
  1127. // CommitStepMessage is sent when a block is committed.
  1128. type CommitStepMessage struct {
  1129. Height int64
  1130. BlockPartsHeader types.PartSetHeader
  1131. BlockParts *cmn.BitArray
  1132. }
  1133. // String returns a string representation.
  1134. func (m *CommitStepMessage) String() string {
  1135. return fmt.Sprintf("[CommitStep H:%v BP:%v BA:%v]", m.Height, m.BlockPartsHeader, m.BlockParts)
  1136. }
  1137. //-------------------------------------
  1138. // ProposalMessage is sent when a new block is proposed.
  1139. type ProposalMessage struct {
  1140. Proposal *types.Proposal
  1141. }
  1142. // String returns a string representation.
  1143. func (m *ProposalMessage) String() string {
  1144. return fmt.Sprintf("[Proposal %v]", m.Proposal)
  1145. }
  1146. //-------------------------------------
  1147. // ProposalPOLMessage is sent when a previous proposal is re-proposed.
  1148. type ProposalPOLMessage struct {
  1149. Height int64
  1150. ProposalPOLRound int
  1151. ProposalPOL *cmn.BitArray
  1152. }
  1153. // String returns a string representation.
  1154. func (m *ProposalPOLMessage) String() string {
  1155. return fmt.Sprintf("[ProposalPOL H:%v POLR:%v POL:%v]", m.Height, m.ProposalPOLRound, m.ProposalPOL)
  1156. }
  1157. //-------------------------------------
  1158. // BlockPartMessage is sent when gossipping a piece of the proposed block.
  1159. type BlockPartMessage struct {
  1160. Height int64
  1161. Round int
  1162. Part *types.Part
  1163. }
  1164. // String returns a string representation.
  1165. func (m *BlockPartMessage) String() string {
  1166. return fmt.Sprintf("[BlockPart H:%v R:%v P:%v]", m.Height, m.Round, m.Part)
  1167. }
  1168. //-------------------------------------
  1169. // VoteMessage is sent when voting for a proposal (or lack thereof).
  1170. type VoteMessage struct {
  1171. Vote *types.Vote
  1172. }
  1173. // String returns a string representation.
  1174. func (m *VoteMessage) String() string {
  1175. return fmt.Sprintf("[Vote %v]", m.Vote)
  1176. }
  1177. //-------------------------------------
  1178. // HasVoteMessage is sent to indicate that a particular vote has been received.
  1179. type HasVoteMessage struct {
  1180. Height int64
  1181. Round int
  1182. Type byte
  1183. Index int
  1184. }
  1185. // String returns a string representation.
  1186. func (m *HasVoteMessage) String() string {
  1187. return fmt.Sprintf("[HasVote VI:%v V:{%v/%02d/%v}]", m.Index, m.Height, m.Round, m.Type)
  1188. }
  1189. //-------------------------------------
  1190. // VoteSetMaj23Message is sent to indicate that a given BlockID has seen +2/3 votes.
  1191. type VoteSetMaj23Message struct {
  1192. Height int64
  1193. Round int
  1194. Type byte
  1195. BlockID types.BlockID
  1196. }
  1197. // String returns a string representation.
  1198. func (m *VoteSetMaj23Message) String() string {
  1199. return fmt.Sprintf("[VSM23 %v/%02d/%v %v]", m.Height, m.Round, m.Type, m.BlockID)
  1200. }
  1201. //-------------------------------------
  1202. // VoteSetBitsMessage is sent to communicate the bit-array of votes seen for the BlockID.
  1203. type VoteSetBitsMessage struct {
  1204. Height int64
  1205. Round int
  1206. Type byte
  1207. BlockID types.BlockID
  1208. Votes *cmn.BitArray
  1209. }
  1210. // String returns a string representation.
  1211. func (m *VoteSetBitsMessage) String() string {
  1212. return fmt.Sprintf("[VSB %v/%02d/%v %v %v]", m.Height, m.Round, m.Type, m.BlockID, m.Votes)
  1213. }
  1214. //-------------------------------------
  1215. // ProposalHeartbeatMessage is sent to signal that a node is alive and waiting for transactions for a proposal.
  1216. type ProposalHeartbeatMessage struct {
  1217. Heartbeat *types.Heartbeat
  1218. }
  1219. // String returns a string representation.
  1220. func (m *ProposalHeartbeatMessage) String() string {
  1221. return fmt.Sprintf("[HEARTBEAT %v]", m.Heartbeat)
  1222. }