github.com/badrootd/celestia-core@v0.0.0-20240305091328-aa4207a4b25d/abci/example/counter/counter.go (about) 1 package counter 2 3 import ( 4 "encoding/binary" 5 "fmt" 6 7 "github.com/badrootd/celestia-core/abci/example/code" 8 "github.com/badrootd/celestia-core/abci/types" 9 ) 10 11 type Application struct { 12 types.BaseApplication 13 14 hashCount int 15 txCount int 16 serial bool 17 } 18 19 func NewApplication(serial bool) *Application { 20 return &Application{serial: serial} 21 } 22 23 func (app *Application) Info(req types.RequestInfo) types.ResponseInfo { 24 return types.ResponseInfo{Data: fmt.Sprintf("{\"hashes\":%v,\"txs\":%v}", app.hashCount, app.txCount)} 25 } 26 27 func (app *Application) DeliverTx(req types.RequestDeliverTx) types.ResponseDeliverTx { 28 if app.serial { 29 if len(req.Tx) > 8 { 30 return types.ResponseDeliverTx{ 31 Code: code.CodeTypeEncodingError, 32 Log: fmt.Sprintf("Max tx size is 8 bytes, got %d", len(req.Tx))} 33 } 34 tx8 := make([]byte, 8) 35 copy(tx8[len(tx8)-len(req.Tx):], req.Tx) 36 txValue := binary.BigEndian.Uint64(tx8) 37 if txValue != uint64(app.txCount) { 38 return types.ResponseDeliverTx{ 39 Code: code.CodeTypeBadNonce, 40 Log: fmt.Sprintf("Invalid nonce. Expected %v, got %v", app.txCount, txValue)} 41 } 42 } 43 app.txCount++ 44 return types.ResponseDeliverTx{Code: code.CodeTypeOK} 45 } 46 47 func (app *Application) CheckTx(req types.RequestCheckTx) types.ResponseCheckTx { 48 if app.serial { 49 if len(req.Tx) > 8 { 50 return types.ResponseCheckTx{ 51 Code: code.CodeTypeEncodingError, 52 Log: fmt.Sprintf("Max tx size is 8 bytes, got %d", len(req.Tx))} 53 } 54 tx8 := make([]byte, 8) 55 copy(tx8[len(tx8)-len(req.Tx):], req.Tx) 56 txValue := binary.BigEndian.Uint64(tx8) 57 if txValue < uint64(app.txCount) { 58 return types.ResponseCheckTx{ 59 Code: code.CodeTypeBadNonce, 60 Log: fmt.Sprintf("Invalid nonce. Expected >= %v, got %v", app.txCount, txValue)} 61 } 62 } 63 return types.ResponseCheckTx{Code: code.CodeTypeOK} 64 } 65 66 func (app *Application) Commit() (resp types.ResponseCommit) { 67 app.hashCount++ 68 if app.txCount == 0 { 69 return types.ResponseCommit{} 70 } 71 hash := make([]byte, 8) 72 binary.BigEndian.PutUint64(hash, uint64(app.txCount)) 73 return types.ResponseCommit{Data: hash} 74 } 75 76 func (app *Application) Query(reqQuery types.RequestQuery) types.ResponseQuery { 77 switch reqQuery.Path { 78 case "hash": 79 return types.ResponseQuery{Value: []byte(fmt.Sprintf("%v", app.hashCount))} 80 case "tx": 81 return types.ResponseQuery{Value: []byte(fmt.Sprintf("%v", app.txCount))} 82 default: 83 return types.ResponseQuery{Log: fmt.Sprintf("Invalid query path. Expected hash or tx, got %v", reqQuery.Path)} 84 } 85 }