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
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. "github.com/tendermint/tendermint/p2p"
  7. "github.com/tendermint/tendermint/types"
  8. cmn "github.com/tendermint/tmlibs/common"
  9. flow "github.com/tendermint/tmlibs/flowrate"
  10. "github.com/tendermint/tmlibs/log"
  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. func (pool *BlockPool) RedoRequest(height int64) {
  167. pool.mtx.Lock()
  168. defer pool.mtx.Unlock()
  169. request := pool.requesters[height]
  170. if request.block == nil {
  171. cmn.PanicSanity("Expected block to be non-nil")
  172. }
  173. // RemovePeer will redo all requesters associated with this peer.
  174. // TODO: record this malfeasance
  175. pool.removePeer(request.peerID)
  176. }
  177. // TODO: ensure that blocks come in order for each peer.
  178. func (pool *BlockPool) AddBlock(peerID p2p.ID, block *types.Block, blockSize int) {
  179. pool.mtx.Lock()
  180. defer pool.mtx.Unlock()
  181. requester := pool.requesters[block.Height]
  182. if requester == nil {
  183. // a block we didn't expect.
  184. // TODO:if height is too far ahead, punish peer
  185. return
  186. }
  187. if requester.setBlock(block, peerID) {
  188. pool.numPending--
  189. peer := pool.peers[peerID]
  190. if peer != nil {
  191. peer.decrPending(blockSize)
  192. }
  193. } else {
  194. // Bad peer?
  195. }
  196. }
  197. // MaxPeerHeight returns the highest height reported by a peer.
  198. func (pool *BlockPool) MaxPeerHeight() int64 {
  199. pool.mtx.Lock()
  200. defer pool.mtx.Unlock()
  201. return pool.maxPeerHeight
  202. }
  203. // Sets the peer's alleged blockchain height.
  204. func (pool *BlockPool) SetPeerHeight(peerID p2p.ID, height int64) {
  205. pool.mtx.Lock()
  206. defer pool.mtx.Unlock()
  207. peer := pool.peers[peerID]
  208. if peer != nil {
  209. peer.height = height
  210. } else {
  211. peer = newBPPeer(pool, peerID, height)
  212. peer.setLogger(pool.Logger.With("peer", peerID))
  213. pool.peers[peerID] = peer
  214. }
  215. if height > pool.maxPeerHeight {
  216. pool.maxPeerHeight = height
  217. }
  218. }
  219. func (pool *BlockPool) RemovePeer(peerID p2p.ID) {
  220. pool.mtx.Lock()
  221. defer pool.mtx.Unlock()
  222. pool.removePeer(peerID)
  223. }
  224. func (pool *BlockPool) removePeer(peerID p2p.ID) {
  225. for _, requester := range pool.requesters {
  226. if requester.getPeerID() == peerID {
  227. if requester.getBlock() != nil {
  228. pool.numPending++
  229. }
  230. go requester.redo() // pick another peer and ...
  231. }
  232. }
  233. delete(pool.peers, peerID)
  234. }
  235. // Pick an available peer with at least the given minHeight.
  236. // If no peers are available, returns nil.
  237. func (pool *BlockPool) pickIncrAvailablePeer(minHeight int64) *bpPeer {
  238. pool.mtx.Lock()
  239. defer pool.mtx.Unlock()
  240. for _, peer := range pool.peers {
  241. if peer.didTimeout {
  242. pool.removePeer(peer.id)
  243. continue
  244. }
  245. if peer.numPending >= maxPendingRequestsPerPeer {
  246. continue
  247. }
  248. if peer.height < minHeight {
  249. continue
  250. }
  251. peer.incrPending()
  252. return peer
  253. }
  254. return nil
  255. }
  256. func (pool *BlockPool) makeNextRequester() {
  257. pool.mtx.Lock()
  258. defer pool.mtx.Unlock()
  259. nextHeight := pool.height + pool.requestersLen()
  260. request := newBPRequester(pool, nextHeight)
  261. // request.SetLogger(pool.Logger.With("height", nextHeight))
  262. pool.requesters[nextHeight] = request
  263. pool.numPending++
  264. err := request.Start()
  265. if err != nil {
  266. request.Logger.Error("Error starting request", "err", err)
  267. }
  268. }
  269. func (pool *BlockPool) requestersLen() int64 {
  270. return int64(len(pool.requesters))
  271. }
  272. func (pool *BlockPool) sendRequest(height int64, peerID p2p.ID) {
  273. if !pool.IsRunning() {
  274. return
  275. }
  276. pool.requestsCh <- BlockRequest{height, peerID}
  277. }
  278. func (pool *BlockPool) sendTimeout(peerID p2p.ID) {
  279. if !pool.IsRunning() {
  280. return
  281. }
  282. pool.timeoutsCh <- peerID
  283. }
  284. // unused by tendermint; left for debugging purposes
  285. func (pool *BlockPool) debug() string {
  286. pool.mtx.Lock() // Lock
  287. defer pool.mtx.Unlock()
  288. str := ""
  289. nextHeight := pool.height + pool.requestersLen()
  290. for h := pool.height; h < nextHeight; h++ {
  291. if pool.requesters[h] == nil {
  292. str += cmn.Fmt("H(%v):X ", h)
  293. } else {
  294. str += cmn.Fmt("H(%v):", h)
  295. str += cmn.Fmt("B?(%v) ", pool.requesters[h].block != nil)
  296. }
  297. }
  298. return str
  299. }
  300. //-------------------------------------
  301. type bpPeer struct {
  302. pool *BlockPool
  303. id p2p.ID
  304. recvMonitor *flow.Monitor
  305. height int64
  306. numPending int32
  307. timeout *time.Timer
  308. didTimeout bool
  309. logger log.Logger
  310. }
  311. func newBPPeer(pool *BlockPool, peerID p2p.ID, height int64) *bpPeer {
  312. peer := &bpPeer{
  313. pool: pool,
  314. id: peerID,
  315. height: height,
  316. numPending: 0,
  317. logger: log.NewNopLogger(),
  318. }
  319. return peer
  320. }
  321. func (peer *bpPeer) setLogger(l log.Logger) {
  322. peer.logger = l
  323. }
  324. func (peer *bpPeer) resetMonitor() {
  325. peer.recvMonitor = flow.New(time.Second, time.Second*40)
  326. initialValue := float64(minRecvRate) * math.E
  327. peer.recvMonitor.SetREMA(initialValue)
  328. }
  329. func (peer *bpPeer) resetTimeout() {
  330. if peer.timeout == nil {
  331. peer.timeout = time.AfterFunc(time.Second*peerTimeoutSeconds, peer.onTimeout)
  332. } else {
  333. peer.timeout.Reset(time.Second * peerTimeoutSeconds)
  334. }
  335. }
  336. func (peer *bpPeer) incrPending() {
  337. if peer.numPending == 0 {
  338. peer.resetMonitor()
  339. peer.resetTimeout()
  340. }
  341. peer.numPending++
  342. }
  343. func (peer *bpPeer) decrPending(recvSize int) {
  344. peer.numPending--
  345. if peer.numPending == 0 {
  346. peer.timeout.Stop()
  347. } else {
  348. peer.recvMonitor.Update(recvSize)
  349. peer.resetTimeout()
  350. }
  351. }
  352. func (peer *bpPeer) onTimeout() {
  353. peer.pool.mtx.Lock()
  354. defer peer.pool.mtx.Unlock()
  355. peer.pool.sendTimeout(peer.id)
  356. peer.logger.Error("SendTimeout", "reason", "onTimeout")
  357. peer.didTimeout = true
  358. }
  359. //-------------------------------------
  360. type bpRequester struct {
  361. cmn.BaseService
  362. pool *BlockPool
  363. height int64
  364. gotBlockCh chan struct{}
  365. redoCh chan struct{}
  366. mtx sync.Mutex
  367. peerID p2p.ID
  368. block *types.Block
  369. }
  370. func newBPRequester(pool *BlockPool, height int64) *bpRequester {
  371. bpr := &bpRequester{
  372. pool: pool,
  373. height: height,
  374. gotBlockCh: make(chan struct{}),
  375. redoCh: make(chan struct{}),
  376. peerID: "",
  377. block: nil,
  378. }
  379. bpr.BaseService = *cmn.NewBaseService(nil, "bpRequester", bpr)
  380. return bpr
  381. }
  382. func (bpr *bpRequester) OnStart() error {
  383. go bpr.requestRoutine()
  384. return nil
  385. }
  386. // Returns true if the peer matches
  387. func (bpr *bpRequester) setBlock(block *types.Block, peerID p2p.ID) bool {
  388. bpr.mtx.Lock()
  389. if bpr.block != nil || bpr.peerID != peerID {
  390. bpr.mtx.Unlock()
  391. return false
  392. }
  393. bpr.block = block
  394. bpr.mtx.Unlock()
  395. bpr.gotBlockCh <- struct{}{}
  396. return true
  397. }
  398. func (bpr *bpRequester) getBlock() *types.Block {
  399. bpr.mtx.Lock()
  400. defer bpr.mtx.Unlock()
  401. return bpr.block
  402. }
  403. func (bpr *bpRequester) getPeerID() p2p.ID {
  404. bpr.mtx.Lock()
  405. defer bpr.mtx.Unlock()
  406. return bpr.peerID
  407. }
  408. func (bpr *bpRequester) reset() {
  409. bpr.mtx.Lock()
  410. bpr.peerID = ""
  411. bpr.block = nil
  412. bpr.mtx.Unlock()
  413. }
  414. // Tells bpRequester to pick another peer and try again.
  415. // NOTE: blocking
  416. func (bpr *bpRequester) redo() {
  417. bpr.redoCh <- struct{}{}
  418. }
  419. // Responsible for making more requests as necessary
  420. // Returns only when a block is found (e.g. AddBlock() is called)
  421. func (bpr *bpRequester) requestRoutine() {
  422. OUTER_LOOP:
  423. for {
  424. // Pick a peer to send request to.
  425. var peer *bpPeer = nil
  426. PICK_PEER_LOOP:
  427. for {
  428. if !bpr.IsRunning() || !bpr.pool.IsRunning() {
  429. return
  430. }
  431. peer = bpr.pool.pickIncrAvailablePeer(bpr.height)
  432. if peer == nil {
  433. //log.Info("No peers available", "height", height)
  434. time.Sleep(requestIntervalMS * time.Millisecond)
  435. continue PICK_PEER_LOOP
  436. }
  437. break PICK_PEER_LOOP
  438. }
  439. bpr.mtx.Lock()
  440. bpr.peerID = peer.id
  441. bpr.mtx.Unlock()
  442. // Send request and wait.
  443. bpr.pool.sendRequest(bpr.height, peer.id)
  444. select {
  445. case <-bpr.pool.Quit:
  446. bpr.Stop()
  447. return
  448. case <-bpr.Quit:
  449. return
  450. case <-bpr.redoCh:
  451. bpr.reset()
  452. continue OUTER_LOOP // When peer is removed
  453. case <-bpr.gotBlockCh:
  454. // We got the block, now see if it's good.
  455. select {
  456. case <-bpr.pool.Quit:
  457. bpr.Stop()
  458. return
  459. case <-bpr.Quit:
  460. return
  461. case <-bpr.redoCh:
  462. bpr.reset()
  463. continue OUTER_LOOP
  464. }
  465. }
  466. }
  467. }
  468. //-------------------------------------
  469. type BlockRequest struct {
  470. Height int64
  471. PeerID p2p.ID
  472. }