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.

220 lines
6.1 KiB

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