Compare commits

..

3 Commits

Author SHA1 Message Date
arnaubennassar
714530e164 Fix mock server 2021-03-29 10:48:50 +02:00
arnaubennassar
378ba669b6 Merge branch 'master' of github.com:hermeznetwork/hermez-node 2021-03-24 09:08:02 +01:00
arnaubennassar
3865c0a9eb Fix mock server 2021-03-23 17:04:54 +01:00
16 changed files with 57 additions and 347 deletions

3
.gitignore vendored
View File

@@ -1,2 +1 @@
bin/ bin/
dist/

View File

@@ -1,7 +1,6 @@
before: before:
hooks: hooks:
- go mod download - go mod download
- make migration-pack
builds: builds:
- main: ./cli/node/main.go - main: ./cli/node/main.go
@@ -10,8 +9,10 @@ builds:
goos: goos:
- linux - linux
- darwin - darwin
goarch: - windows
- amd64 hooks:
pre: make migration-pack
post: make migration-clean
archives: archives:
- replacements: - replacements:

View File

@@ -60,7 +60,6 @@ func NewAPI(
// Transaction // Transaction
v1.POST("/transactions-pool", a.postPoolTx) v1.POST("/transactions-pool", a.postPoolTx)
v1.GET("/transactions-pool/:id", a.getPoolTx) v1.GET("/transactions-pool/:id", a.getPoolTx)
v1.GET("/transactions-pool", a.getPoolTxs)
} }
// Add explorer endpoints // Add explorer endpoints

View File

