hermez-node/api/batch.go
api/batch.goRaw
1package api
2
3import (
4 "database/sql"
5 "errors"
6 "net/http"
7
8 "github.com/gin-gonic/gin"
9 "github.com/hermeznetwork/hermez-node/common"
10 "github.com/hermeznetwork/hermez-node/db/historydb"
11)
12
13func (a *API) getBatches(c *gin.Context) {
14 // Get query parameters
15 // minBatchNum
16 minBatchNum, err := parseQueryUint("minBatchNum", nil, 0, maxUint32, c)
17 if err != nil {
18 retBadReq(err, c)
19 return
20 }
21 // maxBatchNum
22 maxBatchNum, err := parseQueryUint("maxBatchNum", nil, 0, maxUint32, c)
23 if err != nil {
24 retBadReq(err, c)
25 return
26 }
27 // slotNum
28 slotNum, err := parseQueryUint("slotNum", nil, 0, maxUint32, c)
29 if err != nil {
30 retBadReq(err, c)
31 return
32 }
33 // forgerAddr
34 forgerAddr, err := parseQueryEthAddr("forgerAddr", c)
35 if err != nil {
36 retBadReq(err, c)
37 return
38 }
39 // pagination
40 fromItem, order, limit, err := parsePagination(c)
41 if err != nil {
42 retBadReq(err, c)
43 return
44 }
45 // Fetch batches from historyDB
46 batches, pendingItems, err := a.h.GetBatchesAPI(
47 minBatchNum, maxBatchNum, slotNum, forgerAddr, fromItem, limit, order,
48 )
49 if err != nil {
50 retSQLErr(err, c)
51 return
52 }
53
54 // Build succesfull response
55 type batchesResponse struct {
56 Batches []historydb.BatchAPI `json:"batches"`
57 PendingItems uint64 `json:"pendingItems"`
58 }
59 c.JSON(http.StatusOK, &batchesResponse{
60 Batches: batches,
61 PendingItems: pendingItems,
62 })
63}
64
65func (a *API) getBatch(c *gin.Context) {
66 // Get batchNum
67 batchNum, err := parseParamUint("batchNum", nil, 0, maxUint32, c)
68 if err != nil {
69 retBadReq(err, c)
70 return
71 }
72 if batchNum == nil { // batchNum is required
73 retBadReq(errors.New("Invalid batchNum"), c)
74 return
75 }
76 // Fetch batch from historyDB
77 batch, err := a.h.GetBatchAPI(common.BatchNum(*batchNum))
78 if err != nil {
79 retSQLErr(err, c)
80 return
81 }
82 // JSON response
83 c.JSON(http.StatusOK, batch)
84}
85
86type fullBatch struct {
87 Batch *historydb.BatchAPI `json:"batch"`
88 Txs []historydb.TxAPI `json:"transactions"`
89}
90
91func (a *API) getFullBatch(c *gin.Context) {
92 // Get batchNum
93 batchNum, err := parseParamUint("batchNum", nil, 0, maxUint32, c)
94 if err != nil {
95 retBadReq(err, c)
96 return
97 }
98 if batchNum == nil {
99 retBadReq(errors.New("Invalid batchNum"), c)
100 return
101 }
102 // Fetch batch from historyDB
103 batch, err := a.h.GetBatchAPI(common.BatchNum(*batchNum))
104 if err != nil {
105 retSQLErr(err, c)
106 return
107 }
108 // Fetch txs forged in the batch from historyDB
109 maxTxsPerBatch := uint(2048) //nolint:gomnd
110 txs, _, err := a.h.GetHistoryTxs(
111 nil, nil, nil, nil, batchNum, nil, nil, &maxTxsPerBatch, historydb.OrderAsc,
112 )
113 if err != nil && err != sql.ErrNoRows {
114 retSQLErr(err, c)
115 return
116 }
117 // JSON response
118 c.JSON(http.StatusOK, fullBatch{
119 Batch: batch,
120 Txs: txs,
121 })
122}