diff --git a/mempool/config.go b/mempool/config.go new file mode 100644 index 000000000..936803086 --- /dev/null +++ b/mempool/config.go @@ -0,0 +1,13 @@ +package mempool + +import ( + cfg "github.com/tendermint/tendermint/config" +) + +var config cfg.Config = nil + +func init() { + cfg.OnConfig(func(newConfig cfg.Config) { + config = newConfig + }) +} diff --git a/mempool/mempool.go b/mempool/mempool.go index 17a736e63..98813014b 100644 --- a/mempool/mempool.go +++ b/mempool/mempool.go @@ -39,6 +39,12 @@ func (mem *Mempool) GetCache() *sm.BlockCache { return mem.cache } +func (mem *Mempool) GetHeight() int { + mem.mtx.Lock() + defer mem.mtx.Unlock() + return mem.state.LastBlockHeight +} + // Apply tx to the state and remember it. func (mem *Mempool) AddTx(tx types.Tx) (err error) { mem.mtx.Lock() diff --git a/mempool/mempool_test.go b/mempool/mempool_test.go new file mode 100644 index 000000000..8947adb88 --- /dev/null +++ b/mempool/mempool_test.go @@ -0,0 +1,275 @@ +package mempool + +import ( + "fmt" + "sync" + "testing" + "time" + + acm "github.com/tendermint/tendermint/account" + _ "github.com/tendermint/tendermint/config/tendermint_test" + sm "github.com/tendermint/tendermint/state" + "github.com/tendermint/tendermint/types" +) + +var someAddr = []byte("ABCDEFGHIJABCDEFGHIJ") + +// number of txs +var nTxs = 100 + +// what the ResetInfo should look like after ResetForBlockAndState +var TestResetInfoData = ResetInfo{ + Included: []Range{ + Range{0, 5}, + Range{10, 10}, + Range{30, 5}, + }, + Invalid: []Range{ + Range{5, 5}, + Range{20, 8}, // let 28 and 29 be valid + Range{35, 64}, // let 99 be valid + }, +} + +// inverse of the ResetInfo +var notInvalidNotIncluded = map[int]struct{}{ + 28: struct{}{}, + 29: struct{}{}, + 99: struct{}{}, +} + +func newSendTx(t *testing.T, mempool *Mempool, from *acm.PrivAccount, to []byte, amt int64) types.Tx { + tx := types.NewSendTx() + tx.AddInput(mempool.GetCache(), from.PubKey, amt) + tx.AddOutput(to, amt) + tx.SignInput(config.GetString("chain_id"), 0, from) + if err := mempool.AddTx(tx); err != nil { + t.Fatal(err) + } + return tx +} + +func addTxs(t *testing.T, mempool *Mempool, lastAcc *acm.PrivAccount, privAccs []*acm.PrivAccount) []types.Tx { + txs := make([]types.Tx, nTxs) + for i := 0; i < nTxs; i++ { + if _, ok := notInvalidNotIncluded[i]; ok { + txs[i] = newSendTx(t, mempool, lastAcc, someAddr, 10) + } else { + txs[i] = newSendTx(t, mempool, privAccs[i%len(privAccs)], privAccs[(i+1)%len(privAccs)].Address, 5) + } + } + return txs +} + +func makeBlock(mempool *Mempool) *types.Block { + txs := mempool.GetProposalTxs() + var includedTxs []types.Tx + for _, rid := range TestResetInfoData.Included { + includedTxs = append(includedTxs, txs[rid.Start:rid.Start+rid.Length]...) + } + + mempool.mtx.Lock() + state := mempool.state + state.LastBlockHeight += 1 + mempool.mtx.Unlock() + return &types.Block{ + Header: &types.Header{ + ChainID: state.ChainID, + Height: state.LastBlockHeight, + NumTxs: len(includedTxs), + }, + Data: &types.Data{ + Txs: includedTxs, + }, + } +} + +// Add txs. Grab chunks to put in block. All the others become invalid because of nonce errors except those in notInvalidNotIncluded +func TestResetInfo(t *testing.T) { + amtPerAccount := int64(100000) + state, privAccs, _ := sm.RandGenesisState(6, false, amtPerAccount, 1, true, 100) + + mempool := NewMempool(state) + + lastAcc := privAccs[5] // we save him (his tx wont become invalid) + privAccs = privAccs[:5] + + txs := addTxs(t, mempool, lastAcc, privAccs) + + // its actually an invalid block since we're skipping nonces + // but all we care about is how the mempool responds after + block := makeBlock(mempool) + + mempool.ResetForBlockAndState(block, state) + + ri := mempool.resetInfo + + if len(ri.Included) != len(TestResetInfoData.Included) { + t.Fatalf("invalid number of included ranges. Got %d, expected %d\n", len(ri.Included), len(TestResetInfoData.Included)) + } + + if len(ri.Invalid) != len(TestResetInfoData.Invalid) { + t.Fatalf("invalid number of invalid ranges. Got %d, expected %d\n", len(ri.Invalid), len(TestResetInfoData.Invalid)) + } + + for i, rid := range ri.Included { + inc := TestResetInfoData.Included[i] + if rid.Start != inc.Start { + t.Fatalf("Invalid start of range. Got %d, expected %d\n", inc.Start, rid.Start) + } + if rid.Length != inc.Length { + t.Fatalf("Invalid length of range. Got %d, expected %d\n", inc.Length, rid.Length) + } + } + + txs = mempool.GetProposalTxs() + if len(txs) != len(notInvalidNotIncluded) { + t.Fatalf("Expected %d txs left in mempool. Got %d", len(notInvalidNotIncluded), len(txs)) + } +} + +//------------------------------------------------------------------------------------------ + +type TestPeer struct { + sync.Mutex + running bool + height int + + t *testing.T + + received int + txs map[string]int + + timeoutFail int + + done chan int +} + +func newPeer(t *testing.T, state *sm.State) *TestPeer { + return &TestPeer{ + running: true, + height: state.LastBlockHeight, + t: t, + txs: make(map[string]int), + done: make(chan int), + } +} + +func (tp *TestPeer) IsRunning() bool { + tp.Lock() + defer tp.Unlock() + return tp.running +} + +func (tp *TestPeer) SetRunning(running bool) { + tp.Lock() + defer tp.Unlock() + tp.running = running +} + +func (tp *TestPeer) Send(chID byte, msg interface{}) bool { + if tp.timeoutFail > 0 { + time.Sleep(time.Second * time.Duration(tp.timeoutFail)) + return false + } + tx := msg.(*TxMessage).Tx + id := types.TxID(config.GetString("chain_id"), tx) + if _, ok := tp.txs[string(id)]; ok { + tp.t.Fatal("received the same tx twice!") + } + tp.txs[string(id)] = tp.received + tp.received += 1 + tp.done <- tp.received + return true +} + +func (tp *TestPeer) Get(key string) interface{} { + return tp +} + +func (tp *TestPeer) GetHeight() int { + return tp.height +} + +func TestBroadcast(t *testing.T) { + state, privAccs, _ := sm.RandGenesisState(6, false, 10000, 1, true, 100) + mempool := NewMempool(state) + reactor := NewMempoolReactor(mempool) + reactor.Start() + + lastAcc := privAccs[5] // we save him (his tx wont become invalid) + privAccs = privAccs[:5] + + peer := newPeer(t, state) + newBlockChan := make(chan ResetInfo) + tickerChan := make(chan time.Time) + go reactor.broadcastTxRoutine(tickerChan, newBlockChan, peer) + + // we don't broadcast any before updating + fmt.Println("dont broadcast any") + addTxs(t, mempool, lastAcc, privAccs) + block := makeBlock(mempool) + mempool.ResetForBlockAndState(block, state) + newBlockChan <- mempool.resetInfo + peer.height = mempool.resetInfo.Height + tickerChan <- time.Now() + pullTxs(t, peer, len(mempool.txs)) // should have sent whatever txs are left (3) + + toBroadcast := []int{1, 3, 7, 9, 11, 12, 18, 20, 21, 28, 29, 30, 31, 34, 35, 36, 50, 90, 99, 100} + for _, N := range toBroadcast { + peer = resetPeer(t, reactor, mempool, state, tickerChan, newBlockChan, peer) + + // we broadcast N txs before updating + fmt.Println("broadcast", N) + addTxs(t, mempool, lastAcc, privAccs) + txsToSendPerCheck = N + tickerChan <- time.Now() + pullTxs(t, peer, txsToSendPerCheck) // should have sent N txs + block = makeBlock(mempool) + mempool.ResetForBlockAndState(block, state) + newBlockChan <- mempool.resetInfo + peer.height = mempool.resetInfo.Height + txsToSendPerCheck = 100 + tickerChan <- time.Now() + left := len(mempool.txs) + if N > 99 { + left -= 3 + } else if N > 29 { + left -= 2 + } else if N > 28 { + left -= 1 + } + pullTxs(t, peer, left) // should have sent whatever txs are left that havent been sent + } +} + +func pullTxs(t *testing.T, peer *TestPeer, N int) { + timer := time.NewTicker(time.Second * 2) + for i := 0; i < N; i++ { + select { + case <-peer.done: + case <-timer.C: + panic(fmt.Sprintf("invalid number of received messages. Got %d, expected %d\n", i, N)) + } + } + + if N == 0 { + select { + case <-peer.done: + t.Fatalf("should not have sent any more txs") + case <-timer.C: + } + } +} + +func resetPeer(t *testing.T, reactor *MempoolReactor, mempool *Mempool, state *sm.State, tickerChan chan time.Time, newBlockChan chan ResetInfo, peer *TestPeer) *TestPeer { + // reset peer + mempool.txs = []types.Tx{} + mempool.state = state + mempool.cache = sm.NewBlockCache(state) + peer.SetRunning(false) + tickerChan <- time.Now() + peer = newPeer(t, state) + go reactor.broadcastTxRoutine(tickerChan, newBlockChan, peer) + return peer +} diff --git a/mempool/reactor.go b/mempool/reactor.go index bd055c716..8992c466b 100644 --- a/mempool/reactor.go +++ b/mempool/reactor.go @@ -50,7 +50,14 @@ func (memR *MempoolReactor) GetChannels() []*p2p.ChannelDescriptor { // Implements Reactor func (memR *MempoolReactor) AddPeer(peer *p2p.Peer) { // Each peer gets a go routine on which we broadcast transactions in the same order we applied them to our state. - go memR.broadcastTxRoutine(peer) + newBlockChan := make(chan ResetInfo) + memR.evsw.(*events.EventSwitch).AddListenerForEvent("broadcastRoutine:"+peer.Key, types.EventStringNewBlock(), func(data types.EventData) { + // no lock needed because consensus is blocking on this + // and the mempool is reset before this event fires + newBlockChan <- memR.Mempool.resetInfo + }) + timer := time.NewTicker(time.Millisecond * time.Duration(checkExecutedTxsMilliseconds)) + go memR.broadcastTxRoutine(timer.C, newBlockChan, peer) } // Implements Reactor @@ -92,29 +99,28 @@ type PeerState interface { GetHeight() int } +type Peer interface { + IsRunning() bool + Send(byte, interface{}) bool + Get(string) interface{} +} + // send new mempool txs to peer, strictly in order we applied them to our state. // new blocks take chunks out of the mempool, but we've already sent some txs to the peer. // so we wait to hear that the peer has progressed to the new height, and then continue sending txs from where we left off -func (memR *MempoolReactor) broadcastTxRoutine(peer *p2p.Peer) { - newBlockChan := make(chan ResetInfo) - memR.evsw.(*events.EventSwitch).AddListenerForEvent("broadcastRoutine:"+peer.Key, types.EventStringNewBlock(), func(data types.EventData) { - // no lock needed because consensus is blocking on this - // and the mempool is reset before this event fires - newBlockChan <- memR.Mempool.resetInfo - }) - timer := time.NewTicker(time.Millisecond * time.Duration(checkExecutedTxsMilliseconds)) - currentHeight := memR.Mempool.state.LastBlockHeight +func (memR *MempoolReactor) broadcastTxRoutine(tickerChan <-chan time.Time, newBlockChan chan ResetInfo, peer Peer) { + currentHeight := memR.Mempool.GetHeight() var nTxs, txsSent int var txs []types.Tx for { select { - case <-timer.C: + case <-tickerChan: if !peer.IsRunning() { return } // make sure the peer is up to date - peerState := peer.Data.Get(types.PeerStateKey).(PeerState) + peerState := peer.Get(types.PeerStateKey).(PeerState) if peerState.GetHeight() < currentHeight { continue } @@ -137,7 +143,7 @@ func (memR *MempoolReactor) broadcastTxRoutine(peer *p2p.Peer) { } if theseTxsSent > 0 { txsSent += theseTxsSent - log.Warn("Sent txs to peer", "ntxs", theseTxsSent, "took", time.Since(start), "total_sent", txsSent, "total_exec", nTxs) + log.Info("Sent txs to peer", "ntxs", theseTxsSent, "took", time.Since(start), "total_sent", txsSent, "total_exec", nTxs) } case ri := <-newBlockChan: @@ -180,8 +186,8 @@ func tallyRangesUpTo(ranger []Range, upTo int) int { if r.Start >= upTo { break } - if r.Start+r.Length-1 > upTo { - totalUpTo += upTo - r.Start - 1 + if r.Start+r.Length >= upTo { + totalUpTo += upTo - r.Start break } totalUpTo += r.Length diff --git a/p2p/peer.go b/p2p/peer.go index a03f8713b..a0d8fd6ce 100644 --- a/p2p/peer.go +++ b/p2p/peer.go @@ -128,3 +128,7 @@ func (p *Peer) String() string { func (p *Peer) Equals(other *Peer) bool { return p.Key == other.Key } + +func (p *Peer) Get(key string) interface{} { + return p.Data.Get(key) +} diff --git a/types/keys.go b/types/keys.go new file mode 100644 index 000000000..3f81e46f1 --- /dev/null +++ b/types/keys.go @@ -0,0 +1,5 @@ +package types + +var ( + PeerStateKey = "ConsensusReactor.peerState" +)