-
Notifications
You must be signed in to change notification settings - Fork 2
/
database.go
400 lines (350 loc) 路 13.2 KB
/
database.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
package preconshare
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
)
var ErrBundleNotCancelled = errors.New("bundle not cancelled")
type DBSbundle struct {
Hash []byte `db:"hash"`
MatchingHash []byte `db:"matching_hash"`
Signer []byte `db:"signer"`
Cancelled bool `db:"cancelled"`
AllowMatching bool `db:"allow_matching"`
Prematched bool `db:"prematched"`
ReceivedAt time.Time `db:"received_at"`
SimSuccess bool `db:"sim_success"`
SimError sql.NullString `db:"sim_error"`
SimulatedAt sql.NullTime `db:"simulated_at"`
SimEffGasPrice sql.NullString `db:"sim_eff_gas_price"`
SimProfit sql.NullString `db:"sim_profit"`
SimRefundableValue sql.NullString `db:"sim_refundable_value"`
SimGasUsed sql.NullInt64 `db:"sim_gas_used"`
// sum of all simulations gas used
SimAllSimsGasUsed sql.NullInt64 `db:"sim_all_sims_gas_used"`
// number of simulations that were run for this bundle
SimTotalSimCount sql.NullInt64 `db:"sim_total_sim_count"`
Body []byte `db:"body"`
BodySize int `db:"body_size"`
OriginID sql.NullString `db:"origin_id"`
InsertedAt time.Time `db:"inserted_at"`
}
var insertBundleQuery = `
INSERT INTO sbundle (hash, matching_hash, signer, cancelled, allow_matching, prematched, received_at,
sim_success, sim_error, simulated_at, sim_eff_gas_price, sim_profit, sim_refundable_value, sim_gas_used,
sim_all_sims_gas_used, sim_total_sim_count,
body, body_size, origin_id)
VALUES (:hash, :matching_hash, :signer, :cancelled, :allow_matching, :prematched, :received_at,
:sim_success, :sim_error, :simulated_at, :sim_eff_gas_price, :sim_profit, :sim_refundable_value, :sim_gas_used,
:sim_all_sims_gas_used, :sim_total_sim_count,
:body, :body_size, :origin_id)
ON CONFLICT (hash) DO NOTHING
RETURNING hash`
var selectSimDataBundleQueryForUpdate = `
SELECT hash, sim_success, sim_error, simulated_at, sim_eff_gas_price, sim_profit, sim_refundable_value, sim_gas_used, sim_all_sims_gas_used, sim_total_sim_count
FROM sbundle
WHERE hash = $1
FOR UPDATE`
var updateBundleSimQuery = `
UPDATE sbundle
SET sim_success = :sim_success, sim_error = :sim_error, simulated_at = :simulated_at,
sim_eff_gas_price = :sim_eff_gas_price, sim_profit = :sim_profit, sim_refundable_value = :sim_refundable_value,
sim_gas_used = :sim_gas_used, sim_all_sims_gas_used = :sim_all_sims_gas_used, sim_total_sim_count = :sim_total_sim_count, body = :body
WHERE hash = :hash`
var getBundleQuery = `
SELECT matching_hash, body
FROM sbundle
WHERE matching_hash = $1 AND allow_matching = true AND cancelled = false limit 1`
type DBSbundleBody struct {
Hash []byte `db:"hash"`
ElementHash []byte `db:"element_hash"`
Idx int `db:"idx"`
Type int `db:"type"`
}
var insertBundleBodyQuery = `
INSERT INTO sbundle_body (hash, element_hash, idx, type)
VALUES (:hash, :element_hash, :idx, :type)
ON CONFLICT (hash, idx) DO NOTHING`
type DBSpreconf struct {
Hash []byte `db:"hash"`
Block int64 `db:"block"`
Signature []byte `db:"signature"`
Time int64 `db:"time"`
InsertedAt time.Time `db:"inserted_at"`
}
var insertPreconfQuery = `
INSERT INTO spreconf (hash, block, signature)
VALUES (:hash, :block, :signature)
ON CONFLICT (signature) DO NOTHING`
var getPreconfQuery = `
SELECT block, signature, time
FROM spreconf
WHERE hash = $1
ORDER BY block
LIMIT 1`
var updatePreconfQuery = `UPDATE spreconf SET time = $1 WHERE hash = $2`
var filterPreconfQuery = `DELETE FROM spreconf WHERE hash = $1 AND signature != $2`
var ErrBundleNotFound = errors.New("bundle not found")
type DBSbundleHistoricalHint struct {
ID int64 `db:"id"`
Block int64 `db:"block"`
Hint json.RawMessage `db:"hint"`
InsertedAt time.Time `db:"inserted_at"`
}
var insertBundleHistoricalHintQuery = `
INSERT INTO sbundle_hint_history (block, hint)
VALUES (:block, :hint)
RETURNING id`
type DBBackend struct {
db *sqlx.DB
insertBundle *sqlx.NamedStmt
getBundle *sqlx.Stmt
insertPreconf *sqlx.NamedStmt
getPreconf *sqlx.Stmt
filterPreconf *sqlx.Stmt
updatePreconf *sqlx.Stmt
insertHint *sqlx.NamedStmt
updateBundleSim *sqlx.NamedStmt
}
func NewDBBackend(postgresDSN string) (*DBBackend, error) {
db, err := sqlx.Connect("postgres", postgresDSN)
if err != nil {
return nil, err
}
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(20)
insertBundle, err := db.PrepareNamed(insertBundleQuery)
if err != nil {
return nil, err
}
getBundle, err := db.Preparex(getBundleQuery)
if err != nil {
return nil, err
}
insertPreconf, err := db.PrepareNamed(insertPreconfQuery)
if err != nil {
return nil, err
}
getPreconf, err := db.Preparex(getPreconfQuery)
if err != nil {
return nil, err
}
filterPreconf, err := db.Preparex(filterPreconfQuery)
if err != nil {
return nil, err
}
updatePreconf, err := db.Preparex(updatePreconfQuery)
if err != nil {
return nil, err
}
insertHint, err := db.PrepareNamed(insertBundleHistoricalHintQuery)
if err != nil {
return nil, err
}
updateBundleSim, err := db.PrepareNamed(updateBundleSimQuery)
if err != nil {
return nil, err
}
return &DBBackend{
db: db,
insertBundle: insertBundle,
getBundle: getBundle,
insertPreconf: insertPreconf,
getPreconf: getPreconf,
filterPreconf: filterPreconf,
updatePreconf: updatePreconf,
insertHint: insertHint,
updateBundleSim: updateBundleSim,
}, nil
}
func (b *DBBackend) GetBundleByMatchingHash(ctx context.Context, hash common.Hash) (*SendRequestArgs, error) {
var dbSbundle DBSbundle
err := b.getBundle.GetContext(ctx, &dbSbundle, hash.Bytes())
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrBundleNotFound
} else if err != nil {
return nil, err
}
var bundle SendRequestArgs
err = json.Unmarshal(dbSbundle.Body, &bundle)
if err != nil {
return nil, err
}
return &bundle, nil
}
func (b *DBBackend) GetPreconfByMatchingHash(ctx context.Context, hash common.Hash) (*int64, *hexutil.Bytes, *int64, error) {
var dbSpreconf DBSpreconf
// First, we select the best preconf.
err := b.getPreconf.GetContext(ctx, &dbSpreconf, hash.Bytes())
if errors.Is(err, sql.ErrNoRows) {
return nil, nil, nil, ErrBundleNotFound
} else if err != nil {
return nil, nil, nil, err
}
var signature hexutil.Bytes
err = json.Unmarshal(dbSpreconf.Signature, &signature)
if err != nil {
return nil, nil, nil, err
}
// Then, we remove the other preconfs.
err = b.filterPreconf.GetContext(ctx, &dbSpreconf, hash.Bytes(), dbSpreconf.Signature)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return nil, nil, nil, err
}
return &dbSpreconf.Block, &signature, &dbSpreconf.Time, nil
}
func (b *DBBackend) UpdatePreconfTimeBySignature(ctx context.Context, time int64, hash common.Hash) error {
var dbSpreconf DBSpreconf
// First, we select the best preconf.
err := b.updatePreconf.GetContext(ctx, &dbSpreconf, time, hash.Bytes())
if err != nil {
return err
}
return err
}
// InsertBundleForStats inserts a bundle into the database.
// When called for the second time for the known bundle, it will return known = true and update bundle simulation
// results with the last inserted simulation results.
func (b *DBBackend) InsertBundleForStats(ctx context.Context, bundle *SendRequestArgs) (known bool, err error) { //nolint:gocognit
var dbBundle DBSbundle
if bundle.Metadata == nil {
return known, ErrNilBundleMetadata
}
dbBundle.Hash = bundle.Metadata.RequestHash.Bytes()
dbBundle.MatchingHash = bundle.Metadata.MatchingHash.Bytes()
dbBundle.Signer = bundle.Metadata.Signer.Bytes()
dbBundle.AllowMatching = bundle.Privacy != nil && bundle.Privacy.Hints.HasHint(HintHash)
dbBundle.Prematched = bundle.Metadata.Prematched
dbBundle.Cancelled = false
dbBundle.ReceivedAt = time.UnixMicro(int64(bundle.Metadata.ReceivedAt))
// dbBundle.SimSuccess = result.Success
// dbBundle.SimError = sql.NullString{String: result.Error, Valid: result.Error != ""}
// dbBundle.SimulatedAt = sql.NullTime{Time: time.Now(), Valid: true}
// dbBundle.SimEffGasPrice = sql.NullString{String: dbIntToEth(&result.MevGasPrice), Valid: result.Success}
// dbBundle.SimProfit = sql.NullString{String: dbIntToEth(&result.Profit), Valid: result.Success}
// dbBundle.SimRefundableValue = sql.NullString{String: dbIntToEth(&result.RefundableValue), Valid: result.Success}
// dbBundle.SimGasUsed = sql.NullInt64{Int64: int64(result.GasUsed), Valid: true}
// dbBundle.SimAllSimsGasUsed = sql.NullInt64{Int64: int64(result.GasUsed), Valid: true}
// dbBundle.SimTotalSimCount = sql.NullInt64{Int64: 1, Valid: true}
dbBundle.Body, err = json.Marshal(bundle)
if err != nil {
return known, err
}
dbBundle.BodySize = len(bundle.Body)
dbBundle.OriginID = sql.NullString{String: bundle.Metadata.OriginID, Valid: bundle.Metadata.OriginID != ""}
dbTx, err := b.db.BeginTxx(ctx, nil)
if err != nil {
return known, err
}
// get hash from db
var hash []byte
err = dbTx.NamedStmtContext(ctx, b.insertBundle).GetContext(ctx, &hash, dbBundle)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
// bundle is known so we update it with fresh simulation results
known = true
// 1. get bundle from db
var storedBundle DBSbundle
err = dbTx.GetContext(ctx, &storedBundle, selectSimDataBundleQueryForUpdate, dbBundle.Hash)
if err != nil {
_ = dbTx.Rollback()
return known, err
}
// var shouldUpdateSim bool
// if storedBundle.SimSuccess {
// shouldUpdateSim = result.Success
// } else {
// shouldUpdateSim = true
// }
// if shouldUpdateSim {
// storedBundle.SimSuccess = result.Success
// storedBundle.SimError = sql.NullString{String: result.Error, Valid: result.Error != ""}
// storedBundle.SimulatedAt = sql.NullTime{Time: time.Now(), Valid: true}
// storedBundle.SimEffGasPrice = sql.NullString{String: dbIntToEth(&result.MevGasPrice), Valid: result.Success}
// storedBundle.SimProfit = sql.NullString{String: dbIntToEth(&result.Profit), Valid: result.Success}
// storedBundle.SimRefundableValue = sql.NullString{String: dbIntToEth(&result.RefundableValue), Valid: result.Success}
// storedBundle.SimGasUsed = sql.NullInt64{Int64: int64(result.GasUsed), Valid: true}
// }
// if storedBundle.SimTotalSimCount.Valid {
// storedBundle.SimAllSimsGasUsed = sql.NullInt64{Int64: storedBundle.SimAllSimsGasUsed.Int64 + int64(result.GasUsed), Valid: true}
// } else {
// storedBundle.SimAllSimsGasUsed = sql.NullInt64{Int64: int64(result.GasUsed), Valid: true}
// }
// if storedBundle.SimTotalSimCount.Valid {
// storedBundle.SimTotalSimCount = sql.NullInt64{Int64: storedBundle.SimTotalSimCount.Int64 + 1, Valid: true}
// } else {
// storedBundle.SimTotalSimCount = sql.NullInt64{Int64: 1, Valid: true}
// }
// 2. update bundle
// NOTE: we update bundle body as well to make sure we have the latest bundle body in the db.
// since we are processing bundle every block (and thus updating in database every block) we'll
// have bundle body with the biggest maxBlock in database, which is the desired behavior.
// There are cornercases when system crashes, so we do not record latest bundle inclusion in db
storedBundle.Body = dbBundle.Body
_, err := dbTx.NamedStmtContext(ctx, b.updateBundleSim).ExecContext(ctx, storedBundle)
if err != nil {
_ = dbTx.Rollback()
return known, err
}
_ = dbTx.Commit()
return known, nil
}
_ = dbTx.Rollback()
return known, err
}
// insert body
bodyElements := make([]DBSbundleBody, len(bundle.Metadata.BodyHashes))
for i, hash := range bundle.Metadata.BodyHashes {
var bodyType int
if i < len(bundle.Body) {
if bundle.Body[i].Tx != nil {
bodyType = 1
}
}
bodyElements[i] = DBSbundleBody{Hash: bundle.Metadata.RequestHash.Bytes(), ElementHash: hash.Bytes(), Idx: i, Type: bodyType}
}
_, err = dbTx.NamedExecContext(ctx, insertBundleBodyQuery, bodyElements)
if err != nil {
_ = dbTx.Rollback()
return known, err
}
return known, dbTx.Commit()
}
func (b *DBBackend) InsertPreconf(ctx context.Context, preconf *ConfirmRequestArgs) error {
var dbPreconf DBSpreconf
dbPreconf.Hash = preconf.Preconf.Hash.Bytes()
dbPreconf.Block = int64(uint64(preconf.Preconf.Block))
byteSignature, err := json.Marshal(preconf.Signature)
if err != nil {
return err
}
dbPreconf.Signature = byteSignature
dbPreconf.Time = 0
_, err = b.insertPreconf.ExecContext(ctx, dbPreconf)
if err != nil {
fmt.Printf("error writing to preconf db")
return err
}
return err
}
func (b *DBBackend) InsertHistoricalHint(ctx context.Context, currentBlock uint64, hint *Hint) error {
var dbHint DBSbundleHistoricalHint
dbHint.Block = int64(currentBlock)
byteHint, err := json.Marshal(hint)
if err != nil {
return err
}
dbHint.Hint = byteHint
_, err = b.insertHint.ExecContext(ctx, dbHint)
return err
}
func (b *DBBackend) Close() error {
return b.db.Close()
}