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.

420 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
  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.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. 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.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", tmsp.ValidatorsString(changedValidators))
  111. }
  112. return changedValidators, nil
  113. }
  114. func updateValidators(validators *types.ValidatorSet, changedValidators []*tmsp.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. s.AppHashIsStale = false
  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", "height", blockInfo.BlockHeight, "app_hash", 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. // TODO: (on restart) replay mempool
  289. return nil
  290. }
  291. // Replay all blocks after blockHeight and ensure the result matches the current state.
  292. func (h *Handshaker) ReplayBlocks(appHash []byte, appBlockHeight int, appConnConsensus proxy.AppConnConsensus) error {
  293. storeBlockHeight := h.store.Height()
  294. if storeBlockHeight < appBlockHeight {
  295. // if the app is ahead, there's nothing we can do
  296. return ErrAppBlockHeightTooHigh{storeBlockHeight, appBlockHeight}
  297. } else if storeBlockHeight == appBlockHeight {
  298. // if we crashed between Commit and SaveState,
  299. // the state's app hash is stale
  300. // otherwise we're synced
  301. if h.state.AppHashIsStale {
  302. h.state.AppHashIsStale = false
  303. h.state.AppHash = appHash
  304. }
  305. return nil
  306. } else if h.state.LastBlockHeight == appBlockHeight {
  307. // store is ahead of app but core's state height is at apps height
  308. // this happens if we crashed after saving the block,
  309. // but before committing it. We should be 1 ahead
  310. if storeBlockHeight != appBlockHeight+1 {
  311. PanicSanity(Fmt("core.state.height == app.height but store.height (%d) > app.height+1 (%d)", storeBlockHeight, appBlockHeight+1))
  312. }
  313. // check that the blocks last apphash is the states apphash
  314. block := h.store.LoadBlock(storeBlockHeight)
  315. if !bytes.Equal(block.Header.AppHash, appHash) {
  316. return ErrLastStateMismatch{storeBlockHeight, block.Header.AppHash, appHash}
  317. }
  318. blockMeta := h.store.LoadBlockMeta(storeBlockHeight)
  319. h.nBlocks += 1
  320. var eventCache types.Fireable // nil
  321. // replay the block against the actual tendermint state
  322. return h.state.ApplyBlock(eventCache, appConnConsensus, block, blockMeta.PartsHeader, MockMempool{})
  323. } else {
  324. // either we're caught up or there's blocks to replay
  325. // replay all blocks starting with appBlockHeight+1
  326. var eventCache types.Fireable // nil
  327. var appHash []byte
  328. for i := appBlockHeight + 1; i <= storeBlockHeight; i++ {
  329. h.nBlocks += 1
  330. block := h.store.LoadBlock(i)
  331. _, err := execBlockOnProxyApp(eventCache, appConnConsensus, block)
  332. if err != nil {
  333. log.Warn("Error executing block on proxy app", "height", i, "err", err)
  334. return err
  335. }
  336. // Commit block, get hash back
  337. res := appConnConsensus.CommitSync()
  338. if res.IsErr() {
  339. log.Warn("Error in proxyAppConn.CommitSync", "error", res)
  340. return res
  341. }
  342. if res.Log != "" {
  343. log.Info("Commit.Log: " + res.Log)
  344. }
  345. appHash = res.Data
  346. }
  347. if !bytes.Equal(h.state.AppHash, appHash) {
  348. return errors.New(Fmt("Tendermint state.AppHash does not match AppHash after replay", "expected", h.state.AppHash, "got", appHash))
  349. }
  350. return nil
  351. }
  352. }