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. "github.com/spf13/viper"
  8. cfg "github.com/tendermint/go-config"
  9. "github.com/tendermint/go-wire"
  10. "github.com/tendermint/tendermint/p2p"
  11. "github.com/tendermint/tendermint/proxy"
  12. sm "github.com/tendermint/tendermint/state"
  13. "github.com/tendermint/tendermint/types"
  14. cmn "github.com/tendermint/tmlibs/common"
  15. )
  16. const (
  17. // BlockchainChannel is a channel for blocks and status updates (`BlockStore` height)
  18. BlockchainChannel = byte(0x40)
  19. defaultChannelCapacity = 100
  20. defaultSleepIntervalMS = 500
  21. trySyncIntervalMS = 100
  22. // stop syncing when last block's time is
  23. // within this much of the system time.
  24. // stopSyncingDurationMinutes = 10
  25. // ask for best height every 10s
  26. statusUpdateIntervalSeconds = 10
  27. // check if we should switch to consensus reactor
  28. switchToConsensusIntervalSeconds = 1
  29. maxBlockchainResponseSize = types.MaxBlockSize + 2
  30. )
  31. type consensusReactor interface {
  32. // for when we switch from blockchain reactor and fast sync to
  33. // the consensus machine
  34. SwitchToConsensus(*sm.State)
  35. }
  36. // BlockchainReactor handles long-term catchup syncing.
  37. type BlockchainReactor struct {
  38. p2p.BaseReactor
  39. config *viper.Viper
  40. state *sm.State
  41. proxyAppConn proxy.AppConnConsensus // same as consensus.proxyAppConn
  42. store *BlockStore
  43. pool *BlockPool
  44. fastSync bool
  45. requestsCh chan BlockRequest
  46. timeoutsCh chan string
  47. lastBlock *types.Block
  48. evsw types.EventSwitch
  49. }
  50. // NewBlockchainReactor returns new reactor instance.
  51. func NewBlockchainReactor(config *viper.Viper, state *sm.State, proxyAppConn proxy.AppConnConsensus, store *BlockStore, fastSync bool) *BlockchainReactor {
  52. if state.LastBlockHeight == store.Height()-1 {
  53. store.height-- // XXX HACK, make this better
  54. }
  55. if state.LastBlockHeight != store.Height() {
  56. cmn.PanicSanity(cmn.Fmt("state (%v) and store (%v) height mismatch", state.LastBlockHeight, store.Height()))
  57. }
  58. requestsCh := make(chan BlockRequest, defaultChannelCapacity)
  59. timeoutsCh := make(chan string, defaultChannelCapacity)
  60. pool := NewBlockPool(
  61. store.Height()+1,
  62. requestsCh,
  63. timeoutsCh,
  64. )
  65. bcR := &BlockchainReactor{
  66. config: config,
  67. state: state,
  68. proxyAppConn: proxyAppConn,
  69. store: store,
  70. pool: pool,
  71. fastSync: fastSync,
  72. requestsCh: requestsCh,
  73. timeoutsCh: timeoutsCh,
  74. }
  75. bcR.BaseReactor = *p2p.NewBaseReactor(log, "BlockchainReactor", bcR)
  76. return bcR
  77. }
  78. // OnStart implements BaseService
  79. func (bcR *BlockchainReactor) OnStart() error {
  80. bcR.BaseReactor.OnStart()
  81. if bcR.fastSync {
  82. _, err := bcR.pool.Start()
  83. if err != nil {
  84. return err
  85. }
  86. go bcR.poolRoutine()
  87. }
  88. return nil
  89. }
  90. // OnStop implements BaseService
  91. func (bcR *BlockchainReactor) OnStop() {
  92. bcR.BaseReactor.OnStop()
  93. bcR.pool.Stop()
  94. }
  95. // GetChannels implements Reactor
  96. func (bcR *BlockchainReactor) GetChannels() []*p2p.ChannelDescriptor {
  97. return []*p2p.ChannelDescriptor{
  98. &p2p.ChannelDescriptor{
  99. ID: BlockchainChannel,
  100. Priority: 5,
  101. SendQueueCapacity: 100,
  102. },
  103. }
  104. }
  105. // AddPeer implements Reactor by sending our state to peer.
  106. func (bcR *BlockchainReactor) AddPeer(peer *p2p.Peer) {
  107. if !peer.Send(BlockchainChannel, struct{ BlockchainMessage }{&bcStatusResponseMessage{bcR.store.Height()}}) {
  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. }
  231. }
  232. continue FOR_LOOP
  233. case <-bcR.Quit:
  234. break FOR_LOOP
  235. }
  236. }
  237. }
  238. // BroadcastStatusRequest broadcasts `BlockStore` height.
  239. func (bcR *BlockchainReactor) BroadcastStatusRequest() error {
  240. bcR.Switch.Broadcast(BlockchainChannel, struct{ BlockchainMessage }{&bcStatusRequestMessage{bcR.store.Height()}})
  241. return nil
  242. }
  243. // SetEventSwitch implements events.Eventable
  244. func (bcR *BlockchainReactor) SetEventSwitch(evsw types.EventSwitch) {
  245. bcR.evsw = evsw
  246. }
  247. //-----------------------------------------------------------------------------
  248. // Messages
  249. const (
  250. msgTypeBlockRequest = byte(0x10)
  251. msgTypeBlockResponse = byte(0x11)
  252. msgTypeStatusResponse = byte(0x20)
  253. msgTypeStatusRequest = byte(0x21)
  254. )
  255. // BlockchainMessage is a generic message for this reactor.
  256. type BlockchainMessage interface{}
  257. var _ = wire.RegisterInterface(
  258. struct{ BlockchainMessage }{},
  259. wire.ConcreteType{&bcBlockRequestMessage{}, msgTypeBlockRequest},
  260. wire.ConcreteType{&bcBlockResponseMessage{}, msgTypeBlockResponse},
  261. wire.ConcreteType{&bcStatusResponseMessage{}, msgTypeStatusResponse},
  262. wire.ConcreteType{&bcStatusRequestMessage{}, msgTypeStatusRequest},
  263. )
  264. // DecodeMessage decodes BlockchainMessage.
  265. // TODO: ensure that bz is completely read.
  266. func DecodeMessage(bz []byte) (msgType byte, msg BlockchainMessage, err error) {
  267. msgType = bz[0]
  268. n := int(0)
  269. r := bytes.NewReader(bz)
  270. msg = wire.ReadBinary(struct{ BlockchainMessage }{}, r, maxBlockchainResponseSize, &n, &err).(struct{ BlockchainMessage }).BlockchainMessage
  271. if err != nil && n != len(bz) {
  272. err = errors.New("DecodeMessage() had bytes left over")
  273. }
  274. return
  275. }
  276. //-------------------------------------
  277. type bcBlockRequestMessage struct {
  278. Height int
  279. }
  280. func (m *bcBlockRequestMessage) String() string {
  281. return cmn.Fmt("[bcBlockRequestMessage %v]", m.Height)
  282. }
  283. //-------------------------------------
  284. // NOTE: keep up-to-date with maxBlockchainResponseSize
  285. type bcBlockResponseMessage struct {
  286. Block *types.Block
  287. }
  288. func (m *bcBlockResponseMessage) String() string {
  289. return cmn.Fmt("[bcBlockResponseMessage %v]", m.Block.Height)
  290. }
  291. //-------------------------------------
  292. type bcStatusRequestMessage struct {
  293. Height int
  294. }
  295. func (m *bcStatusRequestMessage) String() string {
  296. return cmn.Fmt("[bcStatusRequestMessage %v]", m.Height)
  297. }
  298. //-------------------------------------
  299. type bcStatusResponseMessage struct {
  300. Height int
  301. }
  302. func (m *bcStatusResponseMessage) String() string {
  303. return cmn.Fmt("[bcStatusResponseMessage %v]", m.Height)
  304. }