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.

247 lines
7.0 KiB

lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
8 years ago
8 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 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 *Application
  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: &Application{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, err := app.app.state.db.Get(key)
  78. if err != nil {
  79. panic(err)
  80. }
  81. resQuery.Key = reqQuery.Data
  82. resQuery.Value = value
  83. return
  84. default:
  85. return app.app.Query(reqQuery)
  86. }
  87. }
  88. // Save the validators in the merkle tree
  89. func (app *PersistentKVStoreApplication) InitChain(req types.RequestInitChain) types.ResponseInitChain {
  90. for _, v := range req.Validators {
  91. r := app.updateValidator(v)
  92. if r.IsErr() {
  93. app.logger.Error("Error updating validators", "r", r)
  94. }
  95. }
  96. return types.ResponseInitChain{}
  97. }
  98. // Track the block hash and header information
  99. func (app *PersistentKVStoreApplication) BeginBlock(req types.RequestBeginBlock) types.ResponseBeginBlock {
  100. // reset valset changes
  101. app.ValUpdates = make([]types.ValidatorUpdate, 0)
  102. for _, ev := range req.ByzantineValidators {
  103. if ev.Type == tmtypes.ABCIEvidenceTypeDuplicateVote {
  104. // decrease voting power by 1
  105. if ev.TotalVotingPower == 0 {
  106. continue
  107. }
  108. app.updateValidator(types.ValidatorUpdate{
  109. PubKey: app.valAddrToPubKeyMap[string(ev.Validator.Address)],
  110. Power: ev.TotalVotingPower - 1,
  111. })
  112. }
  113. }
  114. return types.ResponseBeginBlock{}
  115. }
  116. // Update the validator set
  117. func (app *PersistentKVStoreApplication) EndBlock(req types.RequestEndBlock) types.ResponseEndBlock {
  118. return types.ResponseEndBlock{ValidatorUpdates: app.ValUpdates}
  119. }
  120. //---------------------------------------------
  121. // update validators
  122. func (app *PersistentKVStoreApplication) Validators() (validators []types.ValidatorUpdate) {
  123. itr, err := app.app.state.db.Iterator(nil, nil)
  124. if err != nil {
  125. panic(err)
  126. }
  127. for ; itr.Valid(); itr.Next() {
  128. if isValidatorTx(itr.Key()) {
  129. validator := new(types.ValidatorUpdate)
  130. err := types.ReadMessage(bytes.NewBuffer(itr.Value()), validator)
  131. if err != nil {
  132. panic(err)
  133. }
  134. validators = append(validators, *validator)
  135. }
  136. }
  137. return
  138. }
  139. func MakeValSetChangeTx(pubkey types.PubKey, power int64) []byte {
  140. pubStr := base64.StdEncoding.EncodeToString(pubkey.Data)
  141. return []byte(fmt.Sprintf("val:%s!%d", pubStr, power))
  142. }
  143. func isValidatorTx(tx []byte) bool {
  144. return strings.HasPrefix(string(tx), ValidatorSetChangePrefix)
  145. }
  146. // format is "val:pubkey!power"
  147. // pubkey is a base64-encoded 32-byte ed25519 key
  148. func (app *PersistentKVStoreApplication) execValidatorTx(tx []byte) types.ResponseDeliverTx {
  149. tx = tx[len(ValidatorSetChangePrefix):]
  150. //get the pubkey and power
  151. pubKeyAndPower := strings.Split(string(tx), "!")
  152. if len(pubKeyAndPower) != 2 {
  153. return types.ResponseDeliverTx{
  154. Code: code.CodeTypeEncodingError,
  155. Log: fmt.Sprintf("Expected 'pubkey!power'. Got %v", pubKeyAndPower)}
  156. }
  157. pubkeyS, powerS := pubKeyAndPower[0], pubKeyAndPower[1]
  158. // decode the pubkey
  159. pubkey, err := base64.StdEncoding.DecodeString(pubkeyS)
  160. if err != nil {
  161. return types.ResponseDeliverTx{
  162. Code: code.CodeTypeEncodingError,
  163. Log: fmt.Sprintf("Pubkey (%s) is invalid base64", pubkeyS)}
  164. }
  165. // decode the power
  166. power, err := strconv.ParseInt(powerS, 10, 64)
  167. if err != nil {
  168. return types.ResponseDeliverTx{
  169. Code: code.CodeTypeEncodingError,
  170. Log: fmt.Sprintf("Power (%s) is not an int", powerS)}
  171. }
  172. // update
  173. return app.updateValidator(types.Ed25519ValidatorUpdate(pubkey, power))
  174. }
  175. // add, update, or remove a validator
  176. func (app *PersistentKVStoreApplication) updateValidator(v types.ValidatorUpdate) types.ResponseDeliverTx {
  177. key := []byte("val:" + string(v.PubKey.Data))
  178. pubkey := ed25519.PubKeyEd25519{}
  179. copy(pubkey[:], v.PubKey.Data)
  180. if v.Power == 0 {
  181. // remove validator
  182. hasKey, err := app.app.state.db.Has(key)
  183. if err != nil {
  184. panic(err)
  185. }
  186. if !hasKey {
  187. pubStr := base64.StdEncoding.EncodeToString(v.PubKey.Data)
  188. return types.ResponseDeliverTx{
  189. Code: code.CodeTypeUnauthorized,
  190. Log: fmt.Sprintf("Cannot remove non-existent validator %s", pubStr)}
  191. }
  192. app.app.state.db.Delete(key)
  193. delete(app.valAddrToPubKeyMap, string(pubkey.Address()))
  194. } else {
  195. // add or update validator
  196. value := bytes.NewBuffer(make([]byte, 0))
  197. if err := types.WriteMessage(&v, value); err != nil {
  198. return types.ResponseDeliverTx{
  199. Code: code.CodeTypeEncodingError,
  200. Log: fmt.Sprintf("Error encoding validator: %v", err)}
  201. }
  202. app.app.state.db.Set(key, value.Bytes())
  203. app.valAddrToPubKeyMap[string(pubkey.Address())] = v.PubKey
  204. }
  205. // we only update the changes array if we successfully updated the tree
  206. app.ValUpdates = append(app.ValUpdates, v)
  207. return types.ResponseDeliverTx{Code: code.CodeTypeOK}
  208. }