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.

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