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.

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