forked from stellar/go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
verify.go
646 lines (571 loc) · 17.1 KB
/
verify.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
package ingest
import (
"context"
"database/sql"
"fmt"
"time"
"github.com/guregu/null"
"github.com/stellar/go/ingest"
"github.com/stellar/go/services/horizon/internal/db2"
"github.com/stellar/go/services/horizon/internal/db2/history"
"github.com/stellar/go/services/horizon/internal/ingest/processors"
"github.com/stellar/go/services/horizon/internal/ingest/verify"
"github.com/stellar/go/support/errors"
logpkg "github.com/stellar/go/support/log"
"github.com/stellar/go/xdr"
)
const verifyBatchSize = 50000
const assetStatsBatchSize = 500
// stateVerifierExpectedIngestionVersion defines a version of ingestion system
// required by state verifier. This is done to prevent situations where
// ingestion has been updated with new features but state verifier does not
// check them.
// There is a test that checks it, to fix it: update the actual `verifyState`
// method instead of just updating this value!
const stateVerifierExpectedIngestionVersion = 15
// verifyState is called as a go routine from pipeline post hook every 64
// ledgers. It checks if the state is correct. If another go routine is already
// running it exits.
func (s *system) verifyState(verifyAgainstLatestCheckpoint bool) error {
s.stateVerificationMutex.Lock()
if s.stateVerificationRunning {
log.Warn("State verification is already running...")
s.stateVerificationMutex.Unlock()
return nil
}
s.stateVerificationRunning = true
s.stateVerificationMutex.Unlock()
defer func() {
s.stateVerificationMutex.Lock()
s.stateVerificationRunning = false
s.stateVerificationMutex.Unlock()
}()
updateMetrics := false
if stateVerifierExpectedIngestionVersion != CurrentVersion {
log.Errorf(
"State verification expected version is %d but actual is: %d",
stateVerifierExpectedIngestionVersion,
CurrentVersion,
)
return nil
}
historyQ := s.historyQ.CloneIngestionQ()
defer historyQ.Rollback()
err := historyQ.BeginTx(&sql.TxOptions{
Isolation: sql.LevelRepeatableRead,
ReadOnly: true,
})
if err != nil {
return errors.Wrap(err, "Error starting transaction")
}
// Ensure the ledger is a checkpoint ledger
ledgerSequence, err := historyQ.GetLastLedgerIngestNonBlocking(s.ctx)
if err != nil {
return errors.Wrap(err, "Error running historyQ.GetLastLedgerIngestNonBlocking")
}
localLog := log.WithFields(logpkg.F{
"subservice": "state_verify",
"sequence": ledgerSequence,
})
if !s.checkpointManager.IsCheckpoint(ledgerSequence) {
localLog.Info("Current ledger is not a checkpoint ledger. Cancelling...")
return nil
}
localLog.Info("Starting state verification")
if verifyAgainstLatestCheckpoint {
retries := 0
for {
// Get root HAS to check if we're checking one of the latest ledgers or
// Horizon is catching up. It doesn't make sense to verify old ledgers as
// we want to check the latest state.
var historyLatestSequence uint32
historyLatestSequence, err = s.historyAdapter.GetLatestLedgerSequence()
if err != nil {
return errors.Wrap(err, "Error getting the latest ledger sequence")
}
if ledgerSequence < historyLatestSequence {
localLog.Info("Current ledger is old. Cancelling...")
return nil
}
if ledgerSequence == historyLatestSequence {
break
}
localLog.Info("Waiting for stellar-core to publish HAS...")
select {
case <-s.ctx.Done():
localLog.Info("State verifier shut down...")
return nil
case <-time.After(5 * time.Second):
// Wait for stellar-core to publish HAS
retries++
if retries == 12 {
localLog.Info("Checkpoint not published. Cancelling...")
return nil
}
}
}
}
startTime := time.Now()
defer func() {
duration := time.Since(startTime).Seconds()
if updateMetrics {
// Don't update metrics if context cancelled.
if s.ctx.Err() != context.Canceled {
s.Metrics().StateVerifyDuration.Observe(float64(duration))
}
}
log.WithField("duration", duration).Info("State verification finished")
}()
localLog.Info("Creating state reader...")
stateReader, err := s.historyAdapter.GetState(s.ctx, ledgerSequence)
if err != nil {
return errors.Wrap(err, "Error running GetState")
}
defer stateReader.Close()
verifier := &verify.StateVerifier{
StateReader: stateReader,
}
assetStats := processors.AssetStatSet{}
total := 0
for {
var keys []xdr.LedgerKey
keys, err = verifier.GetLedgerKeys(verifyBatchSize)
if err != nil {
return errors.Wrap(err, "verifier.GetLedgerKeys")
}
if len(keys) == 0 {
break
}
accounts := make([]string, 0, verifyBatchSize)
data := make([]xdr.LedgerKeyData, 0, verifyBatchSize)
offers := make([]int64, 0, verifyBatchSize)
trustLines := make([]xdr.LedgerKeyTrustLine, 0, verifyBatchSize)
cBalances := make([]xdr.ClaimableBalanceId, 0, verifyBatchSize)
for _, key := range keys {
switch key.Type {
case xdr.LedgerEntryTypeAccount:
accounts = append(accounts, key.Account.AccountId.Address())
case xdr.LedgerEntryTypeData:
data = append(data, *key.Data)
case xdr.LedgerEntryTypeOffer:
offers = append(offers, int64(key.Offer.OfferId))
case xdr.LedgerEntryTypeTrustline:
trustLines = append(trustLines, *key.TrustLine)
case xdr.LedgerEntryTypeClaimableBalance:
cBalances = append(cBalances, key.ClaimableBalance.BalanceId)
default:
return errors.New("GetLedgerKeys return unexpected type")
}
}
err = addAccountsToStateVerifier(s.ctx, verifier, historyQ, accounts)
if err != nil {
return errors.Wrap(err, "addAccountsToStateVerifier failed")
}
err = addDataToStateVerifier(s.ctx, verifier, historyQ, data)
if err != nil {
return errors.Wrap(err, "addDataToStateVerifier failed")
}
err = addOffersToStateVerifier(s.ctx, verifier, historyQ, offers)
if err != nil {
return errors.Wrap(err, "addOffersToStateVerifier failed")
}
err = addTrustLinesToStateVerifier(s.ctx, verifier, assetStats, historyQ, trustLines)
if err != nil {
return errors.Wrap(err, "addTrustLinesToStateVerifier failed")
}
err = addClaimableBalanceToStateVerifier(s.ctx, verifier, assetStats, historyQ, cBalances)
if err != nil {
return errors.Wrap(err, "addClaimableBalanceToStateVerifier failed")
}
total += len(keys)
localLog.WithField("total", total).Info("Batch added to StateVerifier")
}
localLog.WithField("total", total).Info("Finished writing to StateVerifier")
countAccounts, err := historyQ.CountAccounts(s.ctx)
if err != nil {
return errors.Wrap(err, "Error running historyQ.CountAccounts")
}
countData, err := historyQ.CountAccountsData(s.ctx)
if err != nil {
return errors.Wrap(err, "Error running historyQ.CountData")
}
countOffers, err := historyQ.CountOffers(s.ctx)
if err != nil {
return errors.Wrap(err, "Error running historyQ.CountOffers")
}
countTrustLines, err := historyQ.CountTrustLines(s.ctx)
if err != nil {
return errors.Wrap(err, "Error running historyQ.CountTrustLines")
}
countClaimableBalances, err := historyQ.CountClaimableBalances(s.ctx)
if err != nil {
return errors.Wrap(err, "Error running historyQ.CountClaimableBalances")
}
err = verifier.Verify(countAccounts + countData + countOffers + countTrustLines + countClaimableBalances)
if err != nil {
return errors.Wrap(err, "verifier.Verify failed")
}
err = checkAssetStats(s.ctx, assetStats, historyQ)
if err != nil {
return errors.Wrap(err, "checkAssetStats failed")
}
localLog.Info("State correct")
updateMetrics = true
return nil
}
func checkAssetStats(ctx context.Context, set processors.AssetStatSet, q history.IngestionQ) error {
page := db2.PageQuery{
Order: "asc",
Limit: assetStatsBatchSize,
}
for {
assetStats, err := q.GetAssetStats(ctx, "", "", page)
if err != nil {
return errors.Wrap(err, "could not fetch asset stats from db")
}
if len(assetStats) == 0 {
break
}
for _, assetStat := range assetStats {
fromSet, removed := set.Remove(assetStat.AssetType, assetStat.AssetCode, assetStat.AssetIssuer)
if !removed {
return ingest.NewStateError(
fmt.Errorf(
"db contains asset stat with code %s issuer %s which is missing from HAS",
assetStat.AssetCode, assetStat.AssetIssuer,
),
)
}
if fromSet != assetStat {
return ingest.NewStateError(
fmt.Errorf(
"db asset stat with code %s issuer %s does not match asset stat from HAS",
assetStat.AssetCode, assetStat.AssetIssuer,
),
)
}
}
page.Cursor = assetStats[len(assetStats)-1].PagingToken()
}
if len(set) > 0 {
return ingest.NewStateError(
fmt.Errorf(
"HAS contains %d more asset stats than db",
len(set),
),
)
}
return nil
}
func addAccountsToStateVerifier(ctx context.Context, verifier *verify.StateVerifier, q history.IngestionQ, ids []string) error {
if len(ids) == 0 {
return nil
}
accounts, err := q.GetAccountsByIDs(ctx, ids)
if err != nil {
return errors.Wrap(err, "Error running history.Q.GetAccountsByIDs")
}
signers, err := q.SignersForAccounts(ctx, ids)
if err != nil {
return errors.Wrap(err, "Error running history.Q.SignersForAccounts")
}
masterWeightMap := make(map[string]int32)
signersMap := make(map[string][]xdr.Signer)
// map[accountID]map[signerKey]sponsor
sponsoringSignersMap := make(map[string]map[string]string)
for _, row := range signers {
if row.Account == row.Signer {
masterWeightMap[row.Account] = row.Weight
} else {
signersMap[row.Account] = append(
signersMap[row.Account],
xdr.Signer{
Key: xdr.MustSigner(row.Signer),
Weight: xdr.Uint32(row.Weight),
},
)
if sponsoringSignersMap[row.Account] == nil {
sponsoringSignersMap[row.Account] = make(map[string]string)
}
sponsoringSignersMap[row.Account][row.Signer] = row.Sponsor.String
}
}
for _, row := range accounts {
var inflationDest *xdr.AccountId
if row.InflationDestination != "" {
t := xdr.MustAddress(row.InflationDestination)
inflationDest = &t
}
// Ensure master weight matches, if not it's a state error!
if int32(row.MasterWeight) != masterWeightMap[row.AccountID] {
return ingest.NewStateError(
fmt.Errorf(
"Master key weight in account %s does not match (expected=%d, actual=%d)",
row.AccountID,
masterWeightMap[row.AccountID],
int32(row.MasterWeight),
),
)
}
signers := xdr.SortSignersByKey(signersMap[row.AccountID])
signerSponsoringIDs := make([]xdr.SponsorshipDescriptor, len(signers))
for i, signer := range signers {
sponsor := sponsoringSignersMap[row.AccountID][signer.Key.Address()]
if sponsor != "" {
signerSponsoringIDs[i] = xdr.MustAddressPtr(sponsor)
}
}
account := &xdr.AccountEntry{
AccountId: xdr.MustAddress(row.AccountID),
Balance: xdr.Int64(row.Balance),
SeqNum: xdr.SequenceNumber(row.SequenceNumber),
NumSubEntries: xdr.Uint32(row.NumSubEntries),
InflationDest: inflationDest,
Flags: xdr.Uint32(row.Flags),
HomeDomain: xdr.String32(row.HomeDomain),
Thresholds: xdr.Thresholds{
row.MasterWeight,
row.ThresholdLow,
row.ThresholdMedium,
row.ThresholdHigh,
},
Signers: signers,
Ext: xdr.AccountEntryExt{
V: 1,
V1: &xdr.AccountEntryExtensionV1{
Liabilities: xdr.Liabilities{
Buying: xdr.Int64(row.BuyingLiabilities),
Selling: xdr.Int64(row.SellingLiabilities),
},
Ext: xdr.AccountEntryExtensionV1Ext{
V: 2,
V2: &xdr.AccountEntryExtensionV2{
NumSponsored: xdr.Uint32(row.NumSponsored),
NumSponsoring: xdr.Uint32(row.NumSponsoring),
SignerSponsoringIDs: signerSponsoringIDs,
},
},
},
},
}
entry := xdr.LedgerEntry{
LastModifiedLedgerSeq: xdr.Uint32(row.LastModifiedLedger),
Data: xdr.LedgerEntryData{
Type: xdr.LedgerEntryTypeAccount,
Account: account,
},
}
addLedgerEntrySponsor(&entry, row.Sponsor)
err = verifier.Write(entry)
if err != nil {
return err
}
}
return nil
}
func addDataToStateVerifier(ctx context.Context, verifier *verify.StateVerifier, q history.IngestionQ, keys []xdr.LedgerKeyData) error {
if len(keys) == 0 {
return nil
}
data, err := q.GetAccountDataByKeys(ctx, keys)
if err != nil {
return errors.Wrap(err, "Error running history.Q.GetAccountDataByKeys")
}
for _, row := range data {
entry := xdr.LedgerEntry{
LastModifiedLedgerSeq: xdr.Uint32(row.LastModifiedLedger),
Data: xdr.LedgerEntryData{
Type: xdr.LedgerEntryTypeData,
Data: &xdr.DataEntry{
AccountId: xdr.MustAddress(row.AccountID),
DataName: xdr.String64(row.Name),
DataValue: xdr.DataValue(row.Value),
},
},
}
addLedgerEntrySponsor(&entry, row.Sponsor)
err := verifier.Write(entry)
if err != nil {
return err
}
}
return nil
}
func addOffersToStateVerifier(
ctx context.Context,
verifier *verify.StateVerifier,
q history.IngestionQ,
ids []int64,
) error {
if len(ids) == 0 {
return nil
}
offers, err := q.GetOffersByIDs(ctx, ids)
if err != nil {
return errors.Wrap(err, "Error running history.Q.GetOfferByIDs")
}
for _, row := range offers {
entry := xdr.LedgerEntry{
LastModifiedLedgerSeq: xdr.Uint32(row.LastModifiedLedger),
Data: xdr.LedgerEntryData{
Type: xdr.LedgerEntryTypeOffer,
Offer: &xdr.OfferEntry{
SellerId: xdr.MustAddress(row.SellerID),
OfferId: xdr.Int64(row.OfferID),
Selling: row.SellingAsset,
Buying: row.BuyingAsset,
Amount: xdr.Int64(row.Amount),
Price: xdr.Price{
N: xdr.Int32(row.Pricen),
D: xdr.Int32(row.Priced),
},
Flags: xdr.Uint32(row.Flags),
},
},
}
addLedgerEntrySponsor(&entry, row.Sponsor)
err := verifier.Write(entry)
if err != nil {
return err
}
}
return nil
}
func addTrustLinesToStateVerifier(
ctx context.Context,
verifier *verify.StateVerifier,
assetStats processors.AssetStatSet,
q history.IngestionQ,
keys []xdr.LedgerKeyTrustLine,
) error {
if len(keys) == 0 {
return nil
}
trustLines, err := q.GetTrustLinesByKeys(ctx, keys)
if err != nil {
return errors.Wrap(err, "Error running history.Q.GetTrustLinesByKeys")
}
for _, row := range trustLines {
asset := xdr.MustNewCreditAsset(row.AssetCode, row.AssetIssuer)
trustline := xdr.TrustLineEntry{
AccountId: xdr.MustAddress(row.AccountID),
Asset: asset.ToTrustLineAsset(),
Balance: xdr.Int64(row.Balance),
Limit: xdr.Int64(row.Limit),
Flags: xdr.Uint32(row.Flags),
Ext: xdr.TrustLineEntryExt{
V: 1,
V1: &xdr.TrustLineEntryV1{
Liabilities: xdr.Liabilities{
Buying: xdr.Int64(row.BuyingLiabilities),
Selling: xdr.Int64(row.SellingLiabilities),
},
},
},
}
entry := xdr.LedgerEntry{
LastModifiedLedgerSeq: xdr.Uint32(row.LastModifiedLedger),
Data: xdr.LedgerEntryData{
Type: xdr.LedgerEntryTypeTrustline,
TrustLine: &trustline,
},
}
addLedgerEntrySponsor(&entry, row.Sponsor)
if err := verifier.Write(entry); err != nil {
return err
}
if err := assetStats.AddTrustline(
ingest.Change{
Post: &xdr.LedgerEntry{
Data: xdr.LedgerEntryData{
TrustLine: &trustline,
},
},
},
); err != nil {
return ingest.NewStateError(
errors.Wrap(err, "could not add trustline to asset stats"),
)
}
}
return nil
}
func addClaimableBalanceToStateVerifier(
ctx context.Context,
verifier *verify.StateVerifier,
assetStats processors.AssetStatSet,
q history.IngestionQ,
ids []xdr.ClaimableBalanceId,
) error {
if len(ids) == 0 {
return nil
}
cBalances, err := q.GetClaimableBalancesByID(ctx, ids)
if err != nil {
return errors.Wrap(err, "Error running history.Q.GetClaimableBalancesByID")
}
for _, row := range cBalances {
claimants := []xdr.Claimant{}
for _, claimant := range row.Claimants {
claimants = append(claimants, xdr.Claimant{
Type: xdr.ClaimantTypeClaimantTypeV0,
V0: &xdr.ClaimantV0{
Destination: xdr.MustAddress(claimant.Destination),
Predicate: claimant.Predicate,
},
})
}
claimants = xdr.SortClaimantsByDestination(claimants)
var cBalance = xdr.ClaimableBalanceEntry{
BalanceId: row.BalanceID,
Claimants: claimants,
Asset: row.Asset,
Amount: row.Amount,
}
if row.Flags != 0 {
cBalance.Ext = xdr.ClaimableBalanceEntryExt{
V: 1,
V1: &xdr.ClaimableBalanceEntryExtensionV1{
Flags: xdr.Uint32(row.Flags),
},
}
}
entry := xdr.LedgerEntry{
LastModifiedLedgerSeq: xdr.Uint32(row.LastModifiedLedger),
Data: xdr.LedgerEntryData{
Type: xdr.LedgerEntryTypeClaimableBalance,
ClaimableBalance: &cBalance,
},
}
addLedgerEntrySponsor(&entry, row.Sponsor)
if err := verifier.Write(entry); err != nil {
return err
}
if err := assetStats.AddClaimableBalance(
ingest.Change{
Post: &xdr.LedgerEntry{
Data: xdr.LedgerEntryData{
ClaimableBalance: &cBalance,
},
},
},
); err != nil {
return ingest.NewStateError(
errors.Wrap(err, "could not add claimable balance to asset stats"),
)
}
}
return nil
}
func addLedgerEntrySponsor(entry *xdr.LedgerEntry, sponsor null.String) {
ledgerEntrySponsor := xdr.SponsorshipDescriptor(nil)
if !sponsor.IsZero() {
ledgerEntrySponsor = xdr.MustAddressPtr(sponsor.String)
}
entry.Ext = xdr.LedgerEntryExt{
V: 1,
V1: &xdr.LedgerEntryExtensionV1{
SponsoringId: ledgerEntrySponsor,
},
}
}