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.

522 lines
12 KiB

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