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.

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