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.

596 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. // unused by tendermint; left for debugging purposes
  311. func (pool *BlockPool) debug() string {
  312. pool.mtx.Lock()
  313. defer pool.mtx.Unlock()
  314. str := ""
  315. nextHeight := pool.height + pool.requestersLen()
  316. for h := pool.height; h < nextHeight; h++ {
  317. if pool.requesters[h] == nil {
  318. str += fmt.Sprintf("H(%v):X ", h)
  319. } else {
  320. str += fmt.Sprintf("H(%v):", h)
  321. str += fmt.Sprintf("B?(%v) ", pool.requesters[h].block != nil)
  322. }
  323. }
  324. return str
  325. }
  326. //-------------------------------------
  327. type bpPeer struct {
  328. pool *BlockPool
  329. id p2p.ID
  330. recvMonitor *flow.Monitor
  331. height int64
  332. numPending int32
  333. timeout *time.Timer
  334. didTimeout bool
  335. logger log.Logger
  336. }
  337. func newBPPeer(pool *BlockPool, peerID p2p.ID, height int64) *bpPeer {
  338. peer := &bpPeer{
  339. pool: pool,
  340. id: peerID,
  341. height: height,
  342. numPending: 0,
  343. logger: log.NewNopLogger(),
  344. }
  345. return peer
  346. }
  347. func (peer *bpPeer) setLogger(l log.Logger) {
  348. peer.logger = l
  349. }
  350. func (peer *bpPeer) resetMonitor() {
  351. peer.recvMonitor = flow.New(time.Second, time.Second*40)
  352. initialValue := float64(minRecvRate) * math.E
  353. peer.recvMonitor.SetREMA(initialValue)
  354. }
  355. func (peer *bpPeer) resetTimeout() {
  356. if peer.timeout == nil {
  357. peer.timeout = time.AfterFunc(peerTimeout, peer.onTimeout)
  358. } else {
  359. peer.timeout.Reset(peerTimeout)
  360. }
  361. }
  362. func (peer *bpPeer) incrPending() {
  363. if peer.numPending == 0 {
  364. peer.resetMonitor()
  365. peer.resetTimeout()
  366. }
  367. peer.numPending++
  368. }
  369. func (peer *bpPeer) decrPending(recvSize int) {
  370. peer.numPending--
  371. if peer.numPending == 0 {
  372. peer.timeout.Stop()
  373. } else {
  374. peer.recvMonitor.Update(recvSize)
  375. peer.resetTimeout()
  376. }
  377. }
  378. func (peer *bpPeer) onTimeout() {
  379. peer.pool.mtx.Lock()
  380. defer peer.pool.mtx.Unlock()
  381. err := errors.New("peer did not send us anything")
  382. peer.pool.sendError(err, peer.id)
  383. peer.logger.Error("SendTimeout", "reason", err, "timeout", peerTimeout)
  384. peer.didTimeout = true
  385. }
  386. //-------------------------------------
  387. type bpRequester struct {
  388. cmn.BaseService
  389. pool *BlockPool
  390. height int64
  391. gotBlockCh chan struct{}
  392. redoCh chan p2p.ID //redo may send multitime, add peerId to identify repeat
  393. mtx sync.Mutex
  394. peerID p2p.ID
  395. block *types.Block
  396. }
  397. func newBPRequester(pool *BlockPool, height int64) *bpRequester {
  398. bpr := &bpRequester{
  399. pool: pool,
  400. height: height,
  401. gotBlockCh: make(chan struct{}, 1),
  402. redoCh: make(chan p2p.ID, 1),
  403. peerID: "",
  404. block: nil,
  405. }
  406. bpr.BaseService = *cmn.NewBaseService(nil, "bpRequester", bpr)
  407. return bpr
  408. }
  409. func (bpr *bpRequester) OnStart() error {
  410. go bpr.requestRoutine()
  411. return nil
  412. }
  413. // Returns true if the peer matches and block doesn't already exist.
  414. func (bpr *bpRequester) setBlock(block *types.Block, peerID p2p.ID) bool {
  415. bpr.mtx.Lock()
  416. if bpr.block != nil || bpr.peerID != peerID {
  417. bpr.mtx.Unlock()
  418. return false
  419. }
  420. bpr.block = block
  421. bpr.mtx.Unlock()
  422. select {
  423. case bpr.gotBlockCh <- struct{}{}:
  424. default:
  425. }
  426. return true
  427. }
  428. func (bpr *bpRequester) getBlock() *types.Block {
  429. bpr.mtx.Lock()
  430. defer bpr.mtx.Unlock()
  431. return bpr.block
  432. }
  433. func (bpr *bpRequester) getPeerID() p2p.ID {
  434. bpr.mtx.Lock()
  435. defer bpr.mtx.Unlock()
  436. return bpr.peerID
  437. }
  438. // This is called from the requestRoutine, upon redo().
  439. func (bpr *bpRequester) reset() {
  440. bpr.mtx.Lock()
  441. defer bpr.mtx.Unlock()
  442. if bpr.block != nil {
  443. atomic.AddInt32(&bpr.pool.numPending, 1)
  444. }
  445. bpr.peerID = ""
  446. bpr.block = nil
  447. }
  448. // Tells bpRequester to pick another peer and try again.
  449. // NOTE: Nonblocking, and does nothing if another redo
  450. // was already requested.
  451. func (bpr *bpRequester) redo(peerId p2p.ID) {
  452. select {
  453. case bpr.redoCh <- peerId:
  454. default:
  455. }
  456. }
  457. // Responsible for making more requests as necessary
  458. // Returns only when a block is found (e.g. AddBlock() is called)
  459. func (bpr *bpRequester) requestRoutine() {
  460. OUTER_LOOP:
  461. for {
  462. // Pick a peer to send request to.
  463. var peer *bpPeer
  464. PICK_PEER_LOOP:
  465. for {
  466. if !bpr.IsRunning() || !bpr.pool.IsRunning() {
  467. return
  468. }
  469. peer = bpr.pool.pickIncrAvailablePeer(bpr.height)
  470. if peer == nil {
  471. //log.Info("No peers available", "height", height)
  472. time.Sleep(requestIntervalMS * time.Millisecond)
  473. continue PICK_PEER_LOOP
  474. }
  475. break PICK_PEER_LOOP
  476. }
  477. bpr.mtx.Lock()
  478. bpr.peerID = peer.id
  479. bpr.mtx.Unlock()
  480. // Send request and wait.
  481. bpr.pool.sendRequest(bpr.height, peer.id)
  482. WAIT_LOOP:
  483. for {
  484. select {
  485. case <-bpr.pool.Quit():
  486. bpr.Stop()
  487. return
  488. case <-bpr.Quit():
  489. return
  490. case peerID := <-bpr.redoCh:
  491. if peerID == bpr.peerID {
  492. bpr.reset()
  493. continue OUTER_LOOP
  494. } else {
  495. continue WAIT_LOOP
  496. }
  497. case <-bpr.gotBlockCh:
  498. // We got a block!
  499. // Continue the for-loop and wait til Quit.
  500. continue WAIT_LOOP
  501. }
  502. }
  503. }
  504. }
  505. //-------------------------------------
  506. type BlockRequest struct {
  507. Height int64
  508. PeerID p2p.ID
  509. }