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.

556 lines
13 KiB

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