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.

493 lines
11 KiB

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 = 500
  12. maxTotalRequests = 300
  13. maxPendingRequests = maxTotalRequests
  14. maxPendingRequestsPerPeer = 30
  15. peerTimeoutSeconds = 10
  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. // block requests
  30. mtx sync.Mutex
  31. requests map[int]*bpRequester
  32. height int // the lowest key in requests.
  33. numPending int32 // number of requests pending assignment or block response
  34. // peers
  35. peersMtx sync.Mutex
  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. requests: make(map[int]*bpRequester),
  44. height: start,
  45. numPending: 0,
  46. requestsCh: requestsCh,
  47. timeoutsCh: timeoutsCh,
  48. }
  49. bp.QuitService = *NewQuitService(log, "BlockPool", bp)
  50. return bp
  51. }
  52. func (pool *BlockPool) OnStart() error {
  53. pool.QuitService.OnStart()
  54. go pool.makeRequestsRoutine()
  55. return nil
  56. }
  57. func (pool *BlockPool) OnStop() {
  58. pool.QuitService.OnStop()
  59. }
  60. // Run spawns requests as needed.
  61. func (pool *BlockPool) makeRequestsRoutine() {
  62. for {
  63. if !pool.IsRunning() {
  64. break
  65. }
  66. _, numPending := 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 len(pool.requests) >= maxTotalRequests {
  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.makeNextRequest()
  80. }
  81. }
  82. }
  83. func (pool *BlockPool) removeTimedoutPeers() {
  84. for _, peer := range pool.peers {
  85. if !peer.didTimeout && peer.numPending > 0 {
  86. curRate := peer.recvMonitor.Status().CurRate
  87. // XXX remove curRate != 0
  88. if curRate != 0 && curRate < minRecvRate {
  89. pool.sendTimeout(peer.id)
  90. peer.didTimeout = true
  91. }
  92. }
  93. if peer.didTimeout {
  94. pool.removePeer(peer.id)
  95. }
  96. }
  97. }
  98. func (pool *BlockPool) GetStatus() (height int, numPending int32) {
  99. pool.mtx.Lock() // Lock
  100. defer pool.mtx.Unlock()
  101. return pool.height, pool.numPending
  102. }
  103. // TODO: relax conditions, prevent abuse.
  104. func (pool *BlockPool) IsCaughtUp() bool {
  105. pool.mtx.Lock()
  106. height := pool.height
  107. pool.mtx.Unlock()
  108. pool.peersMtx.Lock()
  109. numPeers := len(pool.peers)
  110. maxPeerHeight := 0
  111. for _, peer := range pool.peers {
  112. maxPeerHeight = MaxInt(maxPeerHeight, peer.height)
  113. }
  114. pool.peersMtx.Unlock()
  115. return numPeers >= 3 && height > 0 && height == maxPeerHeight
  116. }
  117. // We need to see the second block's Validation to validate the first block.
  118. // So we peek two blocks at a time.
  119. func (pool *BlockPool) PeekTwoBlocks() (first *types.Block, second *types.Block) {
  120. pool.mtx.Lock() // Lock
  121. defer pool.mtx.Unlock()
  122. if r := pool.requests[pool.height]; r != nil {
  123. first = r.block
  124. }
  125. if r := pool.requests[pool.height+1]; r != nil {
  126. second = r.block
  127. }
  128. return
  129. }
  130. // Pop the first block at pool.height
  131. // It must have been validated by 'second'.Validation from PeekTwoBlocks().
  132. func (pool *BlockPool) PopRequest() {
  133. pool.mtx.Lock() // Lock
  134. defer pool.mtx.Unlock()
  135. if r := pool.requests[pool.height]; r == nil || r.block == nil {
  136. PanicSanity("PopRequest() requires a valid block")
  137. }
  138. delete(pool.requests, pool.height)
  139. pool.height++
  140. }
  141. // Invalidates the block at pool.height,
  142. // Remove the peer and redo request from others.
  143. func (pool *BlockPool) RedoRequest(height int) {
  144. pool.mtx.Lock() // Lock
  145. defer pool.mtx.Unlock()
  146. request := pool.requests[height]
  147. if request.block == nil {
  148. PanicSanity("Expected block to be non-nil")
  149. }
  150. // RemovePeer will redo all requests associated with this peer.
  151. // TODO: record this malfeasance
  152. pool.RemovePeer(request.peerID) // Lock on peersMtx.
  153. }
  154. // TODO: ensure that blocks come in order for each peer.
  155. func (pool *BlockPool) AddBlock(peerID string, block *types.Block, blockSize int) {
  156. pool.mtx.Lock() // Lock
  157. defer pool.mtx.Unlock()
  158. request := pool.requests[block.Height]
  159. if request == nil {
  160. return
  161. }
  162. if request.setBlock(block, peerID) {
  163. pool.numPending--
  164. peer := pool.getPeer(peerID)
  165. peer.decrPending(blockSize)
  166. } else {
  167. // Bad peer?
  168. }
  169. }
  170. // Sets the peer's alleged blockchain height.
  171. func (pool *BlockPool) SetPeerHeight(peerID string, height int) {
  172. pool.peersMtx.Lock() // Lock
  173. defer pool.peersMtx.Unlock()
  174. peer := pool.peers[peerID]
  175. if peer != nil {
  176. peer.height = height
  177. } else {
  178. peer = newBPPeer(pool, peerID, height)
  179. pool.peers[peerID] = peer
  180. }
  181. }
  182. func (pool *BlockPool) RemovePeer(peerID string) {
  183. pool.peersMtx.Lock() // Lock
  184. defer pool.peersMtx.Unlock()
  185. pool.removePeer(peerID)
  186. }
  187. func (pool *BlockPool) removePeer(peerID string) {
  188. for _, request := range pool.requests {
  189. if request.getPeerID() == peerID {
  190. pool.numPending++
  191. request.redo() // pick another peer and ...
  192. }
  193. }
  194. delete(pool.peers, peerID)
  195. }
  196. func (pool *BlockPool) getPeer(peerID string) *bpPeer {
  197. pool.peersMtx.Lock() // Lock
  198. defer pool.peersMtx.Unlock()
  199. peer := pool.peers[peerID]
  200. return peer
  201. }
  202. // Pick an available peer with at least the given minHeight.
  203. // If no peers are available, returns nil.
  204. func (pool *BlockPool) pickIncrAvailablePeer(minHeight int) *bpPeer {
  205. pool.peersMtx.Lock()
  206. defer pool.peersMtx.Unlock()
  207. for _, peer := range pool.peers {
  208. if peer.isBad() {
  209. pool.removePeer(peer.id)
  210. continue
  211. } else {
  212. }
  213. if peer.numPending >= maxPendingRequestsPerPeer {
  214. continue
  215. }
  216. if peer.height < minHeight {
  217. continue
  218. }
  219. peer.incrPending()
  220. return peer
  221. }
  222. return nil
  223. }
  224. func (pool *BlockPool) makeNextRequest() {
  225. pool.mtx.Lock() // Lock
  226. defer pool.mtx.Unlock()
  227. nextHeight := pool.height + len(pool.requests)
  228. request := newBPRequester(pool, nextHeight)
  229. pool.requests[nextHeight] = request
  230. pool.numPending++
  231. request.Start()
  232. }
  233. func (pool *BlockPool) sendRequest(height int, peerID string) {
  234. if !pool.IsRunning() {
  235. return
  236. }
  237. pool.requestsCh <- BlockRequest{height, peerID}
  238. }
  239. func (pool *BlockPool) sendTimeout(peerID string) {
  240. if !pool.IsRunning() {
  241. return
  242. }
  243. pool.timeoutsCh <- peerID
  244. }
  245. func (pool *BlockPool) debug() string {
  246. pool.mtx.Lock() // Lock
  247. defer pool.mtx.Unlock()
  248. str := ""
  249. for h := pool.height; h < pool.height+len(pool.requests); h++ {
  250. if pool.requests[h] == nil {
  251. str += Fmt("H(%v):X ", h)
  252. } else {
  253. str += Fmt("H(%v):", h)
  254. str += Fmt("B?(%v) ", pool.requests[h].block != nil)
  255. }
  256. }
  257. return str
  258. }
  259. //-------------------------------------
  260. type bpPeer struct {
  261. pool *BlockPool
  262. id string
  263. height int
  264. numPending int32
  265. recvMonitor *flow.Monitor
  266. timeout *time.Timer
  267. didTimeout bool
  268. }
  269. func newBPPeer(pool *BlockPool, peerID string, height int) *bpPeer {
  270. peer := &bpPeer{
  271. pool: pool,
  272. id: peerID,
  273. height: height,
  274. numPending: 0,
  275. }
  276. return peer
  277. }
  278. func (bpp *bpPeer) resetMonitor() {
  279. bpp.recvMonitor = flow.New(time.Second, time.Second*40)
  280. var initialValue = float64(minRecvRate) * math.E
  281. bpp.recvMonitor.SetREMA(initialValue)
  282. }
  283. func (bpp *bpPeer) resetTimeout() {
  284. if bpp.timeout == nil {
  285. bpp.timeout = time.AfterFunc(time.Second*peerTimeoutSeconds, bpp.onTimeout)
  286. } else {
  287. bpp.timeout.Reset(time.Second * peerTimeoutSeconds)
  288. }
  289. }
  290. func (bpp *bpPeer) incrPending() {
  291. if bpp.numPending == 0 {
  292. bpp.resetMonitor()
  293. bpp.resetTimeout()
  294. }
  295. bpp.numPending++
  296. }
  297. func (bpp *bpPeer) decrPending(recvSize int) {
  298. bpp.numPending--
  299. if bpp.numPending == 0 {
  300. bpp.timeout.Stop()
  301. } else {
  302. bpp.recvMonitor.Update(recvSize)
  303. bpp.resetTimeout()
  304. }
  305. }
  306. func (bpp *bpPeer) onTimeout() {
  307. bpp.pool.sendTimeout(bpp.id)
  308. bpp.didTimeout = true
  309. }
  310. func (bpp *bpPeer) isBad() bool {
  311. return bpp.didTimeout
  312. }
  313. //-------------------------------------
  314. type bpRequester struct {
  315. QuitService
  316. pool *BlockPool
  317. height int
  318. gotBlockCh chan struct{}
  319. redoCh chan struct{}
  320. mtx sync.Mutex
  321. peerID string
  322. block *types.Block
  323. }
  324. func newBPRequester(pool *BlockPool, height int) *bpRequester {
  325. bpr := &bpRequester{
  326. pool: pool,
  327. height: height,
  328. gotBlockCh: make(chan struct{}),
  329. redoCh: make(chan struct{}),
  330. peerID: "",
  331. block: nil,
  332. }
  333. bpr.QuitService = *NewQuitService(nil, "bpRequester", bpr)
  334. return bpr
  335. }
  336. func (bpr *bpRequester) OnStart() error {
  337. bpr.QuitService.OnStart()
  338. go bpr.requestRoutine()
  339. return nil
  340. }
  341. // Returns true if the peer matches
  342. func (bpr *bpRequester) setBlock(block *types.Block, peerID string) bool {
  343. bpr.mtx.Lock()
  344. if bpr.block != nil || bpr.peerID != peerID {
  345. bpr.mtx.Unlock()
  346. return false
  347. }
  348. bpr.block = block
  349. bpr.mtx.Unlock()
  350. bpr.gotBlockCh <- struct{}{}
  351. return true
  352. }
  353. func (bpr *bpRequester) getPeerID() string {
  354. bpr.mtx.Lock()
  355. defer bpr.mtx.Unlock()
  356. return bpr.peerID
  357. }
  358. func (bpr *bpRequester) reset() {
  359. bpr.mtx.Lock()
  360. bpr.peerID = ""
  361. bpr.block = nil
  362. bpr.mtx.Unlock()
  363. }
  364. // Tells bpRequester to pick another peer and try again.
  365. func (bpr *bpRequester) redo() {
  366. bpr.redoCh <- struct{}{}
  367. }
  368. // Responsible for making more requests as necessary
  369. // Returns only when a block is found (e.g. AddBlock() is called)
  370. func (bpr *bpRequester) requestRoutine() {
  371. OUTER_LOOP:
  372. for {
  373. // Pick a peer to send request to.
  374. var peer *bpPeer = nil
  375. PICK_PEER_LOOP:
  376. for {
  377. if !bpr.IsRunning() || !bpr.pool.IsRunning() {
  378. return
  379. }
  380. peer = bpr.pool.pickIncrAvailablePeer(bpr.height)
  381. if peer == nil {
  382. //log.Info("No peers available", "height", height)
  383. time.Sleep(requestIntervalMS * time.Millisecond)
  384. continue PICK_PEER_LOOP
  385. }
  386. break PICK_PEER_LOOP
  387. }
  388. bpr.mtx.Lock()
  389. bpr.peerID = peer.id
  390. bpr.mtx.Unlock()
  391. // Send request and wait.
  392. bpr.pool.sendRequest(bpr.height, peer.id)
  393. select {
  394. case <-bpr.pool.Quit:
  395. bpr.Stop()
  396. return
  397. case <-bpr.Quit:
  398. return
  399. case <-bpr.redoCh:
  400. bpr.reset()
  401. continue OUTER_LOOP // When peer is removed
  402. case <-bpr.gotBlockCh:
  403. // We got the block, now see if it's good.
  404. select {
  405. case <-bpr.pool.Quit:
  406. bpr.Stop()
  407. return
  408. case <-bpr.Quit:
  409. return
  410. case <-bpr.redoCh:
  411. bpr.reset()
  412. continue OUTER_LOOP
  413. }
  414. }
  415. }
  416. }
  417. //-------------------------------------
  418. type BlockRequest struct {
  419. Height int
  420. PeerID string
  421. }