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.

583 lines
21 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
6 years ago
6 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
6 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
6 years ago
6 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
8 years ago
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
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
  1. package consensus
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "path"
  7. "runtime"
  8. "runtime/pprof"
  9. "sync"
  10. "testing"
  11. "time"
  12. "github.com/stretchr/testify/assert"
  13. "github.com/stretchr/testify/require"
  14. abcicli "github.com/tendermint/tendermint/abci/client"
  15. "github.com/tendermint/tendermint/abci/example/kvstore"
  16. abci "github.com/tendermint/tendermint/abci/types"
  17. bc "github.com/tendermint/tendermint/blockchain"
  18. cfg "github.com/tendermint/tendermint/config"
  19. dbm "github.com/tendermint/tendermint/libs/db"
  20. "github.com/tendermint/tendermint/libs/log"
  21. mempl "github.com/tendermint/tendermint/mempool"
  22. "github.com/tendermint/tendermint/p2p"
  23. sm "github.com/tendermint/tendermint/state"
  24. "github.com/tendermint/tendermint/types"
  25. )
  26. func init() {
  27. config = ResetConfig("consensus_reactor_test")
  28. }
  29. //----------------------------------------------
  30. // in-process testnets
  31. func startConsensusNet(t *testing.T, css []*ConsensusState, N int) (
  32. []*ConsensusReactor,
  33. []types.Subscription,
  34. []*types.EventBus,
  35. ) {
  36. reactors := make([]*ConsensusReactor, N)
  37. blocksSubs := make([]types.Subscription, 0)
  38. eventBuses := make([]*types.EventBus, N)
  39. for i := 0; i < N; i++ {
  40. /*logger, err := tmflags.ParseLogLevel("consensus:info,*:error", logger, "info")
  41. if err != nil { t.Fatal(err)}*/
  42. reactors[i] = NewConsensusReactor(css[i], true) // so we dont start the consensus states
  43. reactors[i].SetLogger(css[i].Logger)
  44. // eventBus is already started with the cs
  45. eventBuses[i] = css[i].eventBus
  46. reactors[i].SetEventBus(eventBuses[i])
  47. blocksSub, err := eventBuses[i].Subscribe(context.Background(), testSubscriber, types.EventQueryNewBlock)
  48. require.NoError(t, err)
  49. blocksSubs = append(blocksSubs, blocksSub)
  50. }
  51. // make connected switches and start all reactors
  52. p2p.MakeConnectedSwitches(config.P2P, N, func(i int, s *p2p.Switch) *p2p.Switch {
  53. s.AddReactor("CONSENSUS", reactors[i])
  54. s.SetLogger(reactors[i].conS.Logger.With("module", "p2p"))
  55. return s
  56. }, p2p.Connect2Switches)
  57. // now that everyone is connected, start the state machines
  58. // If we started the state machines before everyone was connected,
  59. // we'd block when the cs fires NewBlockEvent and the peers are trying to start their reactors
  60. // TODO: is this still true with new pubsub?
  61. for i := 0; i < N; i++ {
  62. s := reactors[i].conS.GetState()
  63. reactors[i].SwitchToConsensus(s, 0)
  64. }
  65. return reactors, blocksSubs, eventBuses
  66. }
  67. func stopConsensusNet(logger log.Logger, reactors []*ConsensusReactor, eventBuses []*types.EventBus) {
  68. logger.Info("stopConsensusNet", "n", len(reactors))
  69. for i, r := range reactors {
  70. logger.Info("stopConsensusNet: Stopping ConsensusReactor", "i", i)
  71. r.Switch.Stop()
  72. }
  73. for i, b := range eventBuses {
  74. logger.Info("stopConsensusNet: Stopping eventBus", "i", i)
  75. b.Stop()
  76. }
  77. logger.Info("stopConsensusNet: DONE", "n", len(reactors))
  78. }
  79. // Ensure a testnet makes blocks
  80. func TestReactorBasic(t *testing.T) {
  81. N := 4
  82. css := randConsensusNet(N, "consensus_reactor_test", newMockTickerFunc(true), newCounter)
  83. reactors, blocksSubs, eventBuses := startConsensusNet(t, css, N)
  84. defer stopConsensusNet(log.TestingLogger(), reactors, eventBuses)
  85. // wait till everyone makes the first new block
  86. timeoutWaitGroup(t, N, func(j int) {
  87. <-blocksSubs[j].Out()
  88. }, css)
  89. }
  90. // Ensure we can process blocks with evidence
  91. func TestReactorWithEvidence(t *testing.T) {
  92. types.RegisterMockEvidences(cdc)
  93. types.RegisterMockEvidences(types.GetCodec())
  94. nValidators := 4
  95. testName := "consensus_reactor_test"
  96. tickerFunc := newMockTickerFunc(true)
  97. appFunc := newCounter
  98. // heed the advice from https://www.sandimetz.com/blog/2016/1/20/the-wrong-abstraction
  99. // to unroll unwieldy abstractions. Here we duplicate the code from:
  100. // css := randConsensusNet(N, "consensus_reactor_test", newMockTickerFunc(true), newCounter)
  101. genDoc, privVals := randGenesisDoc(nValidators, false, 30)
  102. css := make([]*ConsensusState, nValidators)
  103. logger := consensusLogger()
  104. for i := 0; i < nValidators; i++ {
  105. stateDB := dbm.NewMemDB() // each state needs its own db
  106. state, _ := sm.LoadStateFromDBOrGenesisDoc(stateDB, genDoc)
  107. thisConfig := ResetConfig(fmt.Sprintf("%s_%d", testName, i))
  108. ensureDir(path.Dir(thisConfig.Consensus.WalFile()), 0700) // dir for wal
  109. app := appFunc()
  110. vals := types.TM2PB.ValidatorUpdates(state.Validators)
  111. app.InitChain(abci.RequestInitChain{Validators: vals})
  112. pv := privVals[i]
  113. // duplicate code from:
  114. // css[i] = newConsensusStateWithConfig(thisConfig, state, privVals[i], app)
  115. blockDB := dbm.NewMemDB()
  116. blockStore := bc.NewBlockStore(blockDB)
  117. // one for mempool, one for consensus
  118. mtx := new(sync.Mutex)
  119. proxyAppConnMem := abcicli.NewLocalClient(mtx, app)
  120. proxyAppConnCon := abcicli.NewLocalClient(mtx, app)
  121. // Make Mempool
  122. mempool := mempl.NewMempool(thisConfig.Mempool, proxyAppConnMem, 0)
  123. mempool.SetLogger(log.TestingLogger().With("module", "mempool"))
  124. if thisConfig.Consensus.WaitForTxs() {
  125. mempool.EnableTxsAvailable()
  126. }
  127. // mock the evidence pool
  128. // everyone includes evidence of another double signing
  129. vIdx := (i + 1) % nValidators
  130. addr := privVals[vIdx].GetPubKey().Address()
  131. evpool := newMockEvidencePool(addr)
  132. // Make ConsensusState
  133. blockExec := sm.NewBlockExecutor(stateDB, log.TestingLogger(), proxyAppConnCon, mempool, evpool)
  134. cs := NewConsensusState(thisConfig.Consensus, state, blockExec, blockStore, mempool, evpool)
  135. cs.SetLogger(log.TestingLogger().With("module", "consensus"))
  136. cs.SetPrivValidator(pv)
  137. eventBus := types.NewEventBus()
  138. eventBus.SetLogger(log.TestingLogger().With("module", "events"))
  139. eventBus.Start()
  140. cs.SetEventBus(eventBus)
  141. cs.SetTimeoutTicker(tickerFunc())
  142. cs.SetLogger(logger.With("validator", i, "module", "consensus"))
  143. css[i] = cs
  144. }
  145. reactors, blocksSubs, eventBuses := startConsensusNet(t, css, nValidators)
  146. defer stopConsensusNet(log.TestingLogger(), reactors, eventBuses)
  147. // wait till everyone makes the first new block with no evidence
  148. timeoutWaitGroup(t, nValidators, func(j int) {
  149. msg := <-blocksSubs[j].Out()
  150. block := msg.Data().(types.EventDataNewBlock).Block
  151. assert.True(t, len(block.Evidence.Evidence) == 0)
  152. }, css)
  153. // second block should have evidence
  154. timeoutWaitGroup(t, nValidators, func(j int) {
  155. msg := <-blocksSubs[j].Out()
  156. block := msg.Data().(types.EventDataNewBlock).Block
  157. assert.True(t, len(block.Evidence.Evidence) > 0)
  158. }, css)
  159. }
  160. // mock evidence pool returns no evidence for block 1,
  161. // and returnes one piece for all higher blocks. The one piece
  162. // is for a given validator at block 1.
  163. type mockEvidencePool struct {
  164. height int
  165. ev []types.Evidence
  166. }
  167. func newMockEvidencePool(val []byte) *mockEvidencePool {
  168. return &mockEvidencePool{
  169. ev: []types.Evidence{types.NewMockGoodEvidence(1, 1, val)},
  170. }
  171. }
  172. // NOTE: maxBytes is ignored
  173. func (m *mockEvidencePool) PendingEvidence(maxBytes int64) []types.Evidence {
  174. if m.height > 0 {
  175. return m.ev
  176. }
  177. return nil
  178. }
  179. func (m *mockEvidencePool) AddEvidence(types.Evidence) error { return nil }
  180. func (m *mockEvidencePool) Update(block *types.Block, state sm.State) {
  181. if m.height > 0 {
  182. if len(block.Evidence.Evidence) == 0 {
  183. panic("block has no evidence")
  184. }
  185. }
  186. m.height++
  187. }
  188. func (m *mockEvidencePool) IsCommitted(types.Evidence) bool { return false }
  189. //------------------------------------
  190. // Ensure a testnet makes blocks when there are txs
  191. func TestReactorCreatesBlockWhenEmptyBlocksFalse(t *testing.T) {
  192. N := 4
  193. css := randConsensusNet(N, "consensus_reactor_test", newMockTickerFunc(true), newCounter,
  194. func(c *cfg.Config) {
  195. c.Consensus.CreateEmptyBlocks = false
  196. })
  197. reactors, blocksSubs, eventBuses := startConsensusNet(t, css, N)
  198. defer stopConsensusNet(log.TestingLogger(), reactors, eventBuses)
  199. // send a tx
  200. if err := assertMempool(css[3].txNotifier).CheckTx([]byte{1, 2, 3}, nil); err != nil {
  201. //t.Fatal(err)
  202. }
  203. // wait till everyone makes the first new block
  204. timeoutWaitGroup(t, N, func(j int) {
  205. <-blocksSubs[j].Out()
  206. }, css)
  207. }
  208. // Test we record stats about votes and block parts from other peers.
  209. func TestReactorRecordsVotesAndBlockParts(t *testing.T) {
  210. N := 4
  211. css := randConsensusNet(N, "consensus_reactor_test", newMockTickerFunc(true), newCounter)
  212. reactors, blocksSubs, eventBuses := startConsensusNet(t, css, N)
  213. defer stopConsensusNet(log.TestingLogger(), reactors, eventBuses)
  214. // wait till everyone makes the first new block
  215. timeoutWaitGroup(t, N, func(j int) {
  216. <-blocksSubs[j].Out()
  217. }, css)
  218. // Get peer
  219. peer := reactors[1].Switch.Peers().List()[0]
  220. // Get peer state
  221. ps := peer.Get(types.PeerStateKey).(*PeerState)
  222. assert.Equal(t, true, ps.VotesSent() > 0, "number of votes sent should have increased")
  223. assert.Equal(t, true, ps.BlockPartsSent() > 0, "number of votes sent should have increased")
  224. }
  225. //-------------------------------------------------------------
  226. // ensure we can make blocks despite cycling a validator set
  227. func TestReactorVotingPowerChange(t *testing.T) {
  228. nVals := 4
  229. logger := log.TestingLogger()
  230. css := randConsensusNet(nVals, "consensus_voting_power_changes_test", newMockTickerFunc(true), newPersistentKVStore)
  231. reactors, blocksSubs, eventBuses := startConsensusNet(t, css, nVals)
  232. defer stopConsensusNet(logger, reactors, eventBuses)
  233. // map of active validators
  234. activeVals := make(map[string]struct{})
  235. for i := 0; i < nVals; i++ {
  236. addr := css[i].privValidator.GetPubKey().Address()
  237. activeVals[string(addr)] = struct{}{}
  238. }
  239. // wait till everyone makes block 1
  240. timeoutWaitGroup(t, nVals, func(j int) {
  241. <-blocksSubs[j].Out()
  242. }, css)
  243. //---------------------------------------------------------------------------
  244. logger.Debug("---------------------------- Testing changing the voting power of one validator a few times")
  245. val1PubKey := css[0].privValidator.GetPubKey()
  246. val1PubKeyABCI := types.TM2PB.PubKey(val1PubKey)
  247. updateValidatorTx := kvstore.MakeValSetChangeTx(val1PubKeyABCI, 25)
  248. previousTotalVotingPower := css[0].GetRoundState().LastValidators.TotalVotingPower()
  249. waitForAndValidateBlock(t, nVals, activeVals, blocksSubs, css, updateValidatorTx)
  250. waitForAndValidateBlockWithTx(t, nVals, activeVals, blocksSubs, css, updateValidatorTx)
  251. waitForAndValidateBlock(t, nVals, activeVals, blocksSubs, css)
  252. waitForAndValidateBlock(t, nVals, activeVals, blocksSubs, css)
  253. if css[0].GetRoundState().LastValidators.TotalVotingPower() == previousTotalVotingPower {
  254. t.Fatalf("expected voting power to change (before: %d, after: %d)", previousTotalVotingPower, css[0].GetRoundState().LastValidators.TotalVotingPower())
  255. }
  256. updateValidatorTx = kvstore.MakeValSetChangeTx(val1PubKeyABCI, 2)
  257. previousTotalVotingPower = css[0].GetRoundState().LastValidators.TotalVotingPower()
  258. waitForAndValidateBlock(t, nVals, activeVals, blocksSubs, css, updateValidatorTx)
  259. waitForAndValidateBlockWithTx(t, nVals, activeVals, blocksSubs, css, updateValidatorTx)
  260. waitForAndValidateBlock(t, nVals, activeVals, blocksSubs, css)
  261. waitForAndValidateBlock(t, nVals, activeVals, blocksSubs, css)
  262. if css[0].GetRoundState().LastValidators.TotalVotingPower() == previousTotalVotingPower {
  263. t.Fatalf("expected voting power to change (before: %d, after: %d)", previousTotalVotingPower, css[0].GetRoundState().LastValidators.TotalVotingPower())
  264. }
  265. updateValidatorTx = kvstore.MakeValSetChangeTx(val1PubKeyABCI, 26)
  266. previousTotalVotingPower = css[0].GetRoundState().LastValidators.TotalVotingPower()
  267. waitForAndValidateBlock(t, nVals, activeVals, blocksSubs, css, updateValidatorTx)
  268. waitForAndValidateBlockWithTx(t, nVals, activeVals, blocksSubs, css, updateValidatorTx)
  269. waitForAndValidateBlock(t, nVals, activeVals, blocksSubs, css)
  270. waitForAndValidateBlock(t, nVals, activeVals, blocksSubs, css)
  271. if css[0].GetRoundState().LastValidators.TotalVotingPower() == previousTotalVotingPower {
  272. t.Fatalf("expected voting power to change (before: %d, after: %d)", previousTotalVotingPower, css[0].GetRoundState().LastValidators.TotalVotingPower())
  273. }
  274. }
  275. func TestReactorValidatorSetChanges(t *testing.T) {
  276. nPeers := 7
  277. nVals := 4
  278. css := randConsensusNetWithPeers(nVals, nPeers, "consensus_val_set_changes_test", newMockTickerFunc(true), newPersistentKVStore)
  279. logger := log.TestingLogger()
  280. reactors, blocksSubs, eventBuses := startConsensusNet(t, css, nPeers)
  281. defer stopConsensusNet(logger, reactors, eventBuses)
  282. // map of active validators
  283. activeVals := make(map[string]struct{})
  284. for i := 0; i < nVals; i++ {
  285. addr := css[i].privValidator.GetPubKey().Address()
  286. activeVals[string(addr)] = struct{}{}
  287. }
  288. // wait till everyone makes block 1
  289. timeoutWaitGroup(t, nPeers, func(j int) {
  290. <-blocksSubs[j].Out()
  291. }, css)
  292. //---------------------------------------------------------------------------
  293. logger.Info("---------------------------- Testing adding one validator")
  294. newValidatorPubKey1 := css[nVals].privValidator.GetPubKey()
  295. valPubKey1ABCI := types.TM2PB.PubKey(newValidatorPubKey1)
  296. newValidatorTx1 := kvstore.MakeValSetChangeTx(valPubKey1ABCI, testMinPower)
  297. // wait till everyone makes block 2
  298. // ensure the commit includes all validators
  299. // send newValTx to change vals in block 3
  300. waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, css, newValidatorTx1)
  301. // wait till everyone makes block 3.
  302. // it includes the commit for block 2, which is by the original validator set
  303. waitForAndValidateBlockWithTx(t, nPeers, activeVals, blocksSubs, css, newValidatorTx1)
  304. // wait till everyone makes block 4.
  305. // it includes the commit for block 3, which is by the original validator set
  306. waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, css)
  307. // the commits for block 4 should be with the updated validator set
  308. activeVals[string(newValidatorPubKey1.Address())] = struct{}{}
  309. // wait till everyone makes block 5
  310. // it includes the commit for block 4, which should have the updated validator set
  311. waitForBlockWithUpdatedValsAndValidateIt(t, nPeers, activeVals, blocksSubs, css)
  312. //---------------------------------------------------------------------------
  313. logger.Info("---------------------------- Testing changing the voting power of one validator")
  314. updateValidatorPubKey1 := css[nVals].privValidator.GetPubKey()
  315. updatePubKey1ABCI := types.TM2PB.PubKey(updateValidatorPubKey1)
  316. updateValidatorTx1 := kvstore.MakeValSetChangeTx(updatePubKey1ABCI, 25)
  317. previousTotalVotingPower := css[nVals].GetRoundState().LastValidators.TotalVotingPower()
  318. waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, css, updateValidatorTx1)
  319. waitForAndValidateBlockWithTx(t, nPeers, activeVals, blocksSubs, css, updateValidatorTx1)
  320. waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, css)
  321. waitForBlockWithUpdatedValsAndValidateIt(t, nPeers, activeVals, blocksSubs, css)
  322. if css[nVals].GetRoundState().LastValidators.TotalVotingPower() == previousTotalVotingPower {
  323. t.Errorf("expected voting power to change (before: %d, after: %d)", previousTotalVotingPower, css[nVals].GetRoundState().LastValidators.TotalVotingPower())
  324. }
  325. //---------------------------------------------------------------------------
  326. logger.Info("---------------------------- Testing adding two validators at once")
  327. newValidatorPubKey2 := css[nVals+1].privValidator.GetPubKey()
  328. newVal2ABCI := types.TM2PB.PubKey(newValidatorPubKey2)
  329. newValidatorTx2 := kvstore.MakeValSetChangeTx(newVal2ABCI, testMinPower)
  330. newValidatorPubKey3 := css[nVals+2].privValidator.GetPubKey()
  331. newVal3ABCI := types.TM2PB.PubKey(newValidatorPubKey3)
  332. newValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, testMinPower)
  333. waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, css, newValidatorTx2, newValidatorTx3)
  334. waitForAndValidateBlockWithTx(t, nPeers, activeVals, blocksSubs, css, newValidatorTx2, newValidatorTx3)
  335. waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, css)
  336. activeVals[string(newValidatorPubKey2.Address())] = struct{}{}
  337. activeVals[string(newValidatorPubKey3.Address())] = struct{}{}
  338. waitForBlockWithUpdatedValsAndValidateIt(t, nPeers, activeVals, blocksSubs, css)
  339. //---------------------------------------------------------------------------
  340. logger.Info("---------------------------- Testing removing two validators at once")
  341. removeValidatorTx2 := kvstore.MakeValSetChangeTx(newVal2ABCI, 0)
  342. removeValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, 0)
  343. waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, css, removeValidatorTx2, removeValidatorTx3)
  344. waitForAndValidateBlockWithTx(t, nPeers, activeVals, blocksSubs, css, removeValidatorTx2, removeValidatorTx3)
  345. waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, css)
  346. delete(activeVals, string(newValidatorPubKey2.Address()))
  347. delete(activeVals, string(newValidatorPubKey3.Address()))
  348. waitForBlockWithUpdatedValsAndValidateIt(t, nPeers, activeVals, blocksSubs, css)
  349. }
  350. // Check we can make blocks with skip_timeout_commit=false
  351. func TestReactorWithTimeoutCommit(t *testing.T) {
  352. N := 4
  353. css := randConsensusNet(N, "consensus_reactor_with_timeout_commit_test", newMockTickerFunc(false), newCounter)
  354. // override default SkipTimeoutCommit == true for tests
  355. for i := 0; i < N; i++ {
  356. css[i].config.SkipTimeoutCommit = false
  357. }
  358. reactors, blocksSubs, eventBuses := startConsensusNet(t, css, N-1)
  359. defer stopConsensusNet(log.TestingLogger(), reactors, eventBuses)
  360. // wait till everyone makes the first new block
  361. timeoutWaitGroup(t, N-1, func(j int) {
  362. <-blocksSubs[j].Out()
  363. }, css)
  364. }
  365. func waitForAndValidateBlock(
  366. t *testing.T,
  367. n int,
  368. activeVals map[string]struct{},
  369. blocksSubs []types.Subscription,
  370. css []*ConsensusState,
  371. txs ...[]byte,
  372. ) {
  373. timeoutWaitGroup(t, n, func(j int) {
  374. css[j].Logger.Debug("waitForAndValidateBlock")
  375. msg := <-blocksSubs[j].Out()
  376. newBlock := msg.Data().(types.EventDataNewBlock).Block
  377. css[j].Logger.Debug("waitForAndValidateBlock: Got block", "height", newBlock.Height)
  378. err := validateBlock(newBlock, activeVals)
  379. assert.Nil(t, err)
  380. for _, tx := range txs {
  381. err := assertMempool(css[j].txNotifier).CheckTx(tx, nil)
  382. assert.Nil(t, err)
  383. }
  384. }, css)
  385. }
  386. func waitForAndValidateBlockWithTx(
  387. t *testing.T,
  388. n int,
  389. activeVals map[string]struct{},
  390. blocksSubs []types.Subscription,
  391. css []*ConsensusState,
  392. txs ...[]byte,
  393. ) {
  394. timeoutWaitGroup(t, n, func(j int) {
  395. ntxs := 0
  396. BLOCK_TX_LOOP:
  397. for {
  398. css[j].Logger.Debug("waitForAndValidateBlockWithTx", "ntxs", ntxs)
  399. msg := <-blocksSubs[j].Out()
  400. newBlock := msg.Data().(types.EventDataNewBlock).Block
  401. css[j].Logger.Debug("waitForAndValidateBlockWithTx: Got block", "height", newBlock.Height)
  402. err := validateBlock(newBlock, activeVals)
  403. assert.Nil(t, err)
  404. // check that txs match the txs we're waiting for.
  405. // note they could be spread over multiple blocks,
  406. // but they should be in order.
  407. for _, tx := range newBlock.Data.Txs {
  408. assert.EqualValues(t, txs[ntxs], tx)
  409. ntxs++
  410. }
  411. if ntxs == len(txs) {
  412. break BLOCK_TX_LOOP
  413. }
  414. }
  415. }, css)
  416. }
  417. func waitForBlockWithUpdatedValsAndValidateIt(
  418. t *testing.T,
  419. n int,
  420. updatedVals map[string]struct{},
  421. blocksSubs []types.Subscription,
  422. css []*ConsensusState,
  423. ) {
  424. timeoutWaitGroup(t, n, func(j int) {
  425. var newBlock *types.Block
  426. LOOP:
  427. for {
  428. css[j].Logger.Debug("waitForBlockWithUpdatedValsAndValidateIt")
  429. msg := <-blocksSubs[j].Out()
  430. newBlock = msg.Data().(types.EventDataNewBlock).Block
  431. if newBlock.LastCommit.Size() == len(updatedVals) {
  432. css[j].Logger.Debug("waitForBlockWithUpdatedValsAndValidateIt: Got block", "height", newBlock.Height)
  433. break LOOP
  434. } else {
  435. css[j].Logger.Debug("waitForBlockWithUpdatedValsAndValidateIt: Got block with no new validators. Skipping", "height", newBlock.Height)
  436. }
  437. }
  438. err := validateBlock(newBlock, updatedVals)
  439. assert.Nil(t, err)
  440. }, css)
  441. }
  442. // expects high synchrony!
  443. func validateBlock(block *types.Block, activeVals map[string]struct{}) error {
  444. if block.LastCommit.Size() != len(activeVals) {
  445. return fmt.Errorf("Commit size doesn't match number of active validators. Got %d, expected %d", block.LastCommit.Size(), len(activeVals))
  446. }
  447. for _, vote := range block.LastCommit.Precommits {
  448. if _, ok := activeVals[string(vote.ValidatorAddress)]; !ok {
  449. return fmt.Errorf("Found vote for unactive validator %X", vote.ValidatorAddress)
  450. }
  451. }
  452. return nil
  453. }
  454. func timeoutWaitGroup(t *testing.T, n int, f func(int), css []*ConsensusState) {
  455. wg := new(sync.WaitGroup)
  456. wg.Add(n)
  457. for i := 0; i < n; i++ {
  458. go func(j int) {
  459. f(j)
  460. wg.Done()
  461. }(i)
  462. }
  463. done := make(chan struct{})
  464. go func() {
  465. wg.Wait()
  466. close(done)
  467. }()
  468. // we're running many nodes in-process, possibly in in a virtual machine,
  469. // and spewing debug messages - making a block could take a while,
  470. timeout := time.Second * 300
  471. select {
  472. case <-done:
  473. case <-time.After(timeout):
  474. for i, cs := range css {
  475. t.Log("#################")
  476. t.Log("Validator", i)
  477. t.Log(cs.GetRoundState())
  478. t.Log("")
  479. }
  480. os.Stdout.Write([]byte("pprof.Lookup('goroutine'):\n"))
  481. pprof.Lookup("goroutine").WriteTo(os.Stdout, 1)
  482. capture()
  483. panic("Timed out waiting for all validators to commit a block")
  484. }
  485. }
  486. func capture() {
  487. trace := make([]byte, 10240000)
  488. count := runtime.Stack(trace, true)
  489. fmt.Printf("Stack of %d bytes: %s\n", count, trace)
  490. }