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.

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