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.

547 lines
12 KiB

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