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.

508 lines
11 KiB

10 years ago
10 years ago
10 years ago
10 years ago
  1. package blockchain
  2. import (
  3. "math"
  4. "sync"
  5. "time"
  6. flow "github.com/tendermint/tendermint/Godeps/_workspace/src/code.google.com/p/mxk/go1/flowcontrol"
  7. . "github.com/tendermint/tendermint/common"
  8. "github.com/tendermint/tendermint/types"
  9. )
  10. const (
  11. requestIntervalMS = 250
  12. maxTotalRequests = 300
  13. maxPendingRequests = maxTotalRequests
  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. requests map[int]*bpRequester
  33. height int // the lowest key in requests.
  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. requests: 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.makeRequestsRoutine()
  56. pool.startTime = time.Now()
  57. return nil
  58. }
  59. func (pool *BlockPool) OnStop() {
  60. pool.QuitService.OnStop()
  61. }
  62. // Run spawns requests as needed.
  63. func (pool *BlockPool) makeRequestsRoutine() {
  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.requests) >= maxTotalRequests {
  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.makeNextRequest()
  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.requests[pool.height]; r != nil {
  128. first = r.getBlock()
  129. }
  130. if r := pool.requests[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. /* The block can disappear at any time, due to removePeer().
  141. if r := pool.requests[pool.height]; r == nil || r.block == nil {
  142. PanicSanity("PopRequest() requires a valid block")
  143. }
  144. */
  145. delete(pool.requests, pool.height)
  146. pool.height++
  147. }
  148. // Invalidates the block at pool.height,
  149. // Remove the peer and redo request from others.
  150. func (pool *BlockPool) RedoRequest(height int) {
  151. pool.mtx.Lock() // Lock
  152. defer pool.mtx.Unlock()
  153. request := pool.requests[height]
  154. if request.block == nil {
  155. PanicSanity("Expected block to be non-nil")
  156. }
  157. // RemovePeer will redo all requests associated with this peer.
  158. // TODO: record this malfeasance
  159. pool.RemovePeer(request.peerID) // Lock on peersMtx.
  160. }
  161. // TODO: ensure that blocks come in order for each peer.
  162. func (pool *BlockPool) AddBlock(peerID string, block *types.Block, blockSize int) {
  163. pool.mtx.Lock() // Lock
  164. defer pool.mtx.Unlock()
  165. request := pool.requests[block.Height]
  166. if request == nil {
  167. return
  168. }
  169. if request.setBlock(block, peerID) {
  170. pool.numPending--
  171. peer := pool.getPeer(peerID)
  172. peer.decrPending(blockSize)
  173. } else {
  174. // Bad peer?
  175. }
  176. }
  177. // Sets the peer's alleged blockchain height.
  178. func (pool *BlockPool) SetPeerHeight(peerID string, height int) {
  179. pool.peersMtx.Lock() // Lock
  180. defer pool.peersMtx.Unlock()
  181. peer := pool.peers[peerID]
  182. if peer != nil {
  183. peer.height = height
  184. } else {
  185. peer = newBPPeer(pool, peerID, height)
  186. pool.peers[peerID] = peer
  187. }
  188. }
  189. func (pool *BlockPool) RemovePeer(peerID string) {
  190. pool.peersMtx.Lock() // Lock
  191. defer pool.peersMtx.Unlock()
  192. pool.removePeer(peerID)
  193. }
  194. func (pool *BlockPool) removePeer(peerID string) {
  195. for _, request := range pool.requests {
  196. if request.getPeerID() == peerID {
  197. pool.numPending++
  198. go request.redo() // pick another peer and ...
  199. }
  200. }
  201. delete(pool.peers, peerID)
  202. }
  203. func (pool *BlockPool) getPeer(peerID string) *bpPeer {
  204. pool.peersMtx.Lock() // Lock
  205. defer pool.peersMtx.Unlock()
  206. peer := pool.peers[peerID]
  207. return peer
  208. }
  209. // Pick an available peer with at least the given minHeight.
  210. // If no peers are available, returns nil.
  211. func (pool *BlockPool) pickIncrAvailablePeer(minHeight int) *bpPeer {
  212. pool.peersMtx.Lock()
  213. defer pool.peersMtx.Unlock()
  214. for _, peer := range pool.peers {
  215. if peer.isBad() {
  216. pool.removePeer(peer.id)
  217. continue
  218. } else {
  219. }
  220. if peer.numPending >= maxPendingRequestsPerPeer {
  221. continue
  222. }
  223. if peer.height < minHeight {
  224. continue
  225. }
  226. peer.incrPending()
  227. return peer
  228. }
  229. return nil
  230. }
  231. func (pool *BlockPool) makeNextRequest() {
  232. pool.mtx.Lock() // Lock
  233. defer pool.mtx.Unlock()
  234. nextHeight := pool.height + len(pool.requests)
  235. request := newBPRequester(pool, nextHeight)
  236. pool.requests[nextHeight] = request
  237. pool.numPending++
  238. request.Start()
  239. }
  240. func (pool *BlockPool) sendRequest(height int, peerID string) {
  241. if !pool.IsRunning() {
  242. return
  243. }
  244. pool.requestsCh <- BlockRequest{height, peerID}
  245. }
  246. func (pool *BlockPool) sendTimeout(peerID string) {
  247. if !pool.IsRunning() {
  248. return
  249. }
  250. pool.timeoutsCh <- peerID
  251. }
  252. func (pool *BlockPool) debug() string {
  253. pool.mtx.Lock() // Lock
  254. defer pool.mtx.Unlock()
  255. str := ""
  256. for h := pool.height; h < pool.height+len(pool.requests); h++ {
  257. if pool.requests[h] == nil {
  258. str += Fmt("H(%v):X ", h)
  259. } else {
  260. str += Fmt("H(%v):", h)
  261. str += Fmt("B?(%v) ", pool.requests[h].block != nil)
  262. }
  263. }
  264. return str
  265. }
  266. //-------------------------------------
  267. type bpPeer struct {
  268. pool *BlockPool
  269. id string
  270. height int
  271. numPending int32
  272. recvMonitor *flow.Monitor
  273. timeout *time.Timer
  274. didTimeout bool
  275. }
  276. func newBPPeer(pool *BlockPool, peerID string, height int) *bpPeer {
  277. peer := &bpPeer{
  278. pool: pool,
  279. id: peerID,
  280. height: height,
  281. numPending: 0,
  282. }
  283. return peer
  284. }
  285. func (peer *bpPeer) resetMonitor() {
  286. peer.recvMonitor = flow.New(time.Second, time.Second*40)
  287. var initialValue = float64(minRecvRate) * math.E
  288. peer.recvMonitor.SetREMA(initialValue)
  289. }
  290. func (peer *bpPeer) resetTimeout() {
  291. if peer.timeout == nil {
  292. peer.timeout = time.AfterFunc(time.Second*peerTimeoutSeconds, peer.onTimeout)
  293. } else {
  294. peer.timeout.Reset(time.Second * peerTimeoutSeconds)
  295. }
  296. }
  297. func (peer *bpPeer) incrPending() {
  298. if peer.numPending == 0 {
  299. peer.resetMonitor()
  300. peer.resetTimeout()
  301. }
  302. peer.numPending++
  303. }
  304. func (peer *bpPeer) decrPending(recvSize int) {
  305. peer.numPending--
  306. if peer.numPending == 0 {
  307. peer.timeout.Stop()
  308. } else {
  309. peer.recvMonitor.Update(recvSize)
  310. peer.resetTimeout()
  311. }
  312. }
  313. func (peer *bpPeer) onTimeout() {
  314. peer.pool.sendTimeout(peer.id)
  315. log.Warn("SendTimeout", "peer", peer.id, "reason", "onTimeout")
  316. peer.didTimeout = true
  317. }
  318. func (peer *bpPeer) isBad() bool {
  319. return peer.didTimeout
  320. }
  321. //-------------------------------------
  322. type bpRequester struct {
  323. QuitService
  324. pool *BlockPool
  325. height int
  326. gotBlockCh chan struct{}
  327. redoCh chan struct{}
  328. mtx sync.Mutex
  329. peerID string
  330. block *types.Block
  331. }
  332. func newBPRequester(pool *BlockPool, height int) *bpRequester {
  333. bpr := &bpRequester{
  334. pool: pool,
  335. height: height,
  336. gotBlockCh: make(chan struct{}),
  337. redoCh: make(chan struct{}),
  338. peerID: "",
  339. block: nil,
  340. }
  341. bpr.QuitService = *NewQuitService(nil, "bpRequester", bpr)
  342. return bpr
  343. }
  344. func (bpr *bpRequester) OnStart() error {
  345. bpr.QuitService.OnStart()
  346. go bpr.requestRoutine()
  347. return nil
  348. }
  349. // Returns true if the peer matches
  350. func (bpr *bpRequester) setBlock(block *types.Block, peerID string) bool {
  351. bpr.mtx.Lock()
  352. if bpr.block != nil || bpr.peerID != peerID {
  353. bpr.mtx.Unlock()
  354. return false
  355. }
  356. bpr.block = block
  357. bpr.mtx.Unlock()
  358. bpr.gotBlockCh <- struct{}{}
  359. return true
  360. }
  361. func (bpr *bpRequester) getBlock() *types.Block {
  362. bpr.mtx.Lock()
  363. defer bpr.mtx.Unlock()
  364. return bpr.block
  365. }
  366. func (bpr *bpRequester) getPeerID() string {
  367. bpr.mtx.Lock()
  368. defer bpr.mtx.Unlock()
  369. return bpr.peerID
  370. }
  371. func (bpr *bpRequester) reset() {
  372. bpr.mtx.Lock()
  373. bpr.peerID = ""
  374. bpr.block = nil
  375. bpr.mtx.Unlock()
  376. }
  377. // Tells bpRequester to pick another peer and try again.
  378. // NOTE: blocking
  379. func (bpr *bpRequester) redo() {
  380. bpr.redoCh <- struct{}{}
  381. }
  382. // Responsible for making more requests as necessary
  383. // Returns only when a block is found (e.g. AddBlock() is called)
  384. func (bpr *bpRequester) requestRoutine() {
  385. OUTER_LOOP:
  386. for {
  387. // Pick a peer to send request to.
  388. var peer *bpPeer = nil
  389. PICK_PEER_LOOP:
  390. for {
  391. if !bpr.IsRunning() || !bpr.pool.IsRunning() {
  392. return
  393. }
  394. peer = bpr.pool.pickIncrAvailablePeer(bpr.height)
  395. if peer == nil {
  396. //log.Info("No peers available", "height", height)
  397. time.Sleep(requestIntervalMS * time.Millisecond)
  398. continue PICK_PEER_LOOP
  399. }
  400. break PICK_PEER_LOOP
  401. }
  402. bpr.mtx.Lock()
  403. bpr.peerID = peer.id
  404. bpr.mtx.Unlock()
  405. // Send request and wait.
  406. bpr.pool.sendRequest(bpr.height, peer.id)
  407. select {
  408. case <-bpr.pool.Quit:
  409. bpr.Stop()
  410. return
  411. case <-bpr.Quit:
  412. return
  413. case <-bpr.redoCh:
  414. bpr.reset()
  415. continue OUTER_LOOP // When peer is removed
  416. case <-bpr.gotBlockCh:
  417. // We got the block, now see if it's good.
  418. select {
  419. case <-bpr.pool.Quit:
  420. bpr.Stop()
  421. return
  422. case <-bpr.Quit:
  423. return
  424. case <-bpr.redoCh:
  425. bpr.reset()
  426. continue OUTER_LOOP
  427. }
  428. }
  429. }
  430. }
  431. //-------------------------------------
  432. type BlockRequest struct {
  433. Height int
  434. PeerID string
  435. }