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.

563 lines
13 KiB

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