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.

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