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.

311 lines
9.0 KiB

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