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.

539 lines
12 KiB

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