lotus/markets/storageadapter/ondealsectorcommitted.go
Jiaying Wang bd10bdf99a
build: release: v1.18.0 (#9652)
* build: Bump version to v1.17.3-dev

* build: set version to v1.18.0-dev

* chore: actors: Allow builtin-actors to return a map of methods (#9342)

* Allow builtin-actors to return a map of methods

* go mod

* Fix tests

* Fix tests, check carefully please

* Delete lotus-pond (#9352)

* feat: add StateNetworkVersion to mpool API

* chore: refactor: rename NewestNetworkVersion

* feat: actors: Integrate datacap actor into lotus (#9348)

* Integrate datacap actor

* Implement datacap actor in chain/builtin

* feat: support typed errors over RPC

* chore: deps: update to go-jsonrpc 0.1.8

* remove duplicate import

* fix: itest: check for closed connection

* chore: refactor: move retry test to API

* address magik supernit

* Add ability to only have single partition per msg for partitions with recovery sectors

* doc gen

* Address comments

* Return beneficiary info from miner state Info()

* Update builtin-actors to dev/20220922-v9 which includes FIP-0045 changes in progress

* Integrate verifreg changes to lotus

* Setup datacap actor

* Update builtin-actors to dev/20220922-v9-1

* Update datacap actor to query datacap instead of verifreg

* update gst

* update markets

* update actors with hamt fix

* update gst

* Update datacap to parse tokens

* Update bundles

* datacap and verifreg actors use ID addresses without protocol byte

* update builtin-actors to rc1

* update go-fil-markets

* Update bundles to rc2

* Integrate the v9 migration

* Add api for getting allocation

* Add upgrade epoch for butterfly

* Tweak PreSeal struct to be infra-friendly

* docsgen

* More tweaking of PreSeal for genesis

* review fixes

* Use fake cid for test

* add butterfly artifacts for oct 5 upgrade

* check datacaps for v8 verifreg match v9 datacap actor

* Remove print statements

* Update to go-state-types master

* Update to go-state-types v0.9.0-rc1

* review fixes

* use go-fil-markets v1.24.0-v17

* Add accessors for allocations and claims maps

* fix: missing permissions tag

* butterfly

* update butterfly artifacts

* sealing pipeline: Prepare deal assigning logic for FIP-45

* sealing pipeline: Get allocationId with StateApi

* use NoAllocationID instead of nil AllocationId

* address review

* Add datacap actor to registry.go

* Add cli for listing allocations and removing expired allocations

* Update to go-state-types master

* deps: upgrade go-merkledag to 0.8.0

* shark params

* Update cli/filplus.go

Co-authored-by: Aayush Rajasekaran <arajasek94@gmail.com>

* revert change to verifreg util

* docsgen-cli

* miss the stuff

* Update FFI

* Update go-state-types to v0.9.0

* Update builtin-actors to v9.0.0

* add calib upgrade epcoh

* update  the upgrade envvar

* kill shark

* Remove fvm splash banner from nv17 upgrade

* check invariance for pending deals and allocations

* check pending verified deal proposal migrated to allocation

* Add check for unsealed CID in precommit sectors

* Fix counting of allocations in nv17 migration test

* make gen

* pass state trees as pointers

* Add assertion that migrations with & without cache are the same

* compare allocation to verified deal proposal

* Fix miner state precommit info

* fix migration test tool

* add changelog

* Update to go-state-types v0.9.1

* Integrate builtin-actors v9.0.1

* chore: ver: bump version for rc3 (#9512)

* Bump version to 1.18.0-rc3

* Update CHANGELOG.md

* Update CHANGELOG.md

Co-authored-by: Aayush Rajasekaran <arajasek94@gmail.com>

* Update CHANGELOG.md

Co-authored-by: Aayush Rajasekaran <arajasek94@gmail.com>

Co-authored-by: Jiaying Wang <42981373+jennijuju@users.noreply.github.com>
Co-authored-by: Aayush Rajasekaran <arajasek94@gmail.com>

* Migration: Use autobatch bs

* Fix autobatch

Signed-off-by: Jakub Sztandera <kubuxu@protocol.ai>

* Invoker: Use MethodMeta from go-state-types

* Add a second premigration for nv17

* Add more shed tools for migration checking

* address review

* Lotus release v1.18.0-rc4

* fix: ci: fix app-image build on ci (#9527)

* Remove old go version first

* Add GO_VERSION file

* Use GO_VERSION to set / verify go version

* mv GO_VERSION GO_VERSION_MIN

* Use GO_VERSION_MIN in Makefile check

Co-authored-by: Ian Davis <jungziege@gmail.com>

* Update to latest go-state-types for migration fixes

* go mod tidy

* fix: use api.ErrActorNotFound instead of types.ErrActorNotFound

* fix: add fields to ForkUpgradeParams

* docs: update actors_version_checklist.md

* chore: fix lint

* update to go state type v0.9.6 with market migration fix (#9545)

* update go-state-types to v-0.9.7

* Add invariant checks to migration

* fix invariant check: number of entries in datacap actor should include verifreg

* Invariant checks: Only include not-activated deals

* test: nv17 migration

* Address review

* add lotus-shed invariance method

* Migration cli takes a stateroot cid and a height

* make gen

* Update to builtin-actors v9.0.2

* Failing test that shows that notaries can remove datacap from the verifreg actor

* Test that should pass when the problem is solved

* make gen

* Review fixes

* statemanager call function will return call information even if call errors

* update go-state-types

* update builtin-actors

* bubble up errors properly from ApplyImplicitMessage

* bump to rc5

* set new upgrade heights for calibnet

* set new upgrade height for butterfly

* tweak calibnet upgrade schedule

* clarify changelog note about calibnet

* butterfly

* update calibnet artifacts

* Allow setting local bundles for Debug FVM for av 9+

* fix: autobatch: remove potential deadlock when a block is missing

Check the _underlying_ blockstore instead of recursing. Also, drop the
lock before we do that.

* fix imports

* build: set shark mainnet epoch (#9640)

* chore: build: Lotus release v1.18.0 (#9641)

* Lotus release v1.18.0

* add changelog

* address review

* changelog improvement

Co-authored-by: Jennifer Wang <jiayingw703@gmail.com>
Co-authored-by: Jiaying Wang <42981373+jennijuju@users.noreply.github.com>

Signed-off-by: Jakub Sztandera <kubuxu@protocol.ai>
Co-authored-by: Łukasz Magiera <magik6k@gmail.com>
Co-authored-by: Łukasz Magiera <magik6k@users.noreply.github.com>
Co-authored-by: Aayush <arajasek94@gmail.com>
Co-authored-by: Geoff Stuart <geoff.vball@gmail.com>
Co-authored-by: Shrenuj Bansal <shrenuj.bansal@protocol.ai>
Co-authored-by: simlecode <69969590+simlecode@users.noreply.github.com>
Co-authored-by: Rod Vagg <rod@vagg.org>
Co-authored-by: Jakub Sztandera <kubuxu@protocol.ai>
Co-authored-by: Ian Davis <jungziege@gmail.com>
Co-authored-by: zenground0 <ZenGround0@users.noreply.github.com>
Co-authored-by: Steven Allen <steven@stebalien.com>
2022-11-15 20:57:23 -05:00

400 lines
13 KiB
Go

package storageadapter
import (
"bytes"
"context"
"sync"
"github.com/ipfs/go-cid"
"golang.org/x/xerrors"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-bitfield"
"github.com/filecoin-project/go-fil-markets/storagemarket"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/builtin"
"github.com/filecoin-project/go-state-types/builtin/v8/miner"
"github.com/filecoin-project/go-state-types/builtin/v9/market"
"github.com/filecoin-project/lotus/build"
lminer "github.com/filecoin-project/lotus/chain/actors/builtin/miner"
"github.com/filecoin-project/lotus/chain/events"
"github.com/filecoin-project/lotus/chain/types"
pipeline "github.com/filecoin-project/lotus/storage/pipeline"
)
type eventsCalledAPI interface {
Called(ctx context.Context, check events.CheckFunc, msgHnd events.MsgHandler, rev events.RevertHandler, confidence int, timeout abi.ChainEpoch, mf events.MsgMatchFunc) error
}
type dealInfoAPI interface {
GetCurrentDealInfo(ctx context.Context, tsk types.TipSetKey, proposal *market.DealProposal, publishCid cid.Cid) (pipeline.CurrentDealInfo, error)
}
type diffPreCommitsAPI interface {
diffPreCommits(ctx context.Context, actor address.Address, pre, cur types.TipSetKey) (*lminer.PreCommitChanges, error)
}
type SectorCommittedManager struct {
ev eventsCalledAPI
dealInfo dealInfoAPI
dpc diffPreCommitsAPI
}
func NewSectorCommittedManager(ev eventsCalledAPI, tskAPI pipeline.CurrentDealInfoAPI, dpcAPI diffPreCommitsAPI) *SectorCommittedManager {
dim := &pipeline.CurrentDealInfoManager{
CDAPI: tskAPI,
}
return newSectorCommittedManager(ev, dim, dpcAPI)
}
func newSectorCommittedManager(ev eventsCalledAPI, dealInfo dealInfoAPI, dpcAPI diffPreCommitsAPI) *SectorCommittedManager {
return &SectorCommittedManager{
ev: ev,
dealInfo: dealInfo,
dpc: dpcAPI,
}
}
func (mgr *SectorCommittedManager) OnDealSectorPreCommitted(ctx context.Context, provider address.Address, proposal market.DealProposal, publishCid cid.Cid, callback storagemarket.DealSectorPreCommittedCallback) error {
// Ensure callback is only called once
var once sync.Once
cb := func(sectorNumber abi.SectorNumber, isActive bool, err error) {
once.Do(func() {
callback(sectorNumber, isActive, err)
})
}
// First check if the deal is already active, and if so, bail out
checkFunc := func(ctx context.Context, ts *types.TipSet) (done bool, more bool, err error) {
dealInfo, isActive, err := mgr.checkIfDealAlreadyActive(ctx, ts, &proposal, publishCid)
if err != nil {
// Note: the error returned from here will end up being returned
// from OnDealSectorPreCommitted so no need to call the callback
// with the error
return false, false, xerrors.Errorf("failed to check deal activity: %w", err)
}
if isActive {
// Deal is already active, bail out
cb(0, true, nil)
return true, false, nil
}
// Check that precommits which landed between when the deal was published
// and now don't already contain the deal we care about.
// (this can happen when the precommit lands vary quickly (in tests), or
// when the client node was down after the deal was published, and when
// the precommit containing it landed on chain)
diff, err := mgr.dpc.diffPreCommits(ctx, provider, dealInfo.PublishMsgTipSet, ts.Key())
if err != nil {
return false, false, xerrors.Errorf("failed to diff precommits: %w", err)
}
for _, info := range diff.Added {
for _, d := range info.Info.DealIDs {
if d == dealInfo.DealID {
cb(info.Info.SectorNumber, false, nil)
return true, false, nil
}
}
}
// Not yet active, start matching against incoming messages
return false, true, nil
}
// Watch for a pre-commit message to the provider.
matchEvent := func(msg *types.Message) (bool, error) {
matched := msg.To == provider && (msg.Method == builtin.MethodsMiner.PreCommitSector || msg.Method == builtin.MethodsMiner.PreCommitSectorBatch || msg.Method == builtin.MethodsMiner.ProveReplicaUpdates)
return matched, nil
}
// The deal must be accepted by the deal proposal start epoch, so timeout
// if the chain reaches that epoch
timeoutEpoch := proposal.StartEpoch + 1
// Check if the message params included the deal ID we're looking for.
called := func(msg *types.Message, rec *types.MessageReceipt, ts *types.TipSet, curH abi.ChainEpoch) (more bool, err error) {
defer func() {
if err != nil {
cb(0, false, xerrors.Errorf("handling applied event: %w", err))
}
}()
// If the deal hasn't been activated by the proposed start epoch, the
// deal will timeout (when msg == nil it means the timeout epoch was reached)
if msg == nil {
err = xerrors.Errorf("deal with piece CID %s was not activated by proposed deal start epoch %d", proposal.PieceCID, proposal.StartEpoch)
return false, err
}
// Ignore the pre-commit message if it was not executed successfully
if rec.ExitCode != 0 {
return true, nil
}
// When there is a reorg, the deal ID may change, so get the
// current deal ID from the publish message CID
res, err := mgr.dealInfo.GetCurrentDealInfo(ctx, ts.Key(), &proposal, publishCid)
if err != nil {
return false, xerrors.Errorf("failed to get dealinfo: %w", err)
}
// If this is a replica update method that succeeded the deal is active
if msg.Method == builtin.MethodsMiner.ProveReplicaUpdates {
sn, err := dealSectorInReplicaUpdateSuccess(msg, rec, res)
if err != nil {
return false, err
}
if sn != nil {
cb(*sn, true, nil)
return false, nil
}
// Didn't find the deal ID in this message, so keep looking
return true, nil
}
// Extract the message parameters
sn, err := dealSectorInPreCommitMsg(msg, res)
if err != nil {
return false, xerrors.Errorf("failed to extract message params: %w", err)
}
if sn != nil {
cb(*sn, false, nil)
}
// Didn't find the deal ID in this message, so keep looking
return true, nil
}
revert := func(ctx context.Context, ts *types.TipSet) error {
log.Warn("deal pre-commit reverted; TODO: actually handle this!")
// TODO: Just go back to DealSealing?
return nil
}
if err := mgr.ev.Called(ctx, checkFunc, called, revert, int(build.MessageConfidence+1), timeoutEpoch, matchEvent); err != nil {
return xerrors.Errorf("failed to set up called handler: %w", err)
}
return nil
}
func (mgr *SectorCommittedManager) OnDealSectorCommitted(ctx context.Context, provider address.Address, sectorNumber abi.SectorNumber, proposal market.DealProposal, publishCid cid.Cid, callback storagemarket.DealSectorCommittedCallback) error {
// Ensure callback is only called once
var once sync.Once
cb := func(err error) {
once.Do(func() {
callback(err)
})
}
// First check if the deal is already active, and if so, bail out
checkFunc := func(ctx context.Context, ts *types.TipSet) (done bool, more bool, err error) {
_, isActive, err := mgr.checkIfDealAlreadyActive(ctx, ts, &proposal, publishCid)
if err != nil {
// Note: the error returned from here will end up being returned
// from OnDealSectorCommitted so no need to call the callback
// with the error
return false, false, err
}
if isActive {
// Deal is already active, bail out
cb(nil)
return true, false, nil
}
// Not yet active, start matching against incoming messages
return false, true, nil
}
// Match a prove-commit sent to the provider with the given sector number
matchEvent := func(msg *types.Message) (matched bool, err error) {
if msg.To != provider {
return false, nil
}
return sectorInCommitMsg(msg, sectorNumber)
}
// The deal must be accepted by the deal proposal start epoch, so timeout
// if the chain reaches that epoch
timeoutEpoch := proposal.StartEpoch + 1
called := func(msg *types.Message, rec *types.MessageReceipt, ts *types.TipSet, curH abi.ChainEpoch) (more bool, err error) {
defer func() {
if err != nil {
cb(xerrors.Errorf("handling applied event: %w", err))
}
}()
// If the deal hasn't been activated by the proposed start epoch, the
// deal will timeout (when msg == nil it means the timeout epoch was reached)
if msg == nil {
err := xerrors.Errorf("deal with piece CID %s was not activated by proposed deal start epoch %d", proposal.PieceCID, proposal.StartEpoch)
return false, err
}
// Ignore the prove-commit message if it was not executed successfully
if rec.ExitCode != 0 {
return true, nil
}
// Get the deal info
res, err := mgr.dealInfo.GetCurrentDealInfo(ctx, ts.Key(), &proposal, publishCid)
if err != nil {
return false, xerrors.Errorf("failed to look up deal on chain: %w", err)
}
// Make sure the deal is active
if res.MarketDeal.State.SectorStartEpoch < 1 {
return false, xerrors.Errorf("deal wasn't active: deal=%d, parentState=%s, h=%d", res.DealID, ts.ParentState(), ts.Height())
}
log.Infof("Storage deal %d activated at epoch %d", res.DealID, res.MarketDeal.State.SectorStartEpoch)
cb(nil)
return false, nil
}
revert := func(ctx context.Context, ts *types.TipSet) error {
log.Warn("deal activation reverted; TODO: actually handle this!")
// TODO: Just go back to DealSealing?
return nil
}
if err := mgr.ev.Called(ctx, checkFunc, called, revert, int(build.MessageConfidence+1), timeoutEpoch, matchEvent); err != nil {
return xerrors.Errorf("failed to set up called handler: %w", err)
}
return nil
}
func dealSectorInReplicaUpdateSuccess(msg *types.Message, rec *types.MessageReceipt, res pipeline.CurrentDealInfo) (*abi.SectorNumber, error) {
var params miner.ProveReplicaUpdatesParams
if err := params.UnmarshalCBOR(bytes.NewReader(msg.Params)); err != nil {
return nil, xerrors.Errorf("unmarshal prove replica update: %w", err)
}
var seekUpdate miner.ReplicaUpdate
var found bool
for _, update := range params.Updates {
for _, did := range update.Deals {
if did == res.DealID {
seekUpdate = update
found = true
break
}
}
}
if !found {
return nil, nil
}
// check that this update passed validation steps
var successBf bitfield.BitField
if err := successBf.UnmarshalCBOR(bytes.NewReader(rec.Return)); err != nil {
return nil, xerrors.Errorf("unmarshal return value: %w", err)
}
success, err := successBf.IsSet(uint64(seekUpdate.SectorID))
if err != nil {
return nil, xerrors.Errorf("failed to check success of replica update: %w", err)
}
if !success {
return nil, xerrors.Errorf("replica update %d failed", seekUpdate.SectorID)
}
return &seekUpdate.SectorID, nil
}
// dealSectorInPreCommitMsg tries to find a sector containing the specified deal
func dealSectorInPreCommitMsg(msg *types.Message, res pipeline.CurrentDealInfo) (*abi.SectorNumber, error) {
switch msg.Method {
case builtin.MethodsMiner.PreCommitSector:
var params miner.SectorPreCommitInfo
if err := params.UnmarshalCBOR(bytes.NewReader(msg.Params)); err != nil {
return nil, xerrors.Errorf("unmarshal pre commit: %w", err)
}
// Check through the deal IDs associated with this message
for _, did := range params.DealIDs {
if did == res.DealID {
// Found the deal ID in this message. Callback with the sector ID.
return &params.SectorNumber, nil
}
}
case builtin.MethodsMiner.PreCommitSectorBatch:
var params miner.PreCommitSectorBatchParams
if err := params.UnmarshalCBOR(bytes.NewReader(msg.Params)); err != nil {
return nil, xerrors.Errorf("unmarshal pre commit: %w", err)
}
for _, precommit := range params.Sectors {
// Check through the deal IDs associated with this message
for _, did := range precommit.DealIDs {
if did == res.DealID {
// Found the deal ID in this message. Callback with the sector ID.
return &precommit.SectorNumber, nil
}
}
}
default:
return nil, xerrors.Errorf("unexpected method %d", msg.Method)
}
return nil, nil
}
// sectorInCommitMsg checks if the provided message commits specified sector
func sectorInCommitMsg(msg *types.Message, sectorNumber abi.SectorNumber) (bool, error) {
switch msg.Method {
case builtin.MethodsMiner.ProveCommitSector:
var params miner.ProveCommitSectorParams
if err := params.UnmarshalCBOR(bytes.NewReader(msg.Params)); err != nil {
return false, xerrors.Errorf("failed to unmarshal prove commit sector params: %w", err)
}
return params.SectorNumber == sectorNumber, nil
case builtin.MethodsMiner.ProveCommitAggregate:
var params miner.ProveCommitAggregateParams
if err := params.UnmarshalCBOR(bytes.NewReader(msg.Params)); err != nil {
return false, xerrors.Errorf("failed to unmarshal prove commit sector params: %w", err)
}
set, err := params.SectorNumbers.IsSet(uint64(sectorNumber))
if err != nil {
return false, xerrors.Errorf("checking if sectorNumber is set in commit aggregate message: %w", err)
}
return set, nil
default:
return false, nil
}
}
func (mgr *SectorCommittedManager) checkIfDealAlreadyActive(ctx context.Context, ts *types.TipSet, proposal *market.DealProposal, publishCid cid.Cid) (pipeline.CurrentDealInfo, bool, error) {
res, err := mgr.dealInfo.GetCurrentDealInfo(ctx, ts.Key(), proposal, publishCid)
if err != nil {
// TODO: This may be fine for some errors
return res, false, xerrors.Errorf("failed to look up deal on chain: %w", err)
}
// Sector was slashed
if res.MarketDeal.State.SlashEpoch > 0 {
return res, false, xerrors.Errorf("deal %d was slashed at epoch %d", res.DealID, res.MarketDeal.State.SlashEpoch)
}
// Sector with deal is already active
if res.MarketDeal.State.SectorStartEpoch > 0 {
return res, true, nil
}
return res, false, nil
}