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.

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