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.

355 lines
10 KiB

cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 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
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 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
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
7 years ago
7 years ago
7 years ago
7 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 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. dbm "github.com/tendermint/tm-db"
  9. "github.com/tendermint/tendermint/abci/example/code"
  10. "github.com/tendermint/tendermint/abci/types"
  11. "github.com/tendermint/tendermint/crypto/encoding"
  12. "github.com/tendermint/tendermint/libs/log"
  13. cryptoproto "github.com/tendermint/tendermint/proto/tendermint/crypto"
  14. ptypes "github.com/tendermint/tendermint/proto/tendermint/types"
  15. )
  16. const (
  17. ValidatorSetChangePrefix string = "val:"
  18. )
  19. //-----------------------------------------
  20. var _ types.Application = (*PersistentKVStoreApplication)(nil)
  21. type PersistentKVStoreApplication struct {
  22. app *Application
  23. // validator set
  24. ValUpdates []types.ValidatorUpdate
  25. valAddrToPubKeyMap map[string]cryptoproto.PublicKey
  26. logger log.Logger
  27. }
  28. func NewPersistentKVStoreApplication(logger log.Logger, dbDir string) *PersistentKVStoreApplication {
  29. name := "kvstore"
  30. db, err := dbm.NewGoLevelDB(name, dbDir)
  31. if err != nil {
  32. panic(err)
  33. }
  34. state := loadState(db)
  35. return &PersistentKVStoreApplication{
  36. app: &Application{state: state},
  37. valAddrToPubKeyMap: make(map[string]cryptoproto.PublicKey),
  38. logger: logger,
  39. }
  40. }
  41. func (app *PersistentKVStoreApplication) Close() error {
  42. return app.app.state.db.Close()
  43. }
  44. func (app *PersistentKVStoreApplication) Info(req types.RequestInfo) types.ResponseInfo {
  45. res := app.app.Info(req)
  46. res.LastBlockHeight = app.app.state.Height
  47. res.LastBlockAppHash = app.app.state.AppHash
  48. return res
  49. }
  50. // tx is either "val:pubkey!power" or "key=value" or just arbitrary bytes
  51. func (app *PersistentKVStoreApplication) DeliverTx(req types.RequestDeliverTx) types.ResponseDeliverTx {
  52. // if it starts with "val:", update the validator set
  53. // format is "val:pubkey!power"
  54. if isValidatorTx(req.Tx) {
  55. // update validators in the merkle tree
  56. // and in app.ValUpdates
  57. return app.execValidatorTx(req.Tx)
  58. }
  59. if isPrepareTx(req.Tx) {
  60. return app.execPrepareTx(req.Tx)
  61. }
  62. // otherwise, update the key-value store
  63. return app.app.DeliverTx(req)
  64. }
  65. func (app *PersistentKVStoreApplication) CheckTx(req types.RequestCheckTx) types.ResponseCheckTx {
  66. return app.app.CheckTx(req)
  67. }
  68. // Commit will panic if InitChain was not called
  69. func (app *PersistentKVStoreApplication) Commit() types.ResponseCommit {
  70. return app.app.Commit()
  71. }
  72. // When path=/val and data={validator address}, returns the validator update (types.ValidatorUpdate) varint encoded.
  73. // For any other path, returns an associated value or nil if missing.
  74. func (app *PersistentKVStoreApplication) Query(reqQuery types.RequestQuery) (resQuery types.ResponseQuery) {
  75. switch reqQuery.Path {
  76. case "/val":
  77. key := []byte("val:" + string(reqQuery.Data))
  78. value, err := app.app.state.db.Get(key)
  79. if err != nil {
  80. panic(err)
  81. }
  82. resQuery.Key = reqQuery.Data
  83. resQuery.Value = value
  84. return
  85. default:
  86. return app.app.Query(reqQuery)
  87. }
  88. }
  89. // Save the validators in the merkle tree
  90. func (app *PersistentKVStoreApplication) InitChain(req types.RequestInitChain) types.ResponseInitChain {
  91. for _, v := range req.Validators {
  92. r := app.updateValidator(v)
  93. if r.IsErr() {
  94. app.logger.Error("error updating validators", "r", r)
  95. }
  96. }
  97. return types.ResponseInitChain{}
  98. }
  99. // Track the block hash and header information
  100. func (app *PersistentKVStoreApplication) BeginBlock(req types.RequestBeginBlock) types.ResponseBeginBlock {
  101. // reset valset changes
  102. app.ValUpdates = make([]types.ValidatorUpdate, 0)
  103. // Punish validators who committed equivocation.
  104. for _, ev := range req.ByzantineValidators {
  105. if ev.Type == types.EvidenceType_DUPLICATE_VOTE {
  106. addr := string(ev.Validator.Address)
  107. if pubKey, ok := app.valAddrToPubKeyMap[addr]; ok {
  108. app.updateValidator(types.ValidatorUpdate{
  109. PubKey: pubKey,
  110. Power: ev.Validator.Power - 1,
  111. })
  112. app.logger.Info("Decreased val power by 1 because of the equivocation",
  113. "val", addr)
  114. } else {
  115. app.logger.Error("Wanted to punish val, but can't find it",
  116. "val", addr)
  117. }
  118. }
  119. }
  120. return types.ResponseBeginBlock{}
  121. }
  122. // Update the validator set
  123. func (app *PersistentKVStoreApplication) EndBlock(req types.RequestEndBlock) types.ResponseEndBlock {
  124. return types.ResponseEndBlock{ValidatorUpdates: app.ValUpdates}
  125. }
  126. func (app *PersistentKVStoreApplication) ListSnapshots(
  127. req types.RequestListSnapshots) types.ResponseListSnapshots {
  128. return types.ResponseListSnapshots{}
  129. }
  130. func (app *PersistentKVStoreApplication) LoadSnapshotChunk(
  131. req types.RequestLoadSnapshotChunk) types.ResponseLoadSnapshotChunk {
  132. return types.ResponseLoadSnapshotChunk{}
  133. }
  134. func (app *PersistentKVStoreApplication) OfferSnapshot(
  135. req types.RequestOfferSnapshot) types.ResponseOfferSnapshot {
  136. return types.ResponseOfferSnapshot{Result: types.ResponseOfferSnapshot_ABORT}
  137. }
  138. func (app *PersistentKVStoreApplication) ApplySnapshotChunk(
  139. req types.RequestApplySnapshotChunk) types.ResponseApplySnapshotChunk {
  140. return types.ResponseApplySnapshotChunk{Result: types.ResponseApplySnapshotChunk_ABORT}
  141. }
  142. func (app *PersistentKVStoreApplication) ExtendVote(
  143. req types.RequestExtendVote) types.ResponseExtendVote {
  144. return types.ResponseExtendVote{
  145. VoteExtension: ConstructVoteExtension(req.Vote.ValidatorAddress),
  146. }
  147. }
  148. func (app *PersistentKVStoreApplication) VerifyVoteExtension(
  149. req types.RequestVerifyVoteExtension) types.ResponseVerifyVoteExtension {
  150. return types.RespondVerifyVoteExtension(
  151. app.verifyExtension(req.Vote.ValidatorAddress, req.Vote.VoteExtension))
  152. }
  153. func (app *PersistentKVStoreApplication) PrepareProposal(
  154. req types.RequestPrepareProposal) types.ResponsePrepareProposal {
  155. return types.ResponsePrepareProposal{BlockData: app.substPrepareTx(req.BlockData)}
  156. }
  157. //---------------------------------------------
  158. // update validators
  159. func (app *PersistentKVStoreApplication) Validators() (validators []types.ValidatorUpdate) {
  160. itr, err := app.app.state.db.Iterator(nil, nil)
  161. if err != nil {
  162. panic(err)
  163. }
  164. for ; itr.Valid(); itr.Next() {
  165. if isValidatorTx(itr.Key()) {
  166. validator := new(types.ValidatorUpdate)
  167. err := types.ReadMessage(bytes.NewBuffer(itr.Value()), validator)
  168. if err != nil {
  169. panic(err)
  170. }
  171. validators = append(validators, *validator)
  172. }
  173. }
  174. if err = itr.Error(); err != nil {
  175. panic(err)
  176. }
  177. return
  178. }
  179. func MakeValSetChangeTx(pubkey cryptoproto.PublicKey, power int64) []byte {
  180. pk, err := encoding.PubKeyFromProto(pubkey)
  181. if err != nil {
  182. panic(err)
  183. }
  184. pubStr := base64.StdEncoding.EncodeToString(pk.Bytes())
  185. return []byte(fmt.Sprintf("val:%s!%d", pubStr, power))
  186. }
  187. func isValidatorTx(tx []byte) bool {
  188. return strings.HasPrefix(string(tx), ValidatorSetChangePrefix)
  189. }
  190. // format is "val:pubkey!power"
  191. // pubkey is a base64-encoded 32-byte ed25519 key
  192. func (app *PersistentKVStoreApplication) execValidatorTx(tx []byte) types.ResponseDeliverTx {
  193. tx = tx[len(ValidatorSetChangePrefix):]
  194. // get the pubkey and power
  195. pubKeyAndPower := strings.Split(string(tx), "!")
  196. if len(pubKeyAndPower) != 2 {
  197. return types.ResponseDeliverTx{
  198. Code: code.CodeTypeEncodingError,
  199. Log: fmt.Sprintf("Expected 'pubkey!power'. Got %v", pubKeyAndPower)}
  200. }
  201. pubkeyS, powerS := pubKeyAndPower[0], pubKeyAndPower[1]
  202. // decode the pubkey
  203. pubkey, err := base64.StdEncoding.DecodeString(pubkeyS)
  204. if err != nil {
  205. return types.ResponseDeliverTx{
  206. Code: code.CodeTypeEncodingError,
  207. Log: fmt.Sprintf("Pubkey (%s) is invalid base64", pubkeyS)}
  208. }
  209. // decode the power
  210. power, err := strconv.ParseInt(powerS, 10, 64)
  211. if err != nil {
  212. return types.ResponseDeliverTx{
  213. Code: code.CodeTypeEncodingError,
  214. Log: fmt.Sprintf("Power (%s) is not an int", powerS)}
  215. }
  216. // update
  217. return app.updateValidator(types.UpdateValidator(pubkey, power, ""))
  218. }
  219. // add, update, or remove a validator
  220. func (app *PersistentKVStoreApplication) updateValidator(v types.ValidatorUpdate) types.ResponseDeliverTx {
  221. pubkey, err := encoding.PubKeyFromProto(v.PubKey)
  222. if err != nil {
  223. panic(fmt.Errorf("can't decode public key: %w", err))
  224. }
  225. key := []byte("val:" + string(pubkey.Bytes()))
  226. if v.Power == 0 {
  227. // remove validator
  228. hasKey, err := app.app.state.db.Has(key)
  229. if err != nil {
  230. panic(err)
  231. }
  232. if !hasKey {
  233. pubStr := base64.StdEncoding.EncodeToString(pubkey.Bytes())
  234. return types.ResponseDeliverTx{
  235. Code: code.CodeTypeUnauthorized,
  236. Log: fmt.Sprintf("Cannot remove non-existent validator %s", pubStr)}
  237. }
  238. if err = app.app.state.db.Delete(key); err != nil {
  239. panic(err)
  240. }
  241. delete(app.valAddrToPubKeyMap, string(pubkey.Address()))
  242. } else {
  243. // add or update validator
  244. value := bytes.NewBuffer(make([]byte, 0))
  245. if err := types.WriteMessage(&v, value); err != nil {
  246. return types.ResponseDeliverTx{
  247. Code: code.CodeTypeEncodingError,
  248. Log: fmt.Sprintf("error encoding validator: %v", err)}
  249. }
  250. if err = app.app.state.db.Set(key, value.Bytes()); err != nil {
  251. panic(err)
  252. }
  253. app.valAddrToPubKeyMap[string(pubkey.Address())] = v.PubKey
  254. }
  255. // we only update the changes array if we successfully updated the tree
  256. app.ValUpdates = append(app.ValUpdates, v)
  257. return types.ResponseDeliverTx{Code: code.CodeTypeOK}
  258. }
  259. // -----------------------------
  260. const PreparePrefix = "prepare"
  261. func isPrepareTx(tx []byte) bool {
  262. return strings.HasPrefix(string(tx), PreparePrefix)
  263. }
  264. // execPrepareTx is noop. tx data is considered as placeholder
  265. // and is substitute at the PrepareProposal.
  266. func (app *PersistentKVStoreApplication) execPrepareTx(tx []byte) types.ResponseDeliverTx {
  267. // noop
  268. return types.ResponseDeliverTx{}
  269. }
  270. // substPrepareTx subst all the preparetx in the blockdata
  271. // to null string(could be any arbitrary string).
  272. func (app *PersistentKVStoreApplication) substPrepareTx(blockData [][]byte) [][]byte {
  273. // TODO: this mechanism will change with the current spec of PrepareProposal
  274. // We now have a special type for marking a tx as changed
  275. for i, tx := range blockData {
  276. if isPrepareTx(tx) {
  277. blockData[i] = make([]byte, len(tx))
  278. }
  279. }
  280. return blockData
  281. }
  282. func ConstructVoteExtension(valAddr []byte) *ptypes.VoteExtension {
  283. return &ptypes.VoteExtension{
  284. AppDataToSign: valAddr,
  285. AppDataSelfAuthenticating: valAddr,
  286. }
  287. }
  288. func (app *PersistentKVStoreApplication) verifyExtension(valAddr []byte, ext *ptypes.VoteExtension) bool {
  289. if ext == nil {
  290. return false
  291. }
  292. canonical := ConstructVoteExtension(valAddr)
  293. if !bytes.Equal(canonical.AppDataToSign, ext.AppDataToSign) {
  294. return false
  295. }
  296. if !bytes.Equal(canonical.AppDataSelfAuthenticating, ext.AppDataSelfAuthenticating) {
  297. return false
  298. }
  299. return true
  300. }