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.

237 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-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. if ev.Type == tmtypes.ABCIEvidenceTypeDuplicateVote {
  101. // decrease voting power by 1
  102. if ev.TotalVotingPower == 0 {
  103. continue
  104. }
  105. app.updateValidator(types.ValidatorUpdate{
  106. PubKey: app.valAddrToPubKeyMap[string(ev.Validator.Address)],
  107. Power: ev.TotalVotingPower - 1,
  108. })
  109. }
  110. }
  111. return types.ResponseBeginBlock{}
  112. }
  113. // Update the validator set
  114. func (app *PersistentKVStoreApplication) EndBlock(req types.RequestEndBlock) types.ResponseEndBlock {
  115. return types.ResponseEndBlock{ValidatorUpdates: app.ValUpdates}
  116. }
  117. //---------------------------------------------
  118. // update validators
  119. func (app *PersistentKVStoreApplication) Validators() (validators []types.ValidatorUpdate) {
  120. itr := app.app.state.db.Iterator(nil, nil)
  121. for ; itr.Valid(); itr.Next() {
  122. if isValidatorTx(itr.Key()) {
  123. validator := new(types.ValidatorUpdate)
  124. err := types.ReadMessage(bytes.NewBuffer(itr.Value()), validator)
  125. if err != nil {
  126. panic(err)
  127. }
  128. validators = append(validators, *validator)
  129. }
  130. }
  131. return
  132. }
  133. func MakeValSetChangeTx(pubkey types.PubKey, power int64) []byte {
  134. pubStr := base64.StdEncoding.EncodeToString(pubkey.Data)
  135. return []byte(fmt.Sprintf("val:%s!%d", pubStr, power))
  136. }
  137. func isValidatorTx(tx []byte) bool {
  138. return strings.HasPrefix(string(tx), ValidatorSetChangePrefix)
  139. }
  140. // format is "val:pubkey!power"
  141. // pubkey is a base64-encoded 32-byte ed25519 key
  142. func (app *PersistentKVStoreApplication) execValidatorTx(tx []byte) types.ResponseDeliverTx {
  143. tx = tx[len(ValidatorSetChangePrefix):]
  144. //get the pubkey and power
  145. pubKeyAndPower := strings.Split(string(tx), "!")
  146. if len(pubKeyAndPower) != 2 {
  147. return types.ResponseDeliverTx{
  148. Code: code.CodeTypeEncodingError,
  149. Log: fmt.Sprintf("Expected 'pubkey!power'. Got %v", pubKeyAndPower)}
  150. }
  151. pubkeyS, powerS := pubKeyAndPower[0], pubKeyAndPower[1]
  152. // decode the pubkey
  153. pubkey, err := base64.StdEncoding.DecodeString(pubkeyS)
  154. if err != nil {
  155. return types.ResponseDeliverTx{
  156. Code: code.CodeTypeEncodingError,
  157. Log: fmt.Sprintf("Pubkey (%s) is invalid base64", pubkeyS)}
  158. }
  159. // decode the power
  160. power, err := strconv.ParseInt(powerS, 10, 64)
  161. if err != nil {
  162. return types.ResponseDeliverTx{
  163. Code: code.CodeTypeEncodingError,
  164. Log: fmt.Sprintf("Power (%s) is not an int", powerS)}
  165. }
  166. // update
  167. return app.updateValidator(types.Ed25519ValidatorUpdate(pubkey, power))
  168. }
  169. // add, update, or remove a validator
  170. func (app *PersistentKVStoreApplication) updateValidator(v types.ValidatorUpdate) types.ResponseDeliverTx {
  171. key := []byte("val:" + string(v.PubKey.Data))
  172. pubkey := ed25519.PubKeyEd25519{}
  173. copy(pubkey[:], v.PubKey.Data)
  174. if v.Power == 0 {
  175. // remove validator
  176. if !app.app.state.db.Has(key) {
  177. pubStr := base64.StdEncoding.EncodeToString(v.PubKey.Data)
  178. return types.ResponseDeliverTx{
  179. Code: code.CodeTypeUnauthorized,
  180. Log: fmt.Sprintf("Cannot remove non-existent validator %s", pubStr)}
  181. }
  182. app.app.state.db.Delete(key)
  183. delete(app.valAddrToPubKeyMap, string(pubkey.Address()))
  184. } else {
  185. // add or update validator
  186. value := bytes.NewBuffer(make([]byte, 0))
  187. if err := types.WriteMessage(&v, value); err != nil {
  188. return types.ResponseDeliverTx{
  189. Code: code.CodeTypeEncodingError,
  190. Log: fmt.Sprintf("Error encoding validator: %v", err)}
  191. }
  192. app.app.state.db.Set(key, value.Bytes())
  193. app.valAddrToPubKeyMap[string(pubkey.Address())] = v.PubKey
  194. }
  195. // we only update the changes array if we successfully updated the tree
  196. app.ValUpdates = append(app.ValUpdates, v)
  197. return types.ResponseDeliverTx{Code: code.CodeTypeOK}
  198. }