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.

370 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. chainID := bcR.state.ChainID
  166. FOR_LOOP:
  167. for {
  168. select {
  169. case request := <-bcR.requestsCh: // chan BlockRequest
  170. peer := bcR.Switch.Peers().Get(request.PeerID)
  171. if peer == nil {
  172. continue FOR_LOOP // Peer has since been disconnected.
  173. }
  174. msg := &bcBlockRequestMessage{request.Height}
  175. queued := peer.TrySend(BlockchainChannel, struct{ BlockchainMessage }{msg})
  176. if !queued {
  177. // We couldn't make the request, send-queue full.
  178. // The pool handles timeouts, just let it go.
  179. continue FOR_LOOP
  180. }
  181. case peerID := <-bcR.timeoutsCh: // chan string
  182. // Peer timed out.
  183. peer := bcR.Switch.Peers().Get(peerID)
  184. if peer != nil {
  185. bcR.Switch.StopPeerForError(peer, errors.New("BlockchainReactor Timeout"))
  186. }
  187. case <-statusUpdateTicker.C:
  188. // ask for status updates
  189. go bcR.BroadcastStatusRequest()
  190. case <-switchToConsensusTicker.C:
  191. height, numPending, _ := bcR.pool.GetStatus()
  192. outbound, inbound, _ := bcR.Switch.NumPeers()
  193. bcR.Logger.Info("Consensus ticker", "numPending", numPending, "total", len(bcR.pool.requesters),
  194. "outbound", outbound, "inbound", inbound)
  195. if bcR.pool.IsCaughtUp() {
  196. bcR.Logger.Info("Time to switch to consensus reactor!", "height", height)
  197. bcR.pool.Stop()
  198. conR := bcR.Switch.Reactor("CONSENSUS").(consensusReactor)
  199. conR.SwitchToConsensus(bcR.state)
  200. break FOR_LOOP
  201. }
  202. case <-trySyncTicker.C: // chan time
  203. // This loop can be slow as long as it's doing syncing work.
  204. SYNC_LOOP:
  205. for i := 0; i < 10; i++ {
  206. // See if there are any blocks to sync.
  207. first, second := bcR.pool.PeekTwoBlocks()
  208. //bcR.Logger.Info("TrySync peeked", "first", first, "second", second)
  209. if first == nil || second == nil {
  210. // We need both to sync the first block.
  211. break SYNC_LOOP
  212. }
  213. firstParts := first.MakePartSet(bcR.state.Params.BlockPartSizeBytes)
  214. firstPartsHeader := firstParts.Header()
  215. // Finally, verify the first block using the second's commit
  216. // NOTE: we can probably make this more efficient, but note that calling
  217. // first.Hash() doesn't verify the tx contents, so MakePartSet() is
  218. // currently necessary.
  219. err := bcR.state.Validators.VerifyCommit(
  220. chainID, types.BlockID{first.Hash(), firstPartsHeader}, first.Height, second.LastCommit)
  221. if err != nil {
  222. bcR.Logger.Error("Error in validation", "err", err)
  223. bcR.pool.RedoRequest(first.Height)
  224. break SYNC_LOOP
  225. } else {
  226. bcR.pool.PopRequest()
  227. bcR.store.SaveBlock(first, firstParts, second.LastCommit)
  228. // TODO: should we be firing events? need to fire NewBlock events manually ...
  229. // NOTE: we could improve performance if we
  230. // didn't make the app commit to disk every block
  231. // ... but we would need a way to get the hash without it persisting
  232. err := bcR.state.ApplyBlock(bcR.evsw, bcR.proxyAppConn, first, firstPartsHeader, types.MockMempool{})
  233. if err != nil {
  234. // TODO This is bad, are we zombie?
  235. cmn.PanicQ(cmn.Fmt("Failed to process committed block (%d:%X): %v", first.Height, first.Hash(), err))
  236. }
  237. }
  238. }
  239. continue FOR_LOOP
  240. case <-bcR.Quit:
  241. break FOR_LOOP
  242. }
  243. }
  244. }
  245. // BroadcastStatusRequest broadcasts `BlockStore` height.
  246. func (bcR *BlockchainReactor) BroadcastStatusRequest() error {
  247. bcR.Switch.Broadcast(BlockchainChannel, struct{ BlockchainMessage }{&bcStatusRequestMessage{bcR.store.Height()}})
  248. return nil
  249. }
  250. // SetEventSwitch implements events.Eventable
  251. func (bcR *BlockchainReactor) SetEventSwitch(evsw types.EventSwitch) {
  252. bcR.evsw = evsw
  253. }
  254. //-----------------------------------------------------------------------------
  255. // Messages
  256. const (
  257. msgTypeBlockRequest = byte(0x10)
  258. msgTypeBlockResponse = byte(0x11)
  259. msgTypeNoBlockResponse = byte(0x12)
  260. msgTypeStatusResponse = byte(0x20)
  261. msgTypeStatusRequest = byte(0x21)
  262. )
  263. // BlockchainMessage is a generic message for this reactor.
  264. type BlockchainMessage interface{}
  265. var _ = wire.RegisterInterface(
  266. struct{ BlockchainMessage }{},
  267. wire.ConcreteType{&bcBlockRequestMessage{}, msgTypeBlockRequest},
  268. wire.ConcreteType{&bcBlockResponseMessage{}, msgTypeBlockResponse},
  269. wire.ConcreteType{&bcNoBlockResponseMessage{}, msgTypeNoBlockResponse},
  270. wire.ConcreteType{&bcStatusResponseMessage{}, msgTypeStatusResponse},
  271. wire.ConcreteType{&bcStatusRequestMessage{}, msgTypeStatusRequest},
  272. )
  273. // DecodeMessage decodes BlockchainMessage.
  274. // TODO: ensure that bz is completely read.
  275. func DecodeMessage(bz []byte, maxSize int) (msgType byte, msg BlockchainMessage, err error) {
  276. msgType = bz[0]
  277. n := int(0)
  278. r := bytes.NewReader(bz)
  279. msg = wire.ReadBinary(struct{ BlockchainMessage }{}, r, maxSize, &n, &err).(struct{ BlockchainMessage }).BlockchainMessage
  280. if err != nil && n != len(bz) {
  281. err = errors.New("DecodeMessage() had bytes left over")
  282. }
  283. return
  284. }
  285. //-------------------------------------
  286. type bcBlockRequestMessage struct {
  287. Height int
  288. }
  289. func (m *bcBlockRequestMessage) String() string {
  290. return cmn.Fmt("[bcBlockRequestMessage %v]", m.Height)
  291. }
  292. type bcNoBlockResponseMessage struct {
  293. Height int
  294. }
  295. func (brm *bcNoBlockResponseMessage) String() string {
  296. return cmn.Fmt("[bcNoBlockResponseMessage %d]", brm.Height)
  297. }
  298. //-------------------------------------
  299. // NOTE: keep up-to-date with maxBlockchainResponseSize
  300. type bcBlockResponseMessage struct {
  301. Block *types.Block
  302. }
  303. func (m *bcBlockResponseMessage) String() string {
  304. return cmn.Fmt("[bcBlockResponseMessage %v]", m.Block.Height)
  305. }
  306. //-------------------------------------
  307. type bcStatusRequestMessage struct {
  308. Height int
  309. }
  310. func (m *bcStatusRequestMessage) String() string {
  311. return cmn.Fmt("[bcStatusRequestMessage %v]", m.Height)
  312. }
  313. //-------------------------------------
  314. type bcStatusResponseMessage struct {
  315. Height int
  316. }
  317. func (m *bcStatusResponseMessage) String() string {
  318. return cmn.Fmt("[bcStatusResponseMessage %v]", m.Height)
  319. }