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.

368 lines
12 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. // respondToPeer loads a block and sends it to the requesting peer,
  109. // if we have it. Otherwise, we'll respond saying we don't have it.
  110. // According to the Tendermint spec, if all nodes are honest,
  111. // no node should be requesting for a block that's non-existent.
  112. func (bcR *BlockchainReactor) respondToPeer(msg *bcBlockRequestMessage, src p2p.Peer) (queued bool) {
  113. block := bcR.store.LoadBlock(msg.Height)
  114. if block != nil {
  115. msg := &bcBlockResponseMessage{Block: block}
  116. return src.TrySend(BlockchainChannel, struct{ BlockchainMessage }{msg})
  117. }
  118. bcR.Logger.Info("Peer asking for a block we don't have", "src", src, "height", msg.Height)
  119. return src.TrySend(BlockchainChannel, struct{ BlockchainMessage }{
  120. &bcNoBlockResponseMessage{Height: msg.Height},
  121. })
  122. }
  123. // Receive implements Reactor by handling 4 types of messages (look below).
  124. func (bcR *BlockchainReactor) Receive(chID byte, src p2p.Peer, msgBytes []byte) {
  125. _, msg, err := DecodeMessage(msgBytes, bcR.maxMsgSize())
  126. if err != nil {
  127. bcR.Logger.Error("Error decoding message", "err", err)
  128. return
  129. }
  130. bcR.Logger.Debug("Receive", "src", src, "chID", chID, "msg", msg)
  131. // TODO: improve logic to satisfy megacheck
  132. switch msg := msg.(type) {
  133. case *bcBlockRequestMessage:
  134. if queued := bcR.respondToPeer(msg, src); !queued {
  135. // Unfortunately not queued since the queue is full.
  136. }
  137. case *bcBlockResponseMessage:
  138. // Got a block.
  139. bcR.pool.AddBlock(src.Key(), msg.Block, len(msgBytes))
  140. case *bcStatusRequestMessage:
  141. // Send peer our state.
  142. queued := src.TrySend(BlockchainChannel, struct{ BlockchainMessage }{&bcStatusResponseMessage{bcR.store.Height()}})
  143. if !queued {
  144. // sorry
  145. }
  146. case *bcStatusResponseMessage:
  147. // Got a peer status. Unverified.
  148. bcR.pool.SetPeerHeight(src.Key(), msg.Height)
  149. default:
  150. bcR.Logger.Error(cmn.Fmt("Unknown message type %v", reflect.TypeOf(msg)))
  151. }
  152. }
  153. // maxMsgSize returns the maximum allowable size of a
  154. // message on the blockchain reactor.
  155. func (bcR *BlockchainReactor) maxMsgSize() int {
  156. return bcR.state.Params().BlockSizeParams.MaxBytes + 2
  157. }
  158. // Handle messages from the poolReactor telling the reactor what to do.
  159. // NOTE: Don't sleep in the FOR_LOOP or otherwise slow it down!
  160. // (Except for the SYNC_LOOP, which is the primary purpose and must be synchronous.)
  161. func (bcR *BlockchainReactor) poolRoutine() {
  162. trySyncTicker := time.NewTicker(trySyncIntervalMS * time.Millisecond)
  163. statusUpdateTicker := time.NewTicker(statusUpdateIntervalSeconds * time.Second)
  164. switchToConsensusTicker := time.NewTicker(switchToConsensusIntervalSeconds * time.Second)
  165. FOR_LOOP:
  166. for {
  167. select {
  168. case request := <-bcR.requestsCh: // chan BlockRequest
  169. peer := bcR.Switch.Peers().Get(request.PeerID)
  170. if peer == nil {
  171. continue FOR_LOOP // Peer has since been disconnected.
  172. }
  173. msg := &bcBlockRequestMessage{request.Height}
  174. queued := peer.TrySend(BlockchainChannel, struct{ BlockchainMessage }{msg})
  175. if !queued {
  176. // We couldn't make the request, send-queue full.
  177. // The pool handles timeouts, just let it go.
  178. continue FOR_LOOP
  179. }
  180. case peerID := <-bcR.timeoutsCh: // chan string
  181. // Peer timed out.
  182. peer := bcR.Switch.Peers().Get(peerID)
  183. if peer != nil {
  184. bcR.Switch.StopPeerForError(peer, errors.New("BlockchainReactor Timeout"))
  185. }
  186. case <-statusUpdateTicker.C:
  187. // ask for status updates
  188. go bcR.BroadcastStatusRequest()
  189. case <-switchToConsensusTicker.C:
  190. height, numPending, _ := bcR.pool.GetStatus()
  191. outbound, inbound, _ := bcR.Switch.NumPeers()
  192. bcR.Logger.Info("Consensus ticker", "numPending", numPending, "total", len(bcR.pool.requesters),
  193. "outbound", outbound, "inbound", inbound)
  194. if bcR.pool.IsCaughtUp() {
  195. bcR.Logger.Info("Time to switch to consensus reactor!", "height", height)
  196. bcR.pool.Stop()
  197. conR := bcR.Switch.Reactor("CONSENSUS").(consensusReactor)
  198. conR.SwitchToConsensus(bcR.state)
  199. break FOR_LOOP
  200. }
  201. case <-trySyncTicker.C: // chan time
  202. // This loop can be slow as long as it's doing syncing work.
  203. SYNC_LOOP:
  204. for i := 0; i < 10; i++ {
  205. // See if there are any blocks to sync.
  206. first, second := bcR.pool.PeekTwoBlocks()
  207. //bcR.Logger.Info("TrySync peeked", "first", first, "second", second)
  208. if first == nil || second == nil {
  209. // We need both to sync the first block.
  210. break SYNC_LOOP
  211. }
  212. firstParts := first.MakePartSet(bcR.state.Params().BlockPartSizeBytes)
  213. firstPartsHeader := firstParts.Header()
  214. // Finally, verify the first block using the second's commit
  215. // NOTE: we can probably make this more efficient, but note that calling
  216. // first.Hash() doesn't verify the tx contents, so MakePartSet() is
  217. // currently necessary.
  218. err := bcR.state.Validators.VerifyCommit(
  219. bcR.state.ChainID, types.BlockID{first.Hash(), firstPartsHeader}, first.Height, second.LastCommit)
  220. if err != nil {
  221. bcR.Logger.Error("Error in validation", "err", err)
  222. bcR.pool.RedoRequest(first.Height)
  223. break SYNC_LOOP
  224. } else {
  225. bcR.pool.PopRequest()
  226. bcR.store.SaveBlock(first, firstParts, second.LastCommit)
  227. // TODO: should we be firing events? need to fire NewBlock events manually ...
  228. // NOTE: we could improve performance if we
  229. // didn't make the app commit to disk every block
  230. // ... but we would need a way to get the hash without it persisting
  231. err := bcR.state.ApplyBlock(bcR.evsw, bcR.proxyAppConn, first, firstPartsHeader, types.MockMempool{})
  232. if err != nil {
  233. // TODO This is bad, are we zombie?
  234. cmn.PanicQ(cmn.Fmt("Failed to process committed block (%d:%X): %v", first.Height, first.Hash(), err))
  235. }
  236. }
  237. }
  238. continue FOR_LOOP
  239. case <-bcR.Quit:
  240. break FOR_LOOP
  241. }
  242. }
  243. }
  244. // BroadcastStatusRequest broadcasts `BlockStore` height.
  245. func (bcR *BlockchainReactor) BroadcastStatusRequest() error {
  246. bcR.Switch.Broadcast(BlockchainChannel, struct{ BlockchainMessage }{&bcStatusRequestMessage{bcR.store.Height()}})
  247. return nil
  248. }
  249. // SetEventSwitch implements events.Eventable
  250. func (bcR *BlockchainReactor) SetEventSwitch(evsw types.EventSwitch) {
  251. bcR.evsw = evsw
  252. }
  253. //-----------------------------------------------------------------------------
  254. // Messages
  255. const (
  256. msgTypeBlockRequest = byte(0x10)
  257. msgTypeBlockResponse = byte(0x11)
  258. msgTypeNoBlockResponse = byte(0x12)
  259. msgTypeStatusResponse = byte(0x20)
  260. msgTypeStatusRequest = byte(0x21)
  261. )
  262. // BlockchainMessage is a generic message for this reactor.
  263. type BlockchainMessage interface{}
  264. var _ = wire.RegisterInterface(
  265. struct{ BlockchainMessage }{},
  266. wire.ConcreteType{&bcBlockRequestMessage{}, msgTypeBlockRequest},
  267. wire.ConcreteType{&bcBlockResponseMessage{}, msgTypeBlockResponse},
  268. wire.ConcreteType{&bcNoBlockResponseMessage{}, msgTypeNoBlockResponse},
  269. wire.ConcreteType{&bcStatusResponseMessage{}, msgTypeStatusResponse},
  270. wire.ConcreteType{&bcStatusRequestMessage{}, msgTypeStatusRequest},
  271. )
  272. // DecodeMessage decodes BlockchainMessage.
  273. // TODO: ensure that bz is completely read.
  274. func DecodeMessage(bz []byte, maxSize int) (msgType byte, msg BlockchainMessage, err error) {
  275. msgType = bz[0]
  276. n := int(0)
  277. r := bytes.NewReader(bz)
  278. msg = wire.ReadBinary(struct{ BlockchainMessage }{}, r, maxSize, &n, &err).(struct{ BlockchainMessage }).BlockchainMessage
  279. if err != nil && n != len(bz) {
  280. err = errors.New("DecodeMessage() had bytes left over")
  281. }
  282. return
  283. }
  284. //-------------------------------------
  285. type bcBlockRequestMessage struct {
  286. Height int
  287. }
  288. func (m *bcBlockRequestMessage) String() string {
  289. return cmn.Fmt("[bcBlockRequestMessage %v]", m.Height)
  290. }
  291. type bcNoBlockResponseMessage struct {
  292. Height int
  293. }
  294. func (brm *bcNoBlockResponseMessage) String() string {
  295. return cmn.Fmt("[bcNoBlockResponseMessage %d]", brm.Height)
  296. }
  297. //-------------------------------------
  298. // NOTE: keep up-to-date with maxBlockchainResponseSize
  299. type bcBlockResponseMessage struct {
  300. Block *types.Block
  301. }
  302. func (m *bcBlockResponseMessage) String() string {
  303. return cmn.Fmt("[bcBlockResponseMessage %v]", m.Block.Height)
  304. }
  305. //-------------------------------------
  306. type bcStatusRequestMessage struct {
  307. Height int
  308. }
  309. func (m *bcStatusRequestMessage) String() string {
  310. return cmn.Fmt("[bcStatusRequestMessage %v]", m.Height)
  311. }
  312. //-------------------------------------
  313. type bcStatusResponseMessage struct {
  314. Height int
  315. }
  316. func (m *bcStatusResponseMessage) String() string {
  317. return cmn.Fmt("[bcStatusResponseMessage %v]", m.Height)
  318. }