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.

423 lines
12 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. package state
  2. import (
  3. "bytes"
  4. "errors"
  5. "github.com/ebuchman/fail-test"
  6. . "github.com/tendermint/go-common"
  7. cfg "github.com/tendermint/go-config"
  8. "github.com/tendermint/go-crypto"
  9. "github.com/tendermint/tendermint/proxy"
  10. "github.com/tendermint/tendermint/types"
  11. tmsp "github.com/tendermint/tmsp/types"
  12. )
  13. //--------------------------------------------------
  14. // Execute the block
  15. // Execute the block to mutate State.
  16. // Validates block and then executes Data.Txs in the block.
  17. func (s *State) ExecBlock(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus, block *types.Block, blockPartsHeader types.PartSetHeader) error {
  18. // Validate the block.
  19. if err := s.validateBlock(block); err != nil {
  20. return ErrInvalidBlock(err)
  21. }
  22. // compute bitarray of validators that signed
  23. signed := commitBitArrayFromBlock(block)
  24. _ = signed // TODO send on begin block
  25. // copy the valset
  26. valSet := s.Validators.Copy()
  27. nextValSet := valSet.Copy()
  28. // Execute the block txs
  29. changedValidators, err := execBlockOnProxyApp(eventCache, proxyAppConn, block)
  30. if err != nil {
  31. // There was some error in proxyApp
  32. // TODO Report error and wait for proxyApp to be available.
  33. return ErrProxyAppConn(err)
  34. }
  35. // update the validator set
  36. s.valAddedOrRemoved, err = updateValidators(nextValSet, changedValidators)
  37. if err != nil {
  38. log.Warn("Error changing validator set", "error", err)
  39. // TODO: err or carry on?
  40. }
  41. // All good!
  42. // Update validator accums and set state variables
  43. nextValSet.IncrementAccum(1)
  44. s.SetBlockAndValidators(block.Header, blockPartsHeader, valSet, nextValSet)
  45. // save state with updated height/blockhash/validators
  46. // but stale apphash, in case we fail between Commit and Save
  47. s.Save()
  48. return nil
  49. }
  50. // Executes block's transactions on proxyAppConn.
  51. // Returns a list of updates to the validator set
  52. // TODO: Generate a bitmap or otherwise store tx validity in state.
  53. func execBlockOnProxyApp(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus, block *types.Block) ([]*tmsp.Validator, error) {
  54. var validTxs, invalidTxs = 0, 0
  55. // Execute transactions and get hash
  56. proxyCb := func(req *tmsp.Request, res *tmsp.Response) {
  57. switch r := res.Value.(type) {
  58. case *tmsp.Response_AppendTx:
  59. // TODO: make use of res.Log
  60. // TODO: make use of this info
  61. // Blocks may include invalid txs.
  62. // reqAppendTx := req.(tmsp.RequestAppendTx)
  63. txError := ""
  64. apTx := r.AppendTx
  65. if apTx.Code == tmsp.CodeType_OK {
  66. validTxs += 1
  67. } else {
  68. log.Debug("Invalid tx", "code", r.AppendTx.Code, "log", r.AppendTx.Log)
  69. invalidTxs += 1
  70. txError = apTx.Code.String()
  71. }
  72. // NOTE: if we count we can access the tx from the block instead of
  73. // pulling it from the req
  74. event := types.EventDataTx{
  75. Tx: req.GetAppendTx().Tx,
  76. Result: apTx.Data,
  77. Code: apTx.Code,
  78. Log: apTx.Log,
  79. Error: txError,
  80. }
  81. types.FireEventTx(eventCache, event)
  82. }
  83. }
  84. proxyAppConn.SetResponseCallback(proxyCb)
  85. // Begin block
  86. err := proxyAppConn.BeginBlockSync(block.Hash(), types.TM2PB.Header(block.Header))
  87. if err != nil {
  88. log.Warn("Error in proxyAppConn.BeginBlock", "error", err)
  89. return nil, err
  90. }
  91. fail.Fail() // XXX
  92. // Run txs of block
  93. for _, tx := range block.Txs {
  94. fail.FailRand(len(block.Txs)) // XXX
  95. proxyAppConn.AppendTxAsync(tx)
  96. if err := proxyAppConn.Error(); err != nil {
  97. return nil, err
  98. }
  99. }
  100. fail.Fail() // XXX
  101. // End block
  102. changedValidators, err := proxyAppConn.EndBlockSync(uint64(block.Height))
  103. if err != nil {
  104. log.Warn("Error in proxyAppConn.EndBlock", "error", err)
  105. return nil, err
  106. }
  107. fail.Fail() // XXX
  108. log.Info("Executed block", "height", block.Height, "valid txs", validTxs, "invalid txs", invalidTxs)
  109. if len(changedValidators) > 0 {
  110. log.Info("Update to validator set", "updates", changedValidators)
  111. }
  112. return changedValidators, nil
  113. }
  114. func updateValidators(validators *types.ValidatorSet, changedValidators []*tmsp.Validator) (bool, error) {
  115. // TODO: prevent change of 1/3+ at once
  116. var addedOrRemoved bool
  117. for _, v := range changedValidators {
  118. pubkey, err := crypto.PubKeyFromBytes(v.PubKey) // NOTE: expects go-wire encoded pubkey
  119. if err != nil {
  120. return false, err
  121. }
  122. address := pubkey.Address()
  123. power := int64(v.Power)
  124. // mind the overflow from uint64
  125. if power < 0 {
  126. return false, errors.New(Fmt("Power (%d) overflows int64", v.Power))
  127. }
  128. _, val := validators.GetByAddress(address)
  129. if val == nil {
  130. // add val
  131. added := validators.Add(types.NewValidator(pubkey, power))
  132. if !added {
  133. return false, errors.New(Fmt("Failed to add new validator %X with voting power %d", address, power))
  134. }
  135. addedOrRemoved = true
  136. } else if v.Power == 0 {
  137. // remove val
  138. _, removed := validators.Remove(address)
  139. if !removed {
  140. return false, errors.New(Fmt("Failed to remove validator %X)"))
  141. }
  142. addedOrRemoved = true
  143. } else {
  144. // update val
  145. val.VotingPower = power
  146. updated := validators.Update(val)
  147. if !updated {
  148. return false, errors.New(Fmt("Failed to update validator %X with voting power %d", address, power))
  149. }
  150. }
  151. }
  152. return addedOrRemoved, nil
  153. }
  154. // return a bit array of validators that signed the last commit
  155. // NOTE: assumes commits have already been authenticated
  156. func commitBitArrayFromBlock(block *types.Block) *BitArray {
  157. signed := NewBitArray(len(block.LastCommit.Precommits))
  158. for i, precommit := range block.LastCommit.Precommits {
  159. if precommit != nil {
  160. signed.SetIndex(i, true) // val_.LastCommitHeight = block.Height - 1
  161. }
  162. }
  163. return signed
  164. }
  165. //-----------------------------------------------------
  166. // Validate block
  167. func (s *State) ValidateBlock(block *types.Block) error {
  168. return s.validateBlock(block)
  169. }
  170. func (s *State) validateBlock(block *types.Block) error {
  171. // Basic block validation.
  172. err := block.ValidateBasic(s.ChainID, s.LastBlockHeight, s.LastBlockID, s.LastBlockTime, s.AppHash)
  173. if err != nil {
  174. return err
  175. }
  176. // Validate block LastCommit.
  177. if block.Height == 1 {
  178. if len(block.LastCommit.Precommits) != 0 {
  179. return errors.New("Block at height 1 (first block) should have no LastCommit precommits")
  180. }
  181. } else {
  182. if len(block.LastCommit.Precommits) != s.LastValidators.Size() {
  183. return errors.New(Fmt("Invalid block commit size. Expected %v, got %v",
  184. s.LastValidators.Size(), len(block.LastCommit.Precommits)))
  185. }
  186. err := s.LastValidators.VerifyCommit(
  187. s.ChainID, s.LastBlockID, block.Height-1, block.LastCommit)
  188. if err != nil {
  189. return err
  190. }
  191. }
  192. return nil
  193. }
  194. //-----------------------------------------------------------------------------
  195. // ApplyBlock executes the block, then commits and updates the mempool atomically
  196. // Execute and commit block against app, save block and state
  197. func (s *State) ApplyBlock(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus,
  198. block *types.Block, partsHeader types.PartSetHeader, mempool Mempool) error {
  199. // Run the block on the State:
  200. // + update validator sets
  201. // + run txs on the proxyAppConn
  202. err := s.ExecBlock(eventCache, proxyAppConn, block, partsHeader)
  203. if err != nil {
  204. return errors.New(Fmt("Exec failed for application: %v", err))
  205. }
  206. // lock mempool, commit state, update mempoool
  207. err = s.CommitStateUpdateMempool(proxyAppConn, block, mempool)
  208. if err != nil {
  209. return errors.New(Fmt("Commit failed for application: %v", err))
  210. }
  211. return nil
  212. }
  213. // mempool must be locked during commit and update
  214. // because state is typically reset on Commit and old txs must be replayed
  215. // against committed state before new txs are run in the mempool, lest they be invalid
  216. func (s *State) CommitStateUpdateMempool(proxyAppConn proxy.AppConnConsensus, block *types.Block, mempool Mempool) error {
  217. mempool.Lock()
  218. defer mempool.Unlock()
  219. // Commit block, get hash back
  220. res := proxyAppConn.CommitSync()
  221. if res.IsErr() {
  222. log.Warn("Error in proxyAppConn.CommitSync", "error", res)
  223. return res
  224. }
  225. if res.Log != "" {
  226. log.Debug("Commit.Log: " + res.Log)
  227. }
  228. // Set the state's new AppHash
  229. s.AppHash = res.Data
  230. // Update mempool.
  231. mempool.Update(block.Height, block.Txs)
  232. return nil
  233. }
  234. // Updates to the mempool need to be synchronized with committing a block
  235. // so apps can reset their transient state on Commit
  236. type Mempool interface {
  237. Lock()
  238. Unlock()
  239. Update(height int, txs []types.Tx)
  240. }
  241. type mockMempool struct {
  242. }
  243. func (m mockMempool) Lock() {}
  244. func (m mockMempool) Unlock() {}
  245. func (m mockMempool) Update(height int, txs []types.Tx) {}
  246. //----------------------------------------------------------------
  247. // Handshake with app to sync to latest state of core by replaying blocks
  248. // TODO: Should we move blockchain/store.go to its own package?
  249. type BlockStore interface {
  250. Height() int
  251. LoadBlock(height int) *types.Block
  252. LoadBlockMeta(height int) *types.BlockMeta
  253. }
  254. type Handshaker struct {
  255. config cfg.Config
  256. state *State
  257. store BlockStore
  258. nBlocks int // number of blocks applied to the state
  259. }
  260. func NewHandshaker(config cfg.Config, state *State, store BlockStore) *Handshaker {
  261. return &Handshaker{config, state, store, 0}
  262. }
  263. // TODO: retry the handshake/replay if it fails ?
  264. func (h *Handshaker) Handshake(proxyApp proxy.AppConns) error {
  265. // handshake is done via info request on the query conn
  266. res, tmspInfo, blockInfo, configInfo := proxyApp.Query().InfoSync()
  267. if res.IsErr() {
  268. return errors.New(Fmt("Error calling Info. Code: %v; Data: %X; Log: %s", res.Code, res.Data, res.Log))
  269. }
  270. if blockInfo == nil {
  271. log.Warn("blockInfo is nil, aborting handshake")
  272. return nil
  273. }
  274. log.Notice("TMSP Handshake", "height", blockInfo.BlockHeight, "block_hash", blockInfo.BlockHash, "app_hash", blockInfo.AppHash)
  275. blockHeight := int(blockInfo.BlockHeight) // XXX: beware overflow
  276. appHash := blockInfo.AppHash
  277. if tmspInfo != nil {
  278. // TODO: check tmsp version (or do this in the tmspcli?)
  279. _ = tmspInfo
  280. }
  281. if configInfo != nil {
  282. // TODO: set config info
  283. _ = configInfo
  284. }
  285. // replay blocks up to the latest in the blockstore
  286. err := h.ReplayBlocks(appHash, blockHeight, proxyApp.Consensus())
  287. if err != nil {
  288. return errors.New(Fmt("Error on replay: %v", err))
  289. }
  290. // TODO: (on restart) replay mempool
  291. return nil
  292. }
  293. // Replay all blocks after blockHeight and ensure the result matches the current state.
  294. func (h *Handshaker) ReplayBlocks(appHash []byte, appBlockHeight int, appConnConsensus proxy.AppConnConsensus) error {
  295. storeBlockHeight := h.store.Height()
  296. if storeBlockHeight < appBlockHeight {
  297. // if the app is ahead, there's nothing we can do
  298. return ErrAppBlockHeightTooHigh{storeBlockHeight, appBlockHeight}
  299. } else if storeBlockHeight == appBlockHeight {
  300. // if we crashed between Commit and SaveState,
  301. // the state's app hash is stale
  302. // otherwise we're synced
  303. if h.state.Stale {
  304. h.state.Stale = false
  305. h.state.AppHash = appHash
  306. }
  307. return nil
  308. } else if h.state.LastBlockHeight == appBlockHeight {
  309. // store is ahead of app but core's state height is at apps height
  310. // this happens if we crashed after saving the block,
  311. // but before committing it. We should be 1 ahead
  312. if storeBlockHeight != appBlockHeight+1 {
  313. PanicSanity(Fmt("core.state.height == app.height but store.height (%d) > app.height+1 (%d)", storeBlockHeight, appBlockHeight+1))
  314. }
  315. // check that the blocks last apphash is the states apphash
  316. block := h.store.LoadBlock(storeBlockHeight)
  317. if !bytes.Equal(block.Header.AppHash, appHash) {
  318. return ErrLastStateMismatch{storeBlockHeight, block.Header.AppHash, appHash}
  319. }
  320. blockMeta := h.store.LoadBlockMeta(storeBlockHeight)
  321. h.nBlocks += 1
  322. var eventCache types.Fireable // nil
  323. // replay the block against the actual tendermint state
  324. return h.state.ApplyBlock(eventCache, appConnConsensus, block, blockMeta.PartsHeader, mockMempool{})
  325. } else {
  326. // either we're caught up or there's blocks to replay
  327. // replay all blocks starting with appBlockHeight+1
  328. var eventCache types.Fireable // nil
  329. var appHash []byte
  330. for i := appBlockHeight + 1; i <= storeBlockHeight; i++ {
  331. h.nBlocks += 1
  332. block := h.store.LoadBlock(i)
  333. _, err := execBlockOnProxyApp(eventCache, appConnConsensus, block)
  334. if err != nil {
  335. log.Warn("Error executing block on proxy app", "height", i, "err", err)
  336. return err
  337. }
  338. // Commit block, get hash back
  339. res := appConnConsensus.CommitSync()
  340. if res.IsErr() {
  341. log.Warn("Error in proxyAppConn.CommitSync", "error", res)
  342. return res
  343. }
  344. if res.Log != "" {
  345. log.Info("Commit.Log: " + res.Log)
  346. }
  347. appHash = res.Data
  348. }
  349. if !bytes.Equal(h.state.AppHash, appHash) {
  350. return errors.New(Fmt("Tendermint state.AppHash does not match AppHash after replay", "expected", h.state.AppHash, "got", appHash))
  351. }
  352. return nil
  353. }
  354. }