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.

83 lines
2.2 KiB

9 years ago
8 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. package counter
  2. import (
  3. "encoding/binary"
  4. "github.com/tendermint/abci/types"
  5. cmn "github.com/tendermint/tmlibs/common"
  6. )
  7. type CounterApplication struct {
  8. types.BaseApplication
  9. hashCount int
  10. txCount int
  11. serial bool
  12. }
  13. func NewCounterApplication(serial bool) *CounterApplication {
  14. return &CounterApplication{serial: serial}
  15. }
  16. func (app *CounterApplication) Info(req types.RequestInfo) types.ResponseInfo {
  17. return types.ResponseInfo{Data: cmn.Fmt("{\"hashes\":%v,\"txs\":%v}", app.hashCount, app.txCount)}
  18. }
  19. func (app *CounterApplication) SetOption(key string, value string) (log string) {
  20. if key == "serial" && value == "on" {
  21. app.serial = true
  22. }
  23. return ""
  24. }
  25. func (app *CounterApplication) DeliverTx(tx []byte) types.Result {
  26. if app.serial {
  27. if len(tx) > 8 {
  28. return types.ErrEncodingError.SetLog(cmn.Fmt("Max tx size is 8 bytes, got %d", len(tx)))
  29. }
  30. tx8 := make([]byte, 8)
  31. copy(tx8[len(tx8)-len(tx):], tx)
  32. txValue := binary.BigEndian.Uint64(tx8)
  33. if txValue != uint64(app.txCount) {
  34. return types.ErrBadNonce.SetLog(cmn.Fmt("Invalid nonce. Expected %v, got %v", app.txCount, txValue))
  35. }
  36. }
  37. app.txCount++
  38. return types.OK
  39. }
  40. func (app *CounterApplication) CheckTx(tx []byte) types.Result {
  41. if app.serial {
  42. if len(tx) > 8 {
  43. return types.ErrEncodingError.SetLog(cmn.Fmt("Max tx size is 8 bytes, got %d", len(tx)))
  44. }
  45. tx8 := make([]byte, 8)
  46. copy(tx8[len(tx8)-len(tx):], tx)
  47. txValue := binary.BigEndian.Uint64(tx8)
  48. if txValue < uint64(app.txCount) {
  49. return types.ErrBadNonce.SetLog(cmn.Fmt("Invalid nonce. Expected >= %v, got %v", app.txCount, txValue))
  50. }
  51. }
  52. return types.OK
  53. }
  54. func (app *CounterApplication) Commit() types.Result {
  55. app.hashCount++
  56. if app.txCount == 0 {
  57. return types.OK
  58. }
  59. hash := make([]byte, 8)
  60. binary.BigEndian.PutUint64(hash, uint64(app.txCount))
  61. return types.NewResultOK(hash, "")
  62. }
  63. func (app *CounterApplication) Query(reqQuery types.RequestQuery) types.ResponseQuery {
  64. switch reqQuery.Path {
  65. case "hash":
  66. return types.ResponseQuery{Value: []byte(cmn.Fmt("%v", app.hashCount))}
  67. case "tx":
  68. return types.ResponseQuery{Value: []byte(cmn.Fmt("%v", app.txCount))}
  69. default:
  70. return types.ResponseQuery{Log: cmn.Fmt("Invalid query path. Expected hash or tx, got %v", reqQuery.Path)}
  71. }
  72. }