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.

199 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. dbm "github.com/tendermint/tendermint/libs/db"
  11. "github.com/tendermint/tendermint/libs/log"
  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(tx []byte) types.ResponseDeliverTx {
  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.ValUpdates
  55. return app.execValidatorTx(tx)
  56. }
  57. // otherwise, update the key-value store
  58. return app.app.DeliverTx(tx)
  59. }
  60. func (app *PersistentKVStoreApplication) CheckTx(tx []byte) types.ResponseCheckTx {
  61. return app.app.CheckTx(tx)
  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. return []byte(fmt.Sprintf("val:%X/%d", pubkey.Data, power))
  108. }
  109. func isValidatorTx(tx []byte) bool {
  110. return strings.HasPrefix(string(tx), ValidatorSetChangePrefix)
  111. }
  112. // format is "val:pubkey/power"
  113. // pubkey is raw 32-byte ed25519 key
  114. func (app *PersistentKVStoreApplication) 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
  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. // decode the power
  132. power, err := strconv.ParseInt(powerS, 10, 64)
  133. if err != nil {
  134. return types.ResponseDeliverTx{
  135. Code: code.CodeTypeEncodingError,
  136. Log: fmt.Sprintf("Power (%s) is not an int", powerS)}
  137. }
  138. // update
  139. return app.updateValidator(types.Ed25519ValidatorUpdate(pubkey, int64(power)))
  140. }
  141. // add, update, or remove a validator
  142. func (app *PersistentKVStoreApplication) updateValidator(v types.ValidatorUpdate) types.ResponseDeliverTx {
  143. key := []byte("val:" + string(v.PubKey.Data))
  144. if v.Power == 0 {
  145. // remove validator
  146. if !app.app.state.db.Has(key) {
  147. return types.ResponseDeliverTx{
  148. Code: code.CodeTypeUnauthorized,
  149. Log: fmt.Sprintf("Cannot remove non-existent validator %X", key)}
  150. }
  151. app.app.state.db.Delete(key)
  152. } else {
  153. // add or update validator
  154. value := bytes.NewBuffer(make([]byte, 0))
  155. if err := types.WriteMessage(&v, value); err != nil {
  156. return types.ResponseDeliverTx{
  157. Code: code.CodeTypeEncodingError,
  158. Log: fmt.Sprintf("Error encoding validator: %v", err)}
  159. }
  160. app.app.state.db.Set(key, value.Bytes())
  161. }
  162. // we only update the changes array if we successfully updated the tree
  163. app.ValUpdates = append(app.ValUpdates, v)
  164. return types.ResponseDeliverTx{Code: code.CodeTypeOK}
  165. }