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.

452 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
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. abci "github.com/tendermint/abci/types"
  7. . "github.com/tendermint/go-common"
  8. cfg "github.com/tendermint/go-config"
  9. "github.com/tendermint/go-crypto"
  10. "github.com/tendermint/tendermint/proxy"
  11. "github.com/tendermint/tendermint/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) ([]*abci.Validator, error) {
  55. var validTxs, invalidTxs = 0, 0
  56. // Execute transactions and get hash
  57. proxyCb := func(req *abci.Request, res *abci.Response) {
  58. switch r := res.Value.(type) {
  59. case *abci.Response_DeliverTx:
  60. // TODO: make use of res.Log
  61. // TODO: make use of this info
  62. // Blocks may include invalid txs.
  63. // reqDeliverTx := req.(abci.RequestDeliverTx)
  64. txError := ""
  65. apTx := r.DeliverTx
  66. if apTx.Code == abci.CodeType_OK {
  67. validTxs += 1
  68. } else {
  69. log.Debug("Invalid tx", "code", r.DeliverTx.Code, "log", r.DeliverTx.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.GetDeliverTx().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.DeliverTxAsync(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", abci.ValidatorsString(respEndBlock.Diffs))
  112. }
  113. return respEndBlock.Diffs, nil
  114. }
  115. func updateValidators(validators *types.ValidatorSet, changedValidators []*abci.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. // apply a nd commit a block, but with out all the state validation
  233. // returns the application root hash (result of abci.Commit)
  234. func applyBlock(appConnConsensus proxy.AppConnConsensus, block *types.Block) ([]byte, error) {
  235. var eventCache types.Fireable // nil
  236. _, err := execBlockOnProxyApp(eventCache, appConnConsensus, block)
  237. if err != nil {
  238. log.Warn("Error executing block on proxy app", "height", block.Height, "err", err)
  239. return nil, err
  240. }
  241. // Commit block, get hash back
  242. res := appConnConsensus.CommitSync()
  243. if res.IsErr() {
  244. log.Warn("Error in proxyAppConn.CommitSync", "error", res)
  245. return nil, res
  246. }
  247. if res.Log != "" {
  248. log.Info("Commit.Log: " + res.Log)
  249. }
  250. return res.Data, nil
  251. }
  252. // Updates to the mempool need to be synchronized with committing a block
  253. // so apps can reset their transient state on Commit
  254. type Mempool interface {
  255. Lock()
  256. Unlock()
  257. CheckTx(types.Tx, func(*abci.Response)) error
  258. Reap(int) types.Txs
  259. Update(height int, txs types.Txs)
  260. }
  261. type MockMempool struct {
  262. }
  263. func (m MockMempool) Lock() {}
  264. func (m MockMempool) Unlock() {}
  265. func (m MockMempool) CheckTx(tx types.Tx, cb func(*abci.Response)) error { return nil }
  266. func (m MockMempool) Reap(n int) types.Txs { return types.Txs{} }
  267. func (m MockMempool) Update(height int, txs types.Txs) {}
  268. //----------------------------------------------------------------
  269. // Handshake with app to sync to latest state of core by replaying blocks
  270. // TODO: Should we move blockchain/store.go to its own package?
  271. type BlockStore interface {
  272. Height() int
  273. LoadBlockMeta(height int) *types.BlockMeta
  274. LoadBlock(height int) *types.Block
  275. LoadBlockPart(height int, index int) *types.Part
  276. SaveBlock(block *types.Block, blockParts *types.PartSet, seenCommit *types.Commit)
  277. LoadBlockCommit(height int) *types.Commit
  278. LoadSeenCommit(height int) *types.Commit
  279. }
  280. type blockReplayFunc func(cfg.Config, *State, proxy.AppConnConsensus, BlockStore)
  281. type Handshaker struct {
  282. config cfg.Config
  283. state *State
  284. store BlockStore
  285. replayLastBlock blockReplayFunc
  286. nBlocks int // number of blocks applied to the state
  287. }
  288. func NewHandshaker(config cfg.Config, state *State, store BlockStore, f blockReplayFunc) *Handshaker {
  289. return &Handshaker{config, state, store, f, 0}
  290. }
  291. func (h *Handshaker) NBlocks() int {
  292. return h.nBlocks
  293. }
  294. // TODO: retry the handshake/replay if it fails ?
  295. func (h *Handshaker) Handshake(proxyApp proxy.AppConns) error {
  296. // handshake is done via info request on the query conn
  297. res, err := proxyApp.Query().InfoSync()
  298. if err != nil {
  299. return errors.New(Fmt("Error calling Info: %v", err))
  300. }
  301. blockHeight := int(res.LastBlockHeight) // XXX: beware overflow
  302. appHash := res.LastBlockAppHash
  303. log.Notice("ABCI Handshake", "appHeight", blockHeight, "appHash", appHash)
  304. // TODO: check version
  305. // replay blocks up to the latest in the blockstore
  306. err = h.ReplayBlocks(appHash, blockHeight, proxyApp)
  307. if err != nil {
  308. return errors.New(Fmt("Error on replay: %v", err))
  309. }
  310. // TODO: (on restart) replay mempool
  311. return nil
  312. }
  313. // Replay all blocks after blockHeight and ensure the result matches the current state.
  314. func (h *Handshaker) ReplayBlocks(appHash []byte, appBlockHeight int, proxyApp proxy.AppConns) error {
  315. storeBlockHeight := h.store.Height()
  316. stateBlockHeight := h.state.LastBlockHeight
  317. log.Notice("ABCI Replay Blocks", "appHeight", appBlockHeight, "storeHeight", storeBlockHeight, "stateHeight", stateBlockHeight)
  318. if storeBlockHeight == 0 {
  319. return nil
  320. } else if storeBlockHeight < appBlockHeight {
  321. // if the app is ahead, there's nothing we can do
  322. return ErrAppBlockHeightTooHigh{storeBlockHeight, appBlockHeight}
  323. } else if storeBlockHeight == appBlockHeight && storeBlockHeight == stateBlockHeight {
  324. // all good!
  325. return nil
  326. } else if storeBlockHeight == appBlockHeight && storeBlockHeight == stateBlockHeight+1 {
  327. // We already ran Commit, but didn't save the state, so run through consensus with mock app
  328. mockApp := newMockProxyApp(appHash)
  329. log.Info("Replay last block using mock app")
  330. h.replayLastBlock(h.config, h.state, mockApp, h.store)
  331. } else if storeBlockHeight == appBlockHeight+1 && storeBlockHeight == stateBlockHeight+1 {
  332. // We crashed after saving the block
  333. // but before Commit (both the state and app are behind),
  334. // so run through consensus with the real app
  335. log.Info("Replay last block using real app")
  336. h.replayLastBlock(h.config, h.state, proxyApp.Consensus(), h.store)
  337. } else {
  338. // store is more than one ahead,
  339. // so app wants to replay many blocks.
  340. // replay all blocks from appBlockHeight+1 to storeBlockHeight-1.
  341. // Replay the final block through consensus
  342. var appHash []byte
  343. var err error
  344. for i := appBlockHeight + 1; i <= storeBlockHeight; i++ {
  345. log.Info("Applying block", "height", i)
  346. h.nBlocks += 1
  347. block := h.store.LoadBlock(i)
  348. appHash, err = applyBlock(proxyApp.Consensus(), block)
  349. if err != nil {
  350. return err
  351. }
  352. }
  353. // h.replayLastBlock(h.config, h.state, proxyApp.Consensus(), h.store)
  354. if !bytes.Equal(h.state.AppHash, appHash) {
  355. return errors.New(Fmt("Tendermint state.AppHash does not match AppHash after replay. Got %X, expected %X", appHash, h.state.AppHash))
  356. }
  357. return nil
  358. }
  359. return nil
  360. }
  361. //--------------------------------------------------------------------------------
  362. func newMockProxyApp(appHash []byte) proxy.AppConnConsensus {
  363. clientCreator := proxy.NewLocalClientCreator(&mockProxyApp{appHash: appHash})
  364. cli, _ := clientCreator.NewABCIClient()
  365. return proxy.NewAppConnConsensus(cli)
  366. }
  367. type mockProxyApp struct {
  368. abci.BaseApplication
  369. appHash []byte
  370. }
  371. func (mock *mockProxyApp) Commit() abci.Result {
  372. return abci.NewResultOK(mock.appHash, "")
  373. }