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.

239 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(validators []*types.Validator) {
  86. for _, v := range 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(hash []byte, header *types.Header) {
  95. // update latest block info
  96. app.blockHeader = 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. if strings.HasPrefix(string(tx), ValidatorSetChangePrefix) {
  154. return true
  155. }
  156. return false
  157. }
  158. // format is "val:pubkey1/power1,addr2/power2,addr3/power3"tx
  159. func (app *PersistentDummyApplication) execValidatorTx(tx []byte) types.Result {
  160. tx = tx[len(ValidatorSetChangePrefix):]
  161. pubKeyAndPower := strings.Split(string(tx), "/")
  162. if len(pubKeyAndPower) != 2 {
  163. return types.ErrEncodingError.SetLog(cmn.Fmt("Expected 'pubkey/power'. Got %v", pubKeyAndPower))
  164. }
  165. pubkeyS, powerS := pubKeyAndPower[0], pubKeyAndPower[1]
  166. pubkey, err := hex.DecodeString(pubkeyS)
  167. if err != nil {
  168. return types.ErrEncodingError.SetLog(cmn.Fmt("Pubkey (%s) is invalid hex", pubkeyS))
  169. }
  170. power, err := strconv.Atoi(powerS)
  171. if err != nil {
  172. return types.ErrEncodingError.SetLog(cmn.Fmt("Power (%s) is not an int", powerS))
  173. }
  174. // update
  175. return app.updateValidator(&types.Validator{pubkey, uint64(power)})
  176. }
  177. // add, update, or remove a validator
  178. func (app *PersistentDummyApplication) updateValidator(v *types.Validator) types.Result {
  179. key := []byte("val:" + string(v.PubKey))
  180. if v.Power == 0 {
  181. // remove validator
  182. if !app.app.state.Has(key) {
  183. return types.ErrUnauthorized.SetLog(cmn.Fmt("Cannot remove non-existent validator %X", key))
  184. }
  185. app.app.state.Remove(key)
  186. } else {
  187. // add or update validator
  188. value := bytes.NewBuffer(make([]byte, 0))
  189. if err := types.WriteMessage(v, value); err != nil {
  190. return types.ErrInternalError.SetLog(cmn.Fmt("Error encoding validator: %v", err))
  191. }
  192. app.app.state.Set(key, value.Bytes())
  193. }
  194. // we only update the changes array if we succesfully updated the tree
  195. app.changes = append(app.changes, v)
  196. return types.OK
  197. }