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.

85 lines
2.1 KiB

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