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.

328 lines
9.4 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. package blockchain
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "reflect"
  7. "time"
  8. "github.com/tendermint/tendermint/wire"
  9. . "github.com/tendermint/tendermint/common"
  10. "github.com/tendermint/tendermint/events"
  11. "github.com/tendermint/tendermint/p2p"
  12. sm "github.com/tendermint/tendermint/state"
  13. "github.com/tendermint/tendermint/types"
  14. )
  15. const (
  16. BlockchainChannel = byte(0x40)
  17. defaultChannelCapacity = 100
  18. defaultSleepIntervalMS = 500
  19. trySyncIntervalMS = 100
  20. // stop syncing when last block's time is
  21. // within this much of the system time.
  22. // stopSyncingDurationMinutes = 10
  23. // ask for best height every 10s
  24. statusUpdateIntervalSeconds = 10
  25. // check if we should switch to consensus reactor
  26. switchToConsensusIntervalSeconds = 10
  27. )
  28. type consensusReactor interface {
  29. // for when we switch from blockchain reactor and fast sync to
  30. // the consensus machine
  31. SwitchToConsensus(*sm.State)
  32. }
  33. // BlockchainReactor handles long-term catchup syncing.
  34. type BlockchainReactor struct {
  35. p2p.BaseReactor
  36. sw *p2p.Switch
  37. state *sm.State
  38. store *BlockStore
  39. pool *BlockPool
  40. sync bool
  41. requestsCh chan BlockRequest
  42. timeoutsCh chan string
  43. lastBlock *types.Block
  44. evsw events.Fireable
  45. }
  46. func NewBlockchainReactor(state *sm.State, store *BlockStore, sync bool) *BlockchainReactor {
  47. if state.LastBlockHeight != store.Height() &&
  48. state.LastBlockHeight != store.Height()-1 { // XXX double check this logic.
  49. PanicSanity(Fmt("state (%v) and store (%v) height mismatch", state.LastBlockHeight, store.Height()))
  50. }
  51. requestsCh := make(chan BlockRequest, defaultChannelCapacity)
  52. timeoutsCh := make(chan string, defaultChannelCapacity)
  53. pool := NewBlockPool(
  54. store.Height()+1,
  55. requestsCh,
  56. timeoutsCh,
  57. )
  58. bcR := &BlockchainReactor{
  59. state: state,
  60. store: store,
  61. pool: pool,
  62. sync: sync,
  63. requestsCh: requestsCh,
  64. timeoutsCh: timeoutsCh,
  65. }
  66. bcR.BaseReactor = *p2p.NewBaseReactor(log, "BlockchainReactor", bcR)
  67. return bcR
  68. }
  69. func (bcR *BlockchainReactor) OnStart() {
  70. bcR.BaseReactor.OnStart()
  71. if bcR.sync {
  72. bcR.pool.Start()
  73. go bcR.poolRoutine()
  74. }
  75. }
  76. func (bcR *BlockchainReactor) OnStop() {
  77. bcR.BaseReactor.OnStop()
  78. bcR.pool.Stop()
  79. }
  80. // Implements Reactor
  81. func (bcR *BlockchainReactor) GetChannels() []*p2p.ChannelDescriptor {
  82. return []*p2p.ChannelDescriptor{
  83. &p2p.ChannelDescriptor{
  84. Id: BlockchainChannel,
  85. Priority: 5,
  86. SendQueueCapacity: 100,
  87. },
  88. }
  89. }
  90. // Implements Reactor
  91. func (bcR *BlockchainReactor) AddPeer(peer *p2p.Peer) {
  92. // Send peer our state.
  93. peer.Send(BlockchainChannel, &bcStatusResponseMessage{bcR.store.Height()})
  94. }
  95. // Implements Reactor
  96. func (bcR *BlockchainReactor) RemovePeer(peer *p2p.Peer, reason interface{}) {
  97. // Remove peer from the pool.
  98. bcR.pool.RemovePeer(peer.Key)
  99. }
  100. // Implements Reactor
  101. func (bcR *BlockchainReactor) Receive(chId byte, src *p2p.Peer, msgBytes []byte) {
  102. _, msg, err := DecodeMessage(msgBytes)
  103. if err != nil {
  104. log.Warn("Error decoding message", "error", err)
  105. return
  106. }
  107. log.Notice("Received message", "msg", msg)
  108. switch msg := msg.(type) {
  109. case *bcBlockRequestMessage:
  110. // Got a request for a block. Respond with block if we have it.
  111. block := bcR.store.LoadBlock(msg.Height)
  112. if block != nil {
  113. msg := &bcBlockResponseMessage{Block: block}
  114. queued := src.TrySend(BlockchainChannel, msg)
  115. if !queued {
  116. // queue is full, just ignore.
  117. }
  118. } else {
  119. // TODO peer is asking for things we don't have.
  120. }
  121. case *bcBlockResponseMessage:
  122. // Got a block.
  123. bcR.pool.AddBlock(msg.Block, src.Key)
  124. case *bcStatusRequestMessage:
  125. // Send peer our state.
  126. queued := src.TrySend(BlockchainChannel, &bcStatusResponseMessage{bcR.store.Height()})
  127. if !queued {
  128. // sorry
  129. }
  130. case *bcStatusResponseMessage:
  131. // Got a peer status. Unverified.
  132. bcR.pool.SetPeerHeight(src.Key, msg.Height)
  133. default:
  134. log.Warn(Fmt("Unknown message type %v", reflect.TypeOf(msg)))
  135. }
  136. }
  137. // Handle messages from the poolReactor telling the reactor what to do.
  138. // NOTE: Don't sleep in the FOR_LOOP or otherwise slow it down!
  139. // (Except for the SYNC_LOOP, which is the primary purpose and must be synchronous.)
  140. func (bcR *BlockchainReactor) poolRoutine() {
  141. trySyncTicker := time.NewTicker(trySyncIntervalMS * time.Millisecond)
  142. statusUpdateTicker := time.NewTicker(statusUpdateIntervalSeconds * time.Second)
  143. switchToConsensusTicker := time.NewTicker(switchToConsensusIntervalSeconds * time.Second)
  144. FOR_LOOP:
  145. for {
  146. select {
  147. case request := <-bcR.requestsCh: // chan BlockRequest
  148. peer := bcR.Switch.Peers().Get(request.PeerId)
  149. if peer == nil {
  150. // We can't assign the request.
  151. continue FOR_LOOP
  152. }
  153. msg := &bcBlockRequestMessage{request.Height}
  154. queued := peer.TrySend(BlockchainChannel, msg)
  155. if !queued {
  156. // We couldn't make the request, send-queue full.
  157. // The pool handles retries, so just let it go.
  158. continue FOR_LOOP
  159. }
  160. case peerId := <-bcR.timeoutsCh: // chan string
  161. // Peer timed out.
  162. peer := bcR.Switch.Peers().Get(peerId)
  163. if peer != nil {
  164. bcR.Switch.StopPeerForError(peer, errors.New("BlockchainReactor Timeout"))
  165. }
  166. case _ = <-statusUpdateTicker.C:
  167. // ask for status updates
  168. go bcR.BroadcastStatusRequest()
  169. case _ = <-switchToConsensusTicker.C:
  170. height, numPending, numUnassigned := bcR.pool.GetStatus()
  171. outbound, inbound, _ := bcR.Switch.NumPeers()
  172. log.Info("Consensus ticker", "numUnassigned", numUnassigned, "numPending", numPending,
  173. "total", len(bcR.pool.requests), "outbound", outbound, "inbound", inbound)
  174. // NOTE: this condition is very strict right now. may need to weaken
  175. // If all `maxPendingRequests` requests are unassigned
  176. // and we have some peers (say >= 3), then we're caught up
  177. maxPending := numPending == maxPendingRequests
  178. allUnassigned := numPending == numUnassigned
  179. enoughPeers := outbound+inbound >= 3
  180. if maxPending && allUnassigned && enoughPeers {
  181. log.Notice("Time to switch to consensus reactor!", "height", height)
  182. bcR.pool.Stop()
  183. conR := bcR.Switch.Reactor("CONSENSUS").(consensusReactor)
  184. conR.SwitchToConsensus(bcR.state)
  185. break FOR_LOOP
  186. }
  187. case _ = <-trySyncTicker.C: // chan time
  188. // This loop can be slow as long as it's doing syncing work.
  189. SYNC_LOOP:
  190. for i := 0; i < 10; i++ {
  191. // See if there are any blocks to sync.
  192. first, second := bcR.pool.PeekTwoBlocks()
  193. //log.Info("TrySync peeked", "first", first, "second", second)
  194. if first == nil || second == nil {
  195. // We need both to sync the first block.
  196. break SYNC_LOOP
  197. }
  198. firstParts := first.MakePartSet()
  199. firstPartsHeader := firstParts.Header()
  200. // Finally, verify the first block using the second's validation.
  201. err := bcR.state.BondedValidators.VerifyValidation(
  202. bcR.state.ChainID, first.Hash(), firstPartsHeader, first.Height, second.LastValidation)
  203. if err != nil {
  204. log.Info("error in validation", "error", err)
  205. bcR.pool.RedoRequest(first.Height)
  206. break SYNC_LOOP
  207. } else {
  208. bcR.pool.PopRequest()
  209. err := sm.ExecBlock(bcR.state, first, firstPartsHeader)
  210. if err != nil {
  211. // TODO This is bad, are we zombie?
  212. PanicQ(Fmt("Failed to process committed block: %v", err))
  213. }
  214. bcR.store.SaveBlock(first, firstParts, second.LastValidation)
  215. bcR.state.Save()
  216. }
  217. }
  218. continue FOR_LOOP
  219. case <-bcR.Quit:
  220. break FOR_LOOP
  221. }
  222. }
  223. }
  224. func (bcR *BlockchainReactor) BroadcastStatusResponse() error {
  225. bcR.Switch.Broadcast(BlockchainChannel, &bcStatusResponseMessage{bcR.store.Height()})
  226. return nil
  227. }
  228. func (bcR *BlockchainReactor) BroadcastStatusRequest() error {
  229. bcR.Switch.Broadcast(BlockchainChannel, &bcStatusRequestMessage{bcR.store.Height()})
  230. return nil
  231. }
  232. // implements events.Eventable
  233. func (bcR *BlockchainReactor) SetFireable(evsw events.Fireable) {
  234. bcR.evsw = evsw
  235. }
  236. //-----------------------------------------------------------------------------
  237. // Messages
  238. const (
  239. msgTypeBlockRequest = byte(0x10)
  240. msgTypeBlockResponse = byte(0x11)
  241. msgTypeStatusResponse = byte(0x20)
  242. msgTypeStatusRequest = byte(0x21)
  243. )
  244. type BlockchainMessage interface{}
  245. var _ = wire.RegisterInterface(
  246. struct{ BlockchainMessage }{},
  247. wire.ConcreteType{&bcBlockRequestMessage{}, msgTypeBlockRequest},
  248. wire.ConcreteType{&bcBlockResponseMessage{}, msgTypeBlockResponse},
  249. wire.ConcreteType{&bcStatusResponseMessage{}, msgTypeStatusResponse},
  250. wire.ConcreteType{&bcStatusRequestMessage{}, msgTypeStatusRequest},
  251. )
  252. func DecodeMessage(bz []byte) (msgType byte, msg BlockchainMessage, err error) {
  253. msgType = bz[0]
  254. n := new(int64)
  255. r := bytes.NewReader(bz)
  256. msg = wire.ReadBinary(struct{ BlockchainMessage }{}, r, n, &err).(struct{ BlockchainMessage }).BlockchainMessage
  257. return
  258. }
  259. //-------------------------------------
  260. type bcBlockRequestMessage struct {
  261. Height int
  262. }
  263. func (m *bcBlockRequestMessage) String() string {
  264. return fmt.Sprintf("[bcBlockRequestMessage %v]", m.Height)
  265. }
  266. //-------------------------------------
  267. type bcBlockResponseMessage struct {
  268. Block *types.Block
  269. }
  270. func (m *bcBlockResponseMessage) String() string {
  271. return fmt.Sprintf("[bcBlockResponseMessage %v]", m.Block.Height)
  272. }
  273. //-------------------------------------
  274. type bcStatusRequestMessage struct {
  275. Height int
  276. }
  277. func (m *bcStatusRequestMessage) String() string {
  278. return fmt.Sprintf("[bcStatusRequestMessage %v]", m.Height)
  279. }
  280. //-------------------------------------
  281. type bcStatusResponseMessage struct {
  282. Height int
  283. }
  284. func (m *bcStatusResponseMessage) String() string {
  285. return fmt.Sprintf("[bcStatusResponseMessage %v]", m.Height)
  286. }