-
Notifications
You must be signed in to change notification settings - Fork 211
/
atxs.go
672 lines (614 loc) · 19.7 KB
/
atxs.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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
package atxs
import (
"context"
"fmt"
"time"
"github.com/spacemeshos/go-spacemesh/codec"
"github.com/spacemeshos/go-spacemesh/common/types"
"github.com/spacemeshos/go-spacemesh/sql"
"github.com/spacemeshos/go-spacemesh/sql/builder"
)
const (
CacheKindEpochATXs sql.QueryCacheKind = "epoch-atxs"
CacheKindATXBlob sql.QueryCacheKind = "atx-blob"
)
const fullQuery = `select id, atx, base_tick_height, tick_count, pubkey,
effective_num_units, received, epoch, sequence, coinbase, validity from atxs`
type decoderCallback func(*types.VerifiedActivationTx, error) bool
func decoder(fn decoderCallback) sql.Decoder {
return func(stmt *sql.Statement) bool {
var (
a types.ActivationTx
id types.ATXID
)
stmt.ColumnBytes(0, id[:])
checkpointed := stmt.ColumnLen(1) == 0
if !checkpointed {
if _, err := codec.DecodeFrom(stmt.ColumnReader(1), &a); err != nil {
return fn(nil, fmt.Errorf("decode %w", err))
}
}
a.SetID(id)
baseTickHeight := uint64(stmt.ColumnInt64(2))
tickCount := uint64(stmt.ColumnInt64(3))
stmt.ColumnBytes(4, a.SmesherID[:])
effectiveNumUnits := uint32(stmt.ColumnInt32(5))
a.SetEffectiveNumUnits(effectiveNumUnits)
if checkpointed {
a.SetGolden()
a.NumUnits = effectiveNumUnits
a.SetReceived(time.Time{})
} else {
a.SetReceived(time.Unix(0, stmt.ColumnInt64(6)).Local())
}
a.PublishEpoch = types.EpochID(uint32(stmt.ColumnInt(7)))
a.Sequence = uint64(stmt.ColumnInt64(8))
stmt.ColumnBytes(9, a.Coinbase[:])
a.SetValidity(types.Validity(stmt.ColumnInt(10)))
v, err := a.Verify(baseTickHeight, tickCount)
if err != nil {
return fn(nil, err)
}
return fn(v, nil)
}
}
func load(db sql.Executor, query string, enc sql.Encoder) (*types.VerifiedActivationTx, error) {
var (
v *types.VerifiedActivationTx
derr error
)
_, err := db.Exec(query, enc, decoder(func(atx *types.VerifiedActivationTx, err error) bool {
v = atx
derr = err
return derr == nil
}))
if err == nil && derr != nil {
err = derr
}
return v, err
}
// Get gets an ATX by a given ATX ID.
func Get(db sql.Executor, id types.ATXID) (*types.VerifiedActivationTx, error) {
enc := func(stmt *sql.Statement) {
stmt.BindBytes(1, id.Bytes())
}
q := fmt.Sprintf("%v where id =?1;", fullQuery)
v, err := load(db, q, enc)
if err != nil {
return nil, fmt.Errorf("get id %s: %w", id.String(), err)
}
if v == nil {
return nil, fmt.Errorf("get id %s: %w", id.String(), sql.ErrNotFound)
}
return v, nil
}
// GetByEpochAndNodeID gets any ATX by the specified NodeID published in the given epoch.
func GetByEpochAndNodeID(
db sql.Executor,
epoch types.EpochID,
nodeID types.NodeID,
) (*types.VerifiedActivationTx, error) {
enc := func(stmt *sql.Statement) {
stmt.BindInt64(1, int64(epoch))
stmt.BindBytes(2, nodeID.Bytes())
}
q := fmt.Sprintf("%v where epoch = ?1 and pubkey = ?2 limit 1;", fullQuery)
v, err := load(db, q, enc)
if err != nil {
return nil, fmt.Errorf("get by epoch %v nid %s: %w", epoch, nodeID.String(), err)
}
if v == nil {
return nil, fmt.Errorf("get by epoch %v nid %s: %w", epoch, nodeID.String(), sql.ErrNotFound)
}
return v, nil
}
// Has checks if an ATX exists by a given ATX ID.
func Has(db sql.Executor, id types.ATXID) (bool, error) {
rows, err := db.Exec("select 1 from atxs where id = ?1;",
func(stmt *sql.Statement) {
stmt.BindBytes(1, id.Bytes())
}, nil,
)
if err != nil {
return false, fmt.Errorf("exec id %v: %w", id, err)
}
return rows > 0, nil
}
func CommitmentATX(db sql.Executor, nodeID types.NodeID) (id types.ATXID, err error) {
enc := func(stmt *sql.Statement) {
stmt.BindBytes(1, nodeID.Bytes())
}
dec := func(stmt *sql.Statement) bool {
stmt.ColumnBytes(0, id[:])
return true
}
if rows, err := db.Exec(`
select commitment_atx from atxs
where pubkey = ?1 and commitment_atx is not null
order by epoch desc
limit 1;`, enc, dec); err != nil {
return types.ATXID{}, fmt.Errorf("exec nodeID %v: %w", nodeID, err)
} else if rows == 0 {
return types.ATXID{}, fmt.Errorf("exec nodeID %s: %w", nodeID, sql.ErrNotFound)
}
return id, err
}
// GetFirstIDByNodeID gets the initial ATX ID for a given node ID.
func GetFirstIDByNodeID(db sql.Executor, nodeID types.NodeID) (id types.ATXID, err error) {
enc := func(stmt *sql.Statement) {
stmt.BindBytes(1, nodeID.Bytes())
}
dec := func(stmt *sql.Statement) bool {
stmt.ColumnBytes(0, id[:])
return true
}
if rows, err := db.Exec(`
select id from atxs
where pubkey = ?1
order by epoch asc
limit 1;`, enc, dec); err != nil {
return types.ATXID{}, fmt.Errorf("exec nodeID %v: %w", nodeID, err)
} else if rows == 0 {
return types.ATXID{}, fmt.Errorf("exec nodeID %s: %w", nodeID, sql.ErrNotFound)
}
return id, err
}
// GetLastIDByNodeID gets the last ATX ID for a given node ID.
func GetLastIDByNodeID(db sql.Executor, nodeID types.NodeID) (id types.ATXID, err error) {
enc := func(stmt *sql.Statement) {
stmt.BindBytes(1, nodeID.Bytes())
}
dec := func(stmt *sql.Statement) bool {
stmt.ColumnBytes(0, id[:])
return true
}
if rows, err := db.Exec(`
select id from atxs
where pubkey = ?1
order by epoch desc, received desc
limit 1;`, enc, dec); err != nil {
return types.ATXID{}, fmt.Errorf("exec nodeID %s: %w", nodeID, err)
} else if rows == 0 {
return types.ATXID{}, fmt.Errorf("exec nodeID %s: %w", nodeID, sql.ErrNotFound)
}
return id, err
}
// GetIDByEpochAndNodeID gets an ATX ID for a given epoch and node ID.
func GetIDByEpochAndNodeID(db sql.Executor, epoch types.EpochID, nodeID types.NodeID) (id types.ATXID, err error) {
enc := func(stmt *sql.Statement) {
stmt.BindInt64(1, int64(epoch))
stmt.BindBytes(2, nodeID.Bytes())
}
dec := func(stmt *sql.Statement) bool {
stmt.ColumnBytes(0, id[:])
return true
}
if rows, err := db.Exec(`
select id from atxs
where epoch = ?1 and pubkey = ?2
limit 1;`, enc, dec); err != nil {
return types.ATXID{}, fmt.Errorf("exec nodeID %v: %w", nodeID, err)
} else if rows == 0 {
return types.ATXID{}, fmt.Errorf("exec nodeID %s: %w", nodeID, sql.ErrNotFound)
}
return id, err
}
// IterateIDsByEpoch invokes the specified callback for each ATX ID in a given epoch.
// It stops if the callback returns an error.
func IterateIDsByEpoch(
db sql.Executor,
epoch types.EpochID,
callback func(total int, id types.ATXID) error,
) error {
if sql.IsCached(db) {
// If the slices are cached, let's not do more SELECTs
ids, err := GetIDsByEpoch(context.Background(), db, epoch)
if err != nil {
return err
}
for _, id := range ids {
if err := callback(len(ids), id); err != nil {
return err
}
}
return nil
}
var callbackErr error
enc := func(stmt *sql.Statement) {
stmt.BindInt64(1, int64(epoch))
}
dec := func(stmt *sql.Statement) bool {
var id types.ATXID
total := stmt.ColumnInt(0)
stmt.ColumnBytes(1, id[:])
if callbackErr = callback(total, id); callbackErr != nil {
return false
}
return true
}
// Get total count in the same select statement to avoid the need for transaction
if _, err := db.Exec(
"select (select count(*) from atxs where epoch = ?1) as total, id from atxs where epoch = ?1;",
enc, dec,
); err != nil {
return fmt.Errorf("exec epoch %v: %w", epoch, err)
}
return callbackErr
}
// GetIDsByEpoch gets ATX IDs for a given epoch.
func GetIDsByEpoch(ctx context.Context, db sql.Executor, epoch types.EpochID) (ids []types.ATXID, err error) {
cacheKey := sql.QueryCacheKey(CacheKindEpochATXs, epoch.String())
return sql.WithCachedValue(ctx, db, cacheKey, func(context.Context) (ids []types.ATXID, err error) {
enc := func(stmt *sql.Statement) {
stmt.BindInt64(1, int64(epoch))
}
dec := func(stmt *sql.Statement) bool {
var id types.ATXID
stmt.ColumnBytes(0, id[:])
ids = append(ids, id)
return true
}
if rows, err := db.Exec("select id from atxs where epoch = ?1;", enc, dec); err != nil {
return nil, fmt.Errorf("exec epoch %v: %w", epoch, err)
} else if rows == 0 {
return []types.ATXID{}, nil
}
return ids, nil
})
}
// VRFNonce gets the VRF nonce of a smesher for a given epoch.
func VRFNonce(db sql.Executor, id types.NodeID, epoch types.EpochID) (nonce types.VRFPostIndex, err error) {
enc := func(stmt *sql.Statement) {
stmt.BindBytes(1, id.Bytes())
stmt.BindInt64(2, int64(epoch))
}
dec := func(stmt *sql.Statement) bool {
nonce = types.VRFPostIndex(stmt.ColumnInt64(0))
return true
}
if rows, err := db.Exec(`
select nonce from atxs
where pubkey = ?1 and epoch < ?2 and nonce is not null
order by epoch desc
limit 1;`, enc, dec); err != nil {
return types.VRFPostIndex(0), fmt.Errorf("exec id %v, epoch %d: %w", id, epoch, err)
} else if rows == 0 {
return types.VRFPostIndex(0), fmt.Errorf("exec id %v, epoch %d: %w", id, epoch, sql.ErrNotFound)
}
return nonce, err
}
// GetBlobSizes returns the sizes of the blobs corresponding to ATXs with specified
// ids. For non-existent ATXs, the corresponding items are set to -1.
func GetBlobSizes(db sql.Executor, ids [][]byte) (sizes []int, err error) {
return sql.GetBlobSizes(db, "select id, length(atx) from atxs where id in", ids)
}
// LoadBlob loads ATX as an encoded blob, ready to be sent over the wire.
func LoadBlob(ctx context.Context, db sql.Executor, id []byte, blob *sql.Blob) error {
if sql.IsCached(db) {
b, err := getBlob(ctx, db, id)
if err != nil {
return err
}
blob.Bytes = b
return nil
}
return sql.LoadBlob(db, "select atx from atxs where id = ?1", id, blob)
}
func getBlob(ctx context.Context, db sql.Executor, id []byte) (buf []byte, err error) {
cacheKey := sql.QueryCacheKey(CacheKindATXBlob, string(id))
return sql.WithCachedValue(ctx, db, cacheKey, func(context.Context) ([]byte, error) {
if rows, err := db.Exec("select atx from atxs where id = ?1",
func(stmt *sql.Statement) {
stmt.BindBytes(1, id)
}, func(stmt *sql.Statement) bool {
if stmt.ColumnLen(0) > 0 {
buf = make([]byte, stmt.ColumnLen(0))
stmt.ColumnBytes(0, buf)
}
return true
}); err != nil {
return nil, fmt.Errorf("get %s: %w", types.BytesToHash(id), err)
} else if rows == 0 {
return nil, fmt.Errorf("%w: atx %s", sql.ErrNotFound, types.BytesToHash(id))
}
return buf, nil
})
}
// Add adds an ATX for a given ATX ID.
func Add(db sql.Executor, atx *types.VerifiedActivationTx) error {
buf, err := codec.Encode(atx.ActivationTx)
if err != nil {
return fmt.Errorf("encode: %w", err)
}
enc := func(stmt *sql.Statement) {
stmt.BindBytes(1, atx.ID().Bytes())
stmt.BindInt64(2, int64(atx.PublishEpoch))
stmt.BindInt64(3, int64(atx.EffectiveNumUnits()))
if atx.CommitmentATX != nil {
stmt.BindBytes(4, atx.CommitmentATX.Bytes())
} else {
stmt.BindNull(4)
}
if atx.VRFNonce != nil {
stmt.BindInt64(5, int64(*atx.VRFNonce))
} else {
stmt.BindNull(5)
}
stmt.BindBytes(6, atx.SmesherID.Bytes())
stmt.BindBytes(7, buf)
stmt.BindInt64(8, atx.Received().UnixNano())
stmt.BindInt64(9, int64(atx.BaseTickHeight()))
stmt.BindInt64(10, int64(atx.TickCount()))
stmt.BindInt64(11, int64(atx.Sequence))
stmt.BindBytes(12, atx.Coinbase.Bytes())
stmt.BindInt64(13, int64(atx.Validity()))
}
_, err = db.Exec(`
insert into atxs (id, epoch, effective_num_units, commitment_atx, nonce,
pubkey, atx, received, base_tick_height, tick_count, sequence, coinbase, validity)
values (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13);`, enc, nil)
if err != nil {
return fmt.Errorf("insert ATX ID %v: %w", atx.ID(), err)
}
return nil
}
// AtxAdded updates epoch query cache with new ATX, if the query cache is enabled.
func AtxAdded(db sql.Executor, atx *types.VerifiedActivationTx) {
epochCacheKey := sql.QueryCacheKey(CacheKindEpochATXs, atx.PublishEpoch.String())
sql.AppendToCachedSlice(db, epochCacheKey, atx.ID())
}
type Filter func(types.ATXID) bool
func FilterAll(types.ATXID) bool { return true }
// GetIDWithMaxHeight returns the ID of the atx from the last 2 epoch with the highest (or tied for the highest)
// tick height. It is possible that some poet servers are faster than others and the network ends up having its
// highest ticked atx still in previous epoch and the atxs building on top of it have not been published yet.
// Selecting from the last two epochs to strike a balance between being fair to honest miners while not giving
// unfair advantage for malicious actors who retroactively publish a high tick atx many epochs back.
func GetIDWithMaxHeight(db sql.Executor, pref types.NodeID, filter Filter) (types.ATXID, error) {
if filter == nil {
filter = FilterAll
}
var (
rst types.ATXID
highest uint64
)
dec := func(stmt *sql.Statement) bool {
var id types.ATXID
stmt.ColumnBytes(0, id[:])
height := uint64(stmt.ColumnInt64(1))
switch {
case height < highest:
// Results are ordered by height, so we can stop once we see a lower height.
return false
case height > highest && filter(id):
highest = height
rst = id
// We can stop on the first ATX if `pref` is empty.
return pref != types.EmptyNodeID
case height == highest && filter(id):
// prefer atxs from `pref`
var smesher types.NodeID
stmt.ColumnBytes(2, smesher[:])
if smesher == pref {
rst = id
return false
}
return true
}
return true
}
_, err := db.Exec(`
SELECT id, base_tick_height + tick_count AS height, pubkey
FROM atxs LEFT JOIN identities using(pubkey)
WHERE identities.pubkey is null and epoch >= (select max(epoch) from atxs)-1
ORDER BY height DESC, epoch DESC;`, nil, dec)
switch {
case err != nil:
return types.ATXID{}, fmt.Errorf("selecting high-tick atx: %w", err)
case rst == types.EmptyATXID:
return types.ATXID{}, fmt.Errorf("selecting high-tick atx: %w", sql.ErrNotFound)
}
return rst, nil
}
type CheckpointAtx struct {
ID types.ATXID
Epoch types.EpochID
CommitmentATX types.ATXID
VRFNonce types.VRFPostIndex
NumUnits uint32
BaseTickHeight uint64
TickCount uint64
SmesherID types.NodeID
Sequence uint64
Coinbase types.Address
}
// LatestN returns the latest N ATXs per smesher.
func LatestN(db sql.Executor, n int) ([]CheckpointAtx, error) {
var rst []CheckpointAtx
enc := func(stmt *sql.Statement) {
stmt.BindInt64(1, int64(n))
}
dec := func(stmt *sql.Statement) bool {
var catx CheckpointAtx
stmt.ColumnBytes(0, catx.ID[:])
catx.Epoch = types.EpochID(uint32(stmt.ColumnInt64(1)))
catx.NumUnits = uint32(stmt.ColumnInt64(2))
catx.BaseTickHeight = uint64(stmt.ColumnInt64(3))
catx.TickCount = uint64(stmt.ColumnInt64(4))
stmt.ColumnBytes(5, catx.SmesherID[:])
catx.Sequence = uint64(stmt.ColumnInt64(6))
stmt.ColumnBytes(7, catx.Coinbase[:])
rst = append(rst, catx)
return true
}
if rows, err := db.Exec(`
select id, epoch, effective_num_units, base_tick_height, tick_count, pubkey, sequence, coinbase
from (
select row_number() over (partition by pubkey order by epoch desc) RowNum,
id, epoch, effective_num_units, base_tick_height, tick_count, pubkey, sequence, coinbase from atxs
)
where RowNum <= ?1 order by pubkey;`, enc, dec); err != nil {
return nil, fmt.Errorf("latestN: %w", err)
} else if rows == 0 {
return nil, sql.ErrNotFound
}
return rst, nil
}
func AddCheckpointed(db sql.Executor, catx *CheckpointAtx) error {
enc := func(stmt *sql.Statement) {
stmt.BindBytes(1, catx.ID.Bytes())
stmt.BindInt64(2, int64(catx.Epoch))
stmt.BindInt64(3, int64(catx.NumUnits))
stmt.BindBytes(4, catx.CommitmentATX.Bytes())
stmt.BindInt64(5, int64(catx.VRFNonce))
stmt.BindInt64(6, int64(catx.BaseTickHeight))
stmt.BindInt64(7, int64(catx.TickCount))
stmt.BindInt64(8, int64(catx.Sequence))
stmt.BindBytes(9, catx.SmesherID.Bytes())
stmt.BindBytes(10, catx.Coinbase.Bytes())
}
_, err := db.Exec(`
insert into atxs (id, epoch, effective_num_units, commitment_atx, nonce,
base_tick_height, tick_count, sequence, pubkey, coinbase, received)
values (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, 0);`, enc, nil)
if err != nil {
return fmt.Errorf("insert checkpoint ATX %v: %w", catx.ID, err)
}
return nil
}
// All gets all atx IDs.
func All(db sql.Executor) ([]types.ATXID, error) {
var all []types.ATXID
dec := func(stmt *sql.Statement) bool {
var id types.ATXID
stmt.ColumnBytes(0, id[:])
all = append(all, id)
return true
}
if _, err := db.Exec("select id from atxs order by epoch asc;", nil, dec); err != nil {
return nil, fmt.Errorf("all atxs: %w", err)
}
return all, nil
}
// LatestEpoch with atxs.
func LatestEpoch(db sql.Executor) (types.EpochID, error) {
var epoch types.EpochID
if _, err := db.Exec("select max(epoch) from atxs;",
nil,
func(stmt *sql.Statement) bool {
epoch = types.EpochID(uint32(stmt.ColumnInt64(0)))
return true
}); err != nil {
return epoch, fmt.Errorf("latest epoch: %w", err)
}
return epoch, nil
}
// IterateAtxsData iterate over data used for consensus.
func IterateAtxsData(
db sql.Executor,
from, to types.EpochID,
fn func(
id types.ATXID,
node types.NodeID,
epoch types.EpochID,
coinbase types.Address,
weight uint64,
base uint64,
height uint64,
) bool,
) error {
_, err := db.Exec(
`select id, pubkey, epoch, coinbase, effective_num_units, base_tick_height, tick_count
from atxs where epoch between ?1 and ?2;`,
func(stmt *sql.Statement) {
stmt.BindInt64(1, int64(from.Uint32()))
stmt.BindInt64(2, int64(to.Uint32()))
},
func(stmt *sql.Statement) bool {
var id types.ATXID
stmt.ColumnBytes(0, id[:])
var node types.NodeID
stmt.ColumnBytes(1, node[:])
epoch := types.EpochID(uint32(stmt.ColumnInt64(2)))
var coinbase types.Address
stmt.ColumnBytes(3, coinbase[:])
effectiveUnits := uint64(stmt.ColumnInt64(4))
baseHeight := uint64(stmt.ColumnInt64(5))
ticks := uint64(stmt.ColumnInt64(6))
return fn(id, node, epoch, coinbase, effectiveUnits*ticks, baseHeight, baseHeight+ticks)
},
)
if err != nil {
return fmt.Errorf("iterate atx fields: %w", err)
}
return nil
}
func SetValidity(db sql.Executor, id types.ATXID, validity types.Validity) error {
_, err := db.Exec("UPDATE atxs SET validity = ?1 where id = ?2;",
func(stmt *sql.Statement) {
stmt.BindInt64(1, int64(validity))
stmt.BindBytes(2, id.Bytes())
}, nil,
)
if err != nil {
return fmt.Errorf("setting validity %v: %w", id, err)
}
return nil
}
func IterateAtxsOps(
db sql.Executor,
operations builder.Operations,
fn func(*types.VerifiedActivationTx) bool,
) error {
var derr error
_, err := db.Exec(
fullQuery+builder.FilterFrom(operations),
builder.BindingsFrom(operations),
decoder(func(atx *types.VerifiedActivationTx, err error) bool {
if atx != nil {
return fn(atx)
}
derr = err
return derr == nil
}))
if err != nil {
return err
}
return derr
}
func CountAtxsByOps(db sql.Executor, operations builder.Operations) (count uint32, err error) {
_, err = db.Exec(
"SELECT count(*) FROM atxs"+builder.FilterFrom(operations),
builder.BindingsFrom(operations),
func(stmt *sql.Statement) bool {
count = uint32(stmt.ColumnInt32(0))
return true
},
)
return
}
// IterateForGrading selects every atx from publish epoch and joins identities to load malfeasence proofs if they exist.
func IterateForGrading(
db sql.Executor,
epoch types.EpochID,
fn func(id types.ATXID, atxtime, prooftime int64, weight uint64) bool,
) error {
if _, err := db.Exec(`
select atxs.id, atxs.received, identities.received, effective_num_units, tick_count from atxs
left join identities on atxs.pubkey = identities.pubkey
where atxs.epoch == ?1;`,
func(stmt *sql.Statement) {
stmt.BindInt64(1, int64(epoch))
}, func(stmt *sql.Statement) bool {
id := types.ATXID{}
stmt.ColumnBytes(0, id[:])
atxtime := stmt.ColumnInt64(1)
prooftime := stmt.ColumnInt64(2)
units := uint64(stmt.ColumnInt64(3))
ticks := uint64(stmt.ColumnInt64(4))
return fn(id, atxtime, prooftime, units*ticks)
}); err != nil {
return fmt.Errorf("iterate for grading: %w", err)
}
return nil
}