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.

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