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.

236 lines
6.4 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
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. "strconv"
  6. "strings"
  7. "github.com/pkg/errors"
  8. "github.com/tendermint/abci/types"
  9. wire "github.com/tendermint/go-wire"
  10. "github.com/tendermint/merkleeyes/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. type PersistentDummyApplication struct {
  20. app *DummyApplication
  21. db dbm.DB
  22. // latest received
  23. // TODO: move to merkle tree?
  24. blockHeader *types.Header
  25. // validator set
  26. changes []*types.Validator
  27. logger log.Logger
  28. }
  29. func NewPersistentDummyApplication(dbDir string) *PersistentDummyApplication {
  30. db := dbm.NewDB("dummy", "leveldb", dbDir)
  31. lastBlock := LoadLastBlock(db)
  32. stateTree := iavl.NewIAVLTree(0, db)
  33. stateTree.Load(lastBlock.AppHash)
  34. // log.Notice("Loaded state", "block", lastBlock.Height, "root", stateTree.Hash())
  35. return &PersistentDummyApplication{
  36. app: &DummyApplication{state: stateTree},
  37. db: db,
  38. logger: log.NewNopLogger(),
  39. }
  40. }
  41. func (app *PersistentDummyApplication) SetLogger(l log.Logger) {
  42. app.logger = l
  43. }
  44. func (app *PersistentDummyApplication) Info() (resInfo types.ResponseInfo) {
  45. resInfo = app.app.Info()
  46. lastBlock := LoadLastBlock(app.db)
  47. resInfo.LastBlockHeight = lastBlock.Height
  48. resInfo.LastBlockAppHash = lastBlock.AppHash
  49. return resInfo
  50. }
  51. func (app *PersistentDummyApplication) SetOption(key string, value string) (log string) {
  52. return app.app.SetOption(key, value)
  53. }
  54. // tx is either "key=value" or just arbitrary bytes
  55. func (app *PersistentDummyApplication) DeliverTx(tx []byte) types.Result {
  56. // if it starts with "val:", update the validator set
  57. // format is "val:pubkey/power"
  58. if isValidatorTx(tx) {
  59. // update validators in the merkle tree
  60. // and in app.changes
  61. return app.execValidatorTx(tx)
  62. }
  63. // otherwise, update the key-value store
  64. return app.app.DeliverTx(tx)
  65. }
  66. func (app *PersistentDummyApplication) CheckTx(tx []byte) types.Result {
  67. return app.app.CheckTx(tx)
  68. }
  69. func (app *PersistentDummyApplication) Commit() types.Result {
  70. // Save
  71. appHash := app.app.state.Save()
  72. app.logger.Info("Saved state", "root", appHash)
  73. lastBlock := LastBlockInfo{
  74. Height: app.blockHeader.Height,
  75. AppHash: appHash, // this hash will be in the next block header
  76. }
  77. app.logger.Info("Saving block", "height", lastBlock.Height, "root", lastBlock.AppHash)
  78. SaveLastBlock(app.db, lastBlock)
  79. return types.NewResultOK(appHash, "")
  80. }
  81. func (app *PersistentDummyApplication) Query(reqQuery types.RequestQuery) types.ResponseQuery {
  82. return app.app.Query(reqQuery)
  83. }
  84. // Save the validators in the merkle tree
  85. func (app *PersistentDummyApplication) InitChain(params types.RequestInitChain) {
  86. for _, v := range params.Validators {
  87. r := app.updateValidator(v)
  88. if r.IsErr() {
  89. app.logger.Error("Error updating validators", "r", r)
  90. }
  91. }
  92. }
  93. // Track the block hash and header information
  94. func (app *PersistentDummyApplication) BeginBlock(params types.RequestBeginBlock) {
  95. // update latest block info
  96. app.blockHeader = params.Header
  97. // reset valset changes
  98. app.changes = make([]*types.Validator, 0)
  99. }
  100. // Update the validator set
  101. func (app *PersistentDummyApplication) EndBlock(height uint64) (resEndBlock types.ResponseEndBlock) {
  102. return types.ResponseEndBlock{Diffs: app.changes}
  103. }
  104. //-----------------------------------------
  105. // persist the last block info
  106. var lastBlockKey = []byte("lastblock")
  107. type LastBlockInfo struct {
  108. Height uint64
  109. AppHash []byte
  110. }
  111. // Get the last block from the db
  112. func LoadLastBlock(db dbm.DB) (lastBlock LastBlockInfo) {
  113. buf := db.Get(lastBlockKey)
  114. if len(buf) != 0 {
  115. r, n, err := bytes.NewReader(buf), new(int), new(error)
  116. wire.ReadBinaryPtr(&lastBlock, r, 0, n, err)
  117. if *err != nil {
  118. cmn.PanicCrisis(errors.Wrap(*err, "cannot load last block (data has been corrupted or its spec has changed)"))
  119. }
  120. // TODO: ensure that buf is completely read.
  121. }
  122. return lastBlock
  123. }
  124. func SaveLastBlock(db dbm.DB, lastBlock LastBlockInfo) {
  125. buf, n, err := new(bytes.Buffer), new(int), new(error)
  126. wire.WriteBinary(lastBlock, buf, n, err)
  127. if *err != nil {
  128. // TODO
  129. cmn.PanicCrisis(errors.Wrap(*err, "cannot save last block"))
  130. }
  131. db.Set(lastBlockKey, buf.Bytes())
  132. }
  133. //---------------------------------------------
  134. // update validators
  135. func (app *PersistentDummyApplication) Validators() (validators []*types.Validator) {
  136. app.app.state.Iterate(func(key, value []byte) bool {
  137. if isValidatorTx(key) {
  138. validator := new(types.Validator)
  139. err := types.ReadMessage(bytes.NewBuffer(value), validator)
  140. if err != nil {
  141. panic(err)
  142. }
  143. validators = append(validators, validator)
  144. }
  145. return false
  146. })
  147. return
  148. }
  149. func MakeValSetChangeTx(pubkey []byte, power uint64) []byte {
  150. return []byte(cmn.Fmt("val:%X/%d", pubkey, power))
  151. }
  152. func isValidatorTx(tx []byte) bool {
  153. return strings.HasPrefix(string(tx), ValidatorSetChangePrefix)
  154. }
  155. // format is "val:pubkey1/power1,addr2/power2,addr3/power3"tx
  156. func (app *PersistentDummyApplication) execValidatorTx(tx []byte) types.Result {
  157. tx = tx[len(ValidatorSetChangePrefix):]
  158. pubKeyAndPower := strings.Split(string(tx), "/")
  159. if len(pubKeyAndPower) != 2 {
  160. return types.ErrEncodingError.SetLog(cmn.Fmt("Expected 'pubkey/power'. Got %v", pubKeyAndPower))
  161. }
  162. pubkeyS, powerS := pubKeyAndPower[0], pubKeyAndPower[1]
  163. pubkey, err := hex.DecodeString(pubkeyS)
  164. if err != nil {
  165. return types.ErrEncodingError.SetLog(cmn.Fmt("Pubkey (%s) is invalid hex", pubkeyS))
  166. }
  167. power, err := strconv.Atoi(powerS)
  168. if err != nil {
  169. return types.ErrEncodingError.SetLog(cmn.Fmt("Power (%s) is not an int", powerS))
  170. }
  171. // update
  172. return app.updateValidator(&types.Validator{pubkey, uint64(power)})
  173. }
  174. // add, update, or remove a validator
  175. func (app *PersistentDummyApplication) updateValidator(v *types.Validator) types.Result {
  176. key := []byte("val:" + string(v.PubKey))
  177. if v.Power == 0 {
  178. // remove validator
  179. if !app.app.state.Has(key) {
  180. return types.ErrUnauthorized.SetLog(cmn.Fmt("Cannot remove non-existent validator %X", key))
  181. }
  182. app.app.state.Remove(key)
  183. } else {
  184. // add or update validator
  185. value := bytes.NewBuffer(make([]byte, 0))
  186. if err := types.WriteMessage(v, value); err != nil {
  187. return types.ErrInternalError.SetLog(cmn.Fmt("Error encoding validator: %v", err))
  188. }
  189. app.app.state.Set(key, value.Bytes())
  190. }
  191. // we only update the changes array if we successfully updated the tree
  192. app.changes = append(app.changes, v)
  193. return types.OK
  194. }