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.

521 lines
12 KiB

9 years ago
10 years ago
9 years ago
10 years ago
  1. package blockchain
  2. import (
  3. "math"
  4. "sync"
  5. "time"
  6. flow "github.com/tendermint/flowcontrol"
  7. . "github.com/tendermint/go-common"
  8. "github.com/tendermint/tendermint/types"
  9. )
  10. const (
  11. requestIntervalMS = 250
  12. maxTotalRequesters = 300
  13. maxPendingRequests = maxTotalRequesters
  14. maxPendingRequestsPerPeer = 75
  15. minRecvRate = 10240 // 10Kb/s
  16. )
  17. var peerTimeoutSeconds = time.Duration(15) // not const so we can override with tests
  18. /*
  19. Peers self report their heights when we join the block pool.
  20. Starting from our latest pool.height, we request blocks
  21. in sequence from peers that reported higher heights than ours.
  22. Every so often we ask peers what height they're on so we can keep going.
  23. Requests are continuously made for blocks of heigher heights until
  24. the limits. If most of the requests have no available peers, and we
  25. are not at peer limits, we can probably switch to consensus reactor
  26. */
  27. type BlockPool struct {
  28. QuitService
  29. startTime time.Time
  30. // block requests
  31. mtx sync.Mutex
  32. requesters map[int]*bpRequester
  33. height int // the lowest key in requesters.
  34. numPending int32 // number of requests pending assignment or block response
  35. // peers
  36. peersMtx sync.Mutex
  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.QuitService = *NewQuitService(log, "BlockPool", bp)
  51. return bp
  52. }
  53. func (pool *BlockPool) OnStart() error {
  54. pool.QuitService.OnStart()
  55. go pool.makeRequestersRoutine()
  56. pool.startTime = time.Now()
  57. return nil
  58. }
  59. func (pool *BlockPool) OnStop() {
  60. pool.QuitService.OnStop()
  61. }
  62. // Run spawns requesters as needed.
  63. func (pool *BlockPool) makeRequestersRoutine() {
  64. for {
  65. if !pool.IsRunning() {
  66. break
  67. }
  68. _, numPending := pool.GetStatus()
  69. if numPending >= maxPendingRequests {
  70. // sleep for a bit.
  71. time.Sleep(requestIntervalMS * time.Millisecond)
  72. // check for timed out peers
  73. pool.removeTimedoutPeers()
  74. } else if len(pool.requesters) >= maxTotalRequesters {
  75. // sleep for a bit.
  76. time.Sleep(requestIntervalMS * time.Millisecond)
  77. // check for timed out peers
  78. pool.removeTimedoutPeers()
  79. } else {
  80. // request for more blocks.
  81. pool.makeNextRequester()
  82. }
  83. }
  84. }
  85. func (pool *BlockPool) removeTimedoutPeers() {
  86. for _, peer := range pool.peers {
  87. if !peer.didTimeout && peer.numPending > 0 {
  88. curRate := peer.recvMonitor.Status().CurRate
  89. // XXX remove curRate != 0
  90. if curRate != 0 && curRate < minRecvRate {
  91. pool.sendTimeout(peer.id)
  92. log.Warn("SendTimeout", "peer", peer.id, "reason", "curRate too low")
  93. peer.didTimeout = true
  94. }
  95. }
  96. if peer.didTimeout {
  97. pool.peersMtx.Lock() // Lock
  98. pool.removePeer(peer.id)
  99. pool.peersMtx.Unlock()
  100. }
  101. }
  102. }
  103. func (pool *BlockPool) GetStatus() (height int, numPending int32) {
  104. pool.mtx.Lock() // Lock
  105. defer pool.mtx.Unlock()
  106. return pool.height, pool.numPending
  107. }
  108. // TODO: relax conditions, prevent abuse.
  109. func (pool *BlockPool) IsCaughtUp() bool {
  110. pool.mtx.Lock()
  111. height := pool.height
  112. pool.mtx.Unlock()
  113. // Need at least 1 peer to be considered caught up.
  114. if len(pool.peers) == 0 {
  115. log.Debug("Blockpool has no peers")
  116. return false
  117. }
  118. pool.peersMtx.Lock()
  119. maxPeerHeight := 0
  120. for _, peer := range pool.peers {
  121. maxPeerHeight = MaxInt(maxPeerHeight, peer.height)
  122. }
  123. pool.peersMtx.Unlock()
  124. isCaughtUp := (height > 0 || time.Now().Sub(pool.startTime) > 5*time.Second) && (maxPeerHeight == 0 || height >= maxPeerHeight)
  125. log.Notice(Fmt("IsCaughtUp: %v", isCaughtUp), "height", height, "maxPeerHeight", maxPeerHeight)
  126. return isCaughtUp
  127. }
  128. // We need to see the second block's Commit to validate the first block.
  129. // So we peek two blocks at a time.
  130. // The caller will verify the commit.
  131. func (pool *BlockPool) PeekTwoBlocks() (first *types.Block, second *types.Block) {
  132. pool.mtx.Lock() // Lock
  133. defer pool.mtx.Unlock()
  134. if r := pool.requesters[pool.height]; r != nil {
  135. first = r.getBlock()
  136. }
  137. if r := pool.requesters[pool.height+1]; r != nil {
  138. second = r.getBlock()
  139. }
  140. return
  141. }
  142. // Pop the first block at pool.height
  143. // It must have been validated by 'second'.Commit from PeekTwoBlocks().
  144. func (pool *BlockPool) PopRequest() {
  145. pool.mtx.Lock() // Lock
  146. defer pool.mtx.Unlock()
  147. if r := pool.requesters[pool.height]; r != nil {
  148. /* The block can disappear at any time, due to removePeer().
  149. if r := pool.requesters[pool.height]; r == nil || r.block == nil {
  150. PanicSanity("PopRequest() requires a valid block")
  151. }
  152. */
  153. r.Stop()
  154. delete(pool.requesters, pool.height)
  155. pool.height++
  156. } else {
  157. PanicSanity(Fmt("Expected requester to pop, got nothing at height %v", pool.height))
  158. }
  159. }
  160. // Invalidates the block at pool.height,
  161. // Remove the peer and redo request from others.
  162. func (pool *BlockPool) RedoRequest(height int) {
  163. pool.mtx.Lock() // Lock
  164. defer pool.mtx.Unlock()
  165. request := pool.requesters[height]
  166. if request.block == nil {
  167. PanicSanity("Expected block to be non-nil")
  168. }
  169. // RemovePeer will redo all requesters associated with this peer.
  170. // TODO: record this malfeasance
  171. pool.RemovePeer(request.peerID) // Lock on peersMtx.
  172. }
  173. // TODO: ensure that blocks come in order for each peer.
  174. func (pool *BlockPool) AddBlock(peerID string, block *types.Block, blockSize int) {
  175. pool.mtx.Lock() // Lock
  176. defer pool.mtx.Unlock()
  177. requester := pool.requesters[block.Height]
  178. if requester == nil {
  179. return
  180. }
  181. if requester.setBlock(block, peerID) {
  182. pool.numPending--
  183. peer := pool.getPeer(peerID)
  184. peer.decrPending(blockSize)
  185. } else {
  186. // Bad peer?
  187. }
  188. }
  189. // Sets the peer's alleged blockchain height.
  190. func (pool *BlockPool) SetPeerHeight(peerID string, height int) {
  191. pool.peersMtx.Lock() // Lock
  192. defer pool.peersMtx.Unlock()
  193. peer := pool.peers[peerID]
  194. if peer != nil {
  195. peer.height = height
  196. } else {
  197. peer = newBPPeer(pool, peerID, height)
  198. pool.peers[peerID] = peer
  199. }
  200. }
  201. func (pool *BlockPool) RemovePeer(peerID string) {
  202. pool.peersMtx.Lock() // Lock
  203. defer pool.peersMtx.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. pool.numPending++
  210. go requester.redo() // pick another peer and ...
  211. }
  212. }
  213. delete(pool.peers, peerID)
  214. }
  215. func (pool *BlockPool) getPeer(peerID string) *bpPeer {
  216. pool.peersMtx.Lock() // Lock
  217. defer pool.peersMtx.Unlock()
  218. peer := pool.peers[peerID]
  219. return peer
  220. }
  221. // Pick an available peer with at least the given minHeight.
  222. // If no peers are available, returns nil.
  223. func (pool *BlockPool) pickIncrAvailablePeer(minHeight int) *bpPeer {
  224. pool.peersMtx.Lock()
  225. defer pool.peersMtx.Unlock()
  226. for _, peer := range pool.peers {
  227. if peer.isBad() {
  228. pool.removePeer(peer.id)
  229. continue
  230. } else {
  231. }
  232. if peer.numPending >= maxPendingRequestsPerPeer {
  233. continue
  234. }
  235. if peer.height < minHeight {
  236. continue
  237. }
  238. peer.incrPending()
  239. return peer
  240. }
  241. return nil
  242. }
  243. func (pool *BlockPool) makeNextRequester() {
  244. pool.mtx.Lock() // Lock
  245. defer pool.mtx.Unlock()
  246. nextHeight := pool.height + len(pool.requesters)
  247. request := newBPRequester(pool, nextHeight)
  248. pool.requesters[nextHeight] = request
  249. pool.numPending++
  250. request.Start()
  251. }
  252. func (pool *BlockPool) sendRequest(height int, peerID string) {
  253. if !pool.IsRunning() {
  254. return
  255. }
  256. pool.requestsCh <- BlockRequest{height, peerID}
  257. }
  258. func (pool *BlockPool) sendTimeout(peerID string) {
  259. if !pool.IsRunning() {
  260. return
  261. }
  262. pool.timeoutsCh <- peerID
  263. }
  264. func (pool *BlockPool) debug() string {
  265. pool.mtx.Lock() // Lock
  266. defer pool.mtx.Unlock()
  267. str := ""
  268. for h := pool.height; h < pool.height+len(pool.requesters); h++ {
  269. if pool.requesters[h] == nil {
  270. str += Fmt("H(%v):X ", h)
  271. } else {
  272. str += Fmt("H(%v):", h)
  273. str += Fmt("B?(%v) ", pool.requesters[h].block != nil)
  274. }
  275. }
  276. return str
  277. }
  278. //-------------------------------------
  279. type bpPeer struct {
  280. pool *BlockPool
  281. id string
  282. height int
  283. numPending int32
  284. recvMonitor *flow.Monitor
  285. timeout *time.Timer
  286. didTimeout bool
  287. }
  288. func newBPPeer(pool *BlockPool, peerID string, height int) *bpPeer {
  289. peer := &bpPeer{
  290. pool: pool,
  291. id: peerID,
  292. height: height,
  293. numPending: 0,
  294. }
  295. return peer
  296. }
  297. func (peer *bpPeer) resetMonitor() {
  298. peer.recvMonitor = flow.New(time.Second, time.Second*40)
  299. var initialValue = float64(minRecvRate) * math.E
  300. peer.recvMonitor.SetREMA(initialValue)
  301. }
  302. func (peer *bpPeer) resetTimeout() {
  303. if peer.timeout == nil {
  304. peer.timeout = time.AfterFunc(time.Second*peerTimeoutSeconds, peer.onTimeout)
  305. } else {
  306. peer.timeout.Reset(time.Second * peerTimeoutSeconds)
  307. }
  308. }
  309. func (peer *bpPeer) incrPending() {
  310. if peer.numPending == 0 {
  311. peer.resetMonitor()
  312. peer.resetTimeout()
  313. }
  314. peer.numPending++
  315. }
  316. func (peer *bpPeer) decrPending(recvSize int) {
  317. peer.numPending--
  318. if peer.numPending == 0 {
  319. peer.timeout.Stop()
  320. } else {
  321. peer.recvMonitor.Update(recvSize)
  322. peer.resetTimeout()
  323. }
  324. }
  325. func (peer *bpPeer) onTimeout() {
  326. peer.pool.sendTimeout(peer.id)
  327. log.Warn("SendTimeout", "peer", peer.id, "reason", "onTimeout")
  328. peer.didTimeout = true
  329. }
  330. func (peer *bpPeer) isBad() bool {
  331. return peer.didTimeout
  332. }
  333. //-------------------------------------
  334. type bpRequester struct {
  335. QuitService
  336. pool *BlockPool
  337. height int
  338. gotBlockCh chan struct{}
  339. redoCh chan struct{}
  340. mtx sync.Mutex
  341. peerID string
  342. block *types.Block
  343. }
  344. func newBPRequester(pool *BlockPool, height int) *bpRequester {
  345. bpr := &bpRequester{
  346. pool: pool,
  347. height: height,
  348. gotBlockCh: make(chan struct{}),
  349. redoCh: make(chan struct{}),
  350. peerID: "",
  351. block: nil,
  352. }
  353. bpr.QuitService = *NewQuitService(nil, "bpRequester", bpr)
  354. return bpr
  355. }
  356. func (bpr *bpRequester) OnStart() error {
  357. bpr.QuitService.OnStart()
  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. }