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.

238 lines
6.9 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/crypto/ed25519"
  11. "github.com/tendermint/tendermint/libs/log"
  12. tmtypes "github.com/tendermint/tendermint/types"
  13. dbm "github.com/tendermint/tm-cmn/db"
  14. )
  15. const (
  16. ValidatorSetChangePrefix string = "val:"
  17. )
  18. //-----------------------------------------
  19. var _ types.Application = (*PersistentKVStoreApplication)(nil)
  20. type PersistentKVStoreApplication struct {
  21. app *KVStoreApplication
  22. // validator set
  23. ValUpdates []types.ValidatorUpdate
  24. valAddrToPubKeyMap map[string]types.PubKey
  25. logger log.Logger
  26. }
  27. func NewPersistentKVStoreApplication(dbDir string) *PersistentKVStoreApplication {
  28. name := "kvstore"
  29. db, err := dbm.NewGoLevelDB(name, dbDir)
  30. if err != nil {
  31. panic(err)
  32. }
  33. state := loadState(db)
  34. return &PersistentKVStoreApplication{
  35. app: &KVStoreApplication{state: state},
  36. valAddrToPubKeyMap: make(map[string]types.PubKey),
  37. logger: log.NewNopLogger(),
  38. }
  39. }
  40. func (app *PersistentKVStoreApplication) SetLogger(l log.Logger) {
  41. app.logger = l
  42. }
  43. func (app *PersistentKVStoreApplication) Info(req types.RequestInfo) types.ResponseInfo {
  44. res := app.app.Info(req)
  45. res.LastBlockHeight = app.app.state.Height
  46. res.LastBlockAppHash = app.app.state.AppHash
  47. return res
  48. }
  49. func (app *PersistentKVStoreApplication) SetOption(req types.RequestSetOption) types.ResponseSetOption {
  50. return app.app.SetOption(req)
  51. }
  52. // tx is either "val:pubkey!power" or "key=value" or just arbitrary bytes
  53. func (app *PersistentKVStoreApplication) DeliverTx(req types.RequestDeliverTx) types.ResponseDeliverTx {
  54. // if it starts with "val:", update the validator set
  55. // format is "val:pubkey!power"
  56. if isValidatorTx(req.Tx) {
  57. // update validators in the merkle tree
  58. // and in app.ValUpdates
  59. return app.execValidatorTx(req.Tx)
  60. }
  61. // otherwise, update the key-value store
  62. return app.app.DeliverTx(req)
  63. }
  64. func (app *PersistentKVStoreApplication) CheckTx(req types.RequestCheckTx) types.ResponseCheckTx {
  65. return app.app.CheckTx(req)
  66. }
  67. // Commit will panic if InitChain was not called
  68. func (app *PersistentKVStoreApplication) Commit() types.ResponseCommit {
  69. return app.app.Commit()
  70. }
  71. // When path=/val and data={validator address}, returns the validator update (types.ValidatorUpdate) varint encoded.
  72. // For any other path, returns an associated value or nil if missing.
  73. func (app *PersistentKVStoreApplication) Query(reqQuery types.RequestQuery) (resQuery types.ResponseQuery) {
  74. switch reqQuery.Path {
  75. case "/val":
  76. key := []byte("val:" + string(reqQuery.Data))
  77. value := app.app.state.db.Get(key)
  78. resQuery.Key = reqQuery.Data
  79. resQuery.Value = value
  80. return
  81. default:
  82. return app.app.Query(reqQuery)
  83. }
  84. }
  85. // Save the validators in the merkle tree
  86. func (app *PersistentKVStoreApplication) InitChain(req types.RequestInitChain) types.ResponseInitChain {
  87. for _, v := range req.Validators {
  88. r := app.updateValidator(v)
  89. if r.IsErr() {
  90. app.logger.Error("Error updating validators", "r", r)
  91. }
  92. }
  93. return types.ResponseInitChain{}
  94. }
  95. // Track the block hash and header information
  96. func (app *PersistentKVStoreApplication) BeginBlock(req types.RequestBeginBlock) types.ResponseBeginBlock {
  97. // reset valset changes
  98. app.ValUpdates = make([]types.ValidatorUpdate, 0)
  99. for _, ev := range req.ByzantineValidators {
  100. switch ev.Type {
  101. case tmtypes.ABCIEvidenceTypeDuplicateVote:
  102. // decrease voting power by 1
  103. if ev.TotalVotingPower == 0 {
  104. continue
  105. }
  106. app.updateValidator(types.ValidatorUpdate{
  107. PubKey: app.valAddrToPubKeyMap[string(ev.Validator.Address)],
  108. Power: ev.TotalVotingPower - 1,
  109. })
  110. }
  111. }
  112. return types.ResponseBeginBlock{}
  113. }
  114. // Update the validator set
  115. func (app *PersistentKVStoreApplication) EndBlock(req types.RequestEndBlock) types.ResponseEndBlock {
  116. return types.ResponseEndBlock{ValidatorUpdates: app.ValUpdates}
  117. }
  118. //---------------------------------------------
  119. // update validators
  120. func (app *PersistentKVStoreApplication) Validators() (validators []types.ValidatorUpdate) {
  121. itr := app.app.state.db.Iterator(nil, nil)
  122. for ; itr.Valid(); itr.Next() {
  123. if isValidatorTx(itr.Key()) {
  124. validator := new(types.ValidatorUpdate)
  125. err := types.ReadMessage(bytes.NewBuffer(itr.Value()), validator)
  126. if err != nil {
  127. panic(err)
  128. }
  129. validators = append(validators, *validator)
  130. }
  131. }
  132. return
  133. }
  134. func MakeValSetChangeTx(pubkey types.PubKey, power int64) []byte {
  135. pubStr := base64.StdEncoding.EncodeToString(pubkey.Data)
  136. return []byte(fmt.Sprintf("val:%s!%d", pubStr, power))
  137. }
  138. func isValidatorTx(tx []byte) bool {
  139. return strings.HasPrefix(string(tx), ValidatorSetChangePrefix)
  140. }
  141. // format is "val:pubkey!power"
  142. // pubkey is a base64-encoded 32-byte ed25519 key
  143. func (app *PersistentKVStoreApplication) execValidatorTx(tx []byte) types.ResponseDeliverTx {
  144. tx = tx[len(ValidatorSetChangePrefix):]
  145. //get the pubkey and power
  146. pubKeyAndPower := strings.Split(string(tx), "!")
  147. if len(pubKeyAndPower) != 2 {
  148. return types.ResponseDeliverTx{
  149. Code: code.CodeTypeEncodingError,
  150. Log: fmt.Sprintf("Expected 'pubkey!power'. Got %v", pubKeyAndPower)}
  151. }
  152. pubkeyS, powerS := pubKeyAndPower[0], pubKeyAndPower[1]
  153. // decode the pubkey
  154. pubkey, err := base64.StdEncoding.DecodeString(pubkeyS)
  155. if err != nil {
  156. return types.ResponseDeliverTx{
  157. Code: code.CodeTypeEncodingError,
  158. Log: fmt.Sprintf("Pubkey (%s) is invalid base64", pubkeyS)}
  159. }
  160. // decode the power
  161. power, err := strconv.ParseInt(powerS, 10, 64)
  162. if err != nil {
  163. return types.ResponseDeliverTx{
  164. Code: code.CodeTypeEncodingError,
  165. Log: fmt.Sprintf("Power (%s) is not an int", powerS)}
  166. }
  167. // update
  168. return app.updateValidator(types.Ed25519ValidatorUpdate(pubkey, int64(power)))
  169. }
  170. // add, update, or remove a validator
  171. func (app *PersistentKVStoreApplication) updateValidator(v types.ValidatorUpdate) types.ResponseDeliverTx {
  172. key := []byte("val:" + string(v.PubKey.Data))
  173. pubkey := ed25519.PubKeyEd25519{}
  174. copy(pubkey[:], v.PubKey.Data)
  175. if v.Power == 0 {
  176. // remove validator
  177. if !app.app.state.db.Has(key) {
  178. pubStr := base64.StdEncoding.EncodeToString(v.PubKey.Data)
  179. return types.ResponseDeliverTx{
  180. Code: code.CodeTypeUnauthorized,
  181. Log: fmt.Sprintf("Cannot remove non-existent validator %s", pubStr)}
  182. }
  183. app.app.state.db.Delete(key)
  184. delete(app.valAddrToPubKeyMap, string(pubkey.Address()))
  185. } else {
  186. // add or update validator
  187. value := bytes.NewBuffer(make([]byte, 0))
  188. if err := types.WriteMessage(&v, value); err != nil {
  189. return types.ResponseDeliverTx{
  190. Code: code.CodeTypeEncodingError,
  191. Log: fmt.Sprintf("Error encoding validator: %v", err)}
  192. }
  193. app.app.state.db.Set(key, value.Bytes())
  194. app.valAddrToPubKeyMap[string(pubkey.Address())] = v.PubKey
  195. }
  196. // we only update the changes array if we successfully updated the tree
  197. app.ValUpdates = append(app.ValUpdates, v)
  198. return types.ResponseDeliverTx{Code: code.CodeTypeOK}
  199. }