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.

510 lines
11 KiB

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/go-common"
  7. flow "github.com/tendermint/go-flowrate/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. pool.numPending++
  206. go requester.redo() // pick another peer and ...
  207. }
  208. }
  209. delete(pool.peers, peerID)
  210. }
  211. // Pick an available peer with at least the given minHeight.
  212. // If no peers are available, returns nil.
  213. func (pool *BlockPool) pickIncrAvailablePeer(minHeight int) *bpPeer {
  214. pool.mtx.Lock()
  215. defer pool.mtx.Unlock()
  216. for _, peer := range pool.peers {
  217. if peer.didTimeout {
  218. pool.removePeer(peer.id)
  219. continue
  220. } else {
  221. }
  222. if peer.numPending >= maxPendingRequestsPerPeer {
  223. continue
  224. }
  225. if peer.height < minHeight {
  226. continue
  227. }
  228. peer.incrPending()
  229. return peer
  230. }
  231. return nil
  232. }
  233. func (pool *BlockPool) makeNextRequester() {
  234. pool.mtx.Lock()
  235. defer pool.mtx.Unlock()
  236. nextHeight := pool.height + len(pool.requesters)
  237. request := newBPRequester(pool, nextHeight)
  238. pool.requesters[nextHeight] = request
  239. pool.numPending++
  240. request.Start()
  241. }
  242. func (pool *BlockPool) sendRequest(height int, peerID string) {
  243. if !pool.IsRunning() {
  244. return
  245. }
  246. pool.requestsCh <- BlockRequest{height, peerID}
  247. }
  248. func (pool *BlockPool) sendTimeout(peerID string) {
  249. if !pool.IsRunning() {
  250. return
  251. }
  252. pool.timeoutsCh <- peerID
  253. }
  254. func (pool *BlockPool) debug() string {
  255. pool.mtx.Lock() // Lock
  256. defer pool.mtx.Unlock()
  257. str := ""
  258. for h := pool.height; h < pool.height+len(pool.requesters); h++ {
  259. if pool.requesters[h] == nil {
  260. str += Fmt("H(%v):X ", h)
  261. } else {
  262. str += Fmt("H(%v):", h)
  263. str += Fmt("B?(%v) ", pool.requesters[h].block != nil)
  264. }
  265. }
  266. return str
  267. }
  268. //-------------------------------------
  269. type bpPeer struct {
  270. pool *BlockPool
  271. id string
  272. recvMonitor *flow.Monitor
  273. mtx sync.Mutex
  274. height int
  275. numPending int32
  276. timeout *time.Timer
  277. didTimeout bool
  278. }
  279. func newBPPeer(pool *BlockPool, peerID string, height int) *bpPeer {
  280. peer := &bpPeer{
  281. pool: pool,
  282. id: peerID,
  283. height: height,
  284. numPending: 0,
  285. }
  286. return peer
  287. }
  288. func (peer *bpPeer) resetMonitor() {
  289. peer.recvMonitor = flow.New(time.Second, time.Second*40)
  290. var initialValue = float64(minRecvRate) * math.E
  291. peer.recvMonitor.SetREMA(initialValue)
  292. }
  293. func (peer *bpPeer) resetTimeout() {
  294. if peer.timeout == nil {
  295. peer.timeout = time.AfterFunc(time.Second*peerTimeoutSeconds, peer.onTimeout)
  296. } else {
  297. peer.timeout.Reset(time.Second * peerTimeoutSeconds)
  298. }
  299. }
  300. func (peer *bpPeer) incrPending() {
  301. if peer.numPending == 0 {
  302. peer.resetMonitor()
  303. peer.resetTimeout()
  304. }
  305. peer.numPending++
  306. }
  307. func (peer *bpPeer) decrPending(recvSize int) {
  308. peer.numPending--
  309. if peer.numPending == 0 {
  310. peer.timeout.Stop()
  311. } else {
  312. peer.recvMonitor.Update(recvSize)
  313. peer.resetTimeout()
  314. }
  315. }
  316. func (peer *bpPeer) onTimeout() {
  317. peer.pool.mtx.Lock()
  318. defer peer.pool.mtx.Unlock()
  319. peer.pool.sendTimeout(peer.id)
  320. log.Warn("SendTimeout", "peer", peer.id, "reason", "onTimeout")
  321. peer.didTimeout = true
  322. }
  323. //-------------------------------------
  324. type bpRequester struct {
  325. BaseService
  326. pool *BlockPool
  327. height int
  328. gotBlockCh chan struct{}
  329. redoCh chan struct{}
  330. mtx sync.Mutex
  331. peerID string
  332. block *types.Block
  333. }
  334. func newBPRequester(pool *BlockPool, height int) *bpRequester {
  335. bpr := &bpRequester{
  336. pool: pool,
  337. height: height,
  338. gotBlockCh: make(chan struct{}),
  339. redoCh: make(chan struct{}),
  340. peerID: "",
  341. block: nil,
  342. }
  343. bpr.BaseService = *NewBaseService(nil, "bpRequester", bpr)
  344. return bpr
  345. }
  346. func (bpr *bpRequester) OnStart() error {
  347. go bpr.requestRoutine()
  348. return nil
  349. }
  350. // Returns true if the peer matches
  351. func (bpr *bpRequester) setBlock(block *types.Block, peerID string) bool {
  352. bpr.mtx.Lock()
  353. if bpr.block != nil || bpr.peerID != peerID {
  354. bpr.mtx.Unlock()
  355. return false
  356. }
  357. bpr.block = block
  358. bpr.mtx.Unlock()
  359. bpr.gotBlockCh <- struct{}{}
  360. return true
  361. }
  362. func (bpr *bpRequester) getBlock() *types.Block {
  363. bpr.mtx.Lock()
  364. defer bpr.mtx.Unlock()
  365. return bpr.block
  366. }
  367. func (bpr *bpRequester) getPeerID() string {
  368. bpr.mtx.Lock()
  369. defer bpr.mtx.Unlock()
  370. return bpr.peerID
  371. }
  372. func (bpr *bpRequester) reset() {
  373. bpr.mtx.Lock()
  374. bpr.peerID = ""
  375. bpr.block = nil
  376. bpr.mtx.Unlock()
  377. }
  378. // Tells bpRequester to pick another peer and try again.
  379. // NOTE: blocking
  380. func (bpr *bpRequester) redo() {
  381. bpr.redoCh <- struct{}{}
  382. }
  383. // Responsible for making more requests as necessary
  384. // Returns only when a block is found (e.g. AddBlock() is called)
  385. func (bpr *bpRequester) requestRoutine() {
  386. OUTER_LOOP:
  387. for {
  388. // Pick a peer to send request to.
  389. var peer *bpPeer = nil
  390. PICK_PEER_LOOP:
  391. for {
  392. if !bpr.IsRunning() || !bpr.pool.IsRunning() {
  393. return
  394. }
  395. peer = bpr.pool.pickIncrAvailablePeer(bpr.height)
  396. if peer == nil {
  397. //log.Info("No peers available", "height", height)
  398. time.Sleep(requestIntervalMS * time.Millisecond)
  399. continue PICK_PEER_LOOP
  400. }
  401. break PICK_PEER_LOOP
  402. }
  403. bpr.mtx.Lock()
  404. bpr.peerID = peer.id
  405. bpr.mtx.Unlock()
  406. // Send request and wait.
  407. bpr.pool.sendRequest(bpr.height, peer.id)
  408. select {
  409. case <-bpr.pool.Quit:
  410. bpr.Stop()
  411. return
  412. case <-bpr.Quit:
  413. return
  414. case <-bpr.redoCh:
  415. bpr.reset()
  416. continue OUTER_LOOP // When peer is removed
  417. case <-bpr.gotBlockCh:
  418. // We got the block, now see if it's good.
  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
  428. }
  429. }
  430. }
  431. }
  432. //-------------------------------------
  433. type BlockRequest struct {
  434. Height int
  435. PeerID string
  436. }