/
fork.go
3511 lines (2996 loc) · 104 KB
/
fork.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 fork
import (
"bytes"
"context"
_ "embed"
"encoding/binary"
"errors"
"fmt"
"os"
"runtime"
"sort"
"strconv"
"sync"
"time"
"github.com/docker/go-units"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi"
actorstypes "github.com/filecoin-project/go-state-types/actors"
"github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/go-state-types/manifest"
"github.com/filecoin-project/go-state-types/network"
"github.com/filecoin-project/go-state-types/rt"
gstStore "github.com/filecoin-project/go-state-types/store"
blockstore "github.com/ipfs/boxo/blockstore"
ipfsblock "github.com/ipfs/go-block-format"
"github.com/ipfs/go-cid"
dstore "github.com/ipfs/go-datastore"
cbor "github.com/ipfs/go-ipld-cbor"
ipld "github.com/ipfs/go-ipld-format"
logging "github.com/ipfs/go-log/v2"
"github.com/multiformats/go-multicodec"
cbg "github.com/whyrusleeping/cbor-gen"
"go.opencensus.io/trace"
nv18 "github.com/filecoin-project/go-state-types/builtin/v10/migration"
nv19 "github.com/filecoin-project/go-state-types/builtin/v11/migration"
nv21 "github.com/filecoin-project/go-state-types/builtin/v12/migration"
nv22 "github.com/filecoin-project/go-state-types/builtin/v13/migration"
nv17 "github.com/filecoin-project/go-state-types/builtin/v9/migration"
"github.com/filecoin-project/go-state-types/migration"
"github.com/filecoin-project/specs-actors/actors/migration/nv3"
"github.com/filecoin-project/specs-actors/v2/actors/migration/nv4"
"github.com/filecoin-project/specs-actors/v2/actors/migration/nv7"
"github.com/filecoin-project/specs-actors/v3/actors/migration/nv10"
"github.com/filecoin-project/specs-actors/v4/actors/migration/nv12"
"github.com/filecoin-project/specs-actors/v5/actors/migration/nv13"
"github.com/filecoin-project/specs-actors/v6/actors/migration/nv14"
"github.com/filecoin-project/specs-actors/v7/actors/migration/nv15"
"github.com/filecoin-project/specs-actors/v8/actors/migration/nv16"
init11 "github.com/filecoin-project/go-state-types/builtin/v11/init"
system11 "github.com/filecoin-project/go-state-types/builtin/v11/system"
init12 "github.com/filecoin-project/go-state-types/builtin/v12/init"
system12 "github.com/filecoin-project/go-state-types/builtin/v12/system"
builtin0 "github.com/filecoin-project/specs-actors/actors/builtin"
miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner"
multisig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig"
power0 "github.com/filecoin-project/specs-actors/actors/builtin/power"
adt0 "github.com/filecoin-project/specs-actors/actors/util/adt"
"github.com/filecoin-project/venus/pkg/config"
"github.com/filecoin-project/venus/pkg/constants"
"github.com/filecoin-project/venus/pkg/repo"
vmstate "github.com/filecoin-project/venus/pkg/state/tree"
"github.com/filecoin-project/venus/venus-shared/actors"
"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/multisig"
"github.com/filecoin-project/venus/venus-shared/actors/builtin/system"
blockstoreutil "github.com/filecoin-project/venus/venus-shared/blockstore"
"github.com/filecoin-project/venus/venus-shared/types"
)
//go:embed FVMLiftoff.txt
var fvmLiftoffBanner string
var log = logging.Logger("fork")
var ErrExpensiveFork = errors.New("refusing explicit call due to state fork at epoch")
var (
MigrationMaxWorkerCount int
EnvMigrationMaxWorkerCount = "VENUS_MIGRATION_MAX_WORKER_COUNT"
)
func init() {
// the default calculation used for migration worker count
MigrationMaxWorkerCount = runtime.NumCPU()
// check if an alternative value was request by environment
if mwcs := os.Getenv(EnvMigrationMaxWorkerCount); mwcs != "" {
mwc, err := strconv.ParseInt(mwcs, 10, 32)
if err != nil {
fmt.Printf("invalid value for %s (%s) defaulting to %d: %s\n", EnvMigrationMaxWorkerCount, mwcs, MigrationMaxWorkerCount, err)
return
}
// use value from environment
fmt.Printf("migration worker count set from %s (%d)\n", EnvMigrationMaxWorkerCount, mwc)
MigrationMaxWorkerCount = int(mwc)
return
}
log.Infof("migration worker count: %d", MigrationMaxWorkerCount)
}
// MigrationCache can be used to cache information used by a migration. This is primarily useful to
// "pre-compute" some migration state ahead of time, and make it accessible in the migration itself.
type MigrationCache interface {
Write(key string, value cid.Cid) error
Read(key string) (bool, cid.Cid, error)
Load(key string, loadFunc func() (cid.Cid, error)) (cid.Cid, error)
}
// MigrationFunc is a migration function run at every upgrade.
//
// - The cache is a per-upgrade cache, pre-populated by pre-migrations.
// - The oldState is the state produced by the upgrade epoch.
// - The returned newState is the new state that will be used by the next epoch.
// - The height is the upgrade epoch height (already executed).
// - The tipset is the tipset for the last non-null block before the upgrade. Do
// not assume that ts.Height() is the upgrade height.
type MigrationFunc func(
ctx context.Context,
cache MigrationCache,
oldState cid.Cid,
height abi.ChainEpoch,
ts *types.TipSet,
) (newState cid.Cid, err error)
// PreMigrationFunc is a function run _before_ a network upgrade to pre-compute part of the network
// upgrade and speed it up.
type PreMigrationFunc func(
ctx context.Context,
cache MigrationCache,
oldState cid.Cid,
height abi.ChainEpoch,
ts *types.TipSet,
) error
// PreMigration describes a pre-migration step to prepare for a network state upgrade. Pre-migrations
// are optimizations, are not guaranteed to run, and may be canceled and/or run multiple times.
type PreMigration struct {
// PreMigration is the pre-migration function to run at the specified time. This function is
// run asynchronously and must abort promptly when canceled.
PreMigration PreMigrationFunc
// StartWithin specifies that this pre-migration should be started at most StartWithin
// epochs before the upgrade.
StartWithin abi.ChainEpoch
// DontStartWithin specifies that this pre-migration should not be started DontStartWithin
// epochs before the final upgrade epoch.
//
// This should be set such that the pre-migration is likely to complete before StopWithin.
DontStartWithin abi.ChainEpoch
// StopWithin specifies that this pre-migration should be stopped StopWithin epochs of the
// final upgrade epoch.
StopWithin abi.ChainEpoch
}
type Upgrade struct {
Height abi.ChainEpoch
Network network.Version
Expensive bool
Migration MigrationFunc
// PreMigrations specifies a set of pre-migration functions to run at the indicated epochs.
// These functions should fill the given cache with information that can speed up the
// eventual full migration at the upgrade epoch.
PreMigrations []PreMigration
}
type UpgradeSchedule []Upgrade
type migrationLogger struct{}
func (ml migrationLogger) Log(level rt.LogLevel, msg string, args ...interface{}) {
switch level {
case rt.DEBUG:
log.Debugf(msg, args...)
case rt.INFO:
log.Infof(msg, args...)
case rt.WARN:
log.Warnf(msg, args...)
case rt.ERROR:
log.Errorf(msg, args...)
}
}
func DefaultUpgradeSchedule(cf *ChainFork, upgradeHeight *config.ForkUpgradeConfig) UpgradeSchedule {
var us UpgradeSchedule
updates := []Upgrade{
{
Height: upgradeHeight.UpgradeBreezeHeight,
Network: network.Version1,
Migration: cf.UpgradeFaucetBurnRecovery,
},
{
Height: upgradeHeight.UpgradeSmokeHeight,
Network: network.Version2,
Migration: nil,
},
{
Height: upgradeHeight.UpgradeIgnitionHeight,
Network: network.Version3,
Migration: cf.UpgradeIgnition,
},
{
Height: upgradeHeight.UpgradeRefuelHeight,
Network: network.Version3,
Migration: cf.UpgradeRefuel,
},
{
Height: upgradeHeight.UpgradeAssemblyHeight,
Network: network.Version4,
Expensive: true,
Migration: cf.UpgradeActorsV2,
},
{
Height: upgradeHeight.UpgradeTapeHeight,
Network: network.Version5,
Migration: nil,
},
{
Height: upgradeHeight.UpgradeLiftoffHeight,
Network: network.Version5,
Migration: cf.UpgradeLiftoff,
},
{
Height: upgradeHeight.UpgradeKumquatHeight,
Network: network.Version6,
Migration: nil,
},
//{
// Height: upgradeHeight.UpgradePriceListOopsHeight,
// Network: network.Version6AndAHalf,
// Migration: nil,
//},
{
Height: upgradeHeight.UpgradeCalicoHeight,
Network: network.Version7,
Migration: cf.UpgradeCalico,
},
{
Height: upgradeHeight.UpgradePersianHeight,
Network: network.Version8,
Migration: nil,
},
{
Height: upgradeHeight.UpgradeOrangeHeight,
Network: network.Version9,
Migration: nil,
},
{
Height: upgradeHeight.UpgradeTrustHeight,
Network: network.Version10,
Migration: cf.UpgradeActorsV3,
PreMigrations: []PreMigration{{
PreMigration: cf.PreUpgradeActorsV3,
StartWithin: 120,
DontStartWithin: 60,
StopWithin: 35,
}, {
PreMigration: cf.PreUpgradeActorsV3,
StartWithin: 30,
DontStartWithin: 15,
StopWithin: 5,
}},
Expensive: true,
},
{
Height: upgradeHeight.UpgradeNorwegianHeight,
Network: network.Version11,
Migration: nil,
},
{
Height: upgradeHeight.UpgradeTurboHeight,
Network: network.Version12,
Migration: cf.UpgradeActorsV4,
PreMigrations: []PreMigration{{
PreMigration: cf.PreUpgradeActorsV4,
StartWithin: 120,
DontStartWithin: 60,
StopWithin: 35,
}, {
PreMigration: cf.PreUpgradeActorsV4,
StartWithin: 30,
DontStartWithin: 15,
StopWithin: 5,
}},
Expensive: true,
},
{
Height: upgradeHeight.UpgradeHyperdriveHeight,
Network: network.Version13,
Migration: cf.UpgradeActorsV5,
PreMigrations: []PreMigration{{
PreMigration: cf.PreUpgradeActorsV5,
StartWithin: 120,
DontStartWithin: 60,
StopWithin: 35,
}, {
PreMigration: cf.PreUpgradeActorsV5,
StartWithin: 30,
DontStartWithin: 15,
StopWithin: 5,
}},
Expensive: true,
},
{
Height: upgradeHeight.UpgradeChocolateHeight,
Network: network.Version14,
Migration: cf.UpgradeActorsV6,
PreMigrations: []PreMigration{{
PreMigration: cf.PreUpgradeActorsV6,
StartWithin: 120,
DontStartWithin: 60,
StopWithin: 35,
}, {
PreMigration: cf.PreUpgradeActorsV6,
StartWithin: 30,
DontStartWithin: 15,
StopWithin: 5,
}},
Expensive: true,
},
{
Height: upgradeHeight.UpgradeOhSnapHeight,
Network: network.Version15,
Migration: cf.UpgradeActorsV7,
PreMigrations: []PreMigration{{
PreMigration: cf.PreUpgradeActorsV7,
StartWithin: 180,
DontStartWithin: 60,
StopWithin: 5,
}},
Expensive: true,
},
{
Height: upgradeHeight.UpgradeSkyrHeight,
Network: network.Version16,
Migration: cf.UpgradeActorsV8,
PreMigrations: []PreMigration{{
PreMigration: cf.PreUpgradeActorsV8,
StartWithin: 180,
DontStartWithin: 60,
StopWithin: 5,
}},
Expensive: true,
},
{
Height: upgradeHeight.UpgradeSharkHeight,
Network: network.Version17,
Migration: cf.UpgradeActorsV9,
PreMigrations: []PreMigration{{
PreMigration: cf.PreUpgradeActorsV9,
StartWithin: 240,
DontStartWithin: 60,
StopWithin: 20,
}, {
PreMigration: cf.PreUpgradeActorsV9,
StartWithin: 15,
DontStartWithin: 10,
StopWithin: 5,
}},
Expensive: true,
}, {
Height: upgradeHeight.UpgradeHyggeHeight,
Network: network.Version18,
Migration: cf.UpgradeActorsV10,
PreMigrations: []PreMigration{{
PreMigration: cf.PreUpgradeActorsV10,
StartWithin: 60,
DontStartWithin: 10,
StopWithin: 5,
}},
Expensive: true,
}, {
Height: upgradeHeight.UpgradeLightningHeight,
Network: network.Version19,
Migration: cf.UpgradeActorsV11,
PreMigrations: []PreMigration{{
PreMigration: cf.PreUpgradeActorsV11,
StartWithin: 120,
DontStartWithin: 15,
StopWithin: 10,
}},
Expensive: true,
}, {
Height: upgradeHeight.UpgradeThunderHeight,
Network: network.Version20,
Migration: nil,
}, {
Height: upgradeHeight.UpgradeWatermelonHeight,
Network: network.Version21,
Migration: cf.UpgradeActorsV12,
PreMigrations: []PreMigration{{
PreMigration: cf.PreUpgradeActorsV12,
StartWithin: 180,
DontStartWithin: 15,
StopWithin: 10,
}},
Expensive: true,
}, {
Height: upgradeHeight.UpgradeWatermelonFixHeight,
Network: network.Version21,
Migration: cf.buildUpgradeActorsV12MinerFix(calibnetv12BuggyMinerCID1, calibnetv12BuggyManifestCID2),
},
{
Height: upgradeHeight.UpgradeWatermelonFix2Height,
Network: network.Version21,
Migration: cf.buildUpgradeActorsV12MinerFix(calibnetv12BuggyMinerCID2, calibnetv12CorrectManifestCID1),
},
{
Height: upgradeHeight.UpgradeDragonHeight,
Network: network.Version22,
Migration: cf.UpgradeActorsV13,
PreMigrations: []PreMigration{{
PreMigration: cf.PreUpgradeActorsV13,
StartWithin: 120,
DontStartWithin: 15,
StopWithin: 10,
}},
Expensive: true,
},
{
Height: upgradeHeight.UpgradeCalibrationDragonFixHeight,
Network: network.Version22,
Migration: cf.upgradeActorsV13VerifregFix(calibnetv13BuggyVerifregCID1, calibnetv13CorrectManifestCID1),
},
}
for _, u := range updates {
if u.Height < 0 {
// upgrade disabled
continue
}
us = append(us, u)
}
return us
}
func (us UpgradeSchedule) Validate() error {
// Make sure each upgrade is valid.
for _, u := range us {
if u.Network <= 0 {
return fmt.Errorf("cannot upgrade to version <= 0: %d", u.Network)
}
for _, m := range u.PreMigrations {
if m.StartWithin <= 0 {
return fmt.Errorf("pre-migration must specify a positive start-within epoch")
}
if m.DontStartWithin < 0 || m.StopWithin < 0 {
return fmt.Errorf("pre-migration must specify non-negative epochs")
}
if m.StartWithin <= m.StopWithin {
return fmt.Errorf("pre-migration start-within must come before stop-within")
}
// If we have a dont-start-within.
if m.DontStartWithin != 0 {
if m.DontStartWithin < m.StopWithin {
return fmt.Errorf("pre-migration dont-start-within must come before stop-within")
}
if m.StartWithin <= m.DontStartWithin {
return fmt.Errorf("pre-migration start-within must come after dont-start-within")
}
}
}
if !sort.SliceIsSorted(u.PreMigrations, func(i, j int) bool {
return u.PreMigrations[i].StartWithin > u.PreMigrations[j].StartWithin //nolint:scopelint,gosec
}) {
return fmt.Errorf("pre-migrations must be sorted by start epoch")
}
}
// Make sure the upgrade order makes sense.
for i := 1; i < len(us); i++ {
prev := &us[i-1]
curr := &us[i]
if !(prev.Network <= curr.Network) {
return fmt.Errorf("cannot downgrade from version %d to version %d", prev.Network, curr.Network)
}
// Make sure the heights make sense.
if prev.Height < 0 {
// Previous upgrade was disabled.
continue
}
if !(prev.Height < curr.Height) {
return fmt.Errorf("upgrade heights must be strictly increasing: upgrade %d was at height %d, followed by upgrade %d at height %d", i-1, prev.Height, i, curr.Height)
}
}
return nil
}
type chainReader interface {
GetHead() *types.TipSet
GetTipSet(context.Context, types.TipSetKey) (*types.TipSet, error)
GetTipSetByHeight(context.Context, *types.TipSet, abi.ChainEpoch, bool) (*types.TipSet, error)
GetTipSetState(context.Context, *types.TipSet) (vmstate.Tree, error)
GetGenesisBlock(context.Context) (*types.BlockHeader, error)
GetLookbackTipSetForRound(ctx context.Context, ts *types.TipSet, round abi.ChainEpoch, version network.Version) (*types.TipSet, cid.Cid, error)
SubHeadChanges(context.Context) chan []*types.HeadChange
}
type IFork interface {
HandleStateForks(ctx context.Context, root cid.Cid, height abi.ChainEpoch, ts *types.TipSet) (cid.Cid, error)
GetNetworkVersion(ctx context.Context, height abi.ChainEpoch) network.Version
HasExpensiveFork(ctx context.Context, height abi.ChainEpoch) bool
HasExpensiveForkBetween(parent, height abi.ChainEpoch) bool
GetForkUpgrade() *config.ForkUpgradeConfig
Start(ctx context.Context) error
}
var _ = IFork((*ChainFork)(nil))
type versionSpec struct {
networkVersion network.Version
atOrBelow abi.ChainEpoch
}
type Migration struct {
upgrade MigrationFunc
preMigrations []PreMigration
cache *nv16.MemMigrationCache
migrationResultCache *migrationResultCache
}
type migrationResultCache struct {
ds dstore.Batching
keyPrefix string
}
func (m *migrationResultCache) keyForMigration(root cid.Cid) dstore.Key {
str := fmt.Sprintf("%s/%s", m.keyPrefix, root)
return dstore.NewKey(str)
}
func (m *migrationResultCache) Get(ctx context.Context, root cid.Cid) (cid.Cid, bool, error) {
k := m.keyForMigration(root)
bs, err := m.ds.Get(ctx, k)
if ipld.IsNotFound(err) {
return cid.Undef, false, nil
} else if err != nil {
return cid.Undef, false, fmt.Errorf("error loading migration result: %w", err)
}
c, err := cid.Parse(bs)
if err != nil {
return cid.Undef, false, fmt.Errorf("error parsing migration result: %w", err)
}
return c, true, nil
}
func (m *migrationResultCache) Store(ctx context.Context, root cid.Cid, resultCid cid.Cid) error {
k := m.keyForMigration(root)
if err := m.ds.Put(ctx, k, resultCid.Bytes()); err != nil {
return err
}
return nil
}
type ChainFork struct {
cr chainReader
bs blockstoreutil.Blockstore
ipldstore cbor.IpldStore
// Determines the network version at any given epoch.
networkVersions []versionSpec
latestVersion network.Version
// Maps chain epochs to upgrade functions.
stateMigrations map[abi.ChainEpoch]*Migration
// A set of potentially expensive/time consuming upgrades. Explicit
// calls for, e.g., gas estimation fail against this epoch with
// ErrExpensiveFork.
expensiveUpgrades map[abi.ChainEpoch]struct{}
// upgrade param
networkType types.NetworkType
forkUpgrade *config.ForkUpgradeConfig
metadataDs repo.Datastore
}
func NewChainFork(ctx context.Context,
cr chainReader,
ipldstore cbor.IpldStore,
bs blockstoreutil.Blockstore,
networkParams *config.NetworkParamsConfig,
metadataDs dstore.Batching,
) (*ChainFork, error) {
fork := &ChainFork{
cr: cr,
bs: bs,
ipldstore: ipldstore,
networkType: networkParams.NetworkType,
forkUpgrade: networkParams.ForkUpgradeParam,
metadataDs: metadataDs,
}
// If we have upgrades, make sure they're in-order and make sense.
us := DefaultUpgradeSchedule(fork, networkParams.ForkUpgradeParam)
if err := us.Validate(); err != nil {
return nil, err
}
stateMigrations := make(map[abi.ChainEpoch]*Migration, len(us))
expensiveUpgrades := make(map[abi.ChainEpoch]struct{}, len(us))
var networkVersions []versionSpec
lastVersion := networkParams.GenesisNetworkVersion
if len(us) > 0 {
// If we have any upgrades, process them and create a version schedule.
for _, upgrade := range us {
if upgrade.Migration != nil || upgrade.PreMigrations != nil {
migration := &Migration{
upgrade: upgrade.Migration,
preMigrations: upgrade.PreMigrations,
cache: nv16.NewMemMigrationCache(),
migrationResultCache: &migrationResultCache{
keyPrefix: fmt.Sprintf("/migration-cache/nv%d", upgrade.Network),
ds: metadataDs,
},
}
stateMigrations[upgrade.Height] = migration
}
if upgrade.Expensive {
expensiveUpgrades[upgrade.Height] = struct{}{}
}
networkVersions = append(networkVersions, versionSpec{
networkVersion: lastVersion,
atOrBelow: upgrade.Height,
})
lastVersion = upgrade.Network
}
}
fork.networkVersions = networkVersions
fork.latestVersion = lastVersion
fork.stateMigrations = stateMigrations
fork.expensiveUpgrades = expensiveUpgrades
return fork, nil
}
func (c *ChainFork) Start(ctx context.Context) error {
log.Info("preMigrationWorker start ...")
go c.preMigrationWorker(ctx)
return nil
}
func (c *ChainFork) StateTree(ctx context.Context, st cid.Cid) (*vmstate.State, error) {
return vmstate.LoadState(ctx, c.ipldstore, st)
}
func (c *ChainFork) HandleStateForks(ctx context.Context, root cid.Cid, height abi.ChainEpoch, ts *types.TipSet) (cid.Cid, error) {
retCid := root
u := c.stateMigrations[height]
if u != nil && u.upgrade != nil {
if height != c.forkUpgrade.UpgradeWatermelonFixHeight {
migCid, ok, err := u.migrationResultCache.Get(ctx, root)
if err == nil && ok && !constants.NoMigrationResultCache {
log.Infow("CACHED migration", "height", height, "from", root, "to", migCid)
return migCid, nil
} else if !errors.Is(err, dstore.ErrNotFound) {
log.Errorw("failed to lookup previous migration result", "err", err)
} else {
log.Debug("no cached migration found, migrating from scratch")
}
}
var err error
startTime := time.Now()
log.Warnw("STARTING migration", "height", height, "from", root)
// Yes, we clone the cache, even for the final upgrade epoch. Why? Reverts. We may
// have to migrate multiple times.
tmpCache := u.cache.Clone()
retCid, err = u.upgrade(ctx, tmpCache, root, height, ts)
if err != nil {
log.Errorw("FAILED migration", "height", height, "from", root, "error", err)
return cid.Undef, err
}
log.Warnw("COMPLETED migration",
"height", height,
"from", root,
"to", retCid,
"duration", time.Since(startTime),
)
// Only set if migration ran, we do not want a root => root mapping
if err := u.migrationResultCache.Store(ctx, root, retCid); err != nil {
log.Errorw("failed to store migration result", "err", err)
}
}
return retCid, nil
}
func (c *ChainFork) HasExpensiveFork(ctx context.Context, height abi.ChainEpoch) bool {
_, ok := c.expensiveUpgrades[height]
return ok
}
// Returns true executing tipsets between the specified heights would trigger an expensive
// migration. NOTE: migrations occurring _at_ the target height are not included, as they're
// executed _after_ the target height.
func (c *ChainFork) HasExpensiveForkBetween(parent, height abi.ChainEpoch) bool {
for h := parent; h < height; h++ {
if _, ok := c.expensiveUpgrades[h]; ok {
return true
}
}
return false
}
func (c *ChainFork) GetNetworkVersion(ctx context.Context, height abi.ChainEpoch) network.Version {
// The epochs here are the _last_ epoch for every version, or -1 if the
// version is disabled.
for _, spec := range c.networkVersions {
if height <= spec.atOrBelow {
return spec.networkVersion
}
}
return c.latestVersion
}
func runPreMigration(ctx context.Context, fn PreMigrationFunc, cache *nv16.MemMigrationCache, ts *types.TipSet) {
height := ts.Height()
parent := ts.Blocks()[0].ParentStateRoot
startTime := time.Now()
log.Warn("STARTING pre-migration")
// Clone the cache so we don't actually _update_ it
// till we're done. Otherwise, if we fail, the next
// migration to use the cache may assume that
// certain blocks exist, even if they don't.
tmpCache := cache.Clone()
err := fn(ctx, tmpCache, parent, height, ts)
if err != nil {
log.Errorw("FAILED pre-migration", "error", err)
return
}
// Finally, if everything worked, update the cache.
cache.Update(tmpCache)
log.Warnw("COMPLETED pre-migration", "duration", time.Since(startTime))
}
func (c *ChainFork) preMigrationWorker(ctx context.Context) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
type op struct {
after abi.ChainEpoch
notAfter abi.ChainEpoch
run func(ts *types.TipSet)
}
var wg sync.WaitGroup
defer wg.Wait()
// Turn each pre-migration into an operation in a schedule.
var schedule []op
for upgradeEpoch, migration := range c.stateMigrations {
cache := migration.cache
for _, prem := range migration.preMigrations {
preCtx, preCancel := context.WithCancel(ctx)
migrationFunc := prem.PreMigration
afterEpoch := upgradeEpoch - prem.StartWithin
notAfterEpoch := upgradeEpoch - prem.DontStartWithin
stopEpoch := upgradeEpoch - prem.StopWithin
// We can't start after we stop.
if notAfterEpoch > stopEpoch {
notAfterEpoch = stopEpoch - 1
}
// Add an op to start a pre-migration.
schedule = append(schedule, op{
after: afterEpoch,
notAfter: notAfterEpoch,
// TODO: are these values correct?
run: func(ts *types.TipSet) {
wg.Add(1)
go func() {
defer wg.Done()
runPreMigration(preCtx, migrationFunc, cache, ts)
}()
},
})
// Add an op to cancel the pre-migration if it's still running.
schedule = append(schedule, op{
after: stopEpoch,
notAfter: -1,
run: func(ts *types.TipSet) { preCancel() },
})
}
}
// Then sort by epoch.
sort.Slice(schedule, func(i, j int) bool {
return schedule[i].after < schedule[j].after
})
// Finally, when the head changes, see if there's anything we need to do.
//
// We're intentionally ignoring reorgs as they don't matter for our purposes.
for change := range c.cr.SubHeadChanges(ctx) {
for _, head := range change {
for len(schedule) > 0 {
op := &schedule[0]
if head.Val.Height() < op.after {
break
}
// If we haven't passed the pre-migration height...
if op.notAfter < 0 || head.Val.Height() < op.notAfter {
op.run(head.Val)
}
schedule = schedule[1:]
}
}
}
}
func doTransfer(tree vmstate.Tree, from, to address.Address, amt abi.TokenAmount) error {
fromAct, found, err := tree.GetActor(context.TODO(), from)
if err != nil {
return fmt.Errorf("failed to get 'from' actor for transfer: %v", err)
}
if !found {
return fmt.Errorf("did not find 'from' actor for transfer: %v", from.String())
}
fromAct.Balance = big.Sub(fromAct.Balance, amt)
if fromAct.Balance.Sign() < 0 {
return fmt.Errorf("(sanity) deducted more funds from target account than it had (%s, %s)", from, types.FIL(amt))
}
if err := tree.SetActor(context.TODO(), from, fromAct); err != nil {
return fmt.Errorf("failed to persist from actor: %v", err)
}
toAct, found, err := tree.GetActor(context.TODO(), to)
if err != nil {
return fmt.Errorf("failed to get 'to' actor for transfer: %v", err)
}
if !found {
return fmt.Errorf("did not find 'to' actor for transfer: %v", from.String())
}
toAct.Balance = big.Add(toAct.Balance, amt)
if err := tree.SetActor(context.TODO(), to, toAct); err != nil {
return fmt.Errorf("failed to persist to actor: %v", err)
}
return nil
}
func (c *ChainFork) ParentState(ts *types.TipSet) cid.Cid {
if ts == nil {
tts := c.cr.GetHead()
return tts.Blocks()[0].ParentStateRoot
}
return ts.Blocks()[0].ParentStateRoot
}
func (c *ChainFork) UpgradeFaucetBurnRecovery(ctx context.Context, cache MigrationCache, root cid.Cid, epoch abi.ChainEpoch, ts *types.TipSet) (cid.Cid, error) {
// Some initial parameters
FundsForMiners := types.FromFil(1_000_000)
LookbackEpoch := abi.ChainEpoch(32000)
AccountCap := types.FromFil(0)
BaseMinerBalance := types.FromFil(20)
DesiredReimbursementBalance := types.FromFil(5_000_000)
isSystemAccount := func(addr address.Address) (bool, error) {
id, err := address.IDFromAddress(addr)
if err != nil {
return false, fmt.Errorf("id address: %v", err)
}
if id < 1000 {
return true, nil
}
return false, nil
}
minerFundsAlloc := func(pow, tpow abi.StoragePower) abi.TokenAmount {
return big.Div(big.Mul(pow, FundsForMiners), tpow)
}
// Grab lookback state for account checks
lbts, err := c.cr.GetTipSetByHeight(ctx, ts, LookbackEpoch, false)
if err != nil {
return cid.Undef, fmt.Errorf("failed to get tipset at lookback height: %v", err)
}
pts, err := c.cr.GetTipSet(ctx, lbts.Parents())
if err != nil {
return cid.Undef, fmt.Errorf("failed to get tipset : %v", err)
}
lbtree, err := c.cr.GetTipSetState(ctx, pts)
if err != nil {
return cid.Undef, fmt.Errorf("loading state tree failed: %v", err)
}
tree, err := c.StateTree(ctx, root)
if err != nil {
return cid.Undef, fmt.Errorf("getting state tree: %v", err)
}
type transfer struct {
From address.Address
To address.Address
Amt abi.TokenAmount
}
// todo not needed
var transfers []transfer
//subcalls := make([]types.ExecutionTrace, 0)
//transferCb := func(trace types.ExecutionTrace) {
// subcalls = append(subcalls, trace)
//}
// Take all excess funds away, put them into the reserve account
err = tree.ForEach(func(addr address.Address, act *types.Actor) error {
switch act.Code {
case builtin0.AccountActorCodeID, builtin0.MultisigActorCodeID, builtin0.PaymentChannelActorCodeID:
sysAcc, err := isSystemAccount(addr)
if err != nil {
return fmt.Errorf("checking system account: %v", err)
}
if !sysAcc {
transfers = append(transfers, transfer{
From: addr,
To: builtin.ReserveAddress,
Amt: act.Balance,
})
}
case builtin0.StorageMinerActorCodeID:
var st miner0.State
if err := c.ipldstore.Get(ctx, act.Head, &st); err != nil {
return fmt.Errorf("failed to load miner state: %v", err)
}
var available abi.TokenAmount
{
defer func() {
if err := recover(); err != nil {
log.Warnf("Get available balance failed (%s, %s, %s): %s", addr, act.Head, act.Balance, err)
}
available = abi.NewTokenAmount(0)
}()
// this panics if the miner doesnt have enough funds to cover their locked pledge
available = st.GetAvailableBalance(act.Balance)
}
if !available.IsZero() {
transfers = append(transfers, transfer{
From: addr,
To: builtin.ReserveAddress,
Amt: available,
})
}
}
return nil
})
if err != nil {
return cid.Undef, fmt.Errorf("foreach over state tree failed: %v", err)
}
// Execute transfers from previous step
// fmt.Printf("num:%v, transfers:%v\n", len(transfers), transfers)
for _, t := range transfers {
if err := doTransfer(tree, t.From, t.To, t.Amt); err != nil {
return cid.Undef, fmt.Errorf("transfer %s %s->%s failed: %v", t.Amt, t.From, t.To, err)
}
}
// pull up power table to give miners back some funds proportional to their power
var ps power0.State
powAct, find, err := tree.GetActor(ctx, builtin0.StoragePowerActorAddr)
if err != nil {