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.

349 lines
11 KiB

10 years ago
10 years ago
8 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. package blockchain
  2. import (
  3. "bytes"
  4. "errors"
  5. "reflect"
  6. "time"
  7. cmn "github.com/tendermint/go-common"
  8. cfg "github.com/tendermint/go-config"
  9. "github.com/tendermint/go-p2p"
  10. "github.com/tendermint/go-wire"
  11. "github.com/tendermint/tendermint/proxy"
  12. sm "github.com/tendermint/tendermint/state"
  13. "github.com/tendermint/tendermint/types"
  14. )
  15. const (
  16. // BlockchainChannel is a channel for blocks and status updates (`BlockStore` height)
  17. BlockchainChannel = byte(0x40)
  18. defaultChannelCapacity = 100
  19. defaultSleepIntervalMS = 500
  20. trySyncIntervalMS = 100
  21. // stop syncing when last block's time is
  22. // within this much of the system time.
  23. // stopSyncingDurationMinutes = 10
  24. // ask for best height every 10s
  25. statusUpdateIntervalSeconds = 10
  26. // check if we should switch to consensus reactor
  27. switchToConsensusIntervalSeconds = 1
  28. maxBlockchainResponseSize = types.MaxBlockSize + 2
  29. )
  30. type consensusReactor interface {
  31. // for when we switch from blockchain reactor and fast sync to
  32. // the consensus machine
  33. SwitchToConsensus(*sm.State)
  34. }
  35. // BlockchainReactor handles long-term catchup syncing.
  36. type BlockchainReactor struct {
  37. p2p.BaseReactor
  38. config cfg.Config
  39. state *sm.State
  40. proxyAppConn proxy.AppConnConsensus // same as consensus.proxyAppConn
  41. store *BlockStore
  42. pool *BlockPool
  43. fastSync bool
  44. requestsCh chan BlockRequest
  45. timeoutsCh chan string
  46. lastBlock *types.Block
  47. evsw types.EventSwitch
  48. }
  49. // NewBlockchainReactor returns new reactor instance.
  50. func NewBlockchainReactor(config cfg.Config, state *sm.State, proxyAppConn proxy.AppConnConsensus, store *BlockStore, fastSync bool) *BlockchainReactor {
  51. if state.LastBlockHeight == store.Height()-1 {
  52. store.height-- // XXX HACK, make this better
  53. }
  54. if state.LastBlockHeight != store.Height() {
  55. cmn.PanicSanity(cmn.Fmt("state (%v) and store (%v) height mismatch", state.LastBlockHeight, store.Height()))
  56. }
  57. requestsCh := make(chan BlockRequest, defaultChannelCapacity)
  58. timeoutsCh := make(chan string, defaultChannelCapacity)
  59. pool := NewBlockPool(
  60. store.Height()+1,
  61. requestsCh,
  62. timeoutsCh,
  63. )
  64. bcR := &BlockchainReactor{
  65. config: config,
  66. state: state,
  67. proxyAppConn: proxyAppConn,
  68. store: store,
  69. pool: pool,
  70. fastSync: fastSync,
  71. requestsCh: requestsCh,
  72. timeoutsCh: timeoutsCh,
  73. }
  74. bcR.BaseReactor = *p2p.NewBaseReactor(log, "BlockchainReactor", bcR)
  75. return bcR
  76. }
  77. // OnStart implements BaseService
  78. func (bcR *BlockchainReactor) OnStart() error {
  79. bcR.BaseReactor.OnStart()
  80. if bcR.fastSync {
  81. _, err := bcR.pool.Start()
  82. if err != nil {
  83. return err
  84. }
  85. go bcR.poolRoutine()
  86. }
  87. return nil
  88. }
  89. // OnStop implements BaseService
  90. func (bcR *BlockchainReactor) OnStop() {
  91. bcR.BaseReactor.OnStop()
  92. bcR.pool.Stop()
  93. }
  94. // GetChannels implements Reactor
  95. func (bcR *BlockchainReactor) GetChannels() []*p2p.ChannelDescriptor {
  96. return []*p2p.ChannelDescriptor{
  97. &p2p.ChannelDescriptor{
  98. ID: BlockchainChannel,
  99. Priority: 5,
  100. SendQueueCapacity: 100,
  101. },
  102. }
  103. }
  104. // AddPeer implements Reactor by sending our state to peer.
  105. func (bcR *BlockchainReactor) AddPeer(peer *p2p.Peer) {
  106. if !peer.Send(BlockchainChannel, struct{ BlockchainMessage }{&bcStatusResponseMessage{bcR.store.Height()}}) {
  107. log.Warn("Failed to send our state to peer", "peer", peer)
  108. // doing nothing, will try later in `poolRoutine`
  109. }
  110. }
  111. // RemovePeer implements Reactor by removing peer from the pool.
  112. func (bcR *BlockchainReactor) RemovePeer(peer *p2p.Peer, reason interface{}) {
  113. bcR.pool.RemovePeer(peer.Key)
  114. }
  115. // Receive implements Reactor by handling 4 types of messages (look below).
  116. func (bcR *BlockchainReactor) Receive(chID byte, src *p2p.Peer, msgBytes []byte) {
  117. _, msg, err := DecodeMessage(msgBytes)
  118. if err != nil {
  119. log.Warn("Error decoding message", "error", err)
  120. return
  121. }
  122. log.Debug("Receive", "src", src, "chID", chID, "msg", msg)
  123. switch msg := msg.(type) {
  124. case *bcBlockRequestMessage:
  125. // Got a request for a block. Respond with block if we have it.
  126. block := bcR.store.LoadBlock(msg.Height)
  127. if block != nil {
  128. msg := &bcBlockResponseMessage{Block: block}
  129. queued := src.TrySend(BlockchainChannel, struct{ BlockchainMessage }{msg})
  130. if !queued {
  131. // queue is full, just ignore.
  132. }
  133. } else {
  134. // TODO peer is asking for things we don't have.
  135. }
  136. case *bcBlockResponseMessage:
  137. // Got a block.
  138. bcR.pool.AddBlock(src.Key, msg.Block, len(msgBytes))
  139. case *bcStatusRequestMessage:
  140. // Send peer our state.
  141. queued := src.TrySend(BlockchainChannel, struct{ BlockchainMessage }{&bcStatusResponseMessage{bcR.store.Height()}})
  142. if !queued {
  143. // sorry
  144. }
  145. case *bcStatusResponseMessage:
  146. // Got a peer status. Unverified.
  147. bcR.pool.SetPeerHeight(src.Key, msg.Height)
  148. default:
  149. log.Warn(cmn.Fmt("Unknown message type %v", reflect.TypeOf(msg)))
  150. }
  151. }
  152. // Handle messages from the poolReactor telling the reactor what to do.
  153. // NOTE: Don't sleep in the FOR_LOOP or otherwise slow it down!
  154. // (Except for the SYNC_LOOP, which is the primary purpose and must be synchronous.)
  155. func (bcR *BlockchainReactor) poolRoutine() {
  156. trySyncTicker := time.NewTicker(trySyncIntervalMS * time.Millisecond)
  157. statusUpdateTicker := time.NewTicker(statusUpdateIntervalSeconds * time.Second)
  158. switchToConsensusTicker := time.NewTicker(switchToConsensusIntervalSeconds * time.Second)
  159. FOR_LOOP:
  160. for {
  161. select {
  162. case request := <-bcR.requestsCh: // chan BlockRequest
  163. peer := bcR.Switch.Peers().Get(request.PeerID)
  164. if peer == nil {
  165. continue FOR_LOOP // Peer has since been disconnected.
  166. }
  167. msg := &bcBlockRequestMessage{request.Height}
  168. queued := peer.TrySend(BlockchainChannel, struct{ BlockchainMessage }{msg})
  169. if !queued {
  170. // We couldn't make the request, send-queue full.
  171. // The pool handles timeouts, just let it go.
  172. continue FOR_LOOP
  173. }
  174. case peerID := <-bcR.timeoutsCh: // chan string
  175. // Peer timed out.
  176. peer := bcR.Switch.Peers().Get(peerID)
  177. if peer != nil {
  178. bcR.Switch.StopPeerForError(peer, errors.New("BlockchainReactor Timeout"))
  179. }
  180. case _ = <-statusUpdateTicker.C:
  181. // ask for status updates
  182. go bcR.BroadcastStatusRequest()
  183. case _ = <-switchToConsensusTicker.C:
  184. height, numPending, _ := bcR.pool.GetStatus()
  185. outbound, inbound, _ := bcR.Switch.NumPeers()
  186. log.Info("Consensus ticker", "numPending", numPending, "total", len(bcR.pool.requesters),
  187. "outbound", outbound, "inbound", inbound)
  188. if bcR.pool.IsCaughtUp() {
  189. log.Notice("Time to switch to consensus reactor!", "height", height)
  190. bcR.pool.Stop()
  191. conR := bcR.Switch.Reactor("CONSENSUS").(consensusReactor)
  192. conR.SwitchToConsensus(bcR.state)
  193. break FOR_LOOP
  194. }
  195. case _ = <-trySyncTicker.C: // chan time
  196. // This loop can be slow as long as it's doing syncing work.
  197. SYNC_LOOP:
  198. for i := 0; i < 10; i++ {
  199. // See if there are any blocks to sync.
  200. first, second := bcR.pool.PeekTwoBlocks()
  201. //log.Info("TrySync peeked", "first", first, "second", second)
  202. if first == nil || second == nil {
  203. // We need both to sync the first block.
  204. break SYNC_LOOP
  205. }
  206. firstParts := first.MakePartSet(bcR.config.GetInt("block_part_size")) // TODO: put part size in parts header?
  207. firstPartsHeader := firstParts.Header()
  208. // Finally, verify the first block using the second's commit
  209. // NOTE: we can probably make this more efficient, but note that calling
  210. // first.Hash() doesn't verify the tx contents, so MakePartSet() is
  211. // currently necessary.
  212. err := bcR.state.Validators.VerifyCommit(
  213. bcR.state.ChainID, types.BlockID{first.Hash(), firstPartsHeader}, first.Height, second.LastCommit)
  214. if err != nil {
  215. log.Info("error in validation", "error", err)
  216. bcR.pool.RedoRequest(first.Height)
  217. break SYNC_LOOP
  218. } else {
  219. bcR.pool.PopRequest()
  220. bcR.store.SaveBlock(first, firstParts, second.LastCommit)
  221. // TODO: should we be firing events? need to fire NewBlock events manually ...
  222. // NOTE: we could improve performance if we
  223. // didn't make the app commit to disk every block
  224. // ... but we would need a way to get the hash without it persisting
  225. err := bcR.state.ApplyBlock(bcR.evsw, bcR.proxyAppConn, first, firstPartsHeader, types.MockMempool{})
  226. if err != nil {
  227. // TODO This is bad, are we zombie?
  228. cmn.PanicQ(cmn.Fmt("Failed to process committed block (%d:%X): %v", first.Height, first.Hash(), err))
  229. }
  230. bcR.state.Save()
  231. }
  232. }
  233. continue FOR_LOOP
  234. case <-bcR.Quit:
  235. break FOR_LOOP
  236. }
  237. }
  238. }
  239. // BroadcastStatusRequest broadcasts `BlockStore` height.
  240. func (bcR *BlockchainReactor) BroadcastStatusRequest() error {
  241. bcR.Switch.Broadcast(BlockchainChannel, struct{ BlockchainMessage }{&bcStatusRequestMessage{bcR.store.Height()}})
  242. return nil
  243. }
  244. // SetEventSwitch implements events.Eventable
  245. func (bcR *BlockchainReactor) SetEventSwitch(evsw types.EventSwitch) {
  246. bcR.evsw = evsw
  247. }
  248. //-----------------------------------------------------------------------------
  249. // Messages
  250. const (
  251. msgTypeBlockRequest = byte(0x10)
  252. msgTypeBlockResponse = byte(0x11)
  253. msgTypeStatusResponse = byte(0x20)
  254. msgTypeStatusRequest = byte(0x21)
  255. )
  256. // BlockchainMessage is a generic message for this reactor.
  257. type BlockchainMessage interface{}
  258. var _ = wire.RegisterInterface(
  259. struct{ BlockchainMessage }{},
  260. wire.ConcreteType{&bcBlockRequestMessage{}, msgTypeBlockRequest},
  261. wire.ConcreteType{&bcBlockResponseMessage{}, msgTypeBlockResponse},
  262. wire.ConcreteType{&bcStatusResponseMessage{}, msgTypeStatusResponse},
  263. wire.ConcreteType{&bcStatusRequestMessage{}, msgTypeStatusRequest},
  264. )
  265. // DecodeMessage decodes BlockchainMessage.
  266. // TODO: ensure that bz is completely read.
  267. func DecodeMessage(bz []byte) (msgType byte, msg BlockchainMessage, err error) {
  268. msgType = bz[0]
  269. n := int(0)
  270. r := bytes.NewReader(bz)
  271. msg = wire.ReadBinary(struct{ BlockchainMessage }{}, r, maxBlockchainResponseSize, &n, &err).(struct{ BlockchainMessage }).BlockchainMessage
  272. if err != nil && n != len(bz) {
  273. err = errors.New("DecodeMessage() had bytes left over")
  274. }
  275. return
  276. }
  277. //-------------------------------------
  278. type bcBlockRequestMessage struct {
  279. Height int
  280. }
  281. func (m *bcBlockRequestMessage) String() string {
  282. return cmn.Fmt("[bcBlockRequestMessage %v]", m.Height)
  283. }
  284. //-------------------------------------
  285. // NOTE: keep up-to-date with maxBlockchainResponseSize
  286. type bcBlockResponseMessage struct {
  287. Block *types.Block
  288. }
  289. func (m *bcBlockResponseMessage) String() string {
  290. return cmn.Fmt("[bcBlockResponseMessage %v]", m.Block.Height)
  291. }
  292. //-------------------------------------
  293. type bcStatusRequestMessage struct {
  294. Height int
  295. }
  296. func (m *bcStatusRequestMessage) String() string {
  297. return cmn.Fmt("[bcStatusRequestMessage %v]", m.Height)
  298. }
  299. //-------------------------------------
  300. type bcStatusResponseMessage struct {
  301. Height int
  302. }
  303. func (m *bcStatusResponseMessage) String() string {
  304. return cmn.Fmt("[bcStatusResponseMessage %v]", m.Height)
  305. }