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.

439 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
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. package state
  2. import (
  3. "errors"
  4. "github.com/ebuchman/fail-test"
  5. abci "github.com/tendermint/abci/types"
  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. )
  12. //--------------------------------------------------
  13. // Execute the block
  14. // Execute the block to mutate State.
  15. // Validates block and then executes Data.Txs in the block.
  16. func (s *State) ExecBlock(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus, block *types.Block, blockPartsHeader types.PartSetHeader) error {
  17. // Validate the block.
  18. if err := s.validateBlock(block); err != nil {
  19. return ErrInvalidBlock(err)
  20. }
  21. // compute bitarray of validators that signed
  22. signed := commitBitArrayFromBlock(block)
  23. _ = signed // TODO send on begin block
  24. // copy the valset
  25. valSet := s.Validators.Copy()
  26. nextValSet := valSet.Copy()
  27. // Execute the block txs
  28. changedValidators, err := execBlockOnProxyApp(eventCache, proxyAppConn, block)
  29. if err != nil {
  30. // There was some error in proxyApp
  31. // TODO Report error and wait for proxyApp to be available.
  32. return ErrProxyAppConn(err)
  33. }
  34. // update the validator set
  35. err = updateValidators(nextValSet, changedValidators)
  36. if err != nil {
  37. log.Warn("Error changing validator set", "error", err)
  38. // TODO: err or carry on?
  39. }
  40. // All good!
  41. // Update validator accums and set state variables
  42. nextValSet.IncrementAccum(1)
  43. s.SetBlockAndValidators(block.Header, blockPartsHeader, valSet, nextValSet)
  44. // save state with updated height/blockhash/validators
  45. // but stale apphash, in case we fail between Commit and Save
  46. s.SaveIntermediate()
  47. fail.Fail() // XXX
  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) ([]*abci.Validator, error) {
  54. var validTxs, invalidTxs = 0, 0
  55. // Execute transactions and get hash
  56. proxyCb := func(req *abci.Request, res *abci.Response) {
  57. switch r := res.Value.(type) {
  58. case *abci.Response_DeliverTx:
  59. // TODO: make use of res.Log
  60. // TODO: make use of this info
  61. // Blocks may include invalid txs.
  62. // reqDeliverTx := req.(abci.RequestDeliverTx)
  63. txError := ""
  64. apTx := r.DeliverTx
  65. if apTx.Code == abci.CodeType_OK {
  66. validTxs += 1
  67. } else {
  68. log.Debug("Invalid tx", "code", r.DeliverTx.Code, "log", r.DeliverTx.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.GetDeliverTx().Tx,
  76. Data: 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.DeliverTxAsync(tx)
  96. if err := proxyAppConn.Error(); err != nil {
  97. return nil, err
  98. }
  99. }
  100. fail.Fail() // XXX
  101. // End block
  102. respEndBlock, 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(respEndBlock.Diffs) > 0 {
  110. log.Info("Update to validator set", "updates", abci.ValidatorsString(respEndBlock.Diffs))
  111. }
  112. return respEndBlock.Diffs, nil
  113. }
  114. func updateValidators(validators *types.ValidatorSet, changedValidators []*abci.Validator) error {
  115. // TODO: prevent change of 1/3+ at once
  116. for _, v := range changedValidators {
  117. pubkey, err := crypto.PubKeyFromBytes(v.PubKey) // NOTE: expects go-wire encoded pubkey
  118. if err != nil {
  119. return err
  120. }
  121. address := pubkey.Address()
  122. power := int64(v.Power)
  123. // mind the overflow from uint64
  124. if power < 0 {
  125. return errors.New(Fmt("Power (%d) overflows int64", v.Power))
  126. }
  127. _, val := validators.GetByAddress(address)
  128. if val == nil {
  129. // add val
  130. added := validators.Add(types.NewValidator(pubkey, power))
  131. if !added {
  132. return errors.New(Fmt("Failed to add new validator %X with voting power %d", address, power))
  133. }
  134. } else if v.Power == 0 {
  135. // remove val
  136. _, removed := validators.Remove(address)
  137. if !removed {
  138. return errors.New(Fmt("Failed to remove validator %X)"))
  139. }
  140. } else {
  141. // update val
  142. val.VotingPower = power
  143. updated := validators.Update(val)
  144. if !updated {
  145. return errors.New(Fmt("Failed to update validator %X with voting power %d", address, power))
  146. }
  147. }
  148. }
  149. return nil
  150. }
  151. // return a bit array of validators that signed the last commit
  152. // NOTE: assumes commits have already been authenticated
  153. func commitBitArrayFromBlock(block *types.Block) *BitArray {
  154. signed := NewBitArray(len(block.LastCommit.Precommits))
  155. for i, precommit := range block.LastCommit.Precommits {
  156. if precommit != nil {
  157. signed.SetIndex(i, true) // val_.LastCommitHeight = block.Height - 1
  158. }
  159. }
  160. return signed
  161. }
  162. //-----------------------------------------------------
  163. // Validate block
  164. func (s *State) ValidateBlock(block *types.Block) error {
  165. return s.validateBlock(block)
  166. }
  167. func (s *State) validateBlock(block *types.Block) error {
  168. // Basic block validation.
  169. err := block.ValidateBasic(s.ChainID, s.LastBlockHeight, s.LastBlockID, s.LastBlockTime, s.AppHash)
  170. if err != nil {
  171. return err
  172. }
  173. // Validate block LastCommit.
  174. if block.Height == 1 {
  175. if len(block.LastCommit.Precommits) != 0 {
  176. return errors.New("Block at height 1 (first block) should have no LastCommit precommits")
  177. }
  178. } else {
  179. if len(block.LastCommit.Precommits) != s.LastValidators.Size() {
  180. return errors.New(Fmt("Invalid block commit size. Expected %v, got %v",
  181. s.LastValidators.Size(), len(block.LastCommit.Precommits)))
  182. }
  183. err := s.LastValidators.VerifyCommit(
  184. s.ChainID, s.LastBlockID, block.Height-1, block.LastCommit)
  185. if err != nil {
  186. return err
  187. }
  188. }
  189. return nil
  190. }
  191. //-----------------------------------------------------------------------------
  192. // ApplyBlock executes the block, then commits and updates the mempool atomically
  193. // Execute and commit block against app, save block and state
  194. func (s *State) ApplyBlock(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus,
  195. block *types.Block, partsHeader types.PartSetHeader, mempool Mempool) error {
  196. // Run the block on the State:
  197. // + update validator sets
  198. // + run txs on the proxyAppConn
  199. err := s.ExecBlock(eventCache, proxyAppConn, block, partsHeader)
  200. if err != nil {
  201. return errors.New(Fmt("Exec failed for application: %v", err))
  202. }
  203. // lock mempool, commit state, update mempoool
  204. err = s.CommitStateUpdateMempool(proxyAppConn, block, mempool)
  205. if err != nil {
  206. return errors.New(Fmt("Commit failed for application: %v", err))
  207. }
  208. return nil
  209. }
  210. // mempool must be locked during commit and update
  211. // because state is typically reset on Commit and old txs must be replayed
  212. // against committed state before new txs are run in the mempool, lest they be invalid
  213. func (s *State) CommitStateUpdateMempool(proxyAppConn proxy.AppConnConsensus, block *types.Block, mempool Mempool) error {
  214. mempool.Lock()
  215. defer mempool.Unlock()
  216. // Commit block, get hash back
  217. res := proxyAppConn.CommitSync()
  218. if res.IsErr() {
  219. log.Warn("Error in proxyAppConn.CommitSync", "error", res)
  220. return res
  221. }
  222. if res.Log != "" {
  223. log.Debug("Commit.Log: " + res.Log)
  224. }
  225. // Set the state's new AppHash
  226. s.AppHash = res.Data
  227. // Update mempool.
  228. mempool.Update(block.Height, block.Txs)
  229. return nil
  230. }
  231. // Updates to the mempool need to be synchronized with committing a block
  232. // so apps can reset their transient state on Commit
  233. type Mempool interface {
  234. Lock()
  235. Unlock()
  236. CheckTx(types.Tx, func(*abci.Response)) error
  237. Reap(int) types.Txs
  238. Update(height int, txs types.Txs)
  239. }
  240. type MockMempool struct {
  241. }
  242. func (m MockMempool) Lock() {}
  243. func (m MockMempool) Unlock() {}
  244. func (m MockMempool) CheckTx(tx types.Tx, cb func(*abci.Response)) error { return nil }
  245. func (m MockMempool) Reap(n int) types.Txs { return types.Txs{} }
  246. func (m MockMempool) Update(height int, txs types.Txs) {}
  247. //----------------------------------------------------------------
  248. // Handshake with app to sync to latest state of core by replaying blocks
  249. // TODO: Should we move blockchain/store.go to its own package?
  250. type BlockStore interface {
  251. Height() int
  252. LoadBlockMeta(height int) *types.BlockMeta
  253. LoadBlock(height int) *types.Block
  254. LoadBlockPart(height int, index int) *types.Part
  255. SaveBlock(block *types.Block, blockParts *types.PartSet, seenCommit *types.Commit)
  256. LoadBlockCommit(height int) *types.Commit
  257. LoadSeenCommit(height int) *types.Commit
  258. }
  259. type blockReplayFunc func(cfg.Config, *State, proxy.AppConnConsensus, BlockStore)
  260. type Handshaker struct {
  261. config cfg.Config
  262. state *State
  263. store BlockStore
  264. replayLastBlock blockReplayFunc
  265. nBlocks int // number of blocks applied to the state
  266. }
  267. func NewHandshaker(config cfg.Config, state *State, store BlockStore, f blockReplayFunc) *Handshaker {
  268. return &Handshaker{config, state, store, f, 0}
  269. }
  270. func (h *Handshaker) NBlocks() int {
  271. return h.nBlocks
  272. }
  273. // TODO: retry the handshake/replay if it fails ?
  274. func (h *Handshaker) Handshake(proxyApp proxy.AppConns) error {
  275. // handshake is done via info request on the query conn
  276. res, err := proxyApp.Query().InfoSync()
  277. if err != nil {
  278. return errors.New(Fmt("Error calling Info: %v", err))
  279. }
  280. blockHeight := int(res.LastBlockHeight) // XXX: beware overflow
  281. appHash := res.LastBlockAppHash
  282. log.Notice("ABCI Handshake", "appHeight", blockHeight, "appHash", appHash)
  283. // TODO: check version
  284. // replay blocks up to the latest in the blockstore
  285. err = h.ReplayBlocks(appHash, blockHeight, proxyApp)
  286. if err != nil {
  287. return errors.New(Fmt("Error on replay: %v", err))
  288. }
  289. // TODO: (on restart) replay mempool
  290. return nil
  291. }
  292. // Replay all blocks after blockHeight and ensure the result matches the current state.
  293. func (h *Handshaker) ReplayBlocks(appHash []byte, appBlockHeight int, proxyApp proxy.AppConns) error {
  294. storeBlockHeight := h.store.Height()
  295. stateBlockHeight := h.state.LastBlockHeight
  296. log.Notice("ABCI Replay Blocks", "appHeight", appBlockHeight, "storeHeight", storeBlockHeight, "stateHeight", stateBlockHeight)
  297. if storeBlockHeight == 0 {
  298. return nil
  299. } else if storeBlockHeight < appBlockHeight {
  300. // if the app is ahead, there's nothing we can do
  301. return ErrAppBlockHeightTooHigh{storeBlockHeight, appBlockHeight}
  302. } else if storeBlockHeight == appBlockHeight && storeBlockHeight == stateBlockHeight+1 {
  303. // We already ran Commit, but didn't save the state, so run through consensus with mock app
  304. mockApp := newMockProxyApp(appHash)
  305. log.Info("Replay last block using mock app")
  306. h.replayLastBlock(h.config, h.state, mockApp, h.store)
  307. } else if storeBlockHeight == appBlockHeight+1 {
  308. // We crashed after saving the block
  309. // but before Commit (both the state and app are behind),
  310. // so run through consensus with the real app
  311. log.Info("Replay last block using real app")
  312. h.replayLastBlock(h.config, h.state, proxyApp.Consensus(), h.store)
  313. } else {
  314. // store is more than one ahead,
  315. // so app wants to replay many blocks
  316. /*
  317. // replay all blocks starting with appBlockHeight+1
  318. var eventCache types.Fireable // nil
  319. // TODO: use stateBlockHeight instead and let the consensus state
  320. // do the replay
  321. var appHash []byte
  322. for i := appBlockHeight + 1; i <= storeBlockHeight; i++ {
  323. h.nBlocks += 1
  324. block := h.store.LoadBlock(i)
  325. _, err := execBlockOnProxyApp(eventCache, appConnConsensus, block)
  326. if err != nil {
  327. log.Warn("Error executing block on proxy app", "height", i, "err", err)
  328. return err
  329. }
  330. // Commit block, get hash back
  331. res := appConnConsensus.CommitSync()
  332. if res.IsErr() {
  333. log.Warn("Error in proxyAppConn.CommitSync", "error", res)
  334. return res
  335. }
  336. if res.Log != "" {
  337. log.Info("Commit.Log: " + res.Log)
  338. }
  339. appHash = res.Data
  340. }
  341. if !bytes.Equal(h.state.AppHash, appHash) {
  342. return errors.New(Fmt("Tendermint state.AppHash does not match AppHash after replay. Got %X, expected %X", appHash, h.state.AppHash))
  343. }
  344. */
  345. return nil
  346. }
  347. return nil
  348. }
  349. //--------------------------------------------------------------------------------
  350. func newMockProxyApp(appHash []byte) proxy.AppConnConsensus {
  351. clientCreator := proxy.NewLocalClientCreator(&mockProxyApp{appHash: appHash})
  352. cli, _ := clientCreator.NewABCIClient()
  353. return proxy.NewAppConnConsensus(cli)
  354. }
  355. type mockProxyApp struct {
  356. abci.BaseApplication
  357. appHash []byte
  358. }
  359. func (mock *mockProxyApp) Commit() abci.Result {
  360. return abci.NewResultOK(mock.appHash, "")
  361. }