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.

522 lines
12 KiB

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