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.

630 lines
15 KiB

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