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.

1460 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. } else {
  543. //logger.Info("No parts to send in catch-up, sleeping")
  544. time.Sleep(conR.conS.config.PeerGossipSleep())
  545. return
  546. }
  547. }
  548. func (conR *ConsensusReactor) gossipVotesRoutine(peer p2p.Peer, ps *PeerState) {
  549. logger := conR.Logger.With("peer", peer)
  550. // Simple hack to throttle logs upon sleep.
  551. var sleeping = 0
  552. OUTER_LOOP:
  553. for {
  554. // Manage disconnects from self or peer.
  555. if !peer.IsRunning() || !conR.IsRunning() {
  556. logger.Info("Stopping gossipVotesRoutine for peer")
  557. return
  558. }
  559. rs := conR.conS.GetRoundState()
  560. prs := ps.GetRoundState()
  561. switch sleeping {
  562. case 1: // First sleep
  563. sleeping = 2
  564. case 2: // No more sleep
  565. sleeping = 0
  566. }
  567. //logger.Debug("gossipVotesRoutine", "rsHeight", rs.Height, "rsRound", rs.Round,
  568. // "prsHeight", prs.Height, "prsRound", prs.Round, "prsStep", prs.Step)
  569. // If height matches, then send LastCommit, Prevotes, Precommits.
  570. if rs.Height == prs.Height {
  571. heightLogger := logger.With("height", prs.Height)
  572. if conR.gossipVotesForHeight(heightLogger, rs, prs, ps) {
  573. continue OUTER_LOOP
  574. }
  575. }
  576. // Special catchup logic.
  577. // If peer is lagging by height 1, send LastCommit.
  578. if prs.Height != 0 && rs.Height == prs.Height+1 {
  579. if ps.PickSendVote(rs.LastCommit) {
  580. logger.Debug("Picked rs.LastCommit to send", "height", prs.Height)
  581. continue OUTER_LOOP
  582. }
  583. }
  584. // Catchup logic
  585. // If peer is lagging by more than 1, send Commit.
  586. if prs.Height != 0 && rs.Height >= prs.Height+2 {
  587. // Load the block commit for prs.Height,
  588. // which contains precommit signatures for prs.Height.
  589. commit := conR.conS.blockStore.LoadBlockCommit(prs.Height)
  590. if ps.PickSendVote(commit) {
  591. logger.Debug("Picked Catchup commit to send", "height", prs.Height)
  592. continue OUTER_LOOP
  593. }
  594. }
  595. if sleeping == 0 {
  596. // We sent nothing. Sleep...
  597. sleeping = 1
  598. logger.Debug("No votes to send, sleeping", "rs.Height", rs.Height, "prs.Height", prs.Height,
  599. "localPV", rs.Votes.Prevotes(rs.Round).BitArray(), "peerPV", prs.Prevotes,
  600. "localPC", rs.Votes.Precommits(rs.Round).BitArray(), "peerPC", prs.Precommits)
  601. } else if sleeping == 2 {
  602. // Continued sleep...
  603. sleeping = 1
  604. }
  605. time.Sleep(conR.conS.config.PeerGossipSleep())
  606. continue OUTER_LOOP
  607. }
  608. }
  609. func (conR *ConsensusReactor) gossipVotesForHeight(logger log.Logger, rs *cstypes.RoundState, prs *cstypes.PeerRoundState, ps *PeerState) bool {
  610. // If there are lastCommits to send...
  611. if prs.Step == cstypes.RoundStepNewHeight {
  612. if ps.PickSendVote(rs.LastCommit) {
  613. logger.Debug("Picked rs.LastCommit to send")
  614. return true
  615. }
  616. }
  617. // If there are prevotes to send...
  618. if prs.Step <= cstypes.RoundStepPrevote && prs.Round != -1 && prs.Round <= rs.Round {
  619. if ps.PickSendVote(rs.Votes.Prevotes(prs.Round)) {
  620. logger.Debug("Picked rs.Prevotes(prs.Round) to send", "round", prs.Round)
  621. return true
  622. }
  623. }
  624. // If there are precommits to send...
  625. if prs.Step <= cstypes.RoundStepPrecommit && prs.Round != -1 && prs.Round <= rs.Round {
  626. if ps.PickSendVote(rs.Votes.Precommits(prs.Round)) {
  627. logger.Debug("Picked rs.Precommits(prs.Round) to send", "round", prs.Round)
  628. return true
  629. }
  630. }
  631. // If there are POLPrevotes to send...
  632. if prs.ProposalPOLRound != -1 {
  633. if polPrevotes := rs.Votes.Prevotes(prs.ProposalPOLRound); polPrevotes != nil {
  634. if ps.PickSendVote(polPrevotes) {
  635. logger.Debug("Picked rs.Prevotes(prs.ProposalPOLRound) to send",
  636. "round", prs.ProposalPOLRound)
  637. return true
  638. }
  639. }
  640. }
  641. return false
  642. }
  643. // NOTE: `queryMaj23Routine` has a simple crude design since it only comes
  644. // into play for liveness when there's a signature DDoS attack happening.
  645. func (conR *ConsensusReactor) queryMaj23Routine(peer p2p.Peer, ps *PeerState) {
  646. logger := conR.Logger.With("peer", peer)
  647. OUTER_LOOP:
  648. for {
  649. // Manage disconnects from self or peer.
  650. if !peer.IsRunning() || !conR.IsRunning() {
  651. logger.Info("Stopping queryMaj23Routine for peer")
  652. return
  653. }
  654. // Maybe send Height/Round/Prevotes
  655. {
  656. rs := conR.conS.GetRoundState()
  657. prs := ps.GetRoundState()
  658. if rs.Height == prs.Height {
  659. if maj23, ok := rs.Votes.Prevotes(prs.Round).TwoThirdsMajority(); ok {
  660. peer.TrySend(StateChannel, struct{ ConsensusMessage }{&VoteSetMaj23Message{
  661. Height: prs.Height,
  662. Round: prs.Round,
  663. Type: types.VoteTypePrevote,
  664. BlockID: maj23,
  665. }})
  666. time.Sleep(conR.conS.config.PeerQueryMaj23Sleep())
  667. }
  668. }
  669. }
  670. // Maybe send Height/Round/Precommits
  671. {
  672. rs := conR.conS.GetRoundState()
  673. prs := ps.GetRoundState()
  674. if rs.Height == prs.Height {
  675. if maj23, ok := rs.Votes.Precommits(prs.Round).TwoThirdsMajority(); ok {
  676. peer.TrySend(StateChannel, struct{ ConsensusMessage }{&VoteSetMaj23Message{
  677. Height: prs.Height,
  678. Round: prs.Round,
  679. Type: types.VoteTypePrecommit,
  680. BlockID: maj23,
  681. }})
  682. time.Sleep(conR.conS.config.PeerQueryMaj23Sleep())
  683. }
  684. }
  685. }
  686. // Maybe send Height/Round/ProposalPOL
  687. {
  688. rs := conR.conS.GetRoundState()
  689. prs := ps.GetRoundState()
  690. if rs.Height == prs.Height && prs.ProposalPOLRound >= 0 {
  691. if maj23, ok := rs.Votes.Prevotes(prs.ProposalPOLRound).TwoThirdsMajority(); ok {
  692. peer.TrySend(StateChannel, struct{ ConsensusMessage }{&VoteSetMaj23Message{
  693. Height: prs.Height,
  694. Round: prs.ProposalPOLRound,
  695. Type: types.VoteTypePrevote,
  696. BlockID: maj23,
  697. }})
  698. time.Sleep(conR.conS.config.PeerQueryMaj23Sleep())
  699. }
  700. }
  701. }
  702. // Little point sending LastCommitRound/LastCommit,
  703. // These are fleeting and non-blocking.
  704. // Maybe send Height/CatchupCommitRound/CatchupCommit.
  705. {
  706. prs := ps.GetRoundState()
  707. if prs.CatchupCommitRound != -1 && 0 < prs.Height && prs.Height <= conR.conS.blockStore.Height() {
  708. commit := conR.conS.LoadCommit(prs.Height)
  709. peer.TrySend(StateChannel, struct{ ConsensusMessage }{&VoteSetMaj23Message{
  710. Height: prs.Height,
  711. Round: commit.Round(),
  712. Type: types.VoteTypePrecommit,
  713. BlockID: commit.BlockID,
  714. }})
  715. time.Sleep(conR.conS.config.PeerQueryMaj23Sleep())
  716. }
  717. }
  718. time.Sleep(conR.conS.config.PeerQueryMaj23Sleep())
  719. continue OUTER_LOOP
  720. }
  721. }
  722. // String returns a string representation of the ConsensusReactor.
  723. // NOTE: For now, it is just a hard-coded string to avoid accessing unprotected shared variables.
  724. // TODO: improve!
  725. func (conR *ConsensusReactor) String() string {
  726. // better not to access shared variables
  727. return "ConsensusReactor" // conR.StringIndented("")
  728. }
  729. // StringIndented returns an indented string representation of the ConsensusReactor
  730. func (conR *ConsensusReactor) StringIndented(indent string) string {
  731. s := "ConsensusReactor{\n"
  732. s += indent + " " + conR.conS.StringIndented(indent+" ") + "\n"
  733. for _, peer := range conR.Switch.Peers().List() {
  734. ps := peer.Get(types.PeerStateKey).(*PeerState)
  735. s += indent + " " + ps.StringIndented(indent+" ") + "\n"
  736. }
  737. s += indent + "}"
  738. return s
  739. }
  740. //-----------------------------------------------------------------------------
  741. var (
  742. ErrPeerStateHeightRegression = errors.New("Error peer state height regression")
  743. ErrPeerStateInvalidStartTime = errors.New("Error peer state invalid startTime")
  744. )
  745. // PeerState contains the known state of a peer, including its connection
  746. // and threadsafe access to its PeerRoundState.
  747. type PeerState struct {
  748. Peer p2p.Peer
  749. logger log.Logger
  750. mtx sync.Mutex
  751. cstypes.PeerRoundState
  752. stats *peerStateStats
  753. }
  754. // peerStateStats holds internal statistics for a peer.
  755. type peerStateStats struct {
  756. lastVoteHeight int64
  757. votes int
  758. lastBlockPartHeight int64
  759. blockParts int
  760. }
  761. func (pss peerStateStats) String() string {
  762. return fmt.Sprintf("peerStateStats{votes: %d, blockParts: %d}", pss.votes, pss.blockParts)
  763. }
  764. // NewPeerState returns a new PeerState for the given Peer
  765. func NewPeerState(peer p2p.Peer) *PeerState {
  766. return &PeerState{
  767. Peer: peer,
  768. logger: log.NewNopLogger(),
  769. PeerRoundState: cstypes.PeerRoundState{
  770. Round: -1,
  771. ProposalPOLRound: -1,
  772. LastCommitRound: -1,
  773. CatchupCommitRound: -1,
  774. },
  775. stats: &peerStateStats{},
  776. }
  777. }
  778. func (ps *PeerState) SetLogger(logger log.Logger) *PeerState {
  779. ps.logger = logger
  780. return ps
  781. }
  782. // GetRoundState returns an atomic snapshot of the PeerRoundState.
  783. // There's no point in mutating it since it won't change PeerState.
  784. func (ps *PeerState) GetRoundState() *cstypes.PeerRoundState {
  785. ps.mtx.Lock()
  786. defer ps.mtx.Unlock()
  787. prs := ps.PeerRoundState // copy
  788. return &prs
  789. }
  790. // GetHeight returns an atomic snapshot of the PeerRoundState's height
  791. // used by the mempool to ensure peers are caught up before broadcasting new txs
  792. func (ps *PeerState) GetHeight() int64 {
  793. ps.mtx.Lock()
  794. defer ps.mtx.Unlock()
  795. return ps.PeerRoundState.Height
  796. }
  797. // SetHasProposal sets the given proposal as known for the peer.
  798. func (ps *PeerState) SetHasProposal(proposal *types.Proposal) {
  799. ps.mtx.Lock()
  800. defer ps.mtx.Unlock()
  801. if ps.Height != proposal.Height || ps.Round != proposal.Round {
  802. return
  803. }
  804. if ps.Proposal {
  805. return
  806. }
  807. ps.Proposal = true
  808. ps.ProposalBlockPartsHeader = proposal.BlockPartsHeader
  809. ps.ProposalBlockParts = cmn.NewBitArray(proposal.BlockPartsHeader.Total)
  810. ps.ProposalPOLRound = proposal.POLRound
  811. ps.ProposalPOL = nil // Nil until ProposalPOLMessage received.
  812. }
  813. // InitProposalBlockParts initializes the peer's proposal block parts header and bit array.
  814. func (ps *PeerState) InitProposalBlockParts(partsHeader types.PartSetHeader) {
  815. ps.mtx.Lock()
  816. defer ps.mtx.Unlock()
  817. if ps.ProposalBlockParts != nil {
  818. return
  819. }
  820. ps.ProposalBlockPartsHeader = partsHeader
  821. ps.ProposalBlockParts = cmn.NewBitArray(partsHeader.Total)
  822. }
  823. // SetHasProposalBlockPart sets the given block part index as known for the peer.
  824. func (ps *PeerState) SetHasProposalBlockPart(height int64, round int, index int) {
  825. ps.mtx.Lock()
  826. defer ps.mtx.Unlock()
  827. if ps.Height != height || ps.Round != round {
  828. return
  829. }
  830. ps.ProposalBlockParts.SetIndex(index, true)
  831. }
  832. // PickSendVote picks a vote and sends it to the peer.
  833. // Returns true if vote was sent.
  834. func (ps *PeerState) PickSendVote(votes types.VoteSetReader) bool {
  835. if vote, ok := ps.PickVoteToSend(votes); ok {
  836. msg := &VoteMessage{vote}
  837. ps.logger.Debug("Sending vote message", "ps", ps, "vote", vote)
  838. return ps.Peer.Send(VoteChannel, struct{ ConsensusMessage }{msg})
  839. }
  840. return false
  841. }
  842. // PickVoteToSend picks a vote to send to the peer.
  843. // Returns true if a vote was picked.
  844. // NOTE: `votes` must be the correct Size() for the Height().
  845. func (ps *PeerState) PickVoteToSend(votes types.VoteSetReader) (vote *types.Vote, ok bool) {
  846. ps.mtx.Lock()
  847. defer ps.mtx.Unlock()
  848. if votes.Size() == 0 {
  849. return nil, false
  850. }
  851. height, round, type_, size := votes.Height(), votes.Round(), votes.Type(), votes.Size()
  852. // Lazily set data using 'votes'.
  853. if votes.IsCommit() {
  854. ps.ensureCatchupCommitRound(height, round, size)
  855. }
  856. ps.ensureVoteBitArrays(height, size)
  857. psVotes := ps.getVoteBitArray(height, round, type_)
  858. if psVotes == nil {
  859. return nil, false // Not something worth sending
  860. }
  861. if index, ok := votes.BitArray().Sub(psVotes).PickRandom(); ok {
  862. ps.setHasVote(height, round, type_, index)
  863. return votes.GetByIndex(index), true
  864. }
  865. return nil, false
  866. }
  867. func (ps *PeerState) getVoteBitArray(height int64, round int, type_ byte) *cmn.BitArray {
  868. if !types.IsVoteTypeValid(type_) {
  869. return nil
  870. }
  871. if ps.Height == height {
  872. if ps.Round == round {
  873. switch type_ {
  874. case types.VoteTypePrevote:
  875. return ps.Prevotes
  876. case types.VoteTypePrecommit:
  877. return ps.Precommits
  878. }
  879. }
  880. if ps.CatchupCommitRound == round {
  881. switch type_ {
  882. case types.VoteTypePrevote:
  883. return nil
  884. case types.VoteTypePrecommit:
  885. return ps.CatchupCommit
  886. }
  887. }
  888. if ps.ProposalPOLRound == round {
  889. switch type_ {
  890. case types.VoteTypePrevote:
  891. return ps.ProposalPOL
  892. case types.VoteTypePrecommit:
  893. return nil
  894. }
  895. }
  896. return nil
  897. }
  898. if ps.Height == height+1 {
  899. if ps.LastCommitRound == round {
  900. switch type_ {
  901. case types.VoteTypePrevote:
  902. return nil
  903. case types.VoteTypePrecommit:
  904. return ps.LastCommit
  905. }
  906. }
  907. return nil
  908. }
  909. return nil
  910. }
  911. // 'round': A round for which we have a +2/3 commit.
  912. func (ps *PeerState) ensureCatchupCommitRound(height int64, round int, numValidators int) {
  913. if ps.Height != height {
  914. return
  915. }
  916. /*
  917. NOTE: This is wrong, 'round' could change.
  918. e.g. if orig round is not the same as block LastCommit round.
  919. if ps.CatchupCommitRound != -1 && ps.CatchupCommitRound != round {
  920. cmn.PanicSanity(cmn.Fmt("Conflicting CatchupCommitRound. Height: %v, Orig: %v, New: %v", height, ps.CatchupCommitRound, round))
  921. }
  922. */
  923. if ps.CatchupCommitRound == round {
  924. return // Nothing to do!
  925. }
  926. ps.CatchupCommitRound = round
  927. if round == ps.Round {
  928. ps.CatchupCommit = ps.Precommits
  929. } else {
  930. ps.CatchupCommit = cmn.NewBitArray(numValidators)
  931. }
  932. }
  933. // EnsureVoteVitArrays ensures the bit-arrays have been allocated for tracking
  934. // what votes this peer has received.
  935. // NOTE: It's important to make sure that numValidators actually matches
  936. // what the node sees as the number of validators for height.
  937. func (ps *PeerState) EnsureVoteBitArrays(height int64, numValidators int) {
  938. ps.mtx.Lock()
  939. defer ps.mtx.Unlock()
  940. ps.ensureVoteBitArrays(height, numValidators)
  941. }
  942. func (ps *PeerState) ensureVoteBitArrays(height int64, numValidators int) {
  943. if ps.Height == height {
  944. if ps.Prevotes == nil {
  945. ps.Prevotes = cmn.NewBitArray(numValidators)
  946. }
  947. if ps.Precommits == nil {
  948. ps.Precommits = cmn.NewBitArray(numValidators)
  949. }
  950. if ps.CatchupCommit == nil {
  951. ps.CatchupCommit = cmn.NewBitArray(numValidators)
  952. }
  953. if ps.ProposalPOL == nil {
  954. ps.ProposalPOL = cmn.NewBitArray(numValidators)
  955. }
  956. } else if ps.Height == height+1 {
  957. if ps.LastCommit == nil {
  958. ps.LastCommit = cmn.NewBitArray(numValidators)
  959. }
  960. }
  961. }
  962. // RecordVote updates internal statistics for this peer by recording the vote.
  963. // It returns the total number of votes (1 per block). This essentially means
  964. // the number of blocks for which peer has been sending us votes.
  965. func (ps *PeerState) RecordVote(vote *types.Vote) int {
  966. if ps.stats.lastVoteHeight >= vote.Height {
  967. return ps.stats.votes
  968. }
  969. ps.stats.lastVoteHeight = vote.Height
  970. ps.stats.votes += 1
  971. return ps.stats.votes
  972. }
  973. // VotesSent returns the number of blocks for which peer has been sending us
  974. // votes.
  975. func (ps *PeerState) VotesSent() int {
  976. return ps.stats.votes
  977. }
  978. // RecordVote updates internal statistics for this peer by recording the block part.
  979. // It returns the total number of block parts (1 per block). This essentially means
  980. // the number of blocks for which peer has been sending us block parts.
  981. func (ps *PeerState) RecordBlockPart(bp *BlockPartMessage) int {
  982. if ps.stats.lastBlockPartHeight >= bp.Height {
  983. return ps.stats.blockParts
  984. }
  985. ps.stats.lastBlockPartHeight = bp.Height
  986. ps.stats.blockParts += 1
  987. return ps.stats.blockParts
  988. }
  989. // BlockPartsSent returns the number of blocks for which peer has been sending
  990. // us block parts.
  991. func (ps *PeerState) BlockPartsSent() int {
  992. return ps.stats.blockParts
  993. }
  994. // SetHasVote sets the given vote as known by the peer
  995. func (ps *PeerState) SetHasVote(vote *types.Vote) {
  996. ps.mtx.Lock()
  997. defer ps.mtx.Unlock()
  998. ps.setHasVote(vote.Height, vote.Round, vote.Type, vote.ValidatorIndex)
  999. }
  1000. func (ps *PeerState) setHasVote(height int64, round int, type_ byte, index int) {
  1001. logger := ps.logger.With("peerH/R", cmn.Fmt("%d/%d", ps.Height, ps.Round), "H/R", cmn.Fmt("%d/%d", height, round))
  1002. logger.Debug("setHasVote", "type", type_, "index", index)
  1003. // NOTE: some may be nil BitArrays -> no side effects.
  1004. psVotes := ps.getVoteBitArray(height, round, type_)
  1005. if psVotes != nil {
  1006. psVotes.SetIndex(index, true)
  1007. }
  1008. }
  1009. // ApplyNewRoundStepMessage updates the peer state for the new round.
  1010. func (ps *PeerState) ApplyNewRoundStepMessage(msg *NewRoundStepMessage) {
  1011. ps.mtx.Lock()
  1012. defer ps.mtx.Unlock()
  1013. // Ignore duplicates or decreases
  1014. if CompareHRS(msg.Height, msg.Round, msg.Step, ps.Height, ps.Round, ps.Step) <= 0 {
  1015. return
  1016. }
  1017. // Just remember these values.
  1018. psHeight := ps.Height
  1019. psRound := ps.Round
  1020. //psStep := ps.Step
  1021. psCatchupCommitRound := ps.CatchupCommitRound
  1022. psCatchupCommit := ps.CatchupCommit
  1023. startTime := time.Now().Add(-1 * time.Duration(msg.SecondsSinceStartTime) * time.Second)
  1024. ps.Height = msg.Height
  1025. ps.Round = msg.Round
  1026. ps.Step = msg.Step
  1027. ps.StartTime = startTime
  1028. if psHeight != msg.Height || psRound != msg.Round {
  1029. ps.Proposal = false
  1030. ps.ProposalBlockPartsHeader = types.PartSetHeader{}
  1031. ps.ProposalBlockParts = nil
  1032. ps.ProposalPOLRound = -1
  1033. ps.ProposalPOL = nil
  1034. // We'll update the BitArray capacity later.
  1035. ps.Prevotes = nil
  1036. ps.Precommits = nil
  1037. }
  1038. if psHeight == msg.Height && psRound != msg.Round && msg.Round == psCatchupCommitRound {
  1039. // Peer caught up to CatchupCommitRound.
  1040. // Preserve psCatchupCommit!
  1041. // NOTE: We prefer to use prs.Precommits if
  1042. // pr.Round matches pr.CatchupCommitRound.
  1043. ps.Precommits = psCatchupCommit
  1044. }
  1045. if psHeight != msg.Height {
  1046. // Shift Precommits to LastCommit.
  1047. if psHeight+1 == msg.Height && psRound == msg.LastCommitRound {
  1048. ps.LastCommitRound = msg.LastCommitRound
  1049. ps.LastCommit = ps.Precommits
  1050. } else {
  1051. ps.LastCommitRound = msg.LastCommitRound
  1052. ps.LastCommit = nil
  1053. }
  1054. // We'll update the BitArray capacity later.
  1055. ps.CatchupCommitRound = -1
  1056. ps.CatchupCommit = nil
  1057. }
  1058. }
  1059. // ApplyCommitStepMessage updates the peer state for the new commit.
  1060. func (ps *PeerState) ApplyCommitStepMessage(msg *CommitStepMessage) {
  1061. ps.mtx.Lock()
  1062. defer ps.mtx.Unlock()
  1063. if ps.Height != msg.Height {
  1064. return
  1065. }
  1066. ps.ProposalBlockPartsHeader = msg.BlockPartsHeader
  1067. ps.ProposalBlockParts = msg.BlockParts
  1068. }
  1069. // ApplyProposalPOLMessage updates the peer state for the new proposal POL.
  1070. func (ps *PeerState) ApplyProposalPOLMessage(msg *ProposalPOLMessage) {
  1071. ps.mtx.Lock()
  1072. defer ps.mtx.Unlock()
  1073. if ps.Height != msg.Height {
  1074. return
  1075. }
  1076. if ps.ProposalPOLRound != msg.ProposalPOLRound {
  1077. return
  1078. }
  1079. // TODO: Merge onto existing ps.ProposalPOL?
  1080. // We might have sent some prevotes in the meantime.
  1081. ps.ProposalPOL = msg.ProposalPOL
  1082. }
  1083. // ApplyHasVoteMessage updates the peer state for the new vote.
  1084. func (ps *PeerState) ApplyHasVoteMessage(msg *HasVoteMessage) {
  1085. ps.mtx.Lock()
  1086. defer ps.mtx.Unlock()
  1087. if ps.Height != msg.Height {
  1088. return
  1089. }
  1090. ps.setHasVote(msg.Height, msg.Round, msg.Type, msg.Index)
  1091. }
  1092. // ApplyVoteSetBitsMessage updates the peer state for the bit-array of votes
  1093. // it claims to have for the corresponding BlockID.
  1094. // `ourVotes` is a BitArray of votes we have for msg.BlockID
  1095. // NOTE: if ourVotes is nil (e.g. msg.Height < rs.Height),
  1096. // we conservatively overwrite ps's votes w/ msg.Votes.
  1097. func (ps *PeerState) ApplyVoteSetBitsMessage(msg *VoteSetBitsMessage, ourVotes *cmn.BitArray) {
  1098. ps.mtx.Lock()
  1099. defer ps.mtx.Unlock()
  1100. votes := ps.getVoteBitArray(msg.Height, msg.Round, msg.Type)
  1101. if votes != nil {
  1102. if ourVotes == nil {
  1103. votes.Update(msg.Votes)
  1104. } else {
  1105. otherVotes := votes.Sub(ourVotes)
  1106. hasVotes := otherVotes.Or(msg.Votes)
  1107. votes.Update(hasVotes)
  1108. }
  1109. }
  1110. }
  1111. // String returns a string representation of the PeerState
  1112. func (ps *PeerState) String() string {
  1113. return ps.StringIndented("")
  1114. }
  1115. // StringIndented returns a string representation of the PeerState
  1116. func (ps *PeerState) StringIndented(indent string) string {
  1117. ps.mtx.Lock()
  1118. defer ps.mtx.Unlock()
  1119. return fmt.Sprintf(`PeerState{
  1120. %s Key %v
  1121. %s PRS %v
  1122. %s Stats %v
  1123. %s}`,
  1124. indent, ps.Peer.ID(),
  1125. indent, ps.PeerRoundState.StringIndented(indent+" "),
  1126. indent, ps.stats,
  1127. indent)
  1128. }
  1129. //-----------------------------------------------------------------------------
  1130. // Messages
  1131. const (
  1132. msgTypeNewRoundStep = byte(0x01)
  1133. msgTypeCommitStep = byte(0x02)
  1134. msgTypeProposal = byte(0x11)
  1135. msgTypeProposalPOL = byte(0x12)
  1136. msgTypeBlockPart = byte(0x13) // both block & POL
  1137. msgTypeVote = byte(0x14)
  1138. msgTypeHasVote = byte(0x15)
  1139. msgTypeVoteSetMaj23 = byte(0x16)
  1140. msgTypeVoteSetBits = byte(0x17)
  1141. msgTypeProposalHeartbeat = byte(0x20)
  1142. )
  1143. // ConsensusMessage is a message that can be sent and received on the ConsensusReactor
  1144. type ConsensusMessage interface{}
  1145. var _ = wire.RegisterInterface(
  1146. struct{ ConsensusMessage }{},
  1147. wire.ConcreteType{&NewRoundStepMessage{}, msgTypeNewRoundStep},
  1148. wire.ConcreteType{&CommitStepMessage{}, msgTypeCommitStep},
  1149. wire.ConcreteType{&ProposalMessage{}, msgTypeProposal},
  1150. wire.ConcreteType{&ProposalPOLMessage{}, msgTypeProposalPOL},
  1151. wire.ConcreteType{&BlockPartMessage{}, msgTypeBlockPart},
  1152. wire.ConcreteType{&VoteMessage{}, msgTypeVote},
  1153. wire.ConcreteType{&HasVoteMessage{}, msgTypeHasVote},
  1154. wire.ConcreteType{&VoteSetMaj23Message{}, msgTypeVoteSetMaj23},
  1155. wire.ConcreteType{&VoteSetBitsMessage{}, msgTypeVoteSetBits},
  1156. wire.ConcreteType{&ProposalHeartbeatMessage{}, msgTypeProposalHeartbeat},
  1157. )
  1158. // DecodeMessage decodes the given bytes into a ConsensusMessage.
  1159. // TODO: check for unnecessary extra bytes at the end.
  1160. func DecodeMessage(bz []byte) (msgType byte, msg ConsensusMessage, err error) {
  1161. msgType = bz[0]
  1162. n := new(int)
  1163. r := bytes.NewReader(bz)
  1164. msgI := wire.ReadBinary(struct{ ConsensusMessage }{}, r, maxConsensusMessageSize, n, &err)
  1165. msg = msgI.(struct{ ConsensusMessage }).ConsensusMessage
  1166. return
  1167. }
  1168. //-------------------------------------
  1169. // NewRoundStepMessage is sent for every step taken in the ConsensusState.
  1170. // For every height/round/step transition
  1171. type NewRoundStepMessage struct {
  1172. Height int64
  1173. Round int
  1174. Step cstypes.RoundStepType
  1175. SecondsSinceStartTime int
  1176. LastCommitRound int
  1177. }
  1178. // String returns a string representation.
  1179. func (m *NewRoundStepMessage) String() string {
  1180. return fmt.Sprintf("[NewRoundStep H:%v R:%v S:%v LCR:%v]",
  1181. m.Height, m.Round, m.Step, m.LastCommitRound)
  1182. }
  1183. //-------------------------------------
  1184. // CommitStepMessage is sent when a block is committed.
  1185. type CommitStepMessage struct {
  1186. Height int64
  1187. BlockPartsHeader types.PartSetHeader
  1188. BlockParts *cmn.BitArray
  1189. }
  1190. // String returns a string representation.
  1191. func (m *CommitStepMessage) String() string {
  1192. return fmt.Sprintf("[CommitStep H:%v BP:%v BA:%v]", m.Height, m.BlockPartsHeader, m.BlockParts)
  1193. }
  1194. //-------------------------------------
  1195. // ProposalMessage is sent when a new block is proposed.
  1196. type ProposalMessage struct {
  1197. Proposal *types.Proposal
  1198. }
  1199. // String returns a string representation.
  1200. func (m *ProposalMessage) String() string {
  1201. return fmt.Sprintf("[Proposal %v]", m.Proposal)
  1202. }
  1203. //-------------------------------------
  1204. // ProposalPOLMessage is sent when a previous proposal is re-proposed.
  1205. type ProposalPOLMessage struct {
  1206. Height int64
  1207. ProposalPOLRound int
  1208. ProposalPOL *cmn.BitArray
  1209. }
  1210. // String returns a string representation.
  1211. func (m *ProposalPOLMessage) String() string {
  1212. return fmt.Sprintf("[ProposalPOL H:%v POLR:%v POL:%v]", m.Height, m.ProposalPOLRound, m.ProposalPOL)
  1213. }
  1214. //-------------------------------------
  1215. // BlockPartMessage is sent when gossipping a piece of the proposed block.
  1216. type BlockPartMessage struct {
  1217. Height int64
  1218. Round int
  1219. Part *types.Part
  1220. }
  1221. // String returns a string representation.
  1222. func (m *BlockPartMessage) String() string {
  1223. return fmt.Sprintf("[BlockPart H:%v R:%v P:%v]", m.Height, m.Round, m.Part)
  1224. }
  1225. //-------------------------------------
  1226. // VoteMessage is sent when voting for a proposal (or lack thereof).
  1227. type VoteMessage struct {
  1228. Vote *types.Vote
  1229. }
  1230. // String returns a string representation.
  1231. func (m *VoteMessage) String() string {
  1232. return fmt.Sprintf("[Vote %v]", m.Vote)
  1233. }
  1234. //-------------------------------------
  1235. // HasVoteMessage is sent to indicate that a particular vote has been received.
  1236. type HasVoteMessage struct {
  1237. Height int64
  1238. Round int
  1239. Type byte
  1240. Index int
  1241. }
  1242. // String returns a string representation.
  1243. func (m *HasVoteMessage) String() string {
  1244. return fmt.Sprintf("[HasVote VI:%v V:{%v/%02d/%v}]", m.Index, m.Height, m.Round, m.Type)
  1245. }
  1246. //-------------------------------------
  1247. // VoteSetMaj23Message is sent to indicate that a given BlockID has seen +2/3 votes.
  1248. type VoteSetMaj23Message struct {
  1249. Height int64
  1250. Round int
  1251. Type byte
  1252. BlockID types.BlockID
  1253. }
  1254. // String returns a string representation.
  1255. func (m *VoteSetMaj23Message) String() string {
  1256. return fmt.Sprintf("[VSM23 %v/%02d/%v %v]", m.Height, m.Round, m.Type, m.BlockID)
  1257. }
  1258. //-------------------------------------
  1259. // VoteSetBitsMessage is sent to communicate the bit-array of votes seen for the BlockID.
  1260. type VoteSetBitsMessage struct {
  1261. Height int64
  1262. Round int
  1263. Type byte
  1264. BlockID types.BlockID
  1265. Votes *cmn.BitArray
  1266. }
  1267. // String returns a string representation.
  1268. func (m *VoteSetBitsMessage) String() string {
  1269. return fmt.Sprintf("[VSB %v/%02d/%v %v %v]", m.Height, m.Round, m.Type, m.BlockID, m.Votes)
  1270. }
  1271. //-------------------------------------
  1272. // ProposalHeartbeatMessage is sent to signal that a node is alive and waiting for transactions for a proposal.
  1273. type ProposalHeartbeatMessage struct {
  1274. Heartbeat *types.Heartbeat
  1275. }
  1276. // String returns a string representation.
  1277. func (m *ProposalHeartbeatMessage) String() string {
  1278. return fmt.Sprintf("[HEARTBEAT %v]", m.Heartbeat)
  1279. }