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.

437 lines
13 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
  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. 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.SaveIntermediate()
  48. fail.Fail() // XXX
  49. return nil
  50. }
  51. // Executes block's transactions on proxyAppConn.
  52. // Returns a list of updates to the validator set
  53. // TODO: Generate a bitmap or otherwise store tx validity in state.
  54. func execBlockOnProxyApp(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus, block *types.Block) ([]*tmsp.Validator, error) {
  55. var validTxs, invalidTxs = 0, 0
  56. // Execute transactions and get hash
  57. proxyCb := func(req *tmsp.Request, res *tmsp.Response) {
  58. switch r := res.Value.(type) {
  59. case *tmsp.Response_AppendTx:
  60. // TODO: make use of res.Log
  61. // TODO: make use of this info
  62. // Blocks may include invalid txs.
  63. // reqAppendTx := req.(tmsp.RequestAppendTx)
  64. txError := ""
  65. apTx := r.AppendTx
  66. if apTx.Code == tmsp.CodeType_OK {
  67. validTxs += 1
  68. } else {
  69. log.Debug("Invalid tx", "code", r.AppendTx.Code, "log", r.AppendTx.Log)
  70. invalidTxs += 1
  71. txError = apTx.Code.String()
  72. }
  73. // NOTE: if we count we can access the tx from the block instead of
  74. // pulling it from the req
  75. event := types.EventDataTx{
  76. Tx: req.GetAppendTx().Tx,
  77. Data: apTx.Data,
  78. Code: apTx.Code,
  79. Log: apTx.Log,
  80. Error: txError,
  81. }
  82. types.FireEventTx(eventCache, event)
  83. }
  84. }
  85. proxyAppConn.SetResponseCallback(proxyCb)
  86. // Begin block
  87. err := proxyAppConn.BeginBlockSync(block.Hash(), types.TM2PB.Header(block.Header))
  88. if err != nil {
  89. log.Warn("Error in proxyAppConn.BeginBlock", "error", err)
  90. return nil, err
  91. }
  92. fail.Fail() // XXX
  93. // Run txs of block
  94. for _, tx := range block.Txs {
  95. fail.FailRand(len(block.Txs)) // XXX
  96. proxyAppConn.AppendTxAsync(tx)
  97. if err := proxyAppConn.Error(); err != nil {
  98. return nil, err
  99. }
  100. }
  101. fail.Fail() // XXX
  102. // End block
  103. respEndBlock, err := proxyAppConn.EndBlockSync(uint64(block.Height))
  104. if err != nil {
  105. log.Warn("Error in proxyAppConn.EndBlock", "error", err)
  106. return nil, err
  107. }
  108. fail.Fail() // XXX
  109. log.Info("Executed block", "height", block.Height, "valid txs", validTxs, "invalid txs", invalidTxs)
  110. if len(respEndBlock.Diffs) > 0 {
  111. log.Info("Update to validator set", "updates", tmsp.ValidatorsString(respEndBlock.Diffs))
  112. }
  113. return respEndBlock.Diffs, nil
  114. }
  115. func updateValidators(validators *types.ValidatorSet, changedValidators []*tmsp.Validator) error {
  116. // TODO: prevent change of 1/3+ at once
  117. for _, v := range changedValidators {
  118. pubkey, err := crypto.PubKeyFromBytes(v.PubKey) // NOTE: expects go-wire encoded pubkey
  119. if err != nil {
  120. return err
  121. }
  122. address := pubkey.Address()
  123. power := int64(v.Power)
  124. // mind the overflow from uint64
  125. if power < 0 {
  126. return 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 errors.New(Fmt("Failed to add new validator %X with voting power %d", address, power))
  134. }
  135. } else if v.Power == 0 {
  136. // remove val
  137. _, removed := validators.Remove(address)
  138. if !removed {
  139. return errors.New(Fmt("Failed to remove validator %X)"))
  140. }
  141. } else {
  142. // update val
  143. val.VotingPower = power
  144. updated := validators.Update(val)
  145. if !updated {
  146. return errors.New(Fmt("Failed to update validator %X with voting power %d", address, power))
  147. }
  148. }
  149. }
  150. return nil
  151. }
  152. // return a bit array of validators that signed the last commit
  153. // NOTE: assumes commits have already been authenticated
  154. func commitBitArrayFromBlock(block *types.Block) *BitArray {
  155. signed := NewBitArray(len(block.LastCommit.Precommits))
  156. for i, precommit := range block.LastCommit.Precommits {
  157. if precommit != nil {
  158. signed.SetIndex(i, true) // val_.LastCommitHeight = block.Height - 1
  159. }
  160. }
  161. return signed
  162. }
  163. //-----------------------------------------------------
  164. // Validate block
  165. func (s *State) ValidateBlock(block *types.Block) error {
  166. return s.validateBlock(block)
  167. }
  168. func (s *State) validateBlock(block *types.Block) error {
  169. // Basic block validation.
  170. err := block.ValidateBasic(s.ChainID, s.LastBlockHeight, s.LastBlockID, s.LastBlockTime, s.AppHash)
  171. if err != nil {
  172. return err
  173. }
  174. // Validate block LastCommit.
  175. if block.Height == 1 {
  176. if len(block.LastCommit.Precommits) != 0 {
  177. return errors.New("Block at height 1 (first block) should have no LastCommit precommits")
  178. }
  179. } else {
  180. if len(block.LastCommit.Precommits) != s.LastValidators.Size() {
  181. return errors.New(Fmt("Invalid block commit size. Expected %v, got %v",
  182. s.LastValidators.Size(), len(block.LastCommit.Precommits)))
  183. }
  184. err := s.LastValidators.VerifyCommit(
  185. s.ChainID, s.LastBlockID, block.Height-1, block.LastCommit)
  186. if err != nil {
  187. return err
  188. }
  189. }
  190. return nil
  191. }
  192. //-----------------------------------------------------------------------------
  193. // ApplyBlock executes the block, then commits and updates the mempool atomically
  194. // Execute and commit block against app, save block and state
  195. func (s *State) ApplyBlock(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus,
  196. block *types.Block, partsHeader types.PartSetHeader, mempool Mempool) error {
  197. // Run the block on the State:
  198. // + update validator sets
  199. // + run txs on the proxyAppConn
  200. err := s.ExecBlock(eventCache, proxyAppConn, block, partsHeader)
  201. if err != nil {
  202. return errors.New(Fmt("Exec failed for application: %v", err))
  203. }
  204. // lock mempool, commit state, update mempoool
  205. err = s.CommitStateUpdateMempool(proxyAppConn, block, mempool)
  206. if err != nil {
  207. return errors.New(Fmt("Commit failed for application: %v", err))
  208. }
  209. return nil
  210. }
  211. // mempool must be locked during commit and update
  212. // because state is typically reset on Commit and old txs must be replayed
  213. // against committed state before new txs are run in the mempool, lest they be invalid
  214. func (s *State) CommitStateUpdateMempool(proxyAppConn proxy.AppConnConsensus, block *types.Block, mempool Mempool) error {
  215. mempool.Lock()
  216. defer mempool.Unlock()
  217. // Commit block, get hash back
  218. res := proxyAppConn.CommitSync()
  219. if res.IsErr() {
  220. log.Warn("Error in proxyAppConn.CommitSync", "error", res)
  221. return res
  222. }
  223. if res.Log != "" {
  224. log.Debug("Commit.Log: " + res.Log)
  225. }
  226. // Set the state's new AppHash
  227. s.AppHash = res.Data
  228. // Update mempool.
  229. mempool.Update(block.Height, block.Txs)
  230. return nil
  231. }
  232. // Updates to the mempool need to be synchronized with committing a block
  233. // so apps can reset their transient state on Commit
  234. type Mempool interface {
  235. Lock()
  236. Unlock()
  237. Update(height int, txs []types.Tx)
  238. }
  239. type MockMempool struct {
  240. }
  241. func (m MockMempool) Lock() {}
  242. func (m MockMempool) Unlock() {}
  243. func (m MockMempool) Update(height int, txs []types.Tx) {}
  244. //----------------------------------------------------------------
  245. // Handshake with app to sync to latest state of core by replaying blocks
  246. // TODO: Should we move blockchain/store.go to its own package?
  247. type BlockStore interface {
  248. Height() int
  249. LoadBlock(height int) *types.Block
  250. LoadBlockMeta(height int) *types.BlockMeta
  251. }
  252. type Handshaker struct {
  253. config cfg.Config
  254. state *State
  255. store BlockStore
  256. nBlocks int // number of blocks applied to the state
  257. }
  258. func NewHandshaker(config cfg.Config, state *State, store BlockStore) *Handshaker {
  259. return &Handshaker{config, state, store, 0}
  260. }
  261. // TODO: retry the handshake/replay if it fails ?
  262. func (h *Handshaker) Handshake(proxyApp proxy.AppConns) error {
  263. // handshake is done via info request on the query conn
  264. res, err := proxyApp.Query().InfoSync()
  265. if err != nil {
  266. return errors.New(Fmt("Error calling Info: %v", err))
  267. }
  268. blockHeight := int(res.LastBlockHeight) // XXX: beware overflow
  269. appHash := res.LastBlockAppHash
  270. log.Notice("TMSP Handshake", "appHeight", blockHeight, "appHash", appHash)
  271. // TODO: check version
  272. // replay blocks up to the latest in the blockstore
  273. err = h.ReplayBlocks(appHash, blockHeight, proxyApp.Consensus())
  274. if err != nil {
  275. return errors.New(Fmt("Error on replay: %v", err))
  276. }
  277. // Save the state
  278. h.state.Save()
  279. // TODO: (on restart) replay mempool
  280. return nil
  281. }
  282. // Replay all blocks after blockHeight and ensure the result matches the current state.
  283. func (h *Handshaker) ReplayBlocks(appHash []byte, appBlockHeight int, appConnConsensus proxy.AppConnConsensus) error {
  284. storeBlockHeight := h.store.Height()
  285. stateBlockHeight := h.state.LastBlockHeight
  286. log.Notice("TMSP Replay Blocks", "appHeight", appBlockHeight, "storeHeight", storeBlockHeight, "stateHeight", stateBlockHeight)
  287. if storeBlockHeight == 0 {
  288. return nil
  289. } else if storeBlockHeight < appBlockHeight {
  290. // if the app is ahead, there's nothing we can do
  291. return ErrAppBlockHeightTooHigh{storeBlockHeight, appBlockHeight}
  292. } else if storeBlockHeight == appBlockHeight {
  293. // We ran Commit, but if we crashed before state.Save(),
  294. // load the intermediate state and update the state.AppHash.
  295. // NOTE: If TMSP allowed rollbacks, we could just replay the
  296. // block even though it's been committed
  297. stateAppHash := h.state.AppHash
  298. lastBlockAppHash := h.store.LoadBlock(storeBlockHeight).AppHash
  299. if bytes.Equal(stateAppHash, appHash) {
  300. // we're all synced up
  301. log.Debug("TMSP RelpayBlocks: Already synced")
  302. } else if bytes.Equal(stateAppHash, lastBlockAppHash) {
  303. // we crashed after commit and before saving state,
  304. // so load the intermediate state and update the hash
  305. h.state.LoadIntermediate()
  306. h.state.AppHash = appHash
  307. log.Debug("TMSP RelpayBlocks: Loaded intermediate state and updated state.AppHash")
  308. } else {
  309. PanicSanity(Fmt("Unexpected state.AppHash: state.AppHash %X; app.AppHash %X, lastBlock.AppHash %X", stateAppHash, appHash, lastBlockAppHash))
  310. }
  311. return nil
  312. } else if storeBlockHeight == appBlockHeight+1 &&
  313. storeBlockHeight == stateBlockHeight+1 {
  314. // We crashed after saving the block
  315. // but before Commit (both the state and app are behind),
  316. // so just replay the block
  317. // check that the lastBlock.AppHash matches the state apphash
  318. block := h.store.LoadBlock(storeBlockHeight)
  319. if !bytes.Equal(block.Header.AppHash, appHash) {
  320. return ErrLastStateMismatch{storeBlockHeight, block.Header.AppHash, appHash}
  321. }
  322. blockMeta := h.store.LoadBlockMeta(storeBlockHeight)
  323. h.nBlocks += 1
  324. var eventCache types.Fireable // nil
  325. // replay the latest block
  326. return h.state.ApplyBlock(eventCache, appConnConsensus, block, blockMeta.PartsHeader, MockMempool{})
  327. } else if storeBlockHeight != stateBlockHeight {
  328. // unless we failed before committing or saving state (previous 2 case),
  329. // the store and state should be at the same height!
  330. PanicSanity(Fmt("Expected storeHeight (%d) and stateHeight (%d) to match.", storeBlockHeight, stateBlockHeight))
  331. } else {
  332. // store is more than one ahead,
  333. // so app wants to replay many blocks
  334. // replay all blocks starting with appBlockHeight+1
  335. var eventCache types.Fireable // nil
  336. // TODO: use stateBlockHeight instead and let the consensus state
  337. // do the replay
  338. var appHash []byte
  339. for i := appBlockHeight + 1; i <= storeBlockHeight; i++ {
  340. h.nBlocks += 1
  341. block := h.store.LoadBlock(i)
  342. _, err := execBlockOnProxyApp(eventCache, appConnConsensus, block)
  343. if err != nil {
  344. log.Warn("Error executing block on proxy app", "height", i, "err", err)
  345. return err
  346. }
  347. // Commit block, get hash back
  348. res := appConnConsensus.CommitSync()
  349. if res.IsErr() {
  350. log.Warn("Error in proxyAppConn.CommitSync", "error", res)
  351. return res
  352. }
  353. if res.Log != "" {
  354. log.Info("Commit.Log: " + res.Log)
  355. }
  356. appHash = res.Data
  357. }
  358. if !bytes.Equal(h.state.AppHash, appHash) {
  359. return errors.New(Fmt("Tendermint state.AppHash does not match AppHash after replay. Got %X, expected %X", appHash, h.state.AppHash))
  360. }
  361. return nil
  362. }
  363. return nil
  364. }