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.

450 lines
14 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. changedValidators, 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(changedValidators) > 0 {
  111. log.Info("Update to validator set", "updates", tmsp.ValidatorsString(changedValidators))
  112. }
  113. return changedValidators, 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, tmspInfo, blockInfo, configInfo := proxyApp.Query().InfoSync()
  265. if res.IsErr() {
  266. return errors.New(Fmt("Error calling Info. Code: %v; Data: %X; Log: %s", res.Code, res.Data, res.Log))
  267. }
  268. if blockInfo == nil {
  269. log.Warn("blockInfo is nil, aborting handshake")
  270. return nil
  271. }
  272. log.Notice("TMSP Handshake", "appHeight", blockInfo.BlockHeight, "appHash", blockInfo.AppHash)
  273. blockHeight := int(blockInfo.BlockHeight) // XXX: beware overflow
  274. appHash := blockInfo.AppHash
  275. if tmspInfo != nil {
  276. // TODO: check tmsp version (or do this in the tmspcli?)
  277. _ = tmspInfo
  278. }
  279. if configInfo != nil {
  280. // TODO: set config info
  281. _ = configInfo
  282. }
  283. // replay blocks up to the latest in the blockstore
  284. err := h.ReplayBlocks(appHash, blockHeight, proxyApp.Consensus())
  285. if err != nil {
  286. return errors.New(Fmt("Error on replay: %v", err))
  287. }
  288. // Save the state
  289. h.state.Save()
  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. stateBlockHeight := h.state.LastBlockHeight
  297. log.Notice("TMSP Replay Blocks", "appHeight", appBlockHeight, "storeHeight", storeBlockHeight, "stateHeight", stateBlockHeight)
  298. if storeBlockHeight == 0 {
  299. return nil
  300. } else if storeBlockHeight < appBlockHeight {
  301. // if the app is ahead, there's nothing we can do
  302. return ErrAppBlockHeightTooHigh{storeBlockHeight, appBlockHeight}
  303. } else if storeBlockHeight == appBlockHeight {
  304. // We ran Commit, but if we crashed before state.Save(),
  305. // load the intermediate state and update the state.AppHash.
  306. // NOTE: If TMSP allowed rollbacks, we could just replay the
  307. // block even though it's been committed
  308. stateAppHash := h.state.AppHash
  309. lastBlockAppHash := h.store.LoadBlock(storeBlockHeight).AppHash
  310. if bytes.Equal(stateAppHash, appHash) {
  311. // we're all synced up
  312. log.Debug("TMSP RelpayBlocks: Already synced")
  313. } else if bytes.Equal(stateAppHash, lastBlockAppHash) {
  314. // we crashed after commit and before saving state,
  315. // so load the intermediate state and update the hash
  316. h.state.LoadIntermediate()
  317. h.state.AppHash = appHash
  318. log.Debug("TMSP RelpayBlocks: Loaded intermediate state and updated state.AppHash")
  319. } else {
  320. PanicSanity(Fmt("Unexpected state.AppHash: state.AppHash %X; app.AppHash %X, lastBlock.AppHash %X", stateAppHash, appHash, lastBlockAppHash))
  321. }
  322. return nil
  323. } else if storeBlockHeight == appBlockHeight+1 &&
  324. storeBlockHeight == stateBlockHeight+1 {
  325. // We crashed after saving the block
  326. // but before Commit (both the state and app are behind),
  327. // so just replay the block
  328. // check that the lastBlock.AppHash matches the state apphash
  329. block := h.store.LoadBlock(storeBlockHeight)
  330. if !bytes.Equal(block.Header.AppHash, appHash) {
  331. return ErrLastStateMismatch{storeBlockHeight, block.Header.AppHash, appHash}
  332. }
  333. blockMeta := h.store.LoadBlockMeta(storeBlockHeight)
  334. h.nBlocks += 1
  335. var eventCache types.Fireable // nil
  336. // replay the latest block
  337. return h.state.ApplyBlock(eventCache, appConnConsensus, block, blockMeta.PartsHeader, MockMempool{})
  338. } else if storeBlockHeight != stateBlockHeight {
  339. // unless we failed before committing or saving state (previous 2 case),
  340. // the store and state should be at the same height!
  341. PanicSanity(Fmt("Expected storeHeight (%d) and stateHeight (%d) to match.", storeBlockHeight, stateBlockHeight))
  342. } else {
  343. // store is more than one ahead,
  344. // so app wants to replay many blocks
  345. // replay all blocks starting with appBlockHeight+1
  346. var eventCache types.Fireable // nil
  347. // TODO: use stateBlockHeight instead and let the consensus state
  348. // do the replay
  349. var appHash []byte
  350. for i := appBlockHeight + 1; i <= storeBlockHeight; i++ {
  351. h.nBlocks += 1
  352. block := h.store.LoadBlock(i)
  353. _, err := execBlockOnProxyApp(eventCache, appConnConsensus, block)
  354. if err != nil {
  355. log.Warn("Error executing block on proxy app", "height", i, "err", err)
  356. return err
  357. }
  358. // Commit block, get hash back
  359. res := appConnConsensus.CommitSync()
  360. if res.IsErr() {
  361. log.Warn("Error in proxyAppConn.CommitSync", "error", res)
  362. return res
  363. }
  364. if res.Log != "" {
  365. log.Info("Commit.Log: " + res.Log)
  366. }
  367. appHash = res.Data
  368. }
  369. if !bytes.Equal(h.state.AppHash, appHash) {
  370. return errors.New(Fmt("Tendermint state.AppHash does not match AppHash after replay. Got %X, expected %X", appHash, h.state.AppHash))
  371. }
  372. return nil
  373. }
  374. return nil
  375. }