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.

200 lines
5.6 KiB

8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. package kvstore
  2. import (
  3. "bytes"
  4. "encoding/hex"
  5. "fmt"
  6. "strconv"
  7. "strings"
  8. "github.com/tendermint/tendermint/abci/example/code"
  9. "github.com/tendermint/tendermint/abci/types"
  10. cmn "github.com/tendermint/tendermint/libs/common"
  11. dbm "github.com/tendermint/tendermint/libs/db"
  12. "github.com/tendermint/tendermint/libs/log"
  13. )
  14. const (
  15. ValidatorSetChangePrefix string = "val:"
  16. )
  17. //-----------------------------------------
  18. var _ types.Application = (*PersistentKVStoreApplication)(nil)
  19. type PersistentKVStoreApplication struct {
  20. app *KVStoreApplication
  21. // validator set
  22. ValUpdates []types.Validator
  23. logger log.Logger
  24. }
  25. func NewPersistentKVStoreApplication(dbDir string) *PersistentKVStoreApplication {
  26. name := "kvstore"
  27. db, err := dbm.NewGoLevelDB(name, dbDir)
  28. if err != nil {
  29. panic(err)
  30. }
  31. state := loadState(db)
  32. return &PersistentKVStoreApplication{
  33. app: &KVStoreApplication{state: state},
  34. logger: log.NewNopLogger(),
  35. }
  36. }
  37. func (app *PersistentKVStoreApplication) SetLogger(l log.Logger) {
  38. app.logger = l
  39. }
  40. func (app *PersistentKVStoreApplication) 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 *PersistentKVStoreApplication) 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 *PersistentKVStoreApplication) 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 *PersistentKVStoreApplication) CheckTx(tx []byte) types.ResponseCheckTx {
  62. return app.app.CheckTx(tx)
  63. }
  64. // Commit will panic if InitChain was not called
  65. func (app *PersistentKVStoreApplication) Commit() types.ResponseCommit {
  66. return app.app.Commit()
  67. }
  68. func (app *PersistentKVStoreApplication) Query(reqQuery types.RequestQuery) types.ResponseQuery {
  69. return app.app.Query(reqQuery)
  70. }
  71. // Save the validators in the merkle tree
  72. func (app *PersistentKVStoreApplication) 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 *PersistentKVStoreApplication) 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 *PersistentKVStoreApplication) EndBlock(req types.RequestEndBlock) types.ResponseEndBlock {
  89. return types.ResponseEndBlock{ValidatorUpdates: app.ValUpdates}
  90. }
  91. //---------------------------------------------
  92. // update validators
  93. func (app *PersistentKVStoreApplication) 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 types.PubKey, power int64) []byte {
  108. return []byte(cmn.Fmt("val:%X/%d", pubkey.Data, power))
  109. }
  110. func isValidatorTx(tx []byte) bool {
  111. return strings.HasPrefix(string(tx), ValidatorSetChangePrefix)
  112. }
  113. // format is "val:pubkey/power"
  114. // pubkey is raw 32-byte ed25519 key
  115. func (app *PersistentKVStoreApplication) execValidatorTx(tx []byte) types.ResponseDeliverTx {
  116. tx = tx[len(ValidatorSetChangePrefix):]
  117. //get the pubkey and power
  118. pubKeyAndPower := strings.Split(string(tx), "/")
  119. if len(pubKeyAndPower) != 2 {
  120. return types.ResponseDeliverTx{
  121. Code: code.CodeTypeEncodingError,
  122. Log: fmt.Sprintf("Expected 'pubkey/power'. Got %v", pubKeyAndPower)}
  123. }
  124. pubkeyS, powerS := pubKeyAndPower[0], pubKeyAndPower[1]
  125. // decode the pubkey
  126. pubkey, err := hex.DecodeString(pubkeyS)
  127. if err != nil {
  128. return types.ResponseDeliverTx{
  129. Code: code.CodeTypeEncodingError,
  130. Log: fmt.Sprintf("Pubkey (%s) is invalid hex", pubkeyS)}
  131. }
  132. // decode the power
  133. power, err := strconv.ParseInt(powerS, 10, 64)
  134. if err != nil {
  135. return types.ResponseDeliverTx{
  136. Code: code.CodeTypeEncodingError,
  137. Log: fmt.Sprintf("Power (%s) is not an int", powerS)}
  138. }
  139. // update
  140. return app.updateValidator(types.Ed25519Validator(pubkey, int64(power)))
  141. }
  142. // add, update, or remove a validator
  143. func (app *PersistentKVStoreApplication) updateValidator(v types.Validator) types.ResponseDeliverTx {
  144. key := []byte("val:" + string(v.PubKey.Data))
  145. if v.Power == 0 {
  146. // remove validator
  147. if !app.app.state.db.Has(key) {
  148. return types.ResponseDeliverTx{
  149. Code: code.CodeTypeUnauthorized,
  150. Log: fmt.Sprintf("Cannot remove non-existent validator %X", key)}
  151. }
  152. app.app.state.db.Delete(key)
  153. } else {
  154. // add or update validator
  155. value := bytes.NewBuffer(make([]byte, 0))
  156. if err := types.WriteMessage(&v, value); err != nil {
  157. return types.ResponseDeliverTx{
  158. Code: code.CodeTypeEncodingError,
  159. Log: fmt.Sprintf("Error encoding validator: %v", err)}
  160. }
  161. app.app.state.db.Set(key, value.Bytes())
  162. }
  163. // we only update the changes array if we successfully updated the tree
  164. app.ValUpdates = append(app.ValUpdates, v)
  165. return types.ResponseDeliverTx{Code: code.CodeTypeOK}
  166. }