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

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