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.

222 lines
6.2 KiB

7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. package dummy
  2. import (
  3. "bytes"
  4. "encoding/hex"
  5. "fmt"
  6. "strconv"
  7. "strings"
  8. "github.com/tendermint/abci/example/code"
  9. "github.com/tendermint/abci/types"
  10. crypto "github.com/tendermint/go-crypto"
  11. "github.com/tendermint/iavl"
  12. cmn "github.com/tendermint/tmlibs/common"
  13. dbm "github.com/tendermint/tmlibs/db"
  14. "github.com/tendermint/tmlibs/log"
  15. )
  16. const (
  17. ValidatorSetChangePrefix string = "val:"
  18. )
  19. //-----------------------------------------
  20. var _ types.Application = (*PersistentDummyApplication)(nil)
  21. type PersistentDummyApplication struct {
  22. app *DummyApplication
  23. // validator set
  24. ValUpdates []*types.Validator
  25. logger log.Logger
  26. }
  27. func NewPersistentDummyApplication(dbDir string) *PersistentDummyApplication {
  28. name := "dummy"
  29. db, err := dbm.NewGoLevelDB(name, dbDir)
  30. if err != nil {
  31. panic(err)
  32. }
  33. stateTree := iavl.NewVersionedTree(500, db)
  34. stateTree.Load()
  35. return &PersistentDummyApplication{
  36. app: &DummyApplication{state: stateTree},
  37. logger: log.NewNopLogger(),
  38. }
  39. }
  40. func (app *PersistentDummyApplication) SetLogger(l log.Logger) {
  41. app.logger = l
  42. }
  43. func (app *PersistentDummyApplication) Info(req types.RequestInfo) types.ResponseInfo {
  44. res := app.app.Info(req)
  45. var latestVersion uint64 = app.app.state.LatestVersion() // TODO: change to int64
  46. res.LastBlockHeight = int64(latestVersion)
  47. res.LastBlockAppHash = app.app.state.Hash()
  48. return res
  49. }
  50. func (app *PersistentDummyApplication) SetOption(req types.RequestSetOption) types.ResponseSetOption {
  51. return app.app.SetOption(req)
  52. }
  53. // tx is either "val:pubkey/power" or "key=value" or just arbitrary bytes
  54. func (app *PersistentDummyApplication) DeliverTx(tx []byte) types.ResponseDeliverTx {
  55. // if it starts with "val:", update the validator set
  56. // format is "val:pubkey/power"
  57. if isValidatorTx(tx) {
  58. // update validators in the merkle tree
  59. // and in app.ValUpdates
  60. return app.execValidatorTx(tx)
  61. }
  62. // otherwise, update the key-value store
  63. return app.app.DeliverTx(tx)
  64. }
  65. func (app *PersistentDummyApplication) CheckTx(tx []byte) types.ResponseCheckTx {
  66. return app.app.CheckTx(tx)
  67. }
  68. // Commit will panic if InitChain was not called
  69. func (app *PersistentDummyApplication) Commit() types.ResponseCommit {
  70. // Save a new version for next height
  71. height := app.app.state.LatestVersion() + 1
  72. var appHash []byte
  73. var err error
  74. appHash, err = app.app.state.SaveVersion(height)
  75. if err != nil {
  76. // if this wasn't a dummy app, we'd do something smarter
  77. panic(err)
  78. }
  79. app.logger.Info("Commit block", "height", height, "root", appHash)
  80. return types.ResponseCommit{Code: code.CodeTypeOK, Data: appHash}
  81. }
  82. func (app *PersistentDummyApplication) Query(reqQuery types.RequestQuery) types.ResponseQuery {
  83. return app.app.Query(reqQuery)
  84. }
  85. // Save the validators in the merkle tree
  86. func (app *PersistentDummyApplication) 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 *PersistentDummyApplication) BeginBlock(req types.RequestBeginBlock) types.ResponseBeginBlock {
  97. // reset valset changes
  98. app.ValUpdates = make([]*types.Validator, 0)
  99. return types.ResponseBeginBlock{}
  100. }
  101. // Update the validator set
  102. func (app *PersistentDummyApplication) EndBlock(req types.RequestEndBlock) types.ResponseEndBlock {
  103. return types.ResponseEndBlock{ValidatorUpdates: app.ValUpdates}
  104. }
  105. //---------------------------------------------
  106. // update validators
  107. func (app *PersistentDummyApplication) Validators() (validators []*types.Validator) {
  108. app.app.state.Iterate(func(key, value []byte) bool {
  109. if isValidatorTx(key) {
  110. validator := new(types.Validator)
  111. err := types.ReadMessage(bytes.NewBuffer(value), validator)
  112. if err != nil {
  113. panic(err)
  114. }
  115. validators = append(validators, validator)
  116. }
  117. return false
  118. })
  119. return
  120. }
  121. func MakeValSetChangeTx(pubkey []byte, power int64) []byte {
  122. return []byte(cmn.Fmt("val:%X/%d", pubkey, power))
  123. }
  124. func isValidatorTx(tx []byte) bool {
  125. return strings.HasPrefix(string(tx), ValidatorSetChangePrefix)
  126. }
  127. // format is "val:pubkey1/power1,addr2/power2,addr3/power3"tx
  128. func (app *PersistentDummyApplication) execValidatorTx(tx []byte) types.ResponseDeliverTx {
  129. tx = tx[len(ValidatorSetChangePrefix):]
  130. //get the pubkey and power
  131. pubKeyAndPower := strings.Split(string(tx), "/")
  132. if len(pubKeyAndPower) != 2 {
  133. return types.ResponseDeliverTx{
  134. Code: code.CodeTypeEncodingError,
  135. Log: fmt.Sprintf("Expected 'pubkey/power'. Got %v", pubKeyAndPower)}
  136. }
  137. pubkeyS, powerS := pubKeyAndPower[0], pubKeyAndPower[1]
  138. // decode the pubkey, ensuring its go-crypto encoded
  139. pubkey, err := hex.DecodeString(pubkeyS)
  140. if err != nil {
  141. return types.ResponseDeliverTx{
  142. Code: code.CodeTypeEncodingError,
  143. Log: fmt.Sprintf("Pubkey (%s) is invalid hex", pubkeyS)}
  144. }
  145. _, err = crypto.PubKeyFromBytes(pubkey)
  146. if err != nil {
  147. return types.ResponseDeliverTx{
  148. Code: code.CodeTypeEncodingError,
  149. Log: fmt.Sprintf("Pubkey (%X) is invalid go-crypto encoded", pubkey)}
  150. }
  151. // decode the power
  152. power, err := strconv.ParseInt(powerS, 10, 64)
  153. if err != nil {
  154. return types.ResponseDeliverTx{
  155. Code: code.CodeTypeEncodingError,
  156. Log: fmt.Sprintf("Power (%s) is not an int", powerS)}
  157. }
  158. // update
  159. return app.updateValidator(&types.Validator{pubkey, power})
  160. }
  161. // add, update, or remove a validator
  162. func (app *PersistentDummyApplication) updateValidator(v *types.Validator) types.ResponseDeliverTx {
  163. key := []byte("val:" + string(v.PubKey))
  164. if v.Power == 0 {
  165. // remove validator
  166. if !app.app.state.Has(key) {
  167. return types.ResponseDeliverTx{
  168. Code: code.CodeTypeUnauthorized,
  169. Log: fmt.Sprintf("Cannot remove non-existent validator %X", key)}
  170. }
  171. app.app.state.Remove(key)
  172. } else {
  173. // add or update validator
  174. value := bytes.NewBuffer(make([]byte, 0))
  175. if err := types.WriteMessage(v, value); err != nil {
  176. return types.ResponseDeliverTx{
  177. Code: code.CodeTypeEncodingError,
  178. Log: fmt.Sprintf("Error encoding validator: %v", err)}
  179. }
  180. app.app.state.Set(key, value.Bytes())
  181. }
  182. // we only update the changes array if we successfully updated the tree
  183. app.ValUpdates = append(app.ValUpdates, v)
  184. return types.ResponseDeliverTx{Code: code.CodeTypeOK}
  185. }