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
9 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. peerTimeoutSeconds = 15
  16. minRecvRate = 10240 // 10Kb/s
  17. )
  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. pool.peersMtx.Lock()
  114. numPeers := len(pool.peers)
  115. maxPeerHeight := 0
  116. for _, peer := range pool.peers {
  117. maxPeerHeight = MaxInt(maxPeerHeight, peer.height)
  118. }
  119. pool.peersMtx.Unlock()
  120. return numPeers >= 3 && (height > 0 || time.Now().Sub(pool.startTime) > 30*time.Second) && (maxPeerHeight == 0 || height == maxPeerHeight)
  121. }
  122. // We need to see the second block's Validation to validate the first block.
  123. // So we peek two blocks at a time.
  124. func (pool *BlockPool) PeekTwoBlocks() (first *types.Block, second *types.Block) {
  125. pool.mtx.Lock() // Lock
  126. defer pool.mtx.Unlock()
  127. if r := pool.requesters[pool.height]; r != nil {
  128. first = r.getBlock()
  129. }
  130. if r := pool.requesters[pool.height+1]; r != nil {
  131. second = r.getBlock()
  132. }
  133. return
  134. }
  135. // Pop the first block at pool.height
  136. // It must have been validated by 'second'.Validation from PeekTwoBlocks().
  137. func (pool *BlockPool) PopRequest() {
  138. pool.mtx.Lock() // Lock
  139. defer pool.mtx.Unlock()
  140. if r := pool.requesters[pool.height]; r != nil {
  141. /* The block can disappear at any time, due to removePeer().
  142. if r := pool.requesters[pool.height]; r == nil || r.block == nil {
  143. PanicSanity("PopRequest() requires a valid block")
  144. }
  145. */
  146. r.Stop()
  147. delete(pool.requesters, pool.height)
  148. pool.height++
  149. } else {
  150. PanicSanity(Fmt("Expected requester to pop, got nothing at height %v", pool.height))
  151. }
  152. }
  153. // Invalidates the block at pool.height,
  154. // Remove the peer and redo request from others.
  155. func (pool *BlockPool) RedoRequest(height int) {
  156. pool.mtx.Lock() // Lock
  157. defer pool.mtx.Unlock()
  158. request := pool.requesters[height]
  159. if request.block == nil {
  160. PanicSanity("Expected block to be non-nil")
  161. }
  162. // RemovePeer will redo all requesters associated with this peer.
  163. // TODO: record this malfeasance
  164. pool.RemovePeer(request.peerID) // Lock on peersMtx.
  165. }
  166. // TODO: ensure that blocks come in order for each peer.
  167. func (pool *BlockPool) AddBlock(peerID string, block *types.Block, blockSize int) {
  168. pool.mtx.Lock() // Lock
  169. defer pool.mtx.Unlock()
  170. requester := pool.requesters[block.Height]
  171. if requester == nil {
  172. return
  173. }
  174. if requester.setBlock(block, peerID) {
  175. pool.numPending--
  176. peer := pool.getPeer(peerID)
  177. peer.decrPending(blockSize)
  178. } else {
  179. // Bad peer?
  180. }
  181. }
  182. // Sets the peer's alleged blockchain height.
  183. func (pool *BlockPool) SetPeerHeight(peerID string, height int) {
  184. pool.peersMtx.Lock() // Lock
  185. defer pool.peersMtx.Unlock()
  186. peer := pool.peers[peerID]
  187. if peer != nil {
  188. peer.height = height
  189. } else {
  190. peer = newBPPeer(pool, peerID, height)
  191. pool.peers[peerID] = peer
  192. }
  193. }
  194. func (pool *BlockPool) RemovePeer(peerID string) {
  195. pool.peersMtx.Lock() // Lock
  196. defer pool.peersMtx.Unlock()
  197. pool.removePeer(peerID)
  198. }
  199. func (pool *BlockPool) removePeer(peerID string) {
  200. for _, requester := range pool.requesters {
  201. if requester.getPeerID() == peerID {
  202. pool.numPending++
  203. go requester.redo() // pick another peer and ...
  204. }
  205. }
  206. delete(pool.peers, peerID)
  207. }
  208. func (pool *BlockPool) getPeer(peerID string) *bpPeer {
  209. pool.peersMtx.Lock() // Lock
  210. defer pool.peersMtx.Unlock()
  211. peer := pool.peers[peerID]
  212. return peer
  213. }
  214. // Pick an available peer with at least the given minHeight.
  215. // If no peers are available, returns nil.
  216. func (pool *BlockPool) pickIncrAvailablePeer(minHeight int) *bpPeer {
  217. pool.peersMtx.Lock()
  218. defer pool.peersMtx.Unlock()
  219. for _, peer := range pool.peers {
  220. if peer.isBad() {
  221. pool.removePeer(peer.id)
  222. continue
  223. } else {
  224. }
  225. if peer.numPending >= maxPendingRequestsPerPeer {
  226. continue
  227. }
  228. if peer.height < minHeight {
  229. continue
  230. }
  231. peer.incrPending()
  232. return peer
  233. }
  234. return nil
  235. }
  236. func (pool *BlockPool) makeNextRequester() {
  237. pool.mtx.Lock() // Lock
  238. defer pool.mtx.Unlock()
  239. nextHeight := pool.height + len(pool.requesters)
  240. request := newBPRequester(pool, nextHeight)
  241. pool.requesters[nextHeight] = request
  242. pool.numPending++
  243. request.Start()
  244. }
  245. func (pool *BlockPool) sendRequest(height int, peerID string) {
  246. if !pool.IsRunning() {
  247. return
  248. }
  249. pool.requestsCh <- BlockRequest{height, peerID}
  250. }
  251. func (pool *BlockPool) sendTimeout(peerID string) {
  252. if !pool.IsRunning() {
  253. return
  254. }
  255. pool.timeoutsCh <- peerID
  256. }
  257. func (pool *BlockPool) debug() string {
  258. pool.mtx.Lock() // Lock
  259. defer pool.mtx.Unlock()
  260. str := ""
  261. for h := pool.height; h < pool.height+len(pool.requesters); h++ {
  262. if pool.requesters[h] == nil {
  263. str += Fmt("H(%v):X ", h)
  264. } else {
  265. str += Fmt("H(%v):", h)
  266. str += Fmt("B?(%v) ", pool.requesters[h].block != nil)
  267. }
  268. }
  269. return str
  270. }
  271. //-------------------------------------
  272. type bpPeer struct {
  273. pool *BlockPool
  274. id string
  275. height int
  276. numPending int32
  277. recvMonitor *flow.Monitor
  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.sendTimeout(peer.id)
  320. log.Warn("SendTimeout", "peer", peer.id, "reason", "onTimeout")
  321. peer.didTimeout = true
  322. }
  323. func (peer *bpPeer) isBad() bool {
  324. return peer.didTimeout
  325. }
  326. //-------------------------------------
  327. type bpRequester struct {
  328. QuitService
  329. pool *BlockPool
  330. height int
  331. gotBlockCh chan struct{}
  332. redoCh chan struct{}
  333. mtx sync.Mutex
  334. peerID string
  335. block *types.Block
  336. }
  337. func newBPRequester(pool *BlockPool, height int) *bpRequester {
  338. bpr := &bpRequester{
  339. pool: pool,
  340. height: height,
  341. gotBlockCh: make(chan struct{}),
  342. redoCh: make(chan struct{}),
  343. peerID: "",
  344. block: nil,
  345. }
  346. bpr.QuitService = *NewQuitService(nil, "bpRequester", bpr)
  347. return bpr
  348. }
  349. func (bpr *bpRequester) OnStart() error {
  350. bpr.QuitService.OnStart()
  351. go bpr.requestRoutine()
  352. return nil
  353. }
  354. // Returns true if the peer matches
  355. func (bpr *bpRequester) setBlock(block *types.Block, peerID string) bool {
  356. bpr.mtx.Lock()
  357. if bpr.block != nil || bpr.peerID != peerID {
  358. bpr.mtx.Unlock()
  359. return false
  360. }
  361. bpr.block = block
  362. bpr.mtx.Unlock()
  363. bpr.gotBlockCh <- struct{}{}
  364. return true
  365. }
  366. func (bpr *bpRequester) getBlock() *types.Block {
  367. bpr.mtx.Lock()
  368. defer bpr.mtx.Unlock()
  369. return bpr.block
  370. }
  371. func (bpr *bpRequester) getPeerID() string {
  372. bpr.mtx.Lock()
  373. defer bpr.mtx.Unlock()
  374. return bpr.peerID
  375. }
  376. func (bpr *bpRequester) reset() {
  377. bpr.mtx.Lock()
  378. bpr.peerID = ""
  379. bpr.block = nil
  380. bpr.mtx.Unlock()
  381. }
  382. // Tells bpRequester to pick another peer and try again.
  383. // NOTE: blocking
  384. func (bpr *bpRequester) redo() {
  385. bpr.redoCh <- struct{}{}
  386. }
  387. // Responsible for making more requests as necessary
  388. // Returns only when a block is found (e.g. AddBlock() is called)
  389. func (bpr *bpRequester) requestRoutine() {
  390. OUTER_LOOP:
  391. for {
  392. // Pick a peer to send request to.
  393. var peer *bpPeer = nil
  394. PICK_PEER_LOOP:
  395. for {
  396. if !bpr.IsRunning() || !bpr.pool.IsRunning() {
  397. return
  398. }
  399. peer = bpr.pool.pickIncrAvailablePeer(bpr.height)
  400. if peer == nil {
  401. //log.Info("No peers available", "height", height)
  402. time.Sleep(requestIntervalMS * time.Millisecond)
  403. continue PICK_PEER_LOOP
  404. }
  405. break PICK_PEER_LOOP
  406. }
  407. bpr.mtx.Lock()
  408. bpr.peerID = peer.id
  409. bpr.mtx.Unlock()
  410. // Send request and wait.
  411. bpr.pool.sendRequest(bpr.height, peer.id)
  412. select {
  413. case <-bpr.pool.Quit:
  414. bpr.Stop()
  415. return
  416. case <-bpr.Quit:
  417. return
  418. case <-bpr.redoCh:
  419. bpr.reset()
  420. continue OUTER_LOOP // When peer is removed
  421. case <-bpr.gotBlockCh:
  422. // We got the block, now see if it's good.
  423. select {
  424. case <-bpr.pool.Quit:
  425. bpr.Stop()
  426. return
  427. case <-bpr.Quit:
  428. return
  429. case <-bpr.redoCh:
  430. bpr.reset()
  431. continue OUTER_LOOP
  432. }
  433. }
  434. }
  435. }
  436. //-------------------------------------
  437. type BlockRequest struct {
  438. Height int
  439. PeerID string
  440. }