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.

340 lines
9.7 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. package blockchain
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "reflect"
  7. "sync/atomic"
  8. "time"
  9. "github.com/tendermint/tendermint/binary"
  10. . "github.com/tendermint/tendermint/common"
  11. "github.com/tendermint/tendermint/events"
  12. "github.com/tendermint/tendermint/p2p"
  13. sm "github.com/tendermint/tendermint/state"
  14. "github.com/tendermint/tendermint/types"
  15. )
  16. const (
  17. BlockchainChannel = byte(0x40)
  18. defaultChannelCapacity = 100
  19. defaultSleepIntervalMS = 500
  20. trySyncIntervalMS = 100
  21. // stop syncing when last block's time is
  22. // within this much of the system time.
  23. // stopSyncingDurationMinutes = 10
  24. // ask for best height every 10s
  25. statusUpdateIntervalSeconds = 10
  26. // check if we should switch to consensus reactor
  27. switchToConsensusIntervalSeconds = 10
  28. )
  29. type consensusReactor interface {
  30. // for when we switch from blockchain reactor and fast sync to
  31. // the consensus machine
  32. SwitchToConsensus(*sm.State)
  33. }
  34. // BlockchainReactor handles long-term catchup syncing.
  35. type BlockchainReactor struct {
  36. sw *p2p.Switch
  37. state *sm.State
  38. store *BlockStore
  39. pool *BlockPool
  40. sync bool
  41. requestsCh chan BlockRequest
  42. timeoutsCh chan string
  43. lastBlock *types.Block
  44. quit chan struct{}
  45. running uint32
  46. evsw events.Fireable
  47. }
  48. func NewBlockchainReactor(state *sm.State, store *BlockStore, sync bool) *BlockchainReactor {
  49. // SANITY CHECK
  50. if state.LastBlockHeight != store.Height() &&
  51. state.LastBlockHeight != store.Height()-1 { // XXX double check this logic.
  52. panic(Fmt("state (%v) and store (%v) height mismatch", state.LastBlockHeight, store.Height()))
  53. }
  54. // SANITY CHECK END
  55. requestsCh := make(chan BlockRequest, defaultChannelCapacity)
  56. timeoutsCh := make(chan string, defaultChannelCapacity)
  57. pool := NewBlockPool(
  58. store.Height()+1,
  59. requestsCh,
  60. timeoutsCh,
  61. )
  62. bcR := &BlockchainReactor{
  63. state: state,
  64. store: store,
  65. pool: pool,
  66. sync: sync,
  67. requestsCh: requestsCh,
  68. timeoutsCh: timeoutsCh,
  69. quit: make(chan struct{}),
  70. running: uint32(0),
  71. }
  72. return bcR
  73. }
  74. // Implements Reactor
  75. func (bcR *BlockchainReactor) Start(sw *p2p.Switch) {
  76. if atomic.CompareAndSwapUint32(&bcR.running, 0, 1) {
  77. log.Info("Starting BlockchainReactor")
  78. bcR.sw = sw
  79. if bcR.sync {
  80. bcR.pool.Start()
  81. go bcR.poolRoutine()
  82. }
  83. }
  84. }
  85. // Implements Reactor
  86. func (bcR *BlockchainReactor) Stop() {
  87. if atomic.CompareAndSwapUint32(&bcR.running, 1, 0) {
  88. log.Info("Stopping BlockchainReactor")
  89. close(bcR.quit)
  90. bcR.pool.Stop()
  91. }
  92. }
  93. // Implements Reactor
  94. func (bcR *BlockchainReactor) GetChannels() []*p2p.ChannelDescriptor {
  95. return []*p2p.ChannelDescriptor{
  96. &p2p.ChannelDescriptor{
  97. Id: BlockchainChannel,
  98. Priority: 5,
  99. SendQueueCapacity: 100,
  100. },
  101. }
  102. }
  103. // Implements Reactor
  104. func (bcR *BlockchainReactor) AddPeer(peer *p2p.Peer) {
  105. // Send peer our state.
  106. peer.Send(BlockchainChannel, &bcStatusResponseMessage{bcR.store.Height()})
  107. }
  108. // Implements Reactor
  109. func (bcR *BlockchainReactor) RemovePeer(peer *p2p.Peer, reason interface{}) {
  110. // Remove peer from the pool.
  111. bcR.pool.RemovePeer(peer.Key)
  112. }
  113. // Implements Reactor
  114. func (bcR *BlockchainReactor) Receive(chId byte, src *p2p.Peer, msgBytes []byte) {
  115. _, msg, err := DecodeMessage(msgBytes)
  116. if err != nil {
  117. log.Warn("Error decoding message", "error", err)
  118. return
  119. }
  120. log.Info("Received message", "msg", msg)
  121. switch msg := msg.(type) {
  122. case *bcBlockRequestMessage:
  123. // Got a request for a block. Respond with block if we have it.
  124. block := bcR.store.LoadBlock(msg.Height)
  125. if block != nil {
  126. msg := &bcBlockResponseMessage{Block: block}
  127. queued := src.TrySend(BlockchainChannel, msg)
  128. if !queued {
  129. // queue is full, just ignore.
  130. }
  131. } else {
  132. // TODO peer is asking for things we don't have.
  133. }
  134. case *bcBlockResponseMessage:
  135. // Got a block.
  136. bcR.pool.AddBlock(msg.Block, src.Key)
  137. case *bcStatusRequestMessage:
  138. // Send peer our state.
  139. queued := src.TrySend(BlockchainChannel, &bcStatusResponseMessage{bcR.store.Height()})
  140. if !queued {
  141. // sorry
  142. }
  143. case *bcStatusResponseMessage:
  144. // Got a peer status. Unverified.
  145. bcR.pool.SetPeerHeight(src.Key, msg.Height)
  146. default:
  147. log.Warn(Fmt("Unknown message type %v", reflect.TypeOf(msg)))
  148. }
  149. }
  150. // Handle messages from the poolReactor telling the reactor what to do.
  151. // NOTE: Don't sleep in the FOR_LOOP or otherwise slow it down!
  152. // (Except for the SYNC_LOOP, which is the primary purpose and must be synchronous.)
  153. func (bcR *BlockchainReactor) poolRoutine() {
  154. trySyncTicker := time.NewTicker(trySyncIntervalMS * time.Millisecond)
  155. statusUpdateTicker := time.NewTicker(statusUpdateIntervalSeconds * time.Second)
  156. switchToConsensusTicker := time.NewTicker(switchToConsensusIntervalSeconds * time.Second)
  157. FOR_LOOP:
  158. for {
  159. select {
  160. case request := <-bcR.requestsCh: // chan BlockRequest
  161. peer := bcR.sw.Peers().Get(request.PeerId)
  162. if peer == nil {
  163. // We can't assign the request.
  164. continue FOR_LOOP
  165. }
  166. msg := &bcBlockRequestMessage{request.Height}
  167. queued := peer.TrySend(BlockchainChannel, msg)
  168. if !queued {
  169. // We couldn't make the request, send-queue full.
  170. // The pool handles retries, so just let it go.
  171. continue FOR_LOOP
  172. }
  173. case peerId := <-bcR.timeoutsCh: // chan string
  174. // Peer timed out.
  175. peer := bcR.sw.Peers().Get(peerId)
  176. if peer != nil {
  177. bcR.sw.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, numUnassigned := bcR.pool.GetStatus()
  184. outbound, inbound, _ := bcR.sw.NumPeers()
  185. log.Debug("Consensus ticker", "numUnassigned", numUnassigned, "numPending", numPending,
  186. "total", len(bcR.pool.requests), "outbound", outbound, "inbound", inbound)
  187. // NOTE: this condition is very strict right now. may need to weaken
  188. // If all `maxPendingRequests` requests are unassigned
  189. // and we have some peers (say >= 3), then we're caught up
  190. maxPending := numPending == maxPendingRequests
  191. allUnassigned := numPending == numUnassigned
  192. enoughPeers := outbound+inbound >= 3
  193. if maxPending && allUnassigned && enoughPeers {
  194. log.Info("Time to switch to consensus reactor!", "height", height)
  195. bcR.pool.Stop()
  196. conR := bcR.sw.Reactor("CONSENSUS").(consensusReactor)
  197. conR.SwitchToConsensus(bcR.state)
  198. break FOR_LOOP
  199. }
  200. case _ = <-trySyncTicker.C: // chan time
  201. // This loop can be slow as long as it's doing syncing work.
  202. SYNC_LOOP:
  203. for i := 0; i < 10; i++ {
  204. // See if there are any blocks to sync.
  205. first, second := bcR.pool.PeekTwoBlocks()
  206. //log.Debug("TrySync peeked", "first", first, "second", second)
  207. if first == nil || second == nil {
  208. // We need both to sync the first block.
  209. break SYNC_LOOP
  210. }
  211. firstParts := first.MakePartSet()
  212. firstPartsHeader := firstParts.Header()
  213. // Finally, verify the first block using the second's validation.
  214. err := bcR.state.BondedValidators.VerifyValidation(
  215. bcR.state.ChainID, first.Hash(), firstPartsHeader, first.Height, second.LastValidation)
  216. if err != nil {
  217. log.Debug("error in validation", "error", err)
  218. bcR.pool.RedoRequest(first.Height)
  219. break SYNC_LOOP
  220. } else {
  221. bcR.pool.PopRequest()
  222. err := sm.ExecBlock(bcR.state, first, firstPartsHeader)
  223. if err != nil {
  224. // TODO This is bad, are we zombie?
  225. panic(Fmt("Failed to process committed block: %v", err))
  226. }
  227. bcR.store.SaveBlock(first, firstParts, second.LastValidation)
  228. bcR.state.Save()
  229. }
  230. }
  231. continue FOR_LOOP
  232. case <-bcR.quit:
  233. break FOR_LOOP
  234. }
  235. }
  236. }
  237. func (bcR *BlockchainReactor) BroadcastStatusResponse() error {
  238. bcR.sw.Broadcast(BlockchainChannel, &bcStatusResponseMessage{bcR.store.Height()})
  239. return nil
  240. }
  241. func (bcR *BlockchainReactor) BroadcastStatusRequest() error {
  242. bcR.sw.Broadcast(BlockchainChannel, &bcStatusRequestMessage{bcR.store.Height()})
  243. return nil
  244. }
  245. // implements events.Eventable
  246. func (bcR *BlockchainReactor) SetFireable(evsw events.Fireable) {
  247. bcR.evsw = evsw
  248. }
  249. //-----------------------------------------------------------------------------
  250. // Messages
  251. const (
  252. msgTypeBlockRequest = byte(0x10)
  253. msgTypeBlockResponse = byte(0x11)
  254. msgTypeStatusResponse = byte(0x20)
  255. msgTypeStatusRequest = byte(0x21)
  256. )
  257. type BlockchainMessage interface{}
  258. var _ = binary.RegisterInterface(
  259. struct{ BlockchainMessage }{},
  260. binary.ConcreteType{&bcBlockRequestMessage{}, msgTypeBlockRequest},
  261. binary.ConcreteType{&bcBlockResponseMessage{}, msgTypeBlockResponse},
  262. binary.ConcreteType{&bcStatusResponseMessage{}, msgTypeStatusResponse},
  263. binary.ConcreteType{&bcStatusRequestMessage{}, msgTypeStatusRequest},
  264. )
  265. func DecodeMessage(bz []byte) (msgType byte, msg BlockchainMessage, err error) {
  266. msgType = bz[0]
  267. n := new(int64)
  268. r := bytes.NewReader(bz)
  269. msg = binary.ReadBinary(struct{ BlockchainMessage }{}, r, n, &err).(struct{ BlockchainMessage }).BlockchainMessage
  270. return
  271. }
  272. //-------------------------------------
  273. type bcBlockRequestMessage struct {
  274. Height int
  275. }
  276. func (m *bcBlockRequestMessage) String() string {
  277. return fmt.Sprintf("[bcBlockRequestMessage %v]", m.Height)
  278. }
  279. //-------------------------------------
  280. type bcBlockResponseMessage struct {
  281. Block *types.Block
  282. }
  283. func (m *bcBlockResponseMessage) String() string {
  284. return fmt.Sprintf("[bcBlockResponseMessage %v]", m.Block.Height)
  285. }
  286. //-------------------------------------
  287. type bcStatusRequestMessage struct {
  288. Height int
  289. }
  290. func (m *bcStatusRequestMessage) String() string {
  291. return fmt.Sprintf("[bcStatusRequestMessage %v]", m.Height)
  292. }
  293. //-------------------------------------
  294. type bcStatusResponseMessage struct {
  295. Height int
  296. }
  297. func (m *bcStatusResponseMessage) String() string {
  298. return fmt.Sprintf("[bcStatusResponseMessage %v]", m.Height)
  299. }