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.

579 lines
14 KiB

7 years ago
7 years ago
8 years ago
7 years ago
9 years ago
9 years ago
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" ```
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. package blockchain
  2. import (
  3. "errors"
  4. "fmt"
  5. "math"
  6. "sync"
  7. "time"
  8. cmn "github.com/tendermint/tmlibs/common"
  9. flow "github.com/tendermint/tmlibs/flowrate"
  10. "github.com/tendermint/tmlibs/log"
  11. "github.com/tendermint/tendermint/p2p"
  12. "github.com/tendermint/tendermint/types"
  13. )
  14. /*
  15. eg, L = latency = 0.1s
  16. P = num peers = 10
  17. FN = num full nodes
  18. BS = 1kB block size
  19. CB = 1 Mbit/s = 128 kB/s
  20. CB/P = 12.8 kB
  21. B/S = CB/P/BS = 12.8 blocks/s
  22. 12.8 * 0.1 = 1.28 blocks on conn
  23. */
  24. const (
  25. requestIntervalMS = 100
  26. maxTotalRequesters = 1000
  27. maxPendingRequests = maxTotalRequesters
  28. maxPendingRequestsPerPeer = 50
  29. // Minimum recv rate to ensure we're receiving blocks from a peer fast
  30. // enough. If a peer is not sending us data at at least that rate, we
  31. // consider them to have timedout and we disconnect.
  32. //
  33. // Assuming a DSL connection (not a good choice) 128 Kbps (upload) ~ 15 KB/s,
  34. // sending data across atlantic ~ 7.5 KB/s.
  35. minRecvRate = 7680
  36. // Maximum difference between current and new block's height.
  37. maxDiffBetweenCurrentAndReceivedBlockHeight = 100
  38. )
  39. var peerTimeout = 15 * time.Second // not const so we can override with tests
  40. /*
  41. Peers self report their heights when we join the block pool.
  42. Starting from our latest pool.height, we request blocks
  43. in sequence from peers that reported higher heights than ours.
  44. Every so often we ask peers what height they're on so we can keep going.
  45. Requests are continuously made for blocks of higher heights until
  46. the limit is reached. If most of the requests have no available peers, and we
  47. are not at peer limits, we can probably switch to consensus reactor
  48. */
  49. type BlockPool struct {
  50. cmn.BaseService
  51. startTime time.Time
  52. mtx sync.Mutex
  53. // block requests
  54. requesters map[int64]*bpRequester
  55. height int64 // the lowest key in requesters.
  56. numPending int32 // number of requests pending assignment or block response
  57. // peers
  58. peers map[p2p.ID]*bpPeer
  59. maxPeerHeight int64
  60. requestsCh chan<- BlockRequest
  61. errorsCh chan<- peerError
  62. }
  63. func NewBlockPool(start int64, requestsCh chan<- BlockRequest, errorsCh chan<- peerError) *BlockPool {
  64. bp := &BlockPool{
  65. peers: make(map[p2p.ID]*bpPeer),
  66. requesters: make(map[int64]*bpRequester),
  67. height: start,
  68. numPending: 0,
  69. requestsCh: requestsCh,
  70. errorsCh: errorsCh,
  71. }
  72. bp.BaseService = *cmn.NewBaseService(nil, "BlockPool", bp)
  73. return bp
  74. }
  75. func (pool *BlockPool) OnStart() error {
  76. go pool.makeRequestersRoutine()
  77. pool.startTime = time.Now()
  78. return nil
  79. }
  80. func (pool *BlockPool) OnStop() {}
  81. // Run spawns requesters as needed.
  82. func (pool *BlockPool) makeRequestersRoutine() {
  83. for {
  84. if !pool.IsRunning() {
  85. break
  86. }
  87. _, numPending, lenRequesters := pool.GetStatus()
  88. if numPending >= maxPendingRequests {
  89. // sleep for a bit.
  90. time.Sleep(requestIntervalMS * time.Millisecond)
  91. // check for timed out peers
  92. pool.removeTimedoutPeers()
  93. } else if lenRequesters >= maxTotalRequesters {
  94. // sleep for a bit.
  95. time.Sleep(requestIntervalMS * time.Millisecond)
  96. // check for timed out peers
  97. pool.removeTimedoutPeers()
  98. } else {
  99. // request for more blocks.
  100. pool.makeNextRequester()
  101. }
  102. }
  103. }
  104. func (pool *BlockPool) removeTimedoutPeers() {
  105. pool.mtx.Lock()
  106. defer pool.mtx.Unlock()
  107. for _, peer := range pool.peers {
  108. if !peer.didTimeout && peer.numPending > 0 {
  109. curRate := peer.recvMonitor.Status().CurRate
  110. // curRate can be 0 on start
  111. if curRate != 0 && curRate < minRecvRate {
  112. err := errors.New("peer is not sending us data fast enough")
  113. pool.sendError(err, peer.id)
  114. pool.Logger.Error("SendTimeout", "peer", peer.id,
  115. "reason", err,
  116. "curRate", fmt.Sprintf("%d KB/s", curRate/1024),
  117. "minRate", fmt.Sprintf("%d KB/s", minRecvRate/1024))
  118. peer.didTimeout = true
  119. }
  120. }
  121. if peer.didTimeout {
  122. pool.removePeer(peer.id)
  123. }
  124. }
  125. }
  126. func (pool *BlockPool) GetStatus() (height int64, numPending int32, lenRequesters int) {
  127. pool.mtx.Lock()
  128. defer pool.mtx.Unlock()
  129. return pool.height, pool.numPending, len(pool.requesters)
  130. }
  131. // TODO: relax conditions, prevent abuse.
  132. func (pool *BlockPool) IsCaughtUp() bool {
  133. pool.mtx.Lock()
  134. defer pool.mtx.Unlock()
  135. // Need at least 1 peer to be considered caught up.
  136. if len(pool.peers) == 0 {
  137. pool.Logger.Debug("Blockpool has no peers")
  138. return false
  139. }
  140. // some conditions to determine if we're caught up
  141. receivedBlockOrTimedOut := (pool.height > 0 || time.Since(pool.startTime) > 5*time.Second)
  142. ourChainIsLongestAmongPeers := pool.maxPeerHeight == 0 || pool.height >= pool.maxPeerHeight
  143. isCaughtUp := receivedBlockOrTimedOut && ourChainIsLongestAmongPeers
  144. return isCaughtUp
  145. }
  146. // We need to see the second block's Commit to validate the first block.
  147. // So we peek two blocks at a time.
  148. // The caller will verify the commit.
  149. func (pool *BlockPool) PeekTwoBlocks() (first *types.Block, second *types.Block) {
  150. pool.mtx.Lock()
  151. defer pool.mtx.Unlock()
  152. if r := pool.requesters[pool.height]; r != nil {
  153. first = r.getBlock()
  154. }
  155. if r := pool.requesters[pool.height+1]; r != nil {
  156. second = r.getBlock()
  157. }
  158. return
  159. }
  160. // Pop the first block at pool.height
  161. // It must have been validated by 'second'.Commit from PeekTwoBlocks().
  162. func (pool *BlockPool) PopRequest() {
  163. pool.mtx.Lock()
  164. defer pool.mtx.Unlock()
  165. if r := pool.requesters[pool.height]; r != nil {
  166. /* The block can disappear at any time, due to removePeer().
  167. if r := pool.requesters[pool.height]; r == nil || r.block == nil {
  168. PanicSanity("PopRequest() requires a valid block")
  169. }
  170. */
  171. r.Stop()
  172. delete(pool.requesters, pool.height)
  173. pool.height++
  174. } else {
  175. panic(fmt.Sprintf("Expected requester to pop, got nothing at height %v", pool.height))
  176. }
  177. }
  178. // Invalidates the block at pool.height,
  179. // Remove the peer and redo request from others.
  180. // Returns the ID of the removed peer.
  181. func (pool *BlockPool) RedoRequest(height int64) p2p.ID {
  182. pool.mtx.Lock()
  183. defer pool.mtx.Unlock()
  184. request := pool.requesters[height]
  185. if request.block == nil {
  186. panic("Expected block to be non-nil")
  187. }
  188. // RemovePeer will redo all requesters associated with this peer.
  189. pool.removePeer(request.peerID)
  190. return request.peerID
  191. }
  192. // TODO: ensure that blocks come in order for each peer.
  193. func (pool *BlockPool) AddBlock(peerID p2p.ID, block *types.Block, blockSize int) {
  194. pool.mtx.Lock()
  195. defer pool.mtx.Unlock()
  196. requester := pool.requesters[block.Height]
  197. if requester == nil {
  198. pool.Logger.Info("peer sent us a block we didn't expect", "peer", peerID, "curHeight", pool.height, "blockHeight", block.Height)
  199. diff := pool.height - block.Height
  200. if diff < 0 {
  201. diff *= -1
  202. }
  203. if diff > maxDiffBetweenCurrentAndReceivedBlockHeight {
  204. pool.sendError(errors.New("peer sent us a block we didn't expect with a height too far ahead/behind"), peerID)
  205. }
  206. return
  207. }
  208. if requester.setBlock(block, peerID) {
  209. pool.numPending--
  210. peer := pool.peers[peerID]
  211. if peer != nil {
  212. peer.decrPending(blockSize)
  213. }
  214. } else {
  215. // Bad peer?
  216. }
  217. }
  218. // MaxPeerHeight returns the highest height reported by a peer.
  219. func (pool *BlockPool) MaxPeerHeight() int64 {
  220. pool.mtx.Lock()
  221. defer pool.mtx.Unlock()
  222. return pool.maxPeerHeight
  223. }
  224. // Sets the peer's alleged blockchain height.
  225. func (pool *BlockPool) SetPeerHeight(peerID p2p.ID, height int64) {
  226. pool.mtx.Lock()
  227. defer pool.mtx.Unlock()
  228. peer := pool.peers[peerID]
  229. if peer != nil {
  230. peer.height = height
  231. } else {
  232. peer = newBPPeer(pool, peerID, height)
  233. peer.setLogger(pool.Logger.With("peer", peerID))
  234. pool.peers[peerID] = peer
  235. }
  236. if height > pool.maxPeerHeight {
  237. pool.maxPeerHeight = height
  238. }
  239. }
  240. func (pool *BlockPool) RemovePeer(peerID p2p.ID) {
  241. pool.mtx.Lock()
  242. defer pool.mtx.Unlock()
  243. pool.removePeer(peerID)
  244. }
  245. func (pool *BlockPool) removePeer(peerID p2p.ID) {
  246. for _, requester := range pool.requesters {
  247. if requester.getPeerID() == peerID {
  248. if requester.getBlock() != nil {
  249. pool.numPending++
  250. }
  251. go requester.redo() // pick another peer and ...
  252. }
  253. }
  254. delete(pool.peers, peerID)
  255. }
  256. // Pick an available peer with at least the given minHeight.
  257. // If no peers are available, returns nil.
  258. func (pool *BlockPool) pickIncrAvailablePeer(minHeight int64) *bpPeer {
  259. pool.mtx.Lock()
  260. defer pool.mtx.Unlock()
  261. for _, peer := range pool.peers {
  262. if peer.didTimeout {
  263. pool.removePeer(peer.id)
  264. continue
  265. }
  266. if peer.numPending >= maxPendingRequestsPerPeer {
  267. continue
  268. }
  269. if peer.height < minHeight {
  270. continue
  271. }
  272. peer.incrPending()
  273. return peer
  274. }
  275. return nil
  276. }
  277. func (pool *BlockPool) makeNextRequester() {
  278. pool.mtx.Lock()
  279. defer pool.mtx.Unlock()
  280. nextHeight := pool.height + pool.requestersLen()
  281. request := newBPRequester(pool, nextHeight)
  282. // request.SetLogger(pool.Logger.With("height", nextHeight))
  283. pool.requesters[nextHeight] = request
  284. pool.numPending++
  285. err := request.Start()
  286. if err != nil {
  287. request.Logger.Error("Error starting request", "err", err)
  288. }
  289. }
  290. func (pool *BlockPool) requestersLen() int64 {
  291. return int64(len(pool.requesters))
  292. }
  293. func (pool *BlockPool) sendRequest(height int64, peerID p2p.ID) {
  294. if !pool.IsRunning() {
  295. return
  296. }
  297. pool.requestsCh <- BlockRequest{height, peerID}
  298. }
  299. func (pool *BlockPool) sendError(err error, peerID p2p.ID) {
  300. if !pool.IsRunning() {
  301. return
  302. }
  303. pool.errorsCh <- peerError{err, peerID}
  304. }
  305. // unused by tendermint; left for debugging purposes
  306. func (pool *BlockPool) debug() string {
  307. pool.mtx.Lock() // Lock
  308. defer pool.mtx.Unlock()
  309. str := ""
  310. nextHeight := pool.height + pool.requestersLen()
  311. for h := pool.height; h < nextHeight; h++ {
  312. if pool.requesters[h] == nil {
  313. str += cmn.Fmt("H(%v):X ", h)
  314. } else {
  315. str += cmn.Fmt("H(%v):", h)
  316. str += cmn.Fmt("B?(%v) ", pool.requesters[h].block != nil)
  317. }
  318. }
  319. return str
  320. }
  321. //-------------------------------------
  322. type bpPeer struct {
  323. pool *BlockPool
  324. id p2p.ID
  325. recvMonitor *flow.Monitor
  326. height int64
  327. numPending int32
  328. timeout *time.Timer
  329. didTimeout bool
  330. logger log.Logger
  331. }
  332. func newBPPeer(pool *BlockPool, peerID p2p.ID, height int64) *bpPeer {
  333. peer := &bpPeer{
  334. pool: pool,
  335. id: peerID,
  336. height: height,
  337. numPending: 0,
  338. logger: log.NewNopLogger(),
  339. }
  340. return peer
  341. }
  342. func (peer *bpPeer) setLogger(l log.Logger) {
  343. peer.logger = l
  344. }
  345. func (peer *bpPeer) resetMonitor() {
  346. peer.recvMonitor = flow.New(time.Second, time.Second*40)
  347. initialValue := float64(minRecvRate) * math.E
  348. peer.recvMonitor.SetREMA(initialValue)
  349. }
  350. func (peer *bpPeer) resetTimeout() {
  351. if peer.timeout == nil {
  352. peer.timeout = time.AfterFunc(peerTimeout, peer.onTimeout)
  353. } else {
  354. peer.timeout.Reset(peerTimeout)
  355. }
  356. }
  357. func (peer *bpPeer) incrPending() {
  358. if peer.numPending == 0 {
  359. peer.resetMonitor()
  360. peer.resetTimeout()
  361. }
  362. peer.numPending++
  363. }
  364. func (peer *bpPeer) decrPending(recvSize int) {
  365. peer.numPending--
  366. if peer.numPending == 0 {
  367. peer.timeout.Stop()
  368. } else {
  369. peer.recvMonitor.Update(recvSize)
  370. peer.resetTimeout()
  371. }
  372. }
  373. func (peer *bpPeer) onTimeout() {
  374. peer.pool.mtx.Lock()
  375. defer peer.pool.mtx.Unlock()
  376. err := errors.New("peer did not send us anything")
  377. peer.pool.sendError(err, peer.id)
  378. peer.logger.Error("SendTimeout", "reason", err, "timeout", peerTimeout)
  379. peer.didTimeout = true
  380. }
  381. //-------------------------------------
  382. type bpRequester struct {
  383. cmn.BaseService
  384. pool *BlockPool
  385. height int64
  386. gotBlockCh chan struct{}
  387. redoCh chan struct{}
  388. mtx sync.Mutex
  389. peerID p2p.ID
  390. block *types.Block
  391. }
  392. func newBPRequester(pool *BlockPool, height int64) *bpRequester {
  393. bpr := &bpRequester{
  394. pool: pool,
  395. height: height,
  396. gotBlockCh: make(chan struct{}),
  397. redoCh: make(chan struct{}),
  398. peerID: "",
  399. block: nil,
  400. }
  401. bpr.BaseService = *cmn.NewBaseService(nil, "bpRequester", bpr)
  402. return bpr
  403. }
  404. func (bpr *bpRequester) OnStart() error {
  405. go bpr.requestRoutine()
  406. return nil
  407. }
  408. // Returns true if the peer matches
  409. func (bpr *bpRequester) setBlock(block *types.Block, peerID p2p.ID) bool {
  410. bpr.mtx.Lock()
  411. if bpr.block != nil || bpr.peerID != peerID {
  412. bpr.mtx.Unlock()
  413. return false
  414. }
  415. bpr.block = block
  416. bpr.mtx.Unlock()
  417. bpr.gotBlockCh <- struct{}{}
  418. return true
  419. }
  420. func (bpr *bpRequester) getBlock() *types.Block {
  421. bpr.mtx.Lock()
  422. defer bpr.mtx.Unlock()
  423. return bpr.block
  424. }
  425. func (bpr *bpRequester) getPeerID() p2p.ID {
  426. bpr.mtx.Lock()
  427. defer bpr.mtx.Unlock()
  428. return bpr.peerID
  429. }
  430. func (bpr *bpRequester) reset() {
  431. bpr.mtx.Lock()
  432. bpr.peerID = ""
  433. bpr.block = nil
  434. bpr.mtx.Unlock()
  435. }
  436. // Tells bpRequester to pick another peer and try again.
  437. // NOTE: blocking
  438. func (bpr *bpRequester) redo() {
  439. bpr.redoCh <- struct{}{}
  440. }
  441. // Responsible for making more requests as necessary
  442. // Returns only when a block is found (e.g. AddBlock() is called)
  443. func (bpr *bpRequester) requestRoutine() {
  444. OUTER_LOOP:
  445. for {
  446. // Pick a peer to send request to.
  447. var peer *bpPeer
  448. PICK_PEER_LOOP:
  449. for {
  450. if !bpr.IsRunning() || !bpr.pool.IsRunning() {
  451. return
  452. }
  453. peer = bpr.pool.pickIncrAvailablePeer(bpr.height)
  454. if peer == nil {
  455. //log.Info("No peers available", "height", height)
  456. time.Sleep(requestIntervalMS * time.Millisecond)
  457. continue PICK_PEER_LOOP
  458. }
  459. break PICK_PEER_LOOP
  460. }
  461. bpr.mtx.Lock()
  462. bpr.peerID = peer.id
  463. bpr.mtx.Unlock()
  464. // Send request and wait.
  465. bpr.pool.sendRequest(bpr.height, peer.id)
  466. select {
  467. case <-bpr.pool.Quit():
  468. bpr.Stop()
  469. return
  470. case <-bpr.Quit():
  471. return
  472. case <-bpr.redoCh:
  473. bpr.reset()
  474. continue OUTER_LOOP // When peer is removed
  475. case <-bpr.gotBlockCh:
  476. // We got the block, now see if it's good.
  477. select {
  478. case <-bpr.pool.Quit():
  479. bpr.Stop()
  480. return
  481. case <-bpr.Quit():
  482. return
  483. case <-bpr.redoCh:
  484. bpr.reset()
  485. continue OUTER_LOOP
  486. }
  487. }
  488. }
  489. }
  490. //-------------------------------------
  491. type BlockRequest struct {
  492. Height int64
  493. PeerID p2p.ID
  494. }