635 lines
16 KiB
Go
Raw Normal View History

blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
2019-07-23 10:58:52 +02:00
package v0
2015-03-22 03:30:22 -07:00
import (
"errors"
"fmt"
"math"
2015-03-24 11:02:30 -07:00
"sync"
"sync/atomic"
2015-03-22 03:30:22 -07:00
"time"
2018-07-01 22:36:49 -04:00
cmn "github.com/tendermint/tendermint/libs/common"
flow "github.com/tendermint/tendermint/libs/flowrate"
"github.com/tendermint/tendermint/libs/log"
2018-01-03 11:29:19 +01:00
"github.com/tendermint/tendermint/p2p"
"github.com/tendermint/tendermint/types"
2015-03-22 03:30:22 -07:00
)
/*
eg, L = latency = 0.1s
P = num peers = 10
FN = num full nodes
BS = 1kB block size
CB = 1 Mbit/s = 128 kB/s
CB/P = 12.8 kB
B/S = CB/P/BS = 12.8 blocks/s
12.8 * 0.1 = 1.28 blocks on conn
*/
2015-03-22 03:30:22 -07:00
const (
requestIntervalMS = 2
maxTotalRequesters = 600
maxPendingRequests = maxTotalRequesters
maxPendingRequestsPerPeer = 20
// Minimum recv rate to ensure we're receiving blocks from a peer fast
// enough. If a peer is not sending us data at at least that rate, we
// consider them to have timedout and we disconnect.
//
// Assuming a DSL connection (not a good choice) 128 Kbps (upload) ~ 15 KB/s,
// sending data across atlantic ~ 7.5 KB/s.
minRecvRate = 7680
// Maximum difference between current and new block's height.
maxDiffBetweenCurrentAndReceivedBlockHeight = 100
2015-03-22 19:20:54 -07:00
)
var peerTimeout = 15 * time.Second // not const so we can override with tests
/*
2015-07-10 15:39:49 +00:00
Peers self report their heights when we join the block pool.
Starting from our latest pool.height, we request blocks
in sequence from peers that reported higher heights than ours.
Every so often we ask peers what height they're on so we can keep going.
2017-01-13 13:16:50 +04:00
Requests are continuously made for blocks of higher heights until
2017-06-28 11:12:45 -04:00
the limit is reached. If most of the requests have no available peers, and we
are not at peer limits, we can probably switch to consensus reactor
*/
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
2019-07-23 10:58:52 +02:00
// BlockPool keeps track of the fast sync peers, block requests and block responses.
2015-03-22 03:30:22 -07:00
type BlockPool struct {
2017-10-04 16:40:45 -04:00
cmn.BaseService
2015-09-11 19:00:27 -07:00
startTime time.Time
2016-06-28 18:02:27 -07:00
mtx sync.Mutex
2015-03-24 11:02:30 -07:00
// block requests
requesters map[int64]*bpRequester
height int64 // the lowest key in requesters.
2015-03-24 11:02:30 -07:00
// peers
2018-01-01 21:27:38 -05:00
peers map[p2p.ID]*bpPeer
maxPeerHeight int64 // the biggest reported height
2015-03-24 11:02:30 -07:00
// atomic
numPending int32 // number of requests pending assignment or block response
2015-03-24 11:02:30 -07:00
requestsCh chan<- BlockRequest
errorsCh chan<- peerError
2015-03-22 03:30:22 -07:00
}
// NewBlockPool returns a new BlockPool with the height equal to start. Block
// requests and errors will be sent to requestsCh and errorsCh accordingly.
func NewBlockPool(start int64, requestsCh chan<- BlockRequest, errorsCh chan<- peerError) *BlockPool {
bp := &BlockPool{
2018-01-01 21:27:38 -05:00
peers: make(map[p2p.ID]*bpPeer),
2015-03-24 11:02:30 -07:00
requesters: make(map[int64]*bpRequester),
height: start,
numPending: 0,
2015-03-22 03:30:22 -07:00
requestsCh: requestsCh,
errorsCh: errorsCh,
2015-03-22 03:30:22 -07:00
}
2017-10-04 16:40:45 -04:00
bp.BaseService = *cmn.NewBaseService(nil, "BlockPool", bp)
return bp
2015-03-22 03:30:22 -07:00
}
// OnStart implements cmn.Service by spawning requesters routine and recording
// pool's start time.
func (pool *BlockPool) OnStart() error {
go pool.makeRequestersRoutine()
2015-09-11 19:00:27 -07:00
pool.startTime = time.Now()
return nil
2015-03-22 03:30:22 -07:00
}
// spawns requesters as needed
func (pool *BlockPool) makeRequestersRoutine() {
2015-03-22 03:30:22 -07:00
for {
if !pool.IsRunning() {
break
2015-03-24 11:02:30 -07:00
}
2016-06-24 20:21:44 -04:00
_, numPending, lenRequesters := pool.GetStatus()
2019-08-02 08:53:52 +02:00
switch {
case numPending >= maxPendingRequests:
2015-03-24 11:02:30 -07:00
// sleep for a bit.
time.Sleep(requestIntervalMS * time.Millisecond)
2015-09-09 21:44:48 -07:00
// check for timed out peers
pool.removeTimedoutPeers()
2019-08-02 08:53:52 +02:00
case lenRequesters >= maxTotalRequesters:
2015-03-24 11:02:30 -07:00
// sleep for a bit.
time.Sleep(requestIntervalMS * time.Millisecond)
2015-09-09 21:44:48 -07:00
// check for timed out peers
pool.removeTimedoutPeers()
2019-08-02 08:53:52 +02:00
default:
2015-03-24 11:02:30 -07:00
// request for more blocks.
pool.makeNextRequester()
2015-03-22 03:30:22 -07:00
}
}
}
2015-09-09 21:44:48 -07:00
func (pool *BlockPool) removeTimedoutPeers() {
2016-06-28 18:02:27 -07:00
pool.mtx.Lock()
defer pool.mtx.Unlock()
2015-09-09 21:44:48 -07:00
for _, peer := range pool.peers {
if !peer.didTimeout && peer.numPending > 0 {
curRate := peer.recvMonitor.Status().CurRate
2018-02-09 13:02:44 +04:00
// curRate can be 0 on start
if curRate != 0 && curRate < minRecvRate {
err := errors.New("peer is not sending us data fast enough")
pool.sendError(err, peer.id)
pool.Logger.Error("SendTimeout", "peer", peer.id,
"reason", err,
"curRate", fmt.Sprintf("%d KB/s", curRate/1024),
"minRate", fmt.Sprintf("%d KB/s", minRecvRate/1024))
2015-09-09 21:44:48 -07:00
peer.didTimeout = true
}
}
if peer.didTimeout {
pool.removePeer(peer.id)
}
}
}
// GetStatus returns pool's height, numPending requests and the number of
// requesters.
func (pool *BlockPool) GetStatus() (height int64, numPending int32, lenRequesters int) {
2016-06-28 18:02:27 -07:00
pool.mtx.Lock()
defer pool.mtx.Unlock()
return pool.height, atomic.LoadInt32(&pool.numPending), len(pool.requesters)
}
// IsCaughtUp returns true if this node is caught up, false - otherwise.
// TODO: relax conditions, prevent abuse.
func (pool *BlockPool) IsCaughtUp() bool {
2016-06-28 18:02:27 -07:00
pool.mtx.Lock()
defer pool.mtx.Unlock()
2016-06-24 20:21:44 -04:00
2016-01-02 16:21:40 -08:00
// Need at least 1 peer to be considered caught up.
if len(pool.peers) == 0 {
2017-05-02 11:53:32 +04:00
pool.Logger.Debug("Blockpool has no peers")
2016-01-02 16:21:40 -08:00
return false
}
// Some conditions to determine if we're caught up.
// Ensures we've either received a block or waited some amount of time,
// and that we're synced to the highest known height.
// Note we use maxPeerHeight - 1 because to sync block H requires block H+1
// to verify the LastCommit.
receivedBlockOrTimedOut := pool.height > 0 || time.Since(pool.startTime) > 5*time.Second
ourChainIsLongestAmongPeers := pool.maxPeerHeight == 0 || pool.height >= (pool.maxPeerHeight-1)
2017-06-23 22:34:38 -04:00
isCaughtUp := receivedBlockOrTimedOut && ourChainIsLongestAmongPeers
2016-02-07 16:56:59 -08:00
return isCaughtUp
2015-03-24 11:02:30 -07:00
}
2015-03-22 16:23:24 -07:00
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
2019-07-23 10:58:52 +02:00
// PeekTwoBlocks returns blocks at pool.height and pool.height+1.
2016-04-02 09:10:16 -07:00
// We need to see the second block's Commit to validate the first block.
2015-03-24 11:02:30 -07:00
// So we peek two blocks at a time.
2016-04-02 09:10:16 -07:00
// The caller will verify the commit.
func (pool *BlockPool) PeekTwoBlocks() (first *types.Block, second *types.Block) {
2016-06-28 18:02:27 -07:00
pool.mtx.Lock()
defer pool.mtx.Unlock()
2015-03-24 11:02:30 -07:00
if r := pool.requesters[pool.height]; r != nil {
2015-09-12 08:47:59 -07:00
first = r.getBlock()
2015-03-24 11:02:30 -07:00
}
if r := pool.requesters[pool.height+1]; r != nil {
2015-09-12 08:47:59 -07:00
second = r.getBlock()
2015-03-22 03:30:22 -07:00
}
2015-03-24 11:02:30 -07:00
return
2015-03-22 03:30:22 -07:00
}
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
2019-07-23 10:58:52 +02:00
// PopRequest pops the first block at pool.height.
2016-04-02 09:10:16 -07:00
// It must have been validated by 'second'.Commit from PeekTwoBlocks().
func (pool *BlockPool) PopRequest() {
2016-06-28 18:02:27 -07:00
pool.mtx.Lock()
defer pool.mtx.Unlock()
2015-03-24 11:02:30 -07:00
if r := pool.requesters[pool.height]; r != nil {
/* The block can disappear at any time, due to removePeer().
if r := pool.requesters[pool.height]; r == nil || r.block == nil {
PanicSanity("PopRequest() requires a valid block")
}
*/
r.Stop()
delete(pool.requesters, pool.height)
pool.height++
} else {
2018-02-26 17:33:55 +04:00
panic(fmt.Sprintf("Expected requester to pop, got nothing at height %v", pool.height))
2015-03-22 03:30:22 -07:00
}
2015-03-22 12:46:53 -07:00
}
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
2019-07-23 10:58:52 +02:00
// RedoRequest invalidates the block at pool.height,
// Remove the peer and redo request from others.
// Returns the ID of the removed peer.
func (pool *BlockPool) RedoRequest(height int64) p2p.ID {
2016-06-28 18:02:27 -07:00
pool.mtx.Lock()
defer pool.mtx.Unlock()
request := pool.requesters[height]
peerID := request.getPeerID()
if peerID != p2p.ID("") {
// RemovePeer will redo all requesters associated with this peer.
pool.removePeer(peerID)
2015-03-22 03:30:22 -07:00
}
return peerID
2015-03-22 03:30:22 -07:00
}
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
2019-07-23 10:58:52 +02:00
// AddBlock validates that the block comes from the peer it was expected from and calls the requester to store it.
// TODO: ensure that blocks come in order for each peer.
2018-01-01 21:27:38 -05:00
func (pool *BlockPool) AddBlock(peerID p2p.ID, block *types.Block, blockSize int) {
2016-06-28 18:02:27 -07:00
pool.mtx.Lock()
defer pool.mtx.Unlock()
2015-03-24 11:02:30 -07:00
requester := pool.requesters[block.Height]
if requester == nil {
pool.Logger.Info("peer sent us a block we didn't expect", "peer", peerID, "curHeight", pool.height, "blockHeight", block.Height)
diff := pool.height - block.Height
if diff < 0 {
diff *= -1
}
if diff > maxDiffBetweenCurrentAndReceivedBlockHeight {
pool.sendError(errors.New("peer sent us a block we didn't expect with a height too far ahead/behind"), peerID)
}
2015-03-24 11:02:30 -07:00
return
2015-03-22 12:46:53 -07:00
}
if requester.setBlock(block, peerID) {
atomic.AddInt32(&pool.numPending, -1)
2016-06-28 18:02:27 -07:00
peer := pool.peers[peerID]
fix invalid memory address or nil pointer dereference error (Refs #762) https://github.com/tendermint/tendermint/issues/762#issuecomment-338276055 ``` E[10-19|04:52:38.969] Stopping peer for error module=p2p peer="Peer{MConn{178.62.46.14:46656} B14916FAF38A out}" err="Error: runtime error: invalid memory address or nil pointer dereference\nStack: goroutine 529485 [running]:\nruntime/debug.Stack(0xc4355cfb38, 0xb463e0, 0x11b1c30)\n\t/usr/local/go/src/runtime/debug/stack.go:24 +0xa7\ngithub.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/p2p.(*MConnection)._recover(0xc439a28870)\n\t/home/ubuntu/go/src/github.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/p2p/connection.go:206 +0x6e\npanic(0xb463e0, 0x11b1c30)\n\t/usr/local/go/src/runtime/panic.go:491 +0x283\ngithub.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/blockchain.(*bpPeer).decrPending(0x0, 0x381)\n\t/home/ubuntu/go/src/github.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/blockchain/pool.go:376 +0x22\ngithub.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/blockchain.(*BlockPool).AddBlock(0xc4200e4000, 0xc4266d1f00, 0x40, 0xc432ac9640, 0x381)\n\t/home/ubuntu/go/src/github.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/blockchain/pool.go:215 +0x139\ngithub.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/blockchain.(*BlockchainReactor).Receive(0xc42050a780, 0xc420257740, 0x1171be0, 0xc42ff302d0, 0xc4384b2000, 0x381, 0x1000)\n\t/home/ubuntu/go/src/github.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/blockchain/reactor.go:160 +0x712\ngithub.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/p2p.createMConnection.func1(0x11e5040, 0xc4384b2000, 0x381, 0x1000)\n\t/home/ubuntu/go/src/github.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/p2p/peer.go:334 +0xbd\ngithub.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/p2p.(*MConnection).recvRoutine(0xc439a28870)\n\t/home/ubuntu/go/src/github.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/p2p/connection.go:475 +0x4a3\ncreated by github.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/p2p.(*MConnection).OnStart\n\t/home/ubuntu/go/src/github.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/p2p/connection.go:170 +0x187\n" ```
2017-10-20 21:56:10 +04:00
if peer != nil {
peer.decrPending(blockSize)
}
2017-06-23 21:36:47 -04:00
} else {
pool.Logger.Info("invalid peer", "peer", peerID, "blockHeight", block.Height)
pool.sendError(errors.New("invalid peer"), peerID)
2017-06-23 21:36:47 -04:00
}
}
// MaxPeerHeight returns the highest reported height.
func (pool *BlockPool) MaxPeerHeight() int64 {
pool.mtx.Lock()
defer pool.mtx.Unlock()
return pool.maxPeerHeight
}
// SetPeerHeight sets the peer's alleged blockchain height.
2018-01-01 21:27:38 -05:00
func (pool *BlockPool) SetPeerHeight(peerID p2p.ID, height int64) {
2016-06-28 18:02:27 -07:00
pool.mtx.Lock()
defer pool.mtx.Unlock()
2015-03-24 11:02:30 -07:00
peer := pool.peers[peerID]
if peer != nil {
peer.height = height
} else {
peer = newBPPeer(pool, peerID, height)
2017-05-02 11:53:32 +04:00
peer.setLogger(pool.Logger.With("peer", peerID))
pool.peers[peerID] = peer
2015-03-24 11:02:30 -07:00
}
if height > pool.maxPeerHeight {
pool.maxPeerHeight = height
}
2015-03-24 11:02:30 -07:00
}
// RemovePeer removes the peer with peerID from the pool. If there's no peer
// with peerID, function is a no-op.
2018-01-01 21:27:38 -05:00
func (pool *BlockPool) RemovePeer(peerID p2p.ID) {
2016-06-28 18:02:27 -07:00
pool.mtx.Lock()
defer pool.mtx.Unlock()
2015-03-24 11:02:30 -07:00
pool.removePeer(peerID)
2015-03-22 12:46:53 -07:00
}
2018-01-01 21:27:38 -05:00
func (pool *BlockPool) removePeer(peerID p2p.ID) {
for _, requester := range pool.requesters {
if requester.getPeerID() == peerID {
requester.redo(peerID)
2015-03-22 12:46:53 -07:00
}
}
peer, ok := pool.peers[peerID]
if ok {
if peer.timeout != nil {
peer.timeout.Stop()
}
delete(pool.peers, peerID)
// Find a new peer with the biggest height and update maxPeerHeight if the
// peer's height was the biggest.
if peer.height == pool.maxPeerHeight {
pool.updateMaxPeerHeight()
}
}
}
// If no peers are left, maxPeerHeight is set to 0.
func (pool *BlockPool) updateMaxPeerHeight() {
var max int64
for _, peer := range pool.peers {
if peer.height > max {
max = peer.height
}
}
pool.maxPeerHeight = max
2015-03-22 12:46:53 -07:00
}
2015-03-24 11:02:30 -07:00
// Pick an available peer with at least the given minHeight.
// If no peers are available, returns nil.
func (pool *BlockPool) pickIncrAvailablePeer(minHeight int64) *bpPeer {
2016-06-28 18:02:27 -07:00
pool.mtx.Lock()
defer pool.mtx.Unlock()
2015-03-24 11:02:30 -07:00
for _, peer := range pool.peers {
2016-06-28 18:02:27 -07:00
if peer.didTimeout {
pool.removePeer(peer.id)
continue
}
if peer.numPending >= maxPendingRequestsPerPeer {
2015-03-24 11:02:30 -07:00
continue
}
if peer.height < minHeight {
continue
}
2016-06-28 18:02:27 -07:00
peer.incrPending()
2015-03-24 11:02:30 -07:00
return peer
2015-03-22 03:30:22 -07:00
}
2015-03-24 11:02:30 -07:00
return nil
2015-03-22 03:30:22 -07:00
}
func (pool *BlockPool) makeNextRequester() {
2016-06-28 18:02:27 -07:00
pool.mtx.Lock()
defer pool.mtx.Unlock()
2015-03-22 03:30:22 -07:00
2017-11-30 13:08:38 -06:00
nextHeight := pool.height + pool.requestersLen()
if nextHeight > pool.maxPeerHeight {
return
}
request := newBPRequester(pool, nextHeight)
2015-03-24 11:02:30 -07:00
pool.requesters[nextHeight] = request
atomic.AddInt32(&pool.numPending, 1)
err := request.Start()
2017-09-06 13:11:47 -04:00
if err != nil {
2017-10-03 18:12:17 -04:00
request.Logger.Error("Error starting request", "err", err)
2017-09-06 13:11:47 -04:00
}
2015-03-22 03:30:22 -07:00
}
func (pool *BlockPool) requestersLen() int64 {
return int64(len(pool.requesters))
2017-11-30 13:08:38 -06:00
}
2018-01-01 21:27:38 -05:00
func (pool *BlockPool) sendRequest(height int64, peerID p2p.ID) {
if !pool.IsRunning() {
2015-03-24 11:02:30 -07:00
return
2015-03-22 03:30:22 -07:00
}
pool.requestsCh <- BlockRequest{height, peerID}
2015-03-22 03:30:22 -07:00
}
func (pool *BlockPool) sendError(err error, peerID p2p.ID) {
if !pool.IsRunning() {
2015-03-24 11:02:30 -07:00
return
}
pool.errorsCh <- peerError{err, peerID}
2015-03-24 11:02:30 -07:00
}
2019-02-06 15:16:38 +04:00
// for debugging purposes
2019-02-06 18:20:10 +04:00
//nolint:unused
func (pool *BlockPool) debug() string {
pool.mtx.Lock()
defer pool.mtx.Unlock()
str := ""
nextHeight := pool.height + pool.requestersLen()
for h := pool.height; h < nextHeight; h++ {
if pool.requesters[h] == nil {
str += fmt.Sprintf("H(%v):X ", h)
} else {
str += fmt.Sprintf("H(%v):", h)
str += fmt.Sprintf("B?(%v) ", pool.requesters[h].block != nil)
}
}
return str
}
2015-03-22 03:30:22 -07:00
//-------------------------------------
2015-03-24 11:02:30 -07:00
type bpPeer struct {
didTimeout bool
numPending int32
height int64
pool *BlockPool
2018-01-01 21:27:38 -05:00
id p2p.ID
recvMonitor *flow.Monitor
2016-06-28 18:02:27 -07:00
timeout *time.Timer
2017-05-02 11:53:32 +04:00
logger log.Logger
2015-03-22 03:30:22 -07:00
}
2018-01-01 21:27:38 -05:00
func newBPPeer(pool *BlockPool, peerID p2p.ID, height int64) *bpPeer {
peer := &bpPeer{
pool: pool,
id: peerID,
height: height,
numPending: 0,
2017-05-02 11:53:32 +04:00
logger: log.NewNopLogger(),
}
return peer
}
2017-05-02 11:53:32 +04:00
func (peer *bpPeer) setLogger(l log.Logger) {
peer.logger = l
}
2015-09-12 08:47:59 -07:00
func (peer *bpPeer) resetMonitor() {
peer.recvMonitor = flow.New(time.Second, time.Second*40)
2017-09-11 15:45:12 -04:00
initialValue := float64(minRecvRate) * math.E
2015-09-12 08:47:59 -07:00
peer.recvMonitor.SetREMA(initialValue)
}
2016-06-28 18:02:27 -07:00
func (peer *bpPeer) resetTimeout() {
2015-09-12 08:47:59 -07:00
if peer.timeout == nil {
peer.timeout = time.AfterFunc(peerTimeout, peer.onTimeout)
} else {
peer.timeout.Reset(peerTimeout)
}
}
2016-06-28 18:02:27 -07:00
func (peer *bpPeer) incrPending() {
2015-09-12 08:47:59 -07:00
if peer.numPending == 0 {
peer.resetMonitor()
2016-06-28 18:02:27 -07:00
peer.resetTimeout()
}
2015-09-12 08:47:59 -07:00
peer.numPending++
}
2016-06-28 18:02:27 -07:00
func (peer *bpPeer) decrPending(recvSize int) {
2015-09-12 08:47:59 -07:00
peer.numPending--
if peer.numPending == 0 {
peer.timeout.Stop()
} else {
2015-09-12 08:47:59 -07:00
peer.recvMonitor.Update(recvSize)
2016-06-28 18:02:27 -07:00
peer.resetTimeout()
}
}
2015-09-12 08:47:59 -07:00
func (peer *bpPeer) onTimeout() {
2016-06-28 18:02:27 -07:00
peer.pool.mtx.Lock()
defer peer.pool.mtx.Unlock()
err := errors.New("peer did not send us anything")
peer.pool.sendError(err, peer.id)
peer.logger.Error("SendTimeout", "reason", err, "timeout", peerTimeout)
2015-09-12 08:47:59 -07:00
peer.didTimeout = true
}
2015-03-24 11:02:30 -07:00
//-------------------------------------
type bpRequester struct {
2017-10-04 16:40:45 -04:00
cmn.BaseService
pool *BlockPool
height int64
gotBlockCh chan struct{}
redoCh chan p2p.ID //redo may send multitime, add peerId to identify repeat
mtx sync.Mutex
2018-01-01 21:27:38 -05:00
peerID p2p.ID
block *types.Block
}
func newBPRequester(pool *BlockPool, height int64) *bpRequester {
bpr := &bpRequester{
pool: pool,
height: height,
gotBlockCh: make(chan struct{}, 1),
redoCh: make(chan p2p.ID, 1),
peerID: "",
block: nil,
}
2017-10-04 16:40:45 -04:00
bpr.BaseService = *cmn.NewBaseService(nil, "bpRequester", bpr)
return bpr
}
func (bpr *bpRequester) OnStart() error {
go bpr.requestRoutine()
return nil
}
// Returns true if the peer matches and block doesn't already exist.
2018-01-01 21:27:38 -05:00
func (bpr *bpRequester) setBlock(block *types.Block, peerID p2p.ID) bool {
bpr.mtx.Lock()
if bpr.block != nil || bpr.peerID != peerID {
bpr.mtx.Unlock()
return false
}
bpr.block = block
bpr.mtx.Unlock()
select {
case bpr.gotBlockCh <- struct{}{}:
default:
}
return true
}
2015-09-12 08:47:59 -07:00
func (bpr *bpRequester) getBlock() *types.Block {
bpr.mtx.Lock()
defer bpr.mtx.Unlock()
return bpr.block
}
2018-01-01 21:27:38 -05:00
func (bpr *bpRequester) getPeerID() p2p.ID {
bpr.mtx.Lock()
defer bpr.mtx.Unlock()
return bpr.peerID
}
// This is called from the requestRoutine, upon redo().
func (bpr *bpRequester) reset() {
bpr.mtx.Lock()
defer bpr.mtx.Unlock()
if bpr.block != nil {
atomic.AddInt32(&bpr.pool.numPending, 1)
}
bpr.peerID = ""
bpr.block = nil
}
// Tells bpRequester to pick another peer and try again.
// NOTE: Nonblocking, and does nothing if another redo
// was already requested.
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
2019-07-23 10:58:52 +02:00
func (bpr *bpRequester) redo(peerID p2p.ID) {
select {
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
2019-07-23 10:58:52 +02:00
case bpr.redoCh <- peerID:
default:
}
}
2015-03-24 11:02:30 -07:00
// Responsible for making more requests as necessary
// Returns only when a block is found (e.g. AddBlock() is called)
func (bpr *bpRequester) requestRoutine() {
OUTER_LOOP:
2015-03-24 11:02:30 -07:00
for {
// Pick a peer to send request to.
2018-01-03 11:29:19 +01:00
var peer *bpPeer
PICK_PEER_LOOP:
2015-03-24 11:02:30 -07:00
for {
if !bpr.IsRunning() || !bpr.pool.IsRunning() {
2015-03-24 11:02:30 -07:00
return
}
peer = bpr.pool.pickIncrAvailablePeer(bpr.height)
2015-03-24 11:02:30 -07:00
if peer == nil {
2015-07-19 21:49:13 +00:00
//log.Info("No peers available", "height", height)
2015-03-24 11:02:30 -07:00
time.Sleep(requestIntervalMS * time.Millisecond)
continue PICK_PEER_LOOP
2015-03-24 11:02:30 -07:00
}
break PICK_PEER_LOOP
2015-03-24 11:02:30 -07:00
}
bpr.mtx.Lock()
bpr.peerID = peer.id
bpr.mtx.Unlock()
// Send request and wait.
bpr.pool.sendRequest(bpr.height, peer.id)
WAIT_LOOP:
for {
select {
case <-bpr.pool.Quit():
bpr.Stop()
2015-03-24 11:02:30 -07:00
return
case <-bpr.Quit():
2015-03-24 11:02:30 -07:00
return
case peerID := <-bpr.redoCh:
if peerID == bpr.peerID {
bpr.reset()
continue OUTER_LOOP
} else {
continue WAIT_LOOP
}
case <-bpr.gotBlockCh:
// We got a block!
// Continue the for-loop and wait til Quit.
continue WAIT_LOOP
2015-03-24 11:02:30 -07:00
}
}
}
}
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
2019-07-23 10:58:52 +02:00
// BlockRequest stores a block request identified by the block Height and the PeerID responsible for
// delivering the block
2015-03-24 11:02:30 -07:00
type BlockRequest struct {
Height int64
2018-01-01 21:27:38 -05:00
PeerID p2p.ID
2015-03-22 03:30:22 -07:00
}