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.

205 lines
5.7 KiB

  1. package dummy
  2. import (
  3. "bytes"
  4. "encoding/hex"
  5. "fmt"
  6. "strconv"
  7. "strings"
  8. "github.com/tendermint/abci/example/code"
  9. "github.com/tendermint/abci/types"
  10. cmn "github.com/tendermint/tmlibs/common"
  11. dbm "github.com/tendermint/tmlibs/db"
  12. "github.com/tendermint/tmlibs/log"
  13. )
  14. const (
  15. ValidatorSetChangePrefix string = "val:"
  16. )
  17. //-----------------------------------------
  18. var _ types.Application = (*PersistentDummyApplication)(nil)
  19. type PersistentDummyApplication struct {
  20. app *DummyApplication
  21. // validator set
  22. ValUpdates []types.Validator
  23. logger log.Logger
  24. }
  25. func NewPersistentDummyApplication(dbDir string) *PersistentDummyApplication {
  26. name := "dummy"
  27. db, err := dbm.NewGoLevelDB(name, dbDir)
  28. if err != nil {
  29. panic(err)
  30. }
  31. state := loadState(db)
  32. return &PersistentDummyApplication{
  33. app: &DummyApplication{state: state},
  34. logger: log.NewNopLogger(),
  35. }
  36. }
  37. func (app *PersistentDummyApplication) SetLogger(l log.Logger) {
  38. app.logger = l
  39. }
  40. func (app *PersistentDummyApplication) Info(req types.RequestInfo) types.ResponseInfo {
  41. res := app.app.Info(req)
  42. res.LastBlockHeight = app.app.state.Height
  43. res.LastBlockAppHash = app.app.state.AppHash
  44. return res
  45. }
  46. func (app *PersistentDummyApplication) SetOption(req types.RequestSetOption) types.ResponseSetOption {
  47. return app.app.SetOption(req)
  48. }
  49. // tx is either "val:pubkey/power" or "key=value" or just arbitrary bytes
  50. func (app *PersistentDummyApplication) DeliverTx(tx []byte) types.ResponseDeliverTx {
  51. // if it starts with "val:", update the validator set
  52. // format is "val:pubkey/power"
  53. if isValidatorTx(tx) {
  54. // update validators in the merkle tree
  55. // and in app.ValUpdates
  56. return app.execValidatorTx(tx)
  57. }
  58. // otherwise, update the key-value store
  59. return app.app.DeliverTx(tx)
  60. }
  61. func (app *PersistentDummyApplication) CheckTx(tx []byte) types.ResponseCheckTx {
  62. return app.app.CheckTx(tx)
  63. }
  64. // Commit will panic if InitChain was not called
  65. func (app *PersistentDummyApplication) Commit() types.ResponseCommit {
  66. return app.app.Commit()
  67. }
  68. func (app *PersistentDummyApplication) Query(reqQuery types.RequestQuery) types.ResponseQuery {
  69. return app.app.Query(reqQuery)
  70. }
  71. // Save the validators in the merkle tree
  72. func (app *PersistentDummyApplication) InitChain(req types.RequestInitChain) types.ResponseInitChain {
  73. for _, v := range req.Validators {
  74. r := app.updateValidator(v)
  75. if r.IsErr() {
  76. app.logger.Error("Error updating validators", "r", r)
  77. }
  78. }
  79. return types.ResponseInitChain{}
  80. }
  81. // Track the block hash and header information
  82. func (app *PersistentDummyApplication) BeginBlock(req types.RequestBeginBlock) types.ResponseBeginBlock {
  83. // reset valset changes
  84. app.ValUpdates = make([]types.Validator, 0)
  85. return types.ResponseBeginBlock{}
  86. }
  87. // Update the validator set
  88. func (app *PersistentDummyApplication) EndBlock(req types.RequestEndBlock) types.ResponseEndBlock {
  89. return types.ResponseEndBlock{ValidatorUpdates: app.ValUpdates}
  90. }
  91. //---------------------------------------------
  92. // update validators
  93. func (app *PersistentDummyApplication) Validators() (validators []types.Validator) {
  94. itr := app.app.state.db.Iterator(nil, nil)
  95. for ; itr.Valid(); itr.Next() {
  96. if isValidatorTx(itr.Key()) {
  97. validator := new(types.Validator)
  98. err := types.ReadMessage(bytes.NewBuffer(itr.Value()), validator)
  99. if err != nil {
  100. panic(err)
  101. }
  102. validators = append(validators, *validator)
  103. }
  104. }
  105. return
  106. }
  107. func MakeValSetChangeTx(pubkey []byte, power int64) []byte {
  108. return []byte(cmn.Fmt("val:%X/%d", pubkey, power))
  109. }
  110. func isValidatorTx(tx []byte) bool {
  111. return strings.HasPrefix(string(tx), ValidatorSetChangePrefix)
  112. }
  113. // format is "val:pubkey1/power1,addr2/power2,addr3/power3"tx
  114. func (app *PersistentDummyApplication) execValidatorTx(tx []byte) types.ResponseDeliverTx {
  115. tx = tx[len(ValidatorSetChangePrefix):]
  116. //get the pubkey and power
  117. pubKeyAndPower := strings.Split(string(tx), "/")
  118. if len(pubKeyAndPower) != 2 {
  119. return types.ResponseDeliverTx{
  120. Code: code.CodeTypeEncodingError,
  121. Log: fmt.Sprintf("Expected 'pubkey/power'. Got %v", pubKeyAndPower)}
  122. }
  123. pubkeyS, powerS := pubKeyAndPower[0], pubKeyAndPower[1]
  124. // decode the pubkey, ensuring its go-crypto encoded
  125. pubkey, err := hex.DecodeString(pubkeyS)
  126. if err != nil {
  127. return types.ResponseDeliverTx{
  128. Code: code.CodeTypeEncodingError,
  129. Log: fmt.Sprintf("Pubkey (%s) is invalid hex", pubkeyS)}
  130. }
  131. /*_, err = crypto.PubKeyFromBytes(pubkey)
  132. if err != nil {
  133. return types.ResponseDeliverTx{
  134. Code: code.CodeTypeEncodingError,
  135. Log: fmt.Sprintf("Pubkey (%X) is invalid go-crypto encoded", pubkey)}
  136. }*/
  137. // decode the power
  138. power, err := strconv.ParseInt(powerS, 10, 64)
  139. if err != nil {
  140. return types.ResponseDeliverTx{
  141. Code: code.CodeTypeEncodingError,
  142. Log: fmt.Sprintf("Power (%s) is not an int", powerS)}
  143. }
  144. // update
  145. return app.updateValidator(types.Validator{pubkey, power})
  146. }
  147. // add, update, or remove a validator
  148. func (app *PersistentDummyApplication) updateValidator(v types.Validator) types.ResponseDeliverTx {
  149. key := []byte("val:" + string(v.PubKey))
  150. if v.Power == 0 {
  151. // remove validator
  152. if !app.app.state.db.Has(key) {
  153. return types.ResponseDeliverTx{
  154. Code: code.CodeTypeUnauthorized,
  155. Log: fmt.Sprintf("Cannot remove non-existent validator %X", key)}
  156. }
  157. app.app.state.db.Delete(key)
  158. } else {
  159. // add or update validator
  160. value := bytes.NewBuffer(make([]byte, 0))
  161. if err := types.WriteMessage(&v, value); err != nil {
  162. return types.ResponseDeliverTx{
  163. Code: code.CodeTypeEncodingError,
  164. Log: fmt.Sprintf("Error encoding validator: %v", err)}
  165. }
  166. app.app.state.db.Set(key, value.Bytes())
  167. }
  168. // we only update the changes array if we successfully updated the tree
  169. app.ValUpdates = append(app.ValUpdates, v)
  170. return types.ResponseDeliverTx{Code: code.CodeTypeOK}
  171. }