forked from 0xPolygonHermez/zkevm-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pgstorage.go
278 lines (237 loc) · 7.3 KB
/
pgstorage.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
package ethtxmanager
import (
"context"
"encoding/hex"
"errors"
"math/big"
"time"
"github.com/0xPolygonHermez/zkevm-node/db"
"github.com/ethereum/go-ethereum/common"
"github.com/jackc/pgconn"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
)
// PostgresStorage hold txs to be managed
type PostgresStorage struct {
*pgxpool.Pool
}
// NewPostgresStorage creates a new instance of storage that use
// postgres to store data
func NewPostgresStorage(dbCfg db.Config) (*PostgresStorage, error) {
db, err := db.NewSQLDB(dbCfg)
if err != nil {
return nil, err
}
return &PostgresStorage{
db,
}, nil
}
// Add persist a monitored tx
func (s *PostgresStorage) Add(ctx context.Context, mTx monitoredTx, dbTx pgx.Tx) error {
conn := s.dbConn(dbTx)
cmd := `
INSERT INTO state.monitored_txs (owner, id, from_addr, to_addr, nonce, value, data, gas, gas_offset, gas_price, status, block_num, history, created_at, updated_at)
VALUES ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)`
_, err := conn.Exec(ctx, cmd, mTx.owner,
mTx.id, mTx.from.String(), mTx.toStringPtr(),
mTx.nonce, mTx.valueU64Ptr(), mTx.dataStringPtr(),
mTx.gas, mTx.gasOffset, mTx.gasPrice.Uint64(), string(mTx.status), mTx.blockNumberU64Ptr(),
mTx.historyStringSlice(), time.Now().UTC().Round(time.Microsecond),
time.Now().UTC().Round(time.Microsecond))
if err != nil {
if pgErr, ok := err.(*pgconn.PgError); ok && pgErr.ConstraintName == "monitored_txs_pkey" {
return ErrAlreadyExists
} else {
return err
}
}
return nil
}
// Get loads a persisted monitored tx
func (s *PostgresStorage) Get(ctx context.Context, owner, id string, dbTx pgx.Tx) (monitoredTx, error) {
conn := s.dbConn(dbTx)
cmd := `
SELECT owner, id, from_addr, to_addr, nonce, value, data, gas, gas_offset, gas_price, status, block_num, history, created_at, updated_at
FROM state.monitored_txs
WHERE owner = $1
AND id = $2`
mTx := monitoredTx{}
row := conn.QueryRow(ctx, cmd, owner, id)
err := s.scanMtx(row, &mTx)
if errors.Is(err, pgx.ErrNoRows) {
return mTx, ErrNotFound
} else if err != nil {
return mTx, err
}
return mTx, nil
}
// GetByStatus loads all monitored tx that match the provided status
func (s *PostgresStorage) GetByStatus(ctx context.Context, owner *string, statuses []MonitoredTxStatus, dbTx pgx.Tx) ([]monitoredTx, error) {
hasStatusToFilter := len(statuses) > 0
conn := s.dbConn(dbTx)
cmd := `
SELECT owner, id, from_addr, to_addr, nonce, value, data, gas, gas_offset, gas_price, status, block_num, history, created_at, updated_at
FROM state.monitored_txs
WHERE (owner = $1 OR $1 IS NULL)`
if hasStatusToFilter {
cmd += `
AND status = ANY($2)`
}
cmd += `
ORDER BY created_at`
mTxs := []monitoredTx{}
var rows pgx.Rows
var err error
if hasStatusToFilter {
rows, err = conn.Query(ctx, cmd, owner, statuses)
} else {
rows, err = conn.Query(ctx, cmd, owner)
}
if errors.Is(err, pgx.ErrNoRows) {
return []monitoredTx{}, nil
} else if err != nil {
return nil, err
}
for rows.Next() {
mTx := monitoredTx{}
err := s.scanMtx(rows, &mTx)
if err != nil {
return nil, err
}
mTxs = append(mTxs, mTx)
}
return mTxs, nil
}
// GetByBlock loads all monitored tx that have the blockNumber between
// fromBlock and toBlock
func (s *PostgresStorage) GetByBlock(ctx context.Context, fromBlock, toBlock *uint64, dbTx pgx.Tx) ([]monitoredTx, error) {
conn := s.dbConn(dbTx)
cmd := `
SELECT owner, id, from_addr, to_addr, nonce, value, data, gas, gas_offset, gas_price, status, block_num, history, created_at, updated_at
FROM state.monitored_txs
WHERE (block_num >= $1 OR $1 IS NULL)
AND (block_num <= $2 OR $2 IS NULL)
AND block_num IS NOT NULL
ORDER BY created_at`
const numberOfArgs = 2
args := make([]interface{}, 0, numberOfArgs)
if fromBlock != nil {
args = append(args, *fromBlock)
} else {
args = append(args, fromBlock)
}
if toBlock != nil {
args = append(args, *toBlock)
} else {
args = append(args, toBlock)
}
mTxs := []monitoredTx{}
rows, err := conn.Query(ctx, cmd, args...)
if errors.Is(err, pgx.ErrNoRows) {
return []monitoredTx{}, nil
} else if err != nil {
return nil, err
}
for rows.Next() {
mTx := monitoredTx{}
err := s.scanMtx(rows, &mTx)
if err != nil {
return nil, err
}
mTxs = append(mTxs, mTx)
}
return mTxs, nil
}
// Update a persisted monitored tx
func (s *PostgresStorage) Update(ctx context.Context, mTx monitoredTx, dbTx pgx.Tx) error {
conn := s.dbConn(dbTx)
cmd := `
UPDATE state.monitored_txs
SET from_addr = $3
, to_addr = $4
, nonce = $5
, value = $6
, data = $7
, gas = $8
, gas_offset = $9
, gas_price = $10
, status = $11
, block_num = $12
, history = $13
, updated_at = $14
WHERE owner = $1
AND id = $2`
var bn *uint64
if mTx.blockNumber != nil {
tmp := mTx.blockNumber.Uint64()
bn = &tmp
}
_, err := conn.Exec(ctx, cmd, mTx.owner,
mTx.id, mTx.from.String(), mTx.toStringPtr(),
mTx.nonce, mTx.valueU64Ptr(), mTx.dataStringPtr(),
mTx.gas, mTx.gasOffset, mTx.gasPrice.Uint64(), string(mTx.status), bn,
mTx.historyStringSlice(), time.Now().UTC().Round(time.Microsecond))
if err != nil {
return err
}
return nil
}
// scanMtx scans a row and fill the provided instance of monitoredTx with
// the row data
func (s *PostgresStorage) scanMtx(row pgx.Row, mTx *monitoredTx) error {
// id, from, to, nonce, value, data, gas, gas_offset, gas_price, status, history, created_at, updated_at
var from, status string
var to, data *string
var history []string
var value, blockNumber *uint64
var gasPrice uint64
err := row.Scan(&mTx.owner, &mTx.id, &from, &to, &mTx.nonce, &value,
&data, &mTx.gas, &mTx.gasOffset, &gasPrice, &status, &blockNumber, &history,
&mTx.createdAt, &mTx.updatedAt)
if err != nil {
return err
}
mTx.from = common.HexToAddress(from)
mTx.gasPrice = big.NewInt(0).SetUint64(gasPrice)
mTx.status = MonitoredTxStatus(status)
if to != nil {
tmp := common.HexToAddress(*to)
mTx.to = &tmp
}
if value != nil {
tmp := *value
mTx.value = big.NewInt(0).SetUint64(tmp)
}
if data != nil {
tmp := *data
bytes, err := hex.DecodeString(tmp)
if err != nil {
return err
}
mTx.data = bytes
}
if blockNumber != nil {
tmp := *blockNumber
mTx.blockNumber = big.NewInt(0).SetUint64(tmp)
}
h := make(map[common.Hash]bool, len(history))
for _, txHash := range history {
h[common.HexToHash(txHash)] = true
}
mTx.history = h
return nil
}
// dbConn represents an instance of an object that can
// connect to a postgres db to execute sql commands and query data
type dbConn interface {
Exec(ctx context.Context, sql string, arguments ...interface{}) (commandTag pgconn.CommandTag, err error)
Query(ctx context.Context, sql string, args ...interface{}) (pgx.Rows, error)
QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row
}
// dbConn determines which db connection to use, dbTx or the main pgxpool
func (p *PostgresStorage) dbConn(dbTx pgx.Tx) dbConn {
if dbTx != nil {
return dbTx
}
return p
}