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.

566 lines
13 KiB

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