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.

201 lines
5.8 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/base64"
  5. "fmt"
  6. "strconv"
  7. "strings"
  8. "github.com/tendermint/tendermint/abci/example/code"
  9. "github.com/tendermint/tendermint/abci/types"
  10. "github.com/tendermint/tendermint/libs/log"
  11. dbm "github.com/tendermint/tm-cmn/db"
  12. )
  13. const (
  14. ValidatorSetChangePrefix string = "val:"
  15. )
  16. //-----------------------------------------
  17. var _ types.Application = (*PersistentKVStoreApplication)(nil)
  18. type PersistentKVStoreApplication struct {
  19. app *KVStoreApplication
  20. // validator set
  21. ValUpdates []types.ValidatorUpdate
  22. logger log.Logger
  23. }
  24. func NewPersistentKVStoreApplication(dbDir string) *PersistentKVStoreApplication {
  25. name := "kvstore"
  26. db, err := dbm.NewGoLevelDB(name, dbDir)
  27. if err != nil {
  28. panic(err)
  29. }
  30. state := loadState(db)
  31. return &PersistentKVStoreApplication{
  32. app: &KVStoreApplication{state: state},
  33. logger: log.NewNopLogger(),
  34. }
  35. }
  36. func (app *PersistentKVStoreApplication) SetLogger(l log.Logger) {
  37. app.logger = l
  38. }
  39. func (app *PersistentKVStoreApplication) Info(req types.RequestInfo) types.ResponseInfo {
  40. res := app.app.Info(req)
  41. res.LastBlockHeight = app.app.state.Height
  42. res.LastBlockAppHash = app.app.state.AppHash
  43. return res
  44. }
  45. func (app *PersistentKVStoreApplication) SetOption(req types.RequestSetOption) types.ResponseSetOption {
  46. return app.app.SetOption(req)
  47. }
  48. // tx is either "val:pubkey!power" or "key=value" or just arbitrary bytes
  49. func (app *PersistentKVStoreApplication) DeliverTx(req types.RequestDeliverTx) types.ResponseDeliverTx {
  50. // if it starts with "val:", update the validator set
  51. // format is "val:pubkey!power"
  52. if isValidatorTx(req.Tx) {
  53. // update validators in the merkle tree
  54. // and in app.ValUpdates
  55. return app.execValidatorTx(req.Tx)
  56. }
  57. // otherwise, update the key-value store
  58. return app.app.DeliverTx(req)
  59. }
  60. func (app *PersistentKVStoreApplication) CheckTx(req types.RequestCheckTx) types.ResponseCheckTx {
  61. return app.app.CheckTx(req)
  62. }
  63. // Commit will panic if InitChain was not called
  64. func (app *PersistentKVStoreApplication) Commit() types.ResponseCommit {
  65. return app.app.Commit()
  66. }
  67. func (app *PersistentKVStoreApplication) Query(reqQuery types.RequestQuery) types.ResponseQuery {
  68. return app.app.Query(reqQuery)
  69. }
  70. // Save the validators in the merkle tree
  71. func (app *PersistentKVStoreApplication) InitChain(req types.RequestInitChain) types.ResponseInitChain {
  72. for _, v := range req.Validators {
  73. r := app.updateValidator(v)
  74. if r.IsErr() {
  75. app.logger.Error("Error updating validators", "r", r)
  76. }
  77. }
  78. return types.ResponseInitChain{}
  79. }
  80. // Track the block hash and header information
  81. func (app *PersistentKVStoreApplication) BeginBlock(req types.RequestBeginBlock) types.ResponseBeginBlock {
  82. // reset valset changes
  83. app.ValUpdates = make([]types.ValidatorUpdate, 0)
  84. return types.ResponseBeginBlock{}
  85. }
  86. // Update the validator set
  87. func (app *PersistentKVStoreApplication) EndBlock(req types.RequestEndBlock) types.ResponseEndBlock {
  88. return types.ResponseEndBlock{ValidatorUpdates: app.ValUpdates}
  89. }
  90. //---------------------------------------------
  91. // update validators
  92. func (app *PersistentKVStoreApplication) Validators() (validators []types.ValidatorUpdate) {
  93. itr := app.app.state.db.Iterator(nil, nil)
  94. for ; itr.Valid(); itr.Next() {
  95. if isValidatorTx(itr.Key()) {
  96. validator := new(types.ValidatorUpdate)
  97. err := types.ReadMessage(bytes.NewBuffer(itr.Value()), validator)
  98. if err != nil {
  99. panic(err)
  100. }
  101. validators = append(validators, *validator)
  102. }
  103. }
  104. return
  105. }
  106. func MakeValSetChangeTx(pubkey types.PubKey, power int64) []byte {
  107. pubStr := base64.StdEncoding.EncodeToString(pubkey.Data)
  108. return []byte(fmt.Sprintf("val:%s!%d", pubStr, 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 a base64-encoded 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 := base64.StdEncoding.DecodeString(pubkeyS)
  127. if err != nil {
  128. return types.ResponseDeliverTx{
  129. Code: code.CodeTypeEncodingError,
  130. Log: fmt.Sprintf("Pubkey (%s) is invalid base64", 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.Ed25519ValidatorUpdate(pubkey, int64(power)))
  141. }
  142. // add, update, or remove a validator
  143. func (app *PersistentKVStoreApplication) updateValidator(v types.ValidatorUpdate) 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. pubStr := base64.StdEncoding.EncodeToString(v.PubKey.Data)
  149. return types.ResponseDeliverTx{
  150. Code: code.CodeTypeUnauthorized,
  151. Log: fmt.Sprintf("Cannot remove non-existent validator %s", pubStr)}
  152. }
  153. app.app.state.db.Delete(key)
  154. } else {
  155. // add or update validator
  156. value := bytes.NewBuffer(make([]byte, 0))
  157. if err := types.WriteMessage(&v, value); err != nil {
  158. return types.ResponseDeliverTx{
  159. Code: code.CodeTypeEncodingError,
  160. Log: fmt.Sprintf("Error encoding validator: %v", err)}
  161. }
  162. app.app.state.db.Set(key, value.Bytes())
  163. }
  164. // we only update the changes array if we successfully updated the tree
  165. app.ValUpdates = append(app.ValUpdates, v)
  166. return types.ResponseDeliverTx{Code: code.CodeTypeOK}
  167. }