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.1 KiB

9 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
9 years ago
  1. package counter
  2. import (
  3. "encoding/binary"
  4. "fmt"
  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.Sprintf("{\"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.Sprintf("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.Sprintf("Invalid nonce. Expected %v, got %v", app.txCount, txValue))
  34. }
  35. }
  36. app.txCount++
  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.Sprintf("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.Sprintf("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++
  55. if app.txCount == 0 {
  56. return types.OK
  57. }
  58. hash := make([]byte, 8)
  59. binary.BigEndian.PutUint64(hash, uint64(app.txCount))
  60. return types.NewResultOK(hash, "")
  61. }
  62. func (app *CounterApplication) Query(query []byte) types.Result {
  63. queryStr := string(query)
  64. switch queryStr {
  65. case "hash":
  66. return types.NewResultOK(nil, fmt.Sprintf("%v", app.hashCount))
  67. case "tx":
  68. return types.NewResultOK(nil, fmt.Sprintf("%v", app.txCount))
  69. }
  70. return types.ErrUnknownRequest.SetLog(fmt.Sprintf("Invalid nonce. Expected hash or tx, got %v", queryStr))
  71. }