@@ -109,7 +109,7 @@ func (a *API) getFullBatch(c *gin.Context) {
// Fetch txs forged in the batch from historyDB // Fetch txs forged in the batch from historyDB
maxTxsPerBatch := uint(2048) //nolint:gomnd maxTxsPerBatch := uint(2048) //nolint:gomnd
txs, _, err := a.h.GetTxsAPI( txs, _, err := a.h.GetTxsAPI(
nil, nil, nil, nil, nil, batchNum, nil, nil, &maxTxsPerBatch, historydb.OrderAsc, nil, nil, nil, nil, batchNum, nil, nil, &maxTxsPerBatch, historydb.OrderAsc,
) )
if err != nil && tracerr.Unwrap(err) != sql.ErrNoRows { if err != nil && tracerr.Unwrap(err) != sql.ErrNoRows {
retSQLErr(err, c) retSQLErr(err, c)

View File

@@ -96,32 +96,6 @@ func parseQueryBJJ(c querier) (*babyjub.PublicKeyComp, error) {
return hezStringToBJJ(bjjStr, name) return hezStringToBJJ(bjjStr, name)
} }
func parseQueryPoolL2TxState(c querier) (*common.PoolL2TxState, error) {
const name = "state"
stateStr := c.Query(name)
if stateStr == "" {
return nil, nil
}
switch common.PoolL2TxState(stateStr) {
case common.PoolL2TxStatePending:
ret := common.PoolL2TxStatePending
return &ret, nil
case common.PoolL2TxStateForged:
ret := common.PoolL2TxStateForged
return &ret, nil
case common.PoolL2TxStateForging:
ret := common.PoolL2TxStateForging
return &ret, nil
case common.PoolL2TxStateInvalid:
ret := common.PoolL2TxStateInvalid
return &ret, nil
}
return nil, tracerr.Wrap(fmt.Errorf(
"invalid %s, %s is not a valid option. Check the valid options in the docmentation",
name, stateStr,
))
}
func parseQueryTxType(c querier) (*common.TxType, error) { func parseQueryTxType(c querier) (*common.TxType, error) {
const name = "type" const name = "type"
typeStr := c.Query(name) typeStr := c.Query(name)
@@ -172,18 +146,6 @@ func parseIdx(c querier) (*common.Idx, error) {
return stringToIdx(idxStr, name) return stringToIdx(idxStr, name)
} }
func parseFromIdx(c querier) (*common.Idx, error) {
const name = "fromAccountIndex"
idxStr := c.Query(name)
return stringToIdx(idxStr, name)
}
func parseToIdx(c querier) (*common.Idx, error) {
const name = "toAccountIndex"
idxStr := c.Query(name)
return stringToIdx(idxStr, name)
}
func parseExitFilters(c querier) (*common.TokenID, *ethCommon.Address, *babyjub.PublicKeyComp, *common.Idx, error) { func parseExitFilters(c querier) (*common.TokenID, *ethCommon.Address, *babyjub.PublicKeyComp, *common.Idx, error) {
// TokenID // TokenID
tid, err := parseQueryUint("tokenId", nil, 0, maxUint32, c) tid, err := parseQueryUint("tokenId", nil, 0, maxUint32, c)
@@ -219,47 +181,6 @@ func parseExitFilters(c querier) (*common.TokenID, *ethCommon.Address, *babyjub.
return tokenID, addr, bjj, idx, nil return tokenID, addr, bjj, idx, nil
} }
func parseTxsHistoryFilters(c querier) (*common.TokenID, *ethCommon.Address,
*babyjub.PublicKeyComp, *common.Idx, *common.Idx, error) {
// TokenID
tid, err := parseQueryUint("tokenId", nil, 0, maxUint32, c)
if err != nil {
return nil, nil, nil, nil, nil, tracerr.Wrap(err)
}
var tokenID *common.TokenID
if tid != nil {
tokenID = new(common.TokenID)
*tokenID = common.TokenID(*tid)
}
// Hez Eth addr
addr, err := parseQueryHezEthAddr(c)
if err != nil {
return nil, nil, nil, nil, nil, tracerr.Wrap(err)
}
// BJJ
bjj, err := parseQueryBJJ(c)
if err != nil {
return nil, nil, nil, nil, nil, tracerr.Wrap(err)
}
if addr != nil && bjj != nil {
return nil, nil, nil, nil, nil, tracerr.Wrap(errors.New("bjj and hezEthereumAddress params are incompatible"))
}
// from Idx
fromIdx, err := parseFromIdx(c)
if err != nil {
return nil, nil, nil, nil, nil, tracerr.Wrap(err)
}
// to Idx
toIdx, err := parseToIdx(c)
if err != nil {
return nil, nil, nil, nil, nil, tracerr.Wrap(err)
}
if (fromIdx != nil || toIdx != nil) && (addr != nil || bjj != nil || tokenID != nil) {
return nil, nil, nil, nil, nil, tracerr.Wrap(errors.New("accountIndex is incompatible with BJJ, hezEthereumAddress and tokenId"))
}
return tokenID, addr, bjj, fromIdx, toIdx, nil
}
func parseTokenFilters(c querier) ([]common.TokenID, []string, string, error) { func parseTokenFilters(c querier) ([]common.TokenID, []string, string, error) {
idsStr := c.Query("ids") idsStr := c.Query("ids")
symbolsStr := c.Query("symbols") symbolsStr := c.Query("symbols")

View File

@@ -2,7 +2,6 @@ package stateapiupdater
import ( import (
"database/sql" "database/sql"
"fmt"
"sync" "sync"
"github.com/hermeznetwork/hermez-node/common" "github.com/hermeznetwork/hermez-node/common"
@@ -24,7 +23,7 @@ type Updater struct {
// RecommendedFeePolicy describes how the recommended fee is calculated // RecommendedFeePolicy describes how the recommended fee is calculated
type RecommendedFeePolicy struct { type RecommendedFeePolicy struct {
PolicyType RecommendedFeePolicyType `validate:"required"` PolicyType RecommendedFeePolicyType
StaticValue float64 StaticValue float64
} }
@@ -32,9 +31,9 @@ type RecommendedFeePolicy struct {
type RecommendedFeePolicyType string type RecommendedFeePolicyType string
const ( const (
// RecommendedFeePolicyTypeStatic always give the same StaticValue as recommended fee // Always give the same StaticValue as recommended fee
RecommendedFeePolicyTypeStatic RecommendedFeePolicyType = "Static" RecommendedFeePolicyTypeStatic RecommendedFeePolicyType = "Static"
// RecommendedFeePolicyTypeAvgLastHour set the recommended fee using the average fee of the last hour // Set the recommended fee using the average fee of the last hour
RecommendedFeePolicyTypeAvgLastHour RecommendedFeePolicyType = "AvgLastHour" RecommendedFeePolicyTypeAvgLastHour RecommendedFeePolicyType = "AvgLastHour"
) )
@@ -56,7 +55,7 @@ func (rfp *RecommendedFeePolicy) valid() bool {
func NewUpdater(hdb *historydb.HistoryDB, config *historydb.NodeConfig, vars *common.SCVariables, func NewUpdater(hdb *historydb.HistoryDB, config *historydb.NodeConfig, vars *common.SCVariables,
consts *historydb.Constants, rfp *RecommendedFeePolicy) (*Updater, error) { consts *historydb.Constants, rfp *RecommendedFeePolicy) (*Updater, error) {
if ok := rfp.valid(); !ok { if ok := rfp.valid(); !ok {
return nil, tracerr.Wrap(fmt.Errorf("Invalid recommended fee policy: %v", rfp.PolicyType)) return nil, tracerr.New("Invalid recommende fee policy")
} }
u := Updater{ u := Updater{
hdb: hdb, hdb: hdb,

View File

@@ -59,17 +59,21 @@ externalDocs:
description: Find out more about Hermez network. description: Find out more about Hermez network.
url: 'https://hermez.io' url: 'https://hermez.io'
servers: servers:
- description: Hosted mock up - description: Hosted mock up, returns fake data useful for development
url: https://apimock.hermez.network/v1 url: https://apimock.hermez.network
- description: Localhost mock Up - description: Localhost mock up, returns fake data useful for development
url: http://localhost:4010/v1 url: http://localhost:4010
- description: Testnet (Rinkeby) server
url: https://api.testnet.hermez.io
- description: Mainnet (Ethereum) server, use it carefully, specially if attempting to send transactions. You could lose money!
url: https://api.hermez.io
tags: tags:
- name: Coordinator - name: Coordinator
description: Endpoints used by the nodes running in coordinator mode. They are used to interact with the network. description: Endpoints used by the nodes running in coordinator mode. They are used to interact with the network.
- name: Explorer - name: Explorer
description: Endpoints used by the nodes running in explorer mode. They are used to get information of the netwrok. description: Endpoints used by the nodes running in explorer mode. They are used to get information of the netwrok.
paths: paths:
'/account-creation-authorization': '/v1/account-creation-authorization':
post: post:
tags: tags:
- Coordinator - Coordinator
@@ -99,7 +103,7 @@ paths:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/Error500' $ref: '#/components/schemas/Error500'
'/account-creation-authorization/{hezEthereumAddress}': '/v1/account-creation-authorization/{hezEthereumAddress}':
get: get:
tags: tags:
- Coordinator - Coordinator
@@ -139,7 +143,7 @@ paths:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/Error500' $ref: '#/components/schemas/Error500'
'/accounts': '/v1/accounts':
get: get:
tags: tags:
- Explorer - Explorer
@@ -210,7 +214,7 @@ paths:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/Error500' $ref: '#/components/schemas/Error500'
'/accounts/{accountIndex}': '/v1/accounts/{accountIndex}':
get: get:
tags: tags:
- Explorer - Explorer
@@ -249,7 +253,7 @@ paths:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/Error500' $ref: '#/components/schemas/Error500'
'/exits': '/v1/exits':
get: get:
tags: tags:
- Explorer - Explorer
@@ -336,7 +340,7 @@ paths:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/Error500' $ref: '#/components/schemas/Error500'
'/exits/{batchNum}/{accountIndex}': '/v1/exits/{batchNum}/{accountIndex}':
get: get:
tags: tags:
- Explorer - Explorer
@@ -381,7 +385,7 @@ paths:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/Error500' $ref: '#/components/schemas/Error500'
'/transactions-pool': '/v1/transactions-pool':
post: post:
tags: tags:
- Coordinator - Coordinator
@@ -415,56 +419,7 @@ paths:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/Error500' $ref: '#/components/schemas/Error500'
get: '/v1/transactions-pool/{id}':
tags:
- Coordinator
summary: Get transactions that are in the pool.
operationId: getPoolTxs
parameters:
- name: state
in: query
required: false
description: State of the transactions, e.g. "pend"
schema:
$ref: '#/components/schemas/PoolL2TransactionState'
- name: fromAccountIndex
in: query
required: false
description: Id of the from account
schema:
$ref: '#/components/schemas/AccountIndex'
- name: toAccountIndex
in: query
required: false
description: Id of the to account
schema:
$ref: '#/components/schemas/AccountIndex'
responses:
'200':
description: Successful operation.
content:
application/json:
schema:
$ref: '#/components/schemas/PoolL2Transactions'
'400':
description: Bad request.
content:
application/json:
schema:
$ref: '#/components/schemas/Error400'
'404':
description: Not found.
content:
application/json:
schema:
$ref: '#/components/schemas/Error404'
'500':
description: Internal server error
content:
application/json:
schema:
$ref: '#/components/schemas/Error500'
'/transactions-pool/{id}':
get: get:
tags: tags:
- Coordinator - Coordinator
@@ -507,7 +462,7 @@ paths:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/Error500' $ref: '#/components/schemas/Error500'
'/transactions-history': '/v1/transactions-history':
get: get:
tags: tags:
- Explorer - Explorer
@@ -536,16 +491,10 @@ paths:
required: false required: false
schema: schema:
$ref: '#/components/schemas/BJJ' $ref: '#/components/schemas/BJJ'
- name: fromAccountIndex - name: accountIndex
in: query in: query
required: false required: false
description: Only get transactions sent from a specific account. Incompatible with the queries `tokenId`, `hezEthereumAddress` and `BJJ`. description: Only get transactions sent from or to a specific account. Incompatible with the queries `tokenId`, `hezEthereumAddress` and `BJJ`.
schema:
$ref: '#/components/schemas/AccountIndex'
- name: toAccountIndex
in: query
required: false
description: Only get transactions sent to a specific account. Incompatible with the queries `tokenId`, `hezEthereumAddress` and `BJJ`.
schema: schema:
$ref: '#/components/schemas/AccountIndex' $ref: '#/components/schemas/AccountIndex'
- name: batchNum - name: batchNum
@@ -603,7 +552,7 @@ paths:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/Error500' $ref: '#/components/schemas/Error500'
'/transactions-history/{id}': '/v1/transactions-history/{id}':
get: get:
tags: tags:
- Explorer - Explorer
@@ -643,7 +592,7 @@ paths:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/Error500' $ref: '#/components/schemas/Error500'
'/batches': '/v1/batches':
get: get:
tags: tags:
- Explorer - Explorer
@@ -719,7 +668,7 @@ paths:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/Error500' $ref: '#/components/schemas/Error500'
'/batches/{batchNum}': '/v1/batches/{batchNum}':
get: get:
tags: tags:
- Explorer - Explorer
@@ -759,7 +708,7 @@ paths:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/Error500' $ref: '#/components/schemas/Error500'
'/full-batches/{batchNum}': '/v1/full-batches/{batchNum}':
get: get:
tags: tags:
- Explorer - Explorer
@@ -800,7 +749,7 @@ paths:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/Error500' $ref: '#/components/schemas/Error500'
'/slots': '/v1/slots':
get: get:
tags: tags:
- Explorer - Explorer
@@ -876,7 +825,7 @@ paths:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/Error500' $ref: '#/components/schemas/Error500'
'/slots/{slotNum}': '/v1/slots/{slotNum}':
get: get:
tags: tags:
- Explorer - Explorer
@@ -916,7 +865,7 @@ paths:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/Error500' $ref: '#/components/schemas/Error500'
'/bids': '/v1/bids':
get: get:
tags: tags:
- Explorer - Explorer
@@ -980,7 +929,7 @@ paths:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/Error500' $ref: '#/components/schemas/Error500'
'/state': '/v1/state':
get: get:
tags: tags:
- Explorer - Explorer
@@ -1006,7 +955,7 @@ paths:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/Error500' $ref: '#/components/schemas/Error500'
'/config': '/v1/config':
get: get:
tags: tags:
- Explorer - Explorer
@@ -1026,7 +975,7 @@ paths:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/Error500' $ref: '#/components/schemas/Error500'
'/tokens': '/v1/tokens':
get: get:
tags: tags:
- Explorer - Explorer
@@ -1099,7 +1048,7 @@ paths:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/Error500' $ref: '#/components/schemas/Error500'
'/tokens/{id}': '/v1/tokens/{id}':
get: get:
tags: tags:
- Explorer - Explorer
@@ -1138,7 +1087,7 @@ paths:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/Error500' $ref: '#/components/schemas/Error500'
'/coordinators': '/v1/coordinators':
get: get:
tags: tags:
- Explorer - Explorer
@@ -1494,14 +1443,6 @@ components:
- requestFee - requestFee
- requestNonce - requestNonce
- token - token
PoolL2Transactions:
type: object
properties:
transactions:
type: array
description: List of pool l2 transactions
items:
$ref: '#/components/schemas/PoolL2Transaction'
TransactionId: TransactionId:
type: string type: string
description: Identifier for transactions. Used for any kind of transaction (both L1 and L2). More info on how the identifiers are built [here](https://idocs.hermez.io/#/spec/architecture/db/README?id=txid) description: Identifier for transactions. Used for any kind of transaction (both L1 and L2). More info on how the identifiers are built [here](https://idocs.hermez.io/#/spec/architecture/db/README?id=txid)

View File

@@ -9,7 +9,7 @@ import (
func (a *API) getHistoryTxs(c *gin.Context) { func (a *API) getHistoryTxs(c *gin.Context) {
// Get query parameters // Get query parameters
tokenID, addr, bjj, fromIdx, toIdx, err := parseTxsHistoryFilters(c) tokenID, addr, bjj, idx, err := parseExitFilters(c)
if err != nil { if err != nil {
retBadReq(err, c) retBadReq(err, c)
return return
@@ -35,7 +35,7 @@ func (a *API) getHistoryTxs(c *gin.Context) {
// Fetch txs from historyDB // Fetch txs from historyDB
txs, pendingItems, err := a.h.GetTxsAPI( txs, pendingItems, err := a.h.GetTxsAPI(
addr, bjj, tokenID, fromIdx, toIdx, batchNum, txType, fromItem, limit, order, addr, bjj, tokenID, idx, batchNum, txType, fromItem, limit, order,
) )
if err != nil { if err != nil {
retSQLErr(err, c) retSQLErr(err, c)

View File

@@ -324,8 +324,8 @@ func TestGetHistoryTxs(t *testing.T) {
idx, err := stringToIdx(idxStr, "") idx, err := stringToIdx(idxStr, "")
assert.NoError(t, err) assert.NoError(t, err)
path = fmt.Sprintf( path = fmt.Sprintf(
"%s?fromAccountIndex=%s&toAccountIndex=%s&limit=%d", "%s?accountIndex=%s&limit=%d",
endpoint, idxStr, idxStr, limit, endpoint, idxStr, limit,
) )
err = doGoodReqPaginated(path, historydb.OrderAsc, &testTxsResponse{}, appendIter) err = doGoodReqPaginated(path, historydb.OrderAsc, &testTxsResponse{}, appendIter)
assert.NoError(t, err) assert.NoError(t, err)
@@ -431,8 +431,8 @@ func TestGetHistoryTxs(t *testing.T) {
assertTxs(t, []testTx{}, fetchedTxs) assertTxs(t, []testTx{}, fetchedTxs)
// 400 // 400
path = fmt.Sprintf( path = fmt.Sprintf(
"%s?fromAccountIndex=%s&toAccountIndex=%s&hezEthereumAddress=%s", "%s?accountIndex=%s&hezEthereumAddress=%s",
endpoint, idx, idx, account.EthAddr, endpoint, idx, account.EthAddr,
) )
err = doBadReq("GET", path, nil, 400) err = doBadReq("GET", path, nil, 400)
assert.NoError(t, err) assert.NoError(t, err)

View File

@@ -55,41 +55,6 @@ func (a *API) getPoolTx(c *gin.Context) {
c.JSON(http.StatusOK, tx) c.JSON(http.StatusOK, tx)
} }
func (a *API) getPoolTxs(c *gin.Context) {
// Get from idx
fromIdx, err := parseFromIdx(c)
if err != nil {
retBadReq(err, c)
return
}
// Get to idx
toIdx, err := parseToIdx(c)
if err != nil {
retBadReq(err, c)
return
}
// Get state
state, err := parseQueryPoolL2TxState(c)
if err != nil {
retBadReq(err, c)
return
}
// Fetch txs from l2DB
txs, err := a.l2.GetPoolTxs(fromIdx, toIdx, state)
if err != nil {
retSQLErr(err, c)
return
}
// Build successful response
type txsResponse struct {
Txs []*l2db.PoolTxAPI `json:"transactions"`
}
c.JSON(http.StatusOK, &txsResponse{
Txs: txs,
})
}
type receivedPoolTx struct { type receivedPoolTx struct {
TxID common.TxID `json:"id" binding:"required"` TxID common.TxID `json:"id" binding:"required"`
Type common.TxType `json:"type" binding:"required"` Type common.TxType `json:"type" binding:"required"`

View File

@@ -47,10 +47,6 @@ type testPoolTxReceive struct {
Token historydb.TokenWithUSD `json:"token"` Token historydb.TokenWithUSD `json:"token"`
} }
type testPoolTxsResponse struct {
Txs []testPoolTxReceive `json:"transactions"`
}
// testPoolTxSend is a struct to be used as a JSON body // testPoolTxSend is a struct to be used as a JSON body
// when testing POST /transactions-pool // when testing POST /transactions-pool
type testPoolTxSend struct { type testPoolTxSend struct {
@@ -229,24 +225,6 @@ func TestPoolTxs(t *testing.T) {
err = doBadReq("POST", endpoint, jsonTxReader, 400) err = doBadReq("POST", endpoint, jsonTxReader, 400)
require.NoError(t, err) require.NoError(t, err)
// GET // GET
// get by idx
fetchedTxs := testPoolTxsResponse{}
require.NoError(t, doGoodReq(
"GET",
endpoint+"?fromAccountIndex=hez:ETH:263",
nil, &fetchedTxs))
assert.Equal(t, 1, len(fetchedTxs.Txs))
assert.Equal(t, "hez:ETH:263", fetchedTxs.Txs[0].FromIdx)
// get by state
require.NoError(t, doGoodReq(
"GET",
endpoint+"?state=pend",
nil, &fetchedTxs))
assert.Equal(t, 4, len(fetchedTxs.Txs))
for _, v := range fetchedTxs.Txs {
assert.Equal(t, common.PoolL2TxStatePending, v.State)
}
// GET
endpoint += "/" endpoint += "/"
for _, tx := range tc.poolTxsToReceive { for _, tx := range tc.poolTxsToReceive {
fetchedTx := testPoolTxReceive{} fetchedTx := testPoolTxReceive{}

View File

@@ -365,6 +365,7 @@ func getConfig(c *cli.Context) (*Config, error) {
} }
case modeCoord: case modeCoord:
cfg.mode = node.ModeCoordinator cfg.mode = node.ModeCoordinator
fmt.Println("LOADING CFG")
cfg.node, err = config.LoadNode(nodeCfgPath, true) cfg.node, err = config.LoadNode(nodeCfgPath, true)
if err != nil { if err != nil {
return nil, tracerr.Wrap(err) return nil, tracerr.Wrap(err)

View File

@@ -456,7 +456,7 @@ func (hdb *HistoryDB) GetTxAPI(txID common.TxID) (*TxAPI, error) {
// and pagination info // and pagination info
func (hdb *HistoryDB) GetTxsAPI( func (hdb *HistoryDB) GetTxsAPI(
ethAddr *ethCommon.Address, bjj *babyjub.PublicKeyComp, ethAddr *ethCommon.Address, bjj *babyjub.PublicKeyComp,
tokenID *common.TokenID, fromIdx, toIdx *common.Idx, batchNum *uint, txType *common.TxType, tokenID *common.TokenID, idx *common.Idx, batchNum *uint, txType *common.TxType,
fromItem, limit *uint, order string, fromItem, limit *uint, order string,
) ([]TxAPI, uint64, error) { ) ([]TxAPI, uint64, error) {
// Warning: amount_success and deposit_amount_success have true as default for // Warning: amount_success and deposit_amount_success have true as default for
@@ -508,32 +508,14 @@ func (hdb *HistoryDB) GetTxsAPI(
nextIsAnd = true nextIsAnd = true
} }
// idx filter // idx filter
if fromIdx != nil && toIdx != nil { if idx != nil {
if nextIsAnd { if nextIsAnd {
queryStr += "AND " queryStr += "AND "
} else { } else {
queryStr += "WHERE " queryStr += "WHERE "
} }
queryStr += "(tx.effective_from_idx = ? " queryStr += "(tx.effective_from_idx = ? OR tx.to_idx = ?) "
queryStr += "OR tx.to_idx = ?) " args = append(args, idx, idx)
args = append(args, fromIdx, toIdx)
nextIsAnd = true
} else if fromIdx != nil {
if nextIsAnd {
queryStr += "AND "
} else {
queryStr += "WHERE "
}
queryStr += "tx.effective_from_idx = ? "
nextIsAnd = true
} else if toIdx != nil {
if nextIsAnd {
queryStr += "AND "
} else {
queryStr += "WHERE "
}
queryStr += "tx.to_idx = ? "
args = append(args, toIdx)
nextIsAnd = true nextIsAnd = true
} }
// batchNum filter // batchNum filter

View File

@@ -127,57 +127,3 @@ func (l2db *L2DB) GetTxAPI(txID common.TxID) (*PoolTxAPI, error) {
txID, txID,
)) ))
} }
// GetPoolTxs return Txs from the pool
func (l2db *L2DB) GetPoolTxs(fromIdx, toIdx *common.Idx, state *common.PoolL2TxState) ([]*PoolTxAPI, error) {
cancel, err := l2db.apiConnCon.Acquire()
defer cancel()
if err != nil {
return nil, tracerr.Wrap(err)
}
defer l2db.apiConnCon.Release()
// Apply filters
nextIsAnd := false
queryStr := selectPoolTxAPI
var args []interface{}
if state != nil {
queryStr += "WHERE state = ? "
args = append(args, state)
nextIsAnd = true
}
if fromIdx != nil && toIdx != nil {
if nextIsAnd {
queryStr += "AND ("
} else {
queryStr += "WHERE ("
}
queryStr += "tx_pool.from_idx = ? "
queryStr += "OR tx_pool.to_idx = ?) "
args = append(args, fromIdx, toIdx)
} else if fromIdx != nil {
if nextIsAnd {
queryStr += "AND "
} else {
queryStr += "WHERE "
}
queryStr += "tx_pool.from_idx = ? "
args = append(args, fromIdx)
} else if toIdx != nil {
if nextIsAnd {
queryStr += "AND "
} else {
queryStr += "WHERE "
}
queryStr += "tx_pool.to_idx = ? "
args = append(args, toIdx)
}
queryStr += "AND NOT external_delete;"
query := l2db.dbRead.Rebind(queryStr)
txs := []*PoolTxAPI{}
err = meddler.QueryAll(
l2db.dbRead, &txs,
query,
args...)
return txs, tracerr.Wrap(err)
}

View File

@@ -311,28 +311,6 @@ func TestGetPending(t *testing.T) {
} }
} }
func TestL2DB_GetPoolTxs(t *testing.T) {
err := prepareHistoryDB(historyDB)
if err != nil {
log.Error("Error prepare historyDB", err)
}
poolL2Txs, err := generatePoolL2Txs()
require.NoError(t, err)
state := common.PoolL2TxState("pend")
idx := common.Idx(256)
var pendingTxs []*common.PoolL2Tx
for i := range poolL2Txs {
if poolL2Txs[i].FromIdx == idx || poolL2Txs[i].ToIdx == idx {
err := l2DB.AddTxTest(&poolL2Txs[i])
require.NoError(t, err)
pendingTxs = append(pendingTxs, &poolL2Txs[i])
}
}
fetchedTxs, err := l2DBWithACC.GetPoolTxs(&idx, &idx, &state)
require.NoError(t, err)
assert.Equal(t, len(pendingTxs), len(fetchedTxs))
}
func TestStartForging(t *testing.T) { func TestStartForging(t *testing.T) {
// Generate txs // Generate txs
var fakeBatchNum common.BatchNum = 33 var fakeBatchNum common.BatchNum = 33

View File

@@ -245,15 +245,15 @@ func (c *EthereumClient) EthBlockByNumber(ctx context.Context, number int64) (*c
if number == -1 { if number == -1 {
blockNum = nil blockNum = nil
} }
header, err := c.client.HeaderByNumber(ctx, blockNum) block, err := c.client.BlockByNumber(ctx, blockNum)
if err != nil { if err != nil {
return nil, tracerr.Wrap(err) return nil, tracerr.Wrap(err)
} }
b := &common.Block{ b := &common.Block{
Num: header.Number.Int64(), Num: block.Number().Int64(),
Timestamp: time.Unix(int64(header.Time), 0), Timestamp: time.Unix(int64(block.Time()), 0),
ParentHash: header.ParentHash, ParentHash: block.ParentHash(),
Hash: header.Hash(), Hash: block.Hash(),
} }
return b, nil return b, nil
} }