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.

295 lines
8.6 KiB

  1. package app
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "errors"
  6. "fmt"
  7. "path/filepath"
  8. "strconv"
  9. "github.com/tendermint/tendermint/abci/example/code"
  10. abci "github.com/tendermint/tendermint/abci/types"
  11. "github.com/tendermint/tendermint/libs/log"
  12. "github.com/tendermint/tendermint/proto/tendermint/types"
  13. "github.com/tendermint/tendermint/version"
  14. )
  15. // Application is an ABCI application for use by end-to-end tests. It is a
  16. // simple key/value store for strings, storing data in memory and persisting
  17. // to disk as JSON, taking state sync snapshots if requested.
  18. type Application struct {
  19. abci.BaseApplication
  20. logger log.Logger
  21. state *State
  22. snapshots *SnapshotStore
  23. cfg *Config
  24. restoreSnapshot *abci.Snapshot
  25. restoreChunks [][]byte
  26. }
  27. // Config allows for the setting of high level parameters for running the e2e Application
  28. // KeyType and ValidatorUpdates must be the same for all nodes running the same application.
  29. type Config struct {
  30. // The directory with which state.json will be persisted in. Usually $HOME/.tendermint/data
  31. Dir string `toml:"dir"`
  32. // SnapshotInterval specifies the height interval at which the application
  33. // will take state sync snapshots. Defaults to 0 (disabled).
  34. SnapshotInterval uint64 `toml:"snapshot_interval"`
  35. // RetainBlocks specifies the number of recent blocks to retain. Defaults to
  36. // 0, which retains all blocks. Must be greater that PersistInterval,
  37. // SnapshotInterval and EvidenceAgeHeight.
  38. RetainBlocks uint64 `toml:"retain_blocks"`
  39. // KeyType sets the curve that will be used by validators.
  40. // Options are ed25519 & secp256k1
  41. KeyType string `toml:"key_type"`
  42. // PersistInterval specifies the height interval at which the application
  43. // will persist state to disk. Defaults to 1 (every height), setting this to
  44. // 0 disables state persistence.
  45. PersistInterval uint64 `toml:"persist_interval"`
  46. // ValidatorUpdates is a map of heights to validator names and their power,
  47. // and will be returned by the ABCI application. For example, the following
  48. // changes the power of validator01 and validator02 at height 1000:
  49. //
  50. // [validator_update.1000]
  51. // validator01 = 20
  52. // validator02 = 10
  53. //
  54. // Specifying height 0 returns the validator update during InitChain. The
  55. // application returns the validator updates as-is, i.e. removing a
  56. // validator must be done by returning it with power 0, and any validators
  57. // not specified are not changed.
  58. //
  59. // height <-> pubkey <-> voting power
  60. ValidatorUpdates map[string]map[string]uint8 `toml:"validator_update"`
  61. }
  62. func DefaultConfig(dir string) *Config {
  63. return &Config{
  64. PersistInterval: 1,
  65. SnapshotInterval: 100,
  66. Dir: dir,
  67. }
  68. }
  69. // NewApplication creates the application.
  70. func NewApplication(cfg *Config) (*Application, error) {
  71. state, err := NewState(filepath.Join(cfg.Dir, "state.json"), cfg.PersistInterval)
  72. if err != nil {
  73. return nil, err
  74. }
  75. snapshots, err := NewSnapshotStore(filepath.Join(cfg.Dir, "snapshots"))
  76. if err != nil {
  77. return nil, err
  78. }
  79. return &Application{
  80. logger: log.MustNewDefaultLogger(log.LogFormatPlain, log.LogLevelInfo, false),
  81. state: state,
  82. snapshots: snapshots,
  83. cfg: cfg,
  84. }, nil
  85. }
  86. // Info implements ABCI.
  87. func (app *Application) Info(req abci.RequestInfo) abci.ResponseInfo {
  88. return abci.ResponseInfo{
  89. Version: version.ABCIVersion,
  90. AppVersion: 1,
  91. LastBlockHeight: int64(app.state.Height),
  92. LastBlockAppHash: app.state.Hash,
  93. }
  94. }
  95. // Info implements ABCI.
  96. func (app *Application) InitChain(req abci.RequestInitChain) abci.ResponseInitChain {
  97. var err error
  98. app.state.initialHeight = uint64(req.InitialHeight)
  99. if len(req.AppStateBytes) > 0 {
  100. err = app.state.Import(0, req.AppStateBytes)
  101. if err != nil {
  102. panic(err)
  103. }
  104. }
  105. resp := abci.ResponseInitChain{
  106. AppHash: app.state.Hash,
  107. ConsensusParams: &types.ConsensusParams{
  108. Version: &types.VersionParams{
  109. AppVersion: 1,
  110. },
  111. },
  112. }
  113. if resp.Validators, err = app.validatorUpdates(0); err != nil {
  114. panic(err)
  115. }
  116. return resp
  117. }
  118. // CheckTx implements ABCI.
  119. func (app *Application) CheckTx(req abci.RequestCheckTx) abci.ResponseCheckTx {
  120. _, _, err := parseTx(req.Tx)
  121. if err != nil {
  122. return abci.ResponseCheckTx{
  123. Code: code.CodeTypeEncodingError,
  124. Log: err.Error(),
  125. }
  126. }
  127. return abci.ResponseCheckTx{Code: code.CodeTypeOK, GasWanted: 1}
  128. }
  129. // DeliverTx implements ABCI.
  130. func (app *Application) DeliverTx(req abci.RequestDeliverTx) abci.ResponseDeliverTx {
  131. key, value, err := parseTx(req.Tx)
  132. if err != nil {
  133. panic(err) // shouldn't happen since we verified it in CheckTx
  134. }
  135. app.state.Set(key, value)
  136. return abci.ResponseDeliverTx{Code: code.CodeTypeOK}
  137. }
  138. // EndBlock implements ABCI.
  139. func (app *Application) EndBlock(req abci.RequestEndBlock) abci.ResponseEndBlock {
  140. valUpdates, err := app.validatorUpdates(uint64(req.Height))
  141. if err != nil {
  142. panic(err)
  143. }
  144. return abci.ResponseEndBlock{
  145. ValidatorUpdates: valUpdates,
  146. Events: []abci.Event{
  147. {
  148. Type: "val_updates",
  149. Attributes: []abci.EventAttribute{
  150. {
  151. Key: "size",
  152. Value: strconv.Itoa(valUpdates.Len()),
  153. },
  154. {
  155. Key: "height",
  156. Value: strconv.Itoa(int(req.Height)),
  157. },
  158. },
  159. },
  160. },
  161. }
  162. }
  163. // Commit implements ABCI.
  164. func (app *Application) Commit() abci.ResponseCommit {
  165. height, hash, err := app.state.Commit()
  166. if err != nil {
  167. panic(err)
  168. }
  169. if app.cfg.SnapshotInterval > 0 && height%app.cfg.SnapshotInterval == 0 {
  170. snapshot, err := app.snapshots.Create(app.state)
  171. if err != nil {
  172. panic(err)
  173. }
  174. app.logger.Info("Created state sync snapshot", "height", snapshot.Height)
  175. err = app.snapshots.Prune(maxSnapshotCount)
  176. if err != nil {
  177. app.logger.Error("Failed to prune snapshots", "err", err)
  178. }
  179. }
  180. retainHeight := int64(0)
  181. if app.cfg.RetainBlocks > 0 {
  182. retainHeight = int64(height - app.cfg.RetainBlocks + 1)
  183. }
  184. return abci.ResponseCommit{
  185. Data: hash,
  186. RetainHeight: retainHeight,
  187. }
  188. }
  189. // Query implements ABCI.
  190. func (app *Application) Query(req abci.RequestQuery) abci.ResponseQuery {
  191. return abci.ResponseQuery{
  192. Height: int64(app.state.Height),
  193. Key: req.Data,
  194. Value: []byte(app.state.Get(string(req.Data))),
  195. }
  196. }
  197. // ListSnapshots implements ABCI.
  198. func (app *Application) ListSnapshots(req abci.RequestListSnapshots) abci.ResponseListSnapshots {
  199. snapshots, err := app.snapshots.List()
  200. if err != nil {
  201. panic(err)
  202. }
  203. return abci.ResponseListSnapshots{Snapshots: snapshots}
  204. }
  205. // LoadSnapshotChunk implements ABCI.
  206. func (app *Application) LoadSnapshotChunk(req abci.RequestLoadSnapshotChunk) abci.ResponseLoadSnapshotChunk {
  207. chunk, err := app.snapshots.LoadChunk(req.Height, req.Format, req.Chunk)
  208. if err != nil {
  209. panic(err)
  210. }
  211. return abci.ResponseLoadSnapshotChunk{Chunk: chunk}
  212. }
  213. // OfferSnapshot implements ABCI.
  214. func (app *Application) OfferSnapshot(req abci.RequestOfferSnapshot) abci.ResponseOfferSnapshot {
  215. if app.restoreSnapshot != nil {
  216. panic("A snapshot is already being restored")
  217. }
  218. app.restoreSnapshot = req.Snapshot
  219. app.restoreChunks = [][]byte{}
  220. return abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_ACCEPT}
  221. }
  222. // ApplySnapshotChunk implements ABCI.
  223. func (app *Application) ApplySnapshotChunk(req abci.RequestApplySnapshotChunk) abci.ResponseApplySnapshotChunk {
  224. if app.restoreSnapshot == nil {
  225. panic("No restore in progress")
  226. }
  227. app.restoreChunks = append(app.restoreChunks, req.Chunk)
  228. if len(app.restoreChunks) == int(app.restoreSnapshot.Chunks) {
  229. bz := []byte{}
  230. for _, chunk := range app.restoreChunks {
  231. bz = append(bz, chunk...)
  232. }
  233. err := app.state.Import(app.restoreSnapshot.Height, bz)
  234. if err != nil {
  235. panic(err)
  236. }
  237. app.restoreSnapshot = nil
  238. app.restoreChunks = nil
  239. }
  240. return abci.ResponseApplySnapshotChunk{Result: abci.ResponseApplySnapshotChunk_ACCEPT}
  241. }
  242. // validatorUpdates generates a validator set update.
  243. func (app *Application) validatorUpdates(height uint64) (abci.ValidatorUpdates, error) {
  244. updates := app.cfg.ValidatorUpdates[fmt.Sprintf("%v", height)]
  245. if len(updates) == 0 {
  246. return nil, nil
  247. }
  248. valUpdates := abci.ValidatorUpdates{}
  249. for keyString, power := range updates {
  250. keyBytes, err := base64.StdEncoding.DecodeString(keyString)
  251. if err != nil {
  252. return nil, fmt.Errorf("invalid base64 pubkey value %q: %w", keyString, err)
  253. }
  254. valUpdates = append(valUpdates, abci.UpdateValidator(keyBytes, int64(power), app.cfg.KeyType))
  255. }
  256. return valUpdates, nil
  257. }
  258. // parseTx parses a tx in 'key=value' format into a key and value.
  259. func parseTx(tx []byte) (string, string, error) {
  260. parts := bytes.Split(tx, []byte("="))
  261. if len(parts) != 2 {
  262. return "", "", fmt.Errorf("invalid tx format: %q", string(tx))
  263. }
  264. if len(parts[0]) == 0 {
  265. return "", "", errors.New("key cannot be empty")
  266. }
  267. return string(parts[0]), string(parts[1]), nil
  268. }