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.

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