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.

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