-
Notifications
You must be signed in to change notification settings - Fork 464
/
store.go
1453 lines (1207 loc) · 40.8 KB
/
store.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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package chain
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"os"
"runtime/debug"
"sync"
lru "github.com/hashicorp/golang-lru/v2"
"github.com/ipld/go-car"
carutil "github.com/ipld/go-car/util"
carv2 "github.com/ipld/go-car/v2"
mh "github.com/multiformats/go-multihash"
"github.com/pkg/errors"
cbg "github.com/whyrusleeping/cbor-gen"
"go.opencensus.io/trace"
blocks "github.com/ipfs/go-block-format"
"github.com/ipfs/go-cid"
"github.com/ipfs/go-datastore"
blockstore "github.com/ipfs/go-ipfs-blockstore"
cbor "github.com/ipfs/go-ipld-cbor"
logging "github.com/ipfs/go-log/v2"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/go-state-types/network"
"github.com/filecoin-project/pubsub"
blockadt "github.com/filecoin-project/specs-actors/actors/util/adt"
"github.com/filecoin-project/venus/pkg/constants"
"github.com/filecoin-project/venus/pkg/metrics/tracing"
"github.com/filecoin-project/venus/pkg/repo"
"github.com/filecoin-project/venus/pkg/state"
"github.com/filecoin-project/venus/pkg/state/tree"
"github.com/filecoin-project/venus/pkg/util"
"github.com/filecoin-project/venus/venus-shared/actors/adt"
"github.com/filecoin-project/venus/venus-shared/actors/builtin"
_init "github.com/filecoin-project/venus/venus-shared/actors/builtin/init"
"github.com/filecoin-project/venus/venus-shared/actors/builtin/market"
"github.com/filecoin-project/venus/venus-shared/actors/builtin/miner"
"github.com/filecoin-project/venus/venus-shared/actors/builtin/multisig"
"github.com/filecoin-project/venus/venus-shared/actors/builtin/power"
"github.com/filecoin-project/venus/venus-shared/actors/builtin/reward"
"github.com/filecoin-project/venus/venus-shared/actors/builtin/verifreg"
"github.com/filecoin-project/venus/venus-shared/actors/policy"
blockstoreutil "github.com/filecoin-project/venus/venus-shared/blockstore"
"github.com/filecoin-project/venus/venus-shared/types"
)
// GenesisKey is the key at which the genesis Cid is written in the datastore.
var GenesisKey = datastore.NewKey("/consensus/genesisCid")
var log = logging.Logger("chain.store")
// HeadKey is the key at which the head tipset cid's are written in the datastore.
var HeadKey = datastore.NewKey("/chain/heaviestTipSet")
var ErrNotifeeDone = errors.New("notifee is done and should be removed")
type loadTipSetFunc func(context.Context, types.TipSetKey) (*types.TipSet, error)
// ReorgNotifee represents a callback that gets called upon reorgs.
type ReorgNotifee func(rev, app []*types.TipSet) error
var DefaultTipsetLruCacheSize = 10000
type reorg struct {
old []*types.TipSet
new []*types.TipSet
}
// CheckPoint is the key which the check-point written in the datastore.
var CheckPoint = datastore.NewKey("/chain/checkPoint")
// TSState export this func is just for gen cbor tool to work
type TSState struct {
StateRoot cid.Cid
Receipts cid.Cid
}
// Store is a generic implementation of the Store interface.
// It works(tm) for now.
type Store struct {
// ipldSource is a wrapper around ipld storage. It is used
// for reading filecoin block and state objects kept by the node.
stateAndBlockSource cbor.IpldStore
bsstore blockstoreutil.Blockstore
// ds is the datastore for the chain's private metadata which consists
// of the tipset key to state root cid mapping, and the heaviest tipset
// key.
ds repo.Datastore
// genesis is the CID of the genesis block.
genesis cid.Cid
// head is the tipset at the head of the best known chain.
head *types.TipSet
checkPoint types.TipSetKey
// Protects head and genesisCid.
mu sync.RWMutex
// headEvents is a pubsub channel that publishes an event every time the head changes.
// We operate under the assumption that tipsets published to this channel
// will always be queued and delivered to subscribers in the order discovered.
// Successive published tipsets may be supersets of previously published tipsets.
// TODO: rename to notifications. Also, reconsider ordering assumption depending
// on decisions made around the FC node notification system.
// TODO: replace this with a synchronous event bus
// https://github.com/filecoin-project/venus/issues/2309
headEvents *pubsub.PubSub
// Tracks tipsets by height/parentset for use by expected consensus.
tipIndex *TipStateCache
circulatingSupplyCalculator ICirculatingSupplyCalcualtor
chainIndex *ChainIndex
reorgCh chan reorg
reorgNotifeeCh chan ReorgNotifee
tsCache *lru.ARCCache[types.TipSetKey, *types.TipSet]
}
// NewStore constructs a new default store.
func NewStore(chainDs repo.Datastore,
bsstore blockstoreutil.Blockstore,
genesisCid cid.Cid,
circulatiingSupplyCalculator ICirculatingSupplyCalcualtor,
) *Store {
tsCache, _ := lru.NewARC[types.TipSetKey, *types.TipSet](DefaultTipsetLruCacheSize)
store := &Store{
stateAndBlockSource: cbor.NewCborStore(bsstore),
ds: chainDs,
bsstore: bsstore,
headEvents: pubsub.New(64),
checkPoint: types.EmptyTSK,
genesis: genesisCid,
reorgNotifeeCh: make(chan ReorgNotifee),
tsCache: tsCache,
}
// todo cycle reference , may think a better idea
store.tipIndex = NewTipStateCache(store)
store.chainIndex = NewChainIndex(store.GetTipSet)
store.circulatingSupplyCalculator = circulatiingSupplyCalculator
val, err := store.ds.Get(context.TODO(), CheckPoint)
if err != nil {
store.checkPoint = types.NewTipSetKey(genesisCid)
} else {
_ = store.checkPoint.UnmarshalCBOR(bytes.NewReader(val)) //nolint:staticcheck
}
log.Infof("check point value: %v", store.checkPoint)
store.reorgCh = store.reorgWorker(context.TODO())
return store
}
// Load rebuilds the Store's caches by traversing backwards from the
// most recent best head as stored in its datastore. Because Load uses a
// content addressed datastore it guarantees that parent blocks are correctly
// resolved from the datastore. Furthermore Load ensures that all tipsets
// references correctly have the same parent height, weight and parent set.
// However, Load DOES NOT validate state transitions, it assumes that the
// tipset were only Put to the Store after checking for valid transitions.
//
// Furthermore Load trusts that the Store's backing datastore correctly
// preserves the cids of the heaviest tipset under the "HeadKey" datastore key.
// If the HeadKey cids are tampered with and invalid blocks added to the datastore
// then Load could be tricked into loading an invalid chain. Load will error if the
// head does not link back to the expected genesis block, or the Store's
// datastore does not store a link in the chain. In case of error the caller
// should not consider the chain useable and propagate the error.
func (store *Store) Load(ctx context.Context) (err error) {
ctx, span := trace.StartSpan(ctx, "Store.Load")
defer tracing.AddErrorEndSpan(ctx, span, &err)
var headTS *types.TipSet
if headTS, err = store.loadHead(ctx); err != nil {
return err
}
if headTS.Height() == 0 {
return store.SetHead(ctx, headTS)
}
latestHeight := headTS.At(0).Height
loopBack := latestHeight - policy.ChainFinality
log.Infof("start loading chain at tipset: %s, height: %d", headTS.Key(), headTS.Height())
// `Metadata` of head may not exist, this is okay, its parent's `Meta` is surely exists.
headParent, err := store.GetTipSet(ctx, headTS.Parents())
if err != nil {
return err
}
// Provide tipsets directly from the block store, not from the tipset index which is
// being rebuilt by this traversal.
tipsetProvider := TipSetProviderFromBlocks(ctx, store)
for iterator := IterAncestors(ctx, tipsetProvider, headParent); !iterator.Complete(); err = iterator.Next(ctx) {
if err != nil {
return err
}
ts := iterator.Value()
if ts.Height() == 0 {
break
}
tipSetMetadata, err := store.LoadTipsetMetadata(ctx, ts)
if err != nil {
return err
}
store.tipIndex.Put(tipSetMetadata)
if ts.Height() <= loopBack {
break
}
}
log.Infof("finished loading %d tipsets from %s", latestHeight, headTS.String())
// Set actual head.
return store.SetHead(ctx, headTS)
}
// loadHead loads the latest known head from disk.
func (store *Store) loadHead(ctx context.Context) (*types.TipSet, error) {
tskBytes, err := store.ds.Get(ctx, HeadKey)
if err != nil {
return nil, errors.Wrap(err, "failed to read HeadKey")
}
var tsk types.TipSetKey
err = tsk.UnmarshalCBOR(bytes.NewReader(tskBytes))
if err != nil {
// todo: remove after nv18
err = tsk.V0UnmarshalCBOR(bytes.NewReader(tskBytes))
if err != nil {
return nil, errors.Wrap(err, "failed to cast headCids")
}
}
return store.GetTipSet(ctx, tsk)
}
// LoadTipsetMetadata load tipset status (state root and reciepts)
func (store *Store) LoadTipsetMetadata(ctx context.Context, ts *types.TipSet) (*TipSetMetadata, error) {
h := ts.Height()
key := datastore.NewKey(makeKey(ts.String(), h))
tsStateBytes, err := store.ds.Get(ctx, key)
if err != nil {
return nil, errors.Wrapf(err, "failed to read tipset key %s", ts.String())
}
var metadata TSState
err = metadata.UnmarshalCBOR(bytes.NewReader(tsStateBytes))
if err != nil {
return nil, errors.Wrapf(err, "failed to decode tip set metadata %s", ts.String())
}
return &TipSetMetadata{
TipSet: ts,
TipSetStateRoot: metadata.StateRoot,
TipSetReceipts: metadata.Receipts,
}, nil
}
// PutTipSetMetadata persists the blocks of a tipset and the tipset index.
func (store *Store) PutTipSetMetadata(ctx context.Context, tsm *TipSetMetadata) error {
// Update tipindex.
store.tipIndex.Put(tsm)
// Persist the state mapping.
return store.writeTipSetMetadata(ctx, tsm)
}
// Ls returns an iterator over tipsets from head to genesis.
func (store *Store) Ls(ctx context.Context, fromTS *types.TipSet, count int) ([]*types.TipSet, error) {
tipsets := []*types.TipSet{fromTS}
fromKey := fromTS.Parents()
for i := 0; i < count-1; i++ {
ts, err := store.GetTipSet(ctx, fromKey)
if err != nil {
return nil, err
}
tipsets = append(tipsets, ts)
fromKey = ts.Parents()
}
types.ReverseTipSet(tipsets)
return tipsets, nil
}
// GetBlock returns the block identified by `cid`.
func (store *Store) GetBlock(ctx context.Context, blockID cid.Cid) (*types.BlockHeader, error) {
var block types.BlockHeader
err := store.stateAndBlockSource.Get(ctx, blockID, &block)
if err != nil {
return nil, errors.Wrapf(err, "failed to get block %s", blockID.String())
}
return &block, nil
}
// GetBlock returns the block identified by `cid`.
func (store *Store) PutObject(ctx context.Context, obj interface{}) (cid.Cid, error) {
return store.stateAndBlockSource.Put(ctx, obj)
}
// GetTipSet returns the tipset identified by `key`.
func (store *Store) GetTipSet(ctx context.Context, key types.TipSetKey) (*types.TipSet, error) {
if key.IsEmpty() {
return store.GetHead(), nil
}
if val, has := store.tsCache.Get(key); has {
return val, nil
}
cids := key.Cids()
blks := make([]*types.BlockHeader, len(cids))
for idx, c := range cids {
blk, err := store.GetBlock(ctx, c)
if err != nil {
return nil, err
}
blks[idx] = blk
}
ts, err := types.NewTipSet(blks)
if err != nil {
return nil, err
}
store.tsCache.Add(key, ts)
return ts, nil
}
// GetTipSetByHeight looks back for a tipset at the specified epoch.
// In the case that the given height is a null round, the 'prev' flag
// selects the tipset before the null round if true, and the tipset following
// the null round if false.
func (store *Store) GetTipSetByHeight(ctx context.Context, ts *types.TipSet, h abi.ChainEpoch, prev bool) (*types.TipSet, error) {
if h < 0 {
return nil, fmt.Errorf("height %d is negative", h)
}
if ts == nil {
ts = store.head
}
if h > ts.Height() {
return nil, fmt.Errorf("looking for tipset with height greater than start point")
}
if h == ts.Height() {
return ts, nil
}
lbts, err := store.chainIndex.GetTipSetByHeight(ctx, ts, h)
if err != nil {
return nil, err
}
if lbts.Height() < h {
log.Warnf("chain index returned the wrong tipset at height %d, using slow retrieval", h)
lbts, err = store.chainIndex.GetTipsetByHeightWithoutCache(ctx, ts, h)
if err != nil {
return nil, err
}
}
if lbts.Height() == h || !prev {
return lbts, nil
}
return store.GetTipSet(ctx, lbts.Parents())
}
func (store *Store) GetTipSetByCid(ctx context.Context, c cid.Cid) (*types.TipSet, error) {
blk, err := store.bsstore.Get(ctx, c)
if err != nil {
return nil, fmt.Errorf("cannot find tipset with cid %s: %w", c, err)
}
tsk := new(types.TipSetKey)
if err := tsk.UnmarshalCBOR(bytes.NewReader(blk.RawData())); err != nil {
return nil, fmt.Errorf("cannot unmarshal block into tipset key: %w", err)
}
ts, err := store.GetTipSet(ctx, *tsk)
if err != nil {
return nil, fmt.Errorf("cannot get tipset from key: %w", err)
}
return ts, nil
}
// GetTipSetState returns the aggregate state of the tipset identified by `key`.
func (store *Store) GetTipSetState(ctx context.Context, ts *types.TipSet) (tree.Tree, error) {
if ts == nil {
ts = store.head
}
stateCid, err := store.tipIndex.GetTipSetStateRoot(ctx, ts)
if err != nil {
return nil, err
}
return tree.LoadState(ctx, store.stateAndBlockSource, stateCid)
}
// GetGenesisBlock returns the genesis block held by the chain store.
func (store *Store) GetGenesisBlock(ctx context.Context) (*types.BlockHeader, error) {
return store.GetBlock(ctx, store.GenesisCid())
}
func (store *Store) PersistGenesisCID(ctx context.Context, blk *types.BlockHeader) error {
data, err := json.Marshal(blk.Cid())
if err != nil {
return fmt.Errorf("failed to marshal genesis cid: %v", err)
}
return store.ds.Put(ctx, GenesisKey, data)
}
func GenesisBlock(ctx context.Context, chainDs datastore.Datastore, bs blockstoreutil.Blockstore) (types.BlockHeader, error) {
bb, err := chainDs.Get(ctx, GenesisKey)
if err != nil {
return types.BlockHeader{}, fmt.Errorf("failed to read genesisKey: %v", err)
}
var c cid.Cid
err = json.Unmarshal(bb, &c)
if err != nil {
return types.BlockHeader{}, fmt.Errorf("failed to cast genesisCid: %v", err)
}
var blk types.BlockHeader
err = cbor.NewCborStore(bs).Get(ctx, c, &blk)
if err != nil {
return types.BlockHeader{}, fmt.Errorf("failed to read genesis block: %v", err)
}
return blk, nil
}
// GetTipSetStateRoot returns the aggregate state root CID of the tipset identified by `key`.
func (store *Store) GetTipSetStateRoot(ctx context.Context, key *types.TipSet) (cid.Cid, error) {
return store.tipIndex.GetTipSetStateRoot(ctx, key)
}
// GetTipSetReceiptsRoot returns the root CID of the message receipts for the tipset identified by `key`.
func (store *Store) GetTipSetReceiptsRoot(ctx context.Context, key *types.TipSet) (cid.Cid, error) {
return store.tipIndex.GetTipSetReceiptsRoot(ctx, key)
}
func (store *Store) GetTipsetMetadata(ctx context.Context, ts *types.TipSet) (*TipSetMetadata, error) {
tsStat, err := store.tipIndex.Get(ctx, ts)
if err != nil {
return nil, err
}
return &TipSetMetadata{
TipSetStateRoot: tsStat.StateRoot,
TipSet: ts,
TipSetReceipts: tsStat.Receipts,
}, nil
}
// HasTipSetAndState returns true iff the default store's tipindex is indexing
// the tipset identified by `key`.
func (store *Store) HasTipSetAndState(ctx context.Context, ts *types.TipSet) bool {
return store.tipIndex.Has(ctx, ts)
}
// GetLatestBeaconEntry get latest beacon from the height. there're no beacon values in the block, try to
// get beacon in the parents tipset. the max find depth is 20.
func (store *Store) GetLatestBeaconEntry(ctx context.Context, ts *types.TipSet) (*types.BeaconEntry, error) {
cur := ts
for i := 0; i < 20; i++ {
cbe := cur.At(0).BeaconEntries
if len(cbe) > 0 {
return &cbe[len(cbe)-1], nil
}
if cur.Height() == 0 {
return nil, fmt.Errorf("made it back to genesis block without finding beacon entry")
}
next, err := store.GetTipSet(ctx, cur.Parents())
if err != nil {
return nil, fmt.Errorf("failed to load parents when searching back for latest beacon entry: %w", err)
}
cur = next
}
if os.Getenv("VENUS_IGNORE_DRAND") == "_yes_" {
return &types.BeaconEntry{
Data: []byte{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9},
}, nil
}
return nil, fmt.Errorf("found NO beacon entries in the 20 blocks prior to given tipset")
}
// nolint
func (store *Store) walkBack(ctx context.Context, from *types.TipSet, to abi.ChainEpoch) (*types.TipSet, error) {
if to > from.Height() {
return nil, fmt.Errorf("looking for tipset with height greater than start point")
}
if to == from.Height() {
return from, nil
}
ts := from
for {
pts, err := store.GetTipSet(ctx, ts.Parents())
if err != nil {
return nil, err
}
if to > pts.Height() {
// in case pts is lower than the epoch we're looking for (null blocks)
// return a tipset above that height
return ts, nil
}
if to == pts.Height() {
return pts, nil
}
ts = pts
}
}
// SetHead sets the passed in tipset as the new head of this chain.
func (store *Store) SetHead(ctx context.Context, newTS *types.TipSet) error {
log.Infof("SetHead %s %d", newTS.String(), newTS.Height())
// Add logging to debug sporadic test failure.
if !newTS.Defined() {
log.Errorf("publishing empty tipset")
log.Error(debug.Stack())
return nil
}
// reorg tipset
dropped, added, update, err := func() ([]*types.TipSet, []*types.TipSet, bool, error) {
var dropped []*types.TipSet
var added []*types.TipSet
var err error
store.mu.Lock()
defer store.mu.Unlock()
if store.head != nil {
if store.head.Equals(newTS) {
return nil, nil, false, nil
}
// reorg
oldHead := store.head
dropped, added, err = CollectTipsToCommonAncestor(ctx, store, oldHead, newTS)
if err != nil {
return nil, nil, false, err
}
} else {
added = []*types.TipSet{newTS}
}
// Ensure consistency by storing this new head on disk.
if errInner := store.writeHead(ctx, newTS.Key()); errInner != nil {
return nil, nil, false, errors.Wrap(errInner, "failed to write new Head to datastore")
}
store.head = newTS
return dropped, added, true, nil
}()
if err != nil {
return err
}
if !update {
return nil
}
// todo wrap by go function
Reverse(added)
// do reorg
store.reorgCh <- reorg{
old: dropped,
new: added,
}
return nil
}
func (store *Store) PersistTipSetKey(ctx context.Context, key types.TipSetKey) {
tskBlk, err := key.ToStorageBlock()
if err != nil {
log.Errorf("failed to create a block from tsk: %s", key)
}
_ = store.bsstore.Put(ctx, tskBlk)
}
func (store *Store) reorgWorker(ctx context.Context) chan reorg {
headChangeNotifee := func(rev, app []*types.TipSet) error {
notif := make([]*types.HeadChange, len(rev)+len(app))
for i, revert := range rev {
notif[i] = &types.HeadChange{
Type: types.HCRevert,
Val: revert,
}
}
for i, apply := range app {
notif[i+len(rev)] = &types.HeadChange{
Type: types.HCApply,
Val: apply,
}
}
// Publish an event that we have a new head.
store.headEvents.Pub(notif, types.HeadChangeTopic)
return nil
}
out := make(chan reorg, 32)
notifees := []ReorgNotifee{headChangeNotifee}
go func() {
defer log.Warn("reorgWorker quit")
for {
select {
case n := <-store.reorgNotifeeCh:
notifees = append(notifees, n)
case r := <-out:
var toremove map[int]struct{}
for i, hcf := range notifees {
err := hcf(r.old, r.new)
switch err {
case nil:
case ErrNotifeeDone:
if toremove == nil {
toremove = make(map[int]struct{})
}
toremove[i] = struct{}{}
default:
log.Error("head change func errored (BAD): ", err)
}
}
if len(toremove) > 0 {
newNotifees := make([]ReorgNotifee, 0, len(notifees)-len(toremove))
for i, hcf := range notifees {
_, remove := toremove[i]
if remove {
continue
}
newNotifees = append(newNotifees, hcf)
}
notifees = newNotifees
}
case <-ctx.Done():
return
}
}
}()
return out
}
// SubHeadChanges returns channel with chain head updates.
// First message is guaranteed to be of len == 1, and type == 'current'.
// Then event in the message may be HCApply and HCRevert.
func (store *Store) SubHeadChanges(ctx context.Context) chan []*types.HeadChange {
store.mu.RLock()
subCh := store.headEvents.Sub(types.HeadChangeTopic)
head := store.head
store.mu.RUnlock()
out := make(chan []*types.HeadChange, 16)
out <- []*types.HeadChange{{
Type: types.HCCurrent,
Val: head,
}}
go func() {
defer func() {
// Tell the caller we're done first, the following may block for a bit.
close(out)
// Unsubscribe.
store.headEvents.Unsub(subCh)
// Drain the channel.
for range subCh {
}
}()
for {
select {
case val, ok := <-subCh:
if !ok {
log.Warn("chain head sub exit loop")
return
}
select {
case out <- val.([]*types.HeadChange):
default:
log.Errorf("closing head change subscription due to slow reader")
return
}
if len(out) > 5 {
log.Warnf("head change sub is slow, has %d buffered entries", len(out))
}
case <-ctx.Done():
log.Infof("exit sub head change: %v", ctx.Err())
return
}
}
}()
return out
}
// SubscribeHeadChanges subscribe head change event
func (store *Store) SubscribeHeadChanges(f ReorgNotifee) {
store.reorgNotifeeCh <- f
}
// ReadOnlyStateStore provides a read-only IPLD store for access to chain state.
func (store *Store) ReadOnlyStateStore() util.ReadOnlyIpldStore {
return util.ReadOnlyIpldStore{IpldStore: store.stateAndBlockSource}
}
// writeHead writes the given cid set as head to disk.
func (store *Store) writeHead(ctx context.Context, tsk types.TipSetKey) error {
log.Debugf("WriteHead %s", tsk.String())
buf := new(bytes.Buffer)
err := tsk.MarshalCBOR(buf)
if err != nil {
return err
}
return store.ds.Put(ctx, HeadKey, buf.Bytes())
}
// writeTipSetMetadata writes the tipset key and the state root id to the
// datastore.
func (store *Store) writeTipSetMetadata(ctx context.Context, tsm *TipSetMetadata) error {
if tsm.TipSetStateRoot == cid.Undef {
return errors.New("attempting to write state root cid.Undef")
}
if tsm.TipSetReceipts == cid.Undef {
return errors.New("attempting to write receipts cid.Undef")
}
metadata := TSState{
StateRoot: tsm.TipSetStateRoot,
Receipts: tsm.TipSetReceipts,
}
buf := new(bytes.Buffer)
err := metadata.MarshalCBOR(buf)
if err != nil {
return err
}
// datastore keeps key:stateRoot (k,v) pairs.
h := tsm.TipSet.Height()
key := datastore.NewKey(makeKey(tsm.TipSet.String(), h))
return store.ds.Put(ctx, key, buf.Bytes())
}
// deleteTipSetMetadata delete the state root id from the datastore for the tipset key.
func (store *Store) DeleteTipSetMetadata(ctx context.Context, ts *types.TipSet) error { // nolint
store.tipIndex.Del(ts)
h := ts.Height()
key := datastore.NewKey(makeKey(ts.String(), h))
return store.ds.Delete(ctx, key)
}
// GetHead returns the current head tipset cids.
func (store *Store) GetHead() *types.TipSet {
store.mu.RLock()
defer store.mu.RUnlock()
if !store.head.Defined() {
return types.UndefTipSet
}
return store.head
}
// GenesisCid returns the genesis cid of the chain tracked by the default store.
func (store *Store) GenesisCid() cid.Cid {
return store.genesis
}
// GenesisRootCid returns the genesis root cid of the chain tracked by the default store.
func (store *Store) GenesisRootCid() cid.Cid {
genesis, _ := store.GetBlock(context.TODO(), store.GenesisCid())
return genesis.ParentStateRoot
}
func recurseLinks(ctx context.Context, bs blockstore.Blockstore, walked *cid.Set, root cid.Cid, in []cid.Cid) ([]cid.Cid, error) {
if root.Prefix().Codec != cid.DagCBOR {
return in, nil
}
data, err := bs.Get(ctx, root)
if err != nil {
return nil, fmt.Errorf("recurse links get (%s) failed: %w", root, err)
}
var rerr error
err = cbg.ScanForLinks(bytes.NewReader(data.RawData()), func(c cid.Cid) {
if rerr != nil {
// No error return on ScanForLinks :(
return
}
// traversed this already...
if !walked.Visit(c) {
return
}
in = append(in, c)
var err error
in, err = recurseLinks(ctx, bs, walked, c, in)
if err != nil {
rerr = err
}
})
if err != nil {
return nil, fmt.Errorf("scanning for links failed: %w", err)
}
return in, rerr
}
func (store *Store) Export(ctx context.Context, ts *types.TipSet, inclRecentRoots abi.ChainEpoch, skipOldMsgs bool, w io.Writer) error {
h := &car.CarHeader{
Roots: ts.Cids(),
Version: 1,
}
if err := car.WriteHeader(h, w); err != nil {
return fmt.Errorf("failed to write car header: %s", err)
}
return store.WalkSnapshot(ctx, ts, inclRecentRoots, skipOldMsgs, true, func(c cid.Cid) error {
blk, err := store.bsstore.Get(ctx, c)
if err != nil {
return fmt.Errorf("writing object to car, bs.Get: %w", err)
}
if err := carutil.LdWrite(w, c.Bytes(), blk.RawData()); err != nil {
return fmt.Errorf("failed to write block to car output: %w", err)
}
return nil
})
}
func (store *Store) WalkSnapshot(ctx context.Context, ts *types.TipSet, inclRecentRoots abi.ChainEpoch, skipOldMsgs, skipMsgReceipts bool, cb func(cid.Cid) error) error {
if ts == nil {
ts = store.GetHead()
}
seen := cid.NewSet()
walked := cid.NewSet()
blocksToWalk := ts.Cids()
currentMinHeight := ts.Height()
walkChain := func(blk cid.Cid) error {
if !seen.Visit(blk) {
return nil
}
if err := cb(blk); err != nil {
return err
}
data, err := store.bsstore.Get(ctx, blk)
if err != nil {
return fmt.Errorf("getting block: %w", err)
}
var b types.BlockHeader
if err := b.UnmarshalCBOR(bytes.NewBuffer(data.RawData())); err != nil {
return fmt.Errorf("unmarshaling block header (cid=%s): %w", blk, err)
}
if currentMinHeight > b.Height {
currentMinHeight = b.Height
if currentMinHeight%builtin.EpochsInDay == 0 {
log.Infow("export", "height", currentMinHeight)
}
}
var cids []cid.Cid
if !skipOldMsgs || b.Height > ts.Height()-inclRecentRoots {
if walked.Visit(b.Messages) {
mcids, err := recurseLinks(ctx, store.bsstore, walked, b.Messages, []cid.Cid{b.Messages})
if err != nil {
return fmt.Errorf("recursing messages failed: %w", err)
}
cids = mcids
}
}
if b.Height > 0 {
blocksToWalk = append(blocksToWalk, b.Parents...)
} else {
// include the genesis block
cids = append(cids, b.Parents...)
}
out := cids
if b.Height == 0 || b.Height > ts.Height()-inclRecentRoots {
if walked.Visit(b.ParentStateRoot) {
cids, err := recurseLinks(ctx, store.bsstore, walked, b.ParentStateRoot, []cid.Cid{b.ParentStateRoot})
if err != nil {
return fmt.Errorf("recursing genesis state failed: %w", err)
}
out = append(out, cids...)
}
if !skipMsgReceipts && walked.Visit(b.ParentMessageReceipts) {
out = append(out, b.ParentMessageReceipts)
}
}
for _, c := range out {
if seen.Visit(c) {
prefix := c.Prefix()
// Don't include identity CIDs.
if prefix.MhType == mh.IDENTITY {
continue
}
// We only include raw and dagcbor, for now.
// Raw for "code" CIDs.
switch prefix.Codec {
case cid.Raw, cid.DagCBOR:
default:
continue
}
if err := cb(c); err != nil {
return err
}
}
}
return nil
}
log.Infow("export started")
exportStart := constants.Clock.Now()
for len(blocksToWalk) > 0 {
next := blocksToWalk[0]
blocksToWalk = blocksToWalk[1:]
if err := walkChain(next); err != nil {
return fmt.Errorf("walk chain failed: %w", err)
}
}
log.Infow("export finished", "duration", constants.Clock.Now().Sub(exportStart).Seconds())
return nil
}
// Import import a car file into local db
func (store *Store) Import(ctx context.Context, r io.Reader) (*types.TipSet, error) {
br, err := carv2.NewBlockReader(r)
if err != nil {
return nil, fmt.Errorf("loadcar failed: %w", err)
}
parallelPuts := 5
putThrottle := make(chan error, parallelPuts)
for i := 0; i < parallelPuts; i++ {
putThrottle <- nil