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.

348 lines
11 KiB

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