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.

192 lines
5.3 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. package dummy
  2. import (
  3. "bytes"
  4. "encoding/hex"
  5. "strconv"
  6. "strings"
  7. "github.com/tendermint/abci/types"
  8. "github.com/tendermint/iavl"
  9. cmn "github.com/tendermint/tmlibs/common"
  10. dbm "github.com/tendermint/tmlibs/db"
  11. "github.com/tendermint/tmlibs/log"
  12. )
  13. const (
  14. ValidatorSetChangePrefix string = "val:"
  15. )
  16. //-----------------------------------------
  17. type PersistentDummyApplication struct {
  18. app *DummyApplication
  19. // validator set
  20. changes []*types.Validator
  21. logger log.Logger
  22. }
  23. func NewPersistentDummyApplication(dbDir string) *PersistentDummyApplication {
  24. name := "dummy"
  25. db, err := dbm.NewGoLevelDB(name, dbDir)
  26. if err != nil {
  27. panic(err)
  28. }
  29. stateTree := iavl.NewVersionedTree(500, db)
  30. stateTree.Load()
  31. return &PersistentDummyApplication{
  32. app: &DummyApplication{state: stateTree},
  33. logger: log.NewNopLogger(),
  34. }
  35. }
  36. func (app *PersistentDummyApplication) SetLogger(l log.Logger) {
  37. app.logger = l
  38. }
  39. func (app *PersistentDummyApplication) Info(req types.RequestInfo) (resInfo types.ResponseInfo) {
  40. resInfo = app.app.Info(req)
  41. resInfo.LastBlockHeight = app.app.state.LatestVersion()
  42. resInfo.LastBlockAppHash = app.app.state.Hash()
  43. return resInfo
  44. }
  45. func (app *PersistentDummyApplication) SetOption(key string, value string) (log string) {
  46. return app.app.SetOption(key, value)
  47. }
  48. // tx is either "val:pubkey/power" or "key=value" or just arbitrary bytes
  49. func (app *PersistentDummyApplication) DeliverTx(tx []byte) types.Result {
  50. // if it starts with "val:", update the validator set
  51. // format is "val:pubkey/power"
  52. if isValidatorTx(tx) {
  53. // update validators in the merkle tree
  54. // and in app.changes
  55. return app.execValidatorTx(tx)
  56. }
  57. // otherwise, update the key-value store
  58. return app.app.DeliverTx(tx)
  59. }
  60. func (app *PersistentDummyApplication) CheckTx(tx []byte) types.Result {
  61. return app.app.CheckTx(tx)
  62. }
  63. // Commit will panic if InitChain was not called
  64. func (app *PersistentDummyApplication) Commit() types.Result {
  65. // Save a new version for next height
  66. height := app.app.state.LatestVersion() + 1
  67. var appHash []byte
  68. var err error
  69. appHash, err = app.app.state.SaveVersion(height)
  70. if err != nil {
  71. // if this wasn't a dummy app, we'd do something smarter
  72. panic(err)
  73. }
  74. app.logger.Info("Commit block", "height", height, "root", appHash)
  75. return types.NewResultOK(appHash, "")
  76. }
  77. func (app *PersistentDummyApplication) Query(reqQuery types.RequestQuery) types.ResponseQuery {
  78. return app.app.Query(reqQuery)
  79. }
  80. // Save the validators in the merkle tree
  81. func (app *PersistentDummyApplication) InitChain(params types.RequestInitChain) {
  82. for _, v := range params.Validators {
  83. r := app.updateValidator(v)
  84. if r.IsErr() {
  85. app.logger.Error("Error updating validators", "r", r)
  86. }
  87. }
  88. }
  89. // Track the block hash and header information
  90. func (app *PersistentDummyApplication) BeginBlock(params types.RequestBeginBlock) {
  91. // reset valset changes
  92. app.changes = make([]*types.Validator, 0)
  93. }
  94. // Update the validator set
  95. func (app *PersistentDummyApplication) EndBlock(height uint64) (resEndBlock types.ResponseEndBlock) {
  96. return types.ResponseEndBlock{Diffs: app.changes}
  97. }
  98. //---------------------------------------------
  99. // update validators
  100. func (app *PersistentDummyApplication) Validators() (validators []*types.Validator) {
  101. app.app.state.Iterate(func(key, value []byte) bool {
  102. if isValidatorTx(key) {
  103. validator := new(types.Validator)
  104. err := types.ReadMessage(bytes.NewBuffer(value), validator)
  105. if err != nil {
  106. panic(err)
  107. }
  108. validators = append(validators, validator)
  109. }
  110. return false
  111. })
  112. return
  113. }
  114. func MakeValSetChangeTx(pubkey []byte, power uint64) []byte {
  115. return []byte(cmn.Fmt("val:%X/%d", pubkey, power))
  116. }
  117. func isValidatorTx(tx []byte) bool {
  118. return strings.HasPrefix(string(tx), ValidatorSetChangePrefix)
  119. }
  120. // format is "val:pubkey1/power1,addr2/power2,addr3/power3"tx
  121. func (app *PersistentDummyApplication) execValidatorTx(tx []byte) types.Result {
  122. tx = tx[len(ValidatorSetChangePrefix):]
  123. pubKeyAndPower := strings.Split(string(tx), "/")
  124. if len(pubKeyAndPower) != 2 {
  125. return types.ErrEncodingError.SetLog(cmn.Fmt("Expected 'pubkey/power'. Got %v", pubKeyAndPower))
  126. }
  127. pubkeyS, powerS := pubKeyAndPower[0], pubKeyAndPower[1]
  128. pubkey, err := hex.DecodeString(pubkeyS)
  129. if err != nil {
  130. return types.ErrEncodingError.SetLog(cmn.Fmt("Pubkey (%s) is invalid hex", pubkeyS))
  131. }
  132. power, err := strconv.Atoi(powerS)
  133. if err != nil {
  134. return types.ErrEncodingError.SetLog(cmn.Fmt("Power (%s) is not an int", powerS))
  135. }
  136. // update
  137. return app.updateValidator(&types.Validator{pubkey, uint64(power)})
  138. }
  139. // add, update, or remove a validator
  140. func (app *PersistentDummyApplication) updateValidator(v *types.Validator) types.Result {
  141. key := []byte("val:" + string(v.PubKey))
  142. if v.Power == 0 {
  143. // remove validator
  144. if !app.app.state.Has(key) {
  145. return types.ErrUnauthorized.SetLog(cmn.Fmt("Cannot remove non-existent validator %X", key))
  146. }
  147. app.app.state.Remove(key)
  148. } else {
  149. // add or update validator
  150. value := bytes.NewBuffer(make([]byte, 0))
  151. if err := types.WriteMessage(v, value); err != nil {
  152. return types.ErrInternalError.SetLog(cmn.Fmt("Error encoding validator: %v", err))
  153. }
  154. app.app.state.Set(key, value.Bytes())
  155. }
  156. // we only update the changes array if we successfully updated the tree
  157. app.changes = append(app.changes, v)
  158. return types.OK
  159. }