From e4daadbfcf70c30af00d254bec1b09037a49a187 Mon Sep 17 00:00:00 2001 From: austinabell Date: Thu, 20 Aug 2020 17:54:59 -0400 Subject: [PATCH 001/303] Remove extra tipset load from checking beacon entries --- chain/store/store.go | 12 +++++++----- chain/sync.go | 12 +++++++----- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/chain/store/store.go b/chain/store/store.go index 9c424dc3b..6ecc30b66 100644 --- a/chain/store/store.go +++ b/chain/store/store.go @@ -1258,11 +1258,13 @@ func (cs *ChainStore) GetLatestBeaconEntry(ts *types.TipSet) (*types.BeaconEntry return nil, xerrors.Errorf("made it back to genesis block without finding beacon entry") } - next, err := cs.LoadTipSet(cur.Parents()) - if err != nil { - return nil, xerrors.Errorf("failed to load parents when searching back for latest beacon entry: %w", err) + if i != 19 { + next, err := cs.LoadTipSet(cur.Parents()) + if err != nil { + return nil, xerrors.Errorf("failed to load parents when searching back for latest beacon entry: %w", err) + } + cur = next } - cur = next } if os.Getenv("LOTUS_IGNORE_DRAND") == "_yes_" { @@ -1271,7 +1273,7 @@ func (cs *ChainStore) GetLatestBeaconEntry(ts *types.TipSet) (*types.BeaconEntry }, nil } - return nil, xerrors.Errorf("found NO beacon entries in the 20 blocks prior to given tipset") + return nil, xerrors.Errorf("found NO beacon entries in the 20 latest tipsets") } type chainRand struct { diff --git a/chain/sync.go b/chain/sync.go index b0ae185b0..31f57b402 100644 --- a/chain/sync.go +++ b/chain/sync.go @@ -1591,14 +1591,16 @@ func (syncer *Syncer) getLatestBeaconEntry(_ context.Context, ts *types.TipSet) return nil, xerrors.Errorf("made it back to genesis block without finding beacon entry") } - next, err := syncer.store.LoadTipSet(cur.Parents()) - if err != nil { - return nil, xerrors.Errorf("failed to load parents when searching back for latest beacon entry: %w", err) + if i != 19 { + next, err := syncer.store.LoadTipSet(cur.Parents()) + if err != nil { + return nil, xerrors.Errorf("failed to load parents when searching back for latest beacon entry: %w", err) + } + cur = next } - cur = next } - return nil, xerrors.Errorf("found NO beacon entries in the 20 blocks prior to given tipset") + return nil, xerrors.Errorf("found NO beacon entries in the 20 latest tipsets") } func (syncer *Syncer) IsEpochBeyondCurrMax(epoch abi.ChainEpoch) bool { From cac848c106fb1608944958d4105c9186f957e42e Mon Sep 17 00:00:00 2001 From: whyrusleeping Date: Mon, 31 Aug 2020 14:24:23 -0700 Subject: [PATCH 002/303] add a command to import an ipld object into the chainstore --- cmd/lotus-shed/import-car.go | 57 ++++++++++++++++++++++++++++++++++++ cmd/lotus-shed/main.go | 1 + 2 files changed, 58 insertions(+) diff --git a/cmd/lotus-shed/import-car.go b/cmd/lotus-shed/import-car.go index 01343c4a3..9cbff953b 100644 --- a/cmd/lotus-shed/import-car.go +++ b/cmd/lotus-shed/import-car.go @@ -1,10 +1,13 @@ package main import ( + "encoding/hex" "fmt" "io" "os" + block "github.com/ipfs/go-block-format" + "github.com/ipfs/go-cid" "github.com/ipld/go-car" "github.com/urfave/cli/v2" "golang.org/x/xerrors" @@ -81,3 +84,57 @@ var importCarCmd = &cli.Command{ } }, } + +var importObjectCmd = &cli.Command{ + Name: "import-obj", + Usage: "import a raw ipld object into your datastore", + Action: func(cctx *cli.Context) error { + r, err := repo.NewFS(cctx.String("repo")) + if err != nil { + return xerrors.Errorf("opening fs repo: %w", err) + } + + exists, err := r.Exists() + if err != nil { + return err + } + if !exists { + return xerrors.Errorf("lotus repo doesn't exist") + } + + lr, err := r.Lock(repo.FullNode) + if err != nil { + return err + } + defer lr.Close() //nolint:errcheck + + ds, err := lr.Datastore("/chain") + if err != nil { + return err + } + + bs := blockstore.NewBlockstore(ds) + + c, err := cid.Decode(cctx.Args().Get(0)) + if err != nil { + return err + } + + data, err := hex.DecodeString(cctx.Args().Get(1)) + if err != nil { + return err + } + + blk, err := block.NewBlockWithCid(data, c) + if err != nil { + return err + } + + if err := bs.Put(blk); err != nil { + return err + } + + return nil + + }, +} diff --git a/cmd/lotus-shed/main.go b/cmd/lotus-shed/main.go index 5438a31ef..11b98a3ac 100644 --- a/cmd/lotus-shed/main.go +++ b/cmd/lotus-shed/main.go @@ -24,6 +24,7 @@ func main() { bigIntParseCmd, staterootCmd, importCarCmd, + importObjectCmd, commpToCidCmd, fetchParamCmd, proofsCmd, From f58e8bc9a393c7fb3aca463fad961b45c8a0b8f4 Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Tue, 1 Sep 2020 02:18:02 -0400 Subject: [PATCH 003/303] Fix some failed precommit handling --- extern/storage-sealing/states_failed.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/extern/storage-sealing/states_failed.go b/extern/storage-sealing/states_failed.go index e313fd712..25f60ff2f 100644 --- a/extern/storage-sealing/states_failed.go +++ b/extern/storage-sealing/states_failed.go @@ -37,16 +37,16 @@ func (m *Sealing) checkPreCommitted(ctx statemachine.Context, sector SectorInfo) tok, _, err := m.api.ChainHead(ctx.Context()) if err != nil { log.Errorf("handleSealPrecommit1Failed(%d): temp error: %+v", sector.SectorNumber, err) - return nil, true + return nil, false } info, err := m.api.StateSectorPreCommitInfo(ctx.Context(), m.maddr, sector.SectorNumber, tok) if err != nil { log.Errorf("handleSealPrecommit1Failed(%d): temp error: %+v", sector.SectorNumber, err) - return nil, true + return nil, false } - return info, false + return info, true } func (m *Sealing) handleSealPrecommit1Failed(ctx statemachine.Context, sector SectorInfo) error { @@ -107,7 +107,7 @@ func (m *Sealing) handlePreCommitFailed(ctx statemachine.Context, sector SectorI } if pci, is := m.checkPreCommitted(ctx, sector); is && pci != nil { - if sector.PreCommitMessage != nil { + if sector.PreCommitMessage == nil { log.Warn("sector %d is precommitted on chain, but we don't have precommit message", sector.SectorNumber) return ctx.Send(SectorPreCommitLanded{TipSet: tok}) } From 485f13de1254ad1ef833ab4ebe663bd4f972e9cc Mon Sep 17 00:00:00 2001 From: austinabell Date: Wed, 2 Sep 2020 16:45:23 -0400 Subject: [PATCH 004/303] Remove load check --- chain/store/store.go | 11 +++++------ chain/sync.go | 10 ++++------ 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/chain/store/store.go b/chain/store/store.go index 0d38ba9b5..b64277302 100644 --- a/chain/store/store.go +++ b/chain/store/store.go @@ -1278,13 +1278,12 @@ func (cs *ChainStore) GetLatestBeaconEntry(ts *types.TipSet) (*types.BeaconEntry return nil, xerrors.Errorf("made it back to genesis block without finding beacon entry") } - if i != 19 { - next, err := cs.LoadTipSet(cur.Parents()) - if err != nil { - return nil, xerrors.Errorf("failed to load parents when searching back for latest beacon entry: %w", err) - } - cur = next + next, err := cs.LoadTipSet(cur.Parents()) + if err != nil { + return nil, xerrors.Errorf("failed to load parents when searching back for latest beacon entry: %w", err) } + cur = next + } if os.Getenv("LOTUS_IGNORE_DRAND") == "_yes_" { diff --git a/chain/sync.go b/chain/sync.go index 3e2bf9a0f..775c32843 100644 --- a/chain/sync.go +++ b/chain/sync.go @@ -1630,13 +1630,11 @@ func (syncer *Syncer) getLatestBeaconEntry(_ context.Context, ts *types.TipSet) return nil, xerrors.Errorf("made it back to genesis block without finding beacon entry") } - if i != 19 { - next, err := syncer.store.LoadTipSet(cur.Parents()) - if err != nil { - return nil, xerrors.Errorf("failed to load parents when searching back for latest beacon entry: %w", err) - } - cur = next + next, err := syncer.store.LoadTipSet(cur.Parents()) + if err != nil { + return nil, xerrors.Errorf("failed to load parents when searching back for latest beacon entry: %w", err) } + cur = next } return nil, xerrors.Errorf("found NO beacon entries in the 20 latest tipsets") From 6b63fa379f522cfe9996f25929640c3aede2e6cd Mon Sep 17 00:00:00 2001 From: austinabell Date: Wed, 2 Sep 2020 16:45:50 -0400 Subject: [PATCH 005/303] format --- chain/store/store.go | 1 - 1 file changed, 1 deletion(-) diff --git a/chain/store/store.go b/chain/store/store.go index b64277302..903bdc624 100644 --- a/chain/store/store.go +++ b/chain/store/store.go @@ -1283,7 +1283,6 @@ func (cs *ChainStore) GetLatestBeaconEntry(ts *types.TipSet) (*types.BeaconEntry return nil, xerrors.Errorf("failed to load parents when searching back for latest beacon entry: %w", err) } cur = next - } if os.Getenv("LOTUS_IGNORE_DRAND") == "_yes_" { From fe52c475703ad417178667477c003e6cd5d930bc Mon Sep 17 00:00:00 2001 From: Hector Sanjuan Date: Mon, 31 Aug 2020 17:11:01 +0200 Subject: [PATCH 006/303] Docs review and re-organization This: * Re-organizes the docs into sections that align with what docs.filecoin.io becoming: * An installation section * A "getting started" section (lotus client focused) * A "storing" section (lotus client focused) * A "mining" section (miner focused) * A "build" section (developer focused) * An legacy "architecture" section is left in the last place. A few high-value documentation pages have been reviewed and updated with the latest recommendations: * Installation section and lotus setup * Miner setup * etc. ... Other pages have been correctly merged into the new relevant sections. Some pages have not been touched. The filesystem layout of the documentation has been changed into folders corresponding to the sections (as requested by @cw). Some pages that were not linked at all and/or where hidden, have been moved to "unclassified". This should make the porting of the Lotus documentation to docs.filecoin.io much easier, while ensuring it is more up to date than it was before. For the moment, this breaks most links as link-aliasing is not supported in lotus-docs. --- Makefile | 2 +- documentation/en/.library.json | 353 +++++++++--------- documentation/en/about.md | 14 + documentation/en/api-scripting-support.md | 25 -- documentation/en/api.md | 85 ----- .../en/{ => architecture}/architecture.md | 2 +- documentation/en/{ => architecture}/mpool.md | 0 .../en/{ => building}/api-methods.md | 0 .../en/{ => building}/api-troubleshooting.md | 0 documentation/en/building/api.md | 38 ++ documentation/en/building/building.md | 5 + .../jaeger-tracing.md} | 0 .../local-devnet.md} | 0 .../en/{ => building}/payment-channels.md | 0 documentation/en/building/remote-api.md | 69 ++++ documentation/en/cli.md | 108 ------ documentation/en/dev-tools.md | 3 - documentation/en/environment-vars.md | 65 ---- documentation/en/faqs.md | 36 +- documentation/en/getting-started.md | 23 -- .../en/getting-started/getting-started.md | 3 + .../setup-troubleshooting.md | 13 +- documentation/en/getting-started/setup.md | 169 +++++++++ documentation/en/getting-started/wallet.md | 58 +++ documentation/en/hardware-mining.md | 54 --- documentation/en/hardware.md | 7 - documentation/en/install-lotus-arch.md | 51 --- documentation/en/install-lotus-fedora.md | 54 --- documentation/en/install-lotus-ubuntu.md | 54 --- documentation/en/install-systemd-services.md | 145 ------- .../en/installation/install-linux.md | 129 +++++++ .../install-macos.md} | 2 +- documentation/en/installation/installation.md | 39 ++ documentation/en/installation/update.md | 72 ++++ documentation/en/join-testnet.md | 93 ----- documentation/en/miner-deals.md | 39 -- documentation/en/mining.md | 149 -------- documentation/en/mining/gpus.md | 17 + .../lotus-seal-worker.md} | 58 +-- documentation/en/mining/managing-deals.md | 19 + documentation/en/mining/miner-setup.md | 241 ++++++++++++ .../en/{ => mining}/mining-troubleshooting.md | 9 +- documentation/en/mining/mining.md | 8 + documentation/en/retrieving-data.md | 27 -- documentation/en/setting-a-static-port.md | 54 --- .../adding-from-ipfs.md} | 6 +- documentation/en/store/making-deals.md | 71 ++++ documentation/en/store/retrieve.md | 27 ++ .../storage-troubleshooting.md} | 13 +- documentation/en/store/store.md | 11 + documentation/en/storing-data.md | 62 --- .../WIP-arch-complementary-notes.md | 0 .../en/{ => unclassified}/block-validation.md | 0 .../en/{dev => unclassified}/create-miner.md | 0 .../{ => unclassified}/dev-tools-pond-ui.md | 0 .../en/{ => unclassified}/sealing-procs.md | 0 documentation/en/updating-lotus.md | 14 - 57 files changed, 1239 insertions(+), 1357 deletions(-) create mode 100644 documentation/en/about.md delete mode 100644 documentation/en/api-scripting-support.md delete mode 100644 documentation/en/api.md rename documentation/en/{ => architecture}/architecture.md (99%) rename documentation/en/{ => architecture}/mpool.md (100%) rename documentation/en/{ => building}/api-methods.md (100%) rename documentation/en/{ => building}/api-troubleshooting.md (100%) create mode 100644 documentation/en/building/api.md create mode 100644 documentation/en/building/building.md rename documentation/en/{dev-tools-jaeger-tracing.md => building/jaeger-tracing.md} (100%) rename documentation/en/{local-dev-net.md => building/local-devnet.md} (100%) rename documentation/en/{ => building}/payment-channels.md (100%) create mode 100644 documentation/en/building/remote-api.md delete mode 100644 documentation/en/cli.md delete mode 100644 documentation/en/dev-tools.md delete mode 100644 documentation/en/environment-vars.md delete mode 100644 documentation/en/getting-started.md create mode 100644 documentation/en/getting-started/getting-started.md rename documentation/en/{ => getting-started}/setup-troubleshooting.md (60%) create mode 100644 documentation/en/getting-started/setup.md create mode 100644 documentation/en/getting-started/wallet.md delete mode 100644 documentation/en/hardware-mining.md delete mode 100644 documentation/en/hardware.md delete mode 100644 documentation/en/install-lotus-arch.md delete mode 100644 documentation/en/install-lotus-fedora.md delete mode 100644 documentation/en/install-lotus-ubuntu.md delete mode 100644 documentation/en/install-systemd-services.md create mode 100644 documentation/en/installation/install-linux.md rename documentation/en/{install-lotus-macos.md => installation/install-macos.md} (85%) create mode 100644 documentation/en/installation/installation.md create mode 100644 documentation/en/installation/update.md delete mode 100644 documentation/en/join-testnet.md delete mode 100644 documentation/en/miner-deals.md delete mode 100644 documentation/en/mining.md create mode 100644 documentation/en/mining/gpus.md rename documentation/en/{mining-lotus-worker.md => mining/lotus-seal-worker.md} (60%) create mode 100644 documentation/en/mining/managing-deals.md create mode 100644 documentation/en/mining/miner-setup.md rename documentation/en/{ => mining}/mining-troubleshooting.md (90%) create mode 100644 documentation/en/mining/mining.md delete mode 100644 documentation/en/retrieving-data.md delete mode 100644 documentation/en/setting-a-static-port.md rename documentation/en/{storing-ipfs-integration.md => store/adding-from-ipfs.md} (79%) create mode 100644 documentation/en/store/making-deals.md create mode 100644 documentation/en/store/retrieve.md rename documentation/en/{storing-data-troubleshooting.md => store/storage-troubleshooting.md} (51%) create mode 100644 documentation/en/store/store.md delete mode 100644 documentation/en/storing-data.md rename documentation/en/{dev => unclassified}/WIP-arch-complementary-notes.md (100%) rename documentation/en/{ => unclassified}/block-validation.md (100%) rename documentation/en/{dev => unclassified}/create-miner.md (100%) rename documentation/en/{ => unclassified}/dev-tools-pond-ui.md (100%) rename documentation/en/{ => unclassified}/sealing-procs.md (100%) delete mode 100644 documentation/en/updating-lotus.md diff --git a/Makefile b/Makefile index 4f6ece417..2e91cfa65 100644 --- a/Makefile +++ b/Makefile @@ -280,7 +280,7 @@ method-gen: gen: type-gen method-gen docsgen: - go run ./api/docgen > documentation/en/api-methods.md + go run ./api/docgen > documentation/en/building/api-methods.md print-%: @echo $*=$($*) diff --git a/documentation/en/.library.json b/documentation/en/.library.json index 3fab0df9b..87c7353c1 100644 --- a/documentation/en/.library.json +++ b/documentation/en/.library.json @@ -1,214 +1,207 @@ { "posts": [ { - "title": "Hardware Requirements", - "slug": "en+hardware", - "github": "en/hardware.md", + "title": "About Lotus", + "slug": "en+lotus", + "github": "en/about.md", + "value": null, + "posts": [] + }, + { + "title": "Installation", + "slug": "en+install", + "github": "en/installation/installation.md", "value": null, "posts": [ - { - "title": "Testing Configuration", - "slug": "en+hardware-mining", - "github": "en/hardware-mining.md", - "value": null - } + { + "title": "Linux installation", + "slug": "en+install-linux", + "github": "en/installation/install-linux.md", + "value": null + }, + { + "title": "MacOS installation", + "slug": "en+install-macos", + "github": "en/installation/install-macos.md", + "value": null + }, + { + "title": "Updating Lotus", + "slug": "en+update", + "github": "en/installation/update.md", + "value": null + } ] }, { - "title": "Setup", + "title": "Getting started", "slug": "en+getting-started", - "github": "en/getting-started.md", + "github": "en/getting-started/getting-started.md", "value": null, "posts": [ - { - "title": "Arch Linux Installation", - "slug": "en+install-lotus-arch", - "github": "en/install-lotus-arch.md", - "value": null - }, - { - "title": "Ubuntu Installation", - "slug": "en+install-lotus-ubuntu", - "github": "en/install-lotus-ubuntu.md", - "value": null - }, - { - "title": "Fedora Installation", - "slug": "en+install-lotus-fedora", - "github": "en/install-lotus-fedora.md", - "value": null - }, - { - "title": "MacOS Installation", - "slug": "en+install-lotus-macos", - "github": "en/install-lotus-macos.md", - "value": null - }, - { - "title": "Updating Lotus", - "slug": "en+updating-lotus", - "github": "en/updating-lotus.md", - "value": null - }, - { - "title": "Join Testnet", - "slug": "en+join-testnet", - "github": "en/join-testnet.md", - "value": null - }, - { - "title": "Use Lotus with systemd", - "slug": "en+install-systemd-services", - "github": "en/install-systemd-services.md", - "value": null - }, - { - "title": "Setup Troubleshooting", - "slug": "en+setup-troubleshooting", - "github": "en/setup-troubleshooting.md", - "value": null - }, - { - "title": "Environment Variables", - "slug": "en+env-vars", - "github": "en/environment-vars.md", - "value": null - } + { + "title": "Setting up Lotus", + "slug": "en+setup", + "github": "en/getting-started/setup.md", + "value": null + }, + { + + "title": "Obtaining and sending FIL", + "slug": "en+wallet", + "github": "en/getting-started/wallet.md", + "value": null + }, + { + "title": "Setup troubleshooting", + "slug": "en+setup-troubleshooting", + "github": "en/getting-started/setup-troubleshooting.md", + "value": null + } ] }, { - "title": "Architecture", - "slug": "en+arch", - "github": "en/architecture.md", + "title": "Storing and retrieving data", + "slug": "en+store", + "github": "en/store/store.md", "value": null, "posts": [ - { - "title": "The Message Pool", - "slug": "en+mpool", - "github": "en/mpool.md", - "value": null - } + { + "title": "Making storage deals", + "slug": "en+making-deals", + "github": "en/store/making-deals.md", + "value": null + }, + { + "title": "Adding data from IPFS", + "slug": "en+adding-from-ipfs", + "github": "en/store/adding-from-ipfs.md", + "value": null + }, + { + "title": "Retrieving data", + "slug": "en+retriving", + "github": "en/store/retrieve.md", + "value": null + }, + { + "title": "Storage Troubleshooting", + "slug": "en+storage-troubleshooting", + "github": "en/store/storage-troubleshooting.md", + "value": null + } ] }, { - "title": "Storage Mining", + "title": "Storage mining", "slug": "en+mining", - "github": "en/mining.md", + "github": "en/mining/mining.md", "value": null, "posts": [ - { - "title": "Lotus Worker", - "slug": "en+lotus-worker", - "github": "en/mining-lotus-worker.md", - "value": null - }, - { - "title": "Static Ports", - "slug": "en+setting-a-static-port", - "github": "en/setting-a-static-port.md", - "value": null - }, - { - "title": "Mining Troubleshooting", - "slug": "en+mining-troubleshooting", - "github": "en/mining-troubleshooting.md", - "value": null - } + { + "title": "Miner setup", + "slug": "en+miner-setup", + "github": "en/mining/miner-setup.md", + "value": null + }, + { + "title": "Managing deals", + "slug": "en+managing-deals", + "github": "en/mining/managing-deals.md", + "value": null + }, + { + "title": "Lotus Worker", + "slug": "en+lotus-worker", + "github": "en/mining/lotus-seal-worker.md", + "value": null + }, + { + "title": "Benchmarking GPUs", + "slug": "en+gpus", + "github": "en/mining/gpus.md", + "value": null + }, + { + "title": "Mining Troubleshooting", + "slug": "en+mining-troubleshooting", + "github": "en/mining/mining-troubleshooting.md", + "value": null + } ] }, { - "title": "Storing Data", - "slug": "en+storing-data", - "github": "en/storing-data.md", + "title": "Building", + "slug": "en+building", + "github": "en/building/building.md", "value": null, "posts": [ - { - "title": "Storage Troubleshooting", - "slug": "en+storing-data-troubleshooting", - "github": "en/storing-data-troubleshooting.md", - "value": null - }, - { - "title": "Information for Miners", - "slug": "en+info-for-miners", - "github": "en/miner-deals.md", - "value": null - }, - { - "title": "IPFS Integration", - "slug": "en+ipfs-client-integration", - "github": "en/storing-ipfs-integration.md", - "value": null - } + { + "title": "Setting up remote API access", + "slug": "en+remote-api", + "github": "en/building/remote-api.md", + "value": null, + "posts": [] + }, + { + "title": "API endpoints and methods", + "slug": "en+api", + "github": "en/building/api.md", + "value": null, + "posts": [] + }, + { + "title": "API Reference", + "slug": "en+api-methods", + "github": "en/building/api-methods.md", + "value": null, + "posts": [] + }, + + { + "title": "Payment Channels", + "slug": "en+payment-channels", + "github": "en/building/payment-channels.md", + "value": null, + "posts": [] + }, + + { + "title": "Running a local devnet", + "slug": "en+local-devnet", + "github": "en/building/local-devnet.md", + "value": null, + "posts": [] + }, + { + "title": "Jaeger Tracing", + "slug": "en+jaeger-tracing", + "github": "en/building/jaeger-tracing.md", + "value": null, + "posts": [] + }, + + { + "title": "API Troubleshooting", + "slug": "en+api-troubleshooting", + "github": "en/building/api-troubleshooting.md", + "value": null, + "posts": [] + } ] }, { - "title": "Retrieving Data", - "slug": "en+retrieving-data", - "github": "en/retrieving-data.md", - "value": null, - "posts": [] - }, - { - "title": "Payment Channels", - "slug": "en+payment-channels", - "github": "en/payment-channels.md", - "value": null, - "posts": [] - }, - { - "title": "Command Line Interface", - "slug": "en+cli", - "github": "en/cli.md", - "value": null, - "posts": [] - }, - { - "title": "API", - "slug": "en+api", - "github": "en/api.md", + "title": "Lotus Architecture (WIP)", + "slug": "en+arch", + "github": "en/architectiure/architecture.md", "value": null, "posts": [ - { - "title": "Remote API Support", - "slug": "en+api-scripting-support", - "github": "en/api-scripting-support.md", - "value": null - }, - { - "title": "API Methods", - "slug": "en+api-methods", - "github": "en/api-methods.md", - "value": null - }, - { - "title": "API Troubleshooting", - "slug": "en+api-troubleshooting", - "github": "en/api-troubleshooting.md", - "value": null - } - ] - }, - { - "title": "Developer Tools", - "slug": "en+dev-tools", - "github": "en/dev-tools.md", - "value": null, - "posts": [ - { - "title": "Setup Local Devnet", - "slug": "en+setup-local-dev-net", - "github": "en/local-dev-net.md", - "value": null, - "posts": [] - }, - { - "title": "Jaeger Tracing", - "slug": "en+dev-tools-jaeger-tracing", - "github": "en/dev-tools-jaeger-tracing.md", - "value": null, - "posts": [] - } + { + "title": "The Message Pool", + "slug": "en+mpool", + "github": "en/architecture/mpool.md", + "value": null + } ] }, { @@ -224,7 +217,7 @@ "github": "en/.glossary.json", "value": null, "custom": { - "glossary": true + "glossary": true }, "posts": [] } diff --git a/documentation/en/about.md b/documentation/en/about.md new file mode 100644 index 000000000..ee8536ac9 --- /dev/null +++ b/documentation/en/about.md @@ -0,0 +1,14 @@ +# Lotus + +Lotus is an implementation of the **Filecoin Distributed Storage Network**. + +The **Lotus Node** (and the mining applications) can be built to join any of the [Filecoin networks](https://docs.filecoin.io/how-to/networks/). + +For more details about Filecoin, check out the [Filecoin Docs](https://docs.filecoin.io) and [Filecoin Spec](https://filecoin-project.github.io/specs/). + +## What can I learn here? + +* How to [install](en+installation) and [setup](en+setup) the Lotus software +* How to [store data on the Filecoin network](en+store) +* How to [setup a high performance FIL miner](en+miner-setup) +* How to [configure and access Lotus APIs](en+remote-api) diff --git a/documentation/en/api-scripting-support.md b/documentation/en/api-scripting-support.md deleted file mode 100644 index 653f144ed..000000000 --- a/documentation/en/api-scripting-support.md +++ /dev/null @@ -1,25 +0,0 @@ -# Remote API Support - -You may want to delegate the work **Lotus Miner** or **Lotus Node** performs to other machines. -Here is how to setup the necessary authorization and environment variables. - -## Environment variables - -Environmental variables are variables that are defined for the current shell and are inherited by any child shells or processes. Environmental variables are used to pass information into processes that are spawned from the shell. - -Using the [JWT you generated](https://lotu.sh/en+api#how-do-i-generate-a-token-18865), you can assign it and the **multiaddr** to the appropriate environment variable. - -```sh -# Lotus Node -FULLNODE_API_INFO="JWT_TOKEN:/ip4/127.0.0.1/tcp/1234/http" - -# Lotus Miner -MINER_API_INFO="JWT_TOKEN:/ip4/127.0.0.1/tcp/2345/http" -``` - -You can also use `lotus auth api-info --perm admin` to quickly create _API_INFO env vars - -- The **Lotus Node**'s `mutliaddr` is in `~/.lotus/api`. -- The default token is in `~/.lotus/token`. -- The **Lotus Miner**'s `multiaddr` is in `~/.lotusminer/config`. -- The default token is in `~/.lotusminer/token`. diff --git a/documentation/en/api.md b/documentation/en/api.md deleted file mode 100644 index 9760e2f32..000000000 --- a/documentation/en/api.md +++ /dev/null @@ -1,85 +0,0 @@ -# API - -Here is an early overview of how to make API calls. - -Implementation details for the **JSON-RPC** package are [here](https://github.com/filecoin-project/go-jsonrpc). - -## Overview: How do you modify the config.toml to change the API endpoint? - -API requests are made against `127.0.0.1:1234` unless you modify `.lotus/config.toml`. - -Options: - -- `http://[api:port]/rpc/v0` - HTTP endpoint -- `ws://[api:port]/rpc/v0` - Websocket endpoint -- `PUT http://[api:port]/rest/v0/import` - File import, it requires write permissions. - -## What methods can I use? - -For now, you can look into different files to find methods available to you based on your needs: - -- [Both Lotus node + miner APIs](https://github.com/filecoin-project/lotus/blob/master/api/api_common.go) -- [Lotus node API](https://github.com/filecoin-project/lotus/blob/master/api/api_full.go) -- [Lotus miner API](https://github.com/filecoin-project/lotus/blob/master/api/api_storage.go) - -The necessary permissions for each are in [api/struct.go](https://github.com/filecoin-project/lotus/blob/master/api/struct.go). - -## How do I make an API request? - -To demonstrate making an API request, we will take the method `ChainHead` from [api/api_full.go](https://github.com/filecoin-project/lotus/blob/master/api/api_full.go). - -```go -ChainHead(context.Context) (*types.TipSet, error) -``` - -And create a CURL command. In this command, `ChainHead` is included as `{ "method": "Filecoin.ChainHead" }`: - -```sh -curl -X POST \ - -H "Content-Type: application/json" \ - --data '{ "jsonrpc": "2.0", "method": "Filecoin.ChainHead", "params": [], "id": 3 }' \ - 'http://127.0.0.1:1234/rpc/v0' -``` - -If the request requires authorization, add an authorization header: - -```sh -curl -X POST \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $(cat ~/.lotusminer/token)" \ - --data '{ "jsonrpc": "2.0", "method": "Filecoin.ChainHead", "params": [], "id": 3 }' \ - 'http://127.0.0.1:1234/rpc/v0' -``` - -> In the future we will add a playground to make it easier to build and experiment with API requests. - -## CURL authorization - -To authorize your request, you will need to include the **JWT** in a HTTP header, for example: - -```sh --H "Authorization: Bearer $(cat ~/.lotusminer/token)" -``` - -Admin token is stored in `~/.lotus/token` for the **Lotus Node** or `~/.lotusminer/token` for the **Lotus Miner**. - -## How do I generate a token? - -To generate a JWT with custom permissions, use this command: - -```sh -# Lotus Node -lotus auth create-token --perm admin - -# Lotus Miner -lotus-miner auth create-token --perm admin -``` - -## What authorization level should I use? - -When viewing [api/apistruct/struct.go](https://github.com/filecoin-project/lotus/blob/master/api/apistruct/struct.go), you will encounter these types: - -- `read` - Read node state, no private data. -- `write` - Write to local store / chain, and `read` permissions. -- `sign` - Use private keys stored in wallet for signing, `read` and `write` permissions. -- `admin` - Manage permissions, `read`, `write`, and `sign` permissions. diff --git a/documentation/en/architecture.md b/documentation/en/architecture/architecture.md similarity index 99% rename from documentation/en/architecture.md rename to documentation/en/architecture/architecture.md index 619e04f05..8c4d7be5c 100644 --- a/documentation/en/architecture.md +++ b/documentation/en/architecture/architecture.md @@ -6,7 +6,7 @@ Filecoin protocol, validating the blocks and state transitions. The specification for the Filecoin protocol can be found [here](https://filecoin-project.github.io/specs/). For information on how to setup and operate a Lotus node, -please follow the instructions [here](https://lotu.sh/en+getting-started). +please follow the instructions [here](en+getting-started). # Components diff --git a/documentation/en/mpool.md b/documentation/en/architecture/mpool.md similarity index 100% rename from documentation/en/mpool.md rename to documentation/en/architecture/mpool.md diff --git a/documentation/en/api-methods.md b/documentation/en/building/api-methods.md similarity index 100% rename from documentation/en/api-methods.md rename to documentation/en/building/api-methods.md diff --git a/documentation/en/api-troubleshooting.md b/documentation/en/building/api-troubleshooting.md similarity index 100% rename from documentation/en/api-troubleshooting.md rename to documentation/en/building/api-troubleshooting.md diff --git a/documentation/en/building/api.md b/documentation/en/building/api.md new file mode 100644 index 000000000..626193ee2 --- /dev/null +++ b/documentation/en/building/api.md @@ -0,0 +1,38 @@ +# API endpoints and methods + +The API can be accessed on: + +- `http://[api:port]/rpc/v0` - HTTP RPC-API endpoint +- `ws://[api:port]/rpc/v0` - Websocket RPC-API endpoint +- `PUT http://[api:port]/rest/v0/import` - REST endpoint for file import (multipart upload). It requires write permissions. + +The RPC methods can be found in the [Reference](en+api-methods) and directly in the source code: + +- [Both Lotus node + miner APIs](https://github.com/filecoin-project/lotus/blob/master/api/api_common.go) +- [Lotus node API](https://github.com/filecoin-project/lotus/blob/master/api/api_full.go) +- [Lotus miner API](https://github.com/filecoin-project/lotus/blob/master/api/api_storage.go) + + +## JSON-RPC client + +Lotus uses its own Go library implementation of [JSON-RPC](https://github.com/filecoin-project/go-jsonrpc). + +## cURL example + +To demonstrate making an API request, we will take the method `ChainHead` from [api/api.go](https://github.com/filecoin-project/lotus/blob/master/api/api_full.go). + +```go +ChainHead(context.Context) (*types.TipSet, error) +``` + +And create a CURL command. In this command, `ChainHead` is included as `{ "method": "Filecoin.ChainHead" }`: + +```sh +curl -X POST \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $(cat ~/.lotusminer/token)" \ + --data '{ "jsonrpc": "2.0", "method": "Filecoin.ChainHead", "params": [], "id": 3 }' \ + 'http://127.0.0.1:1234/rpc/v0' +``` + +(See [this section](en+remote-api) to learn how to generate authorization tokens). diff --git a/documentation/en/building/building.md b/documentation/en/building/building.md new file mode 100644 index 000000000..5194f8314 --- /dev/null +++ b/documentation/en/building/building.md @@ -0,0 +1,5 @@ +# Building with Lotus + +Lotus applications provide HTTP (JSON-RPC) APIs that allow developers to control Lotus programatically. + +This section dives into how to setup and use these APIs, additionally providing information on advanced Lotus features and workflows, like Payment Channels or how to setup a fully local Lotus development network. diff --git a/documentation/en/dev-tools-jaeger-tracing.md b/documentation/en/building/jaeger-tracing.md similarity index 100% rename from documentation/en/dev-tools-jaeger-tracing.md rename to documentation/en/building/jaeger-tracing.md diff --git a/documentation/en/local-dev-net.md b/documentation/en/building/local-devnet.md similarity index 100% rename from documentation/en/local-dev-net.md rename to documentation/en/building/local-devnet.md diff --git a/documentation/en/payment-channels.md b/documentation/en/building/payment-channels.md similarity index 100% rename from documentation/en/payment-channels.md rename to documentation/en/building/payment-channels.md diff --git a/documentation/en/building/remote-api.md b/documentation/en/building/remote-api.md new file mode 100644 index 000000000..d0fedb51b --- /dev/null +++ b/documentation/en/building/remote-api.md @@ -0,0 +1,69 @@ +# Setting up remote API access + +The **Lotus Miner** and the **Lotus Node** applications come with their own local API endpoints setup by default when they are running. + +These endpoints are used by `lotus` and `lotus-miner` to interact with the running process. In this section we will explain how to enable remote access to the Lotus APIs. + +Note that instructions are the same for `lotus` and `lotus-miner`. For simplicity, we will just show how to do it with `lotus`. + +## Setting the listening interface for the API endpoint + +By default, the API listens on the local "loopback" interface (`127.0.0.1`). This is configured in the `config.toml` file: + +```toml +[API] +# ListenAddress = "/ip4/127.0.0.1/tcp/1234/http" +# RemoteListenAddress = "" +# Timeout = "30s" +``` + +To access the API remotely, Lotus needs to listen on the right IP/interface. The IP associated to each interface can be usually found with the command `ip a`. Once the right IP is known, it can be set in the configuration: + +```toml +[API] +ListenAddress = "/ip4//tcp/3453/http" # port is an example + +# Only relevant for lotus-miner +# This should be the IP:Port pair where the miner is reachable from anyone trying to dial to it. +# If you have placed a reverse proxy or a NAT'ing device in front of it, this may be different from +# the EXTERNAL_INTERFACE_IP. +RemoteListenAddress = "" +``` + +> `0.0.0.0` can be used too. This is a wildcard that means "all interfaces". Depending on the network setup, this may affect security (listening on the wrong, exposed interface). + +After making these changes, please restart the affected process. + +## Issuing tokens + +Any client wishing to talk to the API endpoints will need a token. Tokens can be generated with: + +```sh +lotus auth create-token --perm +``` + +(similarly for the Lotus Miner). + +The permissions work as follows: + +- `read` - Read node state, no private data. +- `write` - Write to local store / chain, and `read` permissions. +- `sign` - Use private keys stored in wallet for signing, `read` and `write` permissions. +- `admin` - Manage permissions, `read`, `write`, and `sign` permissions. + + +Tokens can then be used in applications by setting an Authorization header as: + +``` +Authorization: Bearer +``` + + +## Environment variables + +`lotus`, `lotus-miner` and `lotus-worker` can actually interact with their respective applications running on a different node. All is needed to configure them are the following the *environment variables*: + +```sh +FULLNODE_API_INFO="TOKEN:/ip4//tcp//http" +MINER_API_INFO="TOKEN:/ip4//tcp//http" +``` diff --git a/documentation/en/cli.md b/documentation/en/cli.md deleted file mode 100644 index fd26400d0..000000000 --- a/documentation/en/cli.md +++ /dev/null @@ -1,108 +0,0 @@ -# Lotus Command Line Interface - -The Command Line Interface (CLI) is a convenient way to interact with -a Lotus node. You can use the CLI to operate your node, -get information about the blockchain, -manage your accounts and transfer funds, -create storage deals, and much more! - -The CLI is intended to be self-documenting, so when in doubt, simply add `--help` -to whatever command you're trying to run! This will also display all of the -input parameters that can be provided to a command. - -We highlight some of the commonly -used features of the CLI below. -All CLI commands should be run from the home directory of the Lotus project. - -## Operating a Lotus node - -### Starting up a node - -```sh -lotus daemon -``` -This command will start up your Lotus node, with its API port open at 1234. -You can pass `--api=` to use a different port. - -### Checking your sync progress - -```sh -lotus sync status -``` -This command will print your current tipset height under `Height`, and the target tipset height -under `Taregt`. - -You can also run `lotus sync wait` to get constant updates on your sync progress. - -### Getting the head tipset - -```sh -lotus chain head -``` - -### Control the logging level - -```sh -lotus log set-level -``` -This command can be used to toggle the logging levels of the different -systems of a Lotus node. In decreasing order -of logging detail, the levels are `debug`, `info`, `warn`, and `error`. - -As an example, -to set the `chain` and `blocksync` to log at the `debug` level, run -`lotus log set-level --system chain --system blocksync debug`. - -To see the various logging system, run `lotus log list`. - -### Find out what version of Lotus you're running - -```sh -lotus version -``` - -## Managing your accounts - -### Listing accounts in your wallet - -```sh -lotus wallet list -``` - -### Creating a new account - -```sh -lotus wallet new bls -``` -This command will create a new BLS account in your wallet; these -addresses start with the prefix `t3`. Running `lotus wallet new secp256k1` -(or just `lotus wallet new`) will create -a new Secp256k1 account, which begins with the prefix `t1`. - -### Getting an account's balance - -```sh -lotus wallet balance
-``` - -### Transferring funds - -```sh -lotus send --source= -``` -This command will transfer `amount` (in attoFIL) from `source address` to `destination address`. - -### Importing an account into your wallet - -```sh -lotus wallet import -``` -This command will import an account whose private key is saved at the specified file. - -### Exporting an account from your wallet - -```sh -lotus wallet export
-``` -This command will print out the private key of the specified address -if it is in your wallet. Always be careful with your private key! diff --git a/documentation/en/dev-tools.md b/documentation/en/dev-tools.md deleted file mode 100644 index 60b9b26d4..000000000 --- a/documentation/en/dev-tools.md +++ /dev/null @@ -1,3 +0,0 @@ -# Developer Tools - -> Running a local network can be a great way to understand how Lotus works and test your setup. diff --git a/documentation/en/environment-vars.md b/documentation/en/environment-vars.md deleted file mode 100644 index 9d455a74d..000000000 --- a/documentation/en/environment-vars.md +++ /dev/null @@ -1,65 +0,0 @@ -# Lotus Environment Variables - -## Building - -## Common - -The environment variables are common across most lotus binaries. - -### `LOTUS_FD_MAX` - -Sets the file descriptor limit for the process. This should be set high (8192 -or higher) if you ever notice 'too many open file descriptor' errors. - -### `LOTUS_JAEGER` - -This can be set to enable jaeger trace reporting. The value should be the url -of the jaeger trace collector, the default for most jaeger setups should be -`localhost:6831`. - -### `LOTUS_DEV` - -If set to a non-empty value, certain parts of the application will print more -verbose information to aid in development of the software. Not recommended for -end users. - -## Lotus Daemon - -### `LOTUS_PATH` - -Sets the location for the lotus daemon on-disk repo. If left empty, this defaults to `~/.lotus`. - -### `LOTUS_SKIP_GENESIS_CHECK` - -Can be set to `_yes_` if you wish to run a lotus network with a different -genesis than the default one built into your lotus binary. - -### `LOTUS_CHAIN_TIPSET_CACHE` - -Sets the cache size for the chainstore tipset cache. The default value is 8192, -but if your usage of the lotus API involves frequent arbitrary tipset lookups, -you may want to increase this. - -### `LOTUS_CHAIN_INDEX_CACHE` - -Sets the cache size for the chainstore epoch index cache. The default value is 32768, -but if your usage of the lotus API involves frequent deep chain lookups for -block heights that are very far from the current chain height, you may want to -increase this. - - -### `LOTUS_BSYNC_MSG_WINDOW` - -Set the initial maximum window size for message fetching blocksync requests. If -you have a slower internet connection and are having trouble syncing, you might -try lowering this down to 10-20 for a 'poor' internet connection. - -## Lotus Miner - -A number of environment variables are respected for configuring the behavior of the filecoin proving subsystem. For more details on those [see here](https://github.com/filecoin-project/rust-fil-proofs/#settings). - -### `LOTUS_MINER_PATH` - -Sets the location for the lotus miners on-disk repo. If left empty, this defaults to `~/.lotusminer`. - - diff --git a/documentation/en/faqs.md b/documentation/en/faqs.md index c2d526830..74119a5b6 100644 --- a/documentation/en/faqs.md +++ b/documentation/en/faqs.md @@ -11,7 +11,6 @@ go [here](https://filecoin.io/faqs/). Lotus is an implementation of the **Filecoin Distributed Storage Network**, written in Go. It is designed to be modular and interoperable with any other implementation of the Filecoin Protocol. -More information about Lotus can be found [here](https://lotu.sh/). ### What are the components of Lotus? @@ -30,21 +29,19 @@ to a Lotus Node over the JSON-RPC API. ### How do I set up a Lotus Node? -Follow the instructions found [here](https://lotu.sh/en+getting-started). +Follow the instructions found [here](en+install) and [here](en+setup). ### Where can I get the latest version of Lotus? -Download the binary tagged as the `Latest Release` from the - [Lotus Github repo](https://github.com/filecoin-project/lotus/releases). +Download the binary tagged as the `Latest Release` from the [Lotus Github repo](https://github.com/filecoin-project/lotus/releases) or checkout the `master` branch of the source repository. ### What operating systems can Lotus run on? -Lotus can build and run on most Linux and MacOS systems with at least -8GB of RAM. Windows is not yet supported. +Lotus can build and run on most Linux and MacOS systems with [at least 8GB of RAM](en+install#hardware-requirements-1). Windows is not yet supported. ### How can I update to the latest version of Lotus? -To update Lotus, follow the instructions [here](https://lotu.sh/en+updating-lotus). +To update Lotus, follow the instructions [here](en+update). ### How do I prepare a fresh installation of Lotus? @@ -52,7 +49,7 @@ Stop the Lotus daemon, and delete all related files, including sealed and chain running `rm ~/.lotus ~/.lotusminer`. Then, install Lotus afresh by following the instructions -found [here](https://lotu.sh/en+getting-started). +found [here](en+install). ### Can I configure where the node's config and data goes? @@ -73,48 +70,45 @@ directory for more. ### How can I send a request over the JSON-RPC API? Information on how to send a `cURL` request to the JSON-RPC API can be found -[here](https://lotu.sh/en+api). A JavaScript client is under development. +[here](en+api). ### What are the requests I can send over the JSON-RPC API? -Please have a look at the -[source code](https://github.com/filecoin-project/lotus/blob/master/api/api_full.go) -for a list of methods supported by the JSON-RPC API. +Please have a look [here](en+api). + + ## The Test Network ### What is Testnet? Testnet is a live network of Lotus Nodes run by the community for testing purposes. - It has 2 PiB of storage (and growing!) dedicated to it. ### Is FIL on the Testnet worth anything? -Nothing at all! Real-world incentives may be provided in a future phase of Testnet, but this is -yet to be confirmed. +Nothing at all! ### How can I see the status of Testnet? The [dashboard](https://stats.testnet.filecoin.io/) displays the status of the network as -well as a ton -of other metrics you might find interesting. +well as a ton of other metrics you might find interesting. ## Mining with a Lotus Node on Testnet ### How do I get started mining with Lotus? -Follow the instructions found [here](https://lotu.sh/en+mining). +Follow the instructions found [here](en+mining). ### What are the minimum hardware requirements? An example test configuration, and minimum hardware requirements can be found -[here](https://lotu.sh/en+hardware-mining). +[here](en+install#hardware-requirements-8). Note that these might NOT be the minimum requirements for mining on Mainnet. ### What are some GPUs that have been tested? -A list of benchmarked GPUs can be found [here](https://lotu.sh/en+hardware-mining#benchmarked-gpus-7393). +See previous question. ### Why is my GPU not being used when sealing a sector? @@ -135,4 +129,4 @@ You can do so by changing the storage path variable for the second miner, e.g., ### How do I setup my own local devnet? -Follow the instructions found [here](https://lotu.sh/en+setup-local-dev-net). +Follow the instructions found [here](en+local-devnet). diff --git a/documentation/en/getting-started.md b/documentation/en/getting-started.md deleted file mode 100644 index e38a2ab97..000000000 --- a/documentation/en/getting-started.md +++ /dev/null @@ -1,23 +0,0 @@ -# Lotus - -Lotus is an implementation of the **Filecoin Distributed Storage Network**. You can run the Lotus software client to join the **Filecoin Testnet**. - -For more details about Filecoin, check out the [Filecoin Docs](https://docs.filecoin.io) and [Filecoin Spec](https://filecoin-project.github.io/specs/). - -## What can I learn here? - -- How to install Lotus on [Arch Linux](https://lotu.sh/en+install-lotus-arch), [Ubuntu](https://lotu.sh/en+install-lotus-ubuntu), or [MacOS](https://lotu.sh/en+install-lotus-macos). -- Joining the [Lotus Testnet](https://lotu.sh/en+join-testnet). -- [Storing](https://lotu.sh/en+storing-data) or [retrieving](https://lotu.sh/en+retrieving-data) data. -- Mining Filecoin using the **Lotus Miner** in your [CLI](https://lotu.sh/en+mining). - -## How is Lotus designed? - -Lotus is architected modularly to keep clean API boundaries while using the same process. Installing Lotus will include two separate programs: - -- The **Lotus Node** -- The **Lotus Miner** - -The **Lotus Miner** is intended to be run on the machine that manages a single miner instance, and is meant to communicate with the **Lotus Node** via the websocket **JSON-RPC** API for all of the chain interaction needs. - -This way, a mining operation may easily run a **Lotus Miner** or many of them, connected to one or many **Lotus Node** instances. diff --git a/documentation/en/getting-started/getting-started.md b/documentation/en/getting-started/getting-started.md new file mode 100644 index 000000000..99b4095d4 --- /dev/null +++ b/documentation/en/getting-started/getting-started.md @@ -0,0 +1,3 @@ +# Getting started + +This section will get you started with Lotus. We will setup the Lotus daemon (that should already be [installed](en+install)), start it, create a wallet and use it to send and receive some Filecoin. diff --git a/documentation/en/setup-troubleshooting.md b/documentation/en/getting-started/setup-troubleshooting.md similarity index 60% rename from documentation/en/setup-troubleshooting.md rename to documentation/en/getting-started/setup-troubleshooting.md index a1c78b51b..f27a3faa5 100644 --- a/documentation/en/setup-troubleshooting.md +++ b/documentation/en/getting-started/setup-troubleshooting.md @@ -1,5 +1,12 @@ # Setup Troubleshooting + +## Error: initializing node error: cbor input had wrong number of fields + +This happens when you are starting Lotus which has been compiled for one network, but it encounters data in the Lotus data folder which is for a different network, or for an older incompatible version. + +The solution is to clear the data folder (see below). + ## Config: Clearing data Here is a command that will delete your chain data, stored wallets, stored data and any miners you have set up: @@ -8,7 +15,7 @@ Here is a command that will delete your chain data, stored wallets, stored data rm -rf ~/.lotus ~/.lotusminer ``` -This command usually resolves any issues with running `lotus` but it is not always required for updates. We will share information about when resetting your chain data and miners is required for an update in the future. +Note you do not always need to clear your data for [updating](en+update). ## Error: Failed to connect bootstrap peer @@ -33,6 +40,8 @@ ERROR hello hello/hello.go:81 other peer has different genesis! ## Config: Open files limit +Lotus will attempt to set up the file descriptor (FD) limit automatically. If that does not work, you can still configure your system to allow higher than the default values. + On most systems you can check the open files limit with: ```sh @@ -44,3 +53,5 @@ You can also modify this number by using the `ulimit` command. It gives you the ```sh ulimit -n 10000 ``` + +Note that this is not persisted and that systemd manages its own FD limits for services. Please use your favourite search engine to find instructions on how to persist and configure FD limits for your system. diff --git a/documentation/en/getting-started/setup.md b/documentation/en/getting-started/setup.md new file mode 100644 index 000000000..e751da80b --- /dev/null +++ b/documentation/en/getting-started/setup.md @@ -0,0 +1,169 @@ +# Setting up Lotus + +Your Lotus binaries have been installed and you are ready to start participating in the Filecoin network. + +## Selecting the right network + +You should have built the Lotus binaries from the right Github branch and Lotus will be fully setup to join the matching [Filecoin network](https://docs.filecoin.io/how-to/networks/). For more information on switching networks, check the [updating Lotus section](en+update). + +## Starting the daemon + +To start the daemon simply run: + +```sh +lotus daemon +``` + +or if you are using the provided systemd service files, do: + +```sh +systemctl start lotus-daemon +``` + +__If you are using Lotus from China__, make sure you set the following environment variable before running Lotus: + +``` +export IPFS_GATEWAY="https://proof-parameters.s3.cn-south-1.jdcloud-oss.com/ipfs/" +``` + + +During the first start, Lotus: + +* Will setup its data folder at `~/.lotus` +* Will download the necessary parameters +* Start syncing the Lotus chain + +If you started lotus using systemd, the logs will appear in `/var/log/lotus/daemon.log` (not in journalctl as usual), otherwise you will see them in your screen. + +Do not be appalled by the amount of warnings and sometimes errors showing in the logs, there are usually part of the usual functioning of the daemon as part of a distributed network. + +## Waiting to sync + +After the first start, the chain will start syncing until it has reached the tip. You can check how far the syncing process is with: + +```sh +lotus sync status +``` + +You can also interactively wait for the chain to be fully synced with: + +```sh +lotus sync wait +``` + +## Interacting with the Lotus daemon + +As shown above, the `lotus` command allows to interact with the running daemon. You will see it getting used in many of the documentation examples. + +This command-line-interface is self-documenting: + +```sh +# Show general help +lotus --help +# Show specific help for the "client" subcommand +lotus client --help +``` + +For example, after your Lotus daemon has been running for a few minutes, use `lotus` to check the number of other peers that it is connected to in the Filecoin network: + +```sh +lotus net peers +``` + +## Controlling the logging level + +```sh +lotus log set-level +``` +This command can be used to toggle the logging levels of the different +systems of a Lotus node. In decreasing order +of logging detail, the levels are `debug`, `info`, `warn`, and `error`. + +As an example, +to set the `chain` and `blocksync` to log at the `debug` level, run +`lotus log set-level --system chain --system blocksync debug`. + +To see the various logging system, run `lotus log list`. + + +## Configuration + +### Configuration file + +The Lotus daemon stores a configuration file in `~/.lotus/config.toml`. Note that by default all settings are commented. Here is an example configuration: + +```toml +[API] + # Binding address for the Lotus API + ListenAddress = "/ip4/127.0.0.1/tcp/1234/http" + # Not used by lotus daemon + RemoteListenAddress = "" + # General network timeout value + Timeout = "30s" + +# Libp2p provides connectivity to other Filecoin network nodes +[Libp2p] + # Binding address swarm - 0 means random port. + ListenAddresses = ["/ip4/0.0.0.0/tcp/0", "/ip6/::/tcp/0"] + # Insert any addresses you want to explicitally + # announce to other peers here. Otherwise, they are + # guessed. + AnnounceAddresses = [] + # Insert any addresses to avoid announcing here. + NoAnnounceAddresses = [] + # Connection manager settings, decrease if your + # machine is overwhelmed by connections. + ConnMgrLow = 150 + ConnMgrHigh = 180 + ConnMgrGrace = "20s" + +# Pubsub is used to broadcast information in the network +[Pubsub] + Bootstrapper = false + RemoteTracer = "/dns4/pubsub-tracer.filecoin.io/tcp/4001/p2p/QmTd6UvR47vUidRNZ1ZKXHrAFhqTJAD27rKL9XYghEKgKX" + +# This section can be used to enable adding and retriving files from IPFS +[Client] + UseIpfs = false + IpfsMAddr = "" + IpfsUseForRetrieval = false + +# Metrics configuration +[Metrics] + Nickname = "" + HeadNotifs = false +``` + +### Ensuring connectivity to your Lotus daemon + +Usually your lotus daemon will establish connectivity with others in the network and try to make itself diallable using uPnP. If you wish to manually ensure that your daemon is reachable: + +* Set a fixed port of your choice in the `ListenAddresses` in the Libp2p section (i.e. 6665). +* Open a port in your router that is forwarded to this port. This is usually called featured as "Port forwarding" and the instructions differ from router model to model but there are many guides online. +* Add your public IP/port to `AnnounceAddresses`. i.e. `/ip4//tcp/6665/`. + +Note that it is not a requirement to use Lotus as a client to the network to be fully reachable, as your node already connects to others directly. + + +### Environment variables + +Common to most Lotus binaries: + +* `LOTUS_FD_MAX`: Sets the file descriptor limit for the process +* `LOTUS_JAEGER`: Sets the Jaeger URL to send traces. See TODO. +* `LOTUS_DEV`: Any non-empty value will enable more verbose logging, useful only for developers. + +Specific to the *Lotus daemon*: + +* `LOTUS_PATH`: Location to store Lotus data (defaults to `~/.lotus`). +* `LOTUS_SKIP_GENESIS_CHECK=_yes_`: Set only if you wish to run a lotus network with a different genesis block. +* `LOTUS_CHAIN_TIPSET_CACHE`: Sets the size for the chainstore tipset cache. Defaults to `8192`. Increase if you perform frequent arbitrary tipset lookups. +* `LOTUS_CHAIN_INDEX_CACHE`: Sets the size for the epoch index cache. Defaults to `32768`. Increase if you perform frequent deep chain lookups for block heights far from the latest height. +* `LOTUS_BSYNC_MSG_WINDOW`: Set the initial maximum window size for message fetching blocksync request. Set to 10-20 if you have an internet connection with low bandwidth. + +Specific to the *Lotus miner*: + +* `LOTUS_MINER_PATH`: Location for the miner's on-disk repo. Defaults to `./lotusminer`. +* A number of environment variables are respected for configuring the behaviour of the Filecoin proving subsystem. [See here](en+miner-setup). + + diff --git a/documentation/en/getting-started/wallet.md b/documentation/en/getting-started/wallet.md new file mode 100644 index 000000000..25a67fb09 --- /dev/null +++ b/documentation/en/getting-started/wallet.md @@ -0,0 +1,58 @@ +# Obtaining and sending FIL + +In order to receive and send FIL with Lotus you will need to have installed the program and be running the Lotus daemon. + +## Creating a wallet + + +```sh +lotus wallet new bls +``` + +This will print your Filecoin address. + +Your wallet information is stored in the `~/.lotus/keystore` (or `$LOTUS_PATH/keystore`). For instructions on export/import, see below. + +You can create multiple wallets and list them with: + +```sh +lotus wallet list +``` + +## Obtaining FIL + +FIL can be obtained either by using one of the Faucets (available for the test networks) or by buying it from an exchange supporting FIL trading (once mainnet has launched). + +Once you have received some FIL you can check your balance with: + +```sh +lotus wallet balance +``` + +Remember that your will only see the latest balance when your daemon is fully synced to the chain. + +## Sending FIL + +Sending some FIL can be achieved by running: + +```sh +lotus wallet send
+``` + +Make sure to check `lotus wallet send --help` for additional options. + +## Exporting and importing a wallet + +You can export and re-import a wallet with: + +```sh +lotus wallet export
> wallet.private +``` + +and: + +```sh +lotus wallet import wallet.private +``` + +Keep your wallet's private key safe! diff --git a/documentation/en/hardware-mining.md b/documentation/en/hardware-mining.md deleted file mode 100644 index d421f6fb1..000000000 --- a/documentation/en/hardware-mining.md +++ /dev/null @@ -1,54 +0,0 @@ -# Protocol Labs Standard Testing Configuration - -> This documentation page describes the standard testing configuration the Protocol Labs team has used to test **Lotus Miner**s on Lotus. There is no guarantee this testing configuration will be suitable for Filecoin storage mining at MainNet launch. If you need to buy new hardware to join the Filecoin Testnet, we recommend to buy no more hardware than you require for testing. To learn more please read this [Protocol Labs Standard Testing Configuration post](https://filecoin.io/blog/filecoin-testnet-mining/). - -**Sector sizes** and **minimum pledged storage** required to mine blocks are two very important Filecoin Testnet parameters that impact hardware decisions. We will continue to refine all parameters during Testnet. - -BECAUSE OF THIS, OUR STANDARD TESTING CONFIGURATION FOR FILECOIN MAINNET CAN AND WILL CHANGE. YOU HAVE BEEN WARNED. - -## Example configuration - -The setup below is a minimal example for sealing 32 GiB sectors on Lotus: - -- 2 TB of hard drive space. -- 8 core CPU -- 128 GiB of RAM - -Note that 1GB sectors don't require as high of specs, but are likely to be removed as we improve the performance of 32GB sector sealing. - -For the first part of the sealing process, AMD CPU's are __highly recommended__, because of the `Intel SHA Extensions` instruction set that is available there ever since the `Zen` microarchitecture. Hence, AMD CPU's seem to perform much better on the testnet than other CPU's. Contrary to what the name implies, this extended instruction set is not available on recent Intel desktop/server chips. - -## Testnet discoveries - -- If you only have 128GiB of ram, enabling 256GB of **NVMe** swap on an SSD will help you avoid out-of-memory issues while mining. - -## Benchmarked GPUs - -GPUs are a must for getting **block rewards**. Here are a few that have been confirmed to generate **SNARKs** quickly enough to successfully mine blocks on the Lotus Testnet. - -- GeForce RTX 2080 Ti -- GeForce RTX 2080 SUPER -- GeForce RTX 2080 -- GeForce GTX 1080 Ti -- GeForce GTX 1080 -- GeForce GTX 1060 - -## Testing other GPUs - -If you want to test a GPU that is not explicitly supported, use the following global **environment variable**: - -```sh -BELLMAN_CUSTOM_GPU=":" -``` - -Here is an example of trying a GeForce GTX 1660 Ti with 1536 cores. - -```sh -BELLMAN_CUSTOM_GPU="GeForce GTX 1660 Ti:1536" -``` - -To get the number of cores for your GPU, you will need to check your card’s specifications. - -## Benchmarking - -Here is a [benchmarking tool](https://github.com/filecoin-project/lotus/tree/master/cmd/lotus-bench) and a [GitHub issue thread](https://github.com/filecoin-project/lotus/issues/694) for those who wish to experiment with and contribute hardware setups for the **Filecoin Testnet**. diff --git a/documentation/en/hardware.md b/documentation/en/hardware.md deleted file mode 100644 index f6250548a..000000000 --- a/documentation/en/hardware.md +++ /dev/null @@ -1,7 +0,0 @@ -# Hardware - -> This page is a work in progress. Exact mining requirements are still in the works. - -Lotus can build and run on most [Linux](https://ubuntu.com/) and [MacOS](https://www.apple.com/macos) systems with at least 8GiB of RAM. - -Windows is not yet supported. diff --git a/documentation/en/install-lotus-arch.md b/documentation/en/install-lotus-arch.md deleted file mode 100644 index 8e06aae4e..000000000 --- a/documentation/en/install-lotus-arch.md +++ /dev/null @@ -1,51 +0,0 @@ -# Arch Linux Instructions - -These steps will install the following dependencies: - -- go (1.14 or higher) -- gcc (7.4.0 or higher) -- git (version 2 or higher) -- bzr (some go dependency needs this) -- jq -- pkg-config -- opencl-icd-loader -- opencl driver (like nvidia-opencl on arch) (for GPU acceleration) -- opencl-headers (build) -- rustup (proofs build) -- llvm (proofs build) -- clang (proofs build) - -### Install dependencies - -```sh -sudo pacman -Syu opencl-icd-loader gcc git bzr jq pkg-config opencl-icd-loader opencl-headers -``` - -### Install Go 1.14 - -Install the latest version of Go by following [the docs on their website](https://golang.org/doc/install). - -### Clone the Lotus repository - -```sh -git clone https://github.com/filecoin-project/lotus.git -cd lotus/ -``` - -### Build the Lotus binaries from source and install - -! **If you are running an AMD platform or if your CPU supports SHA extensions you will want to build the Filecoin proofs natively** - -```sh -make clean && make all -sudo make install -``` - -#### Native Filecoin FFI building - -```sh -env env RUSTFLAGS="-C target-cpu=native -g" FFI_BUILD_FROM_SOURCE=1 make clean deps all -sudo make install -``` - -After installing Lotus, you can run the `lotus` command directly from your CLI to see usage documentation. Next, you can join the [Lotus Testnet](https://lotu.sh/en+join-testnet). diff --git a/documentation/en/install-lotus-fedora.md b/documentation/en/install-lotus-fedora.md deleted file mode 100644 index c37161b7a..000000000 --- a/documentation/en/install-lotus-fedora.md +++ /dev/null @@ -1,54 +0,0 @@ -# Fedora Instructions - -> tested on 30 - -**NOTE:** If you have an AMD GPU the opencl instructions may be incorrect... - -These steps will install the following dependencies: - -- go (1.14 or higher) -- gcc (7.4.0 or higher) -- git (version 2 or higher) -- bzr (some go dependency needs this) -- jq -- pkg-config -- rustup (proofs build) -- llvm (proofs build) -- clang (proofs build) - -### Install dependencies - -```sh -$ sudo dnf -y update -$ sudo dnf -y install gcc git bzr jq pkgconfig mesa-libOpenCL mesa-libOpenCL-devel opencl-headers ocl-icd ocl-icd-devel clang llvm -$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -``` - -### Install Go 1.14 - -Install the latest version of Go by following [the docs on their website](https://golang.org/doc/install). - -### Clone the Lotus repository - -```sh -git clone https://github.com/filecoin-project/lotus.git -cd lotus/ -``` - -### Build the Lotus binaries from source and install - -! **If you are running an AMD platform or if your CPU supports SHA extensions you will want to build the Filecoin proofs natively** - -```sh -$ make clean && make all -$ sudo make install -``` - -#### Native Filecoin FFI building - -```sh -env env RUSTFLAGS="-C target-cpu=native -g" FFI_BUILD_FROM_SOURCE=1 make clean deps all -sudo make install -``` - -After installing Lotus, you can run the `lotus` command directly from your CLI to see usage documentation. Next, you can join the [Lotus TestNet](https://lotu.sh/en+join-testnet). diff --git a/documentation/en/install-lotus-ubuntu.md b/documentation/en/install-lotus-ubuntu.md deleted file mode 100644 index 500650692..000000000 --- a/documentation/en/install-lotus-ubuntu.md +++ /dev/null @@ -1,54 +0,0 @@ -# Ubuntu Instructions - -These steps will install the following dependencies: - -- go (1.14 or higher) -- gcc (7.4.0 or higher) -- git (version 2 or higher) -- bzr (some go dependency needs this) -- jq -- pkg-config -- opencl-icd-loader -- opencl driver (like nvidia-opencl on arch) (for GPU acceleration) -- opencl-headers (build) -- rustup (proofs build) -- llvm (proofs build) -- clang (proofs build) - -### Install dependencies - -```sh -sudo apt update -sudo apt install mesa-opencl-icd ocl-icd-opencl-dev gcc git bzr jq pkg-config curl -sudo apt upgrade -``` - -### Install Go 1.14 - -Install the latest version of Go by following [the docs on their website](https://golang.org/doc/install). - -### Clone the Lotus repository - -```sh -git clone https://github.com/filecoin-project/lotus.git -cd lotus/ -``` - -### Build the Lotus binaries from source and install - -! **If you are running an AMD platform or if your CPU supports SHA extensions you will want to build the Filecoin proofs natively** - -```sh -make clean && make all -sudo make install -``` - -#### Native Filecoin FFI building - -```sh -env env RUSTFLAGS="-C target-cpu=native -g" FFI_BUILD_FROM_SOURCE=1 make clean deps all -sudo make install -``` - - -After installing Lotus, you can run the `lotus` command directly from your CLI to see usage documentation. Next, you can join the [Lotus Testnet](https://lotu.sh/en+join-testnet). diff --git a/documentation/en/install-systemd-services.md b/documentation/en/install-systemd-services.md deleted file mode 100644 index fbde1feec..000000000 --- a/documentation/en/install-systemd-services.md +++ /dev/null @@ -1,145 +0,0 @@ -# Use Lotus with systemd - -Lotus is capable of running as a systemd service daemon. You can find installable service files for systemd in the [lotus repo scripts directory](https://github.com/filecoin-project/lotus/tree/master/scripts) as files with `.service` extension. In order to install these service files, you can copy these `.service` files to the default systemd unit load path. - -The services expect their binaries to be present in `/usr/local/bin/`. You can use `make` to install them by running: - -```sh -$ sudo make install -``` - -for `lotus` and `lotus-storage-miner` and - -```sh -$ sudo make install-chainwatch -``` - -for the `chainwatch` tool. - -## Installing services via `make` - -If your host uses the default systemd unit load path, the `lotus-daemon` and `lotus-miner` services can be installed by running: - -```sh -$ sudo make install-services -``` - -To install the the `lotus-chainwatch` service run: - -```sh -$ sudo make install-chainwatch-service -``` - -You can install all services together by running: - -```sh -$ sudo make install-all-services -``` - -The `lotus-daemon` and the `lotus-miner` services can be installed individually too by running: - -```sh -$ sudo make install-daemon-service -``` - -and - -```sh -$ sudo make install-miner-service -``` - -### Notes - -When installing the `lotus-miner` and/or `lotus-chainwatch` service the `lotus-daemon` service gets automatically installed since the other two services depend on it being installed to run. - -All `install-*-service*` commands will install the latest binaries in the lotus build folders to `/usr/local/bin/`. If you do not want to use the latest build binaries please copy the `*.service` files by hand. - -## Removing via `make` - -All services can beremoved via `make`. To remove all services together run: - -```sh -$ sudo make clean-all-services -``` - -Individual services can be removed by running: - -```sh -$ sudo make clean-chainwatch-services -$ sudo make clean-miner-services -$ sudo make clean-daemon-services -``` - -### Notes - -The services will be stoppend and disabled when removed. - -Removing the `lotus-daemon` service will automatically remove the depending services `lotus-miner` and `lotus-chainwatch`. - - -## Controlling services - -All service can be controlled with the `systemctl`. A few basic control commands are listed below. To get detailed infos about the capabilities of the `systemctl` command please consult your distributions man pages by running: - -```sh -$ man systemctl -``` - -### Start/Stop services - -You can start the services by running: - -```sh -$ sudo systemctl start lotus-daemon -$ sudo systemctl start lotus-miner -$ sudo systemctl start lotus-chainwatch -``` - -and can be stopped by running: - -```sh -$ sudo systemctl stop lotus-daemon -$ sudo systemctl stop lotus-miner -$ sudo systemctl stop lotus-chainwatch -``` - -### Enabling services on startup - -To enable the services to run automatically on startup execute: - -```sh -$ sudo systemctl enable lotus-daemon -$ sudo systemctl enable lotus-miner -$ sudo systemctl enable lotus-chainwatch -``` - -To disable the services on startup run: - -```sh -$ sudo systemctl disable lotus-daemon -$ sudo systemctl disable lotus-miner -$ sudo systemctl disable lotus-chainwatch -``` -### Notes - -Systemd will not let services be enabled or started without their requirements. Starting the `lotus-chainwatch` and/or `lotus-miner` service with automatically start the `lotus-daemon` service (if installed!). Stopping the `lotus-daemon` service will stop the other two services. The same pattern is executed for enabling and disabling the services. - -## Interacting with service logs - -Logs from the services can be reviewed using `journalctl`. - -### Follow logs from a specific service unit - -```sh -$ sudo journalctl -u lotus-daemon -f -``` - -### View logs in reverse order - -```sh -$ sudo journalctl -u lotus-miner -r -``` - -### Log files - -Besides the systemd service logs all services save their own log files in `/var/log/lotus/`. diff --git a/documentation/en/installation/install-linux.md b/documentation/en/installation/install-linux.md new file mode 100644 index 000000000..6fe12996e --- /dev/null +++ b/documentation/en/installation/install-linux.md @@ -0,0 +1,129 @@ +# Linux installation + +This page will show you the steps to build and install Lotus in your Linux computer. + +## Dependencies + +### System dependencies + +First of all, building Lotus will require installing some system dependencies, usually provided by your distribution. + +For Arch Linux: + +```sh +sudo pacman -Syu opencl-icd-loader gcc git bzr jq pkg-config opencl-icd-loader opencl-headers +``` + +For Ubuntu: + +```sh +sudo apt update +sudo apt install mesa-opencl-icd ocl-icd-opencl-dev gcc git bzr jq pkg-config curl +sudo apt upgrade +``` + +For Fedora: + +```sh +sudo dnf -y update +sudo dnf -y install gcc git bzr jq pkgconfig mesa-libOpenCL mesa-libOpenCL-devel opencl-headers ocl-icd ocl-icd-devel clang llvm +``` + +For OpenSUSE: + +```sh +sudo zypper in gcc git jq make libOpenCL1 opencl-headers ocl-icd-devel clang llvm +sudo ln -s /usr/lib64/libOpenCL.so.1 /usr/lib64/libOpenCL.so +``` + +### Rustup + +Lotus needs [rustup](https://rustup.rs/): + +```sh +curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh +``` + +Please make sure your `$PATH` variable is correctly configured after the rustup installation so that `cargo` and `rustc` are found in their rustup-configured locations. + +### Go + +To build lotus you will need a working installation of **[Go1.14](https://golang.org/dl/)**. Follow the [installation instructions](https://golang.org/doc/install), which generally amount to: + +```sh +# Example! Check the installation instructions. +wget -c https://dl.google.com/go/go1.14.7.linux-amd64.tar.gz -O - | sudo tar -xz -C /usr/local +``` + +## Build and install Lotus + +With all the above, you are ready to build and install the Lotus suite (`lotus`, `lotus-miner` and `lotus-worker`): + +```sh +git clone https://github.com/filecoin-project/lotus.git +cd lotus/ +``` + +__IF YOU ARE IN CHINA__, set `export GOPROXY=https://goproxy.cn` before building + +Now, choose the network that you will be joining: + +* For `testnet`: `git checkout master` +* For `nerpa`: `git checkout ntwk-nerpa` +* For `butterfly`: `git checkout ntwk-butterfly` + +Once on the right branch, do: + +```sh +make clean install +sudo make install +``` + +This will put `lotus`, `lotus-miner` and `lotus-worker` in `/usr/local/bin`. `lotus` will use the `$HOME/.lotus` folder by default for storage (configuration, chain data, wallets...). `lotus-miner` will use `$HOME/.lotusminer` respectively. See the *environment variables* section below for how to customize these. + +> Remeber to [move your Lotus folder](en+update) if you are switching between different networks, or there has been a network reset. + + +### Native Filecoin FFI + +Some newer processors (AMD Zen (and later), Intel Ice Lake) have support SHA extensions. To make full use of your processor's capabilities, make sure you set the following variables BEFORE building from source (as described above): + +```sh +export RUSTFLAGS="-C target-cpu=native -g" +export FFI_BUILD_FROM_SOURCE=1 +``` + +> __NOTE__: This method of building does not produce portable binaries! Make sure you run the binary in the same machine as you built it. + +### systemd service files + +Lotus provides Systemd service files. They can be installed with: + +```sh +make install-daemon-service +make install-miner-service +``` + +After that, you should be able to control Lotus using `systemctl`. + +## Troubleshooting + +This section mentions some of the common pitfalls for building Lotus. Check the [getting started](en+getting-started) section for more tips on issues when running the lotus daemon. + +### Build errors + +Please check the build logs closely. If you have a dirty state in your git branch make sure to: + +```sh +git checkout +git reset origin/ --hard +make clean +``` + +### Slow builds from China + +Users from China can speed up their builds by setting: + +```sh +export GOPROXY=https://goproxy.cn +``` diff --git a/documentation/en/install-lotus-macos.md b/documentation/en/installation/install-macos.md similarity index 85% rename from documentation/en/install-lotus-macos.md rename to documentation/en/installation/install-macos.md index 371832c96..ea9ecb8ca 100644 --- a/documentation/en/install-lotus-macos.md +++ b/documentation/en/installation/install-macos.md @@ -59,4 +59,4 @@ make clean && make all sudo make install ``` -After installing Lotus, you can run the `lotus` command directly from your CLI to see usage documentation. Next, you can join the [Lotus Testnet](https://lotu.sh/en+join-testnet). +After intalling Lotus you will be ready to [setup and run the daemon](en+setup.md). diff --git a/documentation/en/installation/installation.md b/documentation/en/installation/installation.md new file mode 100644 index 000000000..98534da92 --- /dev/null +++ b/documentation/en/installation/installation.md @@ -0,0 +1,39 @@ +# Installation + +Lotus can be installed in [Linux](en-install-linux) and [MacOS](en-install-macos) machines by building it from source. Windows is not supported yet. + +This section contains guides to install Lotus in the supported platforms. + +Lotus is made of 3 binaries: + +* `lotus`: the main [Lotus node](en+setup) (Lotus client) +* `lotus-miner`: an application specifically for [Filecoin mining](en+miner-setup) +* `lotus-worker`: an additional [application to offload some heavy-processing tasks](en+lotus-worker) from the Lotus Miner. + +These applications are written in Go, but also import several Rust libraries. Lotus does not distribute +pre-compiled builds. + +## Hardware requirements + +### For client nodes + +* 8GiB of RAM +* Recommended for syncing speed: CPU with support for *Intel SHA Extensions* (AMD since Zen microarchitecture, Intel since Ice Lake). +* Recommended for speed: SSD hard drive (the bigger the better) + +### For miners + +The following correspond to the latest testing configuration: + +* 2 TB of hard drive space +* 8 core CPU +* 128 GiB of RAM with 256 GiB of NVMe SSD storage for swap (or simply, more RAM). +* Recommended for speed: CPU with support for *Intel SHA Extensions* (AMD since Zen microarchitecture, Intel since Ice Lake). +* GPU for block mining. The following have been [confirmed to be fast enough](en+gpus): + +- GeForce RTX 2080 Ti +- GeForce RTX 2080 SUPER +- GeForce RTX 2080 +- GeForce GTX 1080 Ti +- GeForce GTX 1080 +- GeForce GTX 1060 diff --git a/documentation/en/installation/update.md b/documentation/en/installation/update.md new file mode 100644 index 000000000..5d76592c9 --- /dev/null +++ b/documentation/en/installation/update.md @@ -0,0 +1,72 @@ +# Updating and restarting Lotus + +Updating Lotus is as simple as rebuilding and re-installing the software as explained in the previous sections. + +You can verify which version of Lotus you are running with: + +```sh +lotus version +``` + +Make sure that you `git pull` the branch that corresponds to the network that your Lotus daemon is using: + +```sh +git pull origin +make clean +make all +sudo make install # if necessary +``` + +Finally, restart the Lotus Node and/or Lotus Miner(s). + +__CAVEAT__: If you are running miners: check if your miner is safe to shut down and restart: `lotus-miner proving info`. If any deadline shows a block height in the past, do not restart: + +In the following example, Deadline Open is 454 which is earlier than Current Epoch of 500. This miner should **not** be shut down or restarted. + +``` +$ sudo lotus-miner proving info +Miner: t01001 +Current Epoch: 500 +Proving Period Boundary: 154 +Proving Period Start: 154 (2h53m0s ago) +Next Period Start: 3034 (in 21h7m0s) +Faults: 768 (100.00%) +Recovering: 768 +Deadline Index: 5 +Deadline Sectors: 0 +Deadline Open: 454 (23m0s ago) +Deadline Close: 514 (in 7m0s) +Deadline Challenge: 434 (33m0s ago) +Deadline FaultCutoff: 384 (58m0s ago) +``` + +In this next example, the miner can be safely restarted because no Deadlines are earlier than Current Epoch of 497. You have ~45 minutes before the miner must be back online to declare faults (FaultCutoff). If the miner has no faults, you have about an hour. + +``` +$ sudo lotus-miner proving info +Miner: t01000 +Current Epoch: 497 +Proving Period Boundary: 658 +Proving Period Start: 658 (in 1h20m30s) +Next Period Start: 3538 (in 25h20m30s) +Faults: 0 (0.00%) +Recovering: 0 +Deadline Index: 0 +Deadline Sectors: 768 +Deadline Open: 658 (in 1h20m30s) +Deadline Close: 718 (in 1h50m30s) +Deadline Challenge: 638 (in 1h10m30s) +Deadline FaultCutoff: 588 (in 45m30s) +``` + +## Switching networks and network resets + +If you wish to switch to a different lotus network or there has been a network reset, you will need to: + +* Checkout the appropiate repository branch and rebuild +* Ensure you do not mix Lotus data (`LOTUS_PATH`, usually `~/.lotus`) from a previous or different network. For this, either: + * Rename the folder to something else or, + * Set a different `LOTUS_PATH` for the new network. +* Same for `~/.lotusminer` if you are running a miner. + +Note that deleting the Lotus data folder will wipe all the chain data, wallets and configuration, so think twice before taking any non-reversible action. diff --git a/documentation/en/join-testnet.md b/documentation/en/join-testnet.md deleted file mode 100644 index 6660d26d8..000000000 --- a/documentation/en/join-testnet.md +++ /dev/null @@ -1,93 +0,0 @@ -# Join Testnet - -## Introduction - -Anyone can set up a **Lotus Node** and connect to the **Lotus Testnet**. This is the best way to explore the current CLI and the **Filecoin Decentralized Storage Market**. - -## Note: Using the Lotus Node from China - -If you are trying to use `lotus` from China. You should set this **environment variable** on your machine: - -```sh -export IPFS_GATEWAY="https://proof-parameters.s3.cn-south-1.jdcloud-oss.com/ipfs/" -``` - -## Get started - -Start the **daemon** using the default configuration in `./build`: - -```sh -lotus daemon -``` - -In another terminal window, check your connection with peers: - -```sh -lotus net peers | wc -l -``` - -In order to connect to the network, you need to be connected to at least 1 peer. If you’re seeing 0 peers, read our [troubleshooting notes](https://lotu.sh/en+setup-troubleshooting). - -Make sure that you have a reasonable "open files limit" set on your machine, such as 10000. If you're seeing a lower value, such as 256 (default on macOS), read our [troubleshooting notes](https://lotu.sh/en+setup-troubleshooting) on how to update it prior to starting the Lotus daemon. - -## Chain sync - -While the daemon is running, the next requirement is to sync the chain. Run the command below to view the chain sync progress. To see current chain height, visit the [network stats page](https://stats.testnet.filecoin.io/). - -```sh -lotus sync wait -``` - -- This step will take anywhere between a few hours to a couple of days. -- You will be able to perform **Lotus Testnet** operations after it is finished. - -## Create your first address - -Initialize a new wallet: - -```sh -lotus wallet new -``` - -Sometimes your operating system may limit file name length to under 150 characters. You need to use a file system that supports long filenames. - -Here is an example of the response: - -```sh -t1aswwvjsae63tcrniz6x5ykvsuotlgkvlulnqpsi -``` - -- Visit the [faucet](http://spacerace.faucet.glif.io/) to add funds. -- Paste the address you created under REQUEST. -- Press the Request button. - -## Check wallet address balance - -Wallet balances in the Lotus Testnet are in **FIL**, the smallest denomination of FIL is an **attoFil**, where 1 attoFil = 10^-18 FIL. - -```sh -lotus wallet balance -``` - -You will not see any attoFIL in your wallet if your **chain** is not fully synced. - -## Send FIL to another wallet - -To send FIL to another wallet from your default account, use this command: - -``` -lotus send -``` - -## Configure your node's connectivity - -To effectively accept incoming storage & retrieval deals, your Lotus node needs to be accessible to other nodes on the network. To improve your connectivity, be sure to: - -- [Set the multiaddresses for you miner to listen on](https://docs.filecoin.io/mine/connectivity/#setting-multiaddresses) -- [Maintain a healthy peer count](https://docs.filecoin.io/mine/connectivity/#checking-peer-count) -- [Enable port forwarding](https://docs.filecoin.io/mine/connectivity/#port-forwarding) -- [Configure your public IP address and port](https://docs.filecoin.io/mine/connectivity/#setting-a-public-ip-address) - -## Monitor the dashboard - -To see the latest network activity, including **chain block height**, **block height**, **blocktime**, **total network power**, largest **block producer miner**, check out the [monitoring dashboard](https://stats.testnet.filecoin.io). diff --git a/documentation/en/miner-deals.md b/documentation/en/miner-deals.md deleted file mode 100644 index 0aee0e1af..000000000 --- a/documentation/en/miner-deals.md +++ /dev/null @@ -1,39 +0,0 @@ -# Information for Miners - -Here is how a miner can get set up to accept storage deals. The first step is -to install a Lotus node and sync to the top of the chain. - -## Set up an ask - -``` -lotus-miner set-price -``` - -This command will set up your miner to accept deal proposals that meet the input price. -The price is inputted in FIL per GiB per epoch, and the default is 0.0000000005. - -## Ensure you can be discovered - -Clients need to be able to find you in order to make storage deals with you. -While there isn't necessarily anything you need to do to become discoverable, here are some things you can -try to check that people can connect to you. - -To start off, make sure you are connected to at least some peers, and your port is -open and working. - -### Connect to your own node - -If you are in contact with someone else running Lotus, you can ask them to try connecting -to your node. To do so, provide them your peer ID, which you can get by running `lotus net id` on -your node. - -They can then try running `lotus net findpeer ` to get your address(es), and can then -run `lotus net connect
` to connect to you. If successful, your node will now -appear on their peers list (run `lotus net peers` to check). - -You can also check this by running a second instance of Lotus yourself. - -### Query your own ask - -A client should be able to find your ask by running `lotus client query-ask `. If -someone is not able to retrieve your ask by doing so, then there is an issue with your node. \ No newline at end of file diff --git a/documentation/en/mining.md b/documentation/en/mining.md deleted file mode 100644 index 32c3c51d2..000000000 --- a/documentation/en/mining.md +++ /dev/null @@ -1,149 +0,0 @@ -# Storage Mining - -Here are instructions to learn how to perform storage mining. For hardware specifications please read [this](https://lotu.sh/en+hardware-mining). - -It is useful to [join the Testnet](https://lotu.sh/en+join-testnet) prior to attempting storage mining for the first time. - -## Note: Using the Lotus Miner from China - -If you are trying to use `lotus-miner` from China. You should set this **environment variable** on your machine. - -```sh -export IPFS_GATEWAY="https://proof-parameters.s3.cn-south-1.jdcloud-oss.com/ipfs/" -``` - -## Get started - -Please ensure that at least one **BLS address** (starts with `t3`) in your wallet exists with the following command: - -```sh -lotus wallet list -``` - -If you do not have a bls address, create a new bls wallet: - -```sh -lotus wallet new bls -``` - -With your wallet address: - -- Visit the [faucet](http://spacerace.faucet.glif.io/) -- Paste the address you created under REQUEST. -- Press the Request button. -- Run `/lotus-miner init --owner= --worker=` - -You will have to wait some time for this operation to complete. - -## Mining - -To mine: - -```sh -lotus-miner run -``` - -If you are downloading **Filecoin Proof Parameters**, the download can take some time. - -Get information about your miner: - -```sh -lotus-miner info -# example: miner id `t0111` -``` - -**Seal** random data to start producing **PoSts**: - -```sh -lotus-miner sectors pledge -``` - -- Warning: On Linux configurations, this command will write data to `$TMPDIR` which is not usually the largest partition. You should point the value to a larger partition if possible. - -Get **miner power** and **sector usage**: - -```sh -lotus state power -# returns total power - -lotus state power - -lotus state sectors -``` - -## Performance tuning - -### `FIL_PROOFS_MAXIMIZE_CACHING=1` Environment variable - -This env var can be used with `lotus-miner`, `lotus-worker`, and `lotus-bench` to make the precommit1 step faster at the cost of some memory use (1x sector size) - -### `FIL_PROOFS_USE_GPU_COLUMN_BUILDER=1` Environment variable - -This env var can be used with `lotus-miner`, `lotus-worker`, and `lotus-bench` to enable experimental precommit2 GPU acceleration - -### Setting multiaddresses - -Set multiaddresses for the miner to listen on in a miner's `config.toml` file -(by default, it is located at `~/.lotusminer/config.toml`). The `ListenAddresses` in this file should be interface listen addresses (usually `/ip4/0.0.0.0/tcp/PORT`), and the `AnnounceAddresses` should match the addresses being passed to `set-addrs`. - -The addresses passed to `set-addrs` parameter in the commands below should be currently active and dialable; confirm they are before entering them. - -Once the config file has been updated, set the on-chain record of the miner's listen addresses: - -``` -lotus-miner actor set-addrs ... -``` - -This updates the `MinerInfo` object in the miner's actor, which will be looked up -when a client attempts to make a deal. Any number of addresses can be provided. - -Example: - -``` -lotus-miner actor set-addrs /ip4/123.123.73.123/tcp/12345 /ip4/223.223.83.223/tcp/23456 -``` - -# Separate address for windowPoSt messages - -WindowPoSt is the mechanism through which storage is verified in Filecoin. It requires miners to submit proofs for all sectors every 24h, which require sending messages to the chain. - -Because many other mining related actions require sending messages to the chain, and not all of those are "high value", it may be desirable to use a separate account to send PoSt messages from. This allows for setting lower GasFeeCaps on the lower value messages without creating head-of-line blocking problems for the PoSt messages in congested chain conditions - -To set this up, first create a new account, and send it some funds for gas fees: -```sh -lotus wallet new bls -t3defg... - -lotus send t3defg... 100 -``` - -Next add the control address -```sh -lotus-miner actor control set t3defg... -Add t3defg... -Pass --really-do-it to actually execute this action -``` - -Now actually set the addresses -```sh -lotus-miner actor control set --really-do-it t3defg... -Add t3defg... -Message CID: bafy2.. -``` - -Wait for the message to land on chain -```sh -lotus state wait-msg bafy2.. -... -Exit Code: 0 -... -``` - -Check miner control address list to make sure the address was correctly setup -```sh -lotus-miner actor control list -name ID key use balance -owner t01111 t3abcd... other 300 FIL -worker t01111 t3abcd... other 300 FIL -control-0 t02222 t3defg... post 100 FIL -``` diff --git a/documentation/en/mining/gpus.md b/documentation/en/mining/gpus.md new file mode 100644 index 000000000..ad0ed4f66 --- /dev/null +++ b/documentation/en/mining/gpus.md @@ -0,0 +1,17 @@ +# Benchmarking additional GPUs + +If you want to test a GPU that is not explicitly supported, set the following *environment variable*: + +```sh +BELLMAN_CUSTOM_GPU=":" +``` + +Here is an example of trying a GeForce GTX 1660 Ti with 1536 cores. + +```sh +BELLMAN_CUSTOM_GPU="GeForce GTX 1660 Ti:1536" +``` + +To get the number of cores for your GPU, you will need to check your card’s specifications. + +To perform the benchmark you can use Lotus' [benchmarking tool](https://github.com/filecoin-project/lotus/tree/master/cmd/lotus-bench). Results and discussion are tracked in a [GitHub issue thread](https://github.com/filecoin-project/lotus/issues/694). diff --git a/documentation/en/mining-lotus-worker.md b/documentation/en/mining/lotus-seal-worker.md similarity index 60% rename from documentation/en/mining-lotus-worker.md rename to documentation/en/mining/lotus-seal-worker.md index f93780c44..62dde9bfb 100644 --- a/documentation/en/mining-lotus-worker.md +++ b/documentation/en/mining/lotus-seal-worker.md @@ -2,24 +2,14 @@ The **Lotus Worker** is an extra process that can offload heavy processing tasks from your **Lotus Miner**. The sealing process automatically runs in the **Lotus Miner** process, but you can use the Worker on another machine communicating over a fast network to free up resources on the machine running the mining process. -## Note: Using the Lotus Worker from China +## Installation -If you are trying to use `lotus-worker` from China. You should set this **environment variable** on your machine: - -```sh -export IPFS_GATEWAY="https://proof-parameters.s3.cn-south-1.jdcloud-oss.com/ipfs/" -``` - -## Get Started - -Make sure that the `lotus-worker` is compiled and installed by running: - -```sh -make lotus-worker -``` +The `lotus-worker` application is installed along with the others when running `sudo make install` as shown in the [Installation section](en+install-linux). For simplicity, we recommend following the same procedure in the machines that will run the Lotus Workers (even if the Lotus miner and the Lotus daemon are not used there). ## Setting up the Miner +### Allow external connections to the miner API + First, you will need to ensure your `lotus-miner`'s API is accessible over the network. To do this, open up `~/.lotusminer/config.toml` (Or if you manually set `LOTUS_MINER_PATH`, look under that directory) and look for the API field. @@ -32,30 +22,49 @@ ListenAddress = "/ip4/127.0.0.1/tcp/2345/http" RemoteListenAddress = "127.0.0.1:2345" ``` -To make your node accessible over the local area network, you will need to determine your machines IP on the LAN, and change the `127.0.0.1` in the file to that address. +To make your node accessible over the local area network, you will need to determine your machine's IP on the LAN (`ip a`), and change the `127.0.0.1` in the file to that address. -A more permissive and less secure option is to change it to `0.0.0.0`. This will allow anyone who can connect to your computer on that port to access the [API](https://lotu.sh/en+api). They will still need an auth token. +A more permissive and less secure option is to change it to `0.0.0.0`. This will allow anyone who can connect to your computer on that port to access the miner's API, though they will still need an auth token. `RemoteListenAddress` must be set to an address which other nodes on your network will be able to reach. -Next, you will need to [create an authentication token](https://lotu.sh/en+api-scripting-support#generate-a-jwt-46). All Lotus APIs require authentication tokens to ensure your processes are as secure against attackers attempting to make unauthenticated requests to them. +### Create an authentication token -### Connect the Lotus Worker +Write down the output of: -On the machine that will run `lotus-worker`, set the `MINER_API_INFO` environment variable to `TOKEN:MINER_NODE_MULTIADDR`. Where `TOKEN` is the token we created above, and `NIMER_NODE_MULTIADDR` is the `multiaddr` of the **Lotus Miner** API that was set in `config.toml`. +```sh +lotus-miner auth api-info --perm admin +``` -Once this is set, run: +The Lotus Workers will need this token to connect to the miner. + +## Connecting the Lotus Workers + +On each machine that will run the `lotus-worker` application you will need to define the following *environment variable*: + +```sh +export MINER_API_INFO::/ip4//tcp/2345` +``` + +If you are trying to use `lotus-worker` from China. You should additionally set: + +```sh +export IPFS_GATEWAY="https://proof-parameters.s3.cn-south-1.jdcloud-oss.com/ipfs/" +``` + + +Once that is done, you can run the Worker with: ```sh lotus-worker run ``` -If you are running multiple workers on the same host, you will need to specify the `--listen` flag and ensure each worker is on a different port. +> If you are running multiple workers on the same host, you will need to specify the `--listen` flag and ensure each worker is on a different port. -To check that the **Lotus Worker** is connected to your **Lotus Miner**, run `lotus-miner sealing workers` and check that the remote worker count has increased. +On your Lotus miner, check that the workers are correctly connected: ```sh -why@computer ~/lotus> lotus-miner sealing workers +lotus-miner sealing workers Worker 0, host computer CPU: [ ] 0 core(s) in use RAM: [|||||||||||||||||| ] 28% 18.1 GiB/62.7 GiB @@ -69,9 +78,10 @@ Worker 1, host othercomputer GPU: GeForce RTX 2080, not used ``` -### Running locally for manually managing process priority +## Running locally for manually managing process priority You can also run the **Lotus Worker** on the same machine as your **Lotus Miner**, so you can manually manage the process priority. + To do so you have to first __disable all seal task types__ in the miner config. This is important to prevent conflicts between the two processes. You can then run the miner on your local-loopback interface; diff --git a/documentation/en/mining/managing-deals.md b/documentation/en/mining/managing-deals.md new file mode 100644 index 000000000..5f73a6a2d --- /dev/null +++ b/documentation/en/mining/managing-deals.md @@ -0,0 +1,19 @@ +# Managing deals + + +While the Lotus Miner is running as a daemon, the `lotus-miner` application can be used to manage and configure the miner: + + +```sh +lotus-miner storage-deals --help +``` + +Running the above command will show the different options related to deals. For example, `lotus-miner storage-deals set-ask` allows to set the price for storage that your miner uses to respond ask requests from clients. + +If deals are ongoing, you can check the data transfers with: + +```sh +lotus-miner data-transfers list +``` + +Make sure you explore the `lotus-miner` CLI. Every command is self-documented and takes a `--help` flag that offers specific information about it. diff --git a/documentation/en/mining/miner-setup.md b/documentation/en/mining/miner-setup.md new file mode 100644 index 000000000..cafa1e7b1 --- /dev/null +++ b/documentation/en/mining/miner-setup.md @@ -0,0 +1,241 @@ +# Miner setup + +This page will guide you through all you need to know to sucessfully run a **Lotus Miner**. Before proceeding, remember that you should be running the Lotus daemon on a fully synced chain. + +## Performance tweaks + +This is a list of performance tweaks to consider before starting the miner: + +### Building + +As [explained already](en+install-linux#native-filecoin-ffi-10) should have exported the following variables before building the Lotus applications: + +```sh +export RUSTFLAGS="-C target-cpu=native -g" +export FFI_BUILD_FROM_SOURCE=1 +``` + +### Environment + +For high performance mining, we recommend setting the following variables in your environment so that they are available when running any of the Lotus applications: + +```sh +# See https://github.com/filecoin-project/bellman +export BELLMAN_CPU_UTILIZATION=0.875 + +# See https://github.com/filecoin-project/rust-fil-proofs/ +export FIL_PROOFS_MAXIMIZE_CACHING=1 # More speed at RAM cost (1x sector-size of RAM - 32 GB). +export FIL_PROOFS_USE_GPU_COLUMN_BUILDER=1 # precommit2 GPU acceleration +export FIL_PROOFS_USE_GPU_TREE_BUILDER=1 +``` + +IF YOU ARE RUNNING FROM CHINA: + +```sh +export IPFS_GATEWAY="https://proof-parameters.s3.cn-south-1.jdcloud-oss.com/ipfs/" +``` + +IF YOUR MINER RUNS IN A DIFFERENT MACHINE AS THE LOTUS DAEMON: + +```sh +export FULLNODE_API_INFO=:/ip4//tcp//http +``` + +If you will be using systemd service files to run the Lotus daemon and miner, make sure you include these variables manually in the service files. + +### Adding swap + +If you have only 128GiB of RAM, you will need to make sure your system provides at least an extra 256GiB of fast swap (preferably NVMe SSD): + +```sh +sudo fallocate -l 256G /swapfile +sudo chmod 600 /swapfile +sudo mkswap /swapfile +sudo swapon /swapfile +# show current swap spaces and take note of the current highest priority +swapon --show +# append the following line to /etc/fstab (ensure highest priority) and then reboot +# /swapfile swap swap pri=50 0 0 +sudo reboot +# check a 256GB swap file is automatically mounted and has the highest priority +swapon --show +``` + +## Creating a new BLS wallet + +You will need a BLS wallet (`t3...`) for mining. To create it, if you don't have one already, run: + +```sh +lotus wallet new bls +``` + +Next make sure to [send some funds](en+wallet) to this address so that the miner setup can be completed. + +## Initializing the miner + +> SPACE RACE: +> To participate in the Space race, please register your miner: +> +> - Visit the [faucet](http://spacerace.faucet.glif.io/) +> - Paste the address you created under REQUEST. +> - Press the Request button. + +Now that you have a miner address you can initialize the Lotus Miner: + +```sh +lotus-miner init --owner= --no-local-storage +``` + +* The `--no-local-storage` flag is used so that we configure specific locations for storage later below. +* The init process will download over 100GiB of initialization parameters to /var/tmp/filecoin-proof-parameters. Make sure there is space or set `FIL_PROOFS_PARAMETER_CACHE` to somewhere else. +* The Lotus Miner configuration folder is created at `~/.lotusminer/` or `$LOTUS_MINER_PATH` if set. + +## Reachability + +Before you start your miner, it is __very important__ to configure it so that it is reachable from any peer in the Filecoin network. For this you will need a stable public IP and edit your `~/.lotusminer/config.toml` as follows: + +```toml +... +[Libp2p] + ListenAddresses = ["/ip4/0.0.0.0/tcp/24001"] # choose a fixed port + AnnounceAddresses = ["/ip4//tcp/24001"] # important! +... +``` + +Once you start your miner, make sure you can connect to its public IP/port (you can use `telnet`, `nc` for the task...). If you have an active firewall or some sort, you may need to additionally open ports in it. + + +## Starting the miner + +You are now ready to start your Lotus miner: + +```sh +lotus-miner run +``` + +or if you are using the systemd service file: + +```sh +systemctl start lotus-miner +``` + +> __Do not proceed__ from here until you have verified that your miner not only is running, but also __reachable on its public IP address__. + +## Publishing the miner addresses + +Once the miner is up and running, publish your miner address (which you configured above) on the chain (please ensure it is dialable): + +```sh +lotus-miner actor set-addrs /ip4//tcp/24001 +``` + +## Setting locations for sealing and long-term storage + +If you used the `--no-local-storage` flag during initialization, you can now specify the disk locations for sealing (SSD recommended) and long-term storage (otherwise you can skip this): + +``` +lotus-miner storage attach --init --seal +lotus-miner storage attach --init --store +lotus-miner storage list +``` + +## Pledging sectors + +If you would like to compete for block rewards by increasing your power in the network as soon as possible, you can optionally pledge one or several sectors, depending on your storage. It can also be used to test that the sealing process works correctly. Pledging is equivalent to storing random data instead of real data obtained through storage deals. + +> Note that pledging sectors to the mainnet network makes most sense when trying to obtain a reasonable amount of total power in the network, thus obtaining real chances to mine new blocks. Otherwise it is only useful for testing purposes. + +If you decide to go ahead, then do: + +```sh +lotus-miner sectors pledge +``` + +This will write data to `$TMPDIR` so make sure that there is enough space available. + +You shoud check that your sealing job has started with: + +```sh +lotus-miner sealing jobs +``` + +This will be accommpanied by a file in `/unsealed`. + +After some minutes, you can check the sealing progress with: + +```sh +lotus-miner sectors list +# and +lotus-miner sealing workers +``` + +When sealing for the new is complete, `pSet: NO` will become `pSet: YES`. + +Once the sealing is finished, you will want to configure how long it took your miner to seal this sector and configure the miner accordingly. To find out how long it took use: + +``` +lotus-miner sectors status --log 0 +``` + +Once you know, you can edit the Miner's `~/.lotusminer/config.toml` accordingly: + +``` +... +[Dealmaking] +... + ExpectedSealDuration = "12h0m0s" # The time it took your miner +``` + +You can also take the chance to edit other values, such as `WaitForDealsDelay` which specifies the delay between accepting the first deal and sealing, allowing to place multiple deals in the same sector. + +Once you are done editing the configuration, [restart your miner](en+update). + +If you wish to be able to re-use a pledged sector for real storage deals before the pledged period of 6 months ends, you will need to mark them for upgrade: + +```sh +lotus-miner sectors mark-for-upgrade +``` + +The sector should become inactive within 24 hours. From that point, the pledged storage can be re-used to store real data associated with real storage deals. + +## Separate address for windowPoSt messages + +WindowPoSt is the mechanism through which storage is verified in Filecoin. It requires miners to submit proofs for all sectors every 24h, which require sending messages to the chain. + +Because many other mining related actions require sending messages to the chain, and not all of those are "high value", it may be desirable to use a separate account to send PoSt messages from. This allows for setting lower GasFeeCaps on the lower value messages without creating head-of-line blocking problems for the PoSt messages in congested chain conditions + +To set this up, first create a new account, and send it some funds for gas fees: + +```sh +lotus wallet new bls +t3defg... + +lotus send t3defg... 100 +``` + +Next add the control address: + +```sh +lotus-miner actor control set --really-do-it t3defg... +Add t3defg... +Message CID: bafy2.. +``` + +Wait for the message to land on chain: + +```sh +lotus state wait-msg bafy2.. +... +Exit Code: 0 +... +``` + +Finally, check the miner control address list to make sure the address was correctly setup: + +```sh +lotus-miner actor control list +name ID key use balance +owner t01111 t3abcd... other 300 FIL +worker t01111 t3abcd... other 300 FIL +control-0 t02222 t3defg... post 100 FIL +``` diff --git a/documentation/en/mining-troubleshooting.md b/documentation/en/mining/mining-troubleshooting.md similarity index 90% rename from documentation/en/mining-troubleshooting.md rename to documentation/en/mining/mining-troubleshooting.md index 5aaf9f6ef..758929075 100644 --- a/documentation/en/mining-troubleshooting.md +++ b/documentation/en/mining/mining-troubleshooting.md @@ -25,7 +25,7 @@ lotus-miner info # WARN main lotus-storage-miner/main.go:73 failed to get api endpoint: (/Users/myrmidon/.lotusminer) %!w(*errors.errorString=&{API not running (no endpoint)}): ``` -If you see this, that means your **Lotus Miner** isn't ready yet. You need to finish [syncing the chain](https://lotu.sh/en+join-testnet). +If you see this, that means your **Lotus Miner** isn't ready yet. You need to finish [syncing the chain](en+setup#waiting-to-sync-370). ## Error: Your computer may not be fast enough @@ -57,10 +57,3 @@ make bench This process uses a fair amount of GPU, and generally takes ~4 minutes to complete. If you do not see any activity in nvtop from lotus during the entire process, it is likely something is misconfigured with your GPU. -## Checking Sync Progress - -You can use this command to check how far behind you are on syncing: - -```sh -date -d @$(./lotus chain getblock $(./lotus chain head) | jq .Timestamp) -``` diff --git a/documentation/en/mining/mining.md b/documentation/en/mining/mining.md new file mode 100644 index 000000000..b1b944c6e --- /dev/null +++ b/documentation/en/mining/mining.md @@ -0,0 +1,8 @@ +# Storage Mining + +This section of the documentation explains how to do storage mining with Lotus. Please note that not everyone can do storage mining, and that you should not attempt it on on networks where sector sizes are 32GB+ unless you meet the [hardware requirements](en+install#hardware-requirements-1). + +From this point we assume that you have setup and are running the [Lotus Node](en+setup), that it has fully synced the Filecoin chain and that you are familiar with how to interact with it using the `lotus` command-line interface. + +In order to perform storage mining, apart from the Lotus daemon, you will be additionally interacting with the `lotus-miner` and potentially the `lotus-worker` applications (which you should have [installed](en+install-linux) along the `lotus` application already). + diff --git a/documentation/en/retrieving-data.md b/documentation/en/retrieving-data.md deleted file mode 100644 index 7cb0e31be..000000000 --- a/documentation/en/retrieving-data.md +++ /dev/null @@ -1,27 +0,0 @@ -# Retrieving Data - -> There are recent bug reports with these instructions. If you happen to encounter any problems, please create a [GitHub issue](https://github.com/filecoin-project/lotus/issues/new) and a maintainer will address the problem as soon as they can. - -Here are the operations you can perform after you have stored and sealed a **Data CID** with the **Lotus Miner** in the network. - -If you would like to learn how to store a **Data CID** on a miner, read the instructions [here](https://lotu.sh/en+storing-data). - -## Find by Data CID - -```sh -lotus client find -# LOCAL -# RETRIEVAL @-- -``` - -## Retrieve by Data CID - -All fields are required. - -```sh -lotus client retrieve -``` - -If the outfile does not exist it will be created in the Lotus repository directory. - -This command will initiate a **retrieval deal** and write the data to your computer. This process may take 2 to 10 minutes. diff --git a/documentation/en/setting-a-static-port.md b/documentation/en/setting-a-static-port.md deleted file mode 100644 index 97ac6528e..000000000 --- a/documentation/en/setting-a-static-port.md +++ /dev/null @@ -1,54 +0,0 @@ -# Static Ports - -Depending on how your network is set up, you may need to set a static port to successfully connect to peers to perform storage deals with your **Lotus Miner**. - -## Setup - -To change the random **swarm port**, you may edit the `config.toml` file located under `$LOTUS_MINER_PATH`. The default location of this file is `$HOME/.lotusminer`. - -To change the port to `1347`: - -```sh -[Libp2p] - ListenAddresses = ["/ip4/0.0.0.0/tcp/1347", "/ip6/::/tcp/1347"] -``` - -After changing the port value, restart your **daemon**. - -## Announce Addresses - -If the **swarm port** is port-forwarded from another address, it is possible to control what addresses -are announced to the network. - -```sh -[Libp2p] - AnnounceAddresses = ["/ip4//tcp/1347"] -``` - -If non-empty, this array specifies the swarm addresses to announce to the network. If empty, the daemon will announce inferred swarm addresses. - -Similarly, it is possible to set `NoAnnounceAddresses` with an array of addresses to not announce to the network. - -## Ubuntu's Uncomplicated Firewall - -Open firewall manually: - -```sh -ufw allow 1347/tcp -``` - -Or open and modify the profile located at `/etc/ufw/applications.d/lotus-daemon`: - -```sh -[Lotus Daemon] -title=Lotus Daemon -description=Lotus Daemon firewall rules -ports=1347/tcp -``` - -Then run these commands: - -```sh -ufw update lotus-daemon -ufw allow lotus-daemon -``` diff --git a/documentation/en/storing-ipfs-integration.md b/documentation/en/store/adding-from-ipfs.md similarity index 79% rename from documentation/en/storing-ipfs-integration.md rename to documentation/en/store/adding-from-ipfs.md index 041364380..2f6b097cc 100644 --- a/documentation/en/storing-ipfs-integration.md +++ b/documentation/en/store/adding-from-ipfs.md @@ -1,10 +1,10 @@ -# IPFS Integration +# Adding data from IPFS Lotus supports making deals with data stored in IPFS, without having to re-import it into lotus. To enable this integration, you need to have an IPFS daemon running in the background. -Then, open up `~/.lotus/config.toml` (or if you manually set `LOTUS_PATH`, look under that directory) -and look for the Client field, and set `UseIpfs` to `true`. + +Then, open up `~/.lotus/config.toml` (or if you manually set `LOTUS_PATH`, look under that directory) and look for the Client field, and set `UseIpfs` to `true`. ```toml [Client] diff --git a/documentation/en/store/making-deals.md b/documentation/en/store/making-deals.md new file mode 100644 index 000000000..ca3a47182 --- /dev/null +++ b/documentation/en/store/making-deals.md @@ -0,0 +1,71 @@ +# Making storage deals + +## Adding a file to Lotus + +Before sending data to a Filecoin miner for storage, the data needs to be correctly formatted and packed. This can be achieved by locally importing the data into Lotus with: + +```sh +lotus client import ./your-example-file.txt +``` + +Upon success, this command will return a **Data CID**. This is a very important piece of information, as it will be used to make deals to both store and retrieve the data in the future. + +You can list the data CIDs of the files you locally imported with: + +```sh +lotus client local +``` + +## Storing data in the network + +To store data in the network you will need to: + +* Find a Filecoin miner willing to store it +* Make a deal with the miner agreeing on the price to pay and the duration for which the data should be stored. + +You can obtain a list of all miners in the network with: + +```sh +lotus state list-miners +t0xxxx +t0xxxy +t0xxxz +... +``` + +This will print a list of miner IDs. In order to ask for the terms offered by a particular miner, you can then run: + +```sh +lotus client query-ask +``` + +If you are satisfied with the terms, you can proceed to propose a deal to the miner, using the **Data CID** that you obtained during the import step: + + +```sh +lotus client deal +``` + +This command will interactively ask you for the CID, miner ID and duration in days for the deal. You can also call it with arguments: + +```sh +lotus client deal +``` + +where the `duration` is expressed in blocks (1 block is equivalent to 30s). + +## Checking the status of the deals + +You can list deals with: + +```sh +lotus client list-deals +``` + +Among other things, this will give you information about the current state on your deals, whether they have been published on chain (by the miners) and whether the miners have been slashed for not honoring them. + +For a deal to succeed, the miner needs to be correctly configured and running, accept the deal and *seal* the file correctly. Otherwise, the deal will appear in error state. + +You can make deals with multiple miners for the same data. + +Once a deal is sucessful and the data is *sealed*, it can be [retrieved](en+retrieving). diff --git a/documentation/en/store/retrieve.md b/documentation/en/store/retrieve.md new file mode 100644 index 000000000..1e8db65af --- /dev/null +++ b/documentation/en/store/retrieve.md @@ -0,0 +1,27 @@ +# Retrieving Data + +Once data has been succesfully [stored](en+making-deals) and sealed by a Filecoin miner, it can be retrieved. + +In order to do this we will need to create a **retrieval deal**. + +## Finding data by CID + +In order to retrieve some data you will need the **Data CID** that was used to create the storage deal. + +You can find who is storing the data by running: + +```sh +lotus client find +``` + +## Making a retrieval deal + +You can then make a retrieval deal with: + +```sh +lotus client retrieve +``` + +This commands take other optional flags (check `--help`). + +If the outfile does not exist it will be created in the Lotus repository directory. This process may take 2 to 10 minutes. diff --git a/documentation/en/storing-data-troubleshooting.md b/documentation/en/store/storage-troubleshooting.md similarity index 51% rename from documentation/en/storing-data-troubleshooting.md rename to documentation/en/store/storage-troubleshooting.md index c8a0254fa..7087ec3d0 100644 --- a/documentation/en/storing-data-troubleshooting.md +++ b/documentation/en/store/storage-troubleshooting.md @@ -2,11 +2,11 @@ ## Error: Routing: not found -```sh +``` WARN main lotus/main.go:72 routing: not found ``` -- This miner is offline. +This error means that the miner is offline. ## Error: Failed to start deal @@ -14,14 +14,17 @@ WARN main lotus/main.go:72 routing: not found WARN main lotus/main.go:72 failed to start deal: computing commP failed: generating CommP: Piece must be at least 127 bytes ``` -- There is a minimum file size of 127 bytes. +This error means that there is a minimum file size of 127 bytes. ## Error: 0kb file response during retrieval -In order to retrieve a file, it must be sealed. Miners can check sealing progress with this command: +This means that the file to be retrieved may have not yet been sealed and is thus, not retrievable yet. + +Miners can check sealing progress with this command: ```sh lotus-miner sectors list ``` -When sealing is complete, `pSet: NO` will become `pSet: YES`. From now on the **Data CID** is [retrievable](https://lotu.sh/en+retrieving-data) from the **Lotus Miner**. +When sealing is complete, `pSet: NO` will become `pSet: YES`. + diff --git a/documentation/en/store/store.md b/documentation/en/store/store.md new file mode 100644 index 000000000..205bd0e23 --- /dev/null +++ b/documentation/en/store/store.md @@ -0,0 +1,11 @@ +# Storing and retrieving data + +Lotus enables you to store any data on the Filecoin network and retrieve it later. This is achieved by making *deals* with miners. + +A *storage deal* specifies that a miner should store ceratin data for a previously agreed period and price. + +Once a deal is made, the data is then sent to the miners, which regularly proves that it is storing it. If they fail to do so, the miner is penalized (slashed). + +The data can be retrieved with a *retrieval deal*. + +This section explains how to use Lotus to [store](en+making-deals) and [retrieve](en+retrieving) data from the Filecoin network. diff --git a/documentation/en/storing-data.md b/documentation/en/storing-data.md deleted file mode 100644 index 67d2b1533..000000000 --- a/documentation/en/storing-data.md +++ /dev/null @@ -1,62 +0,0 @@ -# Storing Data - -> There are recent bug reports with these instructions. If you happen to encounter any problems, please create a [GitHub issue](https://github.com/filecoin-project/lotus/issues/new) and a maintainer will address the problem as soon as they can. - -Here are instructions for how to store data on the **Lotus Testnet**. - -## Adding a file locally - -Adding a file locally allows you to make miner deals on the **Lotus Testnet**. - -```sh -lotus client import ./your-example-file.txt -``` - -Upon success, this command will return a **Data CID**. - -## List your local files - -The command to see a list of files by `CID`, `name`, `size` in bytes, and `status`: - -```sh -lotus client local -``` - -An example of the output: - -```sh -bafkreierupr5ioxn4obwly4i2a5cd2rwxqi6kwmcyyylifxjsmos7hrgpe Development/sample-1.txt 2332 ok -bafkreieuk7h4zs5alzpdyhlph4lxkefowvwdho3a3pml6j7dam5mipzaii Development/sample-2.txt 30618 ok -``` - -## Make a Miner Deal on Lotus Testnet - -Get a list of all miners that can store data: - -```sh -lotus state list-miners -``` - -Get the requirements of a miner you wish to store data with: - -```sh -lotus client query-ask -``` - -Store a **Data CID** with a miner: - -```sh -lotus client deal -``` - -Check the status of a deal: - -```sh -lotus client list-deals -``` - -- The `duration`, which represents how long the miner will keep your file hosted, is represented in blocks. Each block represents 25 seconds. - -Upon success, this command will return a **Deal CID**. - -The miner will need to **seal** the file before it can be retrieved. If the **Lotus Miner** is not running on a machine designed for sealing, the process will take a very long time. diff --git a/documentation/en/dev/WIP-arch-complementary-notes.md b/documentation/en/unclassified/WIP-arch-complementary-notes.md similarity index 100% rename from documentation/en/dev/WIP-arch-complementary-notes.md rename to documentation/en/unclassified/WIP-arch-complementary-notes.md diff --git a/documentation/en/block-validation.md b/documentation/en/unclassified/block-validation.md similarity index 100% rename from documentation/en/block-validation.md rename to documentation/en/unclassified/block-validation.md diff --git a/documentation/en/dev/create-miner.md b/documentation/en/unclassified/create-miner.md similarity index 100% rename from documentation/en/dev/create-miner.md rename to documentation/en/unclassified/create-miner.md diff --git a/documentation/en/dev-tools-pond-ui.md b/documentation/en/unclassified/dev-tools-pond-ui.md similarity index 100% rename from documentation/en/dev-tools-pond-ui.md rename to documentation/en/unclassified/dev-tools-pond-ui.md diff --git a/documentation/en/sealing-procs.md b/documentation/en/unclassified/sealing-procs.md similarity index 100% rename from documentation/en/sealing-procs.md rename to documentation/en/unclassified/sealing-procs.md diff --git a/documentation/en/updating-lotus.md b/documentation/en/updating-lotus.md deleted file mode 100644 index 862cea136..000000000 --- a/documentation/en/updating-lotus.md +++ /dev/null @@ -1,14 +0,0 @@ -# Updating Lotus - -If you installed Lotus on your machine, you can upgrade to the latest version by doing the following: - -```sh -# get the latest -git pull origin master - -# clean and remake the binaries -make clean && make build - -# instal binaries in correct location -make install # or sudo make install if necessary -``` From a153e1d5862b67a031fe7ee7306a7e430c517187 Mon Sep 17 00:00:00 2001 From: Hector Sanjuan Date: Mon, 31 Aug 2020 21:18:50 +0200 Subject: [PATCH 007/303] Fix #2334: Specify seal options to disable with co-located storage worker --- documentation/en/mining/lotus-seal-worker.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/documentation/en/mining/lotus-seal-worker.md b/documentation/en/mining/lotus-seal-worker.md index 62dde9bfb..47e201ca5 100644 --- a/documentation/en/mining/lotus-seal-worker.md +++ b/documentation/en/mining/lotus-seal-worker.md @@ -82,7 +82,15 @@ Worker 1, host othercomputer You can also run the **Lotus Worker** on the same machine as your **Lotus Miner**, so you can manually manage the process priority. -To do so you have to first __disable all seal task types__ in the miner config. This is important to prevent conflicts between the two processes. +To do so you have to first __disable all seal task types__ in the miner config. This is important to prevent conflicts between the two processes: + +```toml +[Storage] + AllowPreCommit1 = false + AllowPreCommit2 = false + AllowCommit = false + AllowUnseal = false +``` You can then run the miner on your local-loopback interface; From af38c902f88d5c7be13f24eca4e8d19b395e963f Mon Sep 17 00:00:00 2001 From: Hector Sanjuan Date: Tue, 1 Sep 2020 15:12:07 +0200 Subject: [PATCH 008/303] Fix architecture entry --- documentation/en/.library.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/documentation/en/.library.json b/documentation/en/.library.json index 87c7353c1..59cc01e29 100644 --- a/documentation/en/.library.json +++ b/documentation/en/.library.json @@ -193,7 +193,7 @@ { "title": "Lotus Architecture (WIP)", "slug": "en+arch", - "github": "en/architectiure/architecture.md", + "github": "en/architecture/architecture.md", "value": null, "posts": [ { From bd0c6a4cccd5a5e21ae3f4939cf9d8822ea9ca37 Mon Sep 17 00:00:00 2001 From: Hector Sanjuan Date: Thu, 3 Sep 2020 16:35:55 +0200 Subject: [PATCH 009/303] Fix filename --- documentation/en/building/api.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/documentation/en/building/api.md b/documentation/en/building/api.md index 626193ee2..3a2c2902b 100644 --- a/documentation/en/building/api.md +++ b/documentation/en/building/api.md @@ -19,7 +19,7 @@ Lotus uses its own Go library implementation of [JSON-RPC](https://github.com/fi ## cURL example -To demonstrate making an API request, we will take the method `ChainHead` from [api/api.go](https://github.com/filecoin-project/lotus/blob/master/api/api_full.go). +To demonstrate making an API request, we will take the method `ChainHead` from [api/api_full.go](https://github.com/filecoin-project/lotus/blob/master/api/api_full.go). ```go ChainHead(context.Context) (*types.TipSet, error) From 64d150e215256cab04c0eb52819ca2675330b151 Mon Sep 17 00:00:00 2001 From: hannahhoward Date: Thu, 10 Sep 2020 10:35:06 -0700 Subject: [PATCH 010/303] feat(cli): add chain delete cmd --- api/api_full.go | 3 +++ api/apistruct/struct.go | 5 +++++ cli/chain.go | 27 +++++++++++++++++++++++++++ node/impl/full/chain.go | 4 ++++ 4 files changed, 39 insertions(+) diff --git a/api/api_full.go b/api/api_full.go index 02417bf78..3dde0e517 100644 --- a/api/api_full.go +++ b/api/api_full.go @@ -75,6 +75,9 @@ type FullNode interface { // blockstore and returns raw bytes. ChainReadObj(context.Context, cid.Cid) ([]byte, error) + // ChainDeleteObj deletes node referenced by the given CID + ChainDeleteObj(context.Context, cid.Cid) error + // ChainHasObj checks if a given CID exists in the chain blockstore. ChainHasObj(context.Context, cid.Cid) (bool, error) diff --git a/api/apistruct/struct.go b/api/apistruct/struct.go index ffb837785..172156c42 100644 --- a/api/apistruct/struct.go +++ b/api/apistruct/struct.go @@ -85,6 +85,7 @@ type FullNodeStruct struct { ChainGetParentMessages func(context.Context, cid.Cid) ([]api.Message, error) `perm:"read"` ChainGetTipSetByHeight func(context.Context, abi.ChainEpoch, types.TipSetKey) (*types.TipSet, error) `perm:"read"` ChainReadObj func(context.Context, cid.Cid) ([]byte, error) `perm:"read"` + ChainDeleteObj func(context.Context, cid.Cid) error `perm:"admin"` ChainHasObj func(context.Context, cid.Cid) (bool, error) `perm:"read"` ChainStatObj func(context.Context, cid.Cid, cid.Cid) (api.ObjStat, error) `perm:"read"` ChainSetHead func(context.Context, types.TipSetKey) error `perm:"admin"` @@ -658,6 +659,10 @@ func (c *FullNodeStruct) ChainReadObj(ctx context.Context, obj cid.Cid) ([]byte, return c.Internal.ChainReadObj(ctx, obj) } +func (c *FullNodeStruct) ChainDeleteObj(ctx context.Context, obj cid.Cid) error { + return c.Internal.ChainDeleteObj(ctx, obj) +} + func (c *FullNodeStruct) ChainHasObj(ctx context.Context, o cid.Cid) (bool, error) { return c.Internal.ChainHasObj(ctx, o) } diff --git a/cli/chain.go b/cli/chain.go index ce1660641..1c63e37a8 100644 --- a/cli/chain.go +++ b/cli/chain.go @@ -193,6 +193,33 @@ var chainReadObjCmd = &cli.Command{ }, } +var chainDeleteObjCmd = &cli.Command{ + Name: "delete-obj", + Usage: "Delete an object", + ArgsUsage: "[objectCid]", + Action: func(cctx *cli.Context) error { + api, closer, err := GetFullNodeAPI(cctx) + if err != nil { + return err + } + defer closer() + ctx := ReqContext(cctx) + + c, err := cid.Decode(cctx.Args().First()) + if err != nil { + return fmt.Errorf("failed to parse cid input: %s", err) + } + + err = api.ChainDeleteObj(ctx, c) + if err != nil { + return err + } + + fmt.Printf("Obj %s deleted\n", c.String()) + return nil + }, +} + var chainStatObjCmd = &cli.Command{ Name: "stat-obj", Usage: "Collect size and ipld link counts for objs", diff --git a/node/impl/full/chain.go b/node/impl/full/chain.go index c5dd5c9a9..84335280d 100644 --- a/node/impl/full/chain.go +++ b/node/impl/full/chain.go @@ -197,6 +197,10 @@ func (a *ChainAPI) ChainReadObj(ctx context.Context, obj cid.Cid) ([]byte, error return blk.RawData(), nil } +func (a *ChainAPI) ChainDeleteObj(ctx context.Context, obj cid.Cid) error { + return a.Chain.Blockstore().DeleteBlock(obj) +} + func (a *ChainAPI) ChainHasObj(ctx context.Context, obj cid.Cid) (bool, error) { return a.Chain.Blockstore().Has(obj) } From e86a74156e85c520b7ef63d885ee7b3874815340 Mon Sep 17 00:00:00 2001 From: hannahhoward Date: Thu, 10 Sep 2020 10:39:17 -0700 Subject: [PATCH 011/303] feat(cli): add command to list --- cli/chain.go | 1 + 1 file changed, 1 insertion(+) diff --git a/cli/chain.go b/cli/chain.go index 1c63e37a8..0f1e36518 100644 --- a/cli/chain.go +++ b/cli/chain.go @@ -40,6 +40,7 @@ var chainCmd = &cli.Command{ chainHeadCmd, chainGetBlock, chainReadObjCmd, + chainDeleteObjCmd, chainStatObjCmd, chainGetMsgCmd, chainSetHeadCmd, From 5e445f5a4803abfbffa977b9f52da5f72dd94bc9 Mon Sep 17 00:00:00 2001 From: hannahhoward Date: Thu, 10 Sep 2020 10:47:19 -0700 Subject: [PATCH 012/303] docs(apidocs): run docs gen --- documentation/en/api-methods.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/documentation/en/api-methods.md b/documentation/en/api-methods.md index 49582d6f8..203a5f141 100644 --- a/documentation/en/api-methods.md +++ b/documentation/en/api-methods.md @@ -9,6 +9,7 @@ * [Beacon](#Beacon) * [BeaconGetEntry](#BeaconGetEntry) * [Chain](#Chain) + * [ChainDeleteObj](#ChainDeleteObj) * [ChainExport](#ChainExport) * [ChainGetBlock](#ChainGetBlock) * [ChainGetBlockMessages](#ChainGetBlockMessages) @@ -279,6 +280,23 @@ The Chain method group contains methods for interacting with the blockchain, but that do not require any form of state computation. +### ChainDeleteObj +ChainDeleteObj deletes node referenced by the given CID + + +Perms: admin + +Inputs: +```json +[ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + } +] +``` + +Response: `{}` + ### ChainExport ChainExport returns a stream of bytes with CAR dump of chain data. The exported chain data includes the header chain from the given tipset From d3594835c4a790026e4747badedf87af11d191f8 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Fri, 11 Sep 2020 20:07:52 -0700 Subject: [PATCH 013/303] [WIP] Network upgrade support This patch starts adding support for network upgrades. * It adds an actors abstraction layer for loading abstract (cross-version) actors. * It starts switching over to a shared deadline type. * It adds an abstraction for ADTs (hamt/amt). * It removes the callback-based API in the StateManager (difficult to abstract across actor versions). * It _does not_ actually add support for actors v2. We can do that in a followup patch but that should be relatively easy. This patch is heavily WIP and does not compile. Feel free to push changes directly to this branch. Notes: * State tree access now needs a network version, because the HAMT type will change. * I haven't figured out a nice way to abstract over changes to the _message_ types. However, many of them will be type aliased to actors v0 in actors v2 so we can likely continue using the v0 versions (or use the v2 versions everywhere). I've been renaming imports to `v0*` to make it clear that we're importing types from a _specific_ actors version. TODO: * Consider merging incremental improvements? We'd have to get this compiling again first but we could merge in the new abstractions, and slowly switch over. * Finish migrating to the new abstractions. * Remove all actor state types from the public API. See `miner.State.Info()` for the planned approach here. * Fix the tests. This is likely going to be a massive pain. --- api/api_full.go | 7 +- api/types.go | 47 +------- chain/actors/adt/adt.go | 57 +++++++++ chain/actors/adt/store.go | 17 +++ chain/actors/builtin/README.md | 29 +++++ chain/actors/builtin/builtin.go | 23 ++++ chain/actors/builtin/init/init.go | 32 +++++ chain/actors/builtin/init/v0.go | 22 ++++ chain/actors/builtin/market/market.go | 32 +++++ chain/actors/builtin/market/v0.go | 25 ++++ chain/actors/builtin/miner/miner.go | 59 ++++++++++ chain/actors/builtin/miner/v0.go | 112 ++++++++++++++++++ chain/actors/builtin/power/power.go | 28 +++++ chain/actors/builtin/power/v0.go | 16 +++ chain/actors/version.go | 24 ++++ chain/messagepool/provider.go | 4 +- chain/state/statetree.go | 31 ++--- chain/stmgr/read.go | 138 ++++------------------ chain/stmgr/stmgr.go | 30 ++--- chain/stmgr/utils.go | 24 ---- chain/sub/incoming.go | 16 +-- chain/sync.go | 3 +- chain/vm/invoker.go | 1 + cmd/lotus-shed/balances.go | 5 +- cmd/lotus-shed/genesis-verify.go | 2 +- cmd/lotus-storage-miner/proving.go | 161 +++++++++++--------------- extern/storage-sealing/checks.go | 4 +- go.mod | 4 +- go.sum | 6 + node/impl/full/state.go | 46 ++++---- storage/adapter_storage_miner.go | 13 +-- storage/wdpost_run.go | 103 +++++++++++----- storage/wdpost_sched.go | 6 +- 33 files changed, 735 insertions(+), 392 deletions(-) create mode 100644 chain/actors/adt/adt.go create mode 100644 chain/actors/adt/store.go create mode 100644 chain/actors/builtin/README.md create mode 100644 chain/actors/builtin/builtin.go create mode 100644 chain/actors/builtin/init/init.go create mode 100644 chain/actors/builtin/init/v0.go create mode 100644 chain/actors/builtin/market/market.go create mode 100644 chain/actors/builtin/market/v0.go create mode 100644 chain/actors/builtin/miner/miner.go create mode 100644 chain/actors/builtin/miner/v0.go create mode 100644 chain/actors/builtin/power/power.go create mode 100644 chain/actors/builtin/power/v0.go create mode 100644 chain/actors/version.go diff --git a/api/api_full.go b/api/api_full.go index 9d1d7ab63..e5147db47 100644 --- a/api/api_full.go +++ b/api/api_full.go @@ -18,6 +18,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" + "github.com/filecoin-project/go-state-types/dline" "github.com/filecoin-project/specs-actors/actors/builtin/market" "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/specs-actors/actors/builtin/paych" @@ -312,15 +313,11 @@ type FullNode interface { StateMinerActiveSectors(context.Context, address.Address, types.TipSetKey) ([]*ChainSectorInfo, error) // StateMinerProvingDeadline calculates the deadline at some epoch for a proving period // and returns the deadline-related calculations. - StateMinerProvingDeadline(context.Context, address.Address, types.TipSetKey) (*miner.DeadlineInfo, error) + StateMinerProvingDeadline(context.Context, address.Address, types.TipSetKey) (*dline.Info, error) // StateMinerPower returns the power of the indicated miner StateMinerPower(context.Context, address.Address, types.TipSetKey) (*MinerPower, error) // StateMinerInfo returns info about the indicated miner StateMinerInfo(context.Context, address.Address, types.TipSetKey) (MinerInfo, error) - // StateMinerDeadlines returns all the proving deadlines for the given miner - StateMinerDeadlines(context.Context, address.Address, types.TipSetKey) ([]*miner.Deadline, error) - // StateMinerPartitions loads miner partitions for the specified miner/deadline - StateMinerPartitions(context.Context, address.Address, uint64, types.TipSetKey) ([]*miner.Partition, error) // StateMinerFaults returns a bitfield indicating the faulty sectors of the given miner StateMinerFaults(context.Context, address.Address, types.TipSetKey) (bitfield.BitField, error) // StateAllMinerFaults returns all non-expired Faults that occur within lookback epochs of the given tipset diff --git a/api/types.go b/api/types.go index dc8432818..4133a7105 100644 --- a/api/types.go +++ b/api/types.go @@ -8,9 +8,10 @@ import ( datatransfer "github.com/filecoin-project/go-data-transfer" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/lotus/build" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/ipfs/go-cid" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + "github.com/libp2p/go-libp2p-core/peer" pubsub "github.com/libp2p/go-libp2p-pubsub" ma "github.com/multiformats/go-multiaddr" @@ -49,48 +50,6 @@ type PubsubScore struct { Score *pubsub.PeerScoreSnapshot } -type MinerInfo struct { - Owner address.Address // Must be an ID-address. - Worker address.Address // Must be an ID-address. - NewWorker address.Address // Must be an ID-address. - ControlAddresses []address.Address // Must be an ID-addresses. - WorkerChangeEpoch abi.ChainEpoch - PeerId *peer.ID - Multiaddrs []abi.Multiaddrs - SealProofType abi.RegisteredSealProof - SectorSize abi.SectorSize - WindowPoStPartitionSectors uint64 -} - -func NewApiMinerInfo(info *miner.MinerInfo) MinerInfo { - var pid *peer.ID - if peerID, err := peer.IDFromBytes(info.PeerId); err == nil { - pid = &peerID - } - - mi := MinerInfo{ - Owner: info.Owner, - Worker: info.Worker, - ControlAddresses: info.ControlAddresses, - - NewWorker: address.Undef, - WorkerChangeEpoch: -1, - - PeerId: pid, - Multiaddrs: info.Multiaddrs, - SealProofType: info.SealProofType, - SectorSize: info.SectorSize, - WindowPoStPartitionSectors: info.WindowPoStPartitionSectors, - } - - if info.PendingWorkerKey != nil { - mi.NewWorker = info.PendingWorkerKey.NewWorker - mi.WorkerChangeEpoch = info.PendingWorkerKey.EffectiveAt - } - - return mi -} - type MessageSendSpec struct { MaxFee abi.TokenAmount } @@ -151,3 +110,5 @@ func NewDataTransferChannel(hostID peer.ID, channelState datatransfer.ChannelSta } return channel } + +type diff --git a/chain/actors/adt/adt.go b/chain/actors/adt/adt.go new file mode 100644 index 000000000..144150659 --- /dev/null +++ b/chain/actors/adt/adt.go @@ -0,0 +1,57 @@ +package adt + +import ( + "github.com/ipfs/go-cid" + "golang.org/x/xerrors" + + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/cbor" + "github.com/filecoin-project/go-state-types/network" + "github.com/filecoin-project/lotus/chain/actors/builtin" + v0adt "github.com/filecoin-project/specs-actors/actors/util/adt" +) + +type Map interface { + Root() (cid.Cid, error) + + Put(k abi.Keyer, v cbor.Marshaler) error + Get(k abi.Keyer, v cbor.Unmarshaler) (bool, error) + Delete(k abi.Keyer) error + + ForEach(v cbor.Unmarshaler, fn func(key string) error) error +} + +func AsMap(store Store, root cid.Cid, version network.Version) (Map, error) { + switch builtin.VersionForNetwork(version) { + case builtin.Version0: + return v0adt.AsMap(store, root) + } + return nil, xerrors.Errorf("unknown network version: %d", version) +} + +func NewMap(store Store, version network.Version) (Map, error) { + switch builtin.VersionForNetwork(version) { + case builtin.Version0: + return v0adt.MakeEmptyMap(store) + } + return nil, xerrors.Errorf("unknown network version: %d", version) +} + +type Array interface { + Root() (cid.Cid, error) + + Set(idx uint64, v cbor.Marshaler) error + Get(idx uint64, v cbor.Unmarshaler) (bool, error) + Delete(idx uint64) error + Length() uint64 + + ForEach(v cbor.Unmarshaler, fn func(idx int) error) error +} + +func AsArray(store Store, root cid.Cid, version network.Version) (Array, error) { + switch builtin.VersionForNetwork(version) { + case builtin.Version0: + return v0adt.AsArray(store, root) + } + return nil, xerrors.Errorf("unknown network version: %d", version) +} diff --git a/chain/actors/adt/store.go b/chain/actors/adt/store.go new file mode 100644 index 000000000..8dd9841a1 --- /dev/null +++ b/chain/actors/adt/store.go @@ -0,0 +1,17 @@ +package adt + +import ( + "context" + + adt "github.com/filecoin-project/specs-actors/actors/util/adt" + cbor "github.com/ipfs/go-ipld-cbor" +) + +type Store interface { + Context() context.Context + cbor.IpldStore +} + +func WrapStore(ctx context.Context, store cbor.IpldStore) Store { + return adt.WrapStore(ctx, store) +} diff --git a/chain/actors/builtin/README.md b/chain/actors/builtin/README.md new file mode 100644 index 000000000..21b3fd38f --- /dev/null +++ b/chain/actors/builtin/README.md @@ -0,0 +1,29 @@ +# Actors + +This package contains shims for abstracting over different actor versions. + +## Design + +Shims in this package follow a few common design principles. + +### Structure Agnostic + +Shims interfaces defined in this package should (ideally) not change even if the +structure of the underlying data changes. For example: + +* All shims store an internal "store" object. That way, state can be moved into + a separate object without needing to add a store to the function signature. +* All functions must return an error, even if unused for now. + +### Minimal + +These interfaces should be expanded only as necessary to reduce maintenance burden. + +### Queries, not field assessors. + +When possible, functions should query the state instead of simply acting as +field assessors. These queries are more likely to remain stable across +specs-actor upgrades than specific state fields. + +Note: there is a trade-off here. Avoid implementing _complicated_ query logic +inside these shims, as it will need to be replicated in every shim. diff --git a/chain/actors/builtin/builtin.go b/chain/actors/builtin/builtin.go new file mode 100644 index 000000000..173f50ba6 --- /dev/null +++ b/chain/actors/builtin/builtin.go @@ -0,0 +1,23 @@ +package builtin + +import ( + "fmt" + + "github.com/filecoin-project/go-state-types/network" +) + +type Version int + +const ( + Version0 = iota +) + +// Converts a network version into a specs-actors version. +func VersionForNetwork(version network.Version) Version { + switch version { + case network.Version0, network.Version1: + return Version + default: + panic(fmt.Sprintf("unsupported network version %d", version)) + } +} diff --git a/chain/actors/builtin/init/init.go b/chain/actors/builtin/init/init.go new file mode 100644 index 000000000..de71a032c --- /dev/null +++ b/chain/actors/builtin/init/init.go @@ -0,0 +1,32 @@ +package init + +import ( + "github.com/filecoin-project/go-bitfield" + "github.com/filecoin-project/go-state-types/cbor" + "golang.org/x/xerrors" + + v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" + + "github.com/filecoin-project/lotus/chain/actors/adt" + "github.com/filecoin-project/lotus/chain/types" +) + +func Load(store adt.Store, act *types.Actor) (State, error) { + switch act.Code { + case v0builtin.InitActorCodeID: + out := v0State{store: store} + err := store.Get(store.Context(), act.Head, &out) + if err != nil { + return nil, err + } + return &out, nil + } + return nil, xerrors.Errorf("unknown actor code %s", act.Code) +} + +type State interface { + cbor.Marshaler + + ResolveAddress(address addr.Address) (address.Address, bool, error) + MapAddressToNewID(address addr.Address) (address.Address, error) +} diff --git a/chain/actors/builtin/init/v0.go b/chain/actors/builtin/init/v0.go new file mode 100644 index 000000000..3a94f59f0 --- /dev/null +++ b/chain/actors/builtin/init/v0.go @@ -0,0 +1,22 @@ +package init + +import ( + "github.com/filecoin-project/go-address" + + "github.com/filecoin-project/specs-actors/actors/builtin/init" + + "github.com/filecoin-project/lotus/chain/actors/adt" +) + +type v0State struct { + init.State + store adt.Store +} + +func (s *v0State) ResolveAddress(address address.Address) (address.Address, bool, error) { + return s.State.ResolveAddress(s.store, address) +} + +func (s *v0State) MapAddressToNewID(address address.Address) (address.Address, error) { + return s.State.MapAddressToNewID(s.store, address) +} diff --git a/chain/actors/builtin/market/market.go b/chain/actors/builtin/market/market.go new file mode 100644 index 000000000..663fa0e83 --- /dev/null +++ b/chain/actors/builtin/market/market.go @@ -0,0 +1,32 @@ +package market + +import ( + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/cbor" + "github.com/ipfs/go-cid" +) + +func Load(store adt.Store, act *types.Actor) (st State, err error) { + switch act.Code { + case v0builtin.MarketActorCodeID: + out := v0State{store: store} + err := store.Get(store.Context(), act.Head, &out) + if err != nil { + return nil, err + } + return &out, nil + } + return nil, xerrors.Errorf("unknown actor code %s", act.Code) +} + +type State interface { + cbor.Marshaler + EscrowTable() (BalanceTable, error) + LockedTable() (BalanceTable, error) + TotalLocked() (abi.TokenAmount, error) +} + +type BalanceTable interface { + Get(key address.Address) (abi.TokenAmount, error) +} diff --git a/chain/actors/builtin/market/v0.go b/chain/actors/builtin/market/v0.go new file mode 100644 index 000000000..23f33e3d3 --- /dev/null +++ b/chain/actors/builtin/market/v0.go @@ -0,0 +1,25 @@ +package market + +import ( + "github.com/filecoin-project/specs-actors/actors/builtin/market" + "github.com/filecoin-project/specs-actors/actors/util/adt" +) + +type v0State struct { + market.State + store adt.Store +} + +func (s *v0State) TotalLocked() (abi.TokenAmount, error) { + fml := types.BigAdd(s.TotalClientLockedCollateral, s.TotalProviderLockedCollateral) + fml = types.BigAdd(fml, s.TotalClientStorageFee) + return fml, nil +} + +func (s *v0State) EscrowTable() (BalanceTable, error) { + return adt.AsBalanceTable(s.store, s.State.EscrowTable) +} + +func (s *v0State) Lockedtable() (BalanceTable, error) { + return adt.AsBalanceTable(s.store, s.State.LockedTable) +} diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go new file mode 100644 index 000000000..50453827d --- /dev/null +++ b/chain/actors/builtin/miner/miner.go @@ -0,0 +1,59 @@ +package miner + +import ( + "github.com/filecoin-project/go-bitfield" + "github.com/filecoin-project/go-state-types/abi" + "golang.org/x/xerrors" + + v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" + + "github.com/filecoin-project/lotus/chain/actors/adt" + "github.com/filecoin-project/lotus/chain/types" +) + +func Load(store adt.Store, act *types.Actor) (st State, err error) { + switch act.Code { + case v0builtin.StorageMinerActorCodeID: + out := v0State{store: store} + err := store.Get(store.Context(), act.Head, &out) + if err != nil { + return nil, err + } + return &out, nil + } + return nil, xerrors.Errorf("unknown actor code %s", act.Code) +} + +type State interface { + cbor.Marshaler + + LoadDeadline(idx uint64) (Deadline, error) + ForEachDeadline(cb func(idx uint64, dl Deadline) error) error + NumDeadlines() (uint64, error) +} + +type Deadline interface { + LoadPartition(idx uint64) (Partition, error) + ForEachPartition(cb func(idx uint64, part Partition) error) error +} + +type Partition interface { + AllSectors() (bitfield.BitField, error) + FaultySectors() (bitfield.BitField, error) + RecoveringSectors() (bitfield.BitField, error) + LiveSectors() (bitfield.BitField, error) + ActiveSectors() (bitfield.BitField, error) +} + +type MinerInfo struct { + Owner address.Address // Must be an ID-address. + Worker address.Address // Must be an ID-address. + NewWorker address.Address // Must be an ID-address. + ControlAddresses []address.Address // Must be an ID-addresses. + WorkerChangeEpoch abi.ChainEpoch + PeerId *peer.ID + Multiaddrs []abi.Multiaddrs + SealProofType abi.RegisteredSealProof + SectorSize abi.SectorSize + WindowPoStPartitionSectors uint64 +} diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go new file mode 100644 index 000000000..8898a26a5 --- /dev/null +++ b/chain/actors/builtin/miner/v0.go @@ -0,0 +1,112 @@ +package miner + +import ( + "github.com/filecoin-project/go-bitfield" + "github.com/filecoin-project/lotus/chain/actors/adt" + "github.com/libp2p/go-libp2p-core/peer" + + "github.com/filecoin-project/specs-actors/actors/builtin/miner" +) + +type v0State struct { + miner.State + store adt.Store +} + +type v0Deadline struct { + miner.Deadline + store adt.Store +} + +type v0Partition struct { + miner.Partition + store adt.Store +} + +func (s *v0State) LoadDeadline(idx uint64) (Deadline, error) { + dls, err := s.State.LoadDeadlines(s.store) + if err != nil { + return nil, err + } + dl, err := dls.LoadDeadline(s.store, idx) + if err != nil { + return nil, err + } + return &v0Deadline{*dl, s.store}, nil +} + +func (s *v0State) ForEachDeadline(cb func(uint64, Deadline) error) error { + dls, err := s.State.LoadDeadlines(s.store) + if err != nil { + return err + } + return dls.ForEach(s.store, func(i uint64, dl *miner.Deadline) error { + return cb(i, &v0Deadline{*dl, s.store}) + }) +} + +func (s *v0State) NumDeadlines() (uint64, error) { + return miner.WPoStPeriodDeadlines, nil +} + +func (s *v0State) Info() (MinerInfo, error) { + info, err := s.State.GetInfo(s.store) + + var pid *peer.ID + if peerID, err := peer.IDFromBytes(info.PeerId); err == nil { + pid = &peerID + } + + mi := MinerInfo{ + Owner: info.Owner, + Worker: info.Worker, + ControlAddresses: info.ControlAddresses, + + NewWorker: address.Undef, + WorkerChangeEpoch: -1, + + PeerId: pid, + Multiaddrs: info.Multiaddrs, + SealProofType: info.SealProofType, + SectorSize: info.SectorSize, + WindowPoStPartitionSectors: info.WindowPoStPartitionSectors, + } + + if info.PendingWorkerKey != nil { + mi.NewWorker = info.PendingWorkerKey.NewWorker + mi.WorkerChangeEpoch = info.PendingWorkerKey.EffectiveAt + } + + return mi +} + +func (d *v0Deadline) LoadPartition(idx uint64) (Partition, error) { + p, err := d.Deadline.LoadPartition(d.store, idx) + if err != nil { + return nil, err + } + return &v0Partition{*p, d.store}, nil +} + +func (d *v0Deadline) ForEachPartition(cb func(uint64, Partition) error) error { + ps, err := d.Deadline.PartitionsArray(d.store) + if err != nil { + return err + } + var part miner.Partition + return ps.ForEach(&part, func(i int64) error { + return cb(uint64(i), &v0Partition{part, d.store}) + }) +} + +func (p *v0Partition) AllSectors() (bitfield.BitField, error) { + return p.Partition.Sectors, nil +} + +func (p *v0Partition) FaultySectors() (bitfield.BitField, error) { + return p.Partition.Faults, nil +} + +func (p *v0Partition) RecoveringSectors() (bitfield.BitField, error) { + return p.Partition.Recoveries, nil +} diff --git a/chain/actors/builtin/power/power.go b/chain/actors/builtin/power/power.go new file mode 100644 index 000000000..7671877e3 --- /dev/null +++ b/chain/actors/builtin/power/power.go @@ -0,0 +1,28 @@ +package power + +import ( + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/cbor" + "github.com/filecoin-project/lotus/chain/actors/adt" + "github.com/filecoin-project/lotus/chain/types" + "golang.org/x/xerrors" +) + +func Load(store adt.Store, act *types.Actor) (st State, err error) { + switch act.Code { + case v0builtin.PowerActorCodeID: + out := v0State{store: store} + err := store.Get(store.Context(), act.Head, &out) + if err != nil { + return nil, err + } + return &out, nil + } + return nil, xerrors.Errorf("unknown actor code %s", act.Code) +} + +type State interface { + cbor.Marshaler + + TotalLocked() (abi.TokenAmount, error) +} diff --git a/chain/actors/builtin/power/v0.go b/chain/actors/builtin/power/v0.go new file mode 100644 index 000000000..8851080e6 --- /dev/null +++ b/chain/actors/builtin/power/v0.go @@ -0,0 +1,16 @@ +package power + +import ( + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/lotus/chain/actors/adt" + "github.com/filecoin-project/specs-actors/actors/builtin/power" +) + +type v0State struct { + power.State + store adt.Store +} + +func (s *v0State) TotalLocked() (abi.TokenAmount, error) { + return s.TotalPledgeCollateral, nil +} diff --git a/chain/actors/version.go b/chain/actors/version.go new file mode 100644 index 000000000..99cc59eaa --- /dev/null +++ b/chain/actors/version.go @@ -0,0 +1,24 @@ +package actors + +import ( + "fmt" + + "github.com/filecoin-project/go-state-types/network" +) + +type Version int + +const ( + Version0 = iota + Version1 +) + +// VersionForNetwork resolves the network version into an specs-actors version. +func VersionForNetwork(v network.Version) Version { + switch v { + case network.Version0, network.Version1: + return Version0 + default: + panic(fmt.Sprintf("unimplemented network version: %d", v)) + } +} diff --git a/chain/messagepool/provider.go b/chain/messagepool/provider.go index 80b9a4297..d67468d9a 100644 --- a/chain/messagepool/provider.go +++ b/chain/messagepool/provider.go @@ -52,8 +52,8 @@ func (mpp *mpoolProvider) GetActorAfter(addr address.Address, ts *types.TipSet) if err != nil { return nil, xerrors.Errorf("computing tipset state for GetActor: %w", err) } - - return &act, mpp.sm.WithStateTree(stcid, mpp.sm.WithActor(addr, stmgr.GetActor(&act))) + version := mpp.sm.GetNtwkVersion(context.TODO(), ts.Height()) + return &act, mpp.sm.WithStateTree(stcid, version, mpp.sm.WithActor(addr, stmgr.GetActor(&act))) } func (mpp *mpoolProvider) StateAccountKey(ctx context.Context, addr address.Address, ts *types.TipSet) (address.Address, error) { diff --git a/chain/state/statetree.go b/chain/state/statetree.go index c083f1817..684e6ce5d 100644 --- a/chain/state/statetree.go +++ b/chain/state/statetree.go @@ -4,10 +4,12 @@ import ( "context" "fmt" + "github.com/filecoin-project/go-state-types/network" + "github.com/filecoin-project/lotus/chain/actors/builtin/init" + init_ "github.com/filecoin-project/lotus/chain/actors/builtin/init" "github.com/filecoin-project/specs-actors/actors/builtin" - init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" - "github.com/filecoin-project/specs-actors/actors/util/adt" + "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/ipfs/go-cid" cbor "github.com/ipfs/go-ipld-cbor" logging "github.com/ipfs/go-log/v2" @@ -22,7 +24,7 @@ var log = logging.Logger("statetree") // StateTree stores actors state by their ID. type StateTree struct { - root *adt.Map + root adt.Map Store cbor.IpldStore snaps *stateSnaps @@ -115,17 +117,18 @@ func (ss *stateSnaps) deleteActor(addr address.Address) { ss.layers[len(ss.layers)-1].actors[addr] = streeOp{Delete: true} } -func NewStateTree(cst cbor.IpldStore) (*StateTree, error) { +func NewStateTree(cst cbor.IpldStore, version network.Version) (*StateTree, error) { return &StateTree{ - root: adt.MakeEmptyMap(adt.WrapStore(context.TODO(), cst)), + root: adt.NewMap(adt.WrapStore(context.TODO(), cst), version), Store: cst, snaps: newStateSnaps(), }, nil } -func LoadStateTree(cst cbor.IpldStore, c cid.Cid) (*StateTree, error) { - nd, err := adt.AsMap(adt.WrapStore(context.TODO(), cst), c) +func LoadStateTree(cst cbor.IpldStore, c cid.Cid, version network.Version) (*StateTree, error) { + // NETUPGRADE: switch map adt type on version upgrade. + nd, err := adt.AsMap(adt.WrapStore(context.TODO(), cst), c, version) if err != nil { log.Errorf("loading hamt node %s failed: %s", c, err) return nil, err @@ -165,12 +168,12 @@ func (st *StateTree) LookupID(addr address.Address) (address.Address, error) { return address.Undef, xerrors.Errorf("getting init actor: %w", err) } - var ias init_.State - if err := st.Store.Get(context.TODO(), act.Head, &ias); err != nil { + ias, err := init.Load(&AdtStore{st.Store}, &act) + if err != nil { return address.Undef, xerrors.Errorf("loading init actor state: %w", err) } - a, found, err := ias.ResolveAddress(&AdtStore{st.Store}, addr) + a, found, err := ias.ResolveAddress(addr) if err == nil && !found { err = types.ErrActorNotFound } @@ -283,18 +286,18 @@ func (st *StateTree) ClearSnapshot() { func (st *StateTree) RegisterNewAddress(addr address.Address) (address.Address, error) { var out address.Address err := st.MutateActor(builtin.InitActorAddr, func(initact *types.Actor) error { - var ias init_.State - if err := st.Store.Get(context.TODO(), initact.Head, &ias); err != nil { + ias, err := init.Load(&AdtStore{st.Store}, initact) + if err != nil { return err } - oaddr, err := ias.MapAddressToNewID(&AdtStore{st.Store}, addr) + oaddr, err := ias.MapAddressToNewID(addr) if err != nil { return err } out = oaddr - ncid, err := st.Store.Put(context.TODO(), &ias) + ncid, err := st.Store.Put(context.TODO(), ias) if err != nil { return err } diff --git a/chain/stmgr/read.go b/chain/stmgr/read.go index c707b5195..2daa9f79d 100644 --- a/chain/stmgr/read.go +++ b/chain/stmgr/read.go @@ -10,146 +10,54 @@ import ( cbor "github.com/ipfs/go-ipld-cbor" "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/network" "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/specs-actors/actors/util/adt" ) -type StateTreeCB func(state *state.StateTree) error - -func (sm *StateManager) WithParentStateTsk(tsk types.TipSetKey, cb StateTreeCB) error { +func (sm *StateManager) ParentStateTsk(tsk types.TipSetKey) (*state.StateTree, error) { ts, err := sm.cs.GetTipSetFromKey(tsk) if err != nil { - return xerrors.Errorf("loading tipset %s: %w", tsk, err) + return nil, xerrors.Errorf("loading tipset %s: %w", tsk, err) } + return sm.ParentState(ts, cb) +} +func (sm *StateManager) ParentState(ts *types.TipSet) (*state.StateTree, error) { cst := cbor.NewCborStore(sm.cs.Blockstore()) - state, err := state.LoadStateTree(cst, sm.parentState(ts)) + version := sm.GetNtwkVersion(context.TODO(), ts.Height()-1) + state, err := state.LoadStateTree(cst, sm.parentState(ts), version) if err != nil { - return xerrors.Errorf("load state tree: %w", err) + return nil, xerrors.Errorf("load state tree: %w", err) } - return cb(state) + return state, nil } -func (sm *StateManager) WithParentState(ts *types.TipSet, cb StateTreeCB) error { +func (sm *StateManager) StateTree(st cid.Cid, ntwkVersion network.Version) (*state.StateTree, error) { cst := cbor.NewCborStore(sm.cs.Blockstore()) - state, err := state.LoadStateTree(cst, sm.parentState(ts)) + state, err := state.LoadStateTree(cst, st, ntwkVersion) if err != nil { - return xerrors.Errorf("load state tree: %w", err) + return nil, xerrors.Errorf("load state tree: %w", err) } - return cb(state) + return state, nil } -func (sm *StateManager) WithStateTree(st cid.Cid, cb StateTreeCB) error { - cst := cbor.NewCborStore(sm.cs.Blockstore()) - state, err := state.LoadStateTree(cst, st) +func (sm *StateManager) LoadActor(_ context.Context, addr address.Address, ts *types.TipSet) (*types.Actor, error) { + state, err := sm.ParentState(ts) if err != nil { - return xerrors.Errorf("load state tree: %w", err) + return nil, err } - - return cb(state) + return state.GetActor(addr) } -type ActorCB func(act *types.Actor) error - -func GetActor(out *types.Actor) ActorCB { - return func(act *types.Actor) error { - *out = *act - return nil - } -} - -func (sm *StateManager) WithActor(addr address.Address, cb ActorCB) StateTreeCB { - return func(state *state.StateTree) error { - act, err := state.GetActor(addr) - if err != nil { - return xerrors.Errorf("get actor: %w", err) - } - - return cb(act) - } -} - -// WithActorState usage: -// Option 1: WithActorState(ctx, idAddr, func(store adt.Store, st *ActorStateType) error {...}) -// Option 2: WithActorState(ctx, idAddr, actorStatePtr) -func (sm *StateManager) WithActorState(ctx context.Context, out interface{}) ActorCB { - return func(act *types.Actor) error { - store := sm.cs.Store(ctx) - - outCallback := reflect.TypeOf(out).Kind() == reflect.Func - - var st reflect.Value - if outCallback { - st = reflect.New(reflect.TypeOf(out).In(1).Elem()) - } else { - st = reflect.ValueOf(out) - } - if err := store.Get(ctx, act.Head, st.Interface()); err != nil { - return xerrors.Errorf("read actor head: %w", err) - } - - if outCallback { - out := reflect.ValueOf(out).Call([]reflect.Value{reflect.ValueOf(store), st}) - if !out[0].IsNil() && out[0].Interface().(error) != nil { - return out[0].Interface().(error) - } - } - - return nil - } -} - -type DeadlinesCB func(store adt.Store, deadlines *miner.Deadlines) error - -func (sm *StateManager) WithDeadlines(cb DeadlinesCB) func(store adt.Store, mas *miner.State) error { - return func(store adt.Store, mas *miner.State) error { - deadlines, err := mas.LoadDeadlines(store) - if err != nil { - return err - } - - return cb(store, deadlines) - } -} - -type DeadlineCB func(store adt.Store, idx uint64, deadline *miner.Deadline) error - -func (sm *StateManager) WithDeadline(idx uint64, cb DeadlineCB) DeadlinesCB { - return func(store adt.Store, deadlines *miner.Deadlines) error { - d, err := deadlines.LoadDeadline(store, idx) - if err != nil { - return err - } - - return cb(store, idx, d) - } -} - -func (sm *StateManager) WithEachDeadline(cb DeadlineCB) DeadlinesCB { - return func(store adt.Store, deadlines *miner.Deadlines) error { - return deadlines.ForEach(store, func(dlIdx uint64, dl *miner.Deadline) error { - return cb(store, dlIdx, dl) - }) - } -} - -type PartitionCB func(store adt.Store, idx uint64, partition *miner.Partition) error - -func (sm *StateManager) WithEachPartition(cb PartitionCB) DeadlineCB { - return func(store adt.Store, idx uint64, deadline *miner.Deadline) error { - parts, err := deadline.PartitionsArray(store) - if err != nil { - return err - } - - var partition miner.Partition - return parts.ForEach(&partition, func(i int64) error { - p := partition - return cb(store, uint64(i), &p) - }) +func (sm *StateManager) LoadActorTsk(_ context.Context, addr address.Address, tsk types.TipSetKey) (*types.Actor, error) { + state, err := sm.ParentStateTsk(tsk) + if err != nil { + return nil, err } + return state.GetActor(addr) } diff --git a/chain/stmgr/stmgr.go b/chain/stmgr/stmgr.go index 929c9daf7..fa4b08147 100644 --- a/chain/stmgr/stmgr.go +++ b/chain/stmgr/stmgr.go @@ -7,14 +7,14 @@ import ( "github.com/filecoin-project/specs-actors/actors/runtime" - "github.com/filecoin-project/specs-actors/actors/builtin/power" - "github.com/filecoin-project/specs-actors/actors/builtin/multisig" "github.com/filecoin-project/go-address" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/actors" + "github.com/filecoin-project/lotus/chain/actors/builtin/market" + "github.com/filecoin-project/lotus/chain/actors/builtin/power" "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/store" "github.com/filecoin-project/lotus/chain/types" @@ -23,7 +23,6 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/market" "github.com/filecoin-project/specs-actors/actors/builtin/reward" "github.com/filecoin-project/specs-actors/actors/util/adt" @@ -201,6 +200,7 @@ func (sm *StateManager) ApplyBlocks(ctx context.Context, parentEpoch abi.ChainEp for i := parentEpoch; i < epoch; i++ { // handle state forks + // XXX: The state tre err = sm.handleStateForks(ctx, vmi.StateTree(), i, ts) if err != nil { return cid.Undef, cid.Undef, xerrors.Errorf("error handling state forks: %w", err) @@ -711,11 +711,14 @@ func (sm *StateManager) ListAllActors(ctx context.Context, ts *types.TipSet) ([] } func (sm *StateManager) MarketBalance(ctx context.Context, addr address.Address, ts *types.TipSet) (api.MarketBalance, error) { - var state market.State - _, err := sm.LoadActorState(ctx, builtin.StorageMarketActorAddr, &state, ts) + st, err := sm.ParentState(ts) if err != nil { return api.MarketBalance{}, err } + act, err := st.GetActor(builtin.StorageMarketActorAddr) + if err != nil { + return nil, err + } addr, err = sm.LookupID(ctx, addr, ts) if err != nil { @@ -1016,19 +1019,17 @@ func GetFilMined(ctx context.Context, st *state.StateTree) (abi.TokenAmount, err } func getFilMarketLocked(ctx context.Context, st *state.StateTree) (abi.TokenAmount, error) { - mactor, err := st.GetActor(builtin.StorageMarketActorAddr) + act, err := st.GetActor(builtin.StorageMarketActorAddr) if err != nil { return big.Zero(), xerrors.Errorf("failed to load market actor: %w", err) } - var mst market.State - if err := st.Store.Get(ctx, mactor.Head, &mst); err != nil { + mst, err := market.Load(adt.WrapStore(ctx, st.Store), act) + if err != nil { return big.Zero(), xerrors.Errorf("failed to load market state: %w", err) } - fml := types.BigAdd(mst.TotalClientLockedCollateral, mst.TotalProviderLockedCollateral) - fml = types.BigAdd(fml, mst.TotalClientStorageFee) - return fml, nil + return mst.TotalLocked() } func getFilPowerLocked(ctx context.Context, st *state.StateTree) (abi.TokenAmount, error) { @@ -1037,11 +1038,12 @@ func getFilPowerLocked(ctx context.Context, st *state.StateTree) (abi.TokenAmoun return big.Zero(), xerrors.Errorf("failed to load power actor: %w", err) } - var pst power.State - if err := st.Store.Get(ctx, pactor.Head, &pst); err != nil { + pst, err := power.Load(adt.WrapStore(ctx, st.Store), act) + if err != nil { return big.Zero(), xerrors.Errorf("failed to load power state: %w", err) } - return pst.TotalPledgeCollateral, nil + + return pst.TotalLocked(), nil } func (sm *StateManager) GetFilLocked(ctx context.Context, st *state.StateTree) (abi.TokenAmount, error) { diff --git a/chain/stmgr/utils.go b/chain/stmgr/utils.go index b21400da6..a137afb51 100644 --- a/chain/stmgr/utils.go +++ b/chain/stmgr/utils.go @@ -56,30 +56,6 @@ func GetNetworkName(ctx context.Context, sm *StateManager, st cid.Cid) (dtypes.N return dtypes.NetworkName(state.NetworkName), nil } -func (sm *StateManager) LoadActorState(ctx context.Context, addr address.Address, out interface{}, ts *types.TipSet) (*types.Actor, error) { - var a *types.Actor - if err := sm.WithParentState(ts, sm.WithActor(addr, func(act *types.Actor) error { - a = act - return sm.WithActorState(ctx, out)(act) - })); err != nil { - return nil, err - } - - return a, nil -} - -func (sm *StateManager) LoadActorStateRaw(ctx context.Context, addr address.Address, out interface{}, st cid.Cid) (*types.Actor, error) { - var a *types.Actor - if err := sm.WithStateTree(st, sm.WithActor(addr, func(act *types.Actor) error { - a = act - return sm.WithActorState(ctx, out)(act) - })); err != nil { - return nil, err - } - - return a, nil -} - func GetMinerWorkerRaw(ctx context.Context, sm *StateManager, st cid.Cid, maddr address.Address) (address.Address, error) { var mas miner.State _, err := sm.LoadActorStateRaw(ctx, maddr, &mas, st) diff --git a/chain/sub/incoming.go b/chain/sub/incoming.go index 34dde227f..7c672bee2 100644 --- a/chain/sub/incoming.go +++ b/chain/sub/incoming.go @@ -11,7 +11,6 @@ import ( "golang.org/x/xerrors" address "github.com/filecoin-project/go-address" - miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/specs-actors/actors/util/adt" lru "github.com/hashicorp/golang-lru" blocks "github.com/ipfs/go-block-format" @@ -28,6 +27,7 @@ import ( "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/messagepool" "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/stmgr" @@ -432,9 +432,10 @@ func (bv *BlockValidator) checkPowerAndGetWorkerKey(ctx context.Context, bh *typ if err != nil { return address.Undef, err } + buf := bufbstore.NewBufferedBstore(bv.chain.Blockstore()) cst := cbor.NewCborStore(buf) - state, err := state.LoadStateTree(cst, st) + state, err := state.LoadStateTree(cst, st, bv.stmgr.GetNtwkVersion(ctx, ts.Height())) if err != nil { return address.Undef, err } @@ -443,19 +444,12 @@ func (bv *BlockValidator) checkPowerAndGetWorkerKey(ctx context.Context, bh *typ return address.Undef, err } - blk, err := bv.chain.Blockstore().Get(act.Head) - if err != nil { - return address.Undef, err - } - aso := blk.RawData() - - var mst miner.State - err = mst.UnmarshalCBOR(bytes.NewReader(aso)) + mst, err := miner.Load(bv.chain.Store(ctx), act) if err != nil { return address.Undef, err } - info, err := mst.GetInfo(adt.WrapStore(ctx, cst)) + info, err := mst.Info() if err != nil { return address.Undef, err } diff --git a/chain/sync.go b/chain/sync.go index d2cf08b92..d5bd777b7 100644 --- a/chain/sync.go +++ b/chain/sync.go @@ -1027,9 +1027,10 @@ func (syncer *Syncer) checkBlockMessages(ctx context.Context, b *types.FullBlock if err != nil { return err } + nwVersion := syncer.sm.GetNtwkVersion(ctx, baseTs.Height()) cst := cbor.NewCborStore(syncer.store.Blockstore()) - st, err := state.LoadStateTree(cst, stateroot) + st, err := state.LoadStateTree(cst, stateroot, nwVersion) if err != nil { return xerrors.Errorf("failed to load base state tree: %w", err) } diff --git a/chain/vm/invoker.go b/chain/vm/invoker.go index 2ec56a9db..8583b0438 100644 --- a/chain/vm/invoker.go +++ b/chain/vm/invoker.go @@ -47,6 +47,7 @@ func NewInvoker() *Invoker { } // add builtInCode using: register(cid, singleton) + // NETUPGRADE: register code IDs for v2, etc. inv.Register(builtin.SystemActorCodeID, system.Actor{}, adt.EmptyValue{}) inv.Register(builtin.InitActorCodeID, init_.Actor{}, init_.State{}) inv.Register(builtin.RewardActorCodeID, reward.Actor{}, reward.State{}) diff --git a/cmd/lotus-shed/balances.go b/cmd/lotus-shed/balances.go index aad321783..f3ffd140f 100644 --- a/cmd/lotus-shed/balances.go +++ b/cmd/lotus-shed/balances.go @@ -12,6 +12,7 @@ import ( "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/lotus/chain/state" "github.com/filecoin-project/lotus/chain/stmgr" "github.com/filecoin-project/lotus/chain/store" @@ -170,7 +171,9 @@ var chainBalanceStateCmd = &cli.Command{ sm := stmgr.NewStateManager(cs) - tree, err := state.LoadStateTree(cst, sroot) + // NETUPGRADE: FIXME. + // Options: (a) encode the version in the chain or (b) pass a flag. + tree, err := state.LoadStateTree(cst, sroot, network.Version0) if err != nil { return err } diff --git a/cmd/lotus-shed/genesis-verify.go b/cmd/lotus-shed/genesis-verify.go index 043cb72bb..62808db9b 100644 --- a/cmd/lotus-shed/genesis-verify.go +++ b/cmd/lotus-shed/genesis-verify.go @@ -79,7 +79,7 @@ var genesisVerifyCmd = &cli.Command{ cst := cbor.NewCborStore(bs) - stree, err := state.LoadStateTree(cst, ts.ParentState()) + stree, err := state.LoadStateTree(cst, ts.ParentState(), sm.GetNtwkVersion()) if err != nil { return err } diff --git a/cmd/lotus-storage-miner/proving.go b/cmd/lotus-storage-miner/proving.go index b5087556d..d9bf81376 100644 --- a/cmd/lotus-storage-miner/proving.go +++ b/cmd/lotus-storage-miner/proving.go @@ -12,9 +12,11 @@ import ( "golang.org/x/xerrors" "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" + "github.com/filecoin-project/lotus/api/apibstore" "github.com/filecoin-project/lotus/build" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + "github.com/filecoin-project/lotus/chain/store" "github.com/filecoin-project/lotus/chain/types" lcli "github.com/filecoin-project/lotus/cli" ) @@ -49,54 +51,41 @@ var provingFaultsCmd = &cli.Command{ ctx := lcli.ReqContext(cctx) + stor := store.ActorStore(ctx, apibstore.NewAPIBlockstore(api)) + maddr, err := getActorAddress(ctx, nodeApi, cctx.String("actor")) if err != nil { return err } - var mas miner.State - { - mact, err := api.StateGetActor(ctx, maddr, types.EmptyTSK) - if err != nil { - return err - } - rmas, err := api.ChainReadObj(ctx, mact.Head) - if err != nil { - return err - } - if err := mas.UnmarshalCBOR(bytes.NewReader(rmas)); err != nil { - return err - } + mact, err := api.StateGetActor(ctx, maddr, types.EmptyTSK) + if err != nil { + return err + } + + mas, err := miner.Load(stor, mact) + if err != nil { + return err } fmt.Printf("Miner: %s\n", color.BlueString("%s", maddr)) - head, err := api.ChainHead(ctx) - if err != nil { - return xerrors.Errorf("getting chain head: %w", err) - } - deadlines, err := api.StateMinerDeadlines(ctx, maddr, head.Key()) - if err != nil { - return xerrors.Errorf("getting miner deadlines: %w", err) - } tw := tabwriter.NewWriter(os.Stdout, 2, 4, 2, ' ', 0) _, _ = fmt.Fprintln(tw, "deadline\tpartition\tsectors") - for dlIdx := range deadlines { - partitions, err := api.StateMinerPartitions(ctx, maddr, uint64(dlIdx), types.EmptyTSK) - if err != nil { - return xerrors.Errorf("loading partitions for deadline %d: %w", dlIdx, err) - } - - for partIdx, partition := range partitions { - faulty, err := partition.Faults.All(10000000) + err = mas.ForEachDeadline(func(dlIdx uint64, dl miner.Deadline) error { + dl.ForEachPartition(func(partIdx uint64, part miner.Partition) error { + faults, err := part.Faults() if err != nil { return err } - - for _, num := range faulty { + faults.ForEach(func(num uint64) error { _, _ = fmt.Fprintf(tw, "%d\t%d\t%d\n", dlIdx, partIdx, num) - } - } + return nil + }) + }) + }) + if err != nil { + return err } return tw.Flush() }, @@ -132,67 +121,61 @@ var provingInfoCmd = &cli.Command{ return xerrors.Errorf("getting chain head: %w", err) } + mact, err := api.StateGetActor(ctx, maddr, head.Key()) + if err != nil { + return err + } + + stor := store.ActorStore(ctx, apibstore.NewAPIBlockstore(api)) + + mas, err := miner.Load(stor, mact) + if err != nil { + return err + } + cd, err := api.StateMinerProvingDeadline(ctx, maddr, head.Key()) if err != nil { return xerrors.Errorf("getting miner info: %w", err) } - deadlines, err := api.StateMinerDeadlines(ctx, maddr, head.Key()) - if err != nil { - return xerrors.Errorf("getting miner deadlines: %w", err) - } - fmt.Printf("Miner: %s\n", color.BlueString("%s", maddr)) - var mas miner.State - { - mact, err := api.StateGetActor(ctx, maddr, types.EmptyTSK) - if err != nil { - return err - } - rmas, err := api.ChainReadObj(ctx, mact.Head) - if err != nil { - return err - } - if err := mas.UnmarshalCBOR(bytes.NewReader(rmas)); err != nil { - return err - } - } - - parts := map[uint64][]*miner.Partition{} - for dlIdx := range deadlines { - part, err := api.StateMinerPartitions(ctx, maddr, uint64(dlIdx), types.EmptyTSK) - if err != nil { - return xerrors.Errorf("getting miner partition: %w", err) - } - - parts[uint64(dlIdx)] = part - } - proving := uint64(0) faults := uint64(0) recovering := uint64(0) + curDeadlineSectors := uint64(0) - for _, partitions := range parts { - for _, partition := range partitions { - sc, err := partition.Sectors.Count() - if err != nil { - return xerrors.Errorf("count partition sectors: %w", err) + if err := mas.ForEachDeadline(func(dlIdx uint64, dl miner.Deadline) error { + return dl.ForEachPartition(func(partIdx uint64, part miner.Partition) error { + if bf, err := part.LiveSectors(); err != nil { + return err + } else if count, err := bf.Count(); err != nil { + return err + } else { + proving += count + if dlIdx == cd.Index { + curDeadlineSectors += count + } } - proving += sc - fc, err := partition.Faults.Count() - if err != nil { - return xerrors.Errorf("count partition faults: %w", err) + if bf, err := part.Faults(); err != nil { + return err + } else if count, err := bf.Count(); err != nil { + return err + } else { + faults += count } - faults += fc - rc, err := partition.Recoveries.Count() - if err != nil { - return xerrors.Errorf("count partition recoveries: %w", err) + if bf, err := part.Recovering(); err != nil { + return err + } else if count, err := bf.Count(); err != nil { + return err + } else { + recovering += count } - recovering += rc - } + }) + }); err != nil { + return xerrors.Errorf("walking miner deadlines and partitions: %w", err) } var faultPerc float64 @@ -202,28 +185,15 @@ var provingInfoCmd = &cli.Command{ fmt.Printf("Current Epoch: %d\n", cd.CurrentEpoch) - fmt.Printf("Proving Period Boundary: %d\n", cd.PeriodStart%miner.WPoStProvingPeriod) + fmt.Printf("Proving Period Boundary: %d\n", cd.PeriodStart%cd.WPoStProvingPeriod) fmt.Printf("Proving Period Start: %s\n", epochTime(cd.CurrentEpoch, cd.PeriodStart)) - fmt.Printf("Next Period Start: %s\n\n", epochTime(cd.CurrentEpoch, cd.PeriodStart+miner.WPoStProvingPeriod)) + fmt.Printf("Next Period Start: %s\n\n", epochTime(cd.CurrentEpoch, cd.PeriodStart+cd.WPoStProvingPeriod)) fmt.Printf("Faults: %d (%.2f%%)\n", faults, faultPerc) fmt.Printf("Recovering: %d\n", recovering) fmt.Printf("Deadline Index: %d\n", cd.Index) - - if cd.Index < miner.WPoStPeriodDeadlines { - curDeadlineSectors := uint64(0) - for _, partition := range parts[cd.Index] { - sc, err := partition.Sectors.Count() - if err != nil { - return xerrors.Errorf("counting current deadline sectors: %w", err) - } - curDeadlineSectors += sc - } - - fmt.Printf("Deadline Sectors: %d\n", curDeadlineSectors) - } - + fmt.Printf("Deadline Sectors: %d\n", curDeadlineSectors) fmt.Printf("Deadline Open: %s\n", epochTime(cd.CurrentEpoch, cd.Open)) fmt.Printf("Deadline Close: %s\n", epochTime(cd.CurrentEpoch, cd.Close)) fmt.Printf("Deadline Challenge: %s\n", epochTime(cd.CurrentEpoch, cd.Challenge)) @@ -286,6 +256,7 @@ var provingDeadlinesCmd = &cli.Command{ if err != nil { return err } + miner.Load rmas, err := api.ChainReadObj(ctx, mact.Head) if err != nil { return err diff --git a/extern/storage-sealing/checks.go b/extern/storage-sealing/checks.go index 906c9c106..074c4cfcf 100644 --- a/extern/storage-sealing/checks.go +++ b/extern/storage-sealing/checks.go @@ -4,7 +4,7 @@ import ( "bytes" "context" - saproof "github.com/filecoin-project/specs-actors/actors/runtime/proof" + v0proof "github.com/filecoin-project/specs-actors/actors/runtime/proof" "golang.org/x/xerrors" @@ -170,7 +170,7 @@ func (m *Sealing) checkCommit(ctx context.Context, si SectorInfo, proof []byte, log.Warn("on-chain sealed CID doesn't match!") } - ok, err := m.verif.VerifySeal(saproof.SealVerifyInfo{ + ok, err := m.verif.VerifySeal(v0proof.SealVerifyInfo{ SectorID: m.minerSector(si.SectorNumber), SealedCID: pci.Info.SealedCID, SealProof: spt, diff --git a/go.mod b/go.mod index bc4067d67..9a7c5403b 100644 --- a/go.mod +++ b/go.mod @@ -34,11 +34,11 @@ require ( github.com/filecoin-project/go-multistore v0.0.3 github.com/filecoin-project/go-padreader v0.0.0-20200903213702-ed5fae088b20 github.com/filecoin-project/go-paramfetch v0.0.2-0.20200701152213-3e0f0afdc261 - github.com/filecoin-project/go-state-types v0.0.0-20200905071437-95828685f9df + github.com/filecoin-project/go-state-types v0.0.0-20200911004822-964d6c679cfc github.com/filecoin-project/go-statemachine v0.0.0-20200813232949-df9b130df370 github.com/filecoin-project/go-statestore v0.1.0 github.com/filecoin-project/go-storedcounter v0.0.0-20200421200003-1c99c62e8a5b - github.com/filecoin-project/specs-actors v0.9.7 + github.com/filecoin-project/specs-actors v0.9.9-0.20200911231631-727cd8845d30 github.com/filecoin-project/specs-storage v0.1.1-0.20200907031224-ed2e5cd13796 github.com/filecoin-project/test-vectors/schema v0.0.1 github.com/gbrlsnchs/jwt/v3 v3.0.0-beta.1 diff --git a/go.sum b/go.sum index 0fa13fe70..106814b02 100644 --- a/go.sum +++ b/go.sum @@ -226,6 +226,8 @@ github.com/filecoin-project/go-fil-commcid v0.0.0-20200716160307-8f644712406f h1 github.com/filecoin-project/go-fil-commcid v0.0.0-20200716160307-8f644712406f/go.mod h1:Eaox7Hvus1JgPrL5+M3+h7aSPHc0cVqpSxA+TxIEpZQ= github.com/filecoin-project/go-fil-markets v0.6.0 h1:gfxMweUHo4u+2BZh2Q7/7+cV0/ttikuJfhkkxLRsE2Q= github.com/filecoin-project/go-fil-markets v0.6.0/go.mod h1:LhSFYLkjaoe0vFRKABGYyw1Jz+9jCpF1sPA7yOftLTw= +github.com/filecoin-project/go-hamt-ipld v0.1.5 h1:uoXrKbCQZ49OHpsTCkrThPNelC4W3LPEk0OrS/ytIBM= +github.com/filecoin-project/go-hamt-ipld v0.1.5/go.mod h1:6Is+ONR5Cd5R6XZoCse1CWaXZc0Hdb/JeX+EQCQzX24= github.com/filecoin-project/go-jsonrpc v0.1.2-0.20200822201400-474f4fdccc52 h1:FXtCp0ybqdQL9knb3OGDpkNTaBbPxgkqPeWKotUwkH0= github.com/filecoin-project/go-jsonrpc v0.1.2-0.20200822201400-474f4fdccc52/go.mod h1:XBBpuKIMaXIIzeqzO1iucq4GvbF8CxmXRFoezRh+Cx4= github.com/filecoin-project/go-multistore v0.0.3 h1:vaRBY4YiA2UZFPK57RNuewypB8u0DzzQwqsL0XarpnI= @@ -238,6 +240,8 @@ github.com/filecoin-project/go-state-types v0.0.0-20200903145444-247639ffa6ad/go github.com/filecoin-project/go-state-types v0.0.0-20200904021452-1883f36ca2f4/go.mod h1:IQ0MBPnonv35CJHtWSN3YY1Hz2gkPru1Q9qoaYLxx9I= github.com/filecoin-project/go-state-types v0.0.0-20200905071437-95828685f9df h1:m2esXSuGBkuXlRyCsl1a/7/FkFam63o1OzIgzaHtOfI= github.com/filecoin-project/go-state-types v0.0.0-20200905071437-95828685f9df/go.mod h1:IQ0MBPnonv35CJHtWSN3YY1Hz2gkPru1Q9qoaYLxx9I= +github.com/filecoin-project/go-state-types v0.0.0-20200911004822-964d6c679cfc h1:1vr/LoqGq5m5g37Q3sNSAjfwF1uJY0zmiHcvnxY6hik= +github.com/filecoin-project/go-state-types v0.0.0-20200911004822-964d6c679cfc/go.mod h1:ezYnPf0bNkTsDibL/psSz5dy4B5awOJ/E7P2Saeep8g= github.com/filecoin-project/go-statemachine v0.0.0-20200714194326-a77c3ae20989/go.mod h1:FGwQgZAt2Gh5mjlwJUlVB62JeYdo+if0xWxSEfBD9ig= github.com/filecoin-project/go-statemachine v0.0.0-20200813232949-df9b130df370 h1:Jbburj7Ih2iaJ/o5Q9A+EAeTabME6YII7FLi9SKUf5c= github.com/filecoin-project/go-statemachine v0.0.0-20200813232949-df9b130df370/go.mod h1:FGwQgZAt2Gh5mjlwJUlVB62JeYdo+if0xWxSEfBD9ig= @@ -248,6 +252,8 @@ github.com/filecoin-project/go-storedcounter v0.0.0-20200421200003-1c99c62e8a5b/ github.com/filecoin-project/specs-actors v0.9.4/go.mod h1:BStZQzx5x7TmCkLv0Bpa07U6cPKol6fd3w9KjMPZ6Z4= github.com/filecoin-project/specs-actors v0.9.7 h1:7PAZ8kdqwBdmgf/23FCkQZLCXcVu02XJrkpkhBikiA8= github.com/filecoin-project/specs-actors v0.9.7/go.mod h1:wM2z+kwqYgXn5Z7scV1YHLyd1Q1cy0R8HfTIWQ0BFGU= +github.com/filecoin-project/specs-actors v0.9.9-0.20200911231631-727cd8845d30 h1:6Kn6y3TpJbk5BsvhVha+3jr7C3gAAJq0rCnwUYOWRl0= +github.com/filecoin-project/specs-actors v0.9.9-0.20200911231631-727cd8845d30/go.mod h1:czlvLQGEX0fjLLfdNHD7xLymy6L3n7aQzRWzsYGf+ys= github.com/filecoin-project/specs-storage v0.1.1-0.20200907031224-ed2e5cd13796 h1:dJsTPWpG2pcTeojO2pyn0c6l+x/3MZYCBgo/9d11JEk= github.com/filecoin-project/specs-storage v0.1.1-0.20200907031224-ed2e5cd13796/go.mod h1:nJRRM7Aa9XVvygr3W9k6xGF46RWzr2zxF/iGoAIfA/g= github.com/filecoin-project/test-vectors/schema v0.0.1 h1:5fNF76nl4qolEvcIsjc0kUADlTMVHO73tW4kXXPnsus= diff --git a/node/impl/full/state.go b/node/impl/full/state.go index c068bab93..e9e290fd2 100644 --- a/node/impl/full/state.go +++ b/node/impl/full/state.go @@ -20,7 +20,6 @@ import ( "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin/market" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" samsig "github.com/filecoin-project/specs-actors/actors/builtin/multisig" "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/builtin/reward" @@ -33,6 +32,7 @@ import ( "github.com/filecoin-project/lotus/chain/gen" "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/stmgr" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/store" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/vm" @@ -112,6 +112,8 @@ func (a *StateAPI) StateMinerInfo(ctx context.Context, actor address.Address, ts return api.MinerInfo{}, xerrors.Errorf("loading tipset %s: %w", tsk, err) } + a.StateManager.LoadActorStateRaw(ctx context.Context, addr address.Address, out interface{}, st cid.Cid) + mi, err := stmgr.StateMinerInfo(ctx, a.StateManager, ts, actor) if err != nil { return api.MinerInfo{}, err @@ -119,17 +121,28 @@ func (a *StateAPI) StateMinerInfo(ctx context.Context, actor address.Address, ts return api.NewApiMinerInfo(mi), nil } -func (a *StateAPI) StateMinerDeadlines(ctx context.Context, m address.Address, tsk types.TipSetKey) ([]*miner.Deadline, error) { +func (a *StateAPI) StateMinerDeadlines(ctx context.Context, m address.Address, tsk types.TipSetKey) ([]miner.Deadline, error) { var out []*miner.Deadline - return out, a.StateManager.WithParentStateTsk(tsk, - a.StateManager.WithActor(m, - a.StateManager.WithActorState(ctx, - a.StateManager.WithDeadlines( - a.StateManager.WithEachDeadline( - func(store adt.Store, idx uint64, deadline *miner.Deadline) error { - out = append(out, deadline) - return nil - }))))) + state, err := a.StateManager.LoadParentStateTsk(tsk) + if err != nil { + return nil, err + } + act, err := state.GetActor(addr) + if err != nil { + return nil, err + } + mas, err := miner.Load(a.Chain.Store(ctx), act) + if err != nil { + return nil, err + } + var deadlines []miner.Deadline + if err := mas.ForEachDeadline(func(_ uint64, dl miner.Deadline) error { + deadlines = append(deadlines, dl) + return nil + }); err != nil { + return err + } + return deadlines, nil } func (a *StateAPI) StateMinerPartitions(ctx context.Context, m address.Address, dlIdx uint64, tsk types.TipSetKey) ([]*miner.Partition, error) { @@ -302,7 +315,7 @@ func (a *StateAPI) stateForTs(ctx context.Context, ts *types.TipSet) (*state.Sta buf := bufbstore.NewBufferedBstore(a.Chain.Blockstore()) cst := cbor.NewCborStore(buf) - return state.LoadStateTree(cst, st) + return state.LoadStateTree(cst, st, a.StateManager.GetNtwkVersion(ctx, ts.Height())) } func (a *StateAPI) StateGetActor(ctx context.Context, actor address.Address, tsk types.TipSetKey) (*types.Actor, error) { @@ -1169,16 +1182,9 @@ func (a *StateAPI) StateCirculatingSupply(ctx context.Context, tsk types.TipSetK return api.CirculatingSupply{}, xerrors.Errorf("loading tipset %s: %w", tsk, err) } - st, _, err := a.StateManager.TipSetState(ctx, ts) + sTree, err := a.stateForTs(ctx, ts) if err != nil { return api.CirculatingSupply{}, err } - - cst := cbor.NewCborStore(a.Chain.Blockstore()) - sTree, err := state.LoadStateTree(cst, st) - if err != nil { - return api.CirculatingSupply{}, err - } - return a.StateManager.GetCirculatingSupplyDetailed(ctx, ts.Height(), sTree) } diff --git a/storage/adapter_storage_miner.go b/storage/adapter_storage_miner.go index 2869e48e5..706cd6e04 100644 --- a/storage/adapter_storage_miner.go +++ b/storage/adapter_storage_miner.go @@ -16,13 +16,13 @@ import ( "github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin/market" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/api/apibstore" "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/actors" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/store" "github.com/filecoin-project/lotus/chain/types" sealing "github.com/filecoin-project/lotus/extern/storage-sealing" @@ -179,14 +179,11 @@ func (s SealingAPIAdapter) StateSectorPreCommitInfo(ctx context.Context, maddr a return nil, xerrors.Errorf("handleSealFailed(%d): temp error: %+v", sectorNumber, err) } - st, err := s.delegate.ChainReadObj(ctx, act.Head) - if err != nil { - return nil, xerrors.Errorf("handleSealFailed(%d): temp error: %+v", sectorNumber, err) - } + stor := store.ActorStore(ctx, apibstore.NewAPIBlockstore(s.delegate)) - var state miner.State - if err := state.UnmarshalCBOR(bytes.NewReader(st)); err != nil { - return nil, xerrors.Errorf("handleSealFailed(%d): temp error: unmarshaling miner state: %+v", sectorNumber, err) + state, err := miner.Load(stor, act) + if err != nil { + return nil, xerrors.Errorf("handleSealFailed(%d): temp error: loading miner state: %+v", sectorNumber, err) } stor := store.ActorStore(ctx, apibstore.NewAPIBlockstore(s.delegate)) precommits, err := adt.AsMap(stor, state.PreCommittedSectors) diff --git a/storage/wdpost_run.go b/storage/wdpost_run.go index 51d71e331..0f215048a 100644 --- a/storage/wdpost_run.go +++ b/storage/wdpost_run.go @@ -6,28 +6,32 @@ import ( "errors" "time" - "github.com/filecoin-project/specs-actors/actors/runtime/proof" - "github.com/filecoin-project/go-bitfield" "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/crypto" + "github.com/filecoin-project/go-state-types/dline" "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" "go.opencensus.io/trace" "golang.org/x/xerrors" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + v0proof "github.com/filecoin-project/specs-actors/actors/runtime/proof" + "github.com/filecoin-project/lotus/api" + "github.com/filecoin-project/lotus/api/apibstore" "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/actors" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + "github.com/filecoin-project/lotus/chain/store" "github.com/filecoin-project/lotus/chain/types" ) var errNoPartitions = errors.New("no partitions") -func (s *WindowPoStScheduler) failPost(deadline *miner.DeadlineInfo) { +func (s *WindowPoStScheduler) failPost(deadline *dline.Info) { log.Errorf("TODO") /*s.failLk.Lock() if eps > s.failed { @@ -36,7 +40,7 @@ func (s *WindowPoStScheduler) failPost(deadline *miner.DeadlineInfo) { s.failLk.Unlock()*/ } -func (s *WindowPoStScheduler) doPost(ctx context.Context, deadline *miner.DeadlineInfo, ts *types.TipSet) { +func (s *WindowPoStScheduler) doPost(ctx context.Context, deadline *dline.Info, ts *types.TipSet) { ctx, abort := context.WithCancel(ctx) s.abort = abort @@ -111,18 +115,26 @@ func (s *WindowPoStScheduler) checkSectors(ctx context.Context, check bitfield.B return sbf, nil } -func (s *WindowPoStScheduler) checkNextRecoveries(ctx context.Context, dlIdx uint64, partitions []*miner.Partition) error { +func (s *WindowPoStScheduler) checkNextRecoveries(ctx context.Context, dlIdx uint64, partitions []miner.Partition) error { ctx, span := trace.StartSpan(ctx, "storage.checkNextRecoveries") defer span.End() - params := &miner.DeclareFaultsRecoveredParams{ - Recoveries: []miner.RecoveryDeclaration{}, + params := &v0miner.DeclareFaultsRecoveredParams{ + Recoveries: []v0miner.RecoveryDeclaration{}, } faulty := uint64(0) for partIdx, partition := range partitions { - unrecovered, err := bitfield.SubtractBitField(partition.Faults, partition.Recoveries) + faults, err := partition.FaultySectors() + if err != nil { + return xerrors.Errorf("getting faults: %w", err) + } + recovering, err := partition.RecoveringSectors() + if err != nil { + return xerrors.Errorf("getting recovering: %w", err) + } + unrecovered, err := bitfield.SubtractBitField(faults, recovering) if err != nil { return xerrors.Errorf("subtracting recovered set from fault set: %w", err) } @@ -153,7 +165,7 @@ func (s *WindowPoStScheduler) checkNextRecoveries(ctx context.Context, dlIdx uin continue } - params.Recoveries = append(params.Recoveries, miner.RecoveryDeclaration{ + params.Recoveries = append(params.Recoveries, v0miner.RecoveryDeclaration{ Deadline: dlIdx, Partition: uint64(partIdx), Sectors: recovered, @@ -202,17 +214,17 @@ func (s *WindowPoStScheduler) checkNextRecoveries(ctx context.Context, dlIdx uin return nil } -func (s *WindowPoStScheduler) checkNextFaults(ctx context.Context, dlIdx uint64, partitions []*miner.Partition) error { +func (s *WindowPoStScheduler) checkNextFaults(ctx context.Context, dlIdx uint64, partitions []miner.Partition) error { ctx, span := trace.StartSpan(ctx, "storage.checkNextFaults") defer span.End() - params := &miner.DeclareFaultsParams{ - Faults: []miner.FaultDeclaration{}, + params := &v0miner.DeclareFaultsParams{ + Faults: []v0miner.FaultDeclaration{}, } bad := uint64(0) - for partIdx, partition := range partitions { + for _, partition := range partitions { toCheck, err := partition.ActiveSectors() if err != nil { return xerrors.Errorf("getting active sectors: %w", err) @@ -239,7 +251,7 @@ func (s *WindowPoStScheduler) checkNextFaults(ctx context.Context, dlIdx uint64, bad += c - params.Faults = append(params.Faults, miner.FaultDeclaration{ + params.Faults = append(params.Faults, v0miner.FaultDeclaration{ Deadline: dlIdx, Partition: uint64(partIdx), Sectors: faulty, @@ -286,20 +298,40 @@ func (s *WindowPoStScheduler) checkNextFaults(ctx context.Context, dlIdx uint64, return nil } -func (s *WindowPoStScheduler) runPost(ctx context.Context, di miner.DeadlineInfo, ts *types.TipSet) (*miner.SubmitWindowedPoStParams, error) { +func (s *WindowPoStScheduler) runPost(ctx context.Context, di dline.Info, ts *types.TipSet) (*v0miner.SubmitWindowedPoStParams, error) { ctx, span := trace.StartSpan(ctx, "storage.runPost") defer span.End() + stor := store.ActorStore(ctx, apibstore.NewAPIBlockstore(s.api)) + act, err := s.api.StateGetActor(context.TODO(), s.actor, ts.Key()) + if err != nil { + return nil, xerrors.Errorf("resolving actor: %w", err) + } + + mas, err := miner.Load(stor, act) + if err != nil { + return nil, xerrors.Errorf("getting miner state: %w", err) + } + go func() { // TODO: extract from runPost, run on fault cutoff boundaries // check faults / recoveries for the *next* deadline. It's already too // late to declare them for this deadline - declDeadline := (di.Index + 2) % miner.WPoStPeriodDeadlines + declDeadline := (di.Index + 2) % di.WPoStPeriodDeadlines - partitions, err := s.api.StateMinerPartitions(context.TODO(), s.actor, declDeadline, ts.Key()) + dl, err := mas.LoadDeadline(declDeadline) if err != nil { - log.Errorf("getting partitions: %v", err) + log.Errorf("loading deadline: %v", err) + return + } + var partitions []miner.Partition + err = dl.ForEachPartition(func(_ uint64, part miner.Partition) error { + partitions = append(partitions, part) + return nil + }) + if err != nil { + log.Errorf("loading partitions: %v", err) return } @@ -324,18 +356,27 @@ func (s *WindowPoStScheduler) runPost(ctx context.Context, di miner.DeadlineInfo return nil, xerrors.Errorf("failed to get chain randomness for windowPost (ts=%d; deadline=%d): %w", ts.Height(), di, err) } - partitions, err := s.api.StateMinerPartitions(ctx, s.actor, di.Index, ts.Key()) + dl, err := mas.LoadDeadline(di.Index) if err != nil { - return nil, xerrors.Errorf("getting partitions: %w", err) + return nil, xerrors.Errorf("loading deadline: %w", err) } - params := &miner.SubmitWindowedPoStParams{ + var partitions []miner.Partitions + err = dl.ForEachPartition(func(_ uint64, part miner.Partition) error { + partitions = apppend(partitions, part) + return nil + }) + if err != nil { + return nil, xerrors.Errorf("loading partitions: %w", err) + } + + params := &v0miner.SubmitWindowedPoStParams{ Deadline: di.Index, - Partitions: make([]miner.PoStPartition, 0, len(partitions)), + Partitions: make([]v0miner.PoStPartition, 0, len(partitions)), Proofs: nil, } - var sinfos []proof.SectorInfo + var sinfos []v0proof.SectorInfo sidToPart := map[abi.SectorNumber]uint64{} skipCount := uint64(0) @@ -382,7 +423,7 @@ func (s *WindowPoStScheduler) runPost(ctx context.Context, di miner.DeadlineInfo sidToPart[si.SectorNumber] = uint64(partIdx) } - params.Partitions = append(params.Partitions, miner.PoStPartition{ + params.Partitions = append(params.Partitions, v0miner.PoStPartition{ Index: uint64(partIdx), Skipped: skipped, }) @@ -436,7 +477,7 @@ func (s *WindowPoStScheduler) runPost(ctx context.Context, di miner.DeadlineInfo return params, nil } -func (s *WindowPoStScheduler) sectorsForProof(ctx context.Context, goodSectors, allSectors bitfield.BitField, ts *types.TipSet) ([]proof.SectorInfo, error) { +func (s *WindowPoStScheduler) sectorsForProof(ctx context.Context, goodSectors, allSectors bitfield.BitField, ts *types.TipSet) ([]v0proof.SectorInfo, error) { sset, err := s.api.StateMinerSectors(ctx, s.actor, &goodSectors, false, ts.Key()) if err != nil { return nil, err @@ -446,22 +487,22 @@ func (s *WindowPoStScheduler) sectorsForProof(ctx context.Context, goodSectors, return nil, nil } - substitute := proof.SectorInfo{ + substitute := v0proof.SectorInfo{ SectorNumber: sset[0].ID, SealedCID: sset[0].Info.SealedCID, SealProof: sset[0].Info.SealProof, } - sectorByID := make(map[uint64]proof.SectorInfo, len(sset)) + sectorByID := make(map[uint64]v0proof.SectorInfo, len(sset)) for _, sector := range sset { - sectorByID[uint64(sector.ID)] = proof.SectorInfo{ + sectorByID[uint64(sector.ID)] = v0proof.SectorInfo{ SectorNumber: sector.ID, SealedCID: sector.Info.SealedCID, SealProof: sector.Info.SealProof, } } - proofSectors := make([]proof.SectorInfo, 0, len(sset)) + proofSectors := make([]v0proof.SectorInfo, 0, len(sset)) if err := allSectors.ForEach(func(sectorNo uint64) error { if info, found := sectorByID[sectorNo]; found { proofSectors = append(proofSectors, info) @@ -476,7 +517,7 @@ func (s *WindowPoStScheduler) sectorsForProof(ctx context.Context, goodSectors, return proofSectors, nil } -func (s *WindowPoStScheduler) submitPost(ctx context.Context, proof *miner.SubmitWindowedPoStParams) error { +func (s *WindowPoStScheduler) submitPost(ctx context.Context, proof *v0miner.SubmitWindowedPoStParams) error { ctx, span := trace.StartSpan(ctx, "storage.commitPost") defer span.End() diff --git a/storage/wdpost_sched.go b/storage/wdpost_sched.go index b238a490d..7f7c64926 100644 --- a/storage/wdpost_sched.go +++ b/storage/wdpost_sched.go @@ -8,7 +8,7 @@ import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" + "github.com/filecoin-project/go-state-types/dline" "github.com/filecoin-project/specs-storage/storage" "github.com/filecoin-project/lotus/api" @@ -37,7 +37,7 @@ type WindowPoStScheduler struct { cur *types.TipSet // if a post is in progress, this indicates for which ElectionPeriodStart - activeDeadline *miner.DeadlineInfo + activeDeadline *dline.Info abort context.CancelFunc //failed abi.ChainEpoch // eps @@ -68,7 +68,7 @@ func NewWindowedPoStScheduler(api storageMinerApi, fc config.MinerFeeConfig, sb }, nil } -func deadlineEquals(a, b *miner.DeadlineInfo) bool { +func deadlineEquals(a, b *dline.Info) bool { if a == nil || b == nil { return b == a } From 38f87981c1c5c2a60d65acb22df75a4058b41334 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Mon, 14 Sep 2020 13:14:06 +0200 Subject: [PATCH 014/303] Fix some build errors --- api/api_full.go | 6 +++--- api/apistruct/struct.go | 20 ++++++------------- api/types.go | 5 +---- build/version.go | 2 +- chain/actors/adt/adt.go | 4 ++-- chain/actors/builtin/builtin.go | 2 +- chain/actors/builtin/init/init.go | 8 ++++---- chain/actors/builtin/init/v0.go | 4 ++-- chain/actors/builtin/market/market.go | 9 +++++++-- chain/actors/builtin/market/v0.go | 4 +++- chain/actors/builtin/miner/miner.go | 7 +++++-- chain/actors/builtin/miner/v0.go | 6 +++++- chain/actors/builtin/power/power.go | 7 +++++-- chain/state/statetree.go | 28 +++++++++++++++------------ go.sum | 7 ------- 15 files changed, 61 insertions(+), 58 deletions(-) diff --git a/api/api_full.go b/api/api_full.go index e5147db47..8c7340971 100644 --- a/api/api_full.go +++ b/api/api_full.go @@ -5,8 +5,6 @@ import ( "fmt" "time" - "github.com/filecoin-project/specs-actors/actors/runtime/proof" - "github.com/ipfs/go-cid" "github.com/libp2p/go-libp2p-core/peer" @@ -24,7 +22,9 @@ import ( "github.com/filecoin-project/specs-actors/actors/builtin/paych" "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + "github.com/filecoin-project/specs-actors/actors/runtime/proof" + miner2 "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/types" marketevents "github.com/filecoin-project/lotus/markets/loggers" "github.com/filecoin-project/lotus/node/modules/dtypes" @@ -317,7 +317,7 @@ type FullNode interface { // StateMinerPower returns the power of the indicated miner StateMinerPower(context.Context, address.Address, types.TipSetKey) (*MinerPower, error) // StateMinerInfo returns info about the indicated miner - StateMinerInfo(context.Context, address.Address, types.TipSetKey) (MinerInfo, error) + StateMinerInfo(context.Context, address.Address, types.TipSetKey) (miner2.MinerInfo, error) // StateMinerFaults returns a bitfield indicating the faulty sectors of the given miner StateMinerFaults(context.Context, address.Address, types.TipSetKey) (bitfield.BitField, error) // StateAllMinerFaults returns all non-expired Faults that occur within lookback epochs of the given tipset diff --git a/api/apistruct/struct.go b/api/apistruct/struct.go index 3cf9a0add..45c3f7d63 100644 --- a/api/apistruct/struct.go +++ b/api/apistruct/struct.go @@ -2,6 +2,8 @@ package apistruct import ( "context" + "github.com/filecoin-project/go-state-types/dline" + miner2 "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "io" "time" @@ -160,11 +162,9 @@ type FullNodeStruct struct { StateNetworkName func(context.Context) (dtypes.NetworkName, error) `perm:"read"` StateMinerSectors func(context.Context, address.Address, *bitfield.BitField, bool, types.TipSetKey) ([]*api.ChainSectorInfo, error) `perm:"read"` StateMinerActiveSectors func(context.Context, address.Address, types.TipSetKey) ([]*api.ChainSectorInfo, error) `perm:"read"` - StateMinerProvingDeadline func(context.Context, address.Address, types.TipSetKey) (*miner.DeadlineInfo, error) `perm:"read"` + StateMinerProvingDeadline func(context.Context, address.Address, types.TipSetKey) (*dline.Info, error) `perm:"read"` StateMinerPower func(context.Context, address.Address, types.TipSetKey) (*api.MinerPower, error) `perm:"read"` - StateMinerInfo func(context.Context, address.Address, types.TipSetKey) (api.MinerInfo, error) `perm:"read"` - StateMinerDeadlines func(context.Context, address.Address, types.TipSetKey) ([]*miner.Deadline, error) `perm:"read"` - StateMinerPartitions func(context.Context, address.Address, uint64, types.TipSetKey) ([]*miner.Partition, error) `perm:"read"` + StateMinerInfo func(context.Context, address.Address, types.TipSetKey) (miner2.MinerInfo, error) `perm:"read"` StateMinerFaults func(context.Context, address.Address, types.TipSetKey) (bitfield.BitField, error) `perm:"read"` StateAllMinerFaults func(context.Context, abi.ChainEpoch, types.TipSetKey) ([]*api.Fault, error) `perm:"read"` StateMinerRecoveries func(context.Context, address.Address, types.TipSetKey) (bitfield.BitField, error) `perm:"read"` @@ -724,7 +724,7 @@ func (c *FullNodeStruct) StateMinerActiveSectors(ctx context.Context, addr addre return c.Internal.StateMinerActiveSectors(ctx, addr, tsk) } -func (c *FullNodeStruct) StateMinerProvingDeadline(ctx context.Context, addr address.Address, tsk types.TipSetKey) (*miner.DeadlineInfo, error) { +func (c *FullNodeStruct) StateMinerProvingDeadline(ctx context.Context, addr address.Address, tsk types.TipSetKey) (*dline.Info, error) { return c.Internal.StateMinerProvingDeadline(ctx, addr, tsk) } @@ -732,18 +732,10 @@ func (c *FullNodeStruct) StateMinerPower(ctx context.Context, a address.Address, return c.Internal.StateMinerPower(ctx, a, tsk) } -func (c *FullNodeStruct) StateMinerInfo(ctx context.Context, actor address.Address, tsk types.TipSetKey) (api.MinerInfo, error) { +func (c *FullNodeStruct) StateMinerInfo(ctx context.Context, actor address.Address, tsk types.TipSetKey) (miner2.MinerInfo, error) { return c.Internal.StateMinerInfo(ctx, actor, tsk) } -func (c *FullNodeStruct) StateMinerDeadlines(ctx context.Context, m address.Address, tsk types.TipSetKey) ([]*miner.Deadline, error) { - return c.Internal.StateMinerDeadlines(ctx, m, tsk) -} - -func (c *FullNodeStruct) StateMinerPartitions(ctx context.Context, m address.Address, dlIdx uint64, tsk types.TipSetKey) ([]*miner.Partition, error) { - return c.Internal.StateMinerPartitions(ctx, m, dlIdx, tsk) -} - func (c *FullNodeStruct) StateMinerFaults(ctx context.Context, actor address.Address, tsk types.TipSetKey) (bitfield.BitField, error) { return c.Internal.StateMinerFaults(ctx, actor, tsk) } diff --git a/api/types.go b/api/types.go index 4133a7105..53c0fe203 100644 --- a/api/types.go +++ b/api/types.go @@ -4,14 +4,11 @@ import ( "encoding/json" "fmt" - "github.com/filecoin-project/go-address" datatransfer "github.com/filecoin-project/go-data-transfer" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/lotus/build" "github.com/ipfs/go-cid" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/libp2p/go-libp2p-core/peer" pubsub "github.com/libp2p/go-libp2p-pubsub" ma "github.com/multiformats/go-multiaddr" @@ -111,4 +108,4 @@ func NewDataTransferChannel(hostID peer.ID, channelState datatransfer.ChannelSta return channel } -type +// type TODO (stebalien): this was here, why was this here? diff --git a/build/version.go b/build/version.go index 338be1263..1e55b9889 100644 --- a/build/version.go +++ b/build/version.go @@ -53,7 +53,7 @@ func (ve Version) EqMajorMinor(v2 Version) bool { } // APIVersion is a semver version of the rpc api exposed -var APIVersion Version = newVer(0, 14, 0) +var APIVersion Version = newVer(0, 15, 0) //nolint:varcheck,deadcode const ( diff --git a/chain/actors/adt/adt.go b/chain/actors/adt/adt.go index 144150659..179c73b33 100644 --- a/chain/actors/adt/adt.go +++ b/chain/actors/adt/adt.go @@ -32,7 +32,7 @@ func AsMap(store Store, root cid.Cid, version network.Version) (Map, error) { func NewMap(store Store, version network.Version) (Map, error) { switch builtin.VersionForNetwork(version) { case builtin.Version0: - return v0adt.MakeEmptyMap(store) + return v0adt.MakeEmptyMap(store), nil } return nil, xerrors.Errorf("unknown network version: %d", version) } @@ -45,7 +45,7 @@ type Array interface { Delete(idx uint64) error Length() uint64 - ForEach(v cbor.Unmarshaler, fn func(idx int) error) error + ForEach(v cbor.Unmarshaler, fn func(idx int64) error) error } func AsArray(store Store, root cid.Cid, version network.Version) (Array, error) { diff --git a/chain/actors/builtin/builtin.go b/chain/actors/builtin/builtin.go index 173f50ba6..accc4e7e6 100644 --- a/chain/actors/builtin/builtin.go +++ b/chain/actors/builtin/builtin.go @@ -16,7 +16,7 @@ const ( func VersionForNetwork(version network.Version) Version { switch version { case network.Version0, network.Version1: - return Version + return Version0 default: panic(fmt.Sprintf("unsupported network version %d", version)) } diff --git a/chain/actors/builtin/init/init.go b/chain/actors/builtin/init/init.go index de71a032c..a96c0dfd6 100644 --- a/chain/actors/builtin/init/init.go +++ b/chain/actors/builtin/init/init.go @@ -1,10 +1,10 @@ package init import ( - "github.com/filecoin-project/go-bitfield" - "github.com/filecoin-project/go-state-types/cbor" "golang.org/x/xerrors" + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/cbor" v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/lotus/chain/actors/adt" @@ -27,6 +27,6 @@ func Load(store adt.Store, act *types.Actor) (State, error) { type State interface { cbor.Marshaler - ResolveAddress(address addr.Address) (address.Address, bool, error) - MapAddressToNewID(address addr.Address) (address.Address, error) + ResolveAddress(address address.Address) (address.Address, bool, error) + MapAddressToNewID(address address.Address) (address.Address, error) } diff --git a/chain/actors/builtin/init/v0.go b/chain/actors/builtin/init/v0.go index 3a94f59f0..5001e9806 100644 --- a/chain/actors/builtin/init/v0.go +++ b/chain/actors/builtin/init/v0.go @@ -3,13 +3,13 @@ package init import ( "github.com/filecoin-project/go-address" - "github.com/filecoin-project/specs-actors/actors/builtin/init" + init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" "github.com/filecoin-project/lotus/chain/actors/adt" ) type v0State struct { - init.State + init_.State store adt.Store } diff --git a/chain/actors/builtin/market/market.go b/chain/actors/builtin/market/market.go index 663fa0e83..3d12ac9a8 100644 --- a/chain/actors/builtin/market/market.go +++ b/chain/actors/builtin/market/market.go @@ -1,15 +1,20 @@ package market import ( + "golang.org/x/xerrors" + "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/cbor" - "github.com/ipfs/go-cid" + v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" + + "github.com/filecoin-project/lotus/chain/actors/adt" + "github.com/filecoin-project/lotus/chain/types" ) func Load(store adt.Store, act *types.Actor) (st State, err error) { switch act.Code { - case v0builtin.MarketActorCodeID: + case v0builtin.StorageMarketActorCodeID: out := v0State{store: store} err := store.Get(store.Context(), act.Head, &out) if err != nil { diff --git a/chain/actors/builtin/market/v0.go b/chain/actors/builtin/market/v0.go index 23f33e3d3..da86cda0f 100644 --- a/chain/actors/builtin/market/v0.go +++ b/chain/actors/builtin/market/v0.go @@ -1,6 +1,8 @@ package market import ( + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/specs-actors/actors/builtin/market" "github.com/filecoin-project/specs-actors/actors/util/adt" ) @@ -20,6 +22,6 @@ func (s *v0State) EscrowTable() (BalanceTable, error) { return adt.AsBalanceTable(s.store, s.State.EscrowTable) } -func (s *v0State) Lockedtable() (BalanceTable, error) { +func (s *v0State) LockedTable() (BalanceTable, error) { return adt.AsBalanceTable(s.store, s.State.LockedTable) } diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index 50453827d..11dc3158a 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -1,10 +1,13 @@ package miner import ( - "github.com/filecoin-project/go-bitfield" - "github.com/filecoin-project/go-state-types/abi" + "github.com/libp2p/go-libp2p-core/peer" "golang.org/x/xerrors" + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-bitfield" + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/cbor" v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/lotus/chain/actors/adt" diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index 8898a26a5..1d8a68183 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -1,6 +1,7 @@ package miner import ( + "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-bitfield" "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/libp2p/go-libp2p-core/peer" @@ -51,6 +52,9 @@ func (s *v0State) NumDeadlines() (uint64, error) { func (s *v0State) Info() (MinerInfo, error) { info, err := s.State.GetInfo(s.store) + if err != nil { + return MinerInfo{}, err + } var pid *peer.ID if peerID, err := peer.IDFromBytes(info.PeerId); err == nil { @@ -77,7 +81,7 @@ func (s *v0State) Info() (MinerInfo, error) { mi.WorkerChangeEpoch = info.PendingWorkerKey.EffectiveAt } - return mi + return mi, nil } func (d *v0Deadline) LoadPartition(idx uint64) (Partition, error) { diff --git a/chain/actors/builtin/power/power.go b/chain/actors/builtin/power/power.go index 7671877e3..b7bb9329e 100644 --- a/chain/actors/builtin/power/power.go +++ b/chain/actors/builtin/power/power.go @@ -1,16 +1,19 @@ package power import ( + "golang.org/x/xerrors" + "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/cbor" + v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" + "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/types" - "golang.org/x/xerrors" ) func Load(store adt.Store, act *types.Actor) (st State, err error) { switch act.Code { - case v0builtin.PowerActorCodeID: + case v0builtin.StoragePowerActorCodeID: out := v0State{store: store} err := store.Get(store.Context(), act.Head, &out) if err != nil { diff --git a/chain/state/statetree.go b/chain/state/statetree.go index 684e6ce5d..7aa7701fd 100644 --- a/chain/state/statetree.go +++ b/chain/state/statetree.go @@ -4,12 +4,6 @@ import ( "context" "fmt" - "github.com/filecoin-project/go-state-types/network" - "github.com/filecoin-project/lotus/chain/actors/builtin/init" - init_ "github.com/filecoin-project/lotus/chain/actors/builtin/init" - "github.com/filecoin-project/specs-actors/actors/builtin" - - "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/ipfs/go-cid" cbor "github.com/ipfs/go-ipld-cbor" logging "github.com/ipfs/go-log/v2" @@ -17,6 +11,12 @@ import ( "golang.org/x/xerrors" "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/network" + init_ "github.com/filecoin-project/lotus/chain/actors/builtin/init" + "github.com/filecoin-project/specs-actors/actors/builtin" + + "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/types" ) @@ -118,9 +118,13 @@ func (ss *stateSnaps) deleteActor(addr address.Address) { } func NewStateTree(cst cbor.IpldStore, version network.Version) (*StateTree, error) { + root, err := adt.NewMap(adt.WrapStore(context.TODO(), cst), version) + if err != nil { + return nil, err + } return &StateTree{ - root: adt.NewMap(adt.WrapStore(context.TODO(), cst), version), + root: root, Store: cst, snaps: newStateSnaps(), }, nil @@ -168,7 +172,7 @@ func (st *StateTree) LookupID(addr address.Address) (address.Address, error) { return address.Undef, xerrors.Errorf("getting init actor: %w", err) } - ias, err := init.Load(&AdtStore{st.Store}, &act) + ias, err := init_.Load(&AdtStore{st.Store}, act) if err != nil { return address.Undef, xerrors.Errorf("loading init actor state: %w", err) } @@ -212,7 +216,7 @@ func (st *StateTree) GetActor(addr address.Address) (*types.Actor, error) { } var act types.Actor - if found, err := st.root.Get(adt.AddrKey(addr), &act); err != nil { + if found, err := st.root.Get(abi.AddrKey(addr), &act); err != nil { return nil, xerrors.Errorf("hamt find failed: %w", err) } else if !found { return nil, types.ErrActorNotFound @@ -257,11 +261,11 @@ func (st *StateTree) Flush(ctx context.Context) (cid.Cid, error) { for addr, sto := range st.snaps.layers[0].actors { if sto.Delete { - if err := st.root.Delete(adt.AddrKey(addr)); err != nil { + if err := st.root.Delete(abi.AddrKey(addr)); err != nil { return cid.Undef, err } } else { - if err := st.root.Put(adt.AddrKey(addr), &sto.Act); err != nil { + if err := st.root.Put(abi.AddrKey(addr), &sto.Act); err != nil { return cid.Undef, err } } @@ -286,7 +290,7 @@ func (st *StateTree) ClearSnapshot() { func (st *StateTree) RegisterNewAddress(addr address.Address) (address.Address, error) { var out address.Address err := st.MutateActor(builtin.InitActorAddr, func(initact *types.Actor) error { - ias, err := init.Load(&AdtStore{st.Store}, initact) + ias, err := init_.Load(&AdtStore{st.Store}, initact) if err != nil { return err } diff --git a/go.sum b/go.sum index 106814b02..0ae61535a 100644 --- a/go.sum +++ b/go.sum @@ -249,11 +249,6 @@ github.com/filecoin-project/go-statestore v0.1.0 h1:t56reH59843TwXHkMcwyuayStBIi github.com/filecoin-project/go-statestore v0.1.0/go.mod h1:LFc9hD+fRxPqiHiaqUEZOinUJB4WARkRfNl10O7kTnI= github.com/filecoin-project/go-storedcounter v0.0.0-20200421200003-1c99c62e8a5b h1:fkRZSPrYpk42PV3/lIXiL0LHetxde7vyYYvSsttQtfg= github.com/filecoin-project/go-storedcounter v0.0.0-20200421200003-1c99c62e8a5b/go.mod h1:Q0GQOBtKf1oE10eSXSlhN45kDBdGvEcVOqMiffqX+N8= -github.com/filecoin-project/specs-actors v0.9.4/go.mod h1:BStZQzx5x7TmCkLv0Bpa07U6cPKol6fd3w9KjMPZ6Z4= -github.com/filecoin-project/specs-actors v0.9.7 h1:7PAZ8kdqwBdmgf/23FCkQZLCXcVu02XJrkpkhBikiA8= -github.com/filecoin-project/specs-actors v0.9.7/go.mod h1:wM2z+kwqYgXn5Z7scV1YHLyd1Q1cy0R8HfTIWQ0BFGU= -github.com/filecoin-project/specs-actors v0.9.9-0.20200911231631-727cd8845d30 h1:6Kn6y3TpJbk5BsvhVha+3jr7C3gAAJq0rCnwUYOWRl0= -github.com/filecoin-project/specs-actors v0.9.9-0.20200911231631-727cd8845d30/go.mod h1:czlvLQGEX0fjLLfdNHD7xLymy6L3n7aQzRWzsYGf+ys= github.com/filecoin-project/specs-storage v0.1.1-0.20200907031224-ed2e5cd13796 h1:dJsTPWpG2pcTeojO2pyn0c6l+x/3MZYCBgo/9d11JEk= github.com/filecoin-project/specs-storage v0.1.1-0.20200907031224-ed2e5cd13796/go.mod h1:nJRRM7Aa9XVvygr3W9k6xGF46RWzr2zxF/iGoAIfA/g= github.com/filecoin-project/test-vectors/schema v0.0.1 h1:5fNF76nl4qolEvcIsjc0kUADlTMVHO73tW4kXXPnsus= @@ -503,8 +498,6 @@ github.com/ipfs/go-fs-lock v0.0.6/go.mod h1:OTR+Rj9sHiRubJh3dRhD15Juhd/+w6VPOY28 github.com/ipfs/go-graphsync v0.1.0/go.mod h1:jMXfqIEDFukLPZHqDPp8tJMbHO9Rmeb9CEGevngQbmE= github.com/ipfs/go-graphsync v0.1.2 h1:25Ll9kIXCE+DY0dicvfS3KMw+U5sd01b/FJbA7KAbhg= github.com/ipfs/go-graphsync v0.1.2/go.mod h1:sLXVXm1OxtE2XYPw62MuXCdAuNwkAdsbnfrmos5odbA= -github.com/ipfs/go-hamt-ipld v0.1.1 h1:0IQdvwnAAUKmDE+PMJa5y1QiwOPHpI9+eAbQEEEYthk= -github.com/ipfs/go-hamt-ipld v0.1.1/go.mod h1:1EZCr2v0jlCnhpa+aZ0JZYp8Tt2w16+JJOAVz17YcDk= github.com/ipfs/go-ipfs-blockstore v0.0.1/go.mod h1:d3WClOmRQKFnJ0Jz/jj/zmksX0ma1gROTlovZKBmN08= github.com/ipfs/go-ipfs-blockstore v0.1.0/go.mod h1:5aD0AvHPi7mZc6Ci1WCAhiBQu2IsfTduLl+422H6Rqw= github.com/ipfs/go-ipfs-blockstore v0.1.4/go.mod h1:Jxm3XMVjh6R17WvxFEiyKBLUGr86HgIYJW/D/MwqeYQ= From 68097132fe64dd9454aae00ae86bf6f4b2b36f96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Mon, 14 Sep 2020 13:45:20 +0200 Subject: [PATCH 015/303] Fix vm build --- chain/gen/genesis/genesis.go | 7 +- chain/gen/genesis/miners.go | 4 +- chain/stmgr/stmgr.go | 39 +++++----- chain/vm/invoker.go | 8 +-- chain/vm/runtime.go | 135 ++++++++++++++++------------------- chain/vm/vm.go | 28 ++++---- 6 files changed, 99 insertions(+), 122 deletions(-) diff --git a/chain/gen/genesis/genesis.go b/chain/gen/genesis/genesis.go index ac22b5b19..3c4632437 100644 --- a/chain/gen/genesis/genesis.go +++ b/chain/gen/genesis/genesis.go @@ -6,8 +6,6 @@ import ( "encoding/json" "fmt" - "github.com/filecoin-project/specs-actors/actors/runtime" - "github.com/ipfs/go-cid" "github.com/ipfs/go-datastore" cbor "github.com/ipfs/go-ipld-cbor" @@ -19,6 +17,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" + "github.com/filecoin-project/go-state-types/network" "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin/account" "github.com/filecoin-project/specs-actors/actors/builtin/multisig" @@ -406,8 +405,8 @@ func VerifyPreSealedData(ctx context.Context, cs *store.ChainStore, stateroot ci verifNeeds := make(map[address.Address]abi.PaddedPieceSize) var sum abi.PaddedPieceSize - nwv := func(context.Context, abi.ChainEpoch) runtime.NetworkVersion { - return runtime.NetworkVersion1 + nwv := func(context.Context, abi.ChainEpoch) network.Version { + return network.Version1 } vmopt := vm.VMOpts{ diff --git a/chain/gen/genesis/miners.go b/chain/gen/genesis/miners.go index d8441c66c..6d041bb4d 100644 --- a/chain/gen/genesis/miners.go +++ b/chain/gen/genesis/miners.go @@ -61,8 +61,8 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid return big.Zero(), nil } - nwv := func(context.Context, abi.ChainEpoch) runtime.NetworkVersion { - return runtime.NetworkVersion1 + nwv := func(context.Context, abi.ChainEpoch) network.Version { + return network.Version1 } vmopt := &vm.VMOpts{ diff --git a/chain/stmgr/stmgr.go b/chain/stmgr/stmgr.go index fa4b08147..f5b043dc5 100644 --- a/chain/stmgr/stmgr.go +++ b/chain/stmgr/stmgr.go @@ -5,11 +5,22 @@ import ( "fmt" "sync" - "github.com/filecoin-project/specs-actors/actors/runtime" - - "github.com/filecoin-project/specs-actors/actors/builtin/multisig" + "github.com/ipfs/go-cid" + cbor "github.com/ipfs/go-ipld-cbor" + logging "github.com/ipfs/go-log/v2" + cbg "github.com/whyrusleeping/cbor-gen" + "go.opencensus.io/trace" + "golang.org/x/xerrors" "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/specs-actors/actors/builtin" + "github.com/filecoin-project/specs-actors/actors/builtin/multisig" + "github.com/filecoin-project/specs-actors/actors/builtin/reward" + "github.com/filecoin-project/specs-actors/actors/util/adt" + "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/actors" @@ -19,20 +30,6 @@ import ( "github.com/filecoin-project/lotus/chain/store" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/vm" - - "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/go-state-types/big" - "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/reward" - "github.com/filecoin-project/specs-actors/actors/util/adt" - - "golang.org/x/xerrors" - - "github.com/ipfs/go-cid" - cbor "github.com/ipfs/go-ipld-cbor" - logging "github.com/ipfs/go-log/v2" - cbg "github.com/whyrusleeping/cbor-gen" - "go.opencensus.io/trace" ) var log = logging.Logger("statemgr") @@ -1126,14 +1123,14 @@ func (sm *StateManager) GetCirculatingSupply(ctx context.Context, height abi.Cha return csi.FilCirculating, nil } -func (sm *StateManager) GetNtwkVersion(ctx context.Context, height abi.ChainEpoch) runtime.NetworkVersion { +func (sm *StateManager) GetNtwkVersion(ctx context.Context, height abi.ChainEpoch) network.Version { if build.UpgradeBreezeHeight == 0 { - return runtime.NetworkVersion1 + return network.Version1 } if height <= build.UpgradeBreezeHeight { - return runtime.NetworkVersion0 + return network.Version0 } - return runtime.NetworkVersion1 + return network.Version1 } diff --git a/chain/vm/invoker.go b/chain/vm/invoker.go index 8583b0438..9f5f8e2d9 100644 --- a/chain/vm/invoker.go +++ b/chain/vm/invoker.go @@ -15,6 +15,7 @@ import ( "golang.org/x/xerrors" "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/lotus/chain/actors/aerrors" "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin/cron" init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" @@ -27,9 +28,6 @@ import ( "github.com/filecoin-project/specs-actors/actors/builtin/system" "github.com/filecoin-project/specs-actors/actors/runtime" vmr "github.com/filecoin-project/specs-actors/actors/runtime" - "github.com/filecoin-project/specs-actors/actors/util/adt" - - "github.com/filecoin-project/lotus/chain/actors/aerrors" ) type Invoker struct { @@ -48,7 +46,7 @@ func NewInvoker() *Invoker { // add builtInCode using: register(cid, singleton) // NETUPGRADE: register code IDs for v2, etc. - inv.Register(builtin.SystemActorCodeID, system.Actor{}, adt.EmptyValue{}) + inv.Register(builtin.SystemActorCodeID, system.Actor{}, abi.EmptyValue{}) inv.Register(builtin.InitActorCodeID, init_.Actor{}, init_.State{}) inv.Register(builtin.RewardActorCodeID, reward.Actor{}, reward.State{}) inv.Register(builtin.CronActorCodeID, cron.Actor{}, cron.State{}) @@ -67,7 +65,7 @@ func (inv *Invoker) Invoke(codeCid cid.Cid, rt runtime.Runtime, method abi.Metho code, ok := inv.builtInCode[codeCid] if !ok { - log.Errorf("no code for actor %s (Addr: %s)", codeCid, rt.Message().Receiver()) + log.Errorf("no code for actor %s (Addr: %s)", codeCid, rt.Receiver()) return nil, aerrors.Newf(exitcode.SysErrorIllegalActor, "no code for actor %s(%d)(%s)", codeCid, method, hex.EncodeToString(params)) } if method >= abi.MethodNum(len(code)) || code[method] == nil { diff --git a/chain/vm/runtime.go b/chain/vm/runtime.go index 043ea3a45..87d91e230 100644 --- a/chain/vm/runtime.go +++ b/chain/vm/runtime.go @@ -8,21 +8,24 @@ import ( gruntime "runtime" "time" - "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/crypto" - "github.com/filecoin-project/go-state-types/exitcode" - "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/runtime" - vmr "github.com/filecoin-project/specs-actors/actors/runtime" - "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/ipfs/go-cid" cbor "github.com/ipfs/go-ipld-cbor" cbg "github.com/whyrusleeping/cbor-gen" "go.opencensus.io/trace" "golang.org/x/xerrors" + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/big" + statecbor "github.com/filecoin-project/go-state-types/cbor" + "github.com/filecoin-project/go-state-types/crypto" + "github.com/filecoin-project/go-state-types/exitcode" + "github.com/filecoin-project/go-state-types/network" + rtt "github.com/filecoin-project/go-state-types/rt" + "github.com/filecoin-project/specs-actors/actors/builtin" + "github.com/filecoin-project/specs-actors/actors/runtime" + vmr "github.com/filecoin-project/specs-actors/actors/runtime" + "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/actors/aerrors" "github.com/filecoin-project/lotus/chain/state" @@ -34,15 +37,15 @@ type Runtime struct { vm *VM state *state.StateTree - vmsg vmr.Message height abi.ChainEpoch cst cbor.IpldStore pricelist Pricelist + vmr.Message gasAvailable int64 gasUsed int64 - sys runtime.Syscalls + runtime.Syscalls // address that started invoke chain origin address.Address @@ -56,7 +59,7 @@ type Runtime struct { lastGasCharge *types.GasTrace } -func (rt *Runtime) NetworkVersion() vmr.NetworkVersion { +func (rt *Runtime) NetworkVersion() network.Version { return rt.vm.GetNtwkVersion(rt.ctx, rt.CurrEpoch()) } @@ -84,7 +87,7 @@ type notFoundErr interface { IsNotFound() bool } -func (rt *Runtime) Get(c cid.Cid, o vmr.CBORUnmarshaler) bool { +func (rt *Runtime) StoreGet(c cid.Cid, o statecbor.Unmarshaler) bool { if err := rt.cst.Get(context.TODO(), c, o); err != nil { var nfe notFoundErr if xerrors.As(err, &nfe) && nfe.IsNotFound() { @@ -99,7 +102,7 @@ func (rt *Runtime) Get(c cid.Cid, o vmr.CBORUnmarshaler) bool { return true } -func (rt *Runtime) Put(x vmr.CBORMarshaler) cid.Cid { +func (rt *Runtime) StorePut(x statecbor.Marshaler) cid.Cid { c, err := rt.cst.Put(context.TODO(), x) if err != nil { if xerrors.As(err, new(cbor.SerializationError)) { @@ -136,7 +139,7 @@ func (rt *Runtime) shimCall(f func() interface{}) (rval []byte, aerr aerrors.Act switch ret := ret.(type) { case []byte: return ret, nil - case *adt.EmptyValue: + case *abi.EmptyValue: return nil, nil case cbg.CBORMarshaler: buf := new(bytes.Buffer) @@ -151,17 +154,13 @@ func (rt *Runtime) shimCall(f func() interface{}) (rval []byte, aerr aerrors.Act } } -func (rt *Runtime) Message() vmr.Message { - return rt.vmsg -} - func (rt *Runtime) ValidateImmediateCallerAcceptAny() { rt.abortIfAlreadyValidated() return } func (rt *Runtime) CurrentBalance() abi.TokenAmount { - b, err := rt.GetBalance(rt.Message().Receiver()) + b, err := rt.GetBalance(rt.Receiver()) if err != nil { rt.Abortf(err.RetCode(), "get current balance: %v", err) } @@ -257,7 +256,7 @@ func (rt *Runtime) CreateActor(codeID cid.Cid, address address.Address) { // May only be called by the actor itself. func (rt *Runtime) DeleteActor(beneficiary address.Address) { rt.chargeGas(rt.Pricelist().OnDeleteActor()) - act, err := rt.state.GetActor(rt.Message().Receiver()) + act, err := rt.state.GetActor(rt.Receiver()) if err != nil { if xerrors.Is(err, types.ErrActorNotFound) { rt.Abortf(exitcode.SysErrorIllegalActor, "failed to load actor in delete actor: %s", err) @@ -266,36 +265,32 @@ func (rt *Runtime) DeleteActor(beneficiary address.Address) { } if !act.Balance.IsZero() { // Transfer the executing actor's balance to the beneficiary - if err := rt.vm.transfer(rt.Message().Receiver(), beneficiary, act.Balance); err != nil { + if err := rt.vm.transfer(rt.Receiver(), beneficiary, act.Balance); err != nil { panic(aerrors.Fatalf("failed to transfer balance to beneficiary actor: %s", err)) } } // Delete the executing actor - if err := rt.state.DeleteActor(rt.Message().Receiver()); err != nil { + if err := rt.state.DeleteActor(rt.Receiver()); err != nil { panic(aerrors.Fatalf("failed to delete actor: %s", err)) } _ = rt.chargeGasSafe(gasOnActorExec) } -func (rt *Runtime) Syscalls() vmr.Syscalls { - return rt.sys -} - -func (rt *Runtime) StartSpan(name string) vmr.TraceSpan { +func (rt *Runtime) StartSpan(name string) func() { panic("implement me") } func (rt *Runtime) ValidateImmediateCallerIs(as ...address.Address) { rt.abortIfAlreadyValidated() - imm := rt.Message().Caller() + imm := rt.Caller() for _, a := range as { if imm == a { return } } - rt.Abortf(exitcode.SysErrForbidden, "caller %s is not one of %s", rt.Message().Caller(), as) + rt.Abortf(exitcode.SysErrForbidden, "caller %s is not one of %s", rt.Caller(), as) } func (rt *Runtime) Context() context.Context { @@ -313,7 +308,7 @@ func (rt *Runtime) AbortStateMsg(msg string) { func (rt *Runtime) ValidateImmediateCallerType(ts ...cid.Cid) { rt.abortIfAlreadyValidated() - callerCid, ok := rt.GetActorCodeCID(rt.Message().Caller()) + callerCid, ok := rt.GetActorCodeCID(rt.Caller()) if !ok { panic(aerrors.Fatalf("failed to lookup code cid for caller")) } @@ -329,15 +324,7 @@ func (rt *Runtime) CurrEpoch() abi.ChainEpoch { return rt.height } -type dumbWrapperType struct { - val []byte -} - -func (dwt *dumbWrapperType) Into(um vmr.CBORUnmarshaler) error { - return um.UnmarshalCBOR(bytes.NewReader(dwt.val)) -} - -func (rt *Runtime) Send(to address.Address, method abi.MethodNum, m vmr.CBORMarshaler, value abi.TokenAmount) (vmr.SendReturn, exitcode.ExitCode) { +func (rt *Runtime) Send(to address.Address, method abi.MethodNum, m statecbor.Marshaler, value abi.TokenAmount, out statecbor.Er) exitcode.ExitCode { if !rt.allowInternal { rt.Abortf(exitcode.SysErrorIllegalActor, "runtime.Send() is currently disallowed") } @@ -350,16 +337,22 @@ func (rt *Runtime) Send(to address.Address, method abi.MethodNum, m vmr.CBORMars params = buf.Bytes() } - ret, err := rt.internalSend(rt.Message().Receiver(), to, method, value, params) + ret, err := rt.internalSend(rt.Receiver(), to, method, value, params) if err != nil { if err.IsFatal() { panic(err) } log.Warnf("vmctx send failed: to: %s, method: %d: ret: %d, err: %s", to, method, ret, err) - return &dumbWrapperType{nil}, err.RetCode() + return err.RetCode() } _ = rt.chargeGasSafe(gasOnActorExec) - return &dumbWrapperType{ret}, 0 + + if err := out.UnmarshalCBOR(bytes.NewReader(ret)); err != nil { + // REVIEW: always fatal? + panic(err) + } + + return 0 } func (rt *Runtime) internalSend(from, to address.Address, method abi.MethodNum, value types.BigInt, params []byte) ([]byte, aerrors.ActorError) { @@ -398,54 +391,46 @@ func (rt *Runtime) internalSend(from, to address.Address, method abi.MethodNum, if subrt != nil { rt.numActorsCreated = subrt.numActorsCreated + rt.executionTrace.Subcalls = append(rt.executionTrace.Subcalls, subrt.executionTrace) } - rt.executionTrace.Subcalls = append(rt.executionTrace.Subcalls, subrt.executionTrace) return ret, errSend } -func (rt *Runtime) State() vmr.StateHandle { - return &shimStateHandle{rt: rt} -} - -type shimStateHandle struct { - rt *Runtime -} - -func (ssh *shimStateHandle) Create(obj vmr.CBORMarshaler) { - c := ssh.rt.Put(obj) - err := ssh.rt.stateCommit(EmptyObjectCid, c) +func (rt *Runtime) StateCreate(obj statecbor.Marshaler) { + c := rt.StorePut(obj) + err := rt.stateCommit(EmptyObjectCid, c) if err != nil { panic(fmt.Errorf("failed to commit state after creating object: %w", err)) } } -func (ssh *shimStateHandle) Readonly(obj vmr.CBORUnmarshaler) { - act, err := ssh.rt.state.GetActor(ssh.rt.Message().Receiver()) +func (rt *Runtime) StateReadonly(obj statecbor.Unmarshaler) { + act, err := rt.state.GetActor(rt.Receiver()) if err != nil { - ssh.rt.Abortf(exitcode.SysErrorIllegalArgument, "failed to get actor for Readonly state: %s", err) + rt.Abortf(exitcode.SysErrorIllegalArgument, "failed to get actor for Readonly state: %s", err) } - ssh.rt.Get(act.Head, obj) + rt.StoreGet(act.Head, obj) } -func (ssh *shimStateHandle) Transaction(obj vmr.CBORer, f func()) { +func (rt *Runtime) StateTransaction(obj statecbor.Er, f func()) { if obj == nil { - ssh.rt.Abortf(exitcode.SysErrorIllegalActor, "Must not pass nil to Transaction()") + rt.Abortf(exitcode.SysErrorIllegalActor, "Must not pass nil to Transaction()") } - act, err := ssh.rt.state.GetActor(ssh.rt.Message().Receiver()) + act, err := rt.state.GetActor(rt.Receiver()) if err != nil { - ssh.rt.Abortf(exitcode.SysErrorIllegalActor, "failed to get actor for Transaction: %s", err) + rt.Abortf(exitcode.SysErrorIllegalActor, "failed to get actor for Transaction: %s", err) } baseState := act.Head - ssh.rt.Get(baseState, obj) + rt.StoreGet(baseState, obj) - ssh.rt.allowInternal = false + rt.allowInternal = false f() - ssh.rt.allowInternal = true + rt.allowInternal = true - c := ssh.rt.Put(obj) + c := rt.StorePut(obj) - err = ssh.rt.stateCommit(baseState, c) + err = rt.stateCommit(baseState, c) if err != nil { panic(fmt.Errorf("failed to commit state after transaction: %w", err)) } @@ -465,7 +450,7 @@ func (rt *Runtime) GetBalance(a address.Address) (types.BigInt, aerrors.ActorErr func (rt *Runtime) stateCommit(oldh, newh cid.Cid) aerrors.ActorError { // TODO: we can make this more efficient in the future... - act, err := rt.state.GetActor(rt.Message().Receiver()) + act, err := rt.state.GetActor(rt.Receiver()) if err != nil { return aerrors.Escalate(err, "failed to get actor to commit state") } @@ -476,7 +461,7 @@ func (rt *Runtime) stateCommit(oldh, newh cid.Cid) aerrors.ActorError { act.Head = newh - if err := rt.state.SetActor(rt.Message().Receiver(), act); err != nil { + if err := rt.state.SetActor(rt.Receiver(), act); err != nil { return aerrors.Fatalf("failed to set actor in commit state: %s", err) } @@ -571,15 +556,15 @@ func (rt *Runtime) abortIfAlreadyValidated() { rt.callerValidated = true } -func (rt *Runtime) Log(level vmr.LogLevel, msg string, args ...interface{}) { +func (rt *Runtime) Log(level rtt.LogLevel, msg string, args ...interface{}) { switch level { - case vmr.DEBUG: + case rtt.DEBUG: actorLog.Debugf(msg, args...) - case vmr.INFO: + case rtt.INFO: actorLog.Infof(msg, args...) - case vmr.WARN: + case rtt.WARN: actorLog.Warnf(msg, args...) - case vmr.ERROR: + case rtt.ERROR: actorLog.Errorf(msg, args...) } } diff --git a/chain/vm/vm.go b/chain/vm/vm.go index eb6c2f354..a125df053 100644 --- a/chain/vm/vm.go +++ b/chain/vm/vm.go @@ -7,13 +7,6 @@ import ( "reflect" "time" - "github.com/filecoin-project/specs-actors/actors/runtime" - - bstore "github.com/filecoin-project/lotus/lib/blockstore" - - "github.com/filecoin-project/go-state-types/big" - "github.com/filecoin-project/specs-actors/actors/builtin" - block "github.com/ipfs/go-block-format" cid "github.com/ipfs/go-cid" cbor "github.com/ipfs/go-ipld-cbor" @@ -25,8 +18,11 @@ import ( "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/crypto" "github.com/filecoin-project/go-state-types/exitcode" + "github.com/filecoin-project/go-state-types/network" + "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin/account" "github.com/filecoin-project/lotus/build" @@ -34,6 +30,7 @@ import ( "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/lib/blockstore" + bstore "github.com/filecoin-project/lotus/lib/blockstore" "github.com/filecoin-project/lotus/lib/bufbstore" ) @@ -116,7 +113,7 @@ func (vm *VM) makeRuntime(ctx context.Context, msg *types.Message, origin addres Blocks: &gasChargingBlocks{rt.chargeGasFunc(2), rt.pricelist, vm.cst.Blocks}, Atlas: vm.cst.Atlas, } - rt.sys = pricedSyscalls{ + rt.Syscalls = pricedSyscalls{ under: vm.Syscalls(ctx, vm.cstate, rt.cst), chargeGas: rt.chargeGasFunc(1), pl: rt.pricelist, @@ -128,7 +125,7 @@ func (vm *VM) makeRuntime(ctx context.Context, msg *types.Message, origin addres rt.Abortf(exitcode.SysErrInvalidReceiver, "resolve msg.From address failed") } vmm.From = resF - rt.vmsg = &vmm + rt.Message = &vmm return rt } @@ -142,7 +139,7 @@ func (vm *UnsafeVM) MakeRuntime(ctx context.Context, msg *types.Message, origin } type CircSupplyCalculator func(context.Context, abi.ChainEpoch, *state.StateTree) (abi.TokenAmount, error) -type NtwkVersionGetter func(context.Context, abi.ChainEpoch) runtime.NetworkVersion +type NtwkVersionGetter func(context.Context, abi.ChainEpoch) network.Version type VM struct { cstate *state.StateTree @@ -170,10 +167,11 @@ type VMOpts struct { BaseFee abi.TokenAmount } -func NewVM(opts *VMOpts) (*VM, error) { +func NewVM(ctx context.Context, opts *VMOpts) (*VM, error) { buf := bufbstore.NewBufferedBstore(opts.Bstore) cst := cbor.NewCborStore(buf) - state, err := state.LoadStateTree(cst, opts.StateBase) + nwv := opts.NtwkVersion(ctx, opts.Epoch) // TODO: why do we need a context for this? + state, err := state.LoadStateTree(cst, opts.StateBase, nwv) if err != nil { return nil, err } @@ -700,9 +698,9 @@ func (vm *VM) Invoke(act *types.Actor, rt *Runtime, method abi.MethodNum, params defer span.End() if span.IsRecordingEvents() { span.AddAttributes( - trace.StringAttribute("to", rt.Message().Receiver().String()), + trace.StringAttribute("to", rt.Receiver().String()), trace.Int64Attribute("method", int64(method)), - trace.StringAttribute("value", rt.Message().ValueReceived().String()), + trace.StringAttribute("value", rt.ValueReceived().String()), ) } @@ -722,7 +720,7 @@ func (vm *VM) SetInvoker(i *Invoker) { vm.inv = i } -func (vm *VM) GetNtwkVersion(ctx context.Context, ce abi.ChainEpoch) runtime.NetworkVersion { +func (vm *VM) GetNtwkVersion(ctx context.Context, ce abi.ChainEpoch) network.Version { return vm.ntwkVersion(ctx, ce) } From 683a58195ec966757e1360a5fe0a2d973791d053 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Mon, 14 Sep 2020 14:17:45 +0200 Subject: [PATCH 016/303] More terraforming in chain/ --- chain/actors/builtin/power/power.go | 2 ++ chain/actors/builtin/power/v0.go | 5 ++++ chain/gen/genesis/genesis.go | 11 +++------ chain/gen/genesis/miners.go | 8 ++----- chain/gen/genesis/util.go | 6 +++++ chain/stmgr/call.go | 4 ++-- chain/stmgr/forks.go | 28 ++++++++++------------ chain/stmgr/read.go | 6 +---- chain/stmgr/stmgr.go | 37 +++++++++++++++++------------ chain/stmgr/utils.go | 11 ++++++--- chain/store/store.go | 22 ++++++++++++++++- chain/store/weight.go | 2 +- chain/vm/vm.go | 2 +- 13 files changed, 86 insertions(+), 58 deletions(-) diff --git a/chain/actors/builtin/power/power.go b/chain/actors/builtin/power/power.go index b7bb9329e..0fcbaf971 100644 --- a/chain/actors/builtin/power/power.go +++ b/chain/actors/builtin/power/power.go @@ -1,6 +1,7 @@ package power import ( + "github.com/filecoin-project/go-address" "golang.org/x/xerrors" "github.com/filecoin-project/go-state-types/abi" @@ -28,4 +29,5 @@ type State interface { cbor.Marshaler TotalLocked() (abi.TokenAmount, error) + MinerNominalPowerMeetsConsensusMinimum(adt.Store, address.Address) (bool, error) } diff --git a/chain/actors/builtin/power/v0.go b/chain/actors/builtin/power/v0.go index 8851080e6..879e3e446 100644 --- a/chain/actors/builtin/power/v0.go +++ b/chain/actors/builtin/power/v0.go @@ -1,6 +1,7 @@ package power import ( + "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/specs-actors/actors/builtin/power" @@ -14,3 +15,7 @@ type v0State struct { func (s *v0State) TotalLocked() (abi.TokenAmount, error) { return s.TotalPledgeCollateral, nil } + +func (s *v0State) MinerNominalPowerMeetsConsensusMinimum(st adt.Store, a address.Address) (bool, error) { + return s.State.MinerNominalPowerMeetsConsensusMinimum(st, a) +} diff --git a/chain/gen/genesis/genesis.go b/chain/gen/genesis/genesis.go index 3c4632437..d726dfa50 100644 --- a/chain/gen/genesis/genesis.go +++ b/chain/gen/genesis/genesis.go @@ -17,7 +17,6 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" - "github.com/filecoin-project/go-state-types/network" "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin/account" "github.com/filecoin-project/specs-actors/actors/builtin/multisig" @@ -115,7 +114,7 @@ func MakeInitialStateTree(ctx context.Context, bs bstore.Blockstore, template ge return nil, nil, xerrors.Errorf("putting empty object: %w", err) } - state, err := state.NewStateTree(cst) + state, err := state.NewStateTree(cst, GenesisNetworkVersion) if err != nil { return nil, nil, xerrors.Errorf("making new state tree: %w", err) } @@ -405,10 +404,6 @@ func VerifyPreSealedData(ctx context.Context, cs *store.ChainStore, stateroot ci verifNeeds := make(map[address.Address]abi.PaddedPieceSize) var sum abi.PaddedPieceSize - nwv := func(context.Context, abi.ChainEpoch) network.Version { - return network.Version1 - } - vmopt := vm.VMOpts{ StateBase: stateroot, Epoch: 0, @@ -416,10 +411,10 @@ func VerifyPreSealedData(ctx context.Context, cs *store.ChainStore, stateroot ci Bstore: cs.Blockstore(), Syscalls: mkFakedSigSyscalls(cs.VMSys()), CircSupplyCalc: nil, - NtwkVersion: nwv, + NtwkVersion: genesisNetworkVersion, BaseFee: types.NewInt(0), } - vm, err := vm.NewVM(&vmopt) + vm, err := vm.NewVM(ctx, &vmopt) if err != nil { return cid.Undef, xerrors.Errorf("failed to create NewVM: %w", err) } diff --git a/chain/gen/genesis/miners.go b/chain/gen/genesis/miners.go index 6d041bb4d..ff4668d7f 100644 --- a/chain/gen/genesis/miners.go +++ b/chain/gen/genesis/miners.go @@ -61,10 +61,6 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid return big.Zero(), nil } - nwv := func(context.Context, abi.ChainEpoch) network.Version { - return network.Version1 - } - vmopt := &vm.VMOpts{ StateBase: sroot, Epoch: 0, @@ -72,11 +68,11 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid Bstore: cs.Blockstore(), Syscalls: mkFakedSigSyscalls(cs.VMSys()), CircSupplyCalc: csc, - NtwkVersion: nwv, + NtwkVersion: genesisNetworkVersion, BaseFee: types.NewInt(0), } - vm, err := vm.NewVM(vmopt) + vm, err := vm.NewVM(ctx, vmopt) if err != nil { return cid.Undef, xerrors.Errorf("failed to create NewVM: %w", err) } diff --git a/chain/gen/genesis/util.go b/chain/gen/genesis/util.go index 67a4e9579..54fc4abfe 100644 --- a/chain/gen/genesis/util.go +++ b/chain/gen/genesis/util.go @@ -2,6 +2,7 @@ package genesis import ( "context" + "github.com/filecoin-project/go-state-types/network" "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" @@ -46,3 +47,8 @@ func doExecValue(ctx context.Context, vm *vm.VM, to, from address.Address, value return ret.Return, nil } + +var GenesisNetworkVersion = network.Version1 +func genesisNetworkVersion(context.Context, abi.ChainEpoch) network.Version { + return GenesisNetworkVersion // TODO: Get from build/ +} diff --git a/chain/stmgr/call.go b/chain/stmgr/call.go index 4b83842b4..f4dfc7115 100644 --- a/chain/stmgr/call.go +++ b/chain/stmgr/call.go @@ -33,7 +33,7 @@ func (sm *StateManager) CallRaw(ctx context.Context, msg *types.Message, bstate BaseFee: types.NewInt(0), } - vmi, err := vm.NewVM(vmopt) + vmi, err := vm.NewVM(ctx, vmopt) if err != nil { return nil, xerrors.Errorf("failed to set up vm: %w", err) } @@ -134,7 +134,7 @@ func (sm *StateManager) CallWithGas(ctx context.Context, msg *types.Message, pri NtwkVersion: sm.GetNtwkVersion, BaseFee: ts.Blocks()[0].ParentBaseFee, } - vmi, err := vm.NewVM(vmopt) + vmi, err := vm.NewVM(ctx, vmopt) if err != nil { return nil, xerrors.Errorf("failed to set up vm: %w", err) } diff --git a/chain/stmgr/forks.go b/chain/stmgr/forks.go index addaba90f..650536718 100644 --- a/chain/stmgr/forks.go +++ b/chain/stmgr/forks.go @@ -7,11 +7,10 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/lotus/build" - "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/filecoin-project/specs-actors/actors/builtin/power" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/util/adt" cbor "github.com/ipfs/go-ipld-cbor" "golang.org/x/xerrors" @@ -96,11 +95,8 @@ func UpgradeFaucetBurnRecovery(ctx context.Context, sm *StateManager, tree types return xerrors.Errorf("failed to get tipset at lookback height: %w", err) } - var lbtree *state.StateTree - if err = sm.WithStateTree(lbts.ParentState(), func(state *state.StateTree) error { - lbtree = state - return nil - }); err != nil { + lbtree, err := sm.ParentState(lbts) + if err != nil { return xerrors.Errorf("loading state tree failed: %w", err) } @@ -139,8 +135,8 @@ func UpgradeFaucetBurnRecovery(ctx context.Context, sm *StateManager, tree types }) } case builtin.StorageMinerActorCodeID: - var st miner.State - if err := sm.WithActorState(ctx, &st)(act); err != nil { + var st v0miner.State + if err := sm.ChainStore().Store(ctx).Get(ctx, act.Head, &st); err != nil { return xerrors.Errorf("failed to load miner state: %w", err) } @@ -176,7 +172,7 @@ func UpgradeFaucetBurnRecovery(ctx context.Context, sm *StateManager, tree types } // pull up power table to give miners back some funds proportional to their power - var ps power.State + var ps v0power.State powAct, err := tree.GetActor(builtin.StoragePowerActorAddr) if err != nil { return xerrors.Errorf("failed to load power actor: %w", err) @@ -215,12 +211,12 @@ func UpgradeFaucetBurnRecovery(ctx context.Context, sm *StateManager, tree types }) } case builtin.StorageMinerActorCodeID: - var st miner.State - if err := sm.WithActorState(ctx, &st)(act); err != nil { + var st v0miner.State + if err := sm.ChainStore().Store(ctx).Get(ctx, act.Head, &st); err != nil { return xerrors.Errorf("failed to load miner state: %w", err) } - var minfo miner.MinerInfo + var minfo v0miner.MinerInfo if err := cst.Get(ctx, st.Info, &minfo); err != nil { return xerrors.Errorf("failed to get miner info: %w", err) } @@ -244,8 +240,8 @@ func UpgradeFaucetBurnRecovery(ctx context.Context, sm *StateManager, tree types // Now make sure to give each miner who had power at the lookback some FIL lbact, err := lbtree.GetActor(addr) if err == nil { - var lbst miner.State - if err := sm.WithActorState(ctx, &lbst)(lbact); err != nil { + var lbst v0miner.State + if err := sm.ChainStore().Store(ctx).Get(ctx, lbact.Head, &lbst); err != nil { return xerrors.Errorf("failed to load miner state: %w", err) } diff --git a/chain/stmgr/read.go b/chain/stmgr/read.go index 2daa9f79d..7bf757fb8 100644 --- a/chain/stmgr/read.go +++ b/chain/stmgr/read.go @@ -2,8 +2,6 @@ package stmgr import ( "context" - "reflect" - "golang.org/x/xerrors" "github.com/ipfs/go-cid" @@ -13,8 +11,6 @@ import ( "github.com/filecoin-project/go-state-types/network" "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/types" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/filecoin-project/specs-actors/actors/util/adt" ) func (sm *StateManager) ParentStateTsk(tsk types.TipSetKey) (*state.StateTree, error) { @@ -22,7 +18,7 @@ func (sm *StateManager) ParentStateTsk(tsk types.TipSetKey) (*state.StateTree, e if err != nil { return nil, xerrors.Errorf("loading tipset %s: %w", tsk, err) } - return sm.ParentState(ts, cb) + return sm.ParentState(ts) } func (sm *StateManager) ParentState(ts *types.TipSet) (*state.StateTree, error) { diff --git a/chain/stmgr/stmgr.go b/chain/stmgr/stmgr.go index f5b043dc5..489eaab3d 100644 --- a/chain/stmgr/stmgr.go +++ b/chain/stmgr/stmgr.go @@ -41,7 +41,7 @@ type StateManager struct { compWait map[string]chan struct{} stlk sync.Mutex genesisMsigLk sync.Mutex - newVM func(*vm.VMOpts) (*vm.VM, error) + newVM func(context.Context, *vm.VMOpts) (*vm.VM, error) genInfo *genesisInfo } @@ -156,7 +156,7 @@ func (sm *StateManager) ApplyBlocks(ctx context.Context, parentEpoch abi.ChainEp BaseFee: baseFee, } - vmi, err := sm.newVM(vmopt) + vmi, err := sm.newVM(ctx, vmopt) if err != nil { return cid.Undef, cid.Undef, xerrors.Errorf("instantiating VM failed: %w", err) } @@ -383,7 +383,7 @@ func (sm *StateManager) ResolveToKeyAddress(ctx context.Context, addr address.Ad } cst := cbor.NewCborStore(sm.cs.Blockstore()) - tree, err := state.LoadStateTree(cst, st) + tree, err := state.LoadStateTree(cst, st, sm.GetNtwkVersion(ctx, ts.Height())) if err != nil { return address.Undef, xerrors.Errorf("failed to load state tree") } @@ -406,7 +406,7 @@ func (sm *StateManager) GetBlsPublicKey(ctx context.Context, addr address.Addres func (sm *StateManager) LookupID(ctx context.Context, addr address.Address, ts *types.TipSet) (address.Address, error) { cst := cbor.NewCborStore(sm.cs.Blockstore()) - state, err := state.LoadStateTree(cst, sm.parentState(ts)) + state, err := state.LoadStateTree(cst, sm.parentState(ts), sm.GetNtwkVersion(ctx, ts.Height())) if err != nil { return address.Undef, xerrors.Errorf("load state tree: %w", err) } @@ -598,10 +598,9 @@ func (sm *StateManager) searchBackForMsg(ctx context.Context, from *types.TipSet default: } - var act types.Actor - err := sm.WithParentState(cur, sm.WithActor(m.VMMessage().From, GetActor(&act))) + act, err := sm.LoadActor(ctx, m.VMMessage().From, cur) if err != nil { - return nil, nil, cid.Undef, err + return nil, nil, cid.Cid{}, err } // we either have no messages from the sender, or the latest message we found has a lower nonce than the one being searched for, @@ -712,9 +711,15 @@ func (sm *StateManager) MarketBalance(ctx context.Context, addr address.Address, if err != nil { return api.MarketBalance{}, err } + act, err := st.GetActor(builtin.StorageMarketActorAddr) if err != nil { - return nil, err + return api.MarketBalance{}, err + } + + mstate, err := market.Load(sm.cs.Store(ctx), act) + if err != nil { + return api.MarketBalance{}, err } addr, err = sm.LookupID(ctx, addr, ts) @@ -724,7 +729,7 @@ func (sm *StateManager) MarketBalance(ctx context.Context, addr address.Address, var out api.MarketBalance - et, err := adt.AsBalanceTable(sm.cs.Store(ctx), state.EscrowTable) + et, err := mstate.EscrowTable() if err != nil { return api.MarketBalance{}, err } @@ -733,7 +738,7 @@ func (sm *StateManager) MarketBalance(ctx context.Context, addr address.Address, return api.MarketBalance{}, xerrors.Errorf("getting escrow balance: %w", err) } - lt, err := adt.AsBalanceTable(sm.cs.Store(ctx), state.LockedTable) + lt, err := mstate.LockedTable() if err != nil { return api.MarketBalance{}, err } @@ -774,7 +779,7 @@ func (sm *StateManager) ValidateChain(ctx context.Context, ts *types.TipSet) err return nil } -func (sm *StateManager) SetVMConstructor(nvm func(*vm.VMOpts) (*vm.VM, error)) { +func (sm *StateManager) SetVMConstructor(nvm func(context.Context, *vm.VMOpts) (*vm.VM, error)) { sm.newVM = nvm } @@ -812,7 +817,7 @@ func (sm *StateManager) setupGenesisActors(ctx context.Context) error { } cst := cbor.NewCborStore(sm.cs.Blockstore()) - sTree, err := state.LoadStateTree(cst, st) + sTree, err := state.LoadStateTree(cst, st, sm.GetNtwkVersion(ctx, gts.Height())) if err != nil { return xerrors.Errorf("loading state tree: %w", err) } @@ -918,7 +923,7 @@ func (sm *StateManager) setupGenesisActorsTestnet(ctx context.Context) error { } cst := cbor.NewCborStore(sm.cs.Blockstore()) - sTree, err := state.LoadStateTree(cst, st) + sTree, err := state.LoadStateTree(cst, st, sm.GetNtwkVersion(ctx, gts.Height())) if err != nil { return xerrors.Errorf("loading state tree: %w", err) } @@ -1035,12 +1040,12 @@ func getFilPowerLocked(ctx context.Context, st *state.StateTree) (abi.TokenAmoun return big.Zero(), xerrors.Errorf("failed to load power actor: %w", err) } - pst, err := power.Load(adt.WrapStore(ctx, st.Store), act) + pst, err := power.Load(adt.WrapStore(ctx, st.Store), pactor) if err != nil { return big.Zero(), xerrors.Errorf("failed to load power state: %w", err) } - return pst.TotalLocked(), nil + return pst.TotalLocked() } func (sm *StateManager) GetFilLocked(ctx context.Context, st *state.StateTree) (abi.TokenAmount, error) { @@ -1124,6 +1129,8 @@ func (sm *StateManager) GetCirculatingSupply(ctx context.Context, height abi.Cha } func (sm *StateManager) GetNtwkVersion(ctx context.Context, height abi.ChainEpoch) network.Version { + // TODO: move hard fork epoch checks to a schedule defined in build/ + if build.UpgradeBreezeHeight == 0 { return network.Version1 } diff --git a/chain/stmgr/utils.go b/chain/stmgr/utils.go index a137afb51..a6fdce31e 100644 --- a/chain/stmgr/utils.go +++ b/chain/stmgr/utils.go @@ -21,6 +21,7 @@ import ( "github.com/filecoin-project/go-bitfield" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/crypto" + power2 "github.com/filecoin-project/lotus/chain/actors/builtin/power" "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin/account" @@ -670,17 +671,21 @@ func GetReturnType(ctx context.Context, sm *StateManager, to address.Address, me } func MinerHasMinPower(ctx context.Context, sm *StateManager, addr address.Address, ts *types.TipSet) (bool, error) { - var ps power.State - _, err := sm.LoadActorState(ctx, builtin.StoragePowerActorAddr, &ps, ts) + pact, err := sm.LoadActor(ctx, builtin.StoragePowerActorAddr, ts) if err != nil { return false, xerrors.Errorf("loading power actor state: %w", err) } + ps, err := power2.Load(sm.cs.Store(ctx), pact) + if err != nil { + return false, err + } + return ps.MinerNominalPowerMeetsConsensusMinimum(sm.ChainStore().Store(ctx), addr) } func CheckTotalFIL(ctx context.Context, sm *StateManager, ts *types.TipSet) (abi.TokenAmount, error) { - str, err := state.LoadStateTree(sm.ChainStore().Store(ctx), ts.ParentState()) + str, err := state.LoadStateTree(sm.ChainStore().Store(ctx), ts.ParentState(), sm.GetNtwkVersion(ctx, ts.Height())) if err != nil { return abi.TokenAmount{}, err } diff --git a/chain/store/store.go b/chain/store/store.go index e0a997686..390242294 100644 --- a/chain/store/store.go +++ b/chain/store/store.go @@ -5,6 +5,8 @@ import ( "context" "encoding/binary" "encoding/json" + "github.com/filecoin-project/go-state-types/network" + "github.com/filecoin-project/lotus/build" "io" "os" "strconv" @@ -741,11 +743,29 @@ type BlockMessages struct { WinCount int64 } +// TODO: temp hack until #3682 is merged +func hackgetNtwkVersionhack(ctx context.Context, height abi.ChainEpoch) network.Version { + // TODO: move hard fork epoch checks to a schedule defined in build/ + + if build.UpgradeBreezeHeight == 0 { + return network.Version1 + } + + if height <= build.UpgradeBreezeHeight { + return network.Version0 + } + + return network.Version1 +} + func (cs *ChainStore) BlockMsgsForTipset(ts *types.TipSet) ([]BlockMessages, error) { applied := make(map[address.Address]uint64) cst := cbor.NewCborStore(cs.bs) - st, err := state.LoadStateTree(cst, ts.Blocks()[0].ParentStateRoot) + + nv := hackgetNtwkVersionhack(context.TODO(), ts.Height()) // TODO: part of the temp hack from above + + st, err := state.LoadStateTree(cst, ts.Blocks()[0].ParentStateRoot, nv) if err != nil { return nil, xerrors.Errorf("failed to load state tree") } diff --git a/chain/store/weight.go b/chain/store/weight.go index 5249df011..e27d3fd37 100644 --- a/chain/store/weight.go +++ b/chain/store/weight.go @@ -29,7 +29,7 @@ func (cs *ChainStore) Weight(ctx context.Context, ts *types.TipSet) (types.BigIn tpow := big2.Zero() { cst := cbor.NewCborStore(cs.Blockstore()) - state, err := state.LoadStateTree(cst, ts.ParentState()) + state, err := state.LoadStateTree(cst, ts.ParentState(), hackgetNtwkVersionhack(nil, ts.Height())) // TODO: hackgetNtwkVersionhack: HELP if err != nil { return types.NewInt(0), xerrors.Errorf("load state tree: %w", err) } diff --git a/chain/vm/vm.go b/chain/vm/vm.go index a125df053..ced11e04d 100644 --- a/chain/vm/vm.go +++ b/chain/vm/vm.go @@ -163,7 +163,7 @@ type VMOpts struct { Bstore bstore.Blockstore Syscalls SyscallBuilder CircSupplyCalc CircSupplyCalculator - NtwkVersion NtwkVersionGetter + NtwkVersion NtwkVersionGetter // TODO: stebalien: In what cases do we actually need this? It seems like even when creating new networks we want to use the 'global'/build-default version getter BaseFee abi.TokenAmount } From fb3f7105238ff59ff91fed05aec4eee5ae391dec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Mon, 14 Sep 2020 15:17:00 +0200 Subject: [PATCH 017/303] Some post-master merge fixes --- api/apistruct/struct.go | 8 +++----- chain/gen/genesis/miners.go | 7 +------ chain/gen/genesis/util.go | 13 ++++++++++--- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/api/apistruct/struct.go b/api/apistruct/struct.go index 151e7d99a..1eac858a0 100644 --- a/api/apistruct/struct.go +++ b/api/apistruct/struct.go @@ -2,13 +2,9 @@ package apistruct import ( "context" - "github.com/filecoin-project/go-state-types/dline" - miner2 "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "io" "time" - "github.com/filecoin-project/go-state-types/dline" - "github.com/ipfs/go-cid" metrics "github.com/libp2p/go-libp2p-core/metrics" "github.com/libp2p/go-libp2p-core/network" @@ -25,6 +21,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" + "github.com/filecoin-project/go-state-types/dline" "github.com/filecoin-project/lotus/extern/sector-storage/fsutil" "github.com/filecoin-project/lotus/extern/sector-storage/sealtasks" "github.com/filecoin-project/lotus/extern/sector-storage/stores" @@ -37,6 +34,7 @@ import ( "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" + miner2 "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/node/modules/dtypes" ) @@ -168,7 +166,7 @@ type FullNodeStruct struct { StateMinerActiveSectors func(context.Context, address.Address, types.TipSetKey) ([]*api.ChainSectorInfo, error) `perm:"read"` StateMinerProvingDeadline func(context.Context, address.Address, types.TipSetKey) (*dline.Info, error) `perm:"read"` StateMinerPower func(context.Context, address.Address, types.TipSetKey) (*api.MinerPower, error) `perm:"read"` - StateMinerInfo func(context.Context, address.Address, types.TipSetKey) (miner2.MinerInfo, error) `perm:"read"` + StateMinerInfo func(context.Context, address.Address, types.TipSetKey) (miner2.MinerInfo, error) `perm:"read"` StateMinerFaults func(context.Context, address.Address, types.TipSetKey) (bitfield.BitField, error) `perm:"read"` StateAllMinerFaults func(context.Context, abi.ChainEpoch, types.TipSetKey) ([]*api.Fault, error) `perm:"read"` StateMinerRecoveries func(context.Context, address.Address, types.TipSetKey) (bitfield.BitField, error) `perm:"read"` diff --git a/chain/gen/genesis/miners.go b/chain/gen/genesis/miners.go index 6c1fec23c..3bed1c1a9 100644 --- a/chain/gen/genesis/miners.go +++ b/chain/gen/genesis/miners.go @@ -6,12 +6,6 @@ import ( "fmt" "math/rand" - "github.com/filecoin-project/lotus/build" - - "github.com/filecoin-project/go-state-types/network" - - "github.com/filecoin-project/lotus/chain/state" - "github.com/ipfs/go-cid" cbor "github.com/ipfs/go-ipld-cbor" cbg "github.com/whyrusleeping/cbor-gen" @@ -29,6 +23,7 @@ import ( "github.com/filecoin-project/specs-actors/actors/builtin/reward" "github.com/filecoin-project/specs-actors/actors/runtime" + "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/store" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/vm" diff --git a/chain/gen/genesis/util.go b/chain/gen/genesis/util.go index 54fc4abfe..6a27f2f29 100644 --- a/chain/gen/genesis/util.go +++ b/chain/gen/genesis/util.go @@ -3,6 +3,7 @@ package genesis import ( "context" "github.com/filecoin-project/go-state-types/network" + "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" @@ -48,7 +49,13 @@ func doExecValue(ctx context.Context, vm *vm.VM, to, from address.Address, value return ret.Return, nil } -var GenesisNetworkVersion = network.Version1 -func genesisNetworkVersion(context.Context, abi.ChainEpoch) network.Version { +var GenesisNetworkVersion = func() network.Version {// TODO: Get from build/ + if build.UseNewestNetwork() {// TODO: Get from build/ + return build.NewestNetworkVersion// TODO: Get from build/ + }// TODO: Get from build/ + return network.Version1// TODO: Get from build/ +}()// TODO: Get from build/ + +func genesisNetworkVersion(context.Context, abi.ChainEpoch) network.Version {// TODO: Get from build/ return GenesisNetworkVersion // TODO: Get from build/ -} +}// TODO: Get from build/ From 2088335b9df1362f4a4cfba16c1a9d9dcec406dd Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Mon, 14 Sep 2020 14:40:52 -0700 Subject: [PATCH 018/303] rename to simplify merge --- storage/wdpost_run.go | 52 +++++++++++++++++++++---------------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/storage/wdpost_run.go b/storage/wdpost_run.go index f314dce9a..083c793e8 100644 --- a/storage/wdpost_run.go +++ b/storage/wdpost_run.go @@ -17,14 +17,14 @@ import ( "go.opencensus.io/trace" "golang.org/x/xerrors" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" - v0proof "github.com/filecoin-project/specs-actors/actors/runtime/proof" + "github.com/filecoin-project/specs-actors/actors/builtin/miner" + "github.com/filecoin-project/specs-actors/actors/runtime/proof" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/api/apibstore" "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/actors" - "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + iminer "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/store" "github.com/filecoin-project/lotus/chain/types" ) @@ -115,12 +115,12 @@ func (s *WindowPoStScheduler) checkSectors(ctx context.Context, check bitfield.B return sbf, nil } -func (s *WindowPoStScheduler) checkNextRecoveries(ctx context.Context, dlIdx uint64, partitions []miner.Partition) error { +func (s *WindowPoStScheduler) checkNextRecoveries(ctx context.Context, dlIdx uint64, partitions []iminer.Partition) error { ctx, span := trace.StartSpan(ctx, "storage.checkNextRecoveries") defer span.End() - params := &v0miner.DeclareFaultsRecoveredParams{ - Recoveries: []v0miner.RecoveryDeclaration{}, + params := &miner.DeclareFaultsRecoveredParams{ + Recoveries: []miner.RecoveryDeclaration{}, } faulty := uint64(0) @@ -165,7 +165,7 @@ func (s *WindowPoStScheduler) checkNextRecoveries(ctx context.Context, dlIdx uin continue } - params.Recoveries = append(params.Recoveries, v0miner.RecoveryDeclaration{ + params.Recoveries = append(params.Recoveries, miner.RecoveryDeclaration{ Deadline: dlIdx, Partition: uint64(partIdx), Sectors: recovered, @@ -214,12 +214,12 @@ func (s *WindowPoStScheduler) checkNextRecoveries(ctx context.Context, dlIdx uin return nil } -func (s *WindowPoStScheduler) checkNextFaults(ctx context.Context, dlIdx uint64, partitions []miner.Partition) error { +func (s *WindowPoStScheduler) checkNextFaults(ctx context.Context, dlIdx uint64, partitions []iminer.Partition) error { ctx, span := trace.StartSpan(ctx, "storage.checkNextFaults") defer span.End() - params := &v0miner.DeclareFaultsParams{ - Faults: []v0miner.FaultDeclaration{}, + params := &miner.DeclareFaultsParams{ + Faults: []miner.FaultDeclaration{}, } bad := uint64(0) @@ -251,7 +251,7 @@ func (s *WindowPoStScheduler) checkNextFaults(ctx context.Context, dlIdx uint64, bad += c - params.Faults = append(params.Faults, v0miner.FaultDeclaration{ + params.Faults = append(params.Faults, miner.FaultDeclaration{ Deadline: dlIdx, Partition: uint64(partIdx), Sectors: faulty, @@ -298,7 +298,7 @@ func (s *WindowPoStScheduler) checkNextFaults(ctx context.Context, dlIdx uint64, return nil } -func (s *WindowPoStScheduler) runPost(ctx context.Context, di dline.Info, ts *types.TipSet) (*v0miner.SubmitWindowedPoStParams, error) { +func (s *WindowPoStScheduler) runPost(ctx context.Context, di dline.Info, ts *types.TipSet) (*miner.SubmitWindowedPoStParams, error) { ctx, span := trace.StartSpan(ctx, "storage.runPost") defer span.End() @@ -308,7 +308,7 @@ func (s *WindowPoStScheduler) runPost(ctx context.Context, di dline.Info, ts *ty return nil, xerrors.Errorf("resolving actor: %w", err) } - mas, err := miner.Load(stor, act) + mas, err := iminer.Load(stor, act) if err != nil { return nil, xerrors.Errorf("getting miner state: %w", err) } @@ -325,8 +325,8 @@ func (s *WindowPoStScheduler) runPost(ctx context.Context, di dline.Info, ts *ty log.Errorf("loading deadline: %v", err) return } - var partitions []miner.Partition - err = dl.ForEachPartition(func(_ uint64, part miner.Partition) error { + var partitions []iminer.Partition + err = dl.ForEachPartition(func(_ uint64, part iminer.Partition) error { partitions = append(partitions, part) return nil }) @@ -361,8 +361,8 @@ func (s *WindowPoStScheduler) runPost(ctx context.Context, di dline.Info, ts *ty return nil, xerrors.Errorf("loading deadline: %w", err) } - var partitions []miner.Partitions - err = dl.ForEachPartition(func(_ uint64, part miner.Partition) error { + var partitions []iminer.Partitions + err = dl.ForEachPartition(func(_ uint64, part iminer.Partition) error { partitions = apppend(partitions, part) return nil }) @@ -370,9 +370,9 @@ func (s *WindowPoStScheduler) runPost(ctx context.Context, di dline.Info, ts *ty return nil, xerrors.Errorf("loading partitions: %w", err) } - params := &v0miner.SubmitWindowedPoStParams{ + params := &miner.SubmitWindowedPoStParams{ Deadline: di.Index, - Partitions: make([]v0miner.PoStPartition, 0, len(partitions)), + Partitions: make([]miner.PoStPartition, 0, len(partitions)), Proofs: nil, } @@ -432,7 +432,7 @@ func (s *WindowPoStScheduler) runPost(ctx context.Context, di dline.Info, ts *ty sidToPart[si.SectorNumber] = partIdx } - params.Partitions = append(params.Partitions, v0miner.PoStPartition{ + params.Partitions = append(params.Partitions, miner.PoStPartition{ Index: uint64(partIdx), Skipped: skipped, }) @@ -497,7 +497,7 @@ func (s *WindowPoStScheduler) runPost(ctx context.Context, di dline.Info, ts *ty return params, nil } -func (s *WindowPoStScheduler) sectorsForProof(ctx context.Context, goodSectors, allSectors bitfield.BitField, ts *types.TipSet) ([]v0proof.SectorInfo, error) { +func (s *WindowPoStScheduler) sectorsForProof(ctx context.Context, goodSectors, allSectors bitfield.BitField, ts *types.TipSet) ([]proof.SectorInfo, error) { sset, err := s.api.StateMinerSectors(ctx, s.actor, &goodSectors, false, ts.Key()) if err != nil { return nil, err @@ -507,22 +507,22 @@ func (s *WindowPoStScheduler) sectorsForProof(ctx context.Context, goodSectors, return nil, nil } - substitute := v0proof.SectorInfo{ + substitute := proof.SectorInfo{ SectorNumber: sset[0].ID, SealedCID: sset[0].Info.SealedCID, SealProof: sset[0].Info.SealProof, } - sectorByID := make(map[uint64]v0proof.SectorInfo, len(sset)) + sectorByID := make(map[uint64]proof.SectorInfo, len(sset)) for _, sector := range sset { - sectorByID[uint64(sector.ID)] = v0proof.SectorInfo{ + sectorByID[uint64(sector.ID)] = proof.SectorInfo{ SectorNumber: sector.ID, SealedCID: sector.Info.SealedCID, SealProof: sector.Info.SealProof, } } - proofSectors := make([]v0proof.SectorInfo, 0, len(sset)) + proofSectors := make([]proof.SectorInfo, 0, len(sset)) if err := allSectors.ForEach(func(sectorNo uint64) error { if info, found := sectorByID[sectorNo]; found { proofSectors = append(proofSectors, info) @@ -537,7 +537,7 @@ func (s *WindowPoStScheduler) sectorsForProof(ctx context.Context, goodSectors, return proofSectors, nil } -func (s *WindowPoStScheduler) submitPost(ctx context.Context, proof *v0miner.SubmitWindowedPoStParams) error { +func (s *WindowPoStScheduler) submitPost(ctx context.Context, proof *miner.SubmitWindowedPoStParams) error { ctx, span := trace.StartSpan(ctx, "storage.commitPost") defer span.End() From cc4d5306ebc363fa912310a2b2f96c4db2486c53 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Mon, 14 Sep 2020 15:43:12 -0700 Subject: [PATCH 019/303] Progress --- chain/actors/adt/adt.go | 8 ++-- chain/actors/builtin/init/init.go | 4 ++ chain/actors/builtin/init/v0.go | 5 +++ chain/actors/builtin/miner/miner.go | 2 + chain/actors/builtin/power/power.go | 12 ++++- chain/actors/builtin/power/v0.go | 28 ++++++++++-- chain/actors/version.go | 24 ---------- chain/gen/genesis/genesis.go | 63 +++++++++++++------------- chain/state/statetree.go | 70 ++++++++++++++++++++++------- chain/stmgr/read.go | 16 ++++--- chain/stmgr/stmgr.go | 8 ++-- chain/stmgr/utils.go | 60 ++++++++++++------------- chain/store/store.go | 21 +-------- chain/store/weight.go | 2 +- chain/sub/incoming.go | 2 +- chain/sync.go | 3 +- chain/types/state.go | 15 +++++++ chain/vm/vm.go | 3 +- cmd/lotus-shed/balances.go | 3 +- cmd/lotus-shed/genesis-verify.go | 2 +- gen/main.go | 2 + node/impl/full/state.go | 2 +- 22 files changed, 205 insertions(+), 150 deletions(-) delete mode 100644 chain/actors/version.go create mode 100644 chain/types/state.go diff --git a/chain/actors/adt/adt.go b/chain/actors/adt/adt.go index 179c73b33..ebf32c3c4 100644 --- a/chain/actors/adt/adt.go +++ b/chain/actors/adt/adt.go @@ -21,16 +21,16 @@ type Map interface { ForEach(v cbor.Unmarshaler, fn func(key string) error) error } -func AsMap(store Store, root cid.Cid, version network.Version) (Map, error) { - switch builtin.VersionForNetwork(version) { +func AsMap(store Store, root cid.Cid, version builtin.Version) (Map, error) { + switch version { case builtin.Version0: return v0adt.AsMap(store, root) } return nil, xerrors.Errorf("unknown network version: %d", version) } -func NewMap(store Store, version network.Version) (Map, error) { - switch builtin.VersionForNetwork(version) { +func NewMap(store Store, version builtin.Version) (Map, error) { + switch version { case builtin.Version0: return v0adt.MakeEmptyMap(store), nil } diff --git a/chain/actors/builtin/init/init.go b/chain/actors/builtin/init/init.go index a96c0dfd6..3b1a49564 100644 --- a/chain/actors/builtin/init/init.go +++ b/chain/actors/builtin/init/init.go @@ -9,8 +9,11 @@ import ( "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/types" + "github.com/filecoin-project/lotus/node/modules/dtypes" ) +var Address = v0builtin.InitActorAddr + func Load(store adt.Store, act *types.Actor) (State, error) { switch act.Code { case v0builtin.InitActorCodeID: @@ -29,4 +32,5 @@ type State interface { ResolveAddress(address address.Address) (address.Address, bool, error) MapAddressToNewID(address address.Address) (address.Address, error) + NetworkName() (dtypes.NetworkName, error) } diff --git a/chain/actors/builtin/init/v0.go b/chain/actors/builtin/init/v0.go index 5001e9806..711b702e2 100644 --- a/chain/actors/builtin/init/v0.go +++ b/chain/actors/builtin/init/v0.go @@ -6,6 +6,7 @@ import ( init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" "github.com/filecoin-project/lotus/chain/actors/adt" + "github.com/filecoin-project/lotus/node/modules/dtypes" ) type v0State struct { @@ -20,3 +21,7 @@ func (s *v0State) ResolveAddress(address address.Address) (address.Address, bool func (s *v0State) MapAddressToNewID(address address.Address) (address.Address, error) { return s.State.MapAddressToNewID(s.store, address) } + +func (s *v0State) NetworkName() (dtypes.NetworkName, error) { + return dtypes.NetworkName(s.State.NetworkName), nil +} diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index 11dc3158a..76503d80e 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -14,6 +14,8 @@ import ( "github.com/filecoin-project/lotus/chain/types" ) +var Address = v0builtin.InitActorAddr + func Load(store adt.Store, act *types.Actor) (st State, err error) { switch act.Code { case v0builtin.StorageMinerActorCodeID: diff --git a/chain/actors/builtin/power/power.go b/chain/actors/builtin/power/power.go index 0fcbaf971..7588615a6 100644 --- a/chain/actors/builtin/power/power.go +++ b/chain/actors/builtin/power/power.go @@ -29,5 +29,15 @@ type State interface { cbor.Marshaler TotalLocked() (abi.TokenAmount, error) - MinerNominalPowerMeetsConsensusMinimum(adt.Store, address.Address) (bool, error) + TotalPower() (Claim, error) + MinerPower(address.Address) (Claim, error) + MinerNominalPowerMeetsConsensusMinimum(address.Address) (bool, error) +} + +type Claim struct { + // Sum of raw byte power for a miner's sectors. + RawBytePower abi.StoragePower + + // Sum of quality adjusted power for a miner's sectors. + QualityAdjPower abi.StoragePower } diff --git a/chain/actors/builtin/power/v0.go b/chain/actors/builtin/power/v0.go index 879e3e446..f3152eb6a 100644 --- a/chain/actors/builtin/power/v0.go +++ b/chain/actors/builtin/power/v0.go @@ -3,8 +3,8 @@ package power import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/specs-actors/actors/builtin/power" + "github.com/filecoin-project/specs-actors/actors/util/adt" ) type v0State struct { @@ -16,6 +16,28 @@ func (s *v0State) TotalLocked() (abi.TokenAmount, error) { return s.TotalPledgeCollateral, nil } -func (s *v0State) MinerNominalPowerMeetsConsensusMinimum(st adt.Store, a address.Address) (bool, error) { - return s.State.MinerNominalPowerMeetsConsensusMinimum(st, a) +func (s *v0State) TotalPower() (Claim, error) { + return Claim{ + RawBytePower: s.TotalRawBytePower, + QualityAdjPower: s.TotalQualityAdjPower, + }, nil +} + +func (s *v0State) MinerPower(addr address.Address) (Claim, error) { + claims, err := adt.AsMap(s.store, s.Claims) + if err != nil { + return Claim{}, err + } + var claim power.Claim + if _, err := claims.Get(abi.AddrKey(addr), &claim); err != nil { + return Claim{}, err + } + return Claim{ + RawBytePower: claim.RawBytePower, + QualityAdjPower: claim.QualityAdjPower, + }, nil +} + +func (s *v0State) MinerNominalPowerMeetsConsensusMinimum(a address.Address) (bool, error) { + return s.State.MinerNominalPowerMeetsConsensusMinimum(s.store, a) } diff --git a/chain/actors/version.go b/chain/actors/version.go deleted file mode 100644 index 99cc59eaa..000000000 --- a/chain/actors/version.go +++ /dev/null @@ -1,24 +0,0 @@ -package actors - -import ( - "fmt" - - "github.com/filecoin-project/go-state-types/network" -) - -type Version int - -const ( - Version0 = iota - Version1 -) - -// VersionForNetwork resolves the network version into an specs-actors version. -func VersionForNetwork(v network.Version) Version { - switch v { - case network.Version0, network.Version1: - return Version0 - default: - panic(fmt.Sprintf("unimplemented network version: %d", v)) - } -} diff --git a/chain/gen/genesis/genesis.go b/chain/gen/genesis/genesis.go index d726dfa50..be2ed70aa 100644 --- a/chain/gen/genesis/genesis.go +++ b/chain/gen/genesis/genesis.go @@ -17,13 +17,14 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" - "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/account" - "github.com/filecoin-project/specs-actors/actors/builtin/multisig" - "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" - "github.com/filecoin-project/specs-actors/actors/util/adt" + v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" + v0account "github.com/filecoin-project/specs-actors/actors/builtin/account" + v0multisig "github.com/filecoin-project/specs-actors/actors/builtin/multisig" + v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + v0adt "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/filecoin-project/lotus/build" + "github.com/filecoin-project/lotus/chain/actors/builtin" "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/store" "github.com/filecoin-project/lotus/chain/types" @@ -114,7 +115,7 @@ func MakeInitialStateTree(ctx context.Context, bs bstore.Blockstore, template ge return nil, nil, xerrors.Errorf("putting empty object: %w", err) } - state, err := state.NewStateTree(cst, GenesisNetworkVersion) + state, err := state.NewStateTree(cst, builtin.Version0) if err != nil { return nil, nil, xerrors.Errorf("making new state tree: %w", err) } @@ -125,7 +126,7 @@ func MakeInitialStateTree(ctx context.Context, bs bstore.Blockstore, template ge if err != nil { return nil, nil, xerrors.Errorf("setup init actor: %w", err) } - if err := state.SetActor(builtin.SystemActorAddr, sysact); err != nil { + if err := state.SetActor(v0builtin.SystemActorAddr, sysact); err != nil { return nil, nil, xerrors.Errorf("set init actor: %w", err) } @@ -135,7 +136,7 @@ func MakeInitialStateTree(ctx context.Context, bs bstore.Blockstore, template ge if err != nil { return nil, nil, xerrors.Errorf("setup init actor: %w", err) } - if err := state.SetActor(builtin.InitActorAddr, initact); err != nil { + if err := state.SetActor(v0builtin.InitActorAddr, initact); err != nil { return nil, nil, xerrors.Errorf("set init actor: %w", err) } @@ -146,7 +147,7 @@ func MakeInitialStateTree(ctx context.Context, bs bstore.Blockstore, template ge return nil, nil, xerrors.Errorf("setup init actor: %w", err) } - err = state.SetActor(builtin.RewardActorAddr, rewact) + err = state.SetActor(v0builtin.RewardActorAddr, rewact) if err != nil { return nil, nil, xerrors.Errorf("set network account actor: %w", err) } @@ -156,7 +157,7 @@ func MakeInitialStateTree(ctx context.Context, bs bstore.Blockstore, template ge if err != nil { return nil, nil, xerrors.Errorf("setup cron actor: %w", err) } - if err := state.SetActor(builtin.CronActorAddr, cronact); err != nil { + if err := state.SetActor(v0builtin.CronActorAddr, cronact); err != nil { return nil, nil, xerrors.Errorf("set cron actor: %w", err) } @@ -165,7 +166,7 @@ func MakeInitialStateTree(ctx context.Context, bs bstore.Blockstore, template ge if err != nil { return nil, nil, xerrors.Errorf("setup storage market actor: %w", err) } - if err := state.SetActor(builtin.StoragePowerActorAddr, spact); err != nil { + if err := state.SetActor(v0builtin.StoragePowerActorAddr, spact); err != nil { return nil, nil, xerrors.Errorf("set storage market actor: %w", err) } @@ -174,7 +175,7 @@ func MakeInitialStateTree(ctx context.Context, bs bstore.Blockstore, template ge if err != nil { return nil, nil, xerrors.Errorf("setup storage market actor: %w", err) } - if err := state.SetActor(builtin.StorageMarketActorAddr, marketact); err != nil { + if err := state.SetActor(v0builtin.StorageMarketActorAddr, marketact); err != nil { return nil, nil, xerrors.Errorf("set market actor: %w", err) } @@ -183,20 +184,20 @@ func MakeInitialStateTree(ctx context.Context, bs bstore.Blockstore, template ge if err != nil { return nil, nil, xerrors.Errorf("setup storage market actor: %w", err) } - if err := state.SetActor(builtin.VerifiedRegistryActorAddr, verifact); err != nil { + if err := state.SetActor(v0builtin.VerifiedRegistryActorAddr, verifact); err != nil { return nil, nil, xerrors.Errorf("set market actor: %w", err) } - burntRoot, err := cst.Put(ctx, &account.State{ - Address: builtin.BurntFundsActorAddr, + burntRoot, err := cst.Put(ctx, &v0account.State{ + Address: v0builtin.BurntFundsActorAddr, }) if err != nil { return nil, nil, xerrors.Errorf("failed to setup burnt funds actor state: %w", err) } // Setup burnt-funds - err = state.SetActor(builtin.BurntFundsActorAddr, &types.Actor{ - Code: builtin.AccountActorCodeID, + err = state.SetActor(v0builtin.BurntFundsActorAddr, &types.Actor{ + Code: v0builtin.AccountActorCodeID, Balance: types.NewInt(0), Head: burntRoot, }) @@ -261,13 +262,13 @@ func MakeInitialStateTree(ctx context.Context, bs bstore.Blockstore, template ge return nil, nil, err } - verifierState, err := cst.Put(ctx, &account.State{Address: verifierAd}) + verifierState, err := cst.Put(ctx, &v0account.State{Address: verifierAd}) if err != nil { return nil, nil, err } err = state.SetActor(verifierId, &types.Actor{ - Code: builtin.AccountActorCodeID, + Code: v0builtin.AccountActorCodeID, Balance: types.NewInt(0), Head: verifierState, }) @@ -314,7 +315,7 @@ func createAccountActor(ctx context.Context, cst cbor.IpldStore, state *state.St if err := json.Unmarshal(info.Meta, &ainfo); err != nil { return xerrors.Errorf("unmarshaling account meta: %w", err) } - st, err := cst.Put(ctx, &account.State{Address: ainfo.Owner}) + st, err := cst.Put(ctx, &v0account.State{Address: ainfo.Owner}) if err != nil { return err } @@ -325,7 +326,7 @@ func createAccountActor(ctx context.Context, cst cbor.IpldStore, state *state.St } err = state.SetActor(ida, &types.Actor{ - Code: builtin.AccountActorCodeID, + Code: v0builtin.AccountActorCodeID, Balance: info.Balance, Head: st, }) @@ -343,7 +344,7 @@ func createMultisigAccount(ctx context.Context, bs bstore.Blockstore, cst cbor.I if err := json.Unmarshal(info.Meta, &ainfo); err != nil { return xerrors.Errorf("unmarshaling account meta: %w", err) } - pending, err := adt.MakeEmptyMap(adt.WrapStore(ctx, cst)).Root() + pending, err := v0adt.MakeEmptyMap(v0adt.WrapStore(ctx, cst)).Root() if err != nil { return xerrors.Errorf("failed to create empty map: %v", err) } @@ -363,12 +364,12 @@ func createMultisigAccount(ctx context.Context, bs bstore.Blockstore, cst cbor.I continue } - st, err := cst.Put(ctx, &account.State{Address: e}) + st, err := cst.Put(ctx, &v0account.State{Address: e}) if err != nil { return err } err = state.SetActor(idAddress, &types.Actor{ - Code: builtin.AccountActorCodeID, + Code: v0builtin.AccountActorCodeID, Balance: types.NewInt(0), Head: st, }) @@ -378,7 +379,7 @@ func createMultisigAccount(ctx context.Context, bs bstore.Blockstore, cst cbor.I signers = append(signers, idAddress) } - st, err := cst.Put(ctx, &multisig.State{ + st, err := cst.Put(ctx, &v0multisig.State{ Signers: signers, NumApprovalsThreshold: uint64(ainfo.Threshold), StartEpoch: abi.ChainEpoch(ainfo.VestingStart), @@ -390,7 +391,7 @@ func createMultisigAccount(ctx context.Context, bs bstore.Blockstore, cst cbor.I return err } err = state.SetActor(ida, &types.Actor{ - Code: builtin.MultisigActorCodeID, + Code: v0builtin.MultisigActorCodeID, Balance: info.Balance, Head: st, }) @@ -441,7 +442,7 @@ func VerifyPreSealedData(ctx context.Context, cs *store.ChainStore, stateroot ci return cid.Undef, err } - _, err = doExecValue(ctx, vm, builtin.VerifiedRegistryActorAddr, verifregRoot, types.NewInt(0), builtin.MethodsVerifiedRegistry.AddVerifier, mustEnc(&verifreg.AddVerifierParams{ + _, err = doExecValue(ctx, vm, v0builtin.VerifiedRegistryActorAddr, verifregRoot, types.NewInt(0), v0builtin.MethodsVerifiedRegistry.AddVerifier, mustEnc(&v0verifreg.AddVerifierParams{ Address: verifier, Allowance: abi.NewStoragePower(int64(sum)), // eh, close enough @@ -452,7 +453,7 @@ func VerifyPreSealedData(ctx context.Context, cs *store.ChainStore, stateroot ci } for c, amt := range verifNeeds { - _, err := doExecValue(ctx, vm, builtin.VerifiedRegistryActorAddr, verifier, types.NewInt(0), builtin.MethodsVerifiedRegistry.AddVerifiedClient, mustEnc(&verifreg.AddVerifiedClientParams{ + _, err := doExecValue(ctx, vm, v0builtin.VerifiedRegistryActorAddr, verifier, types.NewInt(0), v0builtin.MethodsVerifiedRegistry.AddVerifiedClient, mustEnc(&v0verifreg.AddVerifiedClientParams{ Address: c, Allowance: abi.NewStoragePower(int64(amt)), })) @@ -494,8 +495,8 @@ func MakeGenesisBlock(ctx context.Context, bs bstore.Blockstore, sys vm.SyscallB return nil, xerrors.Errorf("setup miners failed: %w", err) } - store := adt.WrapStore(ctx, cbor.NewCborStore(bs)) - emptyroot, err := adt.MakeEmptyArray(store).Root() + store := v0adt.WrapStore(ctx, cbor.NewCborStore(bs)) + emptyroot, err := v0adt.MakeEmptyArray(store).Root() if err != nil { return nil, xerrors.Errorf("amt build failed: %w", err) } @@ -543,7 +544,7 @@ func MakeGenesisBlock(ctx context.Context, bs bstore.Blockstore, sys vm.SyscallB } b := &types.BlockHeader{ - Miner: builtin.SystemActorAddr, + Miner: v0builtin.SystemActorAddr, Ticket: genesisticket, Parents: []cid.Cid{filecoinGenesisCid}, Height: 0, diff --git a/chain/state/statetree.go b/chain/state/statetree.go index 7aa7701fd..b3a3b7cee 100644 --- a/chain/state/statetree.go +++ b/chain/state/statetree.go @@ -12,9 +12,8 @@ import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/go-state-types/network" + "github.com/filecoin-project/lotus/chain/actors/builtin" init_ "github.com/filecoin-project/lotus/chain/actors/builtin/init" - "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/types" @@ -24,8 +23,10 @@ var log = logging.Logger("statetree") // StateTree stores actors state by their ID. type StateTree struct { - root adt.Map - Store cbor.IpldStore + root adt.Map + version builtin.Version // TODO + info cid.Cid + Store cbor.IpldStore snaps *stateSnaps } @@ -117,31 +118,57 @@ func (ss *stateSnaps) deleteActor(addr address.Address) { ss.layers[len(ss.layers)-1].actors[addr] = streeOp{Delete: true} } -func NewStateTree(cst cbor.IpldStore, version network.Version) (*StateTree, error) { +func NewStateTree(cst cbor.IpldStore, version builtin.Version) (*StateTree, error) { + var info cid.Cid + switch version { + case builtin.Version0: + // info is undefined + default: + return nil, xerrors.Errorf("unsupported state tree version: %d", version) + } root, err := adt.NewMap(adt.WrapStore(context.TODO(), cst), version) if err != nil { return nil, err } return &StateTree{ - root: root, - Store: cst, - snaps: newStateSnaps(), + root: root, + info: info, + version: version, + Store: cst, + snaps: newStateSnaps(), }, nil } -func LoadStateTree(cst cbor.IpldStore, c cid.Cid, version network.Version) (*StateTree, error) { - // NETUPGRADE: switch map adt type on version upgrade. - nd, err := adt.AsMap(adt.WrapStore(context.TODO(), cst), c, version) +func LoadStateTree(cst cbor.IpldStore, c cid.Cid) (*StateTree, error) { + var root types.StateRoot + // Try loading as a new-style state-tree (version/actors tuple). + if err := cst.Get(context.TODO(), c, &root); err != nil { + // We failed to decode as the new version, must be an old version. + root.Actors = c + root.Version = builtin.Version0 + } + + // If that fails, load as an old-style state-tree (direct hampt, version 0. + nd, err := adt.AsMap(adt.WrapStore(context.TODO(), cst), root.Actors, builtin.Version(root.Version)) if err != nil { log.Errorf("loading hamt node %s failed: %s", c, err) return nil, err } + switch root.Version { + case builtin.Version0: + // supported + default: + return nil, xerrors.Errorf("unsupported state tree version: %d", root.Version) + } + return &StateTree{ - root: nd, - Store: cst, - snaps: newStateSnaps(), + root: nd, + info: root.Info, + version: builtin.Version(root.Version), + Store: cst, + snaps: newStateSnaps(), }, nil } @@ -167,7 +194,7 @@ func (st *StateTree) LookupID(addr address.Address) (address.Address, error) { return resa, nil } - act, err := st.GetActor(builtin.InitActorAddr) + act, err := st.GetActor(init_.Address) if err != nil { return address.Undef, xerrors.Errorf("getting init actor: %w", err) } @@ -271,7 +298,16 @@ func (st *StateTree) Flush(ctx context.Context) (cid.Cid, error) { } } - return st.root.Root() + root, err := st.root.Root() + if err != nil { + return cid.Undef, xerrors.Errorf("failed to flush state-tree hamt: %w", err) + } + // If we're version 0, return a raw tree. + if st.version == builtin.Version0 { + return root, nil + } + // Otherwise, return a versioned tree. + return st.Store.Put(ctx, &types.StateRoot{Version: uint64(st.version), Actors: root, Info: st.info}) } func (st *StateTree) Snapshot(ctx context.Context) error { @@ -289,7 +325,7 @@ func (st *StateTree) ClearSnapshot() { func (st *StateTree) RegisterNewAddress(addr address.Address) (address.Address, error) { var out address.Address - err := st.MutateActor(builtin.InitActorAddr, func(initact *types.Actor) error { + err := st.MutateActor(init_.Address, func(initact *types.Actor) error { ias, err := init_.Load(&AdtStore{st.Store}, initact) if err != nil { return err diff --git a/chain/stmgr/read.go b/chain/stmgr/read.go index 7bf757fb8..53eb8d384 100644 --- a/chain/stmgr/read.go +++ b/chain/stmgr/read.go @@ -8,7 +8,6 @@ import ( cbor "github.com/ipfs/go-ipld-cbor" "github.com/filecoin-project/go-address" - "github.com/filecoin-project/go-state-types/network" "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/types" ) @@ -23,8 +22,7 @@ func (sm *StateManager) ParentStateTsk(tsk types.TipSetKey) (*state.StateTree, e func (sm *StateManager) ParentState(ts *types.TipSet) (*state.StateTree, error) { cst := cbor.NewCborStore(sm.cs.Blockstore()) - version := sm.GetNtwkVersion(context.TODO(), ts.Height()-1) - state, err := state.LoadStateTree(cst, sm.parentState(ts), version) + state, err := state.LoadStateTree(cst, sm.parentState(ts)) if err != nil { return nil, xerrors.Errorf("load state tree: %w", err) } @@ -32,9 +30,9 @@ func (sm *StateManager) ParentState(ts *types.TipSet) (*state.StateTree, error) return state, nil } -func (sm *StateManager) StateTree(st cid.Cid, ntwkVersion network.Version) (*state.StateTree, error) { +func (sm *StateManager) StateTree(st cid.Cid) (*state.StateTree, error) { cst := cbor.NewCborStore(sm.cs.Blockstore()) - state, err := state.LoadStateTree(cst, st, ntwkVersion) + state, err := state.LoadStateTree(cst, st) if err != nil { return nil, xerrors.Errorf("load state tree: %w", err) } @@ -57,3 +55,11 @@ func (sm *StateManager) LoadActorTsk(_ context.Context, addr address.Address, ts } return state.GetActor(addr) } + +func (sm *StateManager) LoadActorRaw(_ context.Context, addr address.Address, st cid.Cid) (*types.Actor, error) { + state, err := sm.StateTree(st) + if err != nil { + return nil, err + } + return state.GetActor(addr) +} diff --git a/chain/stmgr/stmgr.go b/chain/stmgr/stmgr.go index 23e8e92a0..f71b788c8 100644 --- a/chain/stmgr/stmgr.go +++ b/chain/stmgr/stmgr.go @@ -383,7 +383,7 @@ func (sm *StateManager) ResolveToKeyAddress(ctx context.Context, addr address.Ad } cst := cbor.NewCborStore(sm.cs.Blockstore()) - tree, err := state.LoadStateTree(cst, st, sm.GetNtwkVersion(ctx, ts.Height())) + tree, err := state.LoadStateTree(cst, st) if err != nil { return address.Undef, xerrors.Errorf("failed to load state tree") } @@ -406,7 +406,7 @@ func (sm *StateManager) GetBlsPublicKey(ctx context.Context, addr address.Addres func (sm *StateManager) LookupID(ctx context.Context, addr address.Address, ts *types.TipSet) (address.Address, error) { cst := cbor.NewCborStore(sm.cs.Blockstore()) - state, err := state.LoadStateTree(cst, sm.parentState(ts), sm.GetNtwkVersion(ctx, ts.Height())) + state, err := state.LoadStateTree(cst, sm.parentState(ts)) if err != nil { return address.Undef, xerrors.Errorf("load state tree: %w", err) } @@ -817,7 +817,7 @@ func (sm *StateManager) setupGenesisActors(ctx context.Context) error { } cst := cbor.NewCborStore(sm.cs.Blockstore()) - sTree, err := state.LoadStateTree(cst, st, sm.GetNtwkVersion(ctx, gts.Height())) + sTree, err := state.LoadStateTree(cst, st) if err != nil { return xerrors.Errorf("loading state tree: %w", err) } @@ -923,7 +923,7 @@ func (sm *StateManager) setupGenesisActorsTestnet(ctx context.Context) error { } cst := cbor.NewCborStore(sm.cs.Blockstore()) - sTree, err := state.LoadStateTree(cst, st, sm.GetNtwkVersion(ctx, gts.Height())) + sTree, err := state.LoadStateTree(cst, st) if err != nil { return xerrors.Errorf("loading state tree: %w", err) } diff --git a/chain/stmgr/utils.go b/chain/stmgr/utils.go index 81bcb0900..63e3e0f74 100644 --- a/chain/stmgr/utils.go +++ b/chain/stmgr/utils.go @@ -21,23 +21,22 @@ import ( "github.com/filecoin-project/go-bitfield" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/crypto" - power2 "github.com/filecoin-project/lotus/chain/actors/builtin/power" + "github.com/filecoin-project/lotus/chain/actors/builtin/power" "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin/account" "github.com/filecoin-project/specs-actors/actors/builtin/cron" - init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" "github.com/filecoin-project/specs-actors/actors/builtin/market" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/specs-actors/actors/builtin/multisig" "github.com/filecoin-project/specs-actors/actors/builtin/paych" - "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/builtin/reward" "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" + init_ "github.com/filecoin-project/lotus/chain/actors/builtin/init" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/beacon" "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/store" @@ -48,8 +47,11 @@ import ( ) func GetNetworkName(ctx context.Context, sm *StateManager, st cid.Cid) (dtypes.NetworkName, error) { - var state init_.State - err := sm.WithStateTree(st, sm.WithActor(builtin.InitActorAddr, sm.WithActorState(ctx, &state))) + act, err := sm.LoadActorRaw(ctx, init_.Address, st) + if err != nil { + return "", err + } + ias, err := init_.Load(sm.cs.Store(ctx), act) if err != nil { return "", err } @@ -58,21 +60,18 @@ func GetNetworkName(ctx context.Context, sm *StateManager, st cid.Cid) (dtypes.N } func GetMinerWorkerRaw(ctx context.Context, sm *StateManager, st cid.Cid, maddr address.Address) (address.Address, error) { - var mas miner.State - _, err := sm.LoadActorStateRaw(ctx, maddr, &mas, st) + act, err := sm.LoadActorRaw(ctx, sm, maddr, st) if err != nil { return address.Undef, xerrors.Errorf("(get sset) failed to load miner actor state: %w", err) } - - cst := cbor.NewCborStore(sm.cs.Blockstore()) - state, err := state.LoadStateTree(cst, st) + mas, err := miner.Load(sm.cs.Store(ctx), act) if err != nil { return address.Undef, xerrors.Errorf("load state tree: %w", err) } - info, err := mas.GetInfo(sm.cs.Store(ctx)) + info, err := mas.Info() if err != nil { - return address.Address{}, err + return address.Undef, xerrors.Errorf("failed to load actor info: %w", err) } return vm.ResolveToKeyAddr(state, cst, info.Worker) @@ -83,36 +82,35 @@ func GetPower(ctx context.Context, sm *StateManager, ts *types.TipSet, maddr add } func GetPowerRaw(ctx context.Context, sm *StateManager, st cid.Cid, maddr address.Address) (power.Claim, power.Claim, error) { - var ps power.State - _, err := sm.LoadActorStateRaw(ctx, builtin.StoragePowerActorAddr, &ps, st) + act, err := sm.LoadActorRaw(ctx, builtin.StoragePowerActorAddr, st) if err != nil { return power.Claim{}, power.Claim{}, xerrors.Errorf("(get sset) failed to load power actor state: %w", err) } + mas, err := power.Load(sm.cs.Store(ctx), act) + if err != nil { + return power.Claim{}, power.Claim{}, err + } + + tpow, err := mas.TotalPower() + if err != nil { + return power.Claim{}, power.Claim{}, err + } + var mpow power.Claim if maddr != address.Undef { - cm, err := adt.AsMap(sm.cs.Store(ctx), ps.Claims) + mpow, err = mas.MinerPower(maddr) if err != nil { return power.Claim{}, power.Claim{}, err } - - var claim power.Claim - if _, err := cm.Get(abi.AddrKey(maddr), &claim); err != nil { - return power.Claim{}, power.Claim{}, err - } - - mpow = claim } - return mpow, power.Claim{ - RawBytePower: ps.TotalRawBytePower, - QualityAdjPower: ps.TotalQualityAdjPower, - }, nil + return mpow, tpow, nil } func PreCommitInfo(ctx context.Context, sm *StateManager, maddr address.Address, sid abi.SectorNumber, ts *types.TipSet) (miner.SectorPreCommitOnChainInfo, error) { var mas miner.State - _, err := sm.LoadActorState(ctx, maddr, &mas, ts) + act, err := sm.LoadActor(ctx, maddr, ts) if err != nil { return miner.SectorPreCommitOnChainInfo{}, xerrors.Errorf("(get sset) failed to load miner actor state: %w", err) } @@ -676,16 +674,16 @@ func MinerHasMinPower(ctx context.Context, sm *StateManager, addr address.Addres return false, xerrors.Errorf("loading power actor state: %w", err) } - ps, err := power2.Load(sm.cs.Store(ctx), pact) + ps, err := power.Load(sm.cs.Store(ctx), pact) if err != nil { return false, err } - return ps.MinerNominalPowerMeetsConsensusMinimum(sm.ChainStore().Store(ctx), addr) + return ps.MinerNominalPowerMeetsConsensusMinimum(addr) } func CheckTotalFIL(ctx context.Context, sm *StateManager, ts *types.TipSet) (abi.TokenAmount, error) { - str, err := state.LoadStateTree(sm.ChainStore().Store(ctx), ts.ParentState(), sm.GetNtwkVersion(ctx, ts.Height())) + str, err := state.LoadStateTree(sm.ChainStore().Store(ctx), ts.ParentState()) if err != nil { return abi.TokenAmount{}, err } diff --git a/chain/store/store.go b/chain/store/store.go index 2c97e2de5..66e31569b 100644 --- a/chain/store/store.go +++ b/chain/store/store.go @@ -5,8 +5,6 @@ import ( "context" "encoding/binary" "encoding/json" - "github.com/filecoin-project/go-state-types/network" - "github.com/filecoin-project/lotus/build" "io" "os" "strconv" @@ -766,29 +764,12 @@ type BlockMessages struct { WinCount int64 } -// TODO: temp hack until #3682 is merged -func hackgetNtwkVersionhack(ctx context.Context, height abi.ChainEpoch) network.Version { - // TODO: move hard fork epoch checks to a schedule defined in build/ - - if build.UpgradeBreezeHeight == 0 { - return network.Version1 - } - - if height <= build.UpgradeBreezeHeight { - return network.Version0 - } - - return network.Version1 -} - func (cs *ChainStore) BlockMsgsForTipset(ts *types.TipSet) ([]BlockMessages, error) { applied := make(map[address.Address]uint64) cst := cbor.NewCborStore(cs.bs) - nv := hackgetNtwkVersionhack(context.TODO(), ts.Height()) // TODO: part of the temp hack from above - - st, err := state.LoadStateTree(cst, ts.Blocks()[0].ParentStateRoot, nv) + st, err := state.LoadStateTree(cst, ts.Blocks()[0].ParentStateRoot) if err != nil { return nil, xerrors.Errorf("failed to load state tree") } diff --git a/chain/store/weight.go b/chain/store/weight.go index e27d3fd37..5249df011 100644 --- a/chain/store/weight.go +++ b/chain/store/weight.go @@ -29,7 +29,7 @@ func (cs *ChainStore) Weight(ctx context.Context, ts *types.TipSet) (types.BigIn tpow := big2.Zero() { cst := cbor.NewCborStore(cs.Blockstore()) - state, err := state.LoadStateTree(cst, ts.ParentState(), hackgetNtwkVersionhack(nil, ts.Height())) // TODO: hackgetNtwkVersionhack: HELP + state, err := state.LoadStateTree(cst, ts.ParentState()) if err != nil { return types.NewInt(0), xerrors.Errorf("load state tree: %w", err) } diff --git a/chain/sub/incoming.go b/chain/sub/incoming.go index 7c672bee2..1af5d8188 100644 --- a/chain/sub/incoming.go +++ b/chain/sub/incoming.go @@ -435,7 +435,7 @@ func (bv *BlockValidator) checkPowerAndGetWorkerKey(ctx context.Context, bh *typ buf := bufbstore.NewBufferedBstore(bv.chain.Blockstore()) cst := cbor.NewCborStore(buf) - state, err := state.LoadStateTree(cst, st, bv.stmgr.GetNtwkVersion(ctx, ts.Height())) + state, err := state.LoadStateTree(cst, st) if err != nil { return address.Undef, err } diff --git a/chain/sync.go b/chain/sync.go index 1d8e456d8..bb3e50bdb 100644 --- a/chain/sync.go +++ b/chain/sync.go @@ -1045,10 +1045,9 @@ func (syncer *Syncer) checkBlockMessages(ctx context.Context, b *types.FullBlock if err != nil { return err } - nwVersion := syncer.sm.GetNtwkVersion(ctx, baseTs.Height()) cst := cbor.NewCborStore(syncer.store.Blockstore()) - st, err := state.LoadStateTree(cst, stateroot, nwVersion) + st, err := state.LoadStateTree(cst, stateroot) if err != nil { return xerrors.Errorf("failed to load base state tree: %w", err) } diff --git a/chain/types/state.go b/chain/types/state.go new file mode 100644 index 000000000..b99eb19c2 --- /dev/null +++ b/chain/types/state.go @@ -0,0 +1,15 @@ +package types + +import "github.com/ipfs/go-cid" + +type StateRoot struct { + // State root version. Versioned along with actors (for now). + Version uint64 + // Actors tree. The structure depends on the state root version. + Actors cid.Cid + // Info. The structure depends on the state root version. + Info cid.Cid +} + +// TODO: version this. +type StateInfo struct{} diff --git a/chain/vm/vm.go b/chain/vm/vm.go index aa334aad5..5afde5f49 100644 --- a/chain/vm/vm.go +++ b/chain/vm/vm.go @@ -170,8 +170,7 @@ type VMOpts struct { func NewVM(ctx context.Context, opts *VMOpts) (*VM, error) { buf := bufbstore.NewBufferedBstore(opts.Bstore) cst := cbor.NewCborStore(buf) - nwv := opts.NtwkVersion(ctx, opts.Epoch) // TODO: why do we need a context for this? - state, err := state.LoadStateTree(cst, opts.StateBase, nwv) + state, err := state.LoadStateTree(cst, opts.StateBase) if err != nil { return nil, err } diff --git a/cmd/lotus-shed/balances.go b/cmd/lotus-shed/balances.go index f3ffd140f..7dbfe2eb7 100644 --- a/cmd/lotus-shed/balances.go +++ b/cmd/lotus-shed/balances.go @@ -171,9 +171,8 @@ var chainBalanceStateCmd = &cli.Command{ sm := stmgr.NewStateManager(cs) - // NETUPGRADE: FIXME. // Options: (a) encode the version in the chain or (b) pass a flag. - tree, err := state.LoadStateTree(cst, sroot, network.Version0) + tree, err := state.LoadStateTree(cst, sroot) if err != nil { return err } diff --git a/cmd/lotus-shed/genesis-verify.go b/cmd/lotus-shed/genesis-verify.go index 62808db9b..043cb72bb 100644 --- a/cmd/lotus-shed/genesis-verify.go +++ b/cmd/lotus-shed/genesis-verify.go @@ -79,7 +79,7 @@ var genesisVerifyCmd = &cli.Command{ cst := cbor.NewCborStore(bs) - stree, err := state.LoadStateTree(cst, ts.ParentState(), sm.GetNtwkVersion()) + stree, err := state.LoadStateTree(cst, ts.ParentState()) if err != nil { return err } diff --git a/gen/main.go b/gen/main.go index e7586a92a..be227663c 100644 --- a/gen/main.go +++ b/gen/main.go @@ -26,6 +26,8 @@ func main() { types.BlockMsg{}, types.ExpTipSet{}, types.BeaconEntry{}, + types.StateRoot{}, + types.StateInfo{}, ) if err != nil { fmt.Println(err) diff --git a/node/impl/full/state.go b/node/impl/full/state.go index 38e62f905..75f06e636 100644 --- a/node/impl/full/state.go +++ b/node/impl/full/state.go @@ -317,7 +317,7 @@ func (a *StateAPI) stateForTs(ctx context.Context, ts *types.TipSet) (*state.Sta buf := bufbstore.NewBufferedBstore(a.Chain.Blockstore()) cst := cbor.NewCborStore(buf) - return state.LoadStateTree(cst, st, a.StateManager.GetNtwkVersion(ctx, ts.Height())) + return state.LoadStateTree(cst, st) } func (a *StateAPI) StateGetActor(ctx context.Context, actor address.Address, tsk types.TipSetKey) (*types.Actor, error) { From 7fa6c1e8d04c3a68c1a37928af3c10c44b5fcff6 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Mon, 14 Sep 2020 15:45:00 -0700 Subject: [PATCH 020/303] add info method to miner state API --- chain/actors/builtin/miner/miner.go | 1 + 1 file changed, 1 insertion(+) diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index 76503d80e..154648986 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -35,6 +35,7 @@ type State interface { LoadDeadline(idx uint64) (Deadline, error) ForEachDeadline(cb func(idx uint64, dl Deadline) error) error NumDeadlines() (uint64, error) + Info() (MinerInfo, error) } type Deadline interface { From 36f920bcd7487c0bb0fb81326109882fda9b98b9 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Mon, 14 Sep 2020 21:55:49 -0700 Subject: [PATCH 021/303] progress --- api/api_full.go | 2 +- chain/actors/builtin/miner/miner.go | 8 +++++ chain/actors/builtin/miner/v0.go | 19 +++++++++++ chain/stmgr/utils.go | 52 +++++++++++++---------------- extern/storage-sealing/sealing.go | 1 - storage/miner.go | 2 -- 6 files changed, 52 insertions(+), 32 deletions(-) diff --git a/api/api_full.go b/api/api_full.go index a5cf2423d..035c7de43 100644 --- a/api/api_full.go +++ b/api/api_full.go @@ -17,8 +17,8 @@ import ( "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/go-state-types/dline" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/specs-actors/actors/builtin/market" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/specs-actors/actors/builtin/paych" "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index 154648986..eb70d1457 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -9,6 +9,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/cbor" v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/types" @@ -32,6 +33,9 @@ func Load(store adt.Store, act *types.Actor) (st State, err error) { type State interface { cbor.Marshaler + GetSector(abi.SectorNumber) (*SectorOnChainInfo, error) + GetPrecommittedSector(abi.SectorNumber) (*SectorPreCommitOnChainInfo, error) + LoadDeadline(idx uint64) (Deadline, error) ForEachDeadline(cb func(idx uint64, dl Deadline) error) error NumDeadlines() (uint64, error) @@ -51,6 +55,10 @@ type Partition interface { ActiveSectors() (bitfield.BitField, error) } +type SectorOnChainInfo = v0miner.SectorOnChainInfo +type SectorPreCommitInfo = v0miner.SectorPreCommitInfo +type SectorPreCommitOnChainInfo = v0miner.SectorPreCommitOnChainInfo + type MinerInfo struct { Owner address.Address // Must be an ID-address. Worker address.Address // Must be an ID-address. diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index 1d8a68183..40b9e4cc6 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -3,6 +3,7 @@ package miner import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-bitfield" + "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/libp2p/go-libp2p-core/peer" @@ -24,6 +25,24 @@ type v0Partition struct { store adt.Store } +func (s *v0State) GetSector(num abi.SectorNumber) (*SectorOnChainInfo, error) { + info, ok, err := s.State.GetSector(s.store, num) + if !ok || err != nil { + return nil, err + } + + return info, nil +} + +func (s *v0State) GetPrecommittedSector(num abi.SectorNumber) (*SectorPreCommitOnChainInfo, error) { + info, ok, err := s.State.GetPrecommittedSector(s.store, num) + if !ok || err != nil { + return nil, err + } + + return info, nil +} + func (s *v0State) LoadDeadline(idx uint64) (Deadline, error) { dls, err := s.State.LoadDeadlines(s.store) if err != nil { diff --git a/chain/stmgr/utils.go b/chain/stmgr/utils.go index 63e3e0f74..11eedb512 100644 --- a/chain/stmgr/utils.go +++ b/chain/stmgr/utils.go @@ -56,17 +56,21 @@ func GetNetworkName(ctx context.Context, sm *StateManager, st cid.Cid) (dtypes.N return "", err } - return dtypes.NetworkName(state.NetworkName), nil + return ias.NetworkName() } func GetMinerWorkerRaw(ctx context.Context, sm *StateManager, st cid.Cid, maddr address.Address) (address.Address, error) { - act, err := sm.LoadActorRaw(ctx, sm, maddr, st) + state, err := sm.StateTree(st) if err != nil { - return address.Undef, xerrors.Errorf("(get sset) failed to load miner actor state: %w", err) + return address.Undef, xerrors.Errorf("(get sset) failed to load state tree: %w", err) + } + act, err := state.GetActor(maddr) + if err != nil { + return address.Undef, xerrors.Errorf("(get sset) failed to load miner actor: %w", err) } mas, err := miner.Load(sm.cs.Store(ctx), act) if err != nil { - return address.Undef, xerrors.Errorf("load state tree: %w", err) + return address.Undef, xerrors.Errorf("(get sset) failed to load miner actor state: %w", err) } info, err := mas.Info() @@ -74,7 +78,7 @@ func GetMinerWorkerRaw(ctx context.Context, sm *StateManager, st cid.Cid, maddr return address.Undef, xerrors.Errorf("failed to load actor info: %w", err) } - return vm.ResolveToKeyAddr(state, cst, info.Worker) + return vm.ResolveToKeyAddr(state, sm.cs.Store(ctx), info.Worker) } func GetPower(ctx context.Context, sm *StateManager, ts *types.TipSet, maddr address.Address) (power.Claim, power.Claim, error) { @@ -108,40 +112,32 @@ func GetPowerRaw(ctx context.Context, sm *StateManager, st cid.Cid, maddr addres return mpow, tpow, nil } -func PreCommitInfo(ctx context.Context, sm *StateManager, maddr address.Address, sid abi.SectorNumber, ts *types.TipSet) (miner.SectorPreCommitOnChainInfo, error) { - var mas miner.State +func PreCommitInfo(ctx context.Context, sm *StateManager, maddr address.Address, sid abi.SectorNumber, ts *types.TipSet) (*miner.SectorPreCommitOnChainInfo, error) { act, err := sm.LoadActor(ctx, maddr, ts) if err != nil { - return miner.SectorPreCommitOnChainInfo{}, xerrors.Errorf("(get sset) failed to load miner actor state: %w", err) + return nil, xerrors.Errorf("(get sset) failed to load miner actor: %w", err) } - i, ok, err := mas.GetPrecommittedSector(sm.cs.Store(ctx), sid) - if err != nil { - return miner.SectorPreCommitOnChainInfo{}, err - } - if !ok { - return miner.SectorPreCommitOnChainInfo{}, xerrors.New("precommit not found") - } - - return *i, nil -} - -func MinerSectorInfo(ctx context.Context, sm *StateManager, maddr address.Address, sid abi.SectorNumber, ts *types.TipSet) (*miner.SectorOnChainInfo, error) { - var mas miner.State - _, err := sm.LoadActorState(ctx, maddr, &mas, ts) + mas, err := miner.Load(sm.cs.Store(ctx), act) if err != nil { return nil, xerrors.Errorf("(get sset) failed to load miner actor state: %w", err) } - sectorInfo, ok, err := mas.GetSector(sm.cs.Store(ctx), sid) + return mas.GetPrecommittedSector(sid) +} + +func MinerSectorInfo(ctx context.Context, sm *StateManager, maddr address.Address, sid abi.SectorNumber, ts *types.TipSet) (*miner.SectorOnChainInfo, error) { + act, err := sm.LoadActor(ctx, maddr, ts) if err != nil { - return nil, err - } - if !ok { - return nil, nil + return nil, xerrors.Errorf("(get sset) failed to load miner actor: %w", err) } - return sectorInfo, nil + mas, err := miner.Load(sm.cs.Store(ctx), act) + if err != nil { + return nil, xerrors.Errorf("(get sset) failed to load miner actor state: %w", err) + } + + return mas.GetSector(sid) } func GetMinerSectorSet(ctx context.Context, sm *StateManager, ts *types.TipSet, maddr address.Address, filter *bitfield.BitField, filterOut bool) ([]*api.ChainSectorInfo, error) { diff --git a/extern/storage-sealing/sealing.go b/extern/storage-sealing/sealing.go index cb73182d3..533333860 100644 --- a/extern/storage-sealing/sealing.go +++ b/extern/storage-sealing/sealing.go @@ -50,7 +50,6 @@ type SealingAPI interface { StateSectorPartition(ctx context.Context, maddr address.Address, sectorNumber abi.SectorNumber, tok TipSetToken) (*SectorLocation, error) StateMinerSectorSize(context.Context, address.Address, TipSetToken) (abi.SectorSize, error) StateMinerWorkerAddress(ctx context.Context, maddr address.Address, tok TipSetToken) (address.Address, error) - StateMinerDeadlines(ctx context.Context, maddr address.Address, tok TipSetToken) ([]*miner.Deadline, error) StateMinerPreCommitDepositForPower(context.Context, address.Address, miner.SectorPreCommitInfo, TipSetToken) (big.Int, error) StateMinerInitialPledgeCollateral(context.Context, address.Address, miner.SectorPreCommitInfo, TipSetToken) (big.Int, error) StateMarketStorageDeal(context.Context, abi.DealID, TipSetToken) (market.DealProposal, error) diff --git a/storage/miner.go b/storage/miner.go index bf026fc30..d2af4be2c 100644 --- a/storage/miner.go +++ b/storage/miner.go @@ -67,8 +67,6 @@ type SealingStateEvt struct { type storageMinerApi interface { // Call a read only method on actors (no interaction with the chain required) StateCall(context.Context, *types.Message, types.TipSetKey) (*api.InvocResult, error) - StateMinerDeadlines(ctx context.Context, maddr address.Address, tok types.TipSetKey) ([]*miner.Deadline, error) - StateMinerPartitions(context.Context, address.Address, uint64, types.TipSetKey) ([]*miner.Partition, error) StateMinerSectors(context.Context, address.Address, *bitfield.BitField, bool, types.TipSetKey) ([]*api.ChainSectorInfo, error) StateSectorPreCommitInfo(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (miner.SectorPreCommitOnChainInfo, error) StateSectorGetInfo(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (*miner.SectorOnChainInfo, error) From 4dabab5ce649137ee0f240122e1dbbbea1e84182 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Tue, 15 Sep 2020 13:04:45 +0200 Subject: [PATCH 022/303] state manager progress --- api/api_full.go | 9 +- api/apistruct/struct.go | 30 ++--- chain/actors/builtin/miner/miner.go | 6 + chain/actors/builtin/miner/utils.go | 28 +++++ chain/actors/builtin/miner/v0.go | 39 +++++++ chain/stmgr/utils.go | 167 ++++++++++++++-------------- node/impl/full/state.go | 8 +- storage/miner.go | 3 +- 8 files changed, 178 insertions(+), 112 deletions(-) create mode 100644 chain/actors/builtin/miner/utils.go diff --git a/api/api_full.go b/api/api_full.go index 035c7de43..c76b9038c 100644 --- a/api/api_full.go +++ b/api/api_full.go @@ -315,9 +315,9 @@ type FullNode interface { // StateMinerSectors returns info about the given miner's sectors. If the filter bitfield is nil, all sectors are included. // If the filterOut boolean is set to true, any sectors in the filter are excluded. // If false, only those sectors in the filter are included. - StateMinerSectors(context.Context, address.Address, *bitfield.BitField, bool, types.TipSetKey) ([]*ChainSectorInfo, error) + StateMinerSectors(context.Context, address.Address, *bitfield.BitField, bool, types.TipSetKey) ([]*miner2.ChainSectorInfo, error) // StateMinerActiveSectors returns info about sectors that a given miner is actively proving. - StateMinerActiveSectors(context.Context, address.Address, types.TipSetKey) ([]*ChainSectorInfo, error) + StateMinerActiveSectors(context.Context, address.Address, types.TipSetKey) ([]*miner2.ChainSectorInfo, error) // StateMinerProvingDeadline calculates the deadline at some epoch for a proving period // and returns the deadline-related calculations. StateMinerProvingDeadline(context.Context, address.Address, types.TipSetKey) (*dline.Info, error) @@ -538,11 +538,6 @@ type Message struct { Message *types.Message } -type ChainSectorInfo struct { - Info miner.SectorOnChainInfo - ID abi.SectorNumber -} - type ActorState struct { Balance types.BigInt State interface{} diff --git a/api/apistruct/struct.go b/api/apistruct/struct.go index 1eac858a0..ea8c311a0 100644 --- a/api/apistruct/struct.go +++ b/api/apistruct/struct.go @@ -161,19 +161,19 @@ type FullNodeStruct struct { ClientDataTransferUpdates func(ctx context.Context) (<-chan api.DataTransferChannel, error) `perm:"write"` ClientRetrieveTryRestartInsufficientFunds func(ctx context.Context, paymentChannel address.Address) error `perm:"write"` - StateNetworkName func(context.Context) (dtypes.NetworkName, error) `perm:"read"` - StateMinerSectors func(context.Context, address.Address, *bitfield.BitField, bool, types.TipSetKey) ([]*api.ChainSectorInfo, error) `perm:"read"` - StateMinerActiveSectors func(context.Context, address.Address, types.TipSetKey) ([]*api.ChainSectorInfo, error) `perm:"read"` - StateMinerProvingDeadline func(context.Context, address.Address, types.TipSetKey) (*dline.Info, error) `perm:"read"` - StateMinerPower func(context.Context, address.Address, types.TipSetKey) (*api.MinerPower, error) `perm:"read"` - StateMinerInfo func(context.Context, address.Address, types.TipSetKey) (miner2.MinerInfo, error) `perm:"read"` - StateMinerFaults func(context.Context, address.Address, types.TipSetKey) (bitfield.BitField, error) `perm:"read"` - StateAllMinerFaults func(context.Context, abi.ChainEpoch, types.TipSetKey) ([]*api.Fault, error) `perm:"read"` - StateMinerRecoveries func(context.Context, address.Address, types.TipSetKey) (bitfield.BitField, error) `perm:"read"` - StateMinerPreCommitDepositForPower func(context.Context, address.Address, miner.SectorPreCommitInfo, types.TipSetKey) (types.BigInt, error) `perm:"read"` - StateMinerInitialPledgeCollateral func(context.Context, address.Address, miner.SectorPreCommitInfo, types.TipSetKey) (types.BigInt, error) `perm:"read"` - StateMinerAvailableBalance func(context.Context, address.Address, types.TipSetKey) (types.BigInt, error) `perm:"read"` - StateSectorPreCommitInfo func(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (miner.SectorPreCommitOnChainInfo, error) `perm:"read"` + StateNetworkName func(context.Context) (dtypes.NetworkName, error) `perm:"read"` + StateMinerSectors func(context.Context, address.Address, *bitfield.BitField, bool, types.TipSetKey) ([]*miner2.ChainSectorInfo, error) `perm:"read"` + StateMinerActiveSectors func(context.Context, address.Address, types.TipSetKey) ([]*miner2.ChainSectorInfo, error) `perm:"read"` + StateMinerProvingDeadline func(context.Context, address.Address, types.TipSetKey) (*dline.Info, error) `perm:"read"` + StateMinerPower func(context.Context, address.Address, types.TipSetKey) (*api.MinerPower, error) `perm:"read"` + StateMinerInfo func(context.Context, address.Address, types.TipSetKey) (miner2.MinerInfo, error) `perm:"read"` + StateMinerFaults func(context.Context, address.Address, types.TipSetKey) (bitfield.BitField, error) `perm:"read"` + StateAllMinerFaults func(context.Context, abi.ChainEpoch, types.TipSetKey) ([]*api.Fault, error) `perm:"read"` + StateMinerRecoveries func(context.Context, address.Address, types.TipSetKey) (bitfield.BitField, error) `perm:"read"` + StateMinerPreCommitDepositForPower func(context.Context, address.Address, miner.SectorPreCommitInfo, types.TipSetKey) (types.BigInt, error) `perm:"read"` + StateMinerInitialPledgeCollateral func(context.Context, address.Address, miner.SectorPreCommitInfo, types.TipSetKey) (types.BigInt, error) `perm:"read"` + StateMinerAvailableBalance func(context.Context, address.Address, types.TipSetKey) (types.BigInt, error) `perm:"read"` + StateSectorPreCommitInfo func(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (miner.SectorPreCommitOnChainInfo, error) `perm:"read"` StateSectorGetInfo func(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (*miner.SectorOnChainInfo, error) `perm:"read"` StateSectorExpiration func(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (*api.SectorExpiration, error) `perm:"read"` StateSectorPartition func(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (*api.SectorLocation, error) `perm:"read"` @@ -730,11 +730,11 @@ func (c *FullNodeStruct) StateNetworkName(ctx context.Context) (dtypes.NetworkNa return c.Internal.StateNetworkName(ctx) } -func (c *FullNodeStruct) StateMinerSectors(ctx context.Context, addr address.Address, filter *bitfield.BitField, filterOut bool, tsk types.TipSetKey) ([]*api.ChainSectorInfo, error) { +func (c *FullNodeStruct) StateMinerSectors(ctx context.Context, addr address.Address, filter *bitfield.BitField, filterOut bool, tsk types.TipSetKey) ([]*miner2.ChainSectorInfo, error) { return c.Internal.StateMinerSectors(ctx, addr, filter, filterOut, tsk) } -func (c *FullNodeStruct) StateMinerActiveSectors(ctx context.Context, addr address.Address, tsk types.TipSetKey) ([]*api.ChainSectorInfo, error) { +func (c *FullNodeStruct) StateMinerActiveSectors(ctx context.Context, addr address.Address, tsk types.TipSetKey) ([]*miner2.ChainSectorInfo, error) { return c.Internal.StateMinerActiveSectors(ctx, addr, tsk) } diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index eb70d1457..6f3bbe4bb 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -35,6 +35,7 @@ type State interface { GetSector(abi.SectorNumber) (*SectorOnChainInfo, error) GetPrecommittedSector(abi.SectorNumber) (*SectorPreCommitOnChainInfo, error) + LoadSectorsFromSet(filter *bitfield.BitField, filterOut bool) ([]*ChainSectorInfo, error) LoadDeadline(idx uint64) (Deadline, error) ForEachDeadline(cb func(idx uint64, dl Deadline) error) error @@ -71,3 +72,8 @@ type MinerInfo struct { SectorSize abi.SectorSize WindowPoStPartitionSectors uint64 } + +type ChainSectorInfo struct { + Info SectorOnChainInfo + ID abi.SectorNumber +} diff --git a/chain/actors/builtin/miner/utils.go b/chain/actors/builtin/miner/utils.go new file mode 100644 index 000000000..052d2da60 --- /dev/null +++ b/chain/actors/builtin/miner/utils.go @@ -0,0 +1,28 @@ +package miner + +import ( + "golang.org/x/xerrors" + + "github.com/filecoin-project/go-bitfield" +) + +func AllPartSectors(mas State, sget func(Partition) (bitfield.BitField, error)) (bitfield.BitField, error) { + var parts []bitfield.BitField + + err := mas.ForEachDeadline(func(dlidx uint64, dl Deadline) error { + return dl.ForEachPartition(func(partidx uint64, part Partition) error { + s, err := sget(part) + if err != nil { + return xerrors.Errorf("getting sector list (dl: %d, part %d): %w", dlidx, partidx, err) + } + + parts = append(parts, s) + return nil + }) + }) + if err != nil { + return bitfield.BitField{}, err + } + + return bitfield.MultiMerge(parts...) +} \ No newline at end of file diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index 40b9e4cc6..0fb75795c 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -5,7 +5,11 @@ import ( "github.com/filecoin-project/go-bitfield" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/lotus/chain/actors/adt" + v0adt "github.com/filecoin-project/specs-actors/actors/util/adt" + cbor "github.com/ipfs/go-ipld-cbor" "github.com/libp2p/go-libp2p-core/peer" + cbg "github.com/whyrusleeping/cbor-gen" + "golang.org/x/xerrors" "github.com/filecoin-project/specs-actors/actors/builtin/miner" ) @@ -43,6 +47,41 @@ func (s *v0State) GetPrecommittedSector(num abi.SectorNumber) (*SectorPreCommitO return info, nil } +func (s *v0State) LoadSectorsFromSet(filter *bitfield.BitField, filterOut bool) ([]*ChainSectorInfo, error) { + a, err := v0adt.AsArray(s.store, s.State.Sectors) + if err != nil { + return nil, err + } + + var sset []*ChainSectorInfo + var v cbg.Deferred + if err := a.ForEach(&v, func(i int64) error { + if filter != nil { + set, err := filter.IsSet(uint64(i)) + if err != nil { + return xerrors.Errorf("filter check error: %w", err) + } + if set == filterOut { + return nil + } + } + + var oci miner.SectorOnChainInfo + if err := cbor.DecodeInto(v.Raw, &oci); err != nil { + return err + } + sset = append(sset, &ChainSectorInfo{ + Info: oci, + ID: abi.SectorNumber(i), + }) + return nil + }); err != nil { + return nil, err + } + + return sset, nil +} + func (s *v0State) LoadDeadline(idx uint64) (Deadline, error) { dls, err := s.State.LoadDeadlines(s.store) if err != nil { diff --git a/chain/stmgr/utils.go b/chain/stmgr/utils.go index 11eedb512..0217bd91e 100644 --- a/chain/stmgr/utils.go +++ b/chain/stmgr/utils.go @@ -140,60 +140,35 @@ func MinerSectorInfo(ctx context.Context, sm *StateManager, maddr address.Addres return mas.GetSector(sid) } -func GetMinerSectorSet(ctx context.Context, sm *StateManager, ts *types.TipSet, maddr address.Address, filter *bitfield.BitField, filterOut bool) ([]*api.ChainSectorInfo, error) { - var mas miner.State - _, err := sm.LoadActorState(ctx, maddr, &mas, ts) +func GetMinerSectorSet(ctx context.Context, sm *StateManager, ts *types.TipSet, maddr address.Address, filter *bitfield.BitField, filterOut bool) ([]*miner.ChainSectorInfo, error) { + act, err := sm.LoadActor(ctx, maddr, ts) + if err != nil { + return nil, xerrors.Errorf("(get sset) failed to load miner actor: %w", err) + } + + mas, err := miner.Load(sm.cs.Store(ctx), act) if err != nil { return nil, xerrors.Errorf("(get sset) failed to load miner actor state: %w", err) } - return LoadSectorsFromSet(ctx, sm.ChainStore().Blockstore(), mas.Sectors, filter, filterOut) + return mas.LoadSectorsFromSet(filter, filterOut) } func GetSectorsForWinningPoSt(ctx context.Context, pv ffiwrapper.Verifier, sm *StateManager, st cid.Cid, maddr address.Address, rand abi.PoStRandomness) ([]proof.SectorInfo, error) { - var partsProving []bitfield.BitField - var mas *miner.State - var info *miner.MinerInfo - - err := sm.WithStateTree(st, sm.WithActor(maddr, sm.WithActorState(ctx, func(store adt.Store, mst *miner.State) error { - var err error - - mas = mst - - info, err = mas.GetInfo(store) - if err != nil { - return xerrors.Errorf("getting miner info: %w", err) - } - - deadlines, err := mas.LoadDeadlines(store) - if err != nil { - return xerrors.Errorf("loading deadlines: %w", err) - } - - return deadlines.ForEach(store, func(dlIdx uint64, deadline *miner.Deadline) error { - partitions, err := deadline.PartitionsArray(store) - if err != nil { - return xerrors.Errorf("getting partition array: %w", err) - } - - var partition miner.Partition - return partitions.ForEach(&partition, func(partIdx int64) error { - p, err := bitfield.SubtractBitField(partition.Sectors, partition.Faults) - if err != nil { - return xerrors.Errorf("subtract faults from partition sectors: %w", err) - } - - partsProving = append(partsProving, p) - - return nil - }) - }) - }))) + act, err := sm.LoadActorRaw(ctx, maddr, st) if err != nil { - return nil, err + return nil, xerrors.Errorf("failed to load miner actor: %w", err) } - provingSectors, err := bitfield.MultiMerge(partsProving...) + mas, err := miner.Load(sm.cs.Store(ctx), act) + if err != nil { + return nil, xerrors.Errorf("failed to load miner actor state: %w", err) + } + + // TODO (!!): This was partition.Sectors-partition.Faults originally, which was likely very wrong, and will need to be an upgrade + // ^ THE CURRENT THING HERE WON'T SYNC v + + provingSectors, err := miner.AllPartSectors(mas, miner.Partition.ActiveSectors) if err != nil { return nil, xerrors.Errorf("merge partition proving sets: %w", err) } @@ -208,6 +183,11 @@ func GetSectorsForWinningPoSt(ctx context.Context, pv ffiwrapper.Verifier, sm *S return nil, nil } + info, err := mas.Info() + if err != nil { + return nil, xerrors.Errorf("getting miner info: %w", err) + } + spt, err := ffiwrapper.SealProofTypeFromSectorSize(info.SectorSize) if err != nil { return nil, xerrors.Errorf("getting seal proof type: %w", err) @@ -228,31 +208,19 @@ func GetSectorsForWinningPoSt(ctx context.Context, pv ffiwrapper.Verifier, sm *S return nil, xerrors.Errorf("generating winning post challenges: %w", err) } - sectors, err := provingSectors.All(miner.SectorsMax) + sectors, err := mas.LoadSectorsFromSet(&provingSectors, false) if err != nil { - return nil, xerrors.Errorf("failed to enumerate all sector IDs: %w", err) - } - - sectorAmt, err := adt.AsArray(sm.cs.Store(ctx), mas.Sectors) - if err != nil { - return nil, xerrors.Errorf("failed to load sectors amt: %w", err) + return nil, xerrors.Errorf("loading proving sectors: %w", err) } out := make([]proof.SectorInfo, len(ids)) for i, n := range ids { - sid := sectors[n] - - var sinfo miner.SectorOnChainInfo - if found, err := sectorAmt.Get(sid, &sinfo); err != nil { - return nil, xerrors.Errorf("failed to get sector %d: %w", sid, err) - } else if !found { - return nil, xerrors.Errorf("failed to find sector %d", sid) - } + s := sectors[n] out[i] = proof.SectorInfo{ SealProof: spt, - SectorNumber: sinfo.SectorNumber, - SealedCID: sinfo.SealedCID, + SectorNumber: s.ID, + SealedCID: s.Info.SealedCID, } } @@ -260,20 +228,33 @@ func GetSectorsForWinningPoSt(ctx context.Context, pv ffiwrapper.Verifier, sm *S } func StateMinerInfo(ctx context.Context, sm *StateManager, ts *types.TipSet, maddr address.Address) (*miner.MinerInfo, error) { - var mas miner.State - _, err := sm.LoadActorStateRaw(ctx, maddr, &mas, ts.ParentState()) + act, err := sm.LoadActor(ctx, maddr, ts) if err != nil { - return nil, xerrors.Errorf("(get ssize) failed to load miner actor state: %w", err) + return nil, xerrors.Errorf("failed to load miner actor: %w", err) } - return mas.GetInfo(sm.cs.Store(ctx)) + mas, err := miner.Load(sm.cs.Store(ctx), act) + if err != nil { + return nil, xerrors.Errorf("failed to load miner actor state: %w", err) + } + + mi, err := mas.Info() + if err != nil { + return nil, err + } + + return &mi, err } func GetMinerSlashed(ctx context.Context, sm *StateManager, ts *types.TipSet, maddr address.Address) (bool, error) { - var spas power.State - _, err := sm.LoadActorState(ctx, builtin.StoragePowerActorAddr, &spas, ts) + act, err := sm.LoadActor(ctx, builtin.StoragePowerActorAddr, ts) if err != nil { - return false, xerrors.Errorf("(get miner slashed) failed to load power actor state") + return false, xerrors.Errorf("failed to load power actor: %w", err) + } + + spas, err := power.Load(sm.cs.Store(ctx), act) + if err != nil { + return false, xerrors.Errorf("failed to load power actor state: %w", err) } store := sm.cs.Store(ctx) @@ -295,10 +276,16 @@ func GetMinerSlashed(ctx context.Context, sm *StateManager, ts *types.TipSet, ma } func GetStorageDeal(ctx context.Context, sm *StateManager, dealID abi.DealID, ts *types.TipSet) (*api.MarketDeal, error) { - var state market.State - if _, err := sm.LoadActorState(ctx, builtin.StorageMarketActorAddr, &state, ts); err != nil { - return nil, err + act, err := sm.LoadActor(ctx, builtin.StorageMarketActorAddr, ts) + if err != nil { + return nil, xerrors.Errorf("failed to load market actor: %w", err) } + + state, err := market.Load(sm.cs.Store(ctx), act) + if err != nil { + return nil, xerrors.Errorf("failed to load market actor state: %w", err) + } + store := sm.ChainStore().Store(ctx) da, err := adt.AsArray(store, state.Proposals) @@ -338,9 +325,14 @@ func GetStorageDeal(ctx context.Context, sm *StateManager, dealID abi.DealID, ts } func ListMinerActors(ctx context.Context, sm *StateManager, ts *types.TipSet) ([]address.Address, error) { - var state power.State - if _, err := sm.LoadActorState(ctx, builtin.StoragePowerActorAddr, &state, ts); err != nil { - return nil, err + act, err := sm.LoadActor(ctx, builtin.StoragePowerActorAddr, ts) + if err != nil { + return nil, xerrors.Errorf("failed to load power actor: %w", err) + } + + state, err := power.Load(sm.cs.Store(ctx), act) + if err != nil { + return nil, xerrors.Errorf("failed to load power actor state: %w", err) } m, err := adt.AsMap(sm.cs.Store(ctx), state.Claims) @@ -364,13 +356,13 @@ func ListMinerActors(ctx context.Context, sm *StateManager, ts *types.TipSet) ([ return miners, nil } -func LoadSectorsFromSet(ctx context.Context, bs blockstore.Blockstore, ssc cid.Cid, filter *bitfield.BitField, filterOut bool) ([]*api.ChainSectorInfo, error) { +func LoadSectorsFromSet(ctx context.Context, bs blockstore.Blockstore, ssc cid.Cid, filter *bitfield.BitField, filterOut bool) ([]*miner.ChainSectorInfo, error) { a, err := adt.AsArray(store.ActorStore(ctx, bs), ssc) if err != nil { return nil, err } - var sset []*api.ChainSectorInfo + var sset []*miner.ChainSectorInfo var v cbg.Deferred if err := a.ForEach(&v, func(i int64) error { if filter != nil { @@ -387,7 +379,7 @@ func LoadSectorsFromSet(ctx context.Context, bs blockstore.Blockstore, ssc cid.C if err := cbor.DecodeInto(v.Raw, &oci); err != nil { return err } - sset = append(sset, &api.ChainSectorInfo{ + sset = append(sset, &miner.ChainSectorInfo{ Info: oci, ID: abi.SectorNumber(i), }) @@ -420,7 +412,7 @@ func ComputeState(ctx context.Context, sm *StateManager, height abi.ChainEpoch, NtwkVersion: sm.GetNtwkVersion, BaseFee: ts.Blocks()[0].ParentBaseFee, } - vmi, err := vm.NewVM(vmopt) + vmi, err := vm.NewVM(ctx, vmopt) if err != nil { return cid.Undef, nil, err } @@ -508,9 +500,14 @@ func MinerGetBaseInfo(ctx context.Context, sm *StateManager, bcs beacon.Schedule return nil, err } - var mas miner.State - if _, err := sm.LoadActorStateRaw(ctx, maddr, &mas, lbst); err != nil { - return nil, err + act, err := sm.LoadActorRaw(ctx, maddr, lbst) + if err != nil { + return nil, xerrors.Errorf("failed to load miner actor: %w", err) + } + + mas, err := miner.Load(sm.cs.Store(ctx), act) + if err != nil { + return nil, xerrors.Errorf("failed to load miner actor state: %w", err) } buf := new(bytes.Buffer) @@ -537,7 +534,7 @@ func MinerGetBaseInfo(ctx context.Context, sm *StateManager, bcs beacon.Schedule return nil, xerrors.Errorf("failed to get power: %w", err) } - info, err := mas.GetInfo(sm.cs.Store(ctx)) + info, err := mas.Info() if err != nil { return nil, err } @@ -652,9 +649,9 @@ func init() { } func GetReturnType(ctx context.Context, sm *StateManager, to address.Address, method abi.MethodNum, ts *types.TipSet) (cbg.CBORUnmarshaler, error) { - var act types.Actor - if err := sm.WithParentState(ts, sm.WithActor(to, GetActor(&act))); err != nil { - return nil, xerrors.Errorf("getting actor: %w", err) + act, err := sm.LoadActor(ctx, to, ts) + if err != nil { + return nil, xerrors.Errorf("(get sset) failed to load miner actor: %w", err) } m, found := MethodsMap[act.Code][method] diff --git a/node/impl/full/state.go b/node/impl/full/state.go index 75f06e636..f61ebea49 100644 --- a/node/impl/full/state.go +++ b/node/impl/full/state.go @@ -30,11 +30,11 @@ import ( "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/chain/actors" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/beacon" "github.com/filecoin-project/lotus/chain/gen" "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/stmgr" - "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/store" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/vm" @@ -62,7 +62,7 @@ func (a *StateAPI) StateNetworkName(ctx context.Context) (dtypes.NetworkName, er return stmgr.GetNetworkName(ctx, a.StateManager, a.Chain.GetHeaviestTipSet().ParentState()) } -func (a *StateAPI) StateMinerSectors(ctx context.Context, addr address.Address, filter *bitfield.BitField, filterOut bool, tsk types.TipSetKey) ([]*api.ChainSectorInfo, error) { +func (a *StateAPI) StateMinerSectors(ctx context.Context, addr address.Address, filter *bitfield.BitField, filterOut bool, tsk types.TipSetKey) ([]*miner.ChainSectorInfo, error) { ts, err := a.Chain.GetTipSetFromKey(tsk) if err != nil { return nil, xerrors.Errorf("loading tipset %s: %w", tsk, err) @@ -70,8 +70,8 @@ func (a *StateAPI) StateMinerSectors(ctx context.Context, addr address.Address, return stmgr.GetMinerSectorSet(ctx, a.StateManager, ts, addr, filter, filterOut) } -func (a *StateAPI) StateMinerActiveSectors(ctx context.Context, maddr address.Address, tsk types.TipSetKey) ([]*api.ChainSectorInfo, error) { - var out []*api.ChainSectorInfo +func (a *StateAPI) StateMinerActiveSectors(ctx context.Context, maddr address.Address, tsk types.TipSetKey) ([]*miner.ChainSectorInfo, error) { // TODO: only used in cli + var out []*miner.ChainSectorInfo err := a.StateManager.WithParentStateTsk(tsk, a.StateManager.WithActor(maddr, diff --git a/storage/miner.go b/storage/miner.go index d2af4be2c..47f50ce71 100644 --- a/storage/miner.go +++ b/storage/miner.go @@ -3,6 +3,7 @@ package storage import ( "context" "errors" + miner2 "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "time" "github.com/filecoin-project/go-state-types/dline" @@ -67,7 +68,7 @@ type SealingStateEvt struct { type storageMinerApi interface { // Call a read only method on actors (no interaction with the chain required) StateCall(context.Context, *types.Message, types.TipSetKey) (*api.InvocResult, error) - StateMinerSectors(context.Context, address.Address, *bitfield.BitField, bool, types.TipSetKey) ([]*api.ChainSectorInfo, error) + StateMinerSectors(context.Context, address.Address, *bitfield.BitField, bool, types.TipSetKey) ([]*miner2.ChainSectorInfo, error) StateSectorPreCommitInfo(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (miner.SectorPreCommitOnChainInfo, error) StateSectorGetInfo(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (*miner.SectorOnChainInfo, error) StateSectorPartition(ctx context.Context, maddr address.Address, sectorNumber abi.SectorNumber, tok types.TipSetKey) (*api.SectorLocation, error) From 441985019597030eff05ac316d1a873432806e6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Tue, 15 Sep 2020 15:29:25 +0200 Subject: [PATCH 023/303] state api impl fixes --- api/api_full.go | 2 +- chain/actors/builtin/miner/miner.go | 3 + chain/actors/builtin/miner/v0.go | 5 + chain/actors/builtin/power/power.go | 2 +- chain/actors/builtin/power/v0.go | 11 +- chain/stmgr/utils.go | 12 +- node/impl/full/state.go | 171 +++++++++++++--------------- 7 files changed, 99 insertions(+), 107 deletions(-) diff --git a/api/api_full.go b/api/api_full.go index c76b9038c..6625ae7f5 100644 --- a/api/api_full.go +++ b/api/api_full.go @@ -20,11 +20,11 @@ import ( "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/specs-actors/actors/builtin/market" "github.com/filecoin-project/specs-actors/actors/builtin/paych" - "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/specs-actors/actors/runtime/proof" miner2 "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + "github.com/filecoin-project/lotus/chain/actors/builtin/power" "github.com/filecoin-project/lotus/chain/types" marketevents "github.com/filecoin-project/lotus/markets/loggers" "github.com/filecoin-project/lotus/node/modules/dtypes" diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index 6f3bbe4bb..9824ce61c 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -1,6 +1,7 @@ package miner import ( + "github.com/filecoin-project/go-state-types/dline" "github.com/libp2p/go-libp2p-core/peer" "golang.org/x/xerrors" @@ -41,6 +42,8 @@ type State interface { ForEachDeadline(cb func(idx uint64, dl Deadline) error) error NumDeadlines() (uint64, error) Info() (MinerInfo, error) + + DeadlineInfo(epoch abi.ChainEpoch) *dline.Info } type Deadline interface { diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index 0fb75795c..a7ed66fbd 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -4,6 +4,7 @@ import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-bitfield" "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/dline" "github.com/filecoin-project/lotus/chain/actors/adt" v0adt "github.com/filecoin-project/specs-actors/actors/util/adt" cbor "github.com/ipfs/go-ipld-cbor" @@ -142,6 +143,10 @@ func (s *v0State) Info() (MinerInfo, error) { return mi, nil } +func (s *v0State) DeadlineInfo(epoch abi.ChainEpoch) *dline.Info { + return s.State.DeadlineInfo(epoch) +} + func (d *v0Deadline) LoadPartition(idx uint64) (Partition, error) { p, err := d.Deadline.LoadPartition(d.store, idx) if err != nil { diff --git a/chain/actors/builtin/power/power.go b/chain/actors/builtin/power/power.go index 7588615a6..fa0400f2e 100644 --- a/chain/actors/builtin/power/power.go +++ b/chain/actors/builtin/power/power.go @@ -30,7 +30,7 @@ type State interface { TotalLocked() (abi.TokenAmount, error) TotalPower() (Claim, error) - MinerPower(address.Address) (Claim, error) + MinerPower(address.Address) (Claim, bool, error) MinerNominalPowerMeetsConsensusMinimum(address.Address) (bool, error) } diff --git a/chain/actors/builtin/power/v0.go b/chain/actors/builtin/power/v0.go index f3152eb6a..12eb318e5 100644 --- a/chain/actors/builtin/power/v0.go +++ b/chain/actors/builtin/power/v0.go @@ -23,19 +23,20 @@ func (s *v0State) TotalPower() (Claim, error) { }, nil } -func (s *v0State) MinerPower(addr address.Address) (Claim, error) { +func (s *v0State) MinerPower(addr address.Address) (Claim, bool, error) { claims, err := adt.AsMap(s.store, s.Claims) if err != nil { - return Claim{}, err + return Claim{}, false, err } var claim power.Claim - if _, err := claims.Get(abi.AddrKey(addr), &claim); err != nil { - return Claim{}, err + ok, err := claims.Get(abi.AddrKey(addr), &claim) + if err != nil { + return Claim{}, false, err } return Claim{ RawBytePower: claim.RawBytePower, QualityAdjPower: claim.QualityAdjPower, - }, nil + }, ok, nil } func (s *v0State) MinerNominalPowerMeetsConsensusMinimum(a address.Address) (bool, error) { diff --git a/chain/stmgr/utils.go b/chain/stmgr/utils.go index 0217bd91e..4dc210154 100644 --- a/chain/stmgr/utils.go +++ b/chain/stmgr/utils.go @@ -26,7 +26,6 @@ import ( "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin/account" "github.com/filecoin-project/specs-actors/actors/builtin/cron" - "github.com/filecoin-project/specs-actors/actors/builtin/market" "github.com/filecoin-project/specs-actors/actors/builtin/multisig" "github.com/filecoin-project/specs-actors/actors/builtin/paych" "github.com/filecoin-project/specs-actors/actors/builtin/reward" @@ -36,6 +35,7 @@ import ( "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" init_ "github.com/filecoin-project/lotus/chain/actors/builtin/init" + "github.com/filecoin-project/lotus/chain/actors/builtin/market" "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/beacon" "github.com/filecoin-project/lotus/chain/state" @@ -257,17 +257,11 @@ func GetMinerSlashed(ctx context.Context, sm *StateManager, ts *types.TipSet, ma return false, xerrors.Errorf("failed to load power actor state: %w", err) } - store := sm.cs.Store(ctx) - - claims, err := adt.AsMap(store, spas.Claims) + _, ok, err := spas.MinerPower(maddr) if err != nil { - return false, err + return false, xerrors.Errorf("getting miner power: %w", err) } - ok, err := claims.Get(abi.AddrKey(maddr), nil) - if err != nil { - return false, err - } if !ok { return true, nil } diff --git a/node/impl/full/state.go b/node/impl/full/state.go index f61ebea49..98c9ed2e0 100644 --- a/node/impl/full/state.go +++ b/node/impl/full/state.go @@ -71,127 +71,121 @@ func (a *StateAPI) StateMinerSectors(ctx context.Context, addr address.Address, } func (a *StateAPI) StateMinerActiveSectors(ctx context.Context, maddr address.Address, tsk types.TipSetKey) ([]*miner.ChainSectorInfo, error) { // TODO: only used in cli - var out []*miner.ChainSectorInfo - - err := a.StateManager.WithParentStateTsk(tsk, - a.StateManager.WithActor(maddr, - a.StateManager.WithActorState(ctx, func(store adt.Store, mas *miner.State) error { - var allActive []bitfield.BitField - - err := a.StateManager.WithDeadlines( - a.StateManager.WithEachDeadline( - a.StateManager.WithEachPartition(func(store adt.Store, partIdx uint64, partition *miner.Partition) error { - active, err := partition.ActiveSectors() - if err != nil { - return xerrors.Errorf("partition.ActiveSectors: %w", err) - } - - allActive = append(allActive, active) - return nil - })))(store, mas) - if err != nil { - return xerrors.Errorf("with deadlines: %w", err) - } - - active, err := bitfield.MultiMerge(allActive...) - if err != nil { - return xerrors.Errorf("merging active sector bitfields: %w", err) - } - - out, err = stmgr.LoadSectorsFromSet(ctx, a.Chain.Blockstore(), mas.Sectors, &active, false) - return err - }))) + act, err := a.StateManager.LoadActorTsk(ctx, maddr, tsk) if err != nil { - return nil, xerrors.Errorf("getting active sectors from partitions: %w", err) + return nil, xerrors.Errorf("failed to load miner actor: %w", err) } - return out, nil + mas, err := miner.Load(a.StateManager.ChainStore().Store(ctx), act) + if err != nil { + return nil, xerrors.Errorf("failed to load miner actor state: %w", err) + } + + activeSectors, err := miner.AllPartSectors(mas, miner.Partition.ActiveSectors) + if err != nil { + return nil, xerrors.Errorf("merge partition active sets: %w", err) + } + + return mas.LoadSectorsFromSet(&activeSectors, false) } -func (a *StateAPI) StateMinerInfo(ctx context.Context, actor address.Address, tsk types.TipSetKey) (api.MinerInfo, error) { - ts, err := a.Chain.GetTipSetFromKey(tsk) +func (a *StateAPI) StateMinerInfo(ctx context.Context, actor address.Address, tsk types.TipSetKey) (miner.MinerInfo, error) { + act, err := a.StateManager.LoadActorTsk(ctx, actor, tsk) if err != nil { - return api.MinerInfo{}, xerrors.Errorf("loading tipset %s: %w", tsk, err) + return miner.MinerInfo{}, xerrors.Errorf("failed to load miner actor: %w", err) } - a.StateManager.LoadActorStateRaw(ctx context.Context, addr address.Address, out interface{}, st cid.Cid) - - mi, err := stmgr.StateMinerInfo(ctx, a.StateManager, ts, actor) + mas, err := miner.Load(a.StateManager.ChainStore().Store(ctx), act) if err != nil { - return api.MinerInfo{}, err + return miner.MinerInfo{}, xerrors.Errorf("failed to load miner actor state: %w", err) } - return api.NewApiMinerInfo(mi), nil + + return mas.Info() } func (a *StateAPI) StateMinerDeadlines(ctx context.Context, m address.Address, tsk types.TipSetKey) ([]miner.Deadline, error) { - var out []*miner.Deadline - state, err := a.StateManager.LoadParentStateTsk(tsk) + act, err := a.StateManager.LoadActorTsk(ctx, m, tsk) if err != nil { - return nil, err + return nil, xerrors.Errorf("failed to load miner actor: %w", err) } - act, err := state.GetActor(addr) + + mas, err := miner.Load(a.StateManager.ChainStore().Store(ctx), act) if err != nil { - return nil, err + return nil, xerrors.Errorf("failed to load miner actor state: %w", err) } - mas, err := miner.Load(a.Chain.Store(ctx), act) + + deadlines, err := mas.NumDeadlines() if err != nil { - return nil, err + return nil, xerrors.Errorf("getting deadline count: %w", err) } - var deadlines []miner.Deadline - if err := mas.ForEachDeadline(func(_ uint64, dl miner.Deadline) error { - deadlines = append(deadlines, dl) + + out := make([]miner.Deadline, deadlines) + if err := mas.ForEachDeadline(func(i uint64, dl miner.Deadline) error { + out[i] = dl return nil }); err != nil { - return err + return nil, err } - return deadlines, nil + return out, nil } func (a *StateAPI) StateMinerPartitions(ctx context.Context, m address.Address, dlIdx uint64, tsk types.TipSetKey) ([]*miner.Partition, error) { + act, err := a.StateManager.LoadActorTsk(ctx, m, tsk) + if err != nil { + return nil, xerrors.Errorf("failed to load miner actor: %w", err) + } + + mas, err := miner.Load(a.StateManager.ChainStore().Store(ctx), act) + if err != nil { + return nil, xerrors.Errorf("failed to load miner actor state: %w", err) + } + + dl, err := mas.LoadDeadline(dlIdx) + if err != nil { + return nil, xerrors.Errorf("failed to load the deadline: %w", err) + } + var out []*miner.Partition - return out, a.StateManager.WithParentStateTsk(tsk, - a.StateManager.WithActor(m, - a.StateManager.WithActorState(ctx, - a.StateManager.WithDeadlines( - a.StateManager.WithDeadline(dlIdx, - a.StateManager.WithEachPartition(func(store adt.Store, partIdx uint64, partition *miner.Partition) error { - out = append(out, partition) - return nil - })))))) + err = dl.ForEachPartition(func(_ uint64, part miner.Partition) error { + p := part + out = append(out, &p) + return nil + }) + + return out, err } func (a *StateAPI) StateMinerProvingDeadline(ctx context.Context, addr address.Address, tsk types.TipSetKey) (*dline.Info, error) { - ts, err := a.Chain.GetTipSetFromKey(tsk) + ts, err := a.StateManager.ChainStore().GetTipSetFromKey(tsk) if err != nil { return nil, xerrors.Errorf("loading tipset %s: %w", tsk, err) } - var mas miner.State - _, err = a.StateManager.LoadActorState(ctx, addr, &mas, ts) + act, err := a.StateManager.LoadActor(ctx, addr, ts) if err != nil { - return nil, xerrors.Errorf("(get sset) failed to load miner actor state: %w", err) + return nil, xerrors.Errorf("failed to load miner actor: %w", err) + } + + mas, err := miner.Load(a.StateManager.ChainStore().Store(ctx), act) + if err != nil { + return nil, xerrors.Errorf("failed to load miner actor state: %w", err) } return mas.DeadlineInfo(ts.Height()).NextNotElapsed(), nil } func (a *StateAPI) StateMinerFaults(ctx context.Context, addr address.Address, tsk types.TipSetKey) (bitfield.BitField, error) { - out := bitfield.New() - - err := a.StateManager.WithParentStateTsk(tsk, - a.StateManager.WithActor(addr, - a.StateManager.WithActorState(ctx, - a.StateManager.WithDeadlines( - a.StateManager.WithEachDeadline( - a.StateManager.WithEachPartition(func(store adt.Store, idx uint64, partition *miner.Partition) (err error) { - out, err = bitfield.MergeBitFields(out, partition.Faults) - return err - })))))) + act, err := a.StateManager.LoadActorTsk(ctx, addr, tsk) if err != nil { - return bitfield.BitField{}, err + return bitfield.BitField{}, xerrors.Errorf("failed to load miner actor: %w", err) } - return out, err + mas, err := miner.Load(a.StateManager.ChainStore().Store(ctx), act) + if err != nil { + return bitfield.BitField{}, xerrors.Errorf("failed to load miner actor state: %w", err) + } + + return miner.AllPartSectors(mas, miner.Partition.FaultySectors) } func (a *StateAPI) StateAllMinerFaults(ctx context.Context, lookback abi.ChainEpoch, endTsk types.TipSetKey) ([]*api.Fault, error) { @@ -238,22 +232,17 @@ func (a *StateAPI) StateAllMinerFaults(ctx context.Context, lookback abi.ChainEp } func (a *StateAPI) StateMinerRecoveries(ctx context.Context, addr address.Address, tsk types.TipSetKey) (bitfield.BitField, error) { - out := bitfield.New() - - err := a.StateManager.WithParentStateTsk(tsk, - a.StateManager.WithActor(addr, - a.StateManager.WithActorState(ctx, - a.StateManager.WithDeadlines( - a.StateManager.WithEachDeadline( - a.StateManager.WithEachPartition(func(store adt.Store, idx uint64, partition *miner.Partition) (err error) { - out, err = bitfield.MergeBitFields(out, partition.Recoveries) - return err - })))))) + act, err := a.StateManager.LoadActorTsk(ctx, addr, tsk) if err != nil { - return bitfield.BitField{}, err + return bitfield.BitField{}, xerrors.Errorf("failed to load miner actor: %w", err) } - return out, err + mas, err := miner.Load(a.StateManager.ChainStore().Store(ctx), act) + if err != nil { + return bitfield.BitField{}, xerrors.Errorf("failed to load miner actor state: %w", err) + } + + return miner.AllPartSectors(mas, miner.Partition.RecoveringSectors) } func (a *StateAPI) StateMinerPower(ctx context.Context, addr address.Address, tsk types.TipSetKey) (*api.MinerPower, error) { From 9dad38c9a5a4fb834c0a479486875ee04988ca59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Tue, 15 Sep 2020 15:29:39 +0200 Subject: [PATCH 024/303] gofmt --- api/apistruct/struct.go | 50 ++++++++++++++--------------- chain/actors/builtin/miner/utils.go | 2 +- chain/gen/genesis/util.go | 16 ++++----- 3 files changed, 34 insertions(+), 34 deletions(-) diff --git a/api/apistruct/struct.go b/api/apistruct/struct.go index ea8c311a0..d0bdd14d3 100644 --- a/api/apistruct/struct.go +++ b/api/apistruct/struct.go @@ -174,31 +174,31 @@ type FullNodeStruct struct { StateMinerInitialPledgeCollateral func(context.Context, address.Address, miner.SectorPreCommitInfo, types.TipSetKey) (types.BigInt, error) `perm:"read"` StateMinerAvailableBalance func(context.Context, address.Address, types.TipSetKey) (types.BigInt, error) `perm:"read"` StateSectorPreCommitInfo func(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (miner.SectorPreCommitOnChainInfo, error) `perm:"read"` - StateSectorGetInfo func(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (*miner.SectorOnChainInfo, error) `perm:"read"` - StateSectorExpiration func(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (*api.SectorExpiration, error) `perm:"read"` - StateSectorPartition func(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (*api.SectorLocation, error) `perm:"read"` - StateCall func(context.Context, *types.Message, types.TipSetKey) (*api.InvocResult, error) `perm:"read"` - StateReplay func(context.Context, types.TipSetKey, cid.Cid) (*api.InvocResult, error) `perm:"read"` - StateGetActor func(context.Context, address.Address, types.TipSetKey) (*types.Actor, error) `perm:"read"` - StateReadState func(context.Context, address.Address, types.TipSetKey) (*api.ActorState, error) `perm:"read"` - StateWaitMsg func(ctx context.Context, cid cid.Cid, confidence uint64) (*api.MsgLookup, error) `perm:"read"` - StateSearchMsg func(context.Context, cid.Cid) (*api.MsgLookup, error) `perm:"read"` - StateListMiners func(context.Context, types.TipSetKey) ([]address.Address, error) `perm:"read"` - StateListActors func(context.Context, types.TipSetKey) ([]address.Address, error) `perm:"read"` - StateMarketBalance func(context.Context, address.Address, types.TipSetKey) (api.MarketBalance, error) `perm:"read"` - StateMarketParticipants func(context.Context, types.TipSetKey) (map[string]api.MarketBalance, error) `perm:"read"` - StateMarketDeals func(context.Context, types.TipSetKey) (map[string]api.MarketDeal, error) `perm:"read"` - StateMarketStorageDeal func(context.Context, abi.DealID, types.TipSetKey) (*api.MarketDeal, error) `perm:"read"` - StateLookupID func(ctx context.Context, addr address.Address, tsk types.TipSetKey) (address.Address, error) `perm:"read"` - StateAccountKey func(context.Context, address.Address, types.TipSetKey) (address.Address, error) `perm:"read"` - StateChangedActors func(context.Context, cid.Cid, cid.Cid) (map[string]types.Actor, error) `perm:"read"` - StateGetReceipt func(context.Context, cid.Cid, types.TipSetKey) (*types.MessageReceipt, error) `perm:"read"` - StateMinerSectorCount func(context.Context, address.Address, types.TipSetKey) (api.MinerSectors, error) `perm:"read"` - StateListMessages func(ctx context.Context, match *types.Message, tsk types.TipSetKey, toht abi.ChainEpoch) ([]cid.Cid, error) `perm:"read"` - StateCompute func(context.Context, abi.ChainEpoch, []*types.Message, types.TipSetKey) (*api.ComputeStateOutput, error) `perm:"read"` - StateVerifiedClientStatus func(context.Context, address.Address, types.TipSetKey) (*verifreg.DataCap, error) `perm:"read"` - StateDealProviderCollateralBounds func(context.Context, abi.PaddedPieceSize, bool, types.TipSetKey) (api.DealCollateralBounds, error) `perm:"read"` - StateCirculatingSupply func(context.Context, types.TipSetKey) (api.CirculatingSupply, error) `perm:"read"` + StateSectorGetInfo func(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (*miner.SectorOnChainInfo, error) `perm:"read"` + StateSectorExpiration func(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (*api.SectorExpiration, error) `perm:"read"` + StateSectorPartition func(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (*api.SectorLocation, error) `perm:"read"` + StateCall func(context.Context, *types.Message, types.TipSetKey) (*api.InvocResult, error) `perm:"read"` + StateReplay func(context.Context, types.TipSetKey, cid.Cid) (*api.InvocResult, error) `perm:"read"` + StateGetActor func(context.Context, address.Address, types.TipSetKey) (*types.Actor, error) `perm:"read"` + StateReadState func(context.Context, address.Address, types.TipSetKey) (*api.ActorState, error) `perm:"read"` + StateWaitMsg func(ctx context.Context, cid cid.Cid, confidence uint64) (*api.MsgLookup, error) `perm:"read"` + StateSearchMsg func(context.Context, cid.Cid) (*api.MsgLookup, error) `perm:"read"` + StateListMiners func(context.Context, types.TipSetKey) ([]address.Address, error) `perm:"read"` + StateListActors func(context.Context, types.TipSetKey) ([]address.Address, error) `perm:"read"` + StateMarketBalance func(context.Context, address.Address, types.TipSetKey) (api.MarketBalance, error) `perm:"read"` + StateMarketParticipants func(context.Context, types.TipSetKey) (map[string]api.MarketBalance, error) `perm:"read"` + StateMarketDeals func(context.Context, types.TipSetKey) (map[string]api.MarketDeal, error) `perm:"read"` + StateMarketStorageDeal func(context.Context, abi.DealID, types.TipSetKey) (*api.MarketDeal, error) `perm:"read"` + StateLookupID func(ctx context.Context, addr address.Address, tsk types.TipSetKey) (address.Address, error) `perm:"read"` + StateAccountKey func(context.Context, address.Address, types.TipSetKey) (address.Address, error) `perm:"read"` + StateChangedActors func(context.Context, cid.Cid, cid.Cid) (map[string]types.Actor, error) `perm:"read"` + StateGetReceipt func(context.Context, cid.Cid, types.TipSetKey) (*types.MessageReceipt, error) `perm:"read"` + StateMinerSectorCount func(context.Context, address.Address, types.TipSetKey) (api.MinerSectors, error) `perm:"read"` + StateListMessages func(ctx context.Context, match *types.Message, tsk types.TipSetKey, toht abi.ChainEpoch) ([]cid.Cid, error) `perm:"read"` + StateCompute func(context.Context, abi.ChainEpoch, []*types.Message, types.TipSetKey) (*api.ComputeStateOutput, error) `perm:"read"` + StateVerifiedClientStatus func(context.Context, address.Address, types.TipSetKey) (*verifreg.DataCap, error) `perm:"read"` + StateDealProviderCollateralBounds func(context.Context, abi.PaddedPieceSize, bool, types.TipSetKey) (api.DealCollateralBounds, error) `perm:"read"` + StateCirculatingSupply func(context.Context, types.TipSetKey) (api.CirculatingSupply, error) `perm:"read"` MsigGetAvailableBalance func(context.Context, address.Address, types.TipSetKey) (types.BigInt, error) `perm:"read"` MsigGetVested func(context.Context, address.Address, types.TipSetKey, types.TipSetKey) (types.BigInt, error) `perm:"read"` diff --git a/chain/actors/builtin/miner/utils.go b/chain/actors/builtin/miner/utils.go index 052d2da60..f9c6b3da3 100644 --- a/chain/actors/builtin/miner/utils.go +++ b/chain/actors/builtin/miner/utils.go @@ -25,4 +25,4 @@ func AllPartSectors(mas State, sget func(Partition) (bitfield.BitField, error)) } return bitfield.MultiMerge(parts...) -} \ No newline at end of file +} diff --git a/chain/gen/genesis/util.go b/chain/gen/genesis/util.go index 6a27f2f29..d87500206 100644 --- a/chain/gen/genesis/util.go +++ b/chain/gen/genesis/util.go @@ -49,13 +49,13 @@ func doExecValue(ctx context.Context, vm *vm.VM, to, from address.Address, value return ret.Return, nil } -var GenesisNetworkVersion = func() network.Version {// TODO: Get from build/ - if build.UseNewestNetwork() {// TODO: Get from build/ - return build.NewestNetworkVersion// TODO: Get from build/ - }// TODO: Get from build/ - return network.Version1// TODO: Get from build/ -}()// TODO: Get from build/ +var GenesisNetworkVersion = func() network.Version { // TODO: Get from build/ + if build.UseNewestNetwork() { // TODO: Get from build/ + return build.NewestNetworkVersion // TODO: Get from build/ + } // TODO: Get from build/ + return network.Version1 // TODO: Get from build/ +}() // TODO: Get from build/ -func genesisNetworkVersion(context.Context, abi.ChainEpoch) network.Version {// TODO: Get from build/ +func genesisNetworkVersion(context.Context, abi.ChainEpoch) network.Version { // TODO: Get from build/ return GenesisNetworkVersion // TODO: Get from build/ -}// TODO: Get from build/ +} // TODO: Get from build/ From 00c6397ec96170efd2124ef9c3bc9432090750f1 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Tue, 15 Sep 2020 10:44:44 -0700 Subject: [PATCH 025/303] more progress --- api/api_full.go | 13 ----- chain/actors/builtin/miner/miner.go | 15 +++++ chain/actors/builtin/miner/v0.go | 83 ++++++++++++++++++++++++++ node/impl/full/state.go | 91 ++++------------------------- 4 files changed, 109 insertions(+), 93 deletions(-) diff --git a/api/api_full.go b/api/api_full.go index 6625ae7f5..a5af175d8 100644 --- a/api/api_full.go +++ b/api/api_full.go @@ -473,19 +473,6 @@ type MinerSectors struct { Active uint64 } -type SectorExpiration struct { - OnTime abi.ChainEpoch - - // non-zero if sector is faulty, epoch at which it will be permanently - // removed if it doesn't recover - Early abi.ChainEpoch -} - -type SectorLocation struct { - Deadline uint64 - Partition uint64 -} - type ImportRes struct { Root cid.Cid ImportID multistore.StoreID diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index 9824ce61c..5ad8db39e 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -35,6 +35,8 @@ type State interface { cbor.Marshaler GetSector(abi.SectorNumber) (*SectorOnChainInfo, error) + FindSector(abi.SectorNumber) (*SectorLocation, error) + GetSectorExpiration(abi.SectorNumber) (*SectorExpiration, error) GetPrecommittedSector(abi.SectorNumber) (*SectorPreCommitOnChainInfo, error) LoadSectorsFromSet(filter *bitfield.BitField, filterOut bool) ([]*ChainSectorInfo, error) @@ -80,3 +82,16 @@ type ChainSectorInfo struct { Info SectorOnChainInfo ID abi.SectorNumber } + +type SectorExpiration struct { + OnTime abi.ChainEpoch + + // non-zero if sector is faulty, epoch at which it will be permanently + // removed if it doesn't recover + Early abi.ChainEpoch +} + +type SectorLocation struct { + Deadline uint64 + Partition uint64 +} diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index a7ed66fbd..1a4bd3800 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -1,6 +1,8 @@ package miner import ( + "errors" + "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-bitfield" "github.com/filecoin-project/go-state-types/abi" @@ -39,6 +41,87 @@ func (s *v0State) GetSector(num abi.SectorNumber) (*SectorOnChainInfo, error) { return info, nil } +func (s *v0State) FindSector(num abi.SectorNumber) (*SectorLocation, error) { + dlIdx, partIdx, err := s.State.FindSector(s.store, num) + if err != nil { + return nil, err + } + return &SectorLocation{ + Deadline: dlIdx, + Partition: partIdx, + }, nil +} + +// GetSectorExpiration returns the effective expiration of the given sector. +// +// If the sector isn't found or has already been terminated, this method returns +// nil and no error. If the sector does not expire early, the Early expiration +// field is 0. +func (s *v0State) GetSectorExpiration(num abi.SectorNumber) (out *SectorExpiration, err error) { + dls, err := s.State.LoadDeadlines(s.store) + if err != nil { + return nil, err + } + // NOTE: this can be optimized significantly. + // 1. If the sector is non-faulty, it will either expire on-time (can be + // learned from the sector info), or in the next quantized expiration + // epoch (i.e., the first element in the partition's expiration queue. + // 2. If it's faulty, it will expire early within the first 14 entries + // of the expiration queue. + stopErr := errors.New("stop") + err := dls.ForEach(s.store, func(dlIdx uint64, dl *miner.Deadline) error { + partitions, err := dl.PartitionsArray(s.store) + if err != nil { + return err + } + quant := s.State.QuantSpecForDeadline(dlIdx) + var part miner.Partition + return partitions.ForEach(&part, func(partIdx int64) error { + if found, err := part.Sectors.IsSet(uint64(num)); err != nil { + return err + } else if !found { + return nil + } + if found, err := part.Terminated.IsSet(uint64(num)); err != nil { + return err + } else if found { + // already terminated + return stopErr + } + + q, err := miner.LoadExpirationQueue(s.store, part.EarlyTerminated, quant) + if err != nil { + return err + } + var exp miner.ExpirationSet + return q.ForEach(&exp, func(epoch int64) error { + if early, err := exp.EarlySectors.IsSet(uint64(num)); err != nil { + return err + } else if early { + out.Early = abi.ChainEpoch(epoch) + return nil + } + if onTime, err := exp.OnTime.IsSet(uint64(num)); err != nil { + return err + } else if onTime { + out.OnTime = epoch + return stopErr + } + }) + }) + }) + if err == stopErr { + err = nil + } + if err != nil { + return nil, err + } + if out.Early == 0 && out.OnTime == 0 { + return nil, nil + } + return out, nil +} + func (s *v0State) GetPrecommittedSector(num abi.SectorNumber) (*SectorPreCommitOnChainInfo, error) { info, ok, err := s.State.GetPrecommittedSector(s.store, num) if !ok || err != nil { diff --git a/node/impl/full/state.go b/node/impl/full/state.go index 98c9ed2e0..73ab7bc4d 100644 --- a/node/impl/full/state.go +++ b/node/impl/full/state.go @@ -698,97 +698,28 @@ func (a *StateAPI) StateSectorGetInfo(ctx context.Context, maddr address.Address return stmgr.MinerSectorInfo(ctx, a.StateManager, maddr, n, ts) } -type sectorPartitionCb func(store adt.Store, mas *miner.State, di uint64, pi uint64, part *miner.Partition) error - -func (a *StateAPI) sectorPartition(ctx context.Context, maddr address.Address, sectorNumber abi.SectorNumber, tsk types.TipSetKey, cb sectorPartitionCb) error { - return a.StateManager.WithParentStateTsk(tsk, - a.StateManager.WithActor(maddr, - a.StateManager.WithActorState(ctx, func(store adt.Store, mas *miner.State) error { - return a.StateManager.WithDeadlines(func(store adt.Store, deadlines *miner.Deadlines) error { - err := a.StateManager.WithEachDeadline(func(store adt.Store, di uint64, deadline *miner.Deadline) error { - return a.StateManager.WithEachPartition(func(store adt.Store, pi uint64, partition *miner.Partition) error { - set, err := partition.Sectors.IsSet(uint64(sectorNumber)) - if err != nil { - return xerrors.Errorf("is set: %w", err) - } - if set { - if err := cb(store, mas, di, pi, partition); err != nil { - return err - } - - return errBreakForeach - } - return nil - })(store, di, deadline) - })(store, deadlines) - if err == errBreakForeach { - err = nil - } - return err - })(store, mas) - }))) -} - func (a *StateAPI) StateSectorExpiration(ctx context.Context, maddr address.Address, sectorNumber abi.SectorNumber, tsk types.TipSetKey) (*api.SectorExpiration, error) { - var onTimeEpoch, earlyEpoch abi.ChainEpoch - - err := a.sectorPartition(ctx, maddr, sectorNumber, tsk, func(store adt.Store, mas *miner.State, di uint64, pi uint64, part *miner.Partition) error { - quant := mas.QuantSpecForDeadline(di) - expirations, err := miner.LoadExpirationQueue(store, part.ExpirationsEpochs, quant) - if err != nil { - return xerrors.Errorf("loading expiration queue: %w", err) - } - - var eset miner.ExpirationSet - return expirations.Array.ForEach(&eset, func(epoch int64) error { - set, err := eset.OnTimeSectors.IsSet(uint64(sectorNumber)) - if err != nil { - return xerrors.Errorf("checking if sector is in onTime set: %w", err) - } - if set { - onTimeEpoch = abi.ChainEpoch(epoch) - } - - set, err = eset.EarlySectors.IsSet(uint64(sectorNumber)) - if err != nil { - return xerrors.Errorf("checking if sector is in early set: %w", err) - } - if set { - earlyEpoch = abi.ChainEpoch(epoch) - } - - return nil - }) - }) + act, err := a.StateManager.LoadActorTsk(ctx, maddr, tsk) if err != nil { return nil, err } - - if onTimeEpoch == 0 { - return nil, xerrors.Errorf("expiration for sector %d not found", sectorNumber) + mas, err := miner.Load(a.StateManager.ChainStore().Store(ctx), act) + if err != nil { + return nil, err } - - return &api.SectorExpiration{ - OnTime: onTimeEpoch, - Early: earlyEpoch, - }, nil + return mas.GetSectorExpiration(sectorNumber) } func (a *StateAPI) StateSectorPartition(ctx context.Context, maddr address.Address, sectorNumber abi.SectorNumber, tsk types.TipSetKey) (*api.SectorLocation, error) { - var found *api.SectorLocation - - err := a.sectorPartition(ctx, maddr, sectorNumber, tsk, func(store adt.Store, mas *miner.State, di, pi uint64, partition *miner.Partition) error { - found = &api.SectorLocation{ - Deadline: di, - Partition: pi, - } - return errBreakForeach - }) + act, err := a.StateManager.LoadActorTsk(ctx, maddr, tsk) if err != nil { return nil, err } - - return found, nil + mas, err := miner.Load(a.StateManager.ChainStore().Store(ctx), act) + if err != nil { + return nil, err + } + return mas.FindSector(sectorNumber) } func (a *StateAPI) StateListMessages(ctx context.Context, match *types.Message, tsk types.TipSetKey, toheight abi.ChainEpoch) ([]cid.Cid, error) { From 6bf7976add095e8544e28f67517985dfb5e6591e Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Tue, 15 Sep 2020 10:51:18 -0700 Subject: [PATCH 026/303] fix decode --- chain/actors/builtin/miner/v0.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index 1a4bd3800..c0712a0c2 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -1,6 +1,7 @@ package miner import ( + "bytes" "errors" "github.com/filecoin-project/go-address" @@ -151,7 +152,7 @@ func (s *v0State) LoadSectorsFromSet(filter *bitfield.BitField, filterOut bool) } var oci miner.SectorOnChainInfo - if err := cbor.DecodeInto(v.Raw, &oci); err != nil { + if err := oci.UnmarshalCBOR(bytes.NewReader(v.Raw)); err != nil { return err } sset = append(sset, &ChainSectorInfo{ From 4cd92d8576aeb31044b821d09ef1d333e2a24f0c Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Tue, 15 Sep 2020 10:57:32 -0700 Subject: [PATCH 027/303] remove final WithStateTree --- chain/messagepool/provider.go | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/chain/messagepool/provider.go b/chain/messagepool/provider.go index d67468d9a..347e90044 100644 --- a/chain/messagepool/provider.go +++ b/chain/messagepool/provider.go @@ -47,13 +47,15 @@ func (mpp *mpoolProvider) PubSubPublish(k string, v []byte) error { } func (mpp *mpoolProvider) GetActorAfter(addr address.Address, ts *types.TipSet) (*types.Actor, error) { - var act types.Actor stcid, _, err := mpp.sm.TipSetState(context.TODO(), ts) if err != nil { return nil, xerrors.Errorf("computing tipset state for GetActor: %w", err) } - version := mpp.sm.GetNtwkVersion(context.TODO(), ts.Height()) - return &act, mpp.sm.WithStateTree(stcid, version, mpp.sm.WithActor(addr, stmgr.GetActor(&act))) + st, err := mpp.sm.StateTree(stcid) + if err != nil { + return nil, xerrors.Errorf("failed to load state tree: %w", err) + } + return st.GetActor(addr) } func (mpp *mpoolProvider) StateAccountKey(ctx context.Context, addr address.Address, ts *types.TipSet) (address.Address, error) { From 53384e83d7c6d5488c0ec605959666dee49dc248 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Tue, 15 Sep 2020 11:16:35 -0700 Subject: [PATCH 028/303] migrate wallet access --- node/impl/full/wallet.go | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/node/impl/full/wallet.go b/node/impl/full/wallet.go index af786085b..bda8824e7 100644 --- a/node/impl/full/wallet.go +++ b/node/impl/full/wallet.go @@ -36,16 +36,13 @@ func (a *WalletAPI) WalletList(ctx context.Context) ([]address.Address, error) { } func (a *WalletAPI) WalletBalance(ctx context.Context, addr address.Address) (types.BigInt, error) { - var bal types.BigInt - err := a.StateManager.WithParentStateTsk(types.EmptyTSK, a.StateManager.WithActor(addr, func(act *types.Actor) error { - bal = act.Balance - return nil - })) - + act, err := a.StateManager.LoadActorTsk(ctx, addr, types.EmptyTSK) if xerrors.Is(err, types.ErrActorNotFound) { return big.Zero(), nil + } else if err != nil { + return big.Zero(), err } - return bal, err + return act.Balance, nil } func (a *WalletAPI) WalletSign(ctx context.Context, k address.Address, msg []byte) (*crypto.Signature, error) { From c64f983900f8a0e2b7c1800dd2a4b1b96b201d1b Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Tue, 15 Sep 2020 12:09:39 -0700 Subject: [PATCH 029/303] migrate StateMinserSectorCount --- api/api_full.go | 8 ++- api/apistruct/struct.go | 88 ++++++++++++++++----------------- cmd/lotus-storage-miner/info.go | 21 +++----- node/impl/full/state.go | 85 +++++++++++++++---------------- storage/miner.go | 7 ++- 5 files changed, 99 insertions(+), 110 deletions(-) diff --git a/api/api_full.go b/api/api_full.go index a5af175d8..d3b655634 100644 --- a/api/api_full.go +++ b/api/api_full.go @@ -469,8 +469,12 @@ type FileRef struct { } type MinerSectors struct { - Sectors uint64 - Active uint64 + // Live sectors that should be proven. + Live uint64 + // Sectors actively contributing to power. + Active uint64 + // Sectors with failed proofs. + Faulty uint64 } type ImportRes struct { diff --git a/api/apistruct/struct.go b/api/apistruct/struct.go index d0bdd14d3..a554d2a5f 100644 --- a/api/apistruct/struct.go +++ b/api/apistruct/struct.go @@ -34,7 +34,7 @@ import ( "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" - miner2 "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/node/modules/dtypes" ) @@ -161,44 +161,44 @@ type FullNodeStruct struct { ClientDataTransferUpdates func(ctx context.Context) (<-chan api.DataTransferChannel, error) `perm:"write"` ClientRetrieveTryRestartInsufficientFunds func(ctx context.Context, paymentChannel address.Address) error `perm:"write"` - StateNetworkName func(context.Context) (dtypes.NetworkName, error) `perm:"read"` - StateMinerSectors func(context.Context, address.Address, *bitfield.BitField, bool, types.TipSetKey) ([]*miner2.ChainSectorInfo, error) `perm:"read"` - StateMinerActiveSectors func(context.Context, address.Address, types.TipSetKey) ([]*miner2.ChainSectorInfo, error) `perm:"read"` - StateMinerProvingDeadline func(context.Context, address.Address, types.TipSetKey) (*dline.Info, error) `perm:"read"` - StateMinerPower func(context.Context, address.Address, types.TipSetKey) (*api.MinerPower, error) `perm:"read"` - StateMinerInfo func(context.Context, address.Address, types.TipSetKey) (miner2.MinerInfo, error) `perm:"read"` - StateMinerFaults func(context.Context, address.Address, types.TipSetKey) (bitfield.BitField, error) `perm:"read"` - StateAllMinerFaults func(context.Context, abi.ChainEpoch, types.TipSetKey) ([]*api.Fault, error) `perm:"read"` - StateMinerRecoveries func(context.Context, address.Address, types.TipSetKey) (bitfield.BitField, error) `perm:"read"` - StateMinerPreCommitDepositForPower func(context.Context, address.Address, miner.SectorPreCommitInfo, types.TipSetKey) (types.BigInt, error) `perm:"read"` - StateMinerInitialPledgeCollateral func(context.Context, address.Address, miner.SectorPreCommitInfo, types.TipSetKey) (types.BigInt, error) `perm:"read"` - StateMinerAvailableBalance func(context.Context, address.Address, types.TipSetKey) (types.BigInt, error) `perm:"read"` - StateSectorPreCommitInfo func(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (miner.SectorPreCommitOnChainInfo, error) `perm:"read"` - StateSectorGetInfo func(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (*miner.SectorOnChainInfo, error) `perm:"read"` - StateSectorExpiration func(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (*api.SectorExpiration, error) `perm:"read"` - StateSectorPartition func(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (*api.SectorLocation, error) `perm:"read"` - StateCall func(context.Context, *types.Message, types.TipSetKey) (*api.InvocResult, error) `perm:"read"` - StateReplay func(context.Context, types.TipSetKey, cid.Cid) (*api.InvocResult, error) `perm:"read"` - StateGetActor func(context.Context, address.Address, types.TipSetKey) (*types.Actor, error) `perm:"read"` - StateReadState func(context.Context, address.Address, types.TipSetKey) (*api.ActorState, error) `perm:"read"` - StateWaitMsg func(ctx context.Context, cid cid.Cid, confidence uint64) (*api.MsgLookup, error) `perm:"read"` - StateSearchMsg func(context.Context, cid.Cid) (*api.MsgLookup, error) `perm:"read"` - StateListMiners func(context.Context, types.TipSetKey) ([]address.Address, error) `perm:"read"` - StateListActors func(context.Context, types.TipSetKey) ([]address.Address, error) `perm:"read"` - StateMarketBalance func(context.Context, address.Address, types.TipSetKey) (api.MarketBalance, error) `perm:"read"` - StateMarketParticipants func(context.Context, types.TipSetKey) (map[string]api.MarketBalance, error) `perm:"read"` - StateMarketDeals func(context.Context, types.TipSetKey) (map[string]api.MarketDeal, error) `perm:"read"` - StateMarketStorageDeal func(context.Context, abi.DealID, types.TipSetKey) (*api.MarketDeal, error) `perm:"read"` - StateLookupID func(ctx context.Context, addr address.Address, tsk types.TipSetKey) (address.Address, error) `perm:"read"` - StateAccountKey func(context.Context, address.Address, types.TipSetKey) (address.Address, error) `perm:"read"` - StateChangedActors func(context.Context, cid.Cid, cid.Cid) (map[string]types.Actor, error) `perm:"read"` - StateGetReceipt func(context.Context, cid.Cid, types.TipSetKey) (*types.MessageReceipt, error) `perm:"read"` - StateMinerSectorCount func(context.Context, address.Address, types.TipSetKey) (api.MinerSectors, error) `perm:"read"` - StateListMessages func(ctx context.Context, match *types.Message, tsk types.TipSetKey, toht abi.ChainEpoch) ([]cid.Cid, error) `perm:"read"` - StateCompute func(context.Context, abi.ChainEpoch, []*types.Message, types.TipSetKey) (*api.ComputeStateOutput, error) `perm:"read"` - StateVerifiedClientStatus func(context.Context, address.Address, types.TipSetKey) (*verifreg.DataCap, error) `perm:"read"` - StateDealProviderCollateralBounds func(context.Context, abi.PaddedPieceSize, bool, types.TipSetKey) (api.DealCollateralBounds, error) `perm:"read"` - StateCirculatingSupply func(context.Context, types.TipSetKey) (api.CirculatingSupply, error) `perm:"read"` + StateNetworkName func(context.Context) (dtypes.NetworkName, error) `perm:"read"` + StateMinerSectors func(context.Context, address.Address, *bitfield.BitField, bool, types.TipSetKey) ([]*miner.ChainSectorInfo, error) `perm:"read"` + StateMinerActiveSectors func(context.Context, address.Address, types.TipSetKey) ([]*miner.ChainSectorInfo, error) `perm:"read"` + StateMinerProvingDeadline func(context.Context, address.Address, types.TipSetKey) (*dline.Info, error) `perm:"read"` + StateMinerPower func(context.Context, address.Address, types.TipSetKey) (*api.MinerPower, error) `perm:"read"` + StateMinerInfo func(context.Context, address.Address, types.TipSetKey) (miner.MinerInfo, error) `perm:"read"` + StateMinerFaults func(context.Context, address.Address, types.TipSetKey) (bitfield.BitField, error) `perm:"read"` + StateAllMinerFaults func(context.Context, abi.ChainEpoch, types.TipSetKey) ([]*api.Fault, error) `perm:"read"` + StateMinerRecoveries func(context.Context, address.Address, types.TipSetKey) (bitfield.BitField, error) `perm:"read"` + StateMinerPreCommitDepositForPower func(context.Context, address.Address, miner.SectorPreCommitInfo, types.TipSetKey) (types.BigInt, error) `perm:"read"` + StateMinerInitialPledgeCollateral func(context.Context, address.Address, miner.SectorPreCommitInfo, types.TipSetKey) (types.BigInt, error) `perm:"read"` + StateMinerAvailableBalance func(context.Context, address.Address, types.TipSetKey) (types.BigInt, error) `perm:"read"` + StateSectorPreCommitInfo func(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (miner.SectorPreCommitOnChainInfo, error) `perm:"read"` + StateSectorGetInfo func(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (*miner.SectorOnChainInfo, error) `perm:"read"` + StateSectorExpiration func(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (*miner.SectorExpiration, error) `perm:"read"` + StateSectorPartition func(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (*miner.SectorLocation, error) `perm:"read"` + StateCall func(context.Context, *types.Message, types.TipSetKey) (*api.InvocResult, error) `perm:"read"` + StateReplay func(context.Context, types.TipSetKey, cid.Cid) (*api.InvocResult, error) `perm:"read"` + StateGetActor func(context.Context, address.Address, types.TipSetKey) (*types.Actor, error) `perm:"read"` + StateReadState func(context.Context, address.Address, types.TipSetKey) (*api.ActorState, error) `perm:"read"` + StateWaitMsg func(ctx context.Context, cid cid.Cid, confidence uint64) (*api.MsgLookup, error) `perm:"read"` + StateSearchMsg func(context.Context, cid.Cid) (*api.MsgLookup, error) `perm:"read"` + StateListMiners func(context.Context, types.TipSetKey) ([]address.Address, error) `perm:"read"` + StateListActors func(context.Context, types.TipSetKey) ([]address.Address, error) `perm:"read"` + StateMarketBalance func(context.Context, address.Address, types.TipSetKey) (api.MarketBalance, error) `perm:"read"` + StateMarketParticipants func(context.Context, types.TipSetKey) (map[string]api.MarketBalance, error) `perm:"read"` + StateMarketDeals func(context.Context, types.TipSetKey) (map[string]api.MarketDeal, error) `perm:"read"` + StateMarketStorageDeal func(context.Context, abi.DealID, types.TipSetKey) (*api.MarketDeal, error) `perm:"read"` + StateLookupID func(ctx context.Context, addr address.Address, tsk types.TipSetKey) (address.Address, error) `perm:"read"` + StateAccountKey func(context.Context, address.Address, types.TipSetKey) (address.Address, error) `perm:"read"` + StateChangedActors func(context.Context, cid.Cid, cid.Cid) (map[string]types.Actor, error) `perm:"read"` + StateGetReceipt func(context.Context, cid.Cid, types.TipSetKey) (*types.MessageReceipt, error) `perm:"read"` + StateMinerSectorCount func(context.Context, address.Address, types.TipSetKey) (api.MinerSectors, error) `perm:"read"` + StateListMessages func(ctx context.Context, match *types.Message, tsk types.TipSetKey, toht abi.ChainEpoch) ([]cid.Cid, error) `perm:"read"` + StateCompute func(context.Context, abi.ChainEpoch, []*types.Message, types.TipSetKey) (*api.ComputeStateOutput, error) `perm:"read"` + StateVerifiedClientStatus func(context.Context, address.Address, types.TipSetKey) (*verifreg.DataCap, error) `perm:"read"` + StateDealProviderCollateralBounds func(context.Context, abi.PaddedPieceSize, bool, types.TipSetKey) (api.DealCollateralBounds, error) `perm:"read"` + StateCirculatingSupply func(context.Context, types.TipSetKey) (api.CirculatingSupply, error) `perm:"read"` MsigGetAvailableBalance func(context.Context, address.Address, types.TipSetKey) (types.BigInt, error) `perm:"read"` MsigGetVested func(context.Context, address.Address, types.TipSetKey, types.TipSetKey) (types.BigInt, error) `perm:"read"` @@ -730,11 +730,11 @@ func (c *FullNodeStruct) StateNetworkName(ctx context.Context) (dtypes.NetworkNa return c.Internal.StateNetworkName(ctx) } -func (c *FullNodeStruct) StateMinerSectors(ctx context.Context, addr address.Address, filter *bitfield.BitField, filterOut bool, tsk types.TipSetKey) ([]*miner2.ChainSectorInfo, error) { +func (c *FullNodeStruct) StateMinerSectors(ctx context.Context, addr address.Address, filter *bitfield.BitField, filterOut bool, tsk types.TipSetKey) ([]*miner.ChainSectorInfo, error) { return c.Internal.StateMinerSectors(ctx, addr, filter, filterOut, tsk) } -func (c *FullNodeStruct) StateMinerActiveSectors(ctx context.Context, addr address.Address, tsk types.TipSetKey) ([]*miner2.ChainSectorInfo, error) { +func (c *FullNodeStruct) StateMinerActiveSectors(ctx context.Context, addr address.Address, tsk types.TipSetKey) ([]*miner.ChainSectorInfo, error) { return c.Internal.StateMinerActiveSectors(ctx, addr, tsk) } @@ -746,7 +746,7 @@ func (c *FullNodeStruct) StateMinerPower(ctx context.Context, a address.Address, return c.Internal.StateMinerPower(ctx, a, tsk) } -func (c *FullNodeStruct) StateMinerInfo(ctx context.Context, actor address.Address, tsk types.TipSetKey) (miner2.MinerInfo, error) { +func (c *FullNodeStruct) StateMinerInfo(ctx context.Context, actor address.Address, tsk types.TipSetKey) (miner.MinerInfo, error) { return c.Internal.StateMinerInfo(ctx, actor, tsk) } @@ -782,11 +782,11 @@ func (c *FullNodeStruct) StateSectorGetInfo(ctx context.Context, maddr address.A return c.Internal.StateSectorGetInfo(ctx, maddr, n, tsk) } -func (c *FullNodeStruct) StateSectorExpiration(ctx context.Context, maddr address.Address, n abi.SectorNumber, tsk types.TipSetKey) (*api.SectorExpiration, error) { +func (c *FullNodeStruct) StateSectorExpiration(ctx context.Context, maddr address.Address, n abi.SectorNumber, tsk types.TipSetKey) (*miner.SectorExpiration, error) { return c.Internal.StateSectorExpiration(ctx, maddr, n, tsk) } -func (c *FullNodeStruct) StateSectorPartition(ctx context.Context, maddr address.Address, sectorNumber abi.SectorNumber, tok types.TipSetKey) (*api.SectorLocation, error) { +func (c *FullNodeStruct) StateSectorPartition(ctx context.Context, maddr address.Address, sectorNumber abi.SectorNumber, tok types.TipSetKey) (*miner.SectorLocation, error) { return c.Internal.StateSectorPartition(ctx, maddr, sectorNumber, tok) } diff --git a/cmd/lotus-storage-miner/info.go b/cmd/lotus-storage-miner/info.go index 55ef024f3..c47a22b0e 100644 --- a/cmd/lotus-storage-miner/info.go +++ b/cmd/lotus-storage-miner/info.go @@ -112,26 +112,19 @@ func infoCmdAct(cctx *cli.Context) error { if err != nil { return err } - faults, err := api.StateMinerFaults(ctx, maddr, types.EmptyTSK) - if err != nil { - return err - } - nfaults, err := faults.Count() - if err != nil { - return xerrors.Errorf("counting faults: %w", err) - } - - fmt.Printf("\tCommitted: %s\n", types.SizeStr(types.BigMul(types.NewInt(secCounts.Sectors), types.NewInt(uint64(mi.SectorSize))))) + proving := secCounts.Active + secCounts.Faulty + nfaults := secCounts.Faulty + fmt.Printf("\tCommitted: %s\n", types.SizeStr(types.BigMul(types.NewInt(secCounts.Live), types.NewInt(uint64(mi.SectorSize))))) if nfaults == 0 { - fmt.Printf("\tProving: %s\n", types.SizeStr(types.BigMul(types.NewInt(secCounts.Active), types.NewInt(uint64(mi.SectorSize))))) + fmt.Printf("\tProving: %s\n", types.SizeStr(types.BigMul(types.NewInt(proving), types.NewInt(uint64(mi.SectorSize))))) } else { var faultyPercentage float64 - if secCounts.Sectors != 0 { - faultyPercentage = float64(10000*nfaults/secCounts.Sectors) / 100. + if secCounts.Live != 0 { + faultyPercentage = float64(10000*nfaults/secCounts.Live) / 100. } fmt.Printf("\tProving: %s (%s Faulty, %.2f%%)\n", - types.SizeStr(types.BigMul(types.NewInt(secCounts.Sectors), types.NewInt(uint64(mi.SectorSize)))), + types.SizeStr(types.BigMul(types.NewInt(proving), types.NewInt(uint64(mi.SectorSize)))), types.SizeStr(types.BigMul(types.NewInt(nfaults), types.NewInt(uint64(mi.SectorSize)))), faultyPercentage) } diff --git a/node/impl/full/state.go b/node/impl/full/state.go index 73ab7bc4d..d1490af64 100644 --- a/node/impl/full/state.go +++ b/node/impl/full/state.go @@ -635,57 +635,50 @@ func (a *StateAPI) StateChangedActors(ctx context.Context, old cid.Cid, new cid. } func (a *StateAPI) StateMinerSectorCount(ctx context.Context, addr address.Address, tsk types.TipSetKey) (api.MinerSectors, error) { - var out api.MinerSectors - - err := a.StateManager.WithParentStateTsk(tsk, - a.StateManager.WithActor(addr, - a.StateManager.WithActorState(ctx, func(store adt.Store, mas *miner.State) error { - var allActive []bitfield.BitField - - err := a.StateManager.WithDeadlines( - a.StateManager.WithEachDeadline( - a.StateManager.WithEachPartition(func(store adt.Store, partIdx uint64, partition *miner.Partition) error { - active, err := partition.ActiveSectors() - if err != nil { - return xerrors.Errorf("partition.ActiveSectors: %w", err) - } - - allActive = append(allActive, active) - return nil - })))(store, mas) - if err != nil { - return xerrors.Errorf("with deadlines: %w", err) - } - - active, err := bitfield.MultiMerge(allActive...) - if err != nil { - return xerrors.Errorf("merging active sector bitfields: %w", err) - } - - out.Active, err = active.Count() - if err != nil { - return xerrors.Errorf("counting active sectors: %w", err) - } - - sarr, err := adt.AsArray(store, mas.Sectors) - if err != nil { - return err - } - - out.Sectors = sarr.Length() - return nil - }))) + act, err := a.StateManager.LoadActorTsk(ctx, addr, tsk) if err != nil { return api.MinerSectors{}, err } - - return out, nil + mas, err := miner.Load(a.Chain.Store(ctx), act) + if err != nil { + return api.MinerSectors{}, err + } + var activeCount, liveCount, faultyCount uint64 + if err := mas.ForEachDeadline(func(_ uint64, dl miner.Deadline) error { + return dl.ForEachPartition(func(_ uint64, part miner.Partition) error { + if active, err := part.ActiveSectors(); err != nil { + return err + } else if count, err := active.Count(); err != nil { + return err + } else { + activeCount += count + } + if live, err := part.LiveSectors(); err != nil { + return err + } else if count, err := live.Count(); err != nil { + return err + } else { + liveCount += count + } + if faulty, err := part.FaultySectors(); err != nil { + return err + } else if count, err := faulty.Count(); err != nil { + return err + } else { + faultyCount += count + } + return nil + }) + }); err != nil { + return api.MinerSectors{}, err + } + return api.MinerSectors{Live: liveCount, Active: activeCount, Faulty: faultyCount}, nil } -func (a *StateAPI) StateSectorPreCommitInfo(ctx context.Context, maddr address.Address, n abi.SectorNumber, tsk types.TipSetKey) (miner.SectorPreCommitOnChainInfo, error) { +func (a *StateAPI) StateSectorPreCommitInfo(ctx context.Context, maddr address.Address, n abi.SectorNumber, tsk types.TipSetKey) (*miner.SectorPreCommitOnChainInfo, error) { ts, err := a.Chain.GetTipSetFromKey(tsk) if err != nil { - return miner.SectorPreCommitOnChainInfo{}, xerrors.Errorf("loading tipset %s: %w", tsk, err) + return nil, xerrors.Errorf("loading tipset %s: %w", tsk, err) } return stmgr.PreCommitInfo(ctx, a.StateManager, maddr, n, ts) } @@ -698,7 +691,7 @@ func (a *StateAPI) StateSectorGetInfo(ctx context.Context, maddr address.Address return stmgr.MinerSectorInfo(ctx, a.StateManager, maddr, n, ts) } -func (a *StateAPI) StateSectorExpiration(ctx context.Context, maddr address.Address, sectorNumber abi.SectorNumber, tsk types.TipSetKey) (*api.SectorExpiration, error) { +func (a *StateAPI) StateSectorExpiration(ctx context.Context, maddr address.Address, sectorNumber abi.SectorNumber, tsk types.TipSetKey) (*miner.SectorExpiration, error) { act, err := a.StateManager.LoadActorTsk(ctx, maddr, tsk) if err != nil { return nil, err @@ -710,7 +703,7 @@ func (a *StateAPI) StateSectorExpiration(ctx context.Context, maddr address.Addr return mas.GetSectorExpiration(sectorNumber) } -func (a *StateAPI) StateSectorPartition(ctx context.Context, maddr address.Address, sectorNumber abi.SectorNumber, tsk types.TipSetKey) (*api.SectorLocation, error) { +func (a *StateAPI) StateSectorPartition(ctx context.Context, maddr address.Address, sectorNumber abi.SectorNumber, tsk types.TipSetKey) (*miner.SectorLocation, error) { act, err := a.StateManager.LoadActorTsk(ctx, maddr, tsk) if err != nil { return nil, err diff --git a/storage/miner.go b/storage/miner.go index 47f50ce71..3485dba03 100644 --- a/storage/miner.go +++ b/storage/miner.go @@ -3,7 +3,6 @@ package storage import ( "context" "errors" - miner2 "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "time" "github.com/filecoin-project/go-state-types/dline" @@ -22,11 +21,11 @@ import ( "github.com/filecoin-project/go-state-types/crypto" sectorstorage "github.com/filecoin-project/lotus/extern/sector-storage" "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/specs-storage/storage" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/events" "github.com/filecoin-project/lotus/chain/gen" "github.com/filecoin-project/lotus/chain/types" @@ -68,10 +67,10 @@ type SealingStateEvt struct { type storageMinerApi interface { // Call a read only method on actors (no interaction with the chain required) StateCall(context.Context, *types.Message, types.TipSetKey) (*api.InvocResult, error) - StateMinerSectors(context.Context, address.Address, *bitfield.BitField, bool, types.TipSetKey) ([]*miner2.ChainSectorInfo, error) + StateMinerSectors(context.Context, address.Address, *bitfield.BitField, bool, types.TipSetKey) ([]*miner.ChainSectorInfo, error) StateSectorPreCommitInfo(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (miner.SectorPreCommitOnChainInfo, error) StateSectorGetInfo(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (*miner.SectorOnChainInfo, error) - StateSectorPartition(ctx context.Context, maddr address.Address, sectorNumber abi.SectorNumber, tok types.TipSetKey) (*api.SectorLocation, error) + StateSectorPartition(ctx context.Context, maddr address.Address, sectorNumber abi.SectorNumber, tok types.TipSetKey) (*miner.SectorLocation, error) StateMinerInfo(context.Context, address.Address, types.TipSetKey) (api.MinerInfo, error) StateMinerProvingDeadline(context.Context, address.Address, types.TipSetKey) (*dline.Info, error) StateMinerPreCommitDepositForPower(context.Context, address.Address, miner.SectorPreCommitInfo, types.TipSetKey) (types.BigInt, error) From 91e9573863b8161b417910c253fdb994624ba211 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Tue, 15 Sep 2020 12:13:13 -0700 Subject: [PATCH 030/303] Compile fixes --- api/api_full.go | 4 ++-- api/apistruct/struct.go | 1 - chain/actors/builtin/miner/v0.go | 8 ++++---- chain/stmgr/utils.go | 6 ++++-- 4 files changed, 10 insertions(+), 9 deletions(-) diff --git a/api/api_full.go b/api/api_full.go index d3b655634..88496d669 100644 --- a/api/api_full.go +++ b/api/api_full.go @@ -344,9 +344,9 @@ type FullNode interface { // expiration epoch StateSectorGetInfo(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (*miner.SectorOnChainInfo, error) // StateSectorExpiration returns epoch at which given sector will expire - StateSectorExpiration(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (*SectorExpiration, error) + StateSectorExpiration(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (*miner.SectorExpiration, error) // StateSectorPartition finds deadline/partition with the specified sector - StateSectorPartition(ctx context.Context, maddr address.Address, sectorNumber abi.SectorNumber, tok types.TipSetKey) (*SectorLocation, error) + StateSectorPartition(ctx context.Context, maddr address.Address, sectorNumber abi.SectorNumber, tok types.TipSetKey) (*miner.SectorLocation, error) // StateSearchMsg searches for a message in the chain, and returns its receipt and the tipset where it was executed StateSearchMsg(context.Context, cid.Cid) (*MsgLookup, error) // StateWaitMsg looks back in the chain for a message. If not found, it blocks until the diff --git a/api/apistruct/struct.go b/api/apistruct/struct.go index a554d2a5f..1fcd5e0f3 100644 --- a/api/apistruct/struct.go +++ b/api/apistruct/struct.go @@ -27,7 +27,6 @@ import ( "github.com/filecoin-project/lotus/extern/sector-storage/stores" "github.com/filecoin-project/lotus/extern/sector-storage/storiface" marketevents "github.com/filecoin-project/lotus/markets/loggers" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/specs-actors/actors/builtin/paych" "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/specs-storage/storage" diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index c0712a0c2..e1ef9c51f 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -10,7 +10,6 @@ import ( "github.com/filecoin-project/go-state-types/dline" "github.com/filecoin-project/lotus/chain/actors/adt" v0adt "github.com/filecoin-project/specs-actors/actors/util/adt" - cbor "github.com/ipfs/go-ipld-cbor" "github.com/libp2p/go-libp2p-core/peer" cbg "github.com/whyrusleeping/cbor-gen" "golang.org/x/xerrors" @@ -70,7 +69,7 @@ func (s *v0State) GetSectorExpiration(num abi.SectorNumber) (out *SectorExpirati // 2. If it's faulty, it will expire early within the first 14 entries // of the expiration queue. stopErr := errors.New("stop") - err := dls.ForEach(s.store, func(dlIdx uint64, dl *miner.Deadline) error { + err = dls.ForEach(s.store, func(dlIdx uint64, dl *miner.Deadline) error { partitions, err := dl.PartitionsArray(s.store) if err != nil { return err @@ -102,12 +101,13 @@ func (s *v0State) GetSectorExpiration(num abi.SectorNumber) (out *SectorExpirati out.Early = abi.ChainEpoch(epoch) return nil } - if onTime, err := exp.OnTime.IsSet(uint64(num)); err != nil { + if onTime, err := exp.OnTimeSectors.IsSet(uint64(num)); err != nil { return err } else if onTime { - out.OnTime = epoch + out.OnTime = abi.ChainEpoch(epoch) return stopErr } + return nil }) }) }) diff --git a/chain/stmgr/utils.go b/chain/stmgr/utils.go index 4dc210154..88275f019 100644 --- a/chain/stmgr/utils.go +++ b/chain/stmgr/utils.go @@ -103,8 +103,10 @@ func GetPowerRaw(ctx context.Context, sm *StateManager, st cid.Cid, maddr addres var mpow power.Claim if maddr != address.Undef { - mpow, err = mas.MinerPower(maddr) - if err != nil { + var found bool + mpow, found, err = mas.MinerPower(maddr) + if err != nil || !found { + // TODO: return an error when not found? return power.Claim{}, power.Claim{}, err } } From 4e01fad0d47faafbf799eb7a0e6ee14e065018b2 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Tue, 15 Sep 2020 14:44:03 -0700 Subject: [PATCH 031/303] start multisig abstraction --- chain/actors/builtin/multisig/multisig.go | 31 +++++++++++++ chain/actors/builtin/multisig/v0.go | 16 +++++++ node/impl/full/state.go | 55 +++++++++-------------- 3 files changed, 69 insertions(+), 33 deletions(-) create mode 100644 chain/actors/builtin/multisig/multisig.go create mode 100644 chain/actors/builtin/multisig/v0.go diff --git a/chain/actors/builtin/multisig/multisig.go b/chain/actors/builtin/multisig/multisig.go new file mode 100644 index 000000000..676dbe75f --- /dev/null +++ b/chain/actors/builtin/multisig/multisig.go @@ -0,0 +1,31 @@ +package multisig + +import ( + "golang.org/x/xerrors" + + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/cbor" + v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" + + "github.com/filecoin-project/lotus/chain/actors/adt" + "github.com/filecoin-project/lotus/chain/types" +) + +func Load(store adt.Store, act *types.Actor) (State, error) { + switch act.Code { + case v0builtin.MultisigActorCodeID: + out := v0State{store: store} + err := store.Get(store.Context(), act.Head, &out) + if err != nil { + return nil, err + } + return &out, nil + } + return nil, xerrors.Errorf("unknown actor code %s", act.Code) +} + +type State interface { + cbor.Marshaler + + LockedBalance(epoch abi.ChainEpoch) (abi.TokenAmount, error) +} diff --git a/chain/actors/builtin/multisig/v0.go b/chain/actors/builtin/multisig/v0.go new file mode 100644 index 000000000..3bc7e70b2 --- /dev/null +++ b/chain/actors/builtin/multisig/v0.go @@ -0,0 +1,16 @@ +package multisig + +import ( + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/lotus/chain/actors/adt" + "github.com/filecoin-project/specs-actors/actors/builtin/multisig" +) + +type v0State struct { + multisig.State + store adt.Store +} + +func (s *v0State) LockedBalance(currEpoch abi.ChainEpoch) (abi.TokenAmount, error) { + return s.State.AmountLocked(currEpoch - s.StartEpoch), nil +} diff --git a/node/impl/full/state.go b/node/impl/full/state.go index d1490af64..10b5de82b 100644 --- a/node/impl/full/state.go +++ b/node/impl/full/state.go @@ -22,7 +22,6 @@ import ( "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin/market" - samsig "github.com/filecoin-project/specs-actors/actors/builtin/multisig" "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/builtin/reward" "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" @@ -31,6 +30,7 @@ import ( "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/chain/actors" "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + "github.com/filecoin-project/lotus/chain/actors/builtin/multisig" "github.com/filecoin-project/lotus/chain/beacon" "github.com/filecoin-project/lotus/chain/gen" "github.com/filecoin-project/lotus/chain/state" @@ -790,28 +790,19 @@ func (a *StateAPI) MsigGetAvailableBalance(ctx context.Context, addr address.Add return types.EmptyInt, xerrors.Errorf("loading tipset %s: %w", tsk, err) } - var st samsig.State - act, err := a.StateManager.LoadActorState(ctx, addr, &st, ts) + act, err := a.StateManager.LoadActor(ctx, addr, ts) + if err != nil { + return types.EmptyInt, xerrors.Errorf("failed to load multisig actor: %w", err) + } + msas, err := multisig.Load(a.Chain.Store(ctx), act) if err != nil { return types.EmptyInt, xerrors.Errorf("failed to load multisig actor state: %w", err) } - - if act.Code != builtin.MultisigActorCodeID { - return types.EmptyInt, fmt.Errorf("given actor was not a multisig") + locked, err := msas.LockedBalance(ts.Height()) + if err != nil { + return types.EmptyInt, xerrors.Errorf("failed to compute locked multisig balance: %w", err) } - - if st.UnlockDuration == 0 { - return act.Balance, nil - } - - offset := ts.Height() - st.StartEpoch - if offset > st.UnlockDuration { - return act.Balance, nil - } - - minBalance := types.BigDiv(st.InitialBalance, types.NewInt(uint64(st.UnlockDuration))) - minBalance = types.BigMul(minBalance, types.NewInt(uint64(offset))) - return types.BigSub(act.Balance, minBalance), nil + return types.BigSub(act.Balance, locked), nil } func (a *StateAPI) MsigGetVested(ctx context.Context, addr address.Address, start types.TipSetKey, end types.TipSetKey) (types.BigInt, error) { @@ -831,29 +822,27 @@ func (a *StateAPI) MsigGetVested(ctx context.Context, addr address.Address, star return big.Zero(), nil } - var mst samsig.State - act, err := a.StateManager.LoadActorState(ctx, addr, &mst, endTs) + act, err := a.StateManager.LoadActor(ctx, addr, endTs) if err != nil { - return types.EmptyInt, xerrors.Errorf("failed to load multisig actor state at end epoch: %w", err) + return types.EmptyInt, xerrors.Errorf("failed to load multisig actor at end epoch: %w", err) } - if act.Code != builtin.MultisigActorCodeID { - return types.EmptyInt, fmt.Errorf("given actor was not a multisig") + msas, err := multisig.Load(a.Chain.Store(ctx), act) + if err != nil { + return types.EmptyInt, xerrors.Errorf("failed to load multisig actor state: %w", err) } - if mst.UnlockDuration == 0 || - mst.InitialBalance.IsZero() || - mst.StartEpoch+mst.UnlockDuration <= startTs.Height() || - mst.StartEpoch >= endTs.Height() { - return big.Zero(), nil + startLk, err := msas.LockedBalance(startTs.Height()) + if err != nil { + return types.EmptyInt, xerrors.Errorf("failed to compute locked balance at start height: %w", err) } - startLk := mst.InitialBalance - if startTs.Height() > mst.StartEpoch { - startLk = mst.AmountLocked(startTs.Height() - mst.StartEpoch) + endLk, err := msas.LockedBalance(endTs.Height()) + if err != nil { + return types.EmptyInt, xerrors.Errorf("failed to compute locked balance at end height: %w", err) } - return big.Sub(startLk, mst.AmountLocked(endTs.Height()-mst.StartEpoch)), nil + return types.BigSub(startLk, endLk), nil } var initialPledgeNum = types.NewInt(110) From e1ba4eb5c449c9686c96d50aacd68d403d1370e0 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Tue, 15 Sep 2020 14:55:48 -0700 Subject: [PATCH 032/303] sub reward actor --- chain/actors/builtin/reward/reward.go | 30 +++++++++++++++++++++++++++ chain/actors/builtin/reward/v0.go | 11 ++++++++++ 2 files changed, 41 insertions(+) create mode 100644 chain/actors/builtin/reward/reward.go create mode 100644 chain/actors/builtin/reward/v0.go diff --git a/chain/actors/builtin/reward/reward.go b/chain/actors/builtin/reward/reward.go new file mode 100644 index 000000000..a1a7cac5d --- /dev/null +++ b/chain/actors/builtin/reward/reward.go @@ -0,0 +1,30 @@ +package reward + +import ( + "golang.org/x/xerrors" + + "github.com/filecoin-project/go-state-types/cbor" + v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" + + "github.com/filecoin-project/lotus/chain/actors/adt" + "github.com/filecoin-project/lotus/chain/types" +) + +var Address = v0builtin.RewardActorAddr + +func Load(store adt.Store, act *types.Actor) (st State, err error) { + switch act.Code { + case v0builtin.RewardActorCodeID: + out := v0State{store: store} + err := store.Get(store.Context(), act.Head, &out) + if err != nil { + return nil, err + } + return &out, nil + } + return nil, xerrors.Errorf("unknown actor code %s", act.Code) +} + +type State interface { + cbor.Marshaler +} diff --git a/chain/actors/builtin/reward/v0.go b/chain/actors/builtin/reward/v0.go new file mode 100644 index 000000000..8fef3756c --- /dev/null +++ b/chain/actors/builtin/reward/v0.go @@ -0,0 +1,11 @@ +package reward + +import ( + "github.com/filecoin-project/specs-actors/actors/builtin/reward" + "github.com/filecoin-project/specs-actors/actors/util/adt" +) + +type v0State struct { + reward.State + store adt.Store +} From 02bc5fab268579539224af39e85b4a960209dbc2 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Tue, 15 Sep 2020 14:56:00 -0700 Subject: [PATCH 033/303] add power actor address alias --- chain/actors/builtin/power/power.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/chain/actors/builtin/power/power.go b/chain/actors/builtin/power/power.go index fa0400f2e..9e35e52ab 100644 --- a/chain/actors/builtin/power/power.go +++ b/chain/actors/builtin/power/power.go @@ -12,6 +12,8 @@ import ( "github.com/filecoin-project/lotus/chain/types" ) +var Address = v0builtin.StoragePowerActorAddr + func Load(store adt.Store, act *types.Actor) (st State, err error) { switch act.Code { case v0builtin.StoragePowerActorCodeID: From e53aee26a3d1b440729212fde7c77b8c06bf9a14 Mon Sep 17 00:00:00 2001 From: austinabell Date: Tue, 15 Sep 2020 18:36:06 -0400 Subject: [PATCH 034/303] Make state transition in validation async --- chain/sync.go | 45 +++++++++++++++++++++++++-------------------- 1 file changed, 25 insertions(+), 20 deletions(-) diff --git a/chain/sync.go b/chain/sync.go index f7530f556..e23284134 100644 --- a/chain/sync.go +++ b/chain/sync.go @@ -788,31 +788,35 @@ func (syncer *Syncer) ValidateBlock(ctx context.Context, b *types.FullBlock) (er b.Header.ParentWeight, pweight) } - // Stuff that needs stateroot / worker address - stateroot, precp, err := syncer.sm.TipSetState(ctx, baseTs) - if err != nil { - return xerrors.Errorf("get tipsetstate(%d, %s) failed: %w", h.Height, h.Parents, err) - } - - if stateroot != h.ParentStateRoot { - msgs, err := syncer.store.MessagesForTipset(baseTs) + stateRootCheck := async.Err(func() error { + stateroot, precp, err := syncer.sm.TipSetState(ctx, baseTs) if err != nil { - log.Error("failed to load messages for tipset during tipset state mismatch error: ", err) - } else { - log.Warn("Messages for tipset with mismatching state:") - for i, m := range msgs { - mm := m.VMMessage() - log.Warnf("Message[%d]: from=%s to=%s method=%d params=%x", i, mm.From, mm.To, mm.Method, mm.Params) - } + return xerrors.Errorf("get tipsetstate(%d, %s) failed: %w", h.Height, h.Parents, err) } - return xerrors.Errorf("parent state root did not match computed state (%s != %s)", stateroot, h.ParentStateRoot) - } + if stateroot != h.ParentStateRoot { + msgs, err := syncer.store.MessagesForTipset(baseTs) + if err != nil { + log.Error("failed to load messages for tipset during tipset state mismatch error: ", err) + } else { + log.Warn("Messages for tipset with mismatching state:") + for i, m := range msgs { + mm := m.VMMessage() + log.Warnf("Message[%d]: from=%s to=%s method=%d params=%x", i, mm.From, mm.To, mm.Method, mm.Params) + } + } - if precp != h.ParentMessageReceipts { - return xerrors.Errorf("parent receipts root did not match computed value (%s != %s)", precp, h.ParentMessageReceipts) - } + return xerrors.Errorf("parent state root did not match computed state (%s != %s)", stateroot, h.ParentStateRoot) + } + if precp != h.ParentMessageReceipts { + return xerrors.Errorf("parent receipts root did not match computed value (%s != %s)", precp, h.ParentMessageReceipts) + } + + return nil + }) + + // Stuff that needs worker address waddr, err := stmgr.GetMinerWorkerRaw(ctx, syncer.sm, lbst, h.Miner) if err != nil { return xerrors.Errorf("GetMinerWorkerRaw failed: %w", err) @@ -933,6 +937,7 @@ func (syncer *Syncer) ValidateBlock(ctx context.Context, b *types.FullBlock) (er winnerCheck, msgsCheck, baseFeeCheck, + stateRootCheck, } var merr error From c2148ba106d7491f145c793f1c9fd9a20654e33c Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Tue, 15 Sep 2020 19:27:36 -0400 Subject: [PATCH 035/303] Multisig: Add a CLI command to propose locking some balance --- cli/multisig.go | 94 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) diff --git a/cli/multisig.go b/cli/multisig.go index 4596628f4..01e922a07 100644 --- a/cli/multisig.go +++ b/cli/multisig.go @@ -11,6 +11,10 @@ import ( "strconv" "text/tabwriter" + "github.com/filecoin-project/lotus/chain/actors" + + "github.com/filecoin-project/go-state-types/big" + "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/util/adt" @@ -43,6 +47,9 @@ var multisigCmd = &cli.Command{ msigSwapProposeCmd, msigSwapApproveCmd, msigSwapCancelCmd, + msigLockProposeCmd, + msigLockApproveCmd, + msigLockCancelCmd, msigVestedCmd, }, } @@ -971,6 +978,93 @@ var msigSwapCancelCmd = &cli.Command{ }, } +var msigLockProposeCmd = &cli.Command{ + Name: "lock-propose", + Usage: "Propose to lock up some balance", + ArgsUsage: "[multisigAddress startEpoch unlockDuration amount]", + Flags: []cli.Flag{ + &cli.StringFlag{ + Name: "from", + Usage: "account to send the approve message from", + }, + }, + Action: func(cctx *cli.Context) error { + if cctx.Args().Len() != 4 { + return ShowHelp(cctx, fmt.Errorf("must pass multisig address, start epoch, unlock duration, and amount")) + } + + api, closer, err := GetFullNodeAPI(cctx) + if err != nil { + return err + } + defer closer() + ctx := ReqContext(cctx) + + msig, err := address.NewFromString(cctx.Args().Get(0)) + if err != nil { + return err + } + + start, err := strconv.ParseUint(cctx.Args().Get(1), 10, 64) + if err != nil { + return err + } + + duration, err := strconv.ParseUint(cctx.Args().Get(2), 10, 64) + if err != nil { + return err + } + + amount, err := types.ParseFIL(cctx.Args().Get(3)) + if err != nil { + return err + } + + var from address.Address + if cctx.IsSet("from") { + f, err := address.NewFromString(cctx.String("from")) + if err != nil { + return err + } + from = f + } else { + defaddr, err := api.WalletDefaultAddress(ctx) + if err != nil { + return err + } + from = defaddr + } + + params, actErr := actors.SerializeParams(&samsig.LockBalanceParams{ + StartEpoch: abi.ChainEpoch(start), + UnlockDuration: abi.ChainEpoch(duration), + Amount: abi.NewTokenAmount(amount.Int64()), + }) + + if actErr != nil { + return actErr + } + + msgCid, err := api.MsigPropose(ctx, msig, msig, big.Zero(), from, uint64(builtin.MethodsMultisig.LockBalance), params) + if err != nil { + return err + } + + fmt.Println("sent lock proposal in message: ", msgCid) + + wait, err := api.StateWaitMsg(ctx, msgCid, build.MessageConfidence) + if err != nil { + return err + } + + if wait.Receipt.ExitCode != 0 { + return fmt.Errorf("lock proposal returned exit %d", wait.Receipt.ExitCode) + } + + return nil + }, +} + var msigVestedCmd = &cli.Command{ Name: "vested", Usage: "Gets the amount vested in an msig between two epochs", From 92471d41d6923032eb807b857c02461e66d225b6 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Tue, 15 Sep 2020 16:47:58 -0700 Subject: [PATCH 036/303] migrate precommit deposit function --- chain/actors/builtin/builtin.go | 5 ++ chain/actors/builtin/market/market.go | 5 ++ chain/actors/builtin/market/v0.go | 7 ++ chain/actors/builtin/power/power.go | 3 + chain/actors/builtin/power/v0.go | 5 ++ chain/actors/builtin/reward/reward.go | 3 + chain/actors/builtin/reward/v0.go | 5 ++ node/impl/full/state.go | 111 +++++++++++--------------- 8 files changed, 81 insertions(+), 63 deletions(-) diff --git a/chain/actors/builtin/builtin.go b/chain/actors/builtin/builtin.go index accc4e7e6..517f0d70c 100644 --- a/chain/actors/builtin/builtin.go +++ b/chain/actors/builtin/builtin.go @@ -4,6 +4,8 @@ import ( "fmt" "github.com/filecoin-project/go-state-types/network" + + v0smoothing "github.com/filecoin-project/specs-actors/actors/util/smoothing" ) type Version int @@ -21,3 +23,6 @@ func VersionForNetwork(version network.Version) Version { panic(fmt.Sprintf("unsupported network version %d", version)) } } + +// TODO: find some way to abstract over this. +type FilterEstimate = v0smoothing.FilterEstimate diff --git a/chain/actors/builtin/market/market.go b/chain/actors/builtin/market/market.go index 3d12ac9a8..99cca9879 100644 --- a/chain/actors/builtin/market/market.go +++ b/chain/actors/builtin/market/market.go @@ -12,6 +12,8 @@ import ( "github.com/filecoin-project/lotus/chain/types" ) +var Address = v0builtin.StorageMarketActorAddr + func Load(store adt.Store, act *types.Actor) (st State, err error) { switch act.Code { case v0builtin.StorageMarketActorCodeID: @@ -30,6 +32,9 @@ type State interface { EscrowTable() (BalanceTable, error) LockedTable() (BalanceTable, error) TotalLocked() (abi.TokenAmount, error) + VerifyDealsForActivation( + minerAddr address.Address, deals []abi.DealID, currEpoch, sectorExpiry abi.ChainEpoch, + ) (weight, verifiedWeight abi.DealWeight, err error) } type BalanceTable interface { diff --git a/chain/actors/builtin/market/v0.go b/chain/actors/builtin/market/v0.go index da86cda0f..fb67902da 100644 --- a/chain/actors/builtin/market/v0.go +++ b/chain/actors/builtin/market/v0.go @@ -1,6 +1,7 @@ package market import ( + "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/specs-actors/actors/builtin/market" @@ -25,3 +26,9 @@ func (s *v0State) EscrowTable() (BalanceTable, error) { func (s *v0State) LockedTable() (BalanceTable, error) { return adt.AsBalanceTable(s.store, s.State.LockedTable) } + +func (s *v0State) VerifyDealsForActivation( + minerAddr address.Address, deals []abi.DealID, currEpoch, sectorExpiry abi.ChainEpoch, +) (weight, verifiedWeight abi.DealWeight, err error) { + return market.ValidateDealsForActivation(&s.State, s.store, deals, minerAddr, sectorExpiry, currEpoch) +} diff --git a/chain/actors/builtin/power/power.go b/chain/actors/builtin/power/power.go index 9e35e52ab..07399e1bf 100644 --- a/chain/actors/builtin/power/power.go +++ b/chain/actors/builtin/power/power.go @@ -9,6 +9,7 @@ import ( v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/lotus/chain/actors/adt" + "github.com/filecoin-project/lotus/chain/actors/builtin" "github.com/filecoin-project/lotus/chain/types" ) @@ -32,6 +33,8 @@ type State interface { TotalLocked() (abi.TokenAmount, error) TotalPower() (Claim, error) + TotalPowerSmoothed() (builtin.FilterEstimate, error) + MinerPower(address.Address) (Claim, bool, error) MinerNominalPowerMeetsConsensusMinimum(address.Address) (bool, error) } diff --git a/chain/actors/builtin/power/v0.go b/chain/actors/builtin/power/v0.go index 12eb318e5..45dd570f6 100644 --- a/chain/actors/builtin/power/v0.go +++ b/chain/actors/builtin/power/v0.go @@ -3,6 +3,7 @@ package power import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/lotus/chain/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/util/adt" ) @@ -42,3 +43,7 @@ func (s *v0State) MinerPower(addr address.Address) (Claim, bool, error) { func (s *v0State) MinerNominalPowerMeetsConsensusMinimum(a address.Address) (bool, error) { return s.State.MinerNominalPowerMeetsConsensusMinimum(s.store, a) } + +func (s *v0State) TotalPowerSmoothed() (builtin.FilterEstimate, error) { + return *s.State.ThisEpochQAPowerSmoothed, nil +} diff --git a/chain/actors/builtin/reward/reward.go b/chain/actors/builtin/reward/reward.go index a1a7cac5d..ba03feced 100644 --- a/chain/actors/builtin/reward/reward.go +++ b/chain/actors/builtin/reward/reward.go @@ -7,6 +7,7 @@ import ( v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/lotus/chain/actors/adt" + "github.com/filecoin-project/lotus/chain/actors/builtin" "github.com/filecoin-project/lotus/chain/types" ) @@ -27,4 +28,6 @@ func Load(store adt.Store, act *types.Actor) (st State, err error) { type State interface { cbor.Marshaler + + RewardSmoothed() (builtin.FilterEstimate, error) } diff --git a/chain/actors/builtin/reward/v0.go b/chain/actors/builtin/reward/v0.go index 8fef3756c..a894fa752 100644 --- a/chain/actors/builtin/reward/v0.go +++ b/chain/actors/builtin/reward/v0.go @@ -1,6 +1,7 @@ package reward import ( + "github.com/filecoin-project/lotus/chain/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin/reward" "github.com/filecoin-project/specs-actors/actors/util/adt" ) @@ -9,3 +10,7 @@ type v0State struct { reward.State store adt.Store } + +func (s *v0State) RewardSmoothed() (builtin.FilterEstimate, error) { + return *s.State.ThisEpochRewardSmoothed, nil +} diff --git a/node/impl/full/state.go b/node/impl/full/state.go index 10b5de82b..3ea40388f 100644 --- a/node/impl/full/state.go +++ b/node/impl/full/state.go @@ -21,16 +21,17 @@ import ( "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/market" - "github.com/filecoin-project/specs-actors/actors/builtin/power" - "github.com/filecoin-project/specs-actors/actors/builtin/reward" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/specs-actors/actors/util/adt" + "github.com/filecoin-project/specs-actors/actors/util/smoothing" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/chain/actors" "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/actors/builtin/multisig" + "github.com/filecoin-project/lotus/chain/actors/builtin/power" + "github.com/filecoin-project/lotus/chain/actors/builtin/reward" "github.com/filecoin-project/lotus/chain/beacon" "github.com/filecoin-project/lotus/chain/gen" "github.com/filecoin-project/lotus/chain/state" @@ -41,6 +42,7 @@ import ( "github.com/filecoin-project/lotus/chain/wallet" "github.com/filecoin-project/lotus/lib/bufbstore" "github.com/filecoin-project/lotus/node/modules/dtypes" + "github.com/filecoin-project/lotus/chain/actors/builtin/market" ) var errBreakForeach = errors.New("break") @@ -854,74 +856,57 @@ func (a *StateAPI) StateMinerPreCommitDepositForPower(ctx context.Context, maddr return types.EmptyInt, xerrors.Errorf("loading tipset %s: %w", tsk, err) } - var minerState miner.State - var powerState power.State - var rewardState reward.State - - err = a.StateManager.WithParentStateTsk(tsk, func(state *state.StateTree) error { - if err := a.StateManager.WithActor(maddr, a.StateManager.WithActorState(ctx, &minerState))(state); err != nil { - return xerrors.Errorf("getting miner state: %w", err) - } - - if err := a.StateManager.WithActor(builtin.StoragePowerActorAddr, a.StateManager.WithActorState(ctx, &powerState))(state); err != nil { - return xerrors.Errorf("getting power state: %w", err) - } - - if err := a.StateManager.WithActor(builtin.RewardActorAddr, a.StateManager.WithActorState(ctx, &rewardState))(state); err != nil { - return xerrors.Errorf("getting reward state: %w", err) - } - - return nil - }) + state, err := a.StateManager.ParentState(ts) if err != nil { - return types.EmptyInt, err + return types.EmptyInt, xerrors.Errorf("loading state %s: %w", tsk, err) } - dealWeights := market.VerifyDealsForActivationReturn{ - DealWeight: big.Zero(), - VerifiedDealWeight: big.Zero(), - } - - if len(pci.DealIDs) != 0 { - var err error - params, err := actors.SerializeParams(&market.VerifyDealsForActivationParams{ - DealIDs: pci.DealIDs, - SectorExpiry: pci.Expiration, - }) - if err != nil { - return types.EmptyInt, err - } - - ret, err := a.StateManager.Call(ctx, &types.Message{ - From: maddr, - To: builtin.StorageMarketActorAddr, - Method: builtin.MethodsMarket.VerifyDealsForActivation, - Params: params, - }, ts) - if err != nil { - return types.EmptyInt, err - } - - if err := dealWeights.UnmarshalCBOR(bytes.NewReader(ret.MsgRct.Return)); err != nil { - return types.BigInt{}, err - } - } - - mi, err := a.StateMinerInfo(ctx, maddr, tsk) + ssize, err := pci.SealProof.SectorSize() if err != nil { - return types.EmptyInt, err + return types.EmptyInt, xerrors.Errorf("failed to get resolve size: %w", err) } - ssize := mi.SectorSize + store := a.Chain.Store(ctx) - duration := pci.Expiration - ts.Height() // NB: not exactly accurate, but should always lead us to *over* estimate, not under + var sectorWeight abi.StoragePower + if act, err := state.GetActor(market.Address); err != nil { + return types.EmptyInt, xerrors.Errorf("loading miner actor %s: %w", maddr, err) + } else s, err := market.Load(store, act); err != nil { + return types.EmptyInt, xerrors.Errorf("loading market actor state %s: %w", maddr, err) + } else if w, vw, err := s.VerifyDealsForActivation(maddr, pci.DealIDs, ts.Height(), pci.Expiration); err != nil { + return types.EmptyInt, xerrors.Errorf("verifying deals for activation: %w", err) + } else { + // NB: not exactly accurate, but should always lead us to *over* estimate, not under + duration := pci.Expiration - ts.Height() - sectorWeight := miner.QAPowerForWeight(ssize, duration, dealWeights.DealWeight, dealWeights.VerifiedDealWeight) - deposit := miner.PreCommitDepositForPower( - rewardState.ThisEpochRewardSmoothed, - powerState.ThisEpochQAPowerSmoothed, - sectorWeight, - ) + // TODO: handle changes to this function across actor upgrades. + sectorWeight = v0miner.QAPowerForWeight(ssize, duration, w, vw) + } + + var powerSmoothed smoothing.FilterEstimate + if act, err := state.GetActor(power.Address); err != nil { + return types.EmptyInt, xerrors.Errorf("loading miner actor: %w", err) + } else s, err := power.Load(store, act); err != nil { + return types.EmptyInt, xerrors.Errorf("loading power actor state: %w", err) + } else p, err := s.TotalPowerSmoothed(); err != nil { + return types.EmptyInt, xerrors.Errorf("failed to determine total power: %w", err) + } else { + powerSmoothed = p + } + + var rewardSmoothed smoothing.FilterEstimate + if act, err := state.GetActor(reward.Address); err != nil { + return types.EmptyInt, xerrors.Errorf("loading miner actor: %w", err) + } else s, err := reward.Load(store, act); err != nil { + return types.EmptyInt, xerrors.Errorf("loading reward actor state: %w", err) + } else r, err := s.RewardSmoothed(); err != nil { + return types.EmptyInt, xerrors.Errorf("failed to determine total reward: %w", err) + } else { + rewardSmoothed = r + } + + // TODO: abstract over network upgrades. + deposit := v0miner.PreCommitDepositForPower(rewardSmoothed, powerSmoothed, sectorWeight) return types.BigDiv(types.BigMul(deposit, initialPledgeNum), initialPledgeDen), nil } From b20f558abba6790322ec6d206bd20ff6ded0e548 Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Tue, 15 Sep 2020 19:51:18 -0400 Subject: [PATCH 037/303] Multisig: Add a CLI command to approve locking some balance --- cli/multisig.go | 100 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) diff --git a/cli/multisig.go b/cli/multisig.go index 01e922a07..9ff1ad18e 100644 --- a/cli/multisig.go +++ b/cli/multisig.go @@ -1065,6 +1065,106 @@ var msigLockProposeCmd = &cli.Command{ }, } +var msigLockApproveCmd = &cli.Command{ + Name: "lock-approve", + Usage: "Approve a message to lock up some balance", + ArgsUsage: "[multisigAddress proposerAddress txId startEpoch unlockDuration amount]", + Flags: []cli.Flag{ + &cli.StringFlag{ + Name: "from", + Usage: "account to send the approve message from", + }, + }, + Action: func(cctx *cli.Context) error { + if cctx.Args().Len() != 6 { + return ShowHelp(cctx, fmt.Errorf("must pass multisig address, proposer address, tx id, start epoch, unlock duration, and amount")) + } + + api, closer, err := GetFullNodeAPI(cctx) + if err != nil { + return err + } + defer closer() + ctx := ReqContext(cctx) + + msig, err := address.NewFromString(cctx.Args().Get(0)) + if err != nil { + return err + } + + prop, err := address.NewFromString(cctx.Args().Get(1)) + if err != nil { + return err + } + + txid, err := strconv.ParseUint(cctx.Args().Get(2), 10, 64) + if err != nil { + return err + } + + start, err := strconv.ParseUint(cctx.Args().Get(3), 10, 64) + if err != nil { + return err + } + + duration, err := strconv.ParseUint(cctx.Args().Get(4), 10, 64) + if err != nil { + return err + } + + amount, err := types.ParseFIL(cctx.Args().Get(5)) + if err != nil { + return err + } + + var from address.Address + if cctx.IsSet("from") { + f, err := address.NewFromString(cctx.String("from")) + if err != nil { + return err + } + from = f + } else { + defaddr, err := api.WalletDefaultAddress(ctx) + if err != nil { + return err + } + from = defaddr + } + + params, actErr := actors.SerializeParams(&samsig.LockBalanceParams{ + StartEpoch: abi.ChainEpoch(start), + UnlockDuration: abi.ChainEpoch(duration), + Amount: abi.NewTokenAmount(amount.Int64()), + }) + + if actErr != nil { + return actErr + } + + // It takes the following params: , , , , , + // , , + + msgCid, err := api.MsigApprove(ctx, msig, txid, prop, msig, big.Zero(), from, uint64(builtin.MethodsMultisig.LockBalance), params) + if err != nil { + return err + } + + fmt.Println("sent lock approval in message: ", msgCid) + + wait, err := api.StateWaitMsg(ctx, msgCid, build.MessageConfidence) + if err != nil { + return err + } + + if wait.Receipt.ExitCode != 0 { + return fmt.Errorf("lock approval returned exit %d", wait.Receipt.ExitCode) + } + + return nil + }, +} + var msigVestedCmd = &cli.Command{ Name: "vested", Usage: "Gets the amount vested in an msig between two epochs", From 2ca1d111c53b7dbab5da50adc0b6176b3dfed9f2 Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Tue, 15 Sep 2020 19:52:58 -0400 Subject: [PATCH 038/303] Multisig: Add a CLI command to cancel locking some balance --- cli/multisig.go | 95 +++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 92 insertions(+), 3 deletions(-) diff --git a/cli/multisig.go b/cli/multisig.go index 9ff1ad18e..1f626ae7f 100644 --- a/cli/multisig.go +++ b/cli/multisig.go @@ -1142,9 +1142,6 @@ var msigLockApproveCmd = &cli.Command{ return actErr } - // It takes the following params: , , , , , - // , , - msgCid, err := api.MsigApprove(ctx, msig, txid, prop, msig, big.Zero(), from, uint64(builtin.MethodsMultisig.LockBalance), params) if err != nil { return err @@ -1165,6 +1162,98 @@ var msigLockApproveCmd = &cli.Command{ }, } +var msigLockCancelCmd = &cli.Command{ + Name: "lock-cancel", + Usage: "Cancel a message to lock up some balance", + ArgsUsage: "[multisigAddress txId startEpoch unlockDuration amount]", + Flags: []cli.Flag{ + &cli.StringFlag{ + Name: "from", + Usage: "account to send the approve message from", + }, + }, + Action: func(cctx *cli.Context) error { + if cctx.Args().Len() != 6 { + return ShowHelp(cctx, fmt.Errorf("must pass multisig address, tx id, start epoch, unlock duration, and amount")) + } + + api, closer, err := GetFullNodeAPI(cctx) + if err != nil { + return err + } + defer closer() + ctx := ReqContext(cctx) + + msig, err := address.NewFromString(cctx.Args().Get(0)) + if err != nil { + return err + } + + txid, err := strconv.ParseUint(cctx.Args().Get(1), 10, 64) + if err != nil { + return err + } + + start, err := strconv.ParseUint(cctx.Args().Get(2), 10, 64) + if err != nil { + return err + } + + duration, err := strconv.ParseUint(cctx.Args().Get(3), 10, 64) + if err != nil { + return err + } + + amount, err := types.ParseFIL(cctx.Args().Get(4)) + if err != nil { + return err + } + + var from address.Address + if cctx.IsSet("from") { + f, err := address.NewFromString(cctx.String("from")) + if err != nil { + return err + } + from = f + } else { + defaddr, err := api.WalletDefaultAddress(ctx) + if err != nil { + return err + } + from = defaddr + } + + params, actErr := actors.SerializeParams(&samsig.LockBalanceParams{ + StartEpoch: abi.ChainEpoch(start), + UnlockDuration: abi.ChainEpoch(duration), + Amount: abi.NewTokenAmount(amount.Int64()), + }) + + if actErr != nil { + return actErr + } + + msgCid, err := api.MsigCancel(ctx, msig, txid, msig, big.Zero(), from, uint64(builtin.MethodsMultisig.LockBalance), params) + if err != nil { + return err + } + + fmt.Println("sent lock cancellation in message: ", msgCid) + + wait, err := api.StateWaitMsg(ctx, msgCid, build.MessageConfidence) + if err != nil { + return err + } + + if wait.Receipt.ExitCode != 0 { + return fmt.Errorf("lock cancellation returned exit %d", wait.Receipt.ExitCode) + } + + return nil + }, +} + var msigVestedCmd = &cli.Command{ Name: "vested", Usage: "Gets the amount vested in an msig between two epochs", From 454c382e7ec024d2de7c7a91f83e6e0d71d78b8b Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Tue, 15 Sep 2020 18:05:33 -0700 Subject: [PATCH 039/303] migrate StateMinerInitialPledgeCollateral --- chain/stmgr/utils.go | 2 +- node/impl/full/state.go | 119 ++++++++++++++++++++-------------------- 2 files changed, 61 insertions(+), 60 deletions(-) diff --git a/chain/stmgr/utils.go b/chain/stmgr/utils.go index 88275f019..1bbc9ccc4 100644 --- a/chain/stmgr/utils.go +++ b/chain/stmgr/utils.go @@ -30,10 +30,10 @@ import ( "github.com/filecoin-project/specs-actors/actors/builtin/paych" "github.com/filecoin-project/specs-actors/actors/builtin/reward" "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" - "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" + "github.com/filecoin-project/lotus/chain/actors/adt" init_ "github.com/filecoin-project/lotus/chain/actors/builtin/init" "github.com/filecoin-project/lotus/chain/actors/builtin/market" "github.com/filecoin-project/lotus/chain/actors/builtin/miner" diff --git a/node/impl/full/state.go b/node/impl/full/state.go index 3ea40388f..d69ba0a41 100644 --- a/node/impl/full/state.go +++ b/node/impl/full/state.go @@ -912,85 +912,86 @@ func (a *StateAPI) StateMinerPreCommitDepositForPower(ctx context.Context, maddr } func (a *StateAPI) StateMinerInitialPledgeCollateral(ctx context.Context, maddr address.Address, pci miner.SectorPreCommitInfo, tsk types.TipSetKey) (types.BigInt, error) { + // TODO: this repeats a lot of the previous function. Fix that. ts, err := a.Chain.GetTipSetFromKey(tsk) if err != nil { return types.EmptyInt, xerrors.Errorf("loading tipset %s: %w", tsk, err) } - var minerState miner.State - var powerState power.State - var rewardState reward.State - - err = a.StateManager.WithParentStateTsk(tsk, func(state *state.StateTree) error { - if err := a.StateManager.WithActor(maddr, a.StateManager.WithActorState(ctx, &minerState))(state); err != nil { - return xerrors.Errorf("getting miner state: %w", err) - } - - if err := a.StateManager.WithActor(builtin.StoragePowerActorAddr, a.StateManager.WithActorState(ctx, &powerState))(state); err != nil { - return xerrors.Errorf("getting power state: %w", err) - } - - if err := a.StateManager.WithActor(builtin.RewardActorAddr, a.StateManager.WithActorState(ctx, &rewardState))(state); err != nil { - return xerrors.Errorf("getting reward state: %w", err) - } - - return nil - }) + state, err := a.StateManager.ParentState(ts) if err != nil { - return types.EmptyInt, err + return types.EmptyInt, xerrors.Errorf("loading state %s: %w", tsk, err) } - dealWeights := market.VerifyDealsForActivationReturn{ - DealWeight: big.Zero(), - VerifiedDealWeight: big.Zero(), - } - - if len(pci.DealIDs) != 0 { - var err error - params, err := actors.SerializeParams(&market.VerifyDealsForActivationParams{ - DealIDs: pci.DealIDs, - SectorExpiry: pci.Expiration, - }) - if err != nil { - return types.EmptyInt, err - } - - ret, err := a.StateManager.Call(ctx, &types.Message{ - From: maddr, - To: builtin.StorageMarketActorAddr, - Method: builtin.MethodsMarket.VerifyDealsForActivation, - Params: params, - }, ts) - if err != nil { - return types.EmptyInt, err - } - - if err := dealWeights.UnmarshalCBOR(bytes.NewReader(ret.MsgRct.Return)); err != nil { - return types.BigInt{}, err - } - } - - mi, err := a.StateMinerInfo(ctx, maddr, tsk) + ssize, err := pci.SealProof.SectorSize() if err != nil { - return types.EmptyInt, err + return types.EmptyInt, xerrors.Errorf("failed to get resolve size: %w", err) } - ssize := mi.SectorSize + store := a.Chain.Store(ctx) - duration := pci.Expiration - ts.Height() // NB: not exactly accurate, but should always lead us to *over* estimate, not under + var sectorWeight abi.StoragePower + if act, err := state.GetActor(market.Address); err != nil { + return types.EmptyInt, xerrors.Errorf("loading miner actor %s: %w", maddr, err) + } else s, err := market.Load(store, act); err != nil { + return types.EmptyInt, xerrors.Errorf("loading market actor state %s: %w", maddr, err) + } else if w, vw, err := s.VerifyDealsForActivation(maddr, pci.DealIDs, ts.Height(), pci.Expiration); err != nil { + return types.EmptyInt, xerrors.Errorf("verifying deals for activation: %w", err) + } else { + // NB: not exactly accurate, but should always lead us to *over* estimate, not under + duration := pci.Expiration - ts.Height() + + // TODO: handle changes to this function across actor upgrades. + sectorWeight = v0miner.QAPowerForWeight(ssize, duration, w, vw) + } + + var ( + powerSmoothed smoothing.FilterEstimate + pledgeCollerateral abi.TokenAmount + ) + if act, err := state.GetActor(power.Address); err != nil { + return types.EmptyInt, xerrors.Errorf("loading miner actor: %w", err) + } else s, err := power.Load(store, act); err != nil { + return types.EmptyInt, xerrors.Errorf("loading power actor state: %w", err) + } else p, err := s.TotalPowerSmoothed(); err != nil { + return types.EmptyInt, xerrors.Errorf("failed to determine total power: %w", err) + } else c, err := s.TotalLocked(); err != nil { + return types.EmptyInt, xerrors.Errorf("failed to determine pledge collateral: %w", err) + } else { + powerSmoothed = p + pledgeCollateral = c + } + + var ( + rewardSmoothed smoothing.FilterEstimate + baselinePower abi.StoragePower + ) + if act, err := state.GetActor(reward.Address); err != nil { + return types.EmptyInt, xerrors.Errorf("loading miner actor: %w", err) + } else s, err := reward.Load(store, act); err != nil { + return types.EmptyInt, xerrors.Errorf("loading reward actor state: %w", err) + } else r, err := s.RewardSmoothed(); err != nil { + return types.EmptyInt, xerrors.Errorf("failed to determine total reward: %w", err) + } else p, err := s.BaselinePower(); err != nil { + return types.EmptyInt, xerrors.Errorf("failed to determine baseline power: %w", err) + } else { + rewardSmoothed = r + baselinePower = p + } + + // TODO: abstract over network upgrades. circSupply, err := a.StateCirculatingSupply(ctx, ts.Key()) if err != nil { return big.Zero(), xerrors.Errorf("getting circulating supply: %w", err) } - sectorWeight := miner.QAPowerForWeight(ssize, duration, dealWeights.DealWeight, dealWeights.VerifiedDealWeight) initialPledge := miner.InitialPledgeForPower( sectorWeight, - rewardState.ThisEpochBaselinePower, - powerState.ThisEpochPledgeCollateral, - rewardState.ThisEpochRewardSmoothed, - powerState.ThisEpochQAPowerSmoothed, + baselinePower, + pledgeCollateral, + rewardSmoothed, + powerSmoothed, circSupply.FilCirculating, ) From 05c11531b1d9cfb2edb3062e22602e9446474fcf Mon Sep 17 00:00:00 2001 From: hannahhoward Date: Tue, 15 Sep 2020 21:06:04 -0700 Subject: [PATCH 040/303] feat(paych): convert paych actor build abstraction for paych actor and switch to using it in payment channel manager and state predicates --- chain/actors/builtin/paych/mock/mock.go | 89 +++++++++++ chain/actors/builtin/paych/paych.go | 56 +++++++ chain/actors/builtin/paych/v0.go | 89 +++++++++++ chain/events/state/predicates.go | 47 +++--- chain/events/state/predicates_test.go | 2 +- chain/stmgr/stmgr.go | 19 +++ cli/paych_test.go | 8 +- paychmgr/manager.go | 37 ++--- paychmgr/mock_test.go | 66 +++------ paychmgr/msglistener_test.go | 2 - paychmgr/paych.go | 97 ++++++------ paychmgr/paych_test.go | 189 +++++++----------------- paychmgr/paychget_test.go | 45 ++---- paychmgr/simple.go | 19 +-- paychmgr/state.go | 41 ++--- 15 files changed, 460 insertions(+), 346 deletions(-) create mode 100644 chain/actors/builtin/paych/mock/mock.go create mode 100644 chain/actors/builtin/paych/paych.go create mode 100644 chain/actors/builtin/paych/v0.go diff --git a/chain/actors/builtin/paych/mock/mock.go b/chain/actors/builtin/paych/mock/mock.go new file mode 100644 index 000000000..31f7fba93 --- /dev/null +++ b/chain/actors/builtin/paych/mock/mock.go @@ -0,0 +1,89 @@ +package mock + +import ( + "io" + + "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/lotus/chain/actors/builtin/paych" +) + +type mockState struct { + from address.Address + to address.Address + settlingAt abi.ChainEpoch + toSend abi.TokenAmount + lanes map[uint64]paych.LaneState +} + +type mockLaneState struct { + redeemed big.Int + nonce uint64 +} + +// NewMockPayChState constructs a state for a payment channel with the set fixed values +// that satisfies the paych.State interface. +func NewMockPayChState(from address.Address, + to address.Address, + settlingAt abi.ChainEpoch, + toSend abi.TokenAmount, + lanes map[uint64]paych.LaneState, +) paych.State { + return &mockState{from, to, settlingAt, toSend, lanes} +} + +// NewMockLaneState constructs a state for a payment channel lane with the set fixed values +// that satisfies the paych.LaneState interface. Useful for populating lanes when +// calling NewMockPayChState +func NewMockLaneState(redeemed big.Int, nonce uint64) paych.LaneState { + return &mockLaneState{redeemed, nonce} +} + +func (ms *mockState) MarshalCBOR(io.Writer) error { + panic("not implemented") +} + +// Channel owner, who has funded the actor +func (ms *mockState) From() address.Address { + return ms.from +} + +// Recipient of payouts from channel +func (ms *mockState) To() address.Address { + return ms.to +} + +// Height at which the channel can be `Collected` +func (ms *mockState) SettlingAt() abi.ChainEpoch { + return ms.settlingAt +} + +// Amount successfully redeemed through the payment channel, paid out on `Collect()` +func (ms *mockState) ToSend() abi.TokenAmount { + return ms.toSend +} + +// Get total number of lanes +func (ms *mockState) LaneCount() (uint64, error) { + return uint64(len(ms.lanes)), nil +} + +// Iterate lane states +func (ms *mockState) ForEachLaneState(cb func(idx uint64, dl paych.LaneState) error) error { + var lastErr error + for lane, state := range ms.lanes { + if err := cb(lane, state); err != nil { + lastErr = err + } + } + return lastErr +} + +func (mls *mockLaneState) Redeemed() big.Int { + return mls.redeemed +} + +func (mls *mockLaneState) Nonce() uint64 { + return mls.nonce +} diff --git a/chain/actors/builtin/paych/paych.go b/chain/actors/builtin/paych/paych.go new file mode 100644 index 000000000..974d64fde --- /dev/null +++ b/chain/actors/builtin/paych/paych.go @@ -0,0 +1,56 @@ +package paych + +import ( + "golang.org/x/xerrors" + + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + big "github.com/filecoin-project/go-state-types/big" + "github.com/filecoin-project/go-state-types/cbor" + v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" + + "github.com/filecoin-project/lotus/chain/actors/adt" + "github.com/filecoin-project/lotus/chain/types" +) + +// Load returns an abstract copy of payment channel state, irregardless of actor version +func Load(store adt.Store, act *types.Actor) (State, error) { + switch act.Code { + case v0builtin.PaymentChannelActorCodeID: + out := v0State{store: store} + err := store.Get(store.Context(), act.Head, &out) + if err != nil { + return nil, err + } + return &out, nil + } + return nil, xerrors.Errorf("unknown actor code %s", act.Code) +} + +// State is an abstract version of payment channel state that works across +// versions +type State interface { + cbor.Marshaler + // Channel owner, who has funded the actor + From() address.Address + // Recipient of payouts from channel + To() address.Address + + // Height at which the channel can be `Collected` + SettlingAt() abi.ChainEpoch + + // Amount successfully redeemed through the payment channel, paid out on `Collect()` + ToSend() abi.TokenAmount + + // Get total number of lanes + LaneCount() (uint64, error) + + // Iterate lane states + ForEachLaneState(cb func(idx uint64, dl LaneState) error) error +} + +// LaneState is an abstract copy of the state of a single lane +type LaneState interface { + Redeemed() big.Int + Nonce() uint64 +} diff --git a/chain/actors/builtin/paych/v0.go b/chain/actors/builtin/paych/v0.go new file mode 100644 index 000000000..16a65bc9b --- /dev/null +++ b/chain/actors/builtin/paych/v0.go @@ -0,0 +1,89 @@ +package paych + +import ( + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + big "github.com/filecoin-project/go-state-types/big" + "github.com/filecoin-project/lotus/chain/actors/adt" + "github.com/filecoin-project/specs-actors/actors/builtin/paych" + v0adt "github.com/filecoin-project/specs-actors/actors/util/adt" +) + +type v0State struct { + paych.State + store adt.Store + lsAmt *v0adt.Array +} + +// Channel owner, who has funded the actor +func (s *v0State) From() address.Address { + return s.State.From +} + +// Recipient of payouts from channel +func (s *v0State) To() address.Address { + return s.State.From +} + +// Height at which the channel can be `Collected` +func (s *v0State) SettlingAt() abi.ChainEpoch { + return s.State.SettlingAt +} + +// Amount successfully redeemed through the payment channel, paid out on `Collect()` +func (s *v0State) ToSend() abi.TokenAmount { + return s.State.ToSend +} + +func (s *v0State) getOrLoadLsAmt() (*v0adt.Array, error) { + if s.lsAmt != nil { + return s.lsAmt, nil + } + + // Get the lane state from the chain + lsamt, err := v0adt.AsArray(s.store, s.State.LaneStates) + if err != nil { + return nil, err + } + + s.lsAmt = lsamt + return lsamt, nil +} + +// Get total number of lanes +func (s *v0State) LaneCount() (uint64, error) { + lsamt, err := s.getOrLoadLsAmt() + if err != nil { + return 0, err + } + return lsamt.Length(), nil +} + +// Iterate lane states +func (s *v0State) ForEachLaneState(cb func(idx uint64, dl LaneState) error) error { + // Get the lane state from the chain + lsamt, err := s.getOrLoadLsAmt() + if err != nil { + return err + } + + // Note: we use a map instead of an array to store laneStates because the + // client sets the lane ID (the index) and potentially they could use a + // very large index. + var ls paych.LaneState + return lsamt.ForEach(&ls, func(i int64) error { + return cb(uint64(i), &v0LaneState{ls}) + }) +} + +type v0LaneState struct { + paych.LaneState +} + +func (ls *v0LaneState) Redeemed() big.Int { + return ls.LaneState.Redeemed +} + +func (ls *v0LaneState) Nonce() uint64 { + return ls.LaneState.Nonce +} diff --git a/chain/events/state/predicates.go b/chain/events/state/predicates.go index 0858793d8..e5caa41d2 100644 --- a/chain/events/state/predicates.go +++ b/chain/events/state/predicates.go @@ -7,13 +7,12 @@ import ( "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/lotus/chain/actors/builtin/paych" "github.com/filecoin-project/specs-actors/actors/builtin" init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" "github.com/filecoin-project/specs-actors/actors/builtin/market" "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/filecoin-project/specs-actors/actors/builtin/paych" "github.com/filecoin-project/specs-actors/actors/util/adt" - "github.com/ipfs/go-cid" cbor "github.com/ipfs/go-ipld-cbor" typegen "github.com/whyrusleeping/cbor-gen" @@ -49,7 +48,7 @@ func NewStatePredicates(api ChainAPI) *StatePredicates { // - err type DiffTipSetKeyFunc func(ctx context.Context, oldState, newState types.TipSetKey) (changed bool, user UserData, err error) -type DiffActorStateFunc func(ctx context.Context, oldActorStateHead, newActorStateHead cid.Cid) (changed bool, user UserData, err error) +type DiffActorStateFunc func(ctx context.Context, oldActorState *types.Actor, newActorState *types.Actor) (changed bool, user UserData, err error) // OnActorStateChanged calls diffStateFunc when the state changes for the given actor func (sp *StatePredicates) OnActorStateChanged(addr address.Address, diffStateFunc DiffActorStateFunc) DiffTipSetKeyFunc { @@ -66,7 +65,7 @@ func (sp *StatePredicates) OnActorStateChanged(addr address.Address, diffStateFu if oldActor.Head.Equals(newActor.Head) { return false, nil, nil } - return diffStateFunc(ctx, oldActor.Head, newActor.Head) + return diffStateFunc(ctx, oldActor, newActor) } } @@ -74,13 +73,13 @@ type DiffStorageMarketStateFunc func(ctx context.Context, oldState *market.State // OnStorageMarketActorChanged calls diffStorageMarketState when the state changes for the market actor func (sp *StatePredicates) OnStorageMarketActorChanged(diffStorageMarketState DiffStorageMarketStateFunc) DiffTipSetKeyFunc { - return sp.OnActorStateChanged(builtin.StorageMarketActorAddr, func(ctx context.Context, oldActorStateHead, newActorStateHead cid.Cid) (changed bool, user UserData, err error) { + return sp.OnActorStateChanged(builtin.StorageMarketActorAddr, func(ctx context.Context, oldActorState, newActorState *types.Actor) (changed bool, user UserData, err error) { var oldState market.State - if err := sp.cst.Get(ctx, oldActorStateHead, &oldState); err != nil { + if err := sp.cst.Get(ctx, oldActorState.Head, &oldState); err != nil { return false, nil, err } var newState market.State - if err := sp.cst.Get(ctx, newActorStateHead, &newState); err != nil { + if err := sp.cst.Get(ctx, newActorState.Head, &newState); err != nil { return false, nil, err } return diffStorageMarketState(ctx, &oldState, &newState) @@ -408,13 +407,13 @@ func (sp *StatePredicates) AvailableBalanceChangedForAddresses(getAddrs func() [ type DiffMinerActorStateFunc func(ctx context.Context, oldState *miner.State, newState *miner.State) (changed bool, user UserData, err error) func (sp *StatePredicates) OnInitActorChange(diffInitActorState DiffInitActorStateFunc) DiffTipSetKeyFunc { - return sp.OnActorStateChanged(builtin.InitActorAddr, func(ctx context.Context, oldActorStateHead, newActorStateHead cid.Cid) (changed bool, user UserData, err error) { + return sp.OnActorStateChanged(builtin.InitActorAddr, func(ctx context.Context, oldActorState, newActorState *types.Actor) (changed bool, user UserData, err error) { var oldState init_.State - if err := sp.cst.Get(ctx, oldActorStateHead, &oldState); err != nil { + if err := sp.cst.Get(ctx, oldActorState.Head, &oldState); err != nil { return false, nil, err } var newState init_.State - if err := sp.cst.Get(ctx, newActorStateHead, &newState); err != nil { + if err := sp.cst.Get(ctx, newActorState.Head, &newState); err != nil { return false, nil, err } return diffInitActorState(ctx, &oldState, &newState) @@ -423,13 +422,13 @@ func (sp *StatePredicates) OnInitActorChange(diffInitActorState DiffInitActorSta } func (sp *StatePredicates) OnMinerActorChange(minerAddr address.Address, diffMinerActorState DiffMinerActorStateFunc) DiffTipSetKeyFunc { - return sp.OnActorStateChanged(minerAddr, func(ctx context.Context, oldActorStateHead, newActorStateHead cid.Cid) (changed bool, user UserData, err error) { + return sp.OnActorStateChanged(minerAddr, func(ctx context.Context, oldActorState, newActorState *types.Actor) (changed bool, user UserData, err error) { var oldState miner.State - if err := sp.cst.Get(ctx, oldActorStateHead, &oldState); err != nil { + if err := sp.cst.Get(ctx, oldActorState.Head, &oldState); err != nil { return false, nil, err } var newState miner.State - if err := sp.cst.Get(ctx, newActorStateHead, &newState); err != nil { + if err := sp.cst.Get(ctx, newActorState.Head, &newState); err != nil { return false, nil, err } return diffMinerActorState(ctx, &oldState, &newState) @@ -608,20 +607,20 @@ func (sp *StatePredicates) OnMinerPreCommitChange() DiffMinerActorStateFunc { } // DiffPaymentChannelStateFunc is function that compares two states for the payment channel -type DiffPaymentChannelStateFunc func(ctx context.Context, oldState *paych.State, newState *paych.State) (changed bool, user UserData, err error) +type DiffPaymentChannelStateFunc func(ctx context.Context, oldState paych.State, newState paych.State) (changed bool, user UserData, err error) // OnPaymentChannelActorChanged calls diffPaymentChannelState when the state changes for the the payment channel actor func (sp *StatePredicates) OnPaymentChannelActorChanged(paychAddr address.Address, diffPaymentChannelState DiffPaymentChannelStateFunc) DiffTipSetKeyFunc { - return sp.OnActorStateChanged(paychAddr, func(ctx context.Context, oldActorStateHead, newActorStateHead cid.Cid) (changed bool, user UserData, err error) { - var oldState paych.State - if err := sp.cst.Get(ctx, oldActorStateHead, &oldState); err != nil { + return sp.OnActorStateChanged(paychAddr, func(ctx context.Context, oldActorState, newActorState *types.Actor) (changed bool, user UserData, err error) { + oldState, err := paych.Load(adt.WrapStore(ctx, sp.cst), oldActorState) + if err != nil { return false, nil, err } - var newState paych.State - if err := sp.cst.Get(ctx, newActorStateHead, &newState); err != nil { + newState, err := paych.Load(adt.WrapStore(ctx, sp.cst), newActorState) + if err != nil { return false, nil, err } - return diffPaymentChannelState(ctx, &oldState, &newState) + return diffPaymentChannelState(ctx, oldState, newState) }) } @@ -633,13 +632,13 @@ type PayChToSendChange struct { // OnToSendAmountChanges monitors changes on the total amount to send from one party to the other on a payment channel func (sp *StatePredicates) OnToSendAmountChanges() DiffPaymentChannelStateFunc { - return func(ctx context.Context, oldState *paych.State, newState *paych.State) (changed bool, user UserData, err error) { - if oldState.ToSend.Equals(newState.ToSend) { + return func(ctx context.Context, oldState paych.State, newState paych.State) (changed bool, user UserData, err error) { + if oldState.ToSend().Equals(newState.ToSend()) { return false, nil, nil } return true, &PayChToSendChange{ - OldToSend: oldState.ToSend, - NewToSend: newState.ToSend, + OldToSend: oldState.ToSend(), + NewToSend: newState.ToSend(), }, nil } } diff --git a/chain/events/state/predicates_test.go b/chain/events/state/predicates_test.go index a1dccfadc..7117a96cc 100644 --- a/chain/events/state/predicates_test.go +++ b/chain/events/state/predicates_test.go @@ -221,7 +221,7 @@ func TestMarketPredicates(t *testing.T) { // Test that OnActorStateChanged does not call the callback if the state has not changed mockAddr, err := address.NewFromString("t01") require.NoError(t, err) - actorDiffFn := preds.OnActorStateChanged(mockAddr, func(context.Context, cid.Cid, cid.Cid) (bool, UserData, error) { + actorDiffFn := preds.OnActorStateChanged(mockAddr, func(context.Context, *types.Actor, *types.Actor) (bool, UserData, error) { t.Fatal("No state change so this should not be called") return false, nil, nil }) diff --git a/chain/stmgr/stmgr.go b/chain/stmgr/stmgr.go index f71b788c8..ae8b47bce 100644 --- a/chain/stmgr/stmgr.go +++ b/chain/stmgr/stmgr.go @@ -25,6 +25,7 @@ import ( "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/actors" "github.com/filecoin-project/lotus/chain/actors/builtin/market" + "github.com/filecoin-project/lotus/chain/actors/builtin/paych" "github.com/filecoin-project/lotus/chain/actors/builtin/power" "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/store" @@ -1145,3 +1146,21 @@ func (sm *StateManager) GetNtwkVersion(ctx context.Context, height abi.ChainEpoc return build.NewestNetworkVersion } + +func (sm *StateManager) GetPaychState(ctx context.Context, addr address.Address, ts *types.TipSet) (*types.Actor, paych.State, error) { + st, err := sm.ParentState(ts) + if err != nil { + return nil, nil, err + } + + act, err := st.GetActor(addr) + if err != nil { + return nil, nil, err + } + + actState, err := paych.Load(sm.cs.Store(ctx), act) + if err != nil { + return nil, nil, err + } + return act, actState, nil +} diff --git a/cli/paych_test.go b/cli/paych_test.go index cccc80ff4..1497a54a6 100644 --- a/cli/paych_test.go +++ b/cli/paych_test.go @@ -24,7 +24,8 @@ import ( "github.com/filecoin-project/lotus/chain/events" "github.com/filecoin-project/lotus/api/apibstore" - "github.com/filecoin-project/specs-actors/actors/builtin/paych" + "github.com/filecoin-project/lotus/chain/actors/adt" + "github.com/filecoin-project/lotus/chain/actors/builtin/paych" cbor "github.com/ipfs/go-ipld-cbor" "github.com/filecoin-project/go-address" @@ -88,7 +89,7 @@ func TestPaymentChannels(t *testing.T) { // Wait for the chain to reach the settle height chState := getPaychState(ctx, t, paymentReceiver, chAddr) - waitForHeight(ctx, t, paymentReceiver, chState.SettlingAt) + waitForHeight(ctx, t, paymentReceiver, chState.SettlingAt()) // receiver: paych collect cmd = []string{chAddr.String()} @@ -540,8 +541,7 @@ func getPaychState(ctx context.Context, t *testing.T, node test.TestNode, chAddr require.NoError(t, err) store := cbor.NewCborStore(apibstore.NewAPIBlockstore(node)) - var chState paych.State - err = store.Get(ctx, act.Head, &chState) + chState, err := paych.Load(adt.WrapStore(ctx, store), act) require.NoError(t, err) return chState diff --git a/paychmgr/manager.go b/paychmgr/manager.go index 4b102f062..4556c37be 100644 --- a/paychmgr/manager.go +++ b/paychmgr/manager.go @@ -4,28 +4,23 @@ import ( "context" "sync" - "github.com/filecoin-project/go-state-types/crypto" - - "github.com/filecoin-project/lotus/node/modules/helpers" - - "github.com/ipfs/go-datastore" - - xerrors "golang.org/x/xerrors" - - "github.com/filecoin-project/lotus/api" - - "github.com/filecoin-project/specs-actors/actors/builtin/paych" - "github.com/filecoin-project/specs-actors/actors/util/adt" - "github.com/ipfs/go-cid" + "github.com/ipfs/go-datastore" logging "github.com/ipfs/go-log/v2" "go.uber.org/fx" + xerrors "golang.org/x/xerrors" "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/crypto" + v0paych "github.com/filecoin-project/specs-actors/actors/builtin/paych" + "github.com/filecoin-project/lotus/api" + "github.com/filecoin-project/lotus/chain/actors/adt" + "github.com/filecoin-project/lotus/chain/actors/builtin/paych" "github.com/filecoin-project/lotus/chain/stmgr" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/node/impl/full" + "github.com/filecoin-project/lotus/node/modules/helpers" ) var log = logging.Logger("paych") @@ -40,9 +35,9 @@ type PaychAPI struct { // stateManagerAPI defines the methods needed from StateManager type stateManagerAPI interface { - LoadActorState(ctx context.Context, a address.Address, out interface{}, ts *types.TipSet) (*types.Actor, error) + ResolveToKeyAddress(ctx context.Context, addr address.Address, ts *types.TipSet) (address.Address, error) + GetPaychState(ctx context.Context, addr address.Address, ts *types.TipSet) (*types.Actor, paych.State, error) Call(ctx context.Context, msg *types.Message, ts *types.TipSet) (*api.InvocResult, error) - AdtStore(ctx context.Context) adt.Store } // paychAPI defines the API methods needed by the payment channel manager @@ -226,7 +221,7 @@ func (pm *Manager) GetChannelInfo(addr address.Address) (*ChannelInfo, error) { return ca.getChannelInfo(addr) } -func (pm *Manager) CreateVoucher(ctx context.Context, ch address.Address, voucher paych.SignedVoucher) (*api.VoucherCreateResult, error) { +func (pm *Manager) CreateVoucher(ctx context.Context, ch address.Address, voucher v0paych.SignedVoucher) (*api.VoucherCreateResult, error) { ca, err := pm.accessorByAddress(ch) if err != nil { return nil, err @@ -238,7 +233,7 @@ func (pm *Manager) CreateVoucher(ctx context.Context, ch address.Address, vouche // CheckVoucherValid checks if the given voucher is valid (is or could become spendable at some point). // If the channel is not in the store, fetches the channel from state (and checks that // the channel To address is owned by the wallet). -func (pm *Manager) CheckVoucherValid(ctx context.Context, ch address.Address, sv *paych.SignedVoucher) error { +func (pm *Manager) CheckVoucherValid(ctx context.Context, ch address.Address, sv *v0paych.SignedVoucher) error { // Get an accessor for the channel, creating it from state if necessary ca, err := pm.inboundChannelAccessor(ctx, ch) if err != nil { @@ -250,7 +245,7 @@ func (pm *Manager) CheckVoucherValid(ctx context.Context, ch address.Address, sv } // CheckVoucherSpendable checks if the given voucher is currently spendable -func (pm *Manager) CheckVoucherSpendable(ctx context.Context, ch address.Address, sv *paych.SignedVoucher, secret []byte, proof []byte) (bool, error) { +func (pm *Manager) CheckVoucherSpendable(ctx context.Context, ch address.Address, sv *v0paych.SignedVoucher, secret []byte, proof []byte) (bool, error) { ca, err := pm.accessorByAddress(ch) if err != nil { return false, err @@ -261,7 +256,7 @@ func (pm *Manager) CheckVoucherSpendable(ctx context.Context, ch address.Address // AddVoucherOutbound adds a voucher for an outbound channel. // Returns an error if the channel is not already in the store. -func (pm *Manager) AddVoucherOutbound(ctx context.Context, ch address.Address, sv *paych.SignedVoucher, proof []byte, minDelta types.BigInt) (types.BigInt, error) { +func (pm *Manager) AddVoucherOutbound(ctx context.Context, ch address.Address, sv *v0paych.SignedVoucher, proof []byte, minDelta types.BigInt) (types.BigInt, error) { ca, err := pm.accessorByAddress(ch) if err != nil { return types.NewInt(0), err @@ -272,7 +267,7 @@ func (pm *Manager) AddVoucherOutbound(ctx context.Context, ch address.Address, s // AddVoucherInbound adds a voucher for an inbound channel. // If the channel is not in the store, fetches the channel from state (and checks that // the channel To address is owned by the wallet). -func (pm *Manager) AddVoucherInbound(ctx context.Context, ch address.Address, sv *paych.SignedVoucher, proof []byte, minDelta types.BigInt) (types.BigInt, error) { +func (pm *Manager) AddVoucherInbound(ctx context.Context, ch address.Address, sv *v0paych.SignedVoucher, proof []byte, minDelta types.BigInt) (types.BigInt, error) { // Get an accessor for the channel, creating it from state if necessary ca, err := pm.inboundChannelAccessor(ctx, ch) if err != nil { @@ -341,7 +336,7 @@ func (pm *Manager) trackInboundChannel(ctx context.Context, ch address.Address) return pm.store.TrackChannel(stateCi) } -func (pm *Manager) SubmitVoucher(ctx context.Context, ch address.Address, sv *paych.SignedVoucher, secret []byte, proof []byte) (cid.Cid, error) { +func (pm *Manager) SubmitVoucher(ctx context.Context, ch address.Address, sv *v0paych.SignedVoucher, secret []byte, proof []byte) (cid.Cid, error) { ca, err := pm.accessorByAddress(ch) if err != nil { return cid.Undef, err diff --git a/paychmgr/mock_test.go b/paychmgr/mock_test.go index bc19de223..c761221d2 100644 --- a/paychmgr/mock_test.go +++ b/paychmgr/mock_test.go @@ -2,23 +2,18 @@ package paychmgr import ( "context" - "fmt" + "errors" "sync" - "github.com/filecoin-project/lotus/lib/sigs" - - "github.com/filecoin-project/go-state-types/crypto" - - cbornode "github.com/ipfs/go-ipld-cbor" - - "github.com/filecoin-project/specs-actors/actors/util/adt" + "github.com/ipfs/go-cid" "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/crypto" + "github.com/filecoin-project/lotus/api" + "github.com/filecoin-project/lotus/chain/actors/builtin/paych" "github.com/filecoin-project/lotus/chain/types" - "github.com/filecoin-project/specs-actors/actors/builtin/account" - "github.com/filecoin-project/specs-actors/actors/builtin/paych" - "github.com/ipfs/go-cid" + "github.com/filecoin-project/lotus/lib/sigs" ) type mockManagerAPI struct { @@ -40,29 +35,23 @@ type mockPchState struct { type mockStateManager struct { lk sync.Mutex - accountState map[address.Address]account.State + accountState map[address.Address]address.Address paychState map[address.Address]mockPchState - store adt.Store response *api.InvocResult lastCall *types.Message } func newMockStateManager() *mockStateManager { return &mockStateManager{ - accountState: make(map[address.Address]account.State), + accountState: make(map[address.Address]address.Address), paychState: make(map[address.Address]mockPchState), - store: adt.WrapStore(context.Background(), cbornode.NewMemCborStore()), } } -func (sm *mockStateManager) AdtStore(ctx context.Context) adt.Store { - return sm.store -} - -func (sm *mockStateManager) setAccountState(a address.Address, state account.State) { +func (sm *mockStateManager) setAccountAddress(a address.Address, lookup address.Address) { sm.lk.Lock() defer sm.lk.Unlock() - sm.accountState[a] = state + sm.accountState[a] = lookup } func (sm *mockStateManager) setPaychState(a address.Address, actor *types.Actor, state paych.State) { @@ -71,31 +60,24 @@ func (sm *mockStateManager) setPaychState(a address.Address, actor *types.Actor, sm.paychState[a] = mockPchState{actor, state} } -func (sm *mockStateManager) storeLaneStates(laneStates map[uint64]paych.LaneState) (cid.Cid, error) { - arr := adt.MakeEmptyArray(sm.store) - for i, ls := range laneStates { - ls := ls - if err := arr.Set(i, &ls); err != nil { - return cid.Undef, err - } - } - return arr.Root() -} - -func (sm *mockStateManager) LoadActorState(ctx context.Context, a address.Address, out interface{}, ts *types.TipSet) (*types.Actor, error) { +func (sm *mockStateManager) ResolveToKeyAddress(ctx context.Context, addr address.Address, ts *types.TipSet) (address.Address, error) { sm.lk.Lock() defer sm.lk.Unlock() + keyAddr, ok := sm.accountState[addr] + if !ok { + return address.Undef, errors.New("not found") + } + return keyAddr, nil +} - if outState, ok := out.(*account.State); ok { - *outState = sm.accountState[a] - return nil, nil +func (sm *mockStateManager) GetPaychState(ctx context.Context, addr address.Address, ts *types.TipSet) (*types.Actor, paych.State, error) { + sm.lk.Lock() + defer sm.lk.Unlock() + info, ok := sm.paychState[addr] + if !ok { + return nil, nil, errors.New("not found") } - if outState, ok := out.(*paych.State); ok { - info := sm.paychState[a] - *outState = info.state - return info.actor, nil - } - panic(fmt.Sprintf("unexpected state type %v", out)) + return info.actor, info.state, nil } func (sm *mockStateManager) setCallResponse(response *api.InvocResult) { diff --git a/paychmgr/msglistener_test.go b/paychmgr/msglistener_test.go index 2c3ae16e4..4b8ae6f30 100644 --- a/paychmgr/msglistener_test.go +++ b/paychmgr/msglistener_test.go @@ -4,9 +4,7 @@ import ( "testing" "github.com/ipfs/go-cid" - "github.com/stretchr/testify/require" - "golang.org/x/xerrors" ) diff --git a/paychmgr/paych.go b/paychmgr/paych.go index 20d76b7fd..53f16b4fc 100644 --- a/paychmgr/paych.go +++ b/paychmgr/paych.go @@ -5,22 +5,20 @@ import ( "context" "fmt" - "github.com/filecoin-project/lotus/api" - - "github.com/filecoin-project/specs-actors/actors/util/adt" - "github.com/ipfs/go-cid" + "golang.org/x/xerrors" "github.com/filecoin-project/go-address" cborutil "github.com/filecoin-project/go-cbor-util" "github.com/filecoin-project/go-state-types/big" + "github.com/filecoin-project/specs-actors/actors/builtin" + v0paych "github.com/filecoin-project/specs-actors/actors/builtin/paych" + + "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/chain/actors" + "github.com/filecoin-project/lotus/chain/actors/builtin/paych" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/lib/sigs" - "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/account" - "github.com/filecoin-project/specs-actors/actors/builtin/paych" - "golang.org/x/xerrors" ) // insufficientFundsErr indicates that there are not enough funds in the @@ -45,6 +43,19 @@ func (e *ErrInsufficientFunds) Shortfall() types.BigInt { return e.shortfall } +type laneState struct { + redeemed big.Int + nonce uint64 +} + +func (ls laneState) Redeemed() big.Int { + return ls.redeemed +} + +func (ls laneState) Nonce() uint64 { + return ls.nonce +} + // channelAccessor is used to simplify locking when accessing a channel type channelAccessor struct { from address.Address @@ -92,7 +103,7 @@ func (ca *channelAccessor) outboundActiveByFromTo(from, to address.Address) (*Ch // nonce, signing the voucher and storing it in the local datastore. // If there are not enough funds in the channel to create the voucher, returns // the shortfall in funds. -func (ca *channelAccessor) createVoucher(ctx context.Context, ch address.Address, voucher paych.SignedVoucher) (*api.VoucherCreateResult, error) { +func (ca *channelAccessor) createVoucher(ctx context.Context, ch address.Address, voucher v0paych.SignedVoucher) (*api.VoucherCreateResult, error) { ca.lk.Lock() defer ca.lk.Unlock() @@ -151,14 +162,14 @@ func (ca *channelAccessor) nextNonceForLane(ci *ChannelInfo, lane uint64) uint64 return maxnonce + 1 } -func (ca *channelAccessor) checkVoucherValid(ctx context.Context, ch address.Address, sv *paych.SignedVoucher) (map[uint64]*paych.LaneState, error) { +func (ca *channelAccessor) checkVoucherValid(ctx context.Context, ch address.Address, sv *v0paych.SignedVoucher) (map[uint64]paych.LaneState, error) { ca.lk.Lock() defer ca.lk.Unlock() return ca.checkVoucherValidUnlocked(ctx, ch, sv) } -func (ca *channelAccessor) checkVoucherValidUnlocked(ctx context.Context, ch address.Address, sv *paych.SignedVoucher) (map[uint64]*paych.LaneState, error) { +func (ca *channelAccessor) checkVoucherValidUnlocked(ctx context.Context, ch address.Address, sv *v0paych.SignedVoucher) (map[uint64]paych.LaneState, error) { if sv.ChannelAddr != ch { return nil, xerrors.Errorf("voucher ChannelAddr doesn't match channel address, got %s, expected %s", sv.ChannelAddr, ch) } @@ -170,12 +181,10 @@ func (ca *channelAccessor) checkVoucherValidUnlocked(ctx context.Context, ch add } // Load channel "From" account actor state - var actState account.State - _, err = ca.api.LoadActorState(ctx, pchState.From, &actState, nil) + from, err := ca.api.ResolveToKeyAddress(ctx, pchState.From(), nil) if err != nil { return nil, err } - from := actState.Address // verify voucher signature vb, err := sv.SigningBytes() @@ -199,12 +208,12 @@ func (ca *channelAccessor) checkVoucherValidUnlocked(ctx context.Context, ch add // If the new voucher nonce value is less than the highest known // nonce for the lane ls, lsExists := laneStates[sv.Lane] - if lsExists && sv.Nonce <= ls.Nonce { + if lsExists && sv.Nonce <= ls.Nonce() { return nil, fmt.Errorf("nonce too low") } // If the voucher amount is less than the highest known voucher amount - if lsExists && sv.Amount.LessThanEqual(ls.Redeemed) { + if lsExists && sv.Amount.LessThanEqual(ls.Redeemed()) { return nil, fmt.Errorf("voucher amount is lower than amount for voucher with lower nonce") } @@ -230,7 +239,7 @@ func (ca *channelAccessor) checkVoucherValidUnlocked(ctx context.Context, ch add // Total required balance = total redeemed + toSend // Must not exceed actor balance - newTotal := types.BigAdd(totalRedeemed, pchState.ToSend) + newTotal := types.BigAdd(totalRedeemed, pchState.ToSend()) if act.Balance.LessThan(newTotal) { return nil, newErrInsufficientFunds(types.BigSub(newTotal, act.Balance)) } @@ -242,7 +251,7 @@ func (ca *channelAccessor) checkVoucherValidUnlocked(ctx context.Context, ch add return laneStates, nil } -func (ca *channelAccessor) checkVoucherSpendable(ctx context.Context, ch address.Address, sv *paych.SignedVoucher, secret []byte, proof []byte) (bool, error) { +func (ca *channelAccessor) checkVoucherSpendable(ctx context.Context, ch address.Address, sv *v0paych.SignedVoucher, secret []byte, proof []byte) (bool, error) { ca.lk.Lock() defer ca.lk.Unlock() @@ -281,7 +290,7 @@ func (ca *channelAccessor) checkVoucherSpendable(ctx context.Context, ch address } } - enc, err := actors.SerializeParams(&paych.UpdateChannelStateParams{ + enc, err := actors.SerializeParams(&v0paych.UpdateChannelStateParams{ Sv: *sv, Secret: secret, Proof: proof, @@ -308,22 +317,22 @@ func (ca *channelAccessor) checkVoucherSpendable(ctx context.Context, ch address } func (ca *channelAccessor) getPaychRecipient(ctx context.Context, ch address.Address) (address.Address, error) { - var state paych.State - if _, err := ca.api.LoadActorState(ctx, ch, &state, nil); err != nil { + _, state, err := ca.api.GetPaychState(ctx, ch, nil) + if err != nil { return address.Address{}, err } - return state.To, nil + return state.To(), nil } -func (ca *channelAccessor) addVoucher(ctx context.Context, ch address.Address, sv *paych.SignedVoucher, proof []byte, minDelta types.BigInt) (types.BigInt, error) { +func (ca *channelAccessor) addVoucher(ctx context.Context, ch address.Address, sv *v0paych.SignedVoucher, proof []byte, minDelta types.BigInt) (types.BigInt, error) { ca.lk.Lock() defer ca.lk.Unlock() return ca.addVoucherUnlocked(ctx, ch, sv, proof, minDelta) } -func (ca *channelAccessor) addVoucherUnlocked(ctx context.Context, ch address.Address, sv *paych.SignedVoucher, proof []byte, minDelta types.BigInt) (types.BigInt, error) { +func (ca *channelAccessor) addVoucherUnlocked(ctx context.Context, ch address.Address, sv *v0paych.SignedVoucher, proof []byte, minDelta types.BigInt) (types.BigInt, error) { ci, err := ca.store.ByAddress(ch) if err != nil { return types.BigInt{}, err @@ -367,7 +376,7 @@ func (ca *channelAccessor) addVoucherUnlocked(ctx context.Context, ch address.Ad laneState, exists := laneStates[sv.Lane] redeemed := big.NewInt(0) if exists { - redeemed = laneState.Redeemed + redeemed = laneState.Redeemed() } delta := types.BigSub(sv.Amount, redeemed) @@ -387,7 +396,7 @@ func (ca *channelAccessor) addVoucherUnlocked(ctx context.Context, ch address.Ad return delta, ca.store.putChannelInfo(ci) } -func (ca *channelAccessor) submitVoucher(ctx context.Context, ch address.Address, sv *paych.SignedVoucher, secret []byte, proof []byte) (cid.Cid, error) { +func (ca *channelAccessor) submitVoucher(ctx context.Context, ch address.Address, sv *v0paych.SignedVoucher, secret []byte, proof []byte) (cid.Cid, error) { ca.lk.Lock() defer ca.lk.Unlock() @@ -428,7 +437,7 @@ func (ca *channelAccessor) submitVoucher(ctx context.Context, ch address.Address } } - enc, err := actors.SerializeParams(&paych.UpdateChannelStateParams{ + enc, err := actors.SerializeParams(&v0paych.UpdateChannelStateParams{ Sv: *sv, Secret: secret, Proof: proof, @@ -487,13 +496,11 @@ func (ca *channelAccessor) listVouchers(ctx context.Context, ch address.Address) // laneState gets the LaneStates from chain, then applies all vouchers in // the data store over the chain state -func (ca *channelAccessor) laneState(ctx context.Context, state *paych.State, ch address.Address) (map[uint64]*paych.LaneState, error) { +func (ca *channelAccessor) laneState(ctx context.Context, state paych.State, ch address.Address) (map[uint64]paych.LaneState, error) { // TODO: we probably want to call UpdateChannelState with all vouchers to be fully correct // (but technically dont't need to) - // Get the lane state from the chain - store := ca.api.AdtStore(ctx) - lsamt, err := adt.AsArray(store, state.LaneStates) + laneCount, err := state.LaneCount() if err != nil { return nil, err } @@ -501,11 +508,9 @@ func (ca *channelAccessor) laneState(ctx context.Context, state *paych.State, ch // Note: we use a map instead of an array to store laneStates because the // client sets the lane ID (the index) and potentially they could use a // very large index. - var ls paych.LaneState - laneStates := make(map[uint64]*paych.LaneState, lsamt.Length()) - err = lsamt.ForEach(&ls, func(i int64) error { - current := ls - laneStates[uint64(i)] = ¤t + laneStates := make(map[uint64]paych.LaneState, laneCount) + err = state.ForEachLaneState(func(idx uint64, ls paych.LaneState) error { + laneStates[idx] = ls return nil }) if err != nil { @@ -526,27 +531,19 @@ func (ca *channelAccessor) laneState(ctx context.Context, state *paych.State, ch // If there's a voucher for a lane that isn't in chain state just // create it ls, ok := laneStates[v.Voucher.Lane] - if !ok { - ls = &paych.LaneState{ - Redeemed: types.NewInt(0), - Nonce: 0, - } - laneStates[v.Voucher.Lane] = ls - } - if v.Voucher.Nonce < ls.Nonce { + if ok && v.Voucher.Nonce < ls.Nonce() { continue } - ls.Nonce = v.Voucher.Nonce - ls.Redeemed = v.Voucher.Amount + laneStates[v.Voucher.Lane] = laneState{v.Voucher.Amount, v.Voucher.Nonce} } return laneStates, nil } // Get the total redeemed amount across all lanes, after applying the voucher -func (ca *channelAccessor) totalRedeemedWithVoucher(laneStates map[uint64]*paych.LaneState, sv *paych.SignedVoucher) (big.Int, error) { +func (ca *channelAccessor) totalRedeemedWithVoucher(laneStates map[uint64]paych.LaneState, sv *v0paych.SignedVoucher) (big.Int, error) { // TODO: merges if len(sv.Merges) != 0 { return big.Int{}, xerrors.Errorf("dont currently support paych lane merges") @@ -554,17 +551,17 @@ func (ca *channelAccessor) totalRedeemedWithVoucher(laneStates map[uint64]*paych total := big.NewInt(0) for _, ls := range laneStates { - total = big.Add(total, ls.Redeemed) + total = big.Add(total, ls.Redeemed()) } lane, ok := laneStates[sv.Lane] if ok { // If the voucher is for an existing lane, and the voucher nonce // is higher than the lane nonce - if sv.Nonce > lane.Nonce { + if sv.Nonce > lane.Nonce() { // Add the delta between the redeemed amount and the voucher // amount to the total - delta := big.Sub(sv.Amount, lane.Redeemed) + delta := big.Sub(sv.Amount, lane.Redeemed()) total = big.Add(total, delta) } } else { diff --git a/paychmgr/paych_test.go b/paychmgr/paych_test.go index 18c6655da..434c83e9c 100644 --- a/paychmgr/paych_test.go +++ b/paychmgr/paych_test.go @@ -5,31 +5,24 @@ import ( "context" "testing" - "github.com/filecoin-project/lotus/api" - - "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/ipfs/go-cid" - - "github.com/filecoin-project/go-state-types/crypto" - "github.com/filecoin-project/lotus/lib/sigs" - - "github.com/stretchr/testify/require" - - "github.com/filecoin-project/go-state-types/big" - - "github.com/filecoin-project/go-state-types/abi" - tutils "github.com/filecoin-project/specs-actors/support/testing" - - "github.com/filecoin-project/specs-actors/actors/builtin/paych" - - "github.com/filecoin-project/specs-actors/actors/builtin/account" - - "github.com/filecoin-project/go-address" - "github.com/filecoin-project/lotus/chain/types" - ds "github.com/ipfs/go-datastore" ds_sync "github.com/ipfs/go-datastore/sync" + "github.com/stretchr/testify/require" + + "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/crypto" + "github.com/filecoin-project/specs-actors/actors/builtin" + v0paych "github.com/filecoin-project/specs-actors/actors/builtin/paych" + tutils "github.com/filecoin-project/specs-actors/support/testing" + + "github.com/filecoin-project/lotus/api" + "github.com/filecoin-project/lotus/chain/actors/builtin/paych" + paychmock "github.com/filecoin-project/lotus/chain/actors/builtin/paych/mock" + "github.com/filecoin-project/lotus/chain/types" + "github.com/filecoin-project/lotus/lib/sigs" ) func TestCheckVoucherValid(t *testing.T) { @@ -46,8 +39,8 @@ func TestCheckVoucherValid(t *testing.T) { toAcct := tutils.NewActorAddr(t, "toAct") mock := newMockManagerAPI() - mock.setAccountState(fromAcct, account.State{Address: from}) - mock.setAccountState(toAcct, account.State{Address: to}) + mock.setAccountAddress(fromAcct, from) + mock.setAccountAddress(toAcct, to) tcases := []struct { name string @@ -96,10 +89,7 @@ func TestCheckVoucherValid(t *testing.T) { voucherLane: 1, voucherNonce: 2, laneStates: map[uint64]paych.LaneState{ - 1: { - Redeemed: big.NewInt(2), - Nonce: 3, - }, + 1: paychmock.NewMockLaneState(big.NewInt(2), 3), }, }, { name: "passes when nonce higher", @@ -110,10 +100,7 @@ func TestCheckVoucherValid(t *testing.T) { voucherLane: 1, voucherNonce: 3, laneStates: map[uint64]paych.LaneState{ - 1: { - Redeemed: big.NewInt(2), - Nonce: 2, - }, + 1: paychmock.NewMockLaneState(big.NewInt(2), 2), }, }, { name: "passes when nonce for different lane", @@ -124,10 +111,7 @@ func TestCheckVoucherValid(t *testing.T) { voucherLane: 2, voucherNonce: 2, laneStates: map[uint64]paych.LaneState{ - 1: { - Redeemed: big.NewInt(2), - Nonce: 3, - }, + 1: paychmock.NewMockLaneState(big.NewInt(2), 3), }, }, { name: "fails when voucher has higher nonce but lower value than lane state", @@ -139,10 +123,7 @@ func TestCheckVoucherValid(t *testing.T) { voucherLane: 1, voucherNonce: 3, laneStates: map[uint64]paych.LaneState{ - 1: { - Redeemed: big.NewInt(6), - Nonce: 2, - }, + 1: paychmock.NewMockLaneState(big.NewInt(6), 2), }, }, { name: "fails when voucher + ToSend > balance", @@ -168,10 +149,7 @@ func TestCheckVoucherValid(t *testing.T) { voucherNonce: 2, laneStates: map[uint64]paych.LaneState{ // Lane 1 (same as voucher lane 1) - 1: { - Redeemed: big.NewInt(4), - Nonce: 1, - }, + 1: paychmock.NewMockLaneState(big.NewInt(4), 1), }, }, { // required balance = toSend + total redeemed @@ -188,10 +166,7 @@ func TestCheckVoucherValid(t *testing.T) { voucherNonce: 1, laneStates: map[uint64]paych.LaneState{ // Lane 2 (different from voucher lane 1) - 2: { - Redeemed: big.NewInt(4), - Nonce: 1, - }, + 2: paychmock.NewMockLaneState(big.NewInt(4), 1), }, }} @@ -208,18 +183,8 @@ func TestCheckVoucherValid(t *testing.T) { Balance: tcase.actorBalance, } - // Set the state of the channel's lanes - laneStates, err := mock.storeLaneStates(tcase.laneStates) - require.NoError(t, err) - - mock.setPaychState(ch, act, paych.State{ - From: fromAcct, - To: toAcct, - ToSend: tcase.toSend, - SettlingAt: abi.ChainEpoch(0), - MinSettleHeight: abi.ChainEpoch(0), - LaneStates: laneStates, - }) + mock.setPaychState(ch, act, paychmock.NewMockPayChState( + fromAcct, toAcct, abi.ChainEpoch(0), tcase.toSend, tcase.laneStates)) // Create a manager mgr, err := newManager(store, mock) @@ -255,22 +220,16 @@ func TestCheckVoucherValidCountingAllLanes(t *testing.T) { minDelta := big.NewInt(0) mock := newMockManagerAPI() - mock.setAccountState(fromAcct, account.State{Address: from}) - mock.setAccountState(toAcct, account.State{Address: to}) + mock.setAccountAddress(fromAcct, from) + mock.setAccountAddress(toAcct, to) store := NewStore(ds_sync.MutexWrap(ds.NewMapDatastore())) actorBalance := big.NewInt(10) toSend := big.NewInt(1) laneStates := map[uint64]paych.LaneState{ - 1: { - Nonce: 1, - Redeemed: big.NewInt(3), - }, - 2: { - Nonce: 1, - Redeemed: big.NewInt(4), - }, + 1: paychmock.NewMockLaneState(big.NewInt(3), 1), + 2: paychmock.NewMockLaneState(big.NewInt(4), 1), } act := &types.Actor{ @@ -280,16 +239,7 @@ func TestCheckVoucherValidCountingAllLanes(t *testing.T) { Balance: actorBalance, } - lsCid, err := mock.storeLaneStates(laneStates) - require.NoError(t, err) - mock.setPaychState(ch, act, paych.State{ - From: fromAcct, - To: toAcct, - ToSend: toSend, - SettlingAt: abi.ChainEpoch(0), - MinSettleHeight: abi.ChainEpoch(0), - LaneStates: lsCid, - }) + mock.setPaychState(ch, act, paychmock.NewMockPayChState(fromAcct, toAcct, abi.ChainEpoch(0), toSend, laneStates)) mgr, err := newManager(store, mock) require.NoError(t, err) @@ -389,7 +339,7 @@ func TestCreateVoucher(t *testing.T) { // Create a voucher in lane 1 voucherLane1Amt := big.NewInt(5) - voucher := paych.SignedVoucher{ + voucher := v0paych.SignedVoucher{ Lane: 1, Amount: voucherLane1Amt, } @@ -404,7 +354,7 @@ func TestCreateVoucher(t *testing.T) { // Create a voucher in lane 1 again, with a higher amount voucherLane1Amt = big.NewInt(8) - voucher = paych.SignedVoucher{ + voucher = v0paych.SignedVoucher{ Lane: 1, Amount: voucherLane1Amt, } @@ -419,7 +369,7 @@ func TestCreateVoucher(t *testing.T) { // Create a voucher in lane 2 that covers all the remaining funds // in the channel voucherLane2Amt := big.Sub(s.amt, voucherLane1Amt) - voucher = paych.SignedVoucher{ + voucher = v0paych.SignedVoucher{ Lane: 2, Amount: voucherLane2Amt, } @@ -433,7 +383,7 @@ func TestCreateVoucher(t *testing.T) { // Create a voucher in lane 2 that exceeds the remaining funds in the // channel voucherLane2Amt = big.Add(voucherLane2Amt, big.NewInt(1)) - voucher = paych.SignedVoucher{ + voucher = v0paych.SignedVoucher{ Lane: 2, Amount: voucherLane2Amt, } @@ -567,8 +517,8 @@ func TestAllocateLaneWithExistingLaneState(t *testing.T) { toAcct := tutils.NewActorAddr(t, "toAct") mock := newMockManagerAPI() - mock.setAccountState(fromAcct, account.State{Address: from}) - mock.setAccountState(toAcct, account.State{Address: to}) + mock.setAccountAddress(fromAcct, from) + mock.setAccountAddress(toAcct, to) mock.addWalletAddress(to) store := NewStore(ds_sync.MutexWrap(ds.NewMapDatastore())) @@ -584,16 +534,7 @@ func TestAllocateLaneWithExistingLaneState(t *testing.T) { Balance: actorBalance, } - arr, err := adt.MakeEmptyArray(mock.store).Root() - require.NoError(t, err) - mock.setPaychState(ch, act, paych.State{ - From: fromAcct, - To: toAcct, - ToSend: toSend, - SettlingAt: abi.ChainEpoch(0), - MinSettleHeight: abi.ChainEpoch(0), - LaneStates: arr, - }) + mock.setPaychState(ch, act, paychmock.NewMockPayChState(fromAcct, toAcct, abi.ChainEpoch(0), toSend, make(map[uint64]paych.LaneState))) mgr, err := newManager(store, mock) require.NoError(t, err) @@ -681,19 +622,10 @@ func TestAddVoucherInboundWalletKey(t *testing.T) { } mock := newMockManagerAPI() - arr, err := adt.MakeEmptyArray(mock.store).Root() - require.NoError(t, err) - mock.setAccountState(fromAcct, account.State{Address: from}) - mock.setAccountState(toAcct, account.State{Address: to}) + mock.setAccountAddress(fromAcct, from) + mock.setAccountAddress(toAcct, to) - mock.setPaychState(ch, act, paych.State{ - From: fromAcct, - To: toAcct, - ToSend: types.NewInt(0), - SettlingAt: abi.ChainEpoch(0), - MinSettleHeight: abi.ChainEpoch(0), - LaneStates: arr, - }) + mock.setPaychState(ch, act, paychmock.NewMockPayChState(fromAcct, toAcct, abi.ChainEpoch(0), types.NewInt(0), make(map[uint64]paych.LaneState))) // Create a manager store := NewStore(ds_sync.MutexWrap(ds.NewMapDatastore())) @@ -840,7 +772,7 @@ func TestCheckSpendable(t *testing.T) { // Check that the secret and proof were passed through correctly lastCall := s.mock.getLastCall() - var p paych.UpdateChannelStateParams + var p v0paych.UpdateChannelStateParams err = p.UnmarshalCBOR(bytes.NewReader(lastCall.Params)) require.NoError(t, err) require.Equal(t, otherProof, p.Proof) @@ -854,7 +786,7 @@ func TestCheckSpendable(t *testing.T) { require.True(t, spendable) lastCall = s.mock.getLastCall() - var p2 paych.UpdateChannelStateParams + var p2 v0paych.UpdateChannelStateParams err = p2.UnmarshalCBOR(bytes.NewReader(lastCall.Params)) require.NoError(t, err) require.Equal(t, proof, p2.Proof) @@ -911,7 +843,7 @@ func TestSubmitVoucher(t *testing.T) { // Check that the secret and proof were passed through correctly msg := s.mock.pushedMessages(submitCid) - var p paych.UpdateChannelStateParams + var p v0paych.UpdateChannelStateParams err = p.UnmarshalCBOR(bytes.NewReader(msg.Message.Params)) require.NoError(t, err) require.Equal(t, submitProof, p.Proof) @@ -931,7 +863,7 @@ func TestSubmitVoucher(t *testing.T) { require.NoError(t, err) msg = s.mock.pushedMessages(submitCid) - var p2 paych.UpdateChannelStateParams + var p2 v0paych.UpdateChannelStateParams err = p2.UnmarshalCBOR(bytes.NewReader(msg.Message.Params)) require.NoError(t, err) require.Equal(t, addVoucherProof2, p2.Proof) @@ -947,7 +879,7 @@ func TestSubmitVoucher(t *testing.T) { require.NoError(t, err) msg = s.mock.pushedMessages(submitCid) - var p3 paych.UpdateChannelStateParams + var p3 v0paych.UpdateChannelStateParams err = p3.UnmarshalCBOR(bytes.NewReader(msg.Message.Params)) require.NoError(t, err) require.Equal(t, proof3, p3.Proof) @@ -986,10 +918,8 @@ func testSetupMgrWithChannel(ctx context.Context, t *testing.T) *testScaffold { toAcct := tutils.NewActorAddr(t, "toAct") mock := newMockManagerAPI() - arr, err := adt.MakeEmptyArray(mock.store).Root() - require.NoError(t, err) - mock.setAccountState(fromAcct, account.State{Address: from}) - mock.setAccountState(toAcct, account.State{Address: to}) + mock.setAccountAddress(fromAcct, from) + mock.setAccountAddress(toAcct, to) // Create channel in state balance := big.NewInt(20) @@ -999,14 +929,7 @@ func testSetupMgrWithChannel(ctx context.Context, t *testing.T) *testScaffold { Nonce: 0, Balance: balance, } - mock.setPaychState(ch, act, paych.State{ - From: fromAcct, - To: toAcct, - ToSend: big.NewInt(0), - SettlingAt: abi.ChainEpoch(0), - MinSettleHeight: abi.ChainEpoch(0), - LaneStates: arr, - }) + mock.setPaychState(ch, act, paychmock.NewMockPayChState(fromAcct, toAcct, abi.ChainEpoch(0), big.NewInt(0), make(map[uint64]paych.LaneState))) store := NewStore(ds_sync.MutexWrap(ds.NewMapDatastore())) mgr, err := newManager(store, mock) @@ -1043,8 +966,8 @@ func testGenerateKeyPair(t *testing.T) ([]byte, []byte) { return priv, pub } -func createTestVoucher(t *testing.T, ch address.Address, voucherLane uint64, nonce uint64, voucherAmount big.Int, key []byte) *paych.SignedVoucher { - sv := &paych.SignedVoucher{ +func createTestVoucher(t *testing.T, ch address.Address, voucherLane uint64, nonce uint64, voucherAmount big.Int, key []byte) *v0paych.SignedVoucher { + sv := &v0paych.SignedVoucher{ ChannelAddr: ch, Lane: voucherLane, Nonce: nonce, @@ -1059,13 +982,13 @@ func createTestVoucher(t *testing.T, ch address.Address, voucherLane uint64, non return sv } -func createTestVoucherWithExtra(t *testing.T, ch address.Address, voucherLane uint64, nonce uint64, voucherAmount big.Int, key []byte) *paych.SignedVoucher { - sv := &paych.SignedVoucher{ +func createTestVoucherWithExtra(t *testing.T, ch address.Address, voucherLane uint64, nonce uint64, voucherAmount big.Int, key []byte) *v0paych.SignedVoucher { + sv := &v0paych.SignedVoucher{ ChannelAddr: ch, Lane: voucherLane, Nonce: nonce, Amount: voucherAmount, - Extra: &paych.ModVerifyParams{ + Extra: &v0paych.ModVerifyParams{ Actor: tutils.NewActorAddr(t, "act"), }, } @@ -1083,13 +1006,13 @@ type mockBestSpendableAPI struct { mgr *Manager } -func (m *mockBestSpendableAPI) PaychVoucherList(ctx context.Context, ch address.Address) ([]*paych.SignedVoucher, error) { +func (m *mockBestSpendableAPI) PaychVoucherList(ctx context.Context, ch address.Address) ([]*v0paych.SignedVoucher, error) { vi, err := m.mgr.ListVouchers(ctx, ch) if err != nil { return nil, err } - out := make([]*paych.SignedVoucher, len(vi)) + out := make([]*v0paych.SignedVoucher, len(vi)) for k, v := range vi { out[k] = v.Voucher } @@ -1097,7 +1020,7 @@ func (m *mockBestSpendableAPI) PaychVoucherList(ctx context.Context, ch address. return out, nil } -func (m *mockBestSpendableAPI) PaychVoucherCheckSpendable(ctx context.Context, ch address.Address, voucher *paych.SignedVoucher, secret []byte, proof []byte) (bool, error) { +func (m *mockBestSpendableAPI) PaychVoucherCheckSpendable(ctx context.Context, ch address.Address, voucher *v0paych.SignedVoucher, secret []byte, proof []byte) (bool, error) { return m.mgr.CheckVoucherSpendable(ctx, ch, voucher, secret, proof) } diff --git a/paychmgr/paychget_test.go b/paychmgr/paychget_test.go index 1f3e4c396..93233c54f 100644 --- a/paychmgr/paychget_test.go +++ b/paychmgr/paychget_test.go @@ -6,29 +6,22 @@ import ( "testing" "time" - "github.com/filecoin-project/specs-actors/actors/builtin/account" - "github.com/filecoin-project/specs-actors/actors/util/adt" - - "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/specs-actors/actors/builtin/paych" - cborrpc "github.com/filecoin-project/go-cbor-util" - - init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" - - "github.com/filecoin-project/specs-actors/actors/builtin" - - "github.com/filecoin-project/lotus/chain/types" - - "github.com/filecoin-project/go-address" - - "github.com/filecoin-project/go-state-types/big" - tutils "github.com/filecoin-project/specs-actors/support/testing" "github.com/ipfs/go-cid" ds "github.com/ipfs/go-datastore" ds_sync "github.com/ipfs/go-datastore/sync" - "github.com/stretchr/testify/require" + + "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/specs-actors/actors/builtin" + init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" + tutils "github.com/filecoin-project/specs-actors/support/testing" + + "github.com/filecoin-project/lotus/chain/actors/builtin/paych" + paychmock "github.com/filecoin-project/lotus/chain/actors/builtin/paych/mock" + "github.com/filecoin-project/lotus/chain/types" ) func testChannelResponse(t *testing.T, ch address.Address) types.MessageReceipt { @@ -976,25 +969,15 @@ func TestPaychAvailableFunds(t *testing.T) { require.EqualValues(t, 0, av.VoucherReedeemedAmt.Int64()) // Create channel in state - arr, err := adt.MakeEmptyArray(mock.store).Root() - require.NoError(t, err) - mock.setAccountState(fromAcct, account.State{Address: from}) - mock.setAccountState(toAcct, account.State{Address: to}) + mock.setAccountAddress(fromAcct, from) + mock.setAccountAddress(toAcct, to) act := &types.Actor{ Code: builtin.AccountActorCodeID, Head: cid.Cid{}, Nonce: 0, Balance: createAmt, } - mock.setPaychState(ch, act, paych.State{ - From: fromAcct, - To: toAcct, - ToSend: big.NewInt(0), - SettlingAt: abi.ChainEpoch(0), - MinSettleHeight: abi.ChainEpoch(0), - LaneStates: arr, - }) - + mock.setPaychState(ch, act, paychmock.NewMockPayChState(fromAcct, toAcct, abi.ChainEpoch(0), big.NewInt(0), make(map[uint64]paych.LaneState))) // Send create channel response response := testChannelResponse(t, ch) mock.receiveMsgResponse(createMsgCid, response) diff --git a/paychmgr/simple.go b/paychmgr/simple.go index 4cf579a47..2f6dc0593 100644 --- a/paychmgr/simple.go +++ b/paychmgr/simple.go @@ -6,20 +6,17 @@ import ( "fmt" "sync" - "github.com/filecoin-project/lotus/api" - - "golang.org/x/sync/errgroup" - - "github.com/filecoin-project/go-state-types/big" - - "github.com/filecoin-project/specs-actors/actors/builtin" - init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" - "github.com/filecoin-project/specs-actors/actors/builtin/paych" "github.com/ipfs/go-cid" + "golang.org/x/sync/errgroup" "golang.org/x/xerrors" "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/big" + "github.com/filecoin-project/specs-actors/actors/builtin" + init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" + v0paych "github.com/filecoin-project/specs-actors/actors/builtin/paych" + "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/actors" "github.com/filecoin-project/lotus/chain/types" @@ -320,7 +317,7 @@ func (ca *channelAccessor) currentAvailableFunds(channelID string, queuedAmt typ } for _, ls := range laneStates { - totalRedeemed = types.BigAdd(totalRedeemed, ls.Redeemed) + totalRedeemed = types.BigAdd(totalRedeemed, ls.Redeemed()) } } @@ -385,7 +382,7 @@ func (ca *channelAccessor) processTask(ctx context.Context, amt types.BigInt) *p // createPaych sends a message to create the channel and returns the message cid func (ca *channelAccessor) createPaych(ctx context.Context, amt types.BigInt) (cid.Cid, error) { - params, aerr := actors.SerializeParams(&paych.ConstructorParams{From: ca.from, To: ca.to}) + params, aerr := actors.SerializeParams(&v0paych.ConstructorParams{From: ca.from, To: ca.to}) if aerr != nil { return cid.Undef, aerr } diff --git a/paychmgr/state.go b/paychmgr/state.go index 00fe2adce..2571ef73e 100644 --- a/paychmgr/state.go +++ b/paychmgr/state.go @@ -3,13 +3,9 @@ package paychmgr import ( "context" - "github.com/filecoin-project/specs-actors/actors/util/adt" - - "github.com/filecoin-project/specs-actors/actors/builtin/account" - "github.com/filecoin-project/go-address" - "github.com/filecoin-project/specs-actors/actors/builtin/paych" + "github.com/filecoin-project/lotus/chain/actors/builtin/paych" "github.com/filecoin-project/lotus/chain/types" ) @@ -17,14 +13,8 @@ type stateAccessor struct { sm stateManagerAPI } -func (ca *stateAccessor) loadPaychActorState(ctx context.Context, ch address.Address) (*types.Actor, *paych.State, error) { - var pcast paych.State - act, err := ca.sm.LoadActorState(ctx, ch, &pcast, nil) - if err != nil { - return nil, nil, err - } - - return act, &pcast, nil +func (ca *stateAccessor) loadPaychActorState(ctx context.Context, ch address.Address) (*types.Actor, paych.State, error) { + return ca.sm.GetPaychState(ctx, ch, nil) } func (ca *stateAccessor) loadStateChannelInfo(ctx context.Context, ch address.Address, dir uint64) (*ChannelInfo, error) { @@ -33,17 +23,15 @@ func (ca *stateAccessor) loadStateChannelInfo(ctx context.Context, ch address.Ad return nil, err } - var account account.State - _, err = ca.sm.LoadActorState(ctx, st.From, &account, nil) + // Load channel "From" account actor state + from, err := ca.sm.ResolveToKeyAddress(ctx, st.From(), nil) if err != nil { return nil, err } - from := account.Address - _, err = ca.sm.LoadActorState(ctx, st.To, &account, nil) + to, err := ca.sm.ResolveToKeyAddress(ctx, st.To(), nil) if err != nil { return nil, err } - to := account.Address nextLane, err := ca.nextLaneFromState(ctx, st) if err != nil { @@ -67,25 +55,24 @@ func (ca *stateAccessor) loadStateChannelInfo(ctx context.Context, ch address.Ad return ci, nil } -func (ca *stateAccessor) nextLaneFromState(ctx context.Context, st *paych.State) (uint64, error) { - store := ca.sm.AdtStore(ctx) - laneStates, err := adt.AsArray(store, st.LaneStates) +func (ca *stateAccessor) nextLaneFromState(ctx context.Context, st paych.State) (uint64, error) { + laneCount, err := st.LaneCount() if err != nil { return 0, err } - if laneStates.Length() == 0 { + if laneCount == 0 { return 0, nil } - maxID := int64(0) - if err := laneStates.ForEach(nil, func(i int64) error { - if i > maxID { - maxID = i + maxID := uint64(0) + if err := st.ForEachLaneState(func(idx uint64, _ paych.LaneState) error { + if idx > maxID { + maxID = idx } return nil }); err != nil { return 0, err } - return uint64(maxID + 1), nil + return maxID + 1, nil } From b4ee51928233bcc6cacedbc185498e45630cb192 Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Wed, 16 Sep 2020 01:00:00 -0400 Subject: [PATCH 041/303] Partial progress towards switching to miner and power interfaces --- build/params_2k.go | 4 +- build/params_testnet.go | 4 +- chain/actors/builtin/power/power.go | 1 + chain/actors/builtin/power/v0.go | 28 ++++++++++++-- chain/gen/gen_test.go | 4 +- chain/gen/genesis/miners.go | 16 ++++---- chain/gen/genesis/t04_power.go | 4 +- chain/gen/genesis/util.go | 1 + chain/stmgr/forks_test.go | 8 ++-- chain/stmgr/stmgr.go | 2 +- chain/stmgr/utils.go | 59 +---------------------------- chain/store/store_test.go | 4 +- chain/store/weight.go | 17 ++++++--- chain/sync.go | 19 +++++----- chain/sync_test.go | 4 +- chain/vectors/gen/main.go | 4 +- chain/vm/invoker.go | 4 +- cli/paych_test.go | 4 +- 18 files changed, 81 insertions(+), 106 deletions(-) diff --git a/build/params_2k.go b/build/params_2k.go index 0ef1d9b34..313ccfa9d 100644 --- a/build/params_2k.go +++ b/build/params_2k.go @@ -6,7 +6,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/filecoin-project/specs-actors/actors/builtin/power" + v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" ) @@ -20,7 +20,7 @@ var DrandSchedule = map[abi.ChainEpoch]DrandEnum{ } func init() { - power.ConsensusMinerMinPower = big.NewInt(2048) + v0power.ConsensusMinerMinPower = big.NewInt(2048) miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } diff --git a/build/params_testnet.go b/build/params_testnet.go index 932ad7a7d..4cfd8a9b6 100644 --- a/build/params_testnet.go +++ b/build/params_testnet.go @@ -9,7 +9,7 @@ import ( "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/filecoin-project/specs-actors/actors/builtin/power" + v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" ) var DrandSchedule = map[abi.ChainEpoch]DrandEnum{ @@ -23,7 +23,7 @@ const BreezeGasTampingDuration = 120 const UpgradeSmokeHeight = 51000 func init() { - power.ConsensusMinerMinPower = big.NewInt(10 << 40) + v0power.ConsensusMinerMinPower = big.NewInt(10 << 40) miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg32GiBV1: {}, abi.RegisteredSealProof_StackedDrg64GiBV1: {}, diff --git a/chain/actors/builtin/power/power.go b/chain/actors/builtin/power/power.go index 07399e1bf..65148f0a5 100644 --- a/chain/actors/builtin/power/power.go +++ b/chain/actors/builtin/power/power.go @@ -37,6 +37,7 @@ type State interface { MinerPower(address.Address) (Claim, bool, error) MinerNominalPowerMeetsConsensusMinimum(address.Address) (bool, error) + ListAllMiners() ([]address.Address, error) } type Claim struct { diff --git a/chain/actors/builtin/power/v0.go b/chain/actors/builtin/power/v0.go index 45dd570f6..5cf6920c8 100644 --- a/chain/actors/builtin/power/v0.go +++ b/chain/actors/builtin/power/v0.go @@ -4,12 +4,12 @@ import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/lotus/chain/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/power" + v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/util/adt" ) type v0State struct { - power.State + v0power.State store adt.Store } @@ -29,7 +29,7 @@ func (s *v0State) MinerPower(addr address.Address) (Claim, bool, error) { if err != nil { return Claim{}, false, err } - var claim power.Claim + var claim v0power.Claim ok, err := claims.Get(abi.AddrKey(addr), &claim) if err != nil { return Claim{}, false, err @@ -47,3 +47,25 @@ func (s *v0State) MinerNominalPowerMeetsConsensusMinimum(a address.Address) (boo func (s *v0State) TotalPowerSmoothed() (builtin.FilterEstimate, error) { return *s.State.ThisEpochQAPowerSmoothed, nil } + +func (s *v0State) ListAllMiners() ([]address.Address, error) { + claims, err := adt.AsMap(s.store, s.Claims) + if err != nil { + return nil, err + } + + var miners []address.Address + err = claims.ForEach(nil, func(k string) error { + a, err := address.NewFromBytes([]byte(k)) + if err != nil { + return err + } + miners = append(miners, a) + return nil + }) + if err != nil { + return nil, err + } + + return miners, nil +} diff --git a/chain/gen/gen_test.go b/chain/gen/gen_test.go index ebc28a990..fd6bceb95 100644 --- a/chain/gen/gen_test.go +++ b/chain/gen/gen_test.go @@ -6,7 +6,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/filecoin-project/specs-actors/actors/builtin/power" + v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" _ "github.com/filecoin-project/lotus/lib/sigs/bls" @@ -17,7 +17,7 @@ func init() { miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } - power.ConsensusMinerMinPower = big.NewInt(2048) + v0power.ConsensusMinerMinPower = big.NewInt(2048) verifreg.MinVerifiedDealSize = big.NewInt(256) } diff --git a/chain/gen/genesis/miners.go b/chain/gen/genesis/miners.go index 3bed1c1a9..88fe57189 100644 --- a/chain/gen/genesis/miners.go +++ b/chain/gen/genesis/miners.go @@ -19,7 +19,7 @@ import ( "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin/market" "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/filecoin-project/specs-actors/actors/builtin/power" + v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/builtin/reward" "github.com/filecoin-project/specs-actors/actors/runtime" @@ -99,7 +99,7 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid } { - constructorParams := &power.CreateMinerParams{ + constructorParams := &v0power.CreateMinerParams{ Owner: m.Worker, Worker: m.Worker, Peer: []byte(m.PeerId), @@ -112,7 +112,7 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid return cid.Undef, xerrors.Errorf("failed to create genesis miner: %w", err) } - var ma power.CreateMinerReturn + var ma v0power.CreateMinerReturn if err := ma.UnmarshalCBOR(bytes.NewReader(rval)); err != nil { return cid.Undef, xerrors.Errorf("unmarshaling CreateMinerReturn: %w", err) } @@ -207,7 +207,7 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid } } - err = vm.MutateState(ctx, builtin.StoragePowerActorAddr, func(cst cbor.IpldStore, st *power.State) error { + err = vm.MutateState(ctx, builtin.StoragePowerActorAddr, func(cst cbor.IpldStore, st *v0power.State) error { st.TotalQualityAdjPower = qaPow st.TotalRawBytePower = rawPow @@ -249,7 +249,7 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid sectorWeight := miner.QAPowerForWeight(m.SectorSize, minerInfos[i].presealExp, dweight.DealWeight, dweight.VerifiedDealWeight) // we've added fake power for this sector above, remove it now - err = vm.MutateState(ctx, builtin.StoragePowerActorAddr, func(cst cbor.IpldStore, st *power.State) error { + err = vm.MutateState(ctx, builtin.StoragePowerActorAddr, func(cst cbor.IpldStore, st *v0power.State) error { st.TotalQualityAdjPower = types.BigSub(st.TotalQualityAdjPower, sectorWeight) //nolint:scopelint st.TotalRawBytePower = types.BigSub(st.TotalRawBytePower, types.NewInt(uint64(m.SectorSize))) return nil @@ -301,7 +301,7 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid } // Sanity-check total network power - err = vm.MutateState(ctx, builtin.StoragePowerActorAddr, func(cst cbor.IpldStore, st *power.State) error { + err = vm.MutateState(ctx, builtin.StoragePowerActorAddr, func(cst cbor.IpldStore, st *v0power.State) error { if !st.TotalRawBytePower.Equals(rawPow) { return xerrors.Errorf("st.TotalRawBytePower doesn't match previously calculated rawPow") } @@ -340,12 +340,12 @@ func (fr *fakeRand) GetBeaconRandomness(ctx context.Context, personalization cry return out, nil } -func currentTotalPower(ctx context.Context, vm *vm.VM, maddr address.Address) (*power.CurrentTotalPowerReturn, error) { +func currentTotalPower(ctx context.Context, vm *vm.VM, maddr address.Address) (*v0power.CurrentTotalPowerReturn, error) { pwret, err := doExecValue(ctx, vm, builtin.StoragePowerActorAddr, maddr, big.Zero(), builtin.MethodsPower.CurrentTotalPower, nil) if err != nil { return nil, err } - var pwr power.CurrentTotalPowerReturn + var pwr v0power.CurrentTotalPowerReturn if err := pwr.UnmarshalCBOR(bytes.NewReader(pwret)); err != nil { return nil, err } diff --git a/chain/gen/genesis/t04_power.go b/chain/gen/genesis/t04_power.go index 86ba684e0..40ea68079 100644 --- a/chain/gen/genesis/t04_power.go +++ b/chain/gen/genesis/t04_power.go @@ -6,7 +6,7 @@ import ( "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/util/adt" - "github.com/filecoin-project/specs-actors/actors/builtin/power" + v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" cbor "github.com/ipfs/go-ipld-cbor" "github.com/filecoin-project/lotus/chain/types" @@ -30,7 +30,7 @@ func SetupStoragePowerActor(bs bstore.Blockstore) (*types.Actor, error) { return nil, err } - sms := power.ConstructState(emptyMap, emptyMultiMap) + sms := v0power.ConstructState(emptyMap, emptyMultiMap) stcid, err := store.Put(store.Context(), sms) if err != nil { diff --git a/chain/gen/genesis/util.go b/chain/gen/genesis/util.go index d87500206..bcafb007e 100644 --- a/chain/gen/genesis/util.go +++ b/chain/gen/genesis/util.go @@ -2,6 +2,7 @@ package genesis import ( "context" + "github.com/filecoin-project/go-state-types/network" "github.com/filecoin-project/lotus/build" diff --git a/chain/stmgr/forks_test.go b/chain/stmgr/forks_test.go index 2fc11b3d7..d9d0af745 100644 --- a/chain/stmgr/forks_test.go +++ b/chain/stmgr/forks_test.go @@ -12,7 +12,7 @@ import ( "github.com/filecoin-project/specs-actors/actors/builtin" init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/filecoin-project/specs-actors/actors/builtin/power" + v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/specs-actors/actors/runtime" "golang.org/x/xerrors" @@ -36,7 +36,7 @@ func init() { miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } - power.ConsensusMinerMinPower = big.NewInt(2048) + v0power.ConsensusMinerMinPower = big.NewInt(2048) verifreg.MinVerifiedDealSize = big.NewInt(256) } @@ -148,8 +148,8 @@ func TestForkHeightTriggers(t *testing.T) { } inv.Register(builtin.PaymentChannelActorCodeID, &testActor{}, &testActorState{}) - sm.SetVMConstructor(func(vmopt *vm.VMOpts) (*vm.VM, error) { - nvm, err := vm.NewVM(vmopt) + sm.SetVMConstructor(func(ctx context.Context, vmopt *vm.VMOpts) (*vm.VM, error) { + nvm, err := vm.NewVM(ctx, vmopt) if err != nil { return nil, err } diff --git a/chain/stmgr/stmgr.go b/chain/stmgr/stmgr.go index f71b788c8..827f23920 100644 --- a/chain/stmgr/stmgr.go +++ b/chain/stmgr/stmgr.go @@ -197,7 +197,7 @@ func (sm *StateManager) ApplyBlocks(ctx context.Context, parentEpoch abi.ChainEp for i := parentEpoch; i < epoch; i++ { // handle state forks - // XXX: The state tre + // XXX: The state tree err = sm.handleStateForks(ctx, vmi.StateTree(), i, ts) if err != nil { return cid.Undef, cid.Undef, xerrors.Errorf("error handling state forks: %w", err) diff --git a/chain/stmgr/utils.go b/chain/stmgr/utils.go index 1bbc9ccc4..e295725f8 100644 --- a/chain/stmgr/utils.go +++ b/chain/stmgr/utils.go @@ -13,7 +13,6 @@ import ( "github.com/filecoin-project/specs-actors/actors/runtime/proof" cid "github.com/ipfs/go-cid" - cbor "github.com/ipfs/go-ipld-cbor" cbg "github.com/whyrusleeping/cbor-gen" "golang.org/x/xerrors" @@ -42,7 +41,6 @@ import ( "github.com/filecoin-project/lotus/chain/store" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/vm" - "github.com/filecoin-project/lotus/lib/blockstore" "github.com/filecoin-project/lotus/node/modules/dtypes" ) @@ -326,65 +324,12 @@ func ListMinerActors(ctx context.Context, sm *StateManager, ts *types.TipSet) ([ return nil, xerrors.Errorf("failed to load power actor: %w", err) } - state, err := power.Load(sm.cs.Store(ctx), act) + powState, err := power.Load(sm.cs.Store(ctx), act) if err != nil { return nil, xerrors.Errorf("failed to load power actor state: %w", err) } - m, err := adt.AsMap(sm.cs.Store(ctx), state.Claims) - if err != nil { - return nil, err - } - - var miners []address.Address - err = m.ForEach(nil, func(k string) error { - a, err := address.NewFromBytes([]byte(k)) - if err != nil { - return err - } - miners = append(miners, a) - return nil - }) - if err != nil { - return nil, err - } - - return miners, nil -} - -func LoadSectorsFromSet(ctx context.Context, bs blockstore.Blockstore, ssc cid.Cid, filter *bitfield.BitField, filterOut bool) ([]*miner.ChainSectorInfo, error) { - a, err := adt.AsArray(store.ActorStore(ctx, bs), ssc) - if err != nil { - return nil, err - } - - var sset []*miner.ChainSectorInfo - var v cbg.Deferred - if err := a.ForEach(&v, func(i int64) error { - if filter != nil { - set, err := filter.IsSet(uint64(i)) - if err != nil { - return xerrors.Errorf("filter check error: %w", err) - } - if set == filterOut { - return nil - } - } - - var oci miner.SectorOnChainInfo - if err := cbor.DecodeInto(v.Raw, &oci); err != nil { - return err - } - sset = append(sset, &miner.ChainSectorInfo{ - Info: oci, - ID: abi.SectorNumber(i), - }) - return nil - }); err != nil { - return nil, err - } - - return sset, nil + return powState.ListAllMiners() } func ComputeState(ctx context.Context, sm *StateManager, height abi.ChainEpoch, msgs []*types.Message, ts *types.TipSet) (cid.Cid, []*api.InvocResult, error) { diff --git a/chain/store/store_test.go b/chain/store/store_test.go index e56bab4c9..8662f10ef 100644 --- a/chain/store/store_test.go +++ b/chain/store/store_test.go @@ -11,7 +11,7 @@ import ( "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/filecoin-project/specs-actors/actors/builtin/power" + v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/lotus/chain/gen" @@ -25,7 +25,7 @@ func init() { miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } - power.ConsensusMinerMinPower = big.NewInt(2048) + v0power.ConsensusMinerMinPower = big.NewInt(2048) verifreg.MinVerifiedDealSize = big.NewInt(256) } diff --git a/chain/store/weight.go b/chain/store/weight.go index 5249df011..2d83738c5 100644 --- a/chain/store/weight.go +++ b/chain/store/weight.go @@ -4,12 +4,13 @@ import ( "context" "math/big" + "github.com/filecoin-project/lotus/chain/actors/builtin/power" + big2 "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/power" cbor "github.com/ipfs/go-ipld-cbor" "golang.org/x/xerrors" ) @@ -39,11 +40,17 @@ func (cs *ChainStore) Weight(ctx context.Context, ts *types.TipSet) (types.BigIn return types.NewInt(0), xerrors.Errorf("get power actor: %w", err) } - var st power.State - if err := cst.Get(ctx, act.Head, &st); err != nil { - return types.NewInt(0), xerrors.Errorf("get power actor head (%s, height=%d): %w", act.Head, ts.Height(), err) + powState, err := power.Load(cs.Store(ctx), act) + if err != nil { + return types.NewInt(0), xerrors.Errorf("failed to load power actor state: %w", err) } - tpow = st.TotalQualityAdjPower // TODO: REVIEW: Is this correct? + + claim, err := powState.TotalPower() + if err != nil { + return types.NewInt(0), xerrors.Errorf("failed to get total power: %w", err) + } + + tpow = claim.QualityAdjPower // TODO: REVIEW: Is this correct? } log2P := int64(0) diff --git a/chain/sync.go b/chain/sync.go index bb3e50bdb..c16821889 100644 --- a/chain/sync.go +++ b/chain/sync.go @@ -34,12 +34,12 @@ import ( "github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/util/adt" blst "github.com/supranational/blst/bindings/go" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" + "github.com/filecoin-project/lotus/chain/actors/builtin/power" "github.com/filecoin-project/lotus/chain/beacon" "github.com/filecoin-project/lotus/chain/exchange" "github.com/filecoin-project/lotus/chain/gen" @@ -635,26 +635,25 @@ func (syncer *Syncer) ValidateTipSet(ctx context.Context, fts *store.FullTipSet) } func (syncer *Syncer) minerIsValid(ctx context.Context, maddr address.Address, baseTs *types.TipSet) error { - var spast power.State - - _, err := syncer.sm.LoadActorState(ctx, builtin.StoragePowerActorAddr, &spast, baseTs) + act, err := syncer.sm.LoadActor(ctx, builtin.StoragePowerActorAddr, baseTs) if err != nil { - return err + return xerrors.Errorf("failed to load power actor: %w", err) } - cm, err := adt.AsMap(syncer.store.Store(ctx), spast.Claims) + powState, err := power.Load(syncer.store.Store(ctx), act) if err != nil { - return err + return xerrors.Errorf("failed to load power actor state: %w", err) } - var claim power.Claim - exist, err := cm.Get(abi.AddrKey(maddr), &claim) + _, exist, err := powState.MinerPower(maddr) if err != nil { - return err + return xerrors.Errorf("failed to look up miner's claim: %w", err) } + if !exist { return xerrors.New("miner isn't valid") } + return nil } diff --git a/chain/sync_test.go b/chain/sync_test.go index 0b0d1ed00..5f972ecc6 100644 --- a/chain/sync_test.go +++ b/chain/sync_test.go @@ -21,7 +21,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/filecoin-project/specs-actors/actors/builtin/power" + v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/lotus/api" @@ -46,7 +46,7 @@ func init() { miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } - power.ConsensusMinerMinPower = big.NewInt(2048) + v0power.ConsensusMinerMinPower = big.NewInt(2048) verifreg.MinVerifiedDealSize = big.NewInt(256) } diff --git a/chain/vectors/gen/main.go b/chain/vectors/gen/main.go index ecc2498b9..4bf2c420e 100644 --- a/chain/vectors/gen/main.go +++ b/chain/vectors/gen/main.go @@ -6,7 +6,7 @@ import ( "math/rand" "os" - "github.com/filecoin-project/specs-actors/actors/builtin/power" + v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/go-address" "golang.org/x/xerrors" @@ -27,7 +27,7 @@ import ( func init() { verifreg.MinVerifiedDealSize = big.NewInt(2048) - power.ConsensusMinerMinPower = big.NewInt(2048) + v0power.ConsensusMinerMinPower = big.NewInt(2048) } func MakeHeaderVectors() []vectors.HeaderVector { diff --git a/chain/vm/invoker.go b/chain/vm/invoker.go index 9f5f8e2d9..56e3bea84 100644 --- a/chain/vm/invoker.go +++ b/chain/vm/invoker.go @@ -23,7 +23,7 @@ import ( "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/specs-actors/actors/builtin/multisig" "github.com/filecoin-project/specs-actors/actors/builtin/paych" - "github.com/filecoin-project/specs-actors/actors/builtin/power" + v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/builtin/reward" "github.com/filecoin-project/specs-actors/actors/builtin/system" "github.com/filecoin-project/specs-actors/actors/runtime" @@ -50,7 +50,7 @@ func NewInvoker() *Invoker { inv.Register(builtin.InitActorCodeID, init_.Actor{}, init_.State{}) inv.Register(builtin.RewardActorCodeID, reward.Actor{}, reward.State{}) inv.Register(builtin.CronActorCodeID, cron.Actor{}, cron.State{}) - inv.Register(builtin.StoragePowerActorCodeID, power.Actor{}, power.State{}) + inv.Register(builtin.StoragePowerActorCodeID, v0power.Actor{}, v0power.State{}) inv.Register(builtin.StorageMarketActorCodeID, market.Actor{}, market.State{}) inv.Register(builtin.StorageMinerActorCodeID, miner.Actor{}, miner.State{}) inv.Register(builtin.MultisigActorCodeID, multisig.Actor{}, multisig.State{}) diff --git a/cli/paych_test.go b/cli/paych_test.go index cccc80ff4..0e5bc0096 100644 --- a/cli/paych_test.go +++ b/cli/paych_test.go @@ -16,7 +16,7 @@ import ( "github.com/filecoin-project/go-state-types/big" saminer "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/filecoin-project/specs-actors/actors/builtin/power" + v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/multiformats/go-multiaddr" @@ -39,7 +39,7 @@ import ( ) func init() { - power.ConsensusMinerMinPower = big.NewInt(2048) + v0power.ConsensusMinerMinPower = big.NewInt(2048) saminer.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } From 90853e24cfd9e3ef749855fbdf319a821f4403aa Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Wed, 16 Sep 2020 01:47:24 -0400 Subject: [PATCH 042/303] Add a boolean HasMinPower to return of GetPower --- api/api_full.go | 5 +++-- chain/stmgr/utils.go | 32 ++++++++++++++++---------------- chain/sync.go | 2 +- cmd/lotus-shed/balances.go | 3 +-- node/impl/full/state.go | 3 ++- 5 files changed, 23 insertions(+), 22 deletions(-) diff --git a/api/api_full.go b/api/api_full.go index 88496d669..fbbf92d8b 100644 --- a/api/api_full.go +++ b/api/api_full.go @@ -600,8 +600,9 @@ type VoucherCreateResult struct { } type MinerPower struct { - MinerPower power.Claim - TotalPower power.Claim + MinerPower power.Claim + TotalPower power.Claim + HasMinPower bool } type QueryOffer struct { diff --git a/chain/stmgr/utils.go b/chain/stmgr/utils.go index e295725f8..e58d69156 100644 --- a/chain/stmgr/utils.go +++ b/chain/stmgr/utils.go @@ -79,37 +79,42 @@ func GetMinerWorkerRaw(ctx context.Context, sm *StateManager, st cid.Cid, maddr return vm.ResolveToKeyAddr(state, sm.cs.Store(ctx), info.Worker) } -func GetPower(ctx context.Context, sm *StateManager, ts *types.TipSet, maddr address.Address) (power.Claim, power.Claim, error) { +func GetPower(ctx context.Context, sm *StateManager, ts *types.TipSet, maddr address.Address) (power.Claim, power.Claim, bool, error) { return GetPowerRaw(ctx, sm, ts.ParentState(), maddr) } -func GetPowerRaw(ctx context.Context, sm *StateManager, st cid.Cid, maddr address.Address) (power.Claim, power.Claim, error) { +func GetPowerRaw(ctx context.Context, sm *StateManager, st cid.Cid, maddr address.Address) (power.Claim, power.Claim, bool, error) { act, err := sm.LoadActorRaw(ctx, builtin.StoragePowerActorAddr, st) if err != nil { - return power.Claim{}, power.Claim{}, xerrors.Errorf("(get sset) failed to load power actor state: %w", err) + return power.Claim{}, power.Claim{}, false, xerrors.Errorf("(get sset) failed to load power actor state: %w", err) } - mas, err := power.Load(sm.cs.Store(ctx), act) + pas, err := power.Load(sm.cs.Store(ctx), act) if err != nil { - return power.Claim{}, power.Claim{}, err + return power.Claim{}, power.Claim{}, false, err } - tpow, err := mas.TotalPower() + tpow, err := pas.TotalPower() if err != nil { - return power.Claim{}, power.Claim{}, err + return power.Claim{}, power.Claim{}, false, err } var mpow power.Claim if maddr != address.Undef { var found bool - mpow, found, err = mas.MinerPower(maddr) + mpow, found, err = pas.MinerPower(maddr) if err != nil || !found { // TODO: return an error when not found? - return power.Claim{}, power.Claim{}, err + return power.Claim{}, power.Claim{}, false, err } } - return mpow, tpow, nil + minpow, err := pas.MinerNominalPowerMeetsConsensusMinimum(maddr) + if err != nil { + return power.Claim{}, power.Claim{}, false, err + } + + return mpow, tpow, minpow, nil } func PreCommitInfo(ctx context.Context, sm *StateManager, maddr address.Address, sid abi.SectorNumber, ts *types.TipSet) (*miner.SectorPreCommitOnChainInfo, error) { @@ -470,7 +475,7 @@ func MinerGetBaseInfo(ctx context.Context, sm *StateManager, bcs beacon.Schedule return nil, nil } - mpow, tpow, err := GetPowerRaw(ctx, sm, lbst, maddr) + mpow, tpow, hmp, err := GetPowerRaw(ctx, sm, lbst, maddr) if err != nil { return nil, xerrors.Errorf("failed to get power: %w", err) } @@ -485,11 +490,6 @@ func MinerGetBaseInfo(ctx context.Context, sm *StateManager, bcs beacon.Schedule return nil, xerrors.Errorf("resolving worker address: %w", err) } - hmp, err := MinerHasMinPower(ctx, sm, maddr, lbts) - if err != nil { - return nil, xerrors.Errorf("determining if miner has min power failed: %w", err) - } - return &api.MiningBaseInfo{ MinerPower: mpow.QualityAdjPower, NetworkPower: tpow.QualityAdjPower, diff --git a/chain/sync.go b/chain/sync.go index c16821889..1d4e1f02b 100644 --- a/chain/sync.go +++ b/chain/sync.go @@ -853,7 +853,7 @@ func (syncer *Syncer) ValidateBlock(ctx context.Context, b *types.FullBlock) (er return xerrors.Errorf("received block was from slashed or invalid miner") } - mpow, tpow, err := stmgr.GetPowerRaw(ctx, syncer.sm, lbst, h.Miner) + mpow, tpow, _, err := stmgr.GetPowerRaw(ctx, syncer.sm, lbst, h.Miner) if err != nil { return xerrors.Errorf("failed getting power: %w", err) } diff --git a/cmd/lotus-shed/balances.go b/cmd/lotus-shed/balances.go index 7dbfe2eb7..248f3b26e 100644 --- a/cmd/lotus-shed/balances.go +++ b/cmd/lotus-shed/balances.go @@ -12,7 +12,6 @@ import ( "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/lotus/chain/state" "github.com/filecoin-project/lotus/chain/stmgr" "github.com/filecoin-project/lotus/chain/store" @@ -193,7 +192,7 @@ var chainBalanceStateCmd = &cli.Command{ } if act.Code == builtin.StorageMinerActorCodeID && minerInfo { - pow, _, err := stmgr.GetPowerRaw(ctx, sm, sroot, addr) + pow, _, _, err := stmgr.GetPowerRaw(ctx, sm, sroot, addr) if err != nil { return xerrors.Errorf("failed to get power: %w", err) } diff --git a/node/impl/full/state.go b/node/impl/full/state.go index d69ba0a41..a19edb1ca 100644 --- a/node/impl/full/state.go +++ b/node/impl/full/state.go @@ -253,7 +253,7 @@ func (a *StateAPI) StateMinerPower(ctx context.Context, addr address.Address, ts return nil, xerrors.Errorf("loading tipset %s: %w", tsk, err) } - m, net, err := stmgr.GetPower(ctx, a.StateManager, ts, addr) + m, net, hmp, err := stmgr.GetPower(ctx, a.StateManager, ts, addr) if err != nil { return nil, err } @@ -261,6 +261,7 @@ func (a *StateAPI) StateMinerPower(ctx context.Context, addr address.Address, ts return &api.MinerPower{ MinerPower: m, TotalPower: net, + HasMinPower: hmp, }, nil } From 72d19f369bf5ed9430c2ee374e1a15fb65ba88a8 Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Wed, 16 Sep 2020 01:49:33 -0400 Subject: [PATCH 043/303] Incremental progress towards using new power state interface --- cmd/lotus-storage-miner/info.go | 3 +- cmd/lotus-storage-miner/init.go | 6 ++-- node/node_test.go | 4 +-- tools/stats/metrics.go | 50 +++++---------------------------- 4 files changed, 13 insertions(+), 50 deletions(-) diff --git a/cmd/lotus-storage-miner/info.go b/cmd/lotus-storage-miner/info.go index c47a22b0e..3a7720c52 100644 --- a/cmd/lotus-storage-miner/info.go +++ b/cmd/lotus-storage-miner/info.go @@ -17,7 +17,6 @@ import ( "github.com/filecoin-project/go-state-types/abi" sealing "github.com/filecoin-project/lotus/extern/storage-sealing" "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/filecoin-project/lotus/api" @@ -129,7 +128,7 @@ func infoCmdAct(cctx *cli.Context) error { faultyPercentage) } - if pow.MinerPower.RawBytePower.LessThan(power.ConsensusMinerMinPower) { + if !pow.HasMinPower { fmt.Print("Below minimum power threshold, no blocks will be won") } else { expWinChance := float64(types.BigMul(qpercI, types.NewInt(build.BlocksPerEpoch)).Int64()) / 1000000 diff --git a/cmd/lotus-storage-miner/init.go b/cmd/lotus-storage-miner/init.go index e2a2419f3..8325aae8b 100644 --- a/cmd/lotus-storage-miner/init.go +++ b/cmd/lotus-storage-miner/init.go @@ -34,7 +34,7 @@ import ( "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin/market" miner2 "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/filecoin-project/specs-actors/actors/builtin/power" + v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" lapi "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" @@ -633,7 +633,7 @@ func createStorageMiner(ctx context.Context, api lapi.FullNode, peerid peer.ID, return address.Undef, err } - params, err := actors.SerializeParams(&power.CreateMinerParams{ + params, err := actors.SerializeParams(&v0power.CreateMinerParams{ Owner: owner, Worker: worker, SealProofType: spt, @@ -681,7 +681,7 @@ func createStorageMiner(ctx context.Context, api lapi.FullNode, peerid peer.ID, return address.Undef, xerrors.Errorf("create miner failed: exit code %d", mw.Receipt.ExitCode) } - var retval power.CreateMinerReturn + var retval v0power.CreateMinerReturn if err := retval.UnmarshalCBOR(bytes.NewReader(mw.Receipt.Return)); err != nil { return address.Undef, err } diff --git a/node/node_test.go b/node/node_test.go index 8cc51f629..0611bca60 100644 --- a/node/node_test.go +++ b/node/node_test.go @@ -11,7 +11,7 @@ import ( "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/lotus/lib/lotuslog" saminer "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/filecoin-project/specs-actors/actors/builtin/power" + v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" logging "github.com/ipfs/go-log/v2" @@ -21,7 +21,7 @@ import ( func init() { _ = logging.SetLogLevel("*", "INFO") - power.ConsensusMinerMinPower = big.NewInt(2048) + v0power.ConsensusMinerMinPower = big.NewInt(2048) saminer.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } diff --git a/tools/stats/metrics.go b/tools/stats/metrics.go index ae79d9273..4f11d2476 100644 --- a/tools/stats/metrics.go +++ b/tools/stats/metrics.go @@ -10,14 +10,11 @@ import ( "strings" "time" - "github.com/filecoin-project/go-address" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/store" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/power" - "github.com/filecoin-project/specs-actors/actors/util/adt" "golang.org/x/xerrors" "github.com/ipfs/go-cid" @@ -255,55 +252,22 @@ func RecordTipsetStatePoints(ctx context.Context, api api.FullNode, pl *PointLis p := NewPoint("network.balance", netBalFilFloat) pl.AddPoint(p) - totalPower, err := api.StateMinerPower(ctx, address.Address{}, tipset.Key()) + miners, err := api.StateListMiners(ctx, tipset.Key()) if err != nil { return err } - p = NewPoint("chain.power", totalPower.TotalPower.QualityAdjPower.Int64()) - pl.AddPoint(p) - - powerActor, err := api.StateGetActor(ctx, builtin.StoragePowerActorAddr, tipset.Key()) - if err != nil { - return err - } - - powerRaw, err := api.ChainReadObj(ctx, powerActor.Head) - if err != nil { - return err - } - - var powerActorState power.State - - if err := powerActorState.UnmarshalCBOR(bytes.NewReader(powerRaw)); err != nil { - return fmt.Errorf("failed to unmarshal power actor state: %w", err) - } - - s := &apiIpldStore{ctx, api} - mp, err := adt.AsMap(s, powerActorState.Claims) - if err != nil { - return err - } - - var claim power.Claim - err = mp.ForEach(&claim, func(key string) error { - addr, err := address.NewFromBytes([]byte(key)) + for _, addr := range miners { + mp, err := api.StateMinerPower(ctx, addr, tipset.Key()) if err != nil { return err } - if claim.QualityAdjPower.Int64() == 0 { - return nil + if !mp.MinerPower.QualityAdjPower.IsZero() { + p = NewPoint("chain.miner_power", mp.MinerPower.QualityAdjPower.Int64()) + p.AddTag("miner", addr.String()) + pl.AddPoint(p) } - - p = NewPoint("chain.miner_power", claim.QualityAdjPower.Int64()) - p.AddTag("miner", addr.String()) - pl.AddPoint(p) - - return nil - }) - if err != nil { - return err } return nil From ed74091c204c417a1f82ec3f6260e32f8042bb9f Mon Sep 17 00:00:00 2001 From: Frank Date: Wed, 16 Sep 2020 19:49:45 +0800 Subject: [PATCH 044/303] add exist sector state check --- cmd/lotus-storage-miner/sectors.go | 6 +++++ extern/storage-sealing/sector_state.go | 33 ++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/cmd/lotus-storage-miner/sectors.go b/cmd/lotus-storage-miner/sectors.go index 06f09fe20..c08d6ca14 100644 --- a/cmd/lotus-storage-miner/sectors.go +++ b/cmd/lotus-storage-miner/sectors.go @@ -17,6 +17,8 @@ import ( "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/chain/types" + + sealing "github.com/filecoin-project/lotus/extern/storage-sealing" lcli "github.com/filecoin-project/lotus/cli" ) @@ -420,6 +422,10 @@ var sectorsUpdateCmd = &cli.Command{ return xerrors.Errorf("could not parse sector number: %w", err) } + if _, ok := sealing.ExistSectorStateList[sealing.SectorState(cctx.Args().Get(1))]; !ok { + return xerrors.Errorf("Not existing sector state") + } + return nodeApi.SectorsUpdate(ctx, abi.SectorNumber(id), api.SectorState(cctx.Args().Get(1))) }, } diff --git a/extern/storage-sealing/sector_state.go b/extern/storage-sealing/sector_state.go index 4e674603d..3ed891064 100644 --- a/extern/storage-sealing/sector_state.go +++ b/extern/storage-sealing/sector_state.go @@ -2,6 +2,8 @@ package sealing type SectorState string +var ExistSectorStateList = make(map[SectorState]struct{}) + const ( UndefinedSectorState SectorState = "" @@ -39,6 +41,37 @@ const ( RemoveFailed SectorState = "RemoveFailed" Removed SectorState = "Removed" ) +func init() { + ExistSectorStateList[Empty] = struct{}{} + ExistSectorStateList[WaitDeals] = struct{}{} + ExistSectorStateList[Packing] = struct{}{} + ExistSectorStateList[PreCommit1] = struct{}{} + ExistSectorStateList[PreCommit2] = struct{}{} + ExistSectorStateList[PreCommitting] = struct{}{} + ExistSectorStateList[PreCommitWait] = struct{}{} + ExistSectorStateList[WaitSeed] = struct{}{} + ExistSectorStateList[Committing] = struct{}{} + ExistSectorStateList[SubmitCommit] = struct{}{} + ExistSectorStateList[CommitWait] = struct{}{} + ExistSectorStateList[FinalizeSector] = struct{}{} + ExistSectorStateList[Proving] = struct{}{} + ExistSectorStateList[FailedUnrecoverable] = struct{}{} + ExistSectorStateList[SealPreCommit1Failed] = struct{}{} + ExistSectorStateList[SealPreCommit2Failed] = struct{}{} + ExistSectorStateList[PreCommitFailed] = struct{}{} + ExistSectorStateList[ComputeProofFailed] = struct{}{} + ExistSectorStateList[CommitFailed] = struct{}{} + ExistSectorStateList[PackingFailed] = struct{}{} + ExistSectorStateList[FinalizeFailed] = struct{}{} + ExistSectorStateList[DealsExpired] = struct{}{} + ExistSectorStateList[RecoverDealIDs] = struct{}{} + ExistSectorStateList[Faulty] = struct{}{} + ExistSectorStateList[FaultReported] = struct{}{} + ExistSectorStateList[FaultedFinal] = struct{}{} + ExistSectorStateList[Removing] = struct{}{} + ExistSectorStateList[RemoveFailed] = struct{}{} + ExistSectorStateList[Removed] = struct{}{} +} func toStatState(st SectorState) statSectorState { switch st { From b530f25f0933b3cb2a311e401456b00c36dfc206 Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Wed, 16 Sep 2020 17:20:25 -0400 Subject: [PATCH 045/303] Migrate miner actor --- api/test/window_post.go | 36 +++++++++++++++++++++-------- chain/actors/builtin/miner/miner.go | 1 + chain/actors/builtin/miner/v0.go | 27 ++++++++++++---------- chain/stmgr/forks_test.go | 4 ++-- node/impl/full/state.go | 1 - 5 files changed, 45 insertions(+), 24 deletions(-) diff --git a/api/test/window_post.go b/api/test/window_post.go index 3f15c754b..bdc390730 100644 --- a/api/test/window_post.go +++ b/api/test/window_post.go @@ -4,6 +4,13 @@ import ( "context" "fmt" + "github.com/filecoin-project/lotus/api/apibstore" + "github.com/filecoin-project/lotus/chain/actors/adt" + lotusminer "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + cbor "github.com/ipfs/go-ipld-cbor" + + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + "os" "strings" "testing" @@ -15,7 +22,6 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/lotus/extern/sector-storage/mock" sealing "github.com/filecoin-project/lotus/extern/storage-sealing" - miner2 "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" @@ -159,7 +165,7 @@ func TestWindowPost(t *testing.T, b APIBuilder, blocktime time.Duration, nSector head, err := client.ChainHead(ctx) require.NoError(t, err) - if head.Height() > di.PeriodStart+(miner2.WPoStProvingPeriod)+2 { + if head.Height() > di.PeriodStart+(v0miner.WPoStProvingPeriod)+2 { break } @@ -178,6 +184,14 @@ func TestWindowPost(t *testing.T, b APIBuilder, blocktime time.Duration, nSector require.Equal(t, p.MinerPower, p.TotalPower) require.Equal(t, p.MinerPower.RawBytePower, types.NewInt(uint64(ssz)*uint64(nSectors+GenesisPreseals))) + store := cbor.NewCborStore(apibstore.NewAPIBlockstore(client)) + + mact, err := client.StateGetActor(ctx, maddr, types.EmptyTSK) + require.NoError(t, err) + + minState, err := lotusminer.Load(adt.WrapStore(ctx, store), mact) + require.NoError(t, err) + fmt.Printf("Drop some sectors\n") // Drop 2 sectors from deadline 2 partition 0 (full partition / deadline) @@ -186,12 +200,14 @@ func TestWindowPost(t *testing.T, b APIBuilder, blocktime time.Duration, nSector require.NoError(t, err) require.Greater(t, len(parts), 0) - n, err := parts[0].Sectors.Count() + secs, err := parts[0].AllSectors() + require.NoError(t, err) + n, err := secs.Count() require.NoError(t, err) require.Equal(t, uint64(2), n) // Drop the partition - err = parts[0].Sectors.ForEach(func(sid uint64) error { + err = secs.ForEach(func(sid uint64) error { return miner.StorageMiner.(*impl.StorageMinerAPI).IStorageMgr.(*mock.SectorMgr).MarkCorrupted(abi.SectorID{ Miner: abi.ActorID(mid), Number: abi.SectorNumber(sid), @@ -208,15 +224,17 @@ func TestWindowPost(t *testing.T, b APIBuilder, blocktime time.Duration, nSector require.NoError(t, err) require.Greater(t, len(parts), 0) - n, err := parts[0].Sectors.Count() + secs, err := parts[0].AllSectors() + require.NoError(t, err) + n, err := secs.Count() require.NoError(t, err) require.Equal(t, uint64(2), n) // Drop the sector - sn, err := parts[0].Sectors.First() + sn, err := secs.First() require.NoError(t, err) - all, err := parts[0].Sectors.All(2) + all, err := secs.All(2) require.NoError(t, err) fmt.Println("the sectors", all) @@ -238,7 +256,7 @@ func TestWindowPost(t *testing.T, b APIBuilder, blocktime time.Duration, nSector head, err := client.ChainHead(ctx) require.NoError(t, err) - if head.Height() > di.PeriodStart+(miner2.WPoStProvingPeriod)+2 { + if head.Height() > di.PeriodStart+(minState.WpostProvingPeriod())+2 { break } @@ -268,7 +286,7 @@ func TestWindowPost(t *testing.T, b APIBuilder, blocktime time.Duration, nSector head, err := client.ChainHead(ctx) require.NoError(t, err) - if head.Height() > di.PeriodStart+(miner2.WPoStProvingPeriod)+2 { + if head.Height() > di.PeriodStart+(minState.WpostProvingPeriod())+2 { break } diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index 5ad8db39e..e436fdc69 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -46,6 +46,7 @@ type State interface { Info() (MinerInfo, error) DeadlineInfo(epoch abi.ChainEpoch) *dline.Info + WpostProvingPeriod() abi.ChainEpoch } type Deadline interface { diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index e1ef9c51f..446c828f1 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -14,21 +14,21 @@ import ( cbg "github.com/whyrusleeping/cbor-gen" "golang.org/x/xerrors" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" ) type v0State struct { - miner.State + v0miner.State store adt.Store } type v0Deadline struct { - miner.Deadline + v0miner.Deadline store adt.Store } type v0Partition struct { - miner.Partition + v0miner.Partition store adt.Store } @@ -69,13 +69,13 @@ func (s *v0State) GetSectorExpiration(num abi.SectorNumber) (out *SectorExpirati // 2. If it's faulty, it will expire early within the first 14 entries // of the expiration queue. stopErr := errors.New("stop") - err = dls.ForEach(s.store, func(dlIdx uint64, dl *miner.Deadline) error { + err = dls.ForEach(s.store, func(dlIdx uint64, dl *v0miner.Deadline) error { partitions, err := dl.PartitionsArray(s.store) if err != nil { return err } quant := s.State.QuantSpecForDeadline(dlIdx) - var part miner.Partition + var part v0miner.Partition return partitions.ForEach(&part, func(partIdx int64) error { if found, err := part.Sectors.IsSet(uint64(num)); err != nil { return err @@ -89,11 +89,11 @@ func (s *v0State) GetSectorExpiration(num abi.SectorNumber) (out *SectorExpirati return stopErr } - q, err := miner.LoadExpirationQueue(s.store, part.EarlyTerminated, quant) + q, err := v0miner.LoadExpirationQueue(s.store, part.EarlyTerminated, quant) if err != nil { return err } - var exp miner.ExpirationSet + var exp v0miner.ExpirationSet return q.ForEach(&exp, func(epoch int64) error { if early, err := exp.EarlySectors.IsSet(uint64(num)); err != nil { return err @@ -151,7 +151,7 @@ func (s *v0State) LoadSectorsFromSet(filter *bitfield.BitField, filterOut bool) } } - var oci miner.SectorOnChainInfo + var oci v0miner.SectorOnChainInfo if err := oci.UnmarshalCBOR(bytes.NewReader(v.Raw)); err != nil { return err } @@ -184,13 +184,13 @@ func (s *v0State) ForEachDeadline(cb func(uint64, Deadline) error) error { if err != nil { return err } - return dls.ForEach(s.store, func(i uint64, dl *miner.Deadline) error { + return dls.ForEach(s.store, func(i uint64, dl *v0miner.Deadline) error { return cb(i, &v0Deadline{*dl, s.store}) }) } func (s *v0State) NumDeadlines() (uint64, error) { - return miner.WPoStPeriodDeadlines, nil + return v0miner.WPoStPeriodDeadlines, nil } func (s *v0State) Info() (MinerInfo, error) { @@ -230,6 +230,9 @@ func (s *v0State) Info() (MinerInfo, error) { func (s *v0State) DeadlineInfo(epoch abi.ChainEpoch) *dline.Info { return s.State.DeadlineInfo(epoch) } +func (s *v0State) WpostProvingPeriod() abi.ChainEpoch { + return v0miner.WPoStProvingPeriod +} func (d *v0Deadline) LoadPartition(idx uint64) (Partition, error) { p, err := d.Deadline.LoadPartition(d.store, idx) @@ -244,7 +247,7 @@ func (d *v0Deadline) ForEachPartition(cb func(uint64, Partition) error) error { if err != nil { return err } - var part miner.Partition + var part v0miner.Partition return ps.ForEach(&part, func(i int64) error { return cb(uint64(i), &v0Partition{part, d.store}) }) diff --git a/chain/stmgr/forks_test.go b/chain/stmgr/forks_test.go index d9d0af745..2db11e832 100644 --- a/chain/stmgr/forks_test.go +++ b/chain/stmgr/forks_test.go @@ -11,7 +11,7 @@ import ( "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/specs-actors/actors/builtin" init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/specs-actors/actors/runtime" @@ -33,7 +33,7 @@ import ( ) func init() { - miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ + v0miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } v0power.ConsensusMinerMinPower = big.NewInt(2048) diff --git a/node/impl/full/state.go b/node/impl/full/state.go index a19edb1ca..766f924bd 100644 --- a/node/impl/full/state.go +++ b/node/impl/full/state.go @@ -27,7 +27,6 @@ import ( "github.com/filecoin-project/specs-actors/actors/util/smoothing" "github.com/filecoin-project/lotus/api" - "github.com/filecoin-project/lotus/chain/actors" "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/actors/builtin/multisig" "github.com/filecoin-project/lotus/chain/actors/builtin/power" From 7115485b0acd78a79b90eb0b335c63b63e9256fe Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Wed, 16 Sep 2020 21:56:02 -0400 Subject: [PATCH 046/303] Add a getter for network version --- api/api_full.go | 4 ++++ api/apistruct/struct.go | 7 +++++++ node/impl/full/state.go | 10 ++++++++++ 3 files changed, 21 insertions(+) diff --git a/api/api_full.go b/api/api_full.go index fbbf92d8b..b472febe0 100644 --- a/api/api_full.go +++ b/api/api_full.go @@ -5,6 +5,8 @@ import ( "fmt" "time" + "github.com/filecoin-project/go-state-types/network" + "github.com/ipfs/go-cid" "github.com/libp2p/go-libp2p-core/peer" @@ -388,6 +390,8 @@ type FullNode interface { // StateCirculatingSupply returns the circulating supply of Filecoin at the given tipset StateCirculatingSupply(context.Context, types.TipSetKey) (CirculatingSupply, error) + // StateNetworkVersion returns the network version at the given tipset + StateNetworkVersion(context.Context, types.TipSetKey) (network.Version, error) // MethodGroup: Msig // The Msig methods are used to interact with multisig wallets on the diff --git a/api/apistruct/struct.go b/api/apistruct/struct.go index 1fcd5e0f3..26f7a8708 100644 --- a/api/apistruct/struct.go +++ b/api/apistruct/struct.go @@ -5,6 +5,8 @@ import ( "io" "time" + stnetwork "github.com/filecoin-project/go-state-types/network" + "github.com/ipfs/go-cid" metrics "github.com/libp2p/go-libp2p-core/metrics" "github.com/libp2p/go-libp2p-core/network" @@ -198,6 +200,7 @@ type FullNodeStruct struct { StateVerifiedClientStatus func(context.Context, address.Address, types.TipSetKey) (*verifreg.DataCap, error) `perm:"read"` StateDealProviderCollateralBounds func(context.Context, abi.PaddedPieceSize, bool, types.TipSetKey) (api.DealCollateralBounds, error) `perm:"read"` StateCirculatingSupply func(context.Context, types.TipSetKey) (api.CirculatingSupply, error) `perm:"read"` + StateNetworkVersion func(context.Context, types.TipSetKey) (stnetwork.Version, error) `perm:"read"` MsigGetAvailableBalance func(context.Context, address.Address, types.TipSetKey) (types.BigInt, error) `perm:"read"` MsigGetVested func(context.Context, address.Address, types.TipSetKey, types.TipSetKey) (types.BigInt, error) `perm:"read"` @@ -873,6 +876,10 @@ func (c *FullNodeStruct) StateCirculatingSupply(ctx context.Context, tsk types.T return c.Internal.StateCirculatingSupply(ctx, tsk) } +func (c *FullNodeStruct) StateNetworkVersion(ctx context.Context, tsk types.TipSetKey) (stnetwork.Version, error) { + return c.Internal.StateNetworkVersion(ctx, tsk) +} + func (c *FullNodeStruct) MsigGetAvailableBalance(ctx context.Context, a address.Address, tsk types.TipSetKey) (types.BigInt, error) { return c.Internal.MsigGetAvailableBalance(ctx, a, tsk) } diff --git a/node/impl/full/state.go b/node/impl/full/state.go index 766f924bd..1b29a93a9 100644 --- a/node/impl/full/state.go +++ b/node/impl/full/state.go @@ -5,6 +5,7 @@ import ( "context" "errors" "fmt" + "github.com/filecoin-project/go-state-types/network" "strconv" "github.com/filecoin-project/go-state-types/dline" @@ -1120,3 +1121,12 @@ func (a *StateAPI) StateCirculatingSupply(ctx context.Context, tsk types.TipSetK } return a.StateManager.GetCirculatingSupplyDetailed(ctx, ts.Height(), sTree) } + +func (a *StateAPI) StateNetworkVersion(ctx context.Context, tsk types.TipSetKey) (network.Version, error) { + ts, err := a.Chain.GetTipSetFromKey(tsk) + if err != nil { + return -1, xerrors.Errorf("loading tipset %s: %w", tsk, err) + } + + return a.StateManager.GetNtwkVersion(ctx, ts.Height()), nil +} From 80b6994fe2cfede39053c452a335fb6dd19c9122 Mon Sep 17 00:00:00 2001 From: hannahhoward Date: Wed, 16 Sep 2020 19:13:12 -0700 Subject: [PATCH 047/303] feat(market): update state diffing for market actor Update to abstract actor for markets state diffing. Also move the diff adt functions inside the abstract actors --- .../{events/state => actors/adt}/diff_adt.go | 7 +- .../state => actors/adt}/diff_adt_test.go | 19 +- chain/actors/builtin/market/market.go | 52 +++++ chain/actors/builtin/market/v0.go | 201 +++++++++++++++- chain/events/state/predicates.go | 221 +++++------------- chain/events/state/predicates_test.go | 81 ++++--- cmd/lotus-chainwatch/processor/market.go | 7 +- 7 files changed, 373 insertions(+), 215 deletions(-) rename chain/{events/state => actors/adt}/diff_adt.go (94%) rename chain/{events/state => actors/adt}/diff_adt_test.go (96%) diff --git a/chain/events/state/diff_adt.go b/chain/actors/adt/diff_adt.go similarity index 94% rename from chain/events/state/diff_adt.go rename to chain/actors/adt/diff_adt.go index 519c61c2d..0784b77a2 100644 --- a/chain/events/state/diff_adt.go +++ b/chain/actors/adt/diff_adt.go @@ -1,10 +1,9 @@ -package state +package adt import ( "bytes" "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/specs-actors/actors/util/adt" typegen "github.com/whyrusleeping/cbor-gen" ) @@ -27,7 +26,7 @@ type AdtArrayDiff interface { // - All values that exist in curArr nnd not in prevArr are passed to adtArrayDiff.Add() // - All values that exist in preArr and in curArr are passed to AdtArrayDiff.Modify() // - It is the responsibility of AdtArrayDiff.Modify() to determine if the values it was passed have been modified. -func DiffAdtArray(preArr, curArr *adt.Array, out AdtArrayDiff) error { +func DiffAdtArray(preArr, curArr Array, out AdtArrayDiff) error { prevVal := new(typegen.Deferred) if err := preArr.ForEach(prevVal, func(i int64) error { curVal := new(typegen.Deferred) @@ -76,7 +75,7 @@ type AdtMapDiff interface { Remove(key string, val *typegen.Deferred) error } -func DiffAdtMap(preMap, curMap *adt.Map, out AdtMapDiff) error { +func DiffAdtMap(preMap, curMap Map, out AdtMapDiff) error { prevVal := new(typegen.Deferred) if err := preMap.ForEach(prevVal, func(key string) error { curVal := new(typegen.Deferred) diff --git a/chain/events/state/diff_adt_test.go b/chain/actors/adt/diff_adt_test.go similarity index 96% rename from chain/events/state/diff_adt_test.go rename to chain/actors/adt/diff_adt_test.go index 55926afb9..436e28bbf 100644 --- a/chain/events/state/diff_adt_test.go +++ b/chain/actors/adt/diff_adt_test.go @@ -1,4 +1,4 @@ -package state +package adt import ( "bytes" @@ -13,7 +13,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/specs-actors/actors/runtime" - "github.com/filecoin-project/specs-actors/actors/util/adt" + v0adt "github.com/filecoin-project/specs-actors/actors/util/adt" bstore "github.com/filecoin-project/lotus/lib/blockstore" ) @@ -22,8 +22,8 @@ func TestDiffAdtArray(t *testing.T) { ctxstoreA := newContextStore() ctxstoreB := newContextStore() - arrA := adt.MakeEmptyArray(ctxstoreA) - arrB := adt.MakeEmptyArray(ctxstoreB) + arrA := v0adt.MakeEmptyArray(ctxstoreA) + arrB := v0adt.MakeEmptyArray(ctxstoreB) require.NoError(t, arrA.Set(0, runtime.CBORBytes([]byte{0}))) // delete @@ -76,8 +76,8 @@ func TestDiffAdtMap(t *testing.T) { ctxstoreA := newContextStore() ctxstoreB := newContextStore() - mapA := adt.MakeEmptyMap(ctxstoreA) - mapB := adt.MakeEmptyMap(ctxstoreB) + mapA := v0adt.MakeEmptyMap(ctxstoreA) + mapB := v0adt.MakeEmptyMap(ctxstoreB) require.NoError(t, mapA.Put(abi.UIntKey(0), runtime.CBORBytes([]byte{0}))) // delete @@ -292,12 +292,9 @@ func (t *TestDiffArray) Remove(key uint64, val *typegen.Deferred) error { return nil } -func newContextStore() *contextStore { +func newContextStore() Store { ctx := context.Background() bs := bstore.NewTemporarySync() store := cbornode.NewCborStore(bs) - return &contextStore{ - ctx: ctx, - cst: store, - } + return WrapStore(ctx, store) } diff --git a/chain/actors/builtin/market/market.go b/chain/actors/builtin/market/market.go index 99cca9879..051c46dbe 100644 --- a/chain/actors/builtin/market/market.go +++ b/chain/actors/builtin/market/market.go @@ -29,9 +29,14 @@ func Load(store adt.Store, act *types.Actor) (st State, err error) { type State interface { cbor.Marshaler + BalancesChanged(State) bool EscrowTable() (BalanceTable, error) LockedTable() (BalanceTable, error) TotalLocked() (abi.TokenAmount, error) + StatesChanged(State) bool + States() (DealStates, error) + ProposalsChanged(State) bool + Proposals() (DealProposals, error) VerifyDealsForActivation( minerAddr address.Address, deals []abi.DealID, currEpoch, sectorExpiry abi.ChainEpoch, ) (weight, verifiedWeight abi.DealWeight, err error) @@ -40,3 +45,50 @@ type State interface { type BalanceTable interface { Get(key address.Address) (abi.TokenAmount, error) } + +type DealStates interface { + GetDeal(key abi.DealID) (DealState, error) + Diff(DealStates) (*DealStateChanges, error) +} + +type DealProposals interface { + Diff(DealProposals) (*DealProposalChanges, error) +} + +type DealState interface { + SectorStartEpoch() abi.ChainEpoch + SlashEpoch() abi.ChainEpoch + LastUpdatedEpoch() abi.ChainEpoch + Equals(DealState) bool +} + +type DealProposal interface { +} + +type DealStateChanges struct { + Added []DealIDState + Modified []DealStateChange + Removed []DealIDState +} + +type DealIDState struct { + ID abi.DealID + Deal DealState +} + +// DealStateChange is a change in deal state from -> to +type DealStateChange struct { + ID abi.DealID + From DealState + To DealState +} + +type DealProposalChanges struct { + Added []ProposalIDState + Removed []ProposalIDState +} + +type ProposalIDState struct { + ID abi.DealID + Proposal DealProposal +} diff --git a/chain/actors/builtin/market/v0.go b/chain/actors/builtin/market/v0.go index fb67902da..8f0aa0594 100644 --- a/chain/actors/builtin/market/v0.go +++ b/chain/actors/builtin/market/v0.go @@ -1,11 +1,17 @@ package market import ( + "bytes" + "errors" + "fmt" + "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/specs-actors/actors/builtin/market" - "github.com/filecoin-project/specs-actors/actors/util/adt" + v0adt "github.com/filecoin-project/specs-actors/actors/util/adt" + typegen "github.com/whyrusleeping/cbor-gen" ) type v0State struct { @@ -19,12 +25,58 @@ func (s *v0State) TotalLocked() (abi.TokenAmount, error) { return fml, nil } +func (s *v0State) BalancesChanged(otherState State) bool { + v0otherState, ok := otherState.(*v0State) + if !ok { + // there's no way to compare differnt versions of the state, so let's + // just say that means the state of balances has changed + return true + } + return !s.State.EscrowTable.Equals(v0otherState.State.EscrowTable) || !s.State.LockedTable.Equals(v0otherState.State.LockedTable) +} + +func (s *v0State) StatesChanged(otherState State) bool { + v0otherState, ok := otherState.(*v0State) + if !ok { + // there's no way to compare differnt versions of the state, so let's + // just say that means the state of balances has changed + return true + } + return !s.State.States.Equals(v0otherState.State.States) +} + +func (s *v0State) States() (DealStates, error) { + stateArray, err := v0adt.AsArray(s.store, s.State.States) + if err != nil { + return nil, err + } + return &v0DealStates{stateArray}, nil +} + +func (s *v0State) ProposalsChanged(otherState State) bool { + v0otherState, ok := otherState.(*v0State) + if !ok { + // there's no way to compare differnt versions of the state, so let's + // just say that means the state of balances has changed + return true + } + return !s.State.Proposals.Equals(v0otherState.State.Proposals) +} + +func (s *v0State) Proposals() (DealProposals, error) { + proposalArray, err := v0adt.AsArray(s.store, s.State.Proposals) + if err != nil { + return nil, err + } + return &v0DealProposals{proposalArray}, nil +} + func (s *v0State) EscrowTable() (BalanceTable, error) { - return adt.AsBalanceTable(s.store, s.State.EscrowTable) + return v0adt.AsBalanceTable(s.store, s.State.EscrowTable) } func (s *v0State) LockedTable() (BalanceTable, error) { - return adt.AsBalanceTable(s.store, s.State.LockedTable) + return v0adt.AsBalanceTable(s.store, s.State.LockedTable) } func (s *v0State) VerifyDealsForActivation( @@ -32,3 +84,146 @@ func (s *v0State) VerifyDealsForActivation( ) (weight, verifiedWeight abi.DealWeight, err error) { return market.ValidateDealsForActivation(&s.State, s.store, deals, minerAddr, sectorExpiry, currEpoch) } + +type v0DealStates struct { + adt.Array +} + +func (s *v0DealStates) GetDeal(dealID abi.DealID) (DealState, error) { + var deal market.DealState + found, err := s.Array.Get(uint64(dealID), &deal) + if err != nil { + return nil, err + } + if !found { + return nil, nil + } + return &v0DealState{deal}, nil +} + +func (s *v0DealStates) Diff(other DealStates) (*DealStateChanges, error) { + v0other, ok := other.(*v0DealStates) + if !ok { + // TODO handle this if possible on a case by case basis but for now, just fail + return nil, errors.New("cannot compare deal states across versions") + } + results := new(DealStateChanges) + if err := adt.DiffAdtArray(s, v0other, &v0MarketStatesDiffer{results}); err != nil { + return nil, fmt.Errorf("diffing deal states: %w", err) + } + + return results, nil +} + +type v0MarketStatesDiffer struct { + Results *DealStateChanges +} + +func (d *v0MarketStatesDiffer) Add(key uint64, val *typegen.Deferred) error { + ds := new(v0DealState) + err := ds.UnmarshalCBOR(bytes.NewReader(val.Raw)) + if err != nil { + return err + } + d.Results.Added = append(d.Results.Added, DealIDState{abi.DealID(key), ds}) + return nil +} + +func (d *v0MarketStatesDiffer) Modify(key uint64, from, to *typegen.Deferred) error { + dsFrom := new(v0DealState) + if err := dsFrom.UnmarshalCBOR(bytes.NewReader(from.Raw)); err != nil { + return err + } + + dsTo := new(v0DealState) + if err := dsTo.UnmarshalCBOR(bytes.NewReader(to.Raw)); err != nil { + return err + } + + if *dsFrom != *dsTo { + d.Results.Modified = append(d.Results.Modified, DealStateChange{abi.DealID(key), dsFrom, dsTo}) + } + return nil +} + +func (d *v0MarketStatesDiffer) Remove(key uint64, val *typegen.Deferred) error { + ds := new(v0DealState) + err := ds.UnmarshalCBOR(bytes.NewReader(val.Raw)) + if err != nil { + return err + } + d.Results.Removed = append(d.Results.Removed, DealIDState{abi.DealID(key), ds}) + return nil +} + +type v0DealState struct { + market.DealState +} + +func (ds *v0DealState) SectorStartEpoch() abi.ChainEpoch { + return ds.DealState.SectorStartEpoch +} + +func (ds *v0DealState) SlashEpoch() abi.ChainEpoch { + return ds.DealState.SlashEpoch +} + +func (ds *v0DealState) LastUpdatedEpoch() abi.ChainEpoch { + return ds.DealState.LastUpdatedEpoch +} + +func (ds *v0DealState) Equals(other DealState) bool { + v0other, ok := other.(*v0DealState) + return ok && *ds == *v0other +} + +type v0DealProposals struct { + adt.Array +} + +func (s *v0DealProposals) Diff(other DealProposals) (*DealProposalChanges, error) { + v0other, ok := other.(*v0DealProposals) + if !ok { + // TODO handle this if possible on a case by case basis but for now, just fail + return nil, errors.New("cannot compare deal proposals across versions") + } + results := new(DealProposalChanges) + if err := adt.DiffAdtArray(s, v0other, &v0MarketProposalsDiffer{results}); err != nil { + return nil, fmt.Errorf("diffing deal proposals: %w", err) + } + + return results, nil +} + +type v0MarketProposalsDiffer struct { + Results *DealProposalChanges +} + +type v0DealProposal struct { + market.DealProposal +} + +func (d *v0MarketProposalsDiffer) Add(key uint64, val *typegen.Deferred) error { + dp := new(v0DealProposal) + err := dp.UnmarshalCBOR(bytes.NewReader(val.Raw)) + if err != nil { + return err + } + d.Results.Added = append(d.Results.Added, ProposalIDState{abi.DealID(key), dp}) + return nil +} + +func (d *v0MarketProposalsDiffer) Modify(key uint64, from, to *typegen.Deferred) error { + // short circuit, DealProposals are static + return nil +} + +func (d *v0MarketProposalsDiffer) Remove(key uint64, val *typegen.Deferred) error { + dp := new(v0DealProposal) + err := dp.UnmarshalCBOR(bytes.NewReader(val.Raw)) + if err != nil { + return err + } + d.Results.Removed = append(d.Results.Removed, ProposalIDState{abi.DealID(key), dp}) + return nil +} diff --git a/chain/events/state/predicates.go b/chain/events/state/predicates.go index e5caa41d2..e1e88e1a1 100644 --- a/chain/events/state/predicates.go +++ b/chain/events/state/predicates.go @@ -7,12 +7,13 @@ import ( "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/lotus/chain/actors/adt" + "github.com/filecoin-project/lotus/chain/actors/builtin/market" "github.com/filecoin-project/lotus/chain/actors/builtin/paych" "github.com/filecoin-project/specs-actors/actors/builtin" init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" - "github.com/filecoin-project/specs-actors/actors/builtin/market" "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/filecoin-project/specs-actors/actors/util/adt" + v0adt "github.com/filecoin-project/specs-actors/actors/util/adt" cbor "github.com/ipfs/go-ipld-cbor" typegen "github.com/whyrusleeping/cbor-gen" @@ -69,26 +70,26 @@ func (sp *StatePredicates) OnActorStateChanged(addr address.Address, diffStateFu } } -type DiffStorageMarketStateFunc func(ctx context.Context, oldState *market.State, newState *market.State) (changed bool, user UserData, err error) +type DiffStorageMarketStateFunc func(ctx context.Context, oldState market.State, newState market.State) (changed bool, user UserData, err error) // OnStorageMarketActorChanged calls diffStorageMarketState when the state changes for the market actor func (sp *StatePredicates) OnStorageMarketActorChanged(diffStorageMarketState DiffStorageMarketStateFunc) DiffTipSetKeyFunc { return sp.OnActorStateChanged(builtin.StorageMarketActorAddr, func(ctx context.Context, oldActorState, newActorState *types.Actor) (changed bool, user UserData, err error) { - var oldState market.State - if err := sp.cst.Get(ctx, oldActorState.Head, &oldState); err != nil { + oldState, err := market.Load(adt.WrapStore(ctx, sp.cst), oldActorState) + if err != nil { return false, nil, err } - var newState market.State - if err := sp.cst.Get(ctx, newActorState.Head, &newState); err != nil { + newState, err := market.Load(adt.WrapStore(ctx, sp.cst), newActorState) + if err != nil { return false, nil, err } - return diffStorageMarketState(ctx, &oldState, &newState) + return diffStorageMarketState(ctx, oldState, newState) }) } type BalanceTables struct { - EscrowTable *adt.BalanceTable - LockedTable *adt.BalanceTable + EscrowTable market.BalanceTable + LockedTable market.BalanceTable } // DiffBalanceTablesFunc compares two balance tables @@ -96,32 +97,27 @@ type DiffBalanceTablesFunc func(ctx context.Context, oldBalanceTable, newBalance // OnBalanceChanged runs when the escrow table for available balances changes func (sp *StatePredicates) OnBalanceChanged(diffBalances DiffBalanceTablesFunc) DiffStorageMarketStateFunc { - return func(ctx context.Context, oldState *market.State, newState *market.State) (changed bool, user UserData, err error) { - if oldState.EscrowTable.Equals(newState.EscrowTable) && oldState.LockedTable.Equals(newState.LockedTable) { + return func(ctx context.Context, oldState market.State, newState market.State) (changed bool, user UserData, err error) { + if !oldState.BalancesChanged(newState) { return false, nil, nil } - ctxStore := &contextStore{ - ctx: ctx, - cst: sp.cst, - } - - oldEscrowRoot, err := adt.AsBalanceTable(ctxStore, oldState.EscrowTable) + oldEscrowRoot, err := oldState.EscrowTable() if err != nil { return false, nil, err } - oldLockedRoot, err := adt.AsBalanceTable(ctxStore, oldState.LockedTable) + oldLockedRoot, err := oldState.LockedTable() if err != nil { return false, nil, err } - newEscrowRoot, err := adt.AsBalanceTable(ctxStore, newState.EscrowTable) + newEscrowRoot, err := newState.EscrowTable() if err != nil { return false, nil, err } - newLockedRoot, err := adt.AsBalanceTable(ctxStore, newState.LockedTable) + newLockedRoot, err := newState.LockedTable() if err != nil { return false, nil, err } @@ -130,25 +126,22 @@ func (sp *StatePredicates) OnBalanceChanged(diffBalances DiffBalanceTablesFunc) } } -type DiffAdtArraysFunc func(ctx context.Context, oldDealStateRoot, newDealStateRoot *adt.Array) (changed bool, user UserData, err error) +type DiffDealStatesFunc func(ctx context.Context, oldDealStateRoot, newDealStateRoot market.DealStates) (changed bool, user UserData, err error) +type DiffDealProposalsFunc func(ctx context.Context, oldDealStateRoot, newDealStateRoot market.DealProposals) (changed bool, user UserData, err error) +type DiffAdtArraysFunc func(ctx context.Context, oldDealStateRoot, newDealStateRoot adt.Array) (changed bool, user UserData, err error) // OnDealStateChanged calls diffDealStates when the market deal state changes -func (sp *StatePredicates) OnDealStateChanged(diffDealStates DiffAdtArraysFunc) DiffStorageMarketStateFunc { - return func(ctx context.Context, oldState *market.State, newState *market.State) (changed bool, user UserData, err error) { - if oldState.States.Equals(newState.States) { +func (sp *StatePredicates) OnDealStateChanged(diffDealStates DiffDealStatesFunc) DiffStorageMarketStateFunc { + return func(ctx context.Context, oldState market.State, newState market.State) (changed bool, user UserData, err error) { + if !oldState.StatesChanged(newState) { return false, nil, nil } - ctxStore := &contextStore{ - ctx: ctx, - cst: sp.cst, - } - - oldRoot, err := adt.AsArray(ctxStore, oldState.States) + oldRoot, err := oldState.States() if err != nil { return false, nil, err } - newRoot, err := adt.AsArray(ctxStore, newState.States) + newRoot, err := newState.States() if err != nil { return false, nil, err } @@ -158,22 +151,17 @@ func (sp *StatePredicates) OnDealStateChanged(diffDealStates DiffAdtArraysFunc) } // OnDealProposalChanged calls diffDealProps when the market proposal state changes -func (sp *StatePredicates) OnDealProposalChanged(diffDealProps DiffAdtArraysFunc) DiffStorageMarketStateFunc { - return func(ctx context.Context, oldState *market.State, newState *market.State) (changed bool, user UserData, err error) { - if oldState.Proposals.Equals(newState.Proposals) { +func (sp *StatePredicates) OnDealProposalChanged(diffDealProps DiffDealProposalsFunc) DiffStorageMarketStateFunc { + return func(ctx context.Context, oldState market.State, newState market.State) (changed bool, user UserData, err error) { + if !oldState.ProposalsChanged(newState) { return false, nil, nil } - ctxStore := &contextStore{ - ctx: ctx, - cst: sp.cst, - } - - oldRoot, err := adt.AsArray(ctxStore, oldState.Proposals) + oldRoot, err := oldState.Proposals() if err != nil { return false, nil, err } - newRoot, err := adt.AsArray(ctxStore, newState.Proposals) + newRoot, err := newState.Proposals() if err != nil { return false, nil, err } @@ -182,51 +170,14 @@ func (sp *StatePredicates) OnDealProposalChanged(diffDealProps DiffAdtArraysFunc } } -var _ AdtArrayDiff = &MarketDealProposalChanges{} - -type MarketDealProposalChanges struct { - Added []ProposalIDState - Removed []ProposalIDState -} - -type ProposalIDState struct { - ID abi.DealID - Proposal market.DealProposal -} - -func (m *MarketDealProposalChanges) Add(key uint64, val *typegen.Deferred) error { - dp := new(market.DealProposal) - err := dp.UnmarshalCBOR(bytes.NewReader(val.Raw)) - if err != nil { - return err - } - m.Added = append(m.Added, ProposalIDState{abi.DealID(key), *dp}) - return nil -} - -func (m *MarketDealProposalChanges) Modify(key uint64, from, to *typegen.Deferred) error { - // short circuit, DealProposals are static - return nil -} - -func (m *MarketDealProposalChanges) Remove(key uint64, val *typegen.Deferred) error { - dp := new(market.DealProposal) - err := dp.UnmarshalCBOR(bytes.NewReader(val.Raw)) - if err != nil { - return err - } - m.Removed = append(m.Removed, ProposalIDState{abi.DealID(key), *dp}) - return nil -} - // OnDealProposalAmtChanged detects changes in the deal proposal AMT for all deal proposals and returns a MarketProposalsChanges structure containing: // - Added Proposals // - Modified Proposals // - Removed Proposals -func (sp *StatePredicates) OnDealProposalAmtChanged() DiffAdtArraysFunc { - return func(ctx context.Context, oldDealProps, newDealProps *adt.Array) (changed bool, user UserData, err error) { - proposalChanges := new(MarketDealProposalChanges) - if err := DiffAdtArray(oldDealProps, newDealProps, proposalChanges); err != nil { +func (sp *StatePredicates) OnDealProposalAmtChanged() DiffDealProposalsFunc { + return func(ctx context.Context, oldDealProps, newDealProps market.DealProposals) (changed bool, user UserData, err error) { + proposalChanges, err := oldDealProps.Diff(newDealProps) + if err != nil { return false, nil, err } @@ -238,64 +189,14 @@ func (sp *StatePredicates) OnDealProposalAmtChanged() DiffAdtArraysFunc { } } -var _ AdtArrayDiff = &MarketDealStateChanges{} - -type MarketDealStateChanges struct { - Added []DealIDState - Modified []DealStateChange - Removed []DealIDState -} - -type DealIDState struct { - ID abi.DealID - Deal market.DealState -} - -func (m *MarketDealStateChanges) Add(key uint64, val *typegen.Deferred) error { - ds := new(market.DealState) - err := ds.UnmarshalCBOR(bytes.NewReader(val.Raw)) - if err != nil { - return err - } - m.Added = append(m.Added, DealIDState{abi.DealID(key), *ds}) - return nil -} - -func (m *MarketDealStateChanges) Modify(key uint64, from, to *typegen.Deferred) error { - dsFrom := new(market.DealState) - if err := dsFrom.UnmarshalCBOR(bytes.NewReader(from.Raw)); err != nil { - return err - } - - dsTo := new(market.DealState) - if err := dsTo.UnmarshalCBOR(bytes.NewReader(to.Raw)); err != nil { - return err - } - - if *dsFrom != *dsTo { - m.Modified = append(m.Modified, DealStateChange{abi.DealID(key), dsFrom, dsTo}) - } - return nil -} - -func (m *MarketDealStateChanges) Remove(key uint64, val *typegen.Deferred) error { - ds := new(market.DealState) - err := ds.UnmarshalCBOR(bytes.NewReader(val.Raw)) - if err != nil { - return err - } - m.Removed = append(m.Removed, DealIDState{abi.DealID(key), *ds}) - return nil -} - // OnDealStateAmtChanged detects changes in the deal state AMT for all deal states and returns a MarketDealStateChanges structure containing: // - Added Deals // - Modified Deals // - Removed Deals -func (sp *StatePredicates) OnDealStateAmtChanged() DiffAdtArraysFunc { - return func(ctx context.Context, oldDealStates, newDealStates *adt.Array) (changed bool, user UserData, err error) { - dealStateChanges := new(MarketDealStateChanges) - if err := DiffAdtArray(oldDealStates, newDealStates, dealStateChanges); err != nil { +func (sp *StatePredicates) OnDealStateAmtChanged() DiffDealStatesFunc { + return func(ctx context.Context, oldDealStates, newDealStates market.DealStates) (changed bool, user UserData, err error) { + dealStateChanges, err := oldDealStates.Diff(newDealStates) + if err != nil { return false, nil, err } @@ -313,37 +214,31 @@ type ChangedDeals map[abi.DealID]DealStateChange // DealStateChange is a change in deal state from -> to type DealStateChange struct { ID abi.DealID - From *market.DealState - To *market.DealState + From market.DealState + To market.DealState } // DealStateChangedForIDs detects changes in the deal state AMT for the given deal IDs -func (sp *StatePredicates) DealStateChangedForIDs(dealIds []abi.DealID) DiffAdtArraysFunc { - return func(ctx context.Context, oldDealStateArray, newDealStateArray *adt.Array) (changed bool, user UserData, err error) { +func (sp *StatePredicates) DealStateChangedForIDs(dealIds []abi.DealID) DiffDealStatesFunc { + return func(ctx context.Context, oldDealStates, newDealStates market.DealStates) (changed bool, user UserData, err error) { changedDeals := make(ChangedDeals) for _, dealID := range dealIds { - var oldDealPtr, newDealPtr *market.DealState - var oldDeal, newDeal market.DealState // If the deal has been removed, we just set it to nil - found, err := oldDealStateArray.Get(uint64(dealID), &oldDeal) + oldDeal, err := oldDealStates.GetDeal(dealID) if err != nil { return false, nil, err } - if found { - oldDealPtr = &oldDeal - } - found, err = newDealStateArray.Get(uint64(dealID), &newDeal) + newDeal, err := newDealStates.GetDeal(dealID) if err != nil { return false, nil, err } - if found { - newDealPtr = &newDeal - } - if oldDeal != newDeal { - changedDeals[dealID] = DealStateChange{dealID, oldDealPtr, newDealPtr} + existenceChanged := (oldDeal == nil) != (newDeal == nil) + valueChanged := (oldDeal != nil && newDeal != nil) && !oldDeal.Equals(newDeal) + if existenceChanged || valueChanged { + changedDeals[dealID] = DealStateChange{dealID, oldDeal, newDeal} } } if len(changedDeals) > 0 { @@ -441,7 +336,7 @@ type MinerSectorChanges struct { Removed []miner.SectorOnChainInfo } -var _ AdtArrayDiff = &MinerSectorChanges{} +var _ adt.AdtArrayDiff = &MinerSectorChanges{} type SectorExtensions struct { From miner.SectorOnChainInfo @@ -508,17 +403,17 @@ func (sp *StatePredicates) OnMinerSectorChange() DiffMinerActorStateFunc { return false, nil, nil } - oldSectors, err := adt.AsArray(ctxStore, oldState.Sectors) + oldSectors, err := v0adt.AsArray(ctxStore, oldState.Sectors) if err != nil { return false, nil, err } - newSectors, err := adt.AsArray(ctxStore, newState.Sectors) + newSectors, err := v0adt.AsArray(ctxStore, newState.Sectors) if err != nil { return false, nil, err } - if err := DiffAdtArray(oldSectors, newSectors, sectorChanges); err != nil { + if err := adt.DiffAdtArray(oldSectors, newSectors, sectorChanges); err != nil { return false, nil, err } @@ -584,17 +479,17 @@ func (sp *StatePredicates) OnMinerPreCommitChange() DiffMinerActorStateFunc { return false, nil, nil } - oldPrecommits, err := adt.AsMap(ctxStore, oldState.PreCommittedSectors) + oldPrecommits, err := v0adt.AsMap(ctxStore, oldState.PreCommittedSectors) if err != nil { return false, nil, err } - newPrecommits, err := adt.AsMap(ctxStore, newState.PreCommittedSectors) + newPrecommits, err := v0adt.AsMap(ctxStore, newState.PreCommittedSectors) if err != nil { return false, nil, err } - if err := DiffAdtMap(oldPrecommits, newPrecommits, precommitChanges); err != nil { + if err := adt.DiffAdtMap(oldPrecommits, newPrecommits, precommitChanges); err != nil { return false, nil, err } @@ -763,17 +658,17 @@ func (sp *StatePredicates) OnAddressMapChange() DiffInitActorStateFunc { return false, nil, nil } - oldAddrs, err := adt.AsMap(ctxStore, oldState.AddressMap) + oldAddrs, err := v0adt.AsMap(ctxStore, oldState.AddressMap) if err != nil { return false, nil, err } - newAddrs, err := adt.AsMap(ctxStore, newState.AddressMap) + newAddrs, err := v0adt.AsMap(ctxStore, newState.AddressMap) if err != nil { return false, nil, err } - if err := DiffAdtMap(oldAddrs, newAddrs, addressChanges); err != nil { + if err := adt.DiffAdtMap(oldAddrs, newAddrs, addressChanges); err != nil { return false, nil, err } diff --git a/chain/events/state/predicates_test.go b/chain/events/state/predicates_test.go index 7117a96cc..783c720ed 100644 --- a/chain/events/state/predicates_test.go +++ b/chain/events/state/predicates_test.go @@ -16,7 +16,10 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" - "github.com/filecoin-project/specs-actors/actors/builtin/market" + "github.com/filecoin-project/lotus/chain/actors/builtin/market" + v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" + v0market "github.com/filecoin-project/specs-actors/actors/builtin/market" + "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/specs-actors/actors/util/adt" tutils "github.com/filecoin-project/specs-actors/support/testing" @@ -69,22 +72,22 @@ func TestMarketPredicates(t *testing.T) { bs := bstore.NewTemporarySync() store := adt.WrapStore(ctx, cbornode.NewCborStore(bs)) - oldDeal1 := &market.DealState{ + oldDeal1 := &v0market.DealState{ SectorStartEpoch: 1, LastUpdatedEpoch: 2, SlashEpoch: 0, } - oldDeal2 := &market.DealState{ + oldDeal2 := &v0market.DealState{ SectorStartEpoch: 4, LastUpdatedEpoch: 5, SlashEpoch: 0, } - oldDeals := map[abi.DealID]*market.DealState{ + oldDeals := map[abi.DealID]*v0market.DealState{ abi.DealID(1): oldDeal1, abi.DealID(2): oldDeal2, } - oldProp1 := &market.DealProposal{ + oldProp1 := &v0market.DealProposal{ PieceCID: dummyCid, PieceSize: 0, VerifiedDeal: false, @@ -96,7 +99,7 @@ func TestMarketPredicates(t *testing.T) { ProviderCollateral: big.Zero(), ClientCollateral: big.Zero(), } - oldProp2 := &market.DealProposal{ + oldProp2 := &v0market.DealProposal{ PieceCID: dummyCid, PieceSize: 0, VerifiedDeal: false, @@ -108,7 +111,7 @@ func TestMarketPredicates(t *testing.T) { ProviderCollateral: big.Zero(), ClientCollateral: big.Zero(), } - oldProps := map[abi.DealID]*market.DealProposal{ + oldProps := map[abi.DealID]*v0market.DealProposal{ abi.DealID(1): oldProp1, abi.DealID(2): oldProp2, } @@ -122,7 +125,7 @@ func TestMarketPredicates(t *testing.T) { oldStateC := createMarketState(ctx, t, store, oldDeals, oldProps, oldBalances) - newDeal1 := &market.DealState{ + newDeal1 := &v0market.DealState{ SectorStartEpoch: 1, LastUpdatedEpoch: 3, SlashEpoch: 0, @@ -131,19 +134,19 @@ func TestMarketPredicates(t *testing.T) { // deal 2 removed // added - newDeal3 := &market.DealState{ + newDeal3 := &v0market.DealState{ SectorStartEpoch: 1, LastUpdatedEpoch: 2, SlashEpoch: 3, } - newDeals := map[abi.DealID]*market.DealState{ + newDeals := map[abi.DealID]*v0market.DealState{ abi.DealID(1): newDeal1, // deal 2 was removed abi.DealID(3): newDeal3, } // added - newProp3 := &market.DealProposal{ + newProp3 := &v0market.DealProposal{ PieceCID: dummyCid, PieceSize: 0, VerifiedDeal: false, @@ -155,7 +158,7 @@ func TestMarketPredicates(t *testing.T) { ProviderCollateral: big.Zero(), ClientCollateral: big.Zero(), } - newProps := map[abi.DealID]*market.DealProposal{ + newProps := map[abi.DealID]*v0market.DealProposal{ abi.DealID(1): oldProp1, // 1 was persisted // prop 2 was removed abi.DealID(3): newProp3, // new @@ -178,8 +181,8 @@ func TestMarketPredicates(t *testing.T) { require.NoError(t, err) api := newMockAPI(bs) - api.setActor(oldState.Key(), &types.Actor{Head: oldStateC}) - api.setActor(newState.Key(), &types.Actor{Head: newStateC}) + api.setActor(oldState.Key(), &types.Actor{Code: v0builtin.StorageMarketActorCodeID, Head: oldStateC}) + api.setActor(newState.Key(), &types.Actor{Code: v0builtin.StorageMarketActorCodeID, Head: newStateC}) t.Run("deal ID predicate", func(t *testing.T) { preds := NewStatePredicates(api) @@ -203,11 +206,11 @@ func TestMarketPredicates(t *testing.T) { require.Contains(t, changedDealIDs, abi.DealID(1)) require.Contains(t, changedDealIDs, abi.DealID(2)) deal1 := changedDealIDs[abi.DealID(1)] - if deal1.From.LastUpdatedEpoch != 2 || deal1.To.LastUpdatedEpoch != 3 { + if deal1.From.LastUpdatedEpoch() != 2 || deal1.To.LastUpdatedEpoch() != 3 { t.Fatal("Unexpected change to LastUpdatedEpoch") } deal2 := changedDealIDs[abi.DealID(2)] - if deal2.From.LastUpdatedEpoch != 5 || deal2.To != nil { + if deal2.From.LastUpdatedEpoch() != 5 || deal2.To != nil { t.Fatal("Expected To to be nil") } @@ -230,11 +233,17 @@ func TestMarketPredicates(t *testing.T) { require.False(t, changed) // Test that OnDealStateChanged does not call the callback if the state has not changed - diffDealStateFn := preds.OnDealStateChanged(func(context.Context, *adt.Array, *adt.Array) (bool, UserData, error) { + diffDealStateFn := preds.OnDealStateChanged(func(context.Context, market.DealStates, market.DealStates) (bool, UserData, error) { t.Fatal("No state change so this should not be called") return false, nil, nil }) - marketState := createEmptyMarketState(t, store) + v0marketState := createEmptyMarketState(t, store) + marketCid, err := store.Put(ctx, v0marketState) + require.NoError(t, err) + marketState, err := market.Load(store, &types.Actor{ + Code: v0builtin.StorageMarketActorCodeID, + Head: marketCid, + }) changed, _, err = diffDealStateFn(ctx, marketState, marketState) require.NoError(t, err) require.False(t, changed) @@ -252,18 +261,18 @@ func TestMarketPredicates(t *testing.T) { require.NoError(t, err) require.True(t, changed) - changedDeals, ok := valArr.(*MarketDealStateChanges) + changedDeals, ok := valArr.(*market.DealStateChanges) require.True(t, ok) require.Len(t, changedDeals.Added, 1) require.Equal(t, abi.DealID(3), changedDeals.Added[0].ID) - require.Equal(t, *newDeal3, changedDeals.Added[0].Deal) + require.True(t, dealEquality(*newDeal3, changedDeals.Added[0].Deal)) require.Len(t, changedDeals.Removed, 1) require.Len(t, changedDeals.Modified, 1) require.Equal(t, abi.DealID(1), changedDeals.Modified[0].ID) - require.Equal(t, newDeal1, changedDeals.Modified[0].To) - require.Equal(t, oldDeal1, changedDeals.Modified[0].From) + require.True(t, dealEquality(*newDeal1, changedDeals.Modified[0].To)) + require.True(t, dealEquality(*oldDeal1, changedDeals.Modified[0].From)) require.Equal(t, abi.DealID(2), changedDeals.Removed[0].ID) }) @@ -279,17 +288,15 @@ func TestMarketPredicates(t *testing.T) { require.NoError(t, err) require.True(t, changed) - changedProps, ok := valArr.(*MarketDealProposalChanges) + changedProps, ok := valArr.(*market.DealProposalChanges) require.True(t, ok) require.Len(t, changedProps.Added, 1) require.Equal(t, abi.DealID(3), changedProps.Added[0].ID) - require.Equal(t, *newProp3, changedProps.Added[0].Proposal) // proposals cannot be modified -- no modified testing require.Len(t, changedProps.Removed, 1) require.Equal(t, abi.DealID(2), changedProps.Removed[0].ID) - require.Equal(t, *oldProp2, changedProps.Removed[0].Proposal) }) t.Run("balances predicate", func(t *testing.T) { @@ -342,7 +349,13 @@ func TestMarketPredicates(t *testing.T) { t.Fatal("No state change so this should not be called") return false, nil, nil }) - marketState := createEmptyMarketState(t, store) + v0marketState := createEmptyMarketState(t, store) + marketCid, err := store.Put(ctx, v0marketState) + require.NoError(t, err) + marketState, err := market.Load(store, &types.Actor{ + Code: v0builtin.StorageMarketActorCodeID, + Head: marketCid, + }) changed, _, err = diffDealBalancesFn(ctx, marketState, marketState) require.NoError(t, err) require.False(t, changed) @@ -450,7 +463,7 @@ type balance struct { locked abi.TokenAmount } -func createMarketState(ctx context.Context, t *testing.T, store adt.Store, deals map[abi.DealID]*market.DealState, props map[abi.DealID]*market.DealProposal, balances map[address.Address]balance) cid.Cid { +func createMarketState(ctx context.Context, t *testing.T, store adt.Store, deals map[abi.DealID]*v0market.DealState, props map[abi.DealID]*v0market.DealProposal, balances map[address.Address]balance) cid.Cid { dealRootCid := createDealAMT(ctx, t, store, deals) propRootCid := createProposalAMT(ctx, t, store, props) balancesCids := createBalanceTable(ctx, t, store, balances) @@ -465,15 +478,15 @@ func createMarketState(ctx context.Context, t *testing.T, store adt.Store, deals return stateC } -func createEmptyMarketState(t *testing.T, store adt.Store) *market.State { +func createEmptyMarketState(t *testing.T, store adt.Store) *v0market.State { emptyArrayCid, err := adt.MakeEmptyArray(store).Root() require.NoError(t, err) emptyMap, err := adt.MakeEmptyMap(store).Root() require.NoError(t, err) - return market.ConstructState(emptyArrayCid, emptyMap, emptyMap) + return v0market.ConstructState(emptyArrayCid, emptyMap, emptyMap) } -func createDealAMT(ctx context.Context, t *testing.T, store adt.Store, deals map[abi.DealID]*market.DealState) cid.Cid { +func createDealAMT(ctx context.Context, t *testing.T, store adt.Store, deals map[abi.DealID]*v0market.DealState) cid.Cid { root := adt.MakeEmptyArray(store) for dealID, dealState := range deals { err := root.Set(uint64(dealID), dealState) @@ -484,7 +497,7 @@ func createDealAMT(ctx context.Context, t *testing.T, store adt.Store, deals map return rootCid } -func createProposalAMT(ctx context.Context, t *testing.T, store adt.Store, props map[abi.DealID]*market.DealProposal) cid.Cid { +func createProposalAMT(ctx context.Context, t *testing.T, store adt.Store, props map[abi.DealID]*v0market.DealProposal) cid.Cid { root := adt.MakeEmptyArray(store) for dealID, prop := range props { err := root.Set(uint64(dealID), prop) @@ -607,3 +620,9 @@ func newSectorPreCommitInfo(sectorNo abi.SectorNumber, sealed cid.Cid, expiratio Expiration: expiration, } } + +func dealEquality(expected v0market.DealState, actual market.DealState) bool { + return expected.LastUpdatedEpoch == actual.LastUpdatedEpoch() && + expected.SectorStartEpoch == actual.SectorStartEpoch() && + expected.SlashEpoch == actual.SlashEpoch() +} diff --git a/cmd/lotus-chainwatch/processor/market.go b/cmd/lotus-chainwatch/processor/market.go index e50ec3076..a4bae4b20 100644 --- a/cmd/lotus-chainwatch/processor/market.go +++ b/cmd/lotus-chainwatch/processor/market.go @@ -8,6 +8,7 @@ import ( "golang.org/x/sync/errgroup" "golang.org/x/xerrors" + "github.com/filecoin-project/lotus/chain/actors/builtin/market" "github.com/filecoin-project/lotus/chain/events/state" ) @@ -293,14 +294,14 @@ func (p *Processor) updateMarketActorDealProposals(ctx context.Context, marketTi if !changed { continue } - changes, ok := val.(*state.MarketDealStateChanges) + changes, ok := val.(*market.DealStateChanges) if !ok { return xerrors.Errorf("Unknown type returned by Deal State AMT predicate: %T", val) } for _, modified := range changes.Modified { - if modified.From.SlashEpoch != modified.To.SlashEpoch { - if _, err := stmt.Exec(modified.To.SlashEpoch, modified.ID); err != nil { + if modified.From.SlashEpoch() != modified.To.SlashEpoch() { + if _, err := stmt.Exec(modified.To.SlashEpoch(), modified.ID); err != nil { return err } } From d5af25b76cba60d0aceb94ab395d5df9ebee1428 Mon Sep 17 00:00:00 2001 From: Frank Date: Thu, 17 Sep 2020 10:38:07 +0800 Subject: [PATCH 048/303] update init sector state list --- cmd/lotus-storage-miner/sectors.go | 4 +- extern/storage-sealing/sector_state.go | 63 +++++++++++++------------- 2 files changed, 33 insertions(+), 34 deletions(-) diff --git a/cmd/lotus-storage-miner/sectors.go b/cmd/lotus-storage-miner/sectors.go index c08d6ca14..1b5cfb676 100644 --- a/cmd/lotus-storage-miner/sectors.go +++ b/cmd/lotus-storage-miner/sectors.go @@ -17,9 +17,9 @@ import ( "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/chain/types" - - sealing "github.com/filecoin-project/lotus/extern/storage-sealing" + lcli "github.com/filecoin-project/lotus/cli" + sealing "github.com/filecoin-project/lotus/extern/storage-sealing" ) var sectorsCmd = &cli.Command{ diff --git a/extern/storage-sealing/sector_state.go b/extern/storage-sealing/sector_state.go index 3ed891064..10b96e504 100644 --- a/extern/storage-sealing/sector_state.go +++ b/extern/storage-sealing/sector_state.go @@ -2,7 +2,37 @@ package sealing type SectorState string -var ExistSectorStateList = make(map[SectorState]struct{}) +var ExistSectorStateList = map[SectorState]struct{}{ + Empty: {}, + WaitDeals: {}, + Packing: {}, + PreCommit1: {}, + PreCommit2: {}, + PreCommitting: {}, + PreCommitWait: {}, + WaitSeed: {}, + Committing: {}, + SubmitCommit: {}, + CommitWait: {}, + FinalizeSector: {}, + Proving: {}, + FailedUnrecoverable: {}, + SealPreCommit1Failed: {}, + SealPreCommit2Failed: {}, + PreCommitFailed: {}, + ComputeProofFailed: {}, + CommitFailed: {}, + PackingFailed: {}, + FinalizeFailed: {}, + DealsExpired: {}, + RecoverDealIDs: {}, + Faulty: {}, + FaultReported: {}, + FaultedFinal: {}, + Removing: {}, + RemoveFailed: {}, + Removed: {}, +} const ( UndefinedSectorState SectorState = "" @@ -41,37 +71,6 @@ const ( RemoveFailed SectorState = "RemoveFailed" Removed SectorState = "Removed" ) -func init() { - ExistSectorStateList[Empty] = struct{}{} - ExistSectorStateList[WaitDeals] = struct{}{} - ExistSectorStateList[Packing] = struct{}{} - ExistSectorStateList[PreCommit1] = struct{}{} - ExistSectorStateList[PreCommit2] = struct{}{} - ExistSectorStateList[PreCommitting] = struct{}{} - ExistSectorStateList[PreCommitWait] = struct{}{} - ExistSectorStateList[WaitSeed] = struct{}{} - ExistSectorStateList[Committing] = struct{}{} - ExistSectorStateList[SubmitCommit] = struct{}{} - ExistSectorStateList[CommitWait] = struct{}{} - ExistSectorStateList[FinalizeSector] = struct{}{} - ExistSectorStateList[Proving] = struct{}{} - ExistSectorStateList[FailedUnrecoverable] = struct{}{} - ExistSectorStateList[SealPreCommit1Failed] = struct{}{} - ExistSectorStateList[SealPreCommit2Failed] = struct{}{} - ExistSectorStateList[PreCommitFailed] = struct{}{} - ExistSectorStateList[ComputeProofFailed] = struct{}{} - ExistSectorStateList[CommitFailed] = struct{}{} - ExistSectorStateList[PackingFailed] = struct{}{} - ExistSectorStateList[FinalizeFailed] = struct{}{} - ExistSectorStateList[DealsExpired] = struct{}{} - ExistSectorStateList[RecoverDealIDs] = struct{}{} - ExistSectorStateList[Faulty] = struct{}{} - ExistSectorStateList[FaultReported] = struct{}{} - ExistSectorStateList[FaultedFinal] = struct{}{} - ExistSectorStateList[Removing] = struct{}{} - ExistSectorStateList[RemoveFailed] = struct{}{} - ExistSectorStateList[Removed] = struct{}{} -} func toStatState(st SectorState) statSectorState { switch st { From bf2e3baa8fd2e192cfcca15c05c66ced1bc12eb9 Mon Sep 17 00:00:00 2001 From: Frank Date: Thu, 17 Sep 2020 11:49:23 +0800 Subject: [PATCH 049/303] fix conformance gen --- conformance/chaos/cbor_gen.go | 6 +++--- conformance/chaos/gen/gen.go | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/conformance/chaos/cbor_gen.go b/conformance/chaos/cbor_gen.go index 2d9deec93..61e36e661 100644 --- a/conformance/chaos/cbor_gen.go +++ b/conformance/chaos/cbor_gen.go @@ -6,10 +6,10 @@ import ( "fmt" "io" - "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/go-state-types/exitcode" + abi "github.com/filecoin-project/go-state-types/abi" + exitcode "github.com/filecoin-project/go-state-types/exitcode" cbg "github.com/whyrusleeping/cbor-gen" - "golang.org/x/xerrors" + xerrors "golang.org/x/xerrors" ) var _ = xerrors.Errorf diff --git a/conformance/chaos/gen/gen.go b/conformance/chaos/gen/gen.go index 496cc3d35..ea04aee21 100644 --- a/conformance/chaos/gen/gen.go +++ b/conformance/chaos/gen/gen.go @@ -7,7 +7,7 @@ import ( ) func main() { - if err := gen.WriteTupleEncodersToFile("../cbor_gen.go", "chaos", + if err := gen.WriteTupleEncodersToFile("./cbor_gen.go", "chaos", chaos.State{}, chaos.CreateActorArgs{}, chaos.ResolveAddressResponse{}, From b5ba7a0fad639952d22ee102037d4dc5ae53b99c Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Wed, 16 Sep 2020 22:34:13 -0400 Subject: [PATCH 050/303] Miner migration --- build/params_2k.go | 4 +- build/params_shared_funcs.go | 6 +-- build/params_shared_vals.go | 5 +- build/params_testground.go | 4 +- build/params_testnet.go | 4 +- chain/actors/builtin/miner/miner.go | 13 +++++- chain/actors/builtin/miner/v0.go | 33 +++++++------ chain/events/state/predicates.go | 34 ++++---------- chain/events/state/predicates_test.go | 22 +++++---- chain/gen/gen.go | 4 +- chain/gen/gen_test.go | 4 +- chain/gen/genesis/miners.go | 19 ++++---- chain/store/store_test.go | 4 +- chain/sync_test.go | 4 +- chain/vm/invoker.go | 4 +- chain/vm/syscalls.go | 6 +-- cli/paych_test.go | 4 +- cmd/lotus-pcr/main.go | 29 ++++++++++-- extern/storage-sealing/checks.go | 27 +++++++++-- extern/storage-sealing/constants.go | 10 +--- extern/storage-sealing/fsm_events.go | 2 +- extern/storage-sealing/precommit_policy.go | 24 ++++++++-- extern/storage-sealing/sealing.go | 22 ++++++++- extern/storage-sealing/states_failed.go | 3 +- extern/storage-sealing/states_sealing.go | 54 ++++++++++++++++++---- extern/storage-sealing/upgrade_queue.go | 3 +- markets/storageadapter/client.go | 3 +- markets/storageadapter/provider.go | 3 +- node/impl/client/client.go | 4 +- node/node_test.go | 6 +-- node/test/builder.go | 4 +- storage/adapter_storage_miner.go | 32 ++++++------- storage/miner.go | 11 ++++- storage/wdpost_journal.go | 2 +- storage/wdpost_run.go | 37 +++++++++------ 35 files changed, 288 insertions(+), 162 deletions(-) diff --git a/build/params_2k.go b/build/params_2k.go index 313ccfa9d..cf34706e5 100644 --- a/build/params_2k.go +++ b/build/params_2k.go @@ -5,7 +5,7 @@ package build import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" ) @@ -21,7 +21,7 @@ var DrandSchedule = map[abi.ChainEpoch]DrandEnum{ func init() { v0power.ConsensusMinerMinPower = big.NewInt(2048) - miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ + v0miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } verifreg.MinVerifiedDealSize = big.NewInt(256) diff --git a/build/params_shared_funcs.go b/build/params_shared_funcs.go index 2c585271a..08f16cefd 100644 --- a/build/params_shared_funcs.go +++ b/build/params_shared_funcs.go @@ -6,14 +6,14 @@ import ( "github.com/libp2p/go-libp2p-core/protocol" "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/lotus/node/modules/dtypes" ) func DefaultSectorSize() abi.SectorSize { - szs := make([]abi.SectorSize, 0, len(miner.SupportedProofTypes)) - for spt := range miner.SupportedProofTypes { + szs := make([]abi.SectorSize, 0, len(v0miner.SupportedProofTypes)) + for spt := range v0miner.SupportedProofTypes { ss, err := spt.SectorSize() if err != nil { panic(err) diff --git a/build/params_shared_vals.go b/build/params_shared_vals.go index 4a46b7fd1..ac7796ae7 100644 --- a/build/params_shared_vals.go +++ b/build/params_shared_vals.go @@ -9,7 +9,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" ) // ///// @@ -23,6 +23,7 @@ const UnixfsLinksPerLevel = 1024 const AllowableClockDriftSecs = uint64(1) const NewestNetworkVersion = network.Version2 +const ActorUpgradeNetworkVersion = network.Version3 // Epochs const ForkLengthThreshold = Finality @@ -31,7 +32,7 @@ const ForkLengthThreshold = Finality var BlocksPerEpoch = uint64(builtin.ExpectedLeadersPerEpoch) // Epochs -const Finality = miner.ChainFinality +const Finality = v0miner.ChainFinality const MessageConfidence = uint64(5) // constants for Weight calculation diff --git a/build/params_testground.go b/build/params_testground.go index 395d2a855..77e312ac2 100644 --- a/build/params_testground.go +++ b/build/params_testground.go @@ -13,7 +13,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/network" "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" ) var ( @@ -32,7 +32,7 @@ var ( AllowableClockDriftSecs = uint64(1) - Finality = miner.ChainFinality + Finality = v0miner.ChainFinality ForkLengthThreshold = Finality SlashablePowerDelay = 20 diff --git a/build/params_testnet.go b/build/params_testnet.go index 4cfd8a9b6..a879d3ba7 100644 --- a/build/params_testnet.go +++ b/build/params_testnet.go @@ -8,7 +8,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" ) @@ -24,7 +24,7 @@ const UpgradeSmokeHeight = 51000 func init() { v0power.ConsensusMinerMinPower = big.NewInt(10 << 40) - miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ + v0miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg32GiBV1: {}, abi.RegisteredSealProof_StackedDrg64GiBV1: {}, } diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index e436fdc69..90c44eff3 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -38,7 +38,9 @@ type State interface { FindSector(abi.SectorNumber) (*SectorLocation, error) GetSectorExpiration(abi.SectorNumber) (*SectorExpiration, error) GetPrecommittedSector(abi.SectorNumber) (*SectorPreCommitOnChainInfo, error) - LoadSectorsFromSet(filter *bitfield.BitField, filterOut bool) ([]*ChainSectorInfo, error) + LoadSectorsFromSet(filter *bitfield.BitField, filterOut bool) (adt.Array, error) + LoadPreCommittedSectorsFromSet(filter *bitfield.BitField, filterOut bool) (adt.Map, error) + IsAllocated(abi.SectorNumber) (bool, error) LoadDeadline(idx uint64) (Deadline, error) ForEachDeadline(cb func(idx uint64, dl Deadline) error) error @@ -65,6 +67,15 @@ type Partition interface { type SectorOnChainInfo = v0miner.SectorOnChainInfo type SectorPreCommitInfo = v0miner.SectorPreCommitInfo type SectorPreCommitOnChainInfo = v0miner.SectorPreCommitOnChainInfo +type PoStPartition = v0miner.PoStPartition +type RecoveryDeclaration = v0miner.RecoveryDeclaration +type FaultDeclaration = v0miner.FaultDeclaration + +// Params +type DeclareFaultsParams = v0miner.DeclareFaultsParams +type DeclareFaultsRecoveredParams = v0miner.DeclareFaultsRecoveredParams +type SubmitWindowedPoStParams = v0miner.SubmitWindowedPoStParams +type ProveCommitSectorParams = v0miner.ProveCommitSectorParams type MinerInfo struct { Owner address.Address // Must be an ID-address. diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index 446c828f1..b56fb1745 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -1,7 +1,6 @@ package miner import ( - "bytes" "errors" "github.com/filecoin-project/go-address" @@ -132,13 +131,12 @@ func (s *v0State) GetPrecommittedSector(num abi.SectorNumber) (*SectorPreCommitO return info, nil } -func (s *v0State) LoadSectorsFromSet(filter *bitfield.BitField, filterOut bool) ([]*ChainSectorInfo, error) { +func (s *v0State) LoadSectorsFromSet(filter *bitfield.BitField, filterOut bool) (adt.Array, error) { a, err := v0adt.AsArray(s.store, s.State.Sectors) if err != nil { return nil, err } - var sset []*ChainSectorInfo var v cbg.Deferred if err := a.ForEach(&v, func(i int64) error { if filter != nil { @@ -147,24 +145,31 @@ func (s *v0State) LoadSectorsFromSet(filter *bitfield.BitField, filterOut bool) return xerrors.Errorf("filter check error: %w", err) } if set == filterOut { - return nil + err = a.Delete(uint64(i)) + if err != nil { + return xerrors.Errorf("filtering error: %w", err) + } } } - - var oci v0miner.SectorOnChainInfo - if err := oci.UnmarshalCBOR(bytes.NewReader(v.Raw)); err != nil { - return err - } - sset = append(sset, &ChainSectorInfo{ - Info: oci, - ID: abi.SectorNumber(i), - }) return nil }); err != nil { return nil, err } - return sset, nil + return a, nil +} + +func (s *v0State) LoadPreCommittedSectors() (adt.Map, error) { + return v0adt.AsMap(s.store, s.State.PreCommittedSectors) +} + +func (s *v0State) IsAllocated(num abi.SectorNumber) (bool, error) { + var allocatedSectors bitfield.BitField + if err := s.store.Get(s.store.Context(), s.State.AllocatedSectors, &allocatedSectors); err != nil { + return false, err + } + + return allocatedSectors.IsSet(uint64(num)) } func (s *v0State) LoadDeadline(idx uint64) (Deadline, error) { diff --git a/chain/events/state/predicates.go b/chain/events/state/predicates.go index e1e88e1a1..5a885504f 100644 --- a/chain/events/state/predicates.go +++ b/chain/events/state/predicates.go @@ -4,6 +4,10 @@ import ( "bytes" "context" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" @@ -12,7 +16,6 @@ import ( "github.com/filecoin-project/lotus/chain/actors/builtin/paych" "github.com/filecoin-project/specs-actors/actors/builtin" init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" v0adt "github.com/filecoin-project/specs-actors/actors/util/adt" cbor "github.com/ipfs/go-ipld-cbor" typegen "github.com/whyrusleeping/cbor-gen" @@ -387,28 +390,18 @@ func (m *MinerSectorChanges) Remove(key uint64, val *typegen.Deferred) error { func (sp *StatePredicates) OnMinerSectorChange() DiffMinerActorStateFunc { return func(ctx context.Context, oldState, newState *miner.State) (changed bool, user UserData, err error) { - ctxStore := &contextStore{ - ctx: ctx, - cst: sp.cst, - } - sectorChanges := &MinerSectorChanges{ Added: []miner.SectorOnChainInfo{}, Extended: []SectorExtensions{}, Removed: []miner.SectorOnChainInfo{}, } - // no sector changes - if oldState.Sectors.Equals(newState.Sectors) { - return false, nil, nil - } - - oldSectors, err := v0adt.AsArray(ctxStore, oldState.Sectors) + oldSectors, err := oldState.LoadSectorsFromSet(nil, false) if err != nil { return false, nil, err } - newSectors, err := v0adt.AsArray(ctxStore, newState.Sectors) + newSectors, err := newState.LoadSectorsFromSet(nil, false) if err != nil { return false, nil, err } @@ -436,7 +429,7 @@ func (m *MinerPreCommitChanges) AsKey(key string) (abi.Keyer, error) { if err != nil { return nil, err } - return miner.SectorKey(abi.SectorNumber(sector)), nil + return v0miner.SectorKey(abi.SectorNumber(sector)), nil } func (m *MinerPreCommitChanges) Add(key string, val *typegen.Deferred) error { @@ -465,26 +458,17 @@ func (m *MinerPreCommitChanges) Remove(key string, val *typegen.Deferred) error func (sp *StatePredicates) OnMinerPreCommitChange() DiffMinerActorStateFunc { return func(ctx context.Context, oldState, newState *miner.State) (changed bool, user UserData, err error) { - ctxStore := &contextStore{ - ctx: ctx, - cst: sp.cst, - } - precommitChanges := &MinerPreCommitChanges{ Added: []miner.SectorPreCommitOnChainInfo{}, Removed: []miner.SectorPreCommitOnChainInfo{}, } - if oldState.PreCommittedSectors.Equals(newState.PreCommittedSectors) { - return false, nil, nil - } - - oldPrecommits, err := v0adt.AsMap(ctxStore, oldState.PreCommittedSectors) + oldPrecommits, err := oldState.LoadPreCommittedSectors() if err != nil { return false, nil, err } - newPrecommits, err := v0adt.AsMap(ctxStore, newState.PreCommittedSectors) + newPrecommits, err := newState.LoadPreCommittedSectors() if err != nil { return false, nil, err } diff --git a/chain/events/state/predicates_test.go b/chain/events/state/predicates_test.go index 783c720ed..25f25334d 100644 --- a/chain/events/state/predicates_test.go +++ b/chain/events/state/predicates_test.go @@ -4,6 +4,8 @@ import ( "context" "testing" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + "github.com/filecoin-project/go-bitfield" "github.com/stretchr/testify/require" @@ -20,7 +22,7 @@ import ( v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" v0market "github.com/filecoin-project/specs-actors/actors/builtin/market" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/specs-actors/actors/util/adt" tutils "github.com/filecoin-project/specs-actors/support/testing" @@ -375,12 +377,12 @@ func TestMinerSectorChange(t *testing.T) { } owner, worker := nextIDAddrF(), nextIDAddrF() - si0 := newSectorOnChainInfo(0, tutils.MakeCID("0", &miner.SealedCIDPrefix), big.NewInt(0), abi.ChainEpoch(0), abi.ChainEpoch(10)) - si1 := newSectorOnChainInfo(1, tutils.MakeCID("1", &miner.SealedCIDPrefix), big.NewInt(1), abi.ChainEpoch(1), abi.ChainEpoch(11)) - si2 := newSectorOnChainInfo(2, tutils.MakeCID("2", &miner.SealedCIDPrefix), big.NewInt(2), abi.ChainEpoch(2), abi.ChainEpoch(11)) + si0 := newSectorOnChainInfo(0, tutils.MakeCID("0", &v0miner.SealedCIDPrefix), big.NewInt(0), abi.ChainEpoch(0), abi.ChainEpoch(10)) + si1 := newSectorOnChainInfo(1, tutils.MakeCID("1", &v0miner.SealedCIDPrefix), big.NewInt(1), abi.ChainEpoch(1), abi.ChainEpoch(11)) + si2 := newSectorOnChainInfo(2, tutils.MakeCID("2", &v0miner.SealedCIDPrefix), big.NewInt(2), abi.ChainEpoch(2), abi.ChainEpoch(11)) oldMinerC := createMinerState(ctx, t, store, owner, worker, []miner.SectorOnChainInfo{si0, si1, si2}) - si3 := newSectorOnChainInfo(3, tutils.MakeCID("3", &miner.SealedCIDPrefix), big.NewInt(3), abi.ChainEpoch(3), abi.ChainEpoch(12)) + si3 := newSectorOnChainInfo(3, tutils.MakeCID("3", &v0miner.SealedCIDPrefix), big.NewInt(3), abi.ChainEpoch(3), abi.ChainEpoch(12)) // 0 delete // 1 extend // 2 same @@ -545,20 +547,20 @@ func createMinerState(ctx context.Context, t *testing.T, store adt.Store, owner, return stateC } -func createEmptyMinerState(ctx context.Context, t *testing.T, store adt.Store, owner, worker address.Address) *miner.State { +func createEmptyMinerState(ctx context.Context, t *testing.T, store adt.Store, owner, worker address.Address) *v0miner.State { emptyArrayCid, err := adt.MakeEmptyArray(store).Root() require.NoError(t, err) emptyMap, err := adt.MakeEmptyMap(store).Root() require.NoError(t, err) - emptyDeadline, err := store.Put(store.Context(), miner.ConstructDeadline(emptyArrayCid)) + emptyDeadline, err := store.Put(store.Context(), v0miner.ConstructDeadline(emptyArrayCid)) require.NoError(t, err) - emptyVestingFunds := miner.ConstructVestingFunds() + emptyVestingFunds := v0miner.ConstructVestingFunds() emptyVestingFundsCid, err := store.Put(store.Context(), emptyVestingFunds) require.NoError(t, err) - emptyDeadlines := miner.ConstructDeadlines(emptyDeadline) + emptyDeadlines := v0miner.ConstructDeadlines(emptyDeadline) emptyDeadlinesCid, err := store.Put(store.Context(), emptyDeadlines) require.NoError(t, err) @@ -568,7 +570,7 @@ func createEmptyMinerState(ctx context.Context, t *testing.T, store adt.Store, o emptyBitfieldCid, err := store.Put(store.Context(), emptyBitfield) require.NoError(t, err) - state, err := miner.ConstructState(minerInfo, 123, emptyBitfieldCid, emptyArrayCid, emptyMap, emptyDeadlinesCid, emptyVestingFundsCid) + state, err := v0miner.ConstructState(minerInfo, 123, emptyBitfieldCid, emptyArrayCid, emptyMap, emptyDeadlinesCid, emptyVestingFundsCid) require.NoError(t, err) return state diff --git a/chain/gen/gen.go b/chain/gen/gen.go index d661411fe..4cae19082 100644 --- a/chain/gen/gen.go +++ b/chain/gen/gen.go @@ -14,7 +14,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" - saminer "github.com/filecoin-project/specs-actors/actors/builtin/miner" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" block "github.com/ipfs/go-block-format" "github.com/ipfs/go-blockservice" "github.com/ipfs/go-cid" @@ -121,7 +121,7 @@ var DefaultRemainderAccountActor = genesis.Actor{ } func NewGeneratorWithSectors(numSectors int) (*ChainGen, error) { - saminer.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ + v0miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } diff --git a/chain/gen/gen_test.go b/chain/gen/gen_test.go index fd6bceb95..496bb016b 100644 --- a/chain/gen/gen_test.go +++ b/chain/gen/gen_test.go @@ -5,7 +5,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" @@ -14,7 +14,7 @@ import ( ) func init() { - miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ + v0miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } v0power.ConsensusMinerMinPower = big.NewInt(2048) diff --git a/chain/gen/genesis/miners.go b/chain/gen/genesis/miners.go index 88fe57189..f6256ffbc 100644 --- a/chain/gen/genesis/miners.go +++ b/chain/gen/genesis/miners.go @@ -6,6 +6,8 @@ import ( "fmt" "math/rand" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + "github.com/ipfs/go-cid" cbor "github.com/ipfs/go-ipld-cbor" cbg "github.com/whyrusleeping/cbor-gen" @@ -18,7 +20,7 @@ import ( "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin/market" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/builtin/reward" "github.com/filecoin-project/specs-actors/actors/runtime" @@ -123,9 +125,10 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid } minerInfos[i].maddr = ma.IDAddress - err = vm.MutateState(ctx, minerInfos[i].maddr, func(cst cbor.IpldStore, st *miner.State) error { - maxPeriods := miner.MaxSectorExpirationExtension / miner.WPoStProvingPeriod - minerInfos[i].presealExp = (maxPeriods-1)*miner.WPoStProvingPeriod + st.ProvingPeriodStart - 1 + // TODO: ActorUpgrade + err = vm.MutateState(ctx, minerInfos[i].maddr, func(cst cbor.IpldStore, st *v0miner.State) error { + maxPeriods := v0miner.MaxSectorExpirationExtension / v0miner.WPoStProvingPeriod + minerInfos[i].presealExp = (maxPeriods-1)*v0miner.WPoStProvingPeriod + st.ProvingPeriodStart - 1 return nil }) @@ -201,7 +204,7 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid return cid.Undef, xerrors.Errorf("getting deal weight: %w", err) } - sectorWeight := miner.QAPowerForWeight(m.SectorSize, minerInfos[i].presealExp, dweight.DealWeight, dweight.VerifiedDealWeight) + sectorWeight := v0miner.QAPowerForWeight(m.SectorSize, minerInfos[i].presealExp, dweight.DealWeight, dweight.VerifiedDealWeight) qaPow = types.BigAdd(qaPow, sectorWeight) } @@ -246,7 +249,7 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid return cid.Undef, xerrors.Errorf("getting deal weight: %w", err) } - sectorWeight := miner.QAPowerForWeight(m.SectorSize, minerInfos[i].presealExp, dweight.DealWeight, dweight.VerifiedDealWeight) + sectorWeight := v0miner.QAPowerForWeight(m.SectorSize, minerInfos[i].presealExp, dweight.DealWeight, dweight.VerifiedDealWeight) // we've added fake power for this sector above, remove it now err = vm.MutateState(ctx, builtin.StoragePowerActorAddr, func(cst cbor.IpldStore, st *v0power.State) error { @@ -268,9 +271,9 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid return cid.Undef, xerrors.Errorf("getting current total power: %w", err) } - pcd := miner.PreCommitDepositForPower(epochReward.ThisEpochRewardSmoothed, tpow.QualityAdjPowerSmoothed, sectorWeight) + pcd := v0miner.PreCommitDepositForPower(epochReward.ThisEpochRewardSmoothed, tpow.QualityAdjPowerSmoothed, sectorWeight) - pledge := miner.InitialPledgeForPower( + pledge := v0miner.InitialPledgeForPower( sectorWeight, epochReward.ThisEpochBaselinePower, tpow.PledgeCollateral, diff --git a/chain/store/store_test.go b/chain/store/store_test.go index 8662f10ef..7da8d219d 100644 --- a/chain/store/store_test.go +++ b/chain/store/store_test.go @@ -10,7 +10,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" @@ -22,7 +22,7 @@ import ( ) func init() { - miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ + v0miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } v0power.ConsensusMinerMinPower = big.NewInt(2048) diff --git a/chain/sync_test.go b/chain/sync_test.go index 5f972ecc6..e8df32c56 100644 --- a/chain/sync_test.go +++ b/chain/sync_test.go @@ -20,7 +20,7 @@ import ( "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/specs-actors/actors/builtin/miner" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" @@ -43,7 +43,7 @@ func init() { if err != nil { panic(err) } - miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ + v0miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } v0power.ConsensusMinerMinPower = big.NewInt(2048) diff --git a/chain/vm/invoker.go b/chain/vm/invoker.go index 56e3bea84..5024164a7 100644 --- a/chain/vm/invoker.go +++ b/chain/vm/invoker.go @@ -20,7 +20,7 @@ import ( "github.com/filecoin-project/specs-actors/actors/builtin/cron" init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" "github.com/filecoin-project/specs-actors/actors/builtin/market" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/specs-actors/actors/builtin/multisig" "github.com/filecoin-project/specs-actors/actors/builtin/paych" v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" @@ -52,7 +52,7 @@ func NewInvoker() *Invoker { inv.Register(builtin.CronActorCodeID, cron.Actor{}, cron.State{}) inv.Register(builtin.StoragePowerActorCodeID, v0power.Actor{}, v0power.State{}) inv.Register(builtin.StorageMarketActorCodeID, market.Actor{}, market.State{}) - inv.Register(builtin.StorageMinerActorCodeID, miner.Actor{}, miner.State{}) + inv.Register(builtin.StorageMinerActorCodeID, v0miner.Actor{}, v0miner.State{}) inv.Register(builtin.MultisigActorCodeID, multisig.Actor{}, multisig.State{}) inv.Register(builtin.PaymentChannelActorCodeID, paych.Actor{}, paych.State{}) inv.Register(builtin.VerifiedRegistryActorCodeID, verifreg.Actor{}, verifreg.State{}) diff --git a/chain/vm/syscalls.go b/chain/vm/syscalls.go index 3e221f61f..aab1812d9 100644 --- a/chain/vm/syscalls.go +++ b/chain/vm/syscalls.go @@ -7,6 +7,8 @@ import ( goruntime "runtime" "sync" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + "github.com/filecoin-project/specs-actors/actors/runtime/proof" "github.com/filecoin-project/go-address" @@ -21,9 +23,7 @@ import ( "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/lib/sigs" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/specs-actors/actors/runtime" - "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" ) @@ -197,7 +197,7 @@ func (ss *syscallShim) VerifyBlockSig(blk *types.BlockHeader) error { return err } - info, err := mas.GetInfo(adt.WrapStore(ss.ctx, ss.cst)) + info, err := mas.Info() if err != nil { return err } diff --git a/cli/paych_test.go b/cli/paych_test.go index c1e52899b..1cf95ef6c 100644 --- a/cli/paych_test.go +++ b/cli/paych_test.go @@ -15,7 +15,7 @@ import ( "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/go-state-types/big" - saminer "github.com/filecoin-project/specs-actors/actors/builtin/miner" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" @@ -41,7 +41,7 @@ import ( func init() { v0power.ConsensusMinerMinPower = big.NewInt(2048) - saminer.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ + v0miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } verifreg.MinVerifiedDealSize = big.NewInt(256) diff --git a/cmd/lotus-pcr/main.go b/cmd/lotus-pcr/main.go index dc12693ca..d265bdd49 100644 --- a/cmd/lotus-pcr/main.go +++ b/cmd/lotus-pcr/main.go @@ -12,6 +12,11 @@ import ( "strconv" "time" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + + "github.com/filecoin-project/go-state-types/network" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + "github.com/ipfs/go-cid" logging "github.com/ipfs/go-log/v2" @@ -24,7 +29,6 @@ import ( "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/exitcode" "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/go-address" "github.com/filecoin-project/lotus/api" @@ -321,6 +325,7 @@ type refunderNodeApi interface { StateMinerInitialPledgeCollateral(ctx context.Context, addr address.Address, precommitInfo miner.SectorPreCommitInfo, tsk types.TipSetKey) (types.BigInt, error) StateSectorPreCommitInfo(ctx context.Context, addr address.Address, sector abi.SectorNumber, tsk types.TipSetKey) (miner.SectorPreCommitOnChainInfo, error) StateGetActor(ctx context.Context, actor address.Address, tsk types.TipSetKey) (*types.Actor, error) + StateNetworkVersion(ctx context.Context, tsk types.TipSetKey) (network.Version, error) MpoolPushMessage(ctx context.Context, msg *types.Message, spec *api.MessageSendSpec) (*types.SignedMessage, error) GasEstimateGasPremium(ctx context.Context, nblocksincl uint64, sender address.Address, gaslimit int64, tsk types.TipSetKey) (types.BigInt, error) WalletBalance(ctx context.Context, addr address.Address) (types.BigInt, error) @@ -389,14 +394,28 @@ func (r *refunder) ProcessTipset(ctx context.Context, tipset *types.TipSet, refu continue } - var proveCommitSector miner.ProveCommitSectorParams - if err := proveCommitSector.UnmarshalCBOR(bytes.NewBuffer(m.Params)); err != nil { - log.Warnw("failed to decode provecommit params", "err", err, "method", messageMethod, "cid", msg.Cid, "miner", m.To) + var sn abi.SectorNumber + + nv, err := r.api.StateNetworkVersion(ctx, tipset.Key()) + if err != nil { + log.Warnw("failed to get network version") continue } + if nv < build.ActorUpgradeNetworkVersion { + var proveCommitSector v0miner.ProveCommitSectorParams + if err := proveCommitSector.UnmarshalCBOR(bytes.NewBuffer(m.Params)); err != nil { + log.Warnw("failed to decode provecommit params", "err", err, "method", messageMethod, "cid", msg.Cid, "miner", m.To) + continue + } + + sn = proveCommitSector.SectorNumber + } else { + // TODO: ActorUpgrade + } + // We use the parent tipset key because precommit information is removed when ProveCommitSector is executed - precommitChainInfo, err := r.api.StateSectorPreCommitInfo(ctx, m.To, proveCommitSector.SectorNumber, tipset.Parents()) + precommitChainInfo, err := r.api.StateSectorPreCommitInfo(ctx, m.To, sn, tipset.Parents()) if err != nil { log.Warnw("failed to get precommit info for sector", "err", err, "method", messageMethod, "cid", msg.Cid, "miner", m.To, "sector_number", proveCommitSector.SectorNumber) continue diff --git a/extern/storage-sealing/checks.go b/extern/storage-sealing/checks.go index 074c4cfcf..ae5ce0d33 100644 --- a/extern/storage-sealing/checks.go +++ b/extern/storage-sealing/checks.go @@ -4,6 +4,9 @@ import ( "bytes" "context" + "github.com/filecoin-project/lotus/build" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + v0proof "github.com/filecoin-project/specs-actors/actors/runtime/proof" "golang.org/x/xerrors" @@ -13,7 +16,6 @@ import ( "github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" "github.com/filecoin-project/lotus/extern/sector-storage/zerocomm" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" ) // TODO: For now we handle this by halting state execution, when we get jsonrpc reconnecting @@ -93,7 +95,19 @@ func checkPrecommit(ctx context.Context, maddr address.Address, si SectorInfo, t return &ErrBadCommD{xerrors.Errorf("on chain CommD differs from sector: %s != %s", commD, si.CommD)} } - if height-(si.TicketEpoch+SealRandomnessLookback) > SealRandomnessLookbackLimit(si.SectorType) { + nv, err := api.StateNetworkVersion(ctx, tok) + if err != nil { + return &ErrApi{xerrors.Errorf("calling StateNetworkVersion: %w", err)} + } + + var msd abi.ChainEpoch + if nv < build.ActorUpgradeNetworkVersion { + msd = v0miner.MaxSealDuration[si.SectorType] + } else { + // TODO: ActorUpgrade + } + + if height-(si.TicketEpoch+SealRandomnessLookback) > msd { return &ErrExpiredTicket{xerrors.Errorf("ticket expired: seal height: %d, head: %d", si.TicketEpoch+SealRandomnessLookback, height)} } @@ -139,8 +153,13 @@ func (m *Sealing) checkCommit(ctx context.Context, si SectorInfo, proof []byte, return &ErrNoPrecommit{xerrors.Errorf("precommit info not found on-chain")} } - if pci.PreCommitEpoch+miner.PreCommitChallengeDelay != si.SeedEpoch { - return &ErrBadSeed{xerrors.Errorf("seed epoch doesn't match on chain info: %d != %d", pci.PreCommitEpoch+miner.PreCommitChallengeDelay, si.SeedEpoch)} + pccd, err := m.getPreCommitChallengeDelay(ctx, tok) + if err != nil { + return xerrors.Errorf("failed to get precommit challenge delay: %w", err) + } + + if pci.PreCommitEpoch+pccd != si.SeedEpoch { + return &ErrBadSeed{xerrors.Errorf("seed epoch doesn't match on chain info: %d != %d", pci.PreCommitEpoch+pccd, si.SeedEpoch)} } buf := new(bytes.Buffer) diff --git a/extern/storage-sealing/constants.go b/extern/storage-sealing/constants.go index ebb3d3347..06c48fa4c 100644 --- a/extern/storage-sealing/constants.go +++ b/extern/storage-sealing/constants.go @@ -1,17 +1,11 @@ package sealing import ( - "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" ) // Epochs -const SealRandomnessLookback = miner.ChainFinality - -// Epochs -func SealRandomnessLookbackLimit(spt abi.RegisteredSealProof) abi.ChainEpoch { - return miner.MaxSealDuration[spt] -} +const SealRandomnessLookback = v0miner.ChainFinality // Epochs const InteractivePoRepConfidence = 6 diff --git a/extern/storage-sealing/fsm_events.go b/extern/storage-sealing/fsm_events.go index ee95ab1c7..3e597d761 100644 --- a/extern/storage-sealing/fsm_events.go +++ b/extern/storage-sealing/fsm_events.go @@ -1,12 +1,12 @@ package sealing import ( + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/ipfs/go-cid" "golang.org/x/xerrors" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/specs-storage/storage" ) diff --git a/extern/storage-sealing/precommit_policy.go b/extern/storage-sealing/precommit_policy.go index 93a963535..e36b8251a 100644 --- a/extern/storage-sealing/precommit_policy.go +++ b/extern/storage-sealing/precommit_policy.go @@ -3,8 +3,11 @@ package sealing import ( "context" + "github.com/filecoin-project/go-state-types/network" + "github.com/filecoin-project/lotus/build" + "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" ) type PreCommitPolicy interface { @@ -13,6 +16,7 @@ type PreCommitPolicy interface { type Chain interface { ChainHead(ctx context.Context) (TipSetToken, abi.ChainEpoch, error) + StateNetworkVersion(ctx context.Context, tok TipSetToken) (network.Version, error) } // BasicPreCommitPolicy satisfies PreCommitPolicy. It has two modes: @@ -48,9 +52,9 @@ func NewBasicPreCommitPolicy(api Chain, duration abi.ChainEpoch, provingBoundary // Expiration produces the pre-commit sector expiration epoch for an encoded // replica containing the provided enumeration of pieces and deals. func (p *BasicPreCommitPolicy) Expiration(ctx context.Context, ps ...Piece) (abi.ChainEpoch, error) { - _, epoch, err := p.api.ChainHead(ctx) + tok, epoch, err := p.api.ChainHead(ctx) if err != nil { - return 0, nil + return 0, err } var end *abi.ChainEpoch @@ -76,7 +80,19 @@ func (p *BasicPreCommitPolicy) Expiration(ctx context.Context, ps ...Piece) (abi end = &tmp } - *end += miner.WPoStProvingPeriod - (*end % miner.WPoStProvingPeriod) + p.provingBoundary - 1 + nv, err := p.api.StateNetworkVersion(ctx, tok) + if err != nil { + return 0, err + } + + var wpp abi.ChainEpoch + if nv < build.ActorUpgradeNetworkVersion { + wpp = v0miner.WPoStProvingPeriod + } else { + // TODO: ActorUpgrade + } + + *end += wpp - (*end % wpp) + p.provingBoundary - 1 return *end, nil } diff --git a/extern/storage-sealing/sealing.go b/extern/storage-sealing/sealing.go index 533333860..0fe754217 100644 --- a/extern/storage-sealing/sealing.go +++ b/extern/storage-sealing/sealing.go @@ -8,6 +8,10 @@ import ( "sync" "time" + "github.com/filecoin-project/lotus/build" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + + "github.com/filecoin-project/go-state-types/network" "github.com/ipfs/go-cid" "github.com/ipfs/go-datastore" "github.com/ipfs/go-datastore/namespace" @@ -20,10 +24,10 @@ import ( "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" statemachine "github.com/filecoin-project/go-statemachine" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" sectorstorage "github.com/filecoin-project/lotus/extern/sector-storage" "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" "github.com/filecoin-project/specs-actors/actors/builtin/market" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" ) const SectorStorePrefix = "/sectors" @@ -53,6 +57,7 @@ type SealingAPI interface { StateMinerPreCommitDepositForPower(context.Context, address.Address, miner.SectorPreCommitInfo, TipSetToken) (big.Int, error) StateMinerInitialPledgeCollateral(context.Context, address.Address, miner.SectorPreCommitInfo, TipSetToken) (big.Int, error) StateMarketStorageDeal(context.Context, abi.DealID, TipSetToken) (market.DealProposal, error) + StateNetworkVersion(ctx context.Context, tok TipSetToken) (network.Version, error) SendMsg(ctx context.Context, from, to address.Address, method abi.MethodNum, value, maxFee abi.TokenAmount, params []byte) (cid.Cid, error) ChainHead(ctx context.Context) (TipSetToken, abi.ChainEpoch, error) ChainGetRandomnessFromBeacon(ctx context.Context, tok TipSetToken, personalization crypto.DomainSeparationTag, randEpoch abi.ChainEpoch, entropy []byte) (abi.Randomness, error) @@ -417,3 +422,18 @@ func getDealPerSectorLimit(size abi.SectorSize) uint64 { } return 512 } + +func (m *Sealing) getPreCommitChallengeDelay(ctx context.Context, tok TipSetToken) (abi.ChainEpoch, error) { + nv, err := m.api.StateNetworkVersion(ctx, tok) + if err != nil { + return -1, xerrors.Errorf("failed to get network version: %w", err) + } + + if nv < build.ActorUpgradeNetworkVersion { + return v0miner.PreCommitChallengeDelay, nil + } else { + // TODO: ActorUpgrade + return -1, nil + } + +} diff --git a/extern/storage-sealing/states_failed.go b/extern/storage-sealing/states_failed.go index 4dd945a81..b026e70f9 100644 --- a/extern/storage-sealing/states_failed.go +++ b/extern/storage-sealing/states_failed.go @@ -4,13 +4,14 @@ import ( "bytes" "time" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + "golang.org/x/xerrors" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/exitcode" "github.com/filecoin-project/go-statemachine" "github.com/filecoin-project/specs-actors/actors/builtin/market" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/lotus/extern/sector-storage/zerocomm" ) diff --git a/extern/storage-sealing/states_sealing.go b/extern/storage-sealing/states_sealing.go index 5e2b72ee1..e7a3d7450 100644 --- a/extern/storage-sealing/states_sealing.go +++ b/extern/storage-sealing/states_sealing.go @@ -4,6 +4,10 @@ import ( "bytes" "context" + "github.com/filecoin-project/lotus/build" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + "golang.org/x/xerrors" "github.com/filecoin-project/go-state-types/abi" @@ -12,7 +16,6 @@ import ( "github.com/filecoin-project/go-state-types/exitcode" "github.com/filecoin-project/go-statemachine" "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/specs-storage/storage" ) @@ -180,7 +183,21 @@ func (m *Sealing) handlePreCommitting(ctx statemachine.Context, sector SectorInf // Sectors must last _at least_ MinSectorExpiration + MaxSealDuration. // TODO: The "+10" allows the pre-commit to take 10 blocks to be accepted. - if minExpiration := height + miner.MaxSealDuration[sector.SectorType] + miner.MinSectorExpiration + 10; expiration < minExpiration { + nv, err := m.api.StateNetworkVersion(ctx.Context(), tok) + if err != nil { + return ctx.Send(SectorSealPreCommit1Failed{xerrors.Errorf("failed to get network version: %w", err)}) + } + + var msd abi.ChainEpoch + var mse abi.ChainEpoch + if nv < build.ActorUpgradeNetworkVersion { + msd = v0miner.MaxSealDuration[sector.SectorType] + mse = v0miner.MinSectorExpiration + } else { + // TODO: ActorUpgrade + } + + if minExpiration := height + msd + mse + 10; expiration < minExpiration { expiration = minExpiration } // TODO: enforce a reasonable _maximum_ sector lifetime? @@ -253,7 +270,7 @@ func (m *Sealing) handlePreCommitWait(ctx statemachine.Context, sector SectorInf func (m *Sealing) handleWaitSeed(ctx statemachine.Context, sector SectorInfo) error { tok, _, err := m.api.ChainHead(ctx.Context()) if err != nil { - log.Errorf("handleCommitting: api error, not proceeding: %+v", err) + log.Errorf("handleWaitSeed: api error, not proceeding: %+v", err) return nil } @@ -265,7 +282,17 @@ func (m *Sealing) handleWaitSeed(ctx statemachine.Context, sector SectorInfo) er return ctx.Send(SectorChainPreCommitFailed{error: xerrors.Errorf("precommit info not found on chain")}) } - randHeight := pci.PreCommitEpoch + miner.PreCommitChallengeDelay + nv, err := m.api.StateNetworkVersion(ctx.Context(), tok) + if err != nil { + return ctx.Send(SectorChainPreCommitFailed{xerrors.Errorf("failed to get network version: %w", err)}) + } + + pccd, err := m.getPreCommitChallengeDelay(ctx.Context(), tok) + if err != nil { + return ctx.Send(SectorChainPreCommitFailed{xerrors.Errorf("failed to get precommit challenge delay: %w", err)}) + } + + randHeight := pci.PreCommitEpoch + pccd err = m.events.ChainAt(func(ectx context.Context, _ TipSetToken, curH abi.ChainEpoch) error { // in case of null blocks the randomness can land after the tipset we @@ -356,14 +383,23 @@ func (m *Sealing) handleSubmitCommit(ctx statemachine.Context, sector SectorInfo return ctx.Send(SectorCommitFailed{xerrors.Errorf("commit check error: %w", err)}) } - params := &miner.ProveCommitSectorParams{ - SectorNumber: sector.SectorNumber, - Proof: sector.Proof, + nv, err := m.api.StateNetworkVersion(ctx.Context(), tok) + if err != nil { + return ctx.Send(SectorCommitFailed{xerrors.Errorf("failed to get network version: %w", err)}) } enc := new(bytes.Buffer) - if err := params.MarshalCBOR(enc); err != nil { - return ctx.Send(SectorCommitFailed{xerrors.Errorf("could not serialize commit sector parameters: %w", err)}) + if nv < build.ActorUpgradeNetworkVersion { + params := &v0miner.ProveCommitSectorParams{ + SectorNumber: sector.SectorNumber, + Proof: sector.Proof, + } + + if err := params.MarshalCBOR(enc); err != nil { + return ctx.Send(SectorCommitFailed{xerrors.Errorf("could not serialize commit sector parameters: %w", err)}) + } + } else { + // TODO: ActorUpgrade } waddr, err := m.api.StateMinerWorkerAddress(ctx.Context(), m.maddr, tok) diff --git a/extern/storage-sealing/upgrade_queue.go b/extern/storage-sealing/upgrade_queue.go index 650fdc83d..371a5c862 100644 --- a/extern/storage-sealing/upgrade_queue.go +++ b/extern/storage-sealing/upgrade_queue.go @@ -3,11 +3,12 @@ package sealing import ( "context" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + "golang.org/x/xerrors" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" ) func (m *Sealing) IsMarkedForUpgrade(id abi.SectorNumber) bool { diff --git a/markets/storageadapter/client.go b/markets/storageadapter/client.go index 4168792da..0c9e66eda 100644 --- a/markets/storageadapter/client.go +++ b/markets/storageadapter/client.go @@ -6,6 +6,8 @@ import ( "bytes" "context" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + "github.com/filecoin-project/go-state-types/big" "golang.org/x/xerrors" @@ -29,7 +31,6 @@ import ( "github.com/filecoin-project/lotus/node/impl/full" "github.com/filecoin-project/specs-actors/actors/builtin" samarket "github.com/filecoin-project/specs-actors/actors/builtin/market" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/ipfs/go-cid" ) diff --git a/markets/storageadapter/provider.go b/markets/storageadapter/provider.go index 7af1808c1..22d6c1e1d 100644 --- a/markets/storageadapter/provider.go +++ b/markets/storageadapter/provider.go @@ -8,6 +8,8 @@ import ( "io" "time" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + "github.com/ipfs/go-cid" logging "github.com/ipfs/go-log/v2" "golang.org/x/xerrors" @@ -20,7 +22,6 @@ import ( "github.com/filecoin-project/go-state-types/exitcode" "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin/market" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/lotus/api" diff --git a/node/impl/client/client.go b/node/impl/client/client.go index 7a107c2fd..6c60269ab 100644 --- a/node/impl/client/client.go +++ b/node/impl/client/client.go @@ -41,7 +41,7 @@ import ( "github.com/filecoin-project/go-multistore" "github.com/filecoin-project/go-padreader" "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" marketevents "github.com/filecoin-project/lotus/markets/loggers" @@ -87,7 +87,7 @@ func calcDealExpiration(minDuration uint64, md *dline.Info, startEpoch abi.Chain minExp := startEpoch + abi.ChainEpoch(minDuration) // Align on miners ProvingPeriodBoundary - return minExp + miner.WPoStProvingPeriod - (minExp % miner.WPoStProvingPeriod) + (md.PeriodStart % miner.WPoStProvingPeriod) - 1 + return minExp + v0miner.WPoStProvingPeriod - (minExp % v0miner.WPoStProvingPeriod) + (md.PeriodStart % v0miner.WPoStProvingPeriod) - 1 } func (a *API) imgr() *importmgr.Mgr { diff --git a/node/node_test.go b/node/node_test.go index 0611bca60..92b741f73 100644 --- a/node/node_test.go +++ b/node/node_test.go @@ -10,7 +10,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/lotus/lib/lotuslog" - saminer "github.com/filecoin-project/specs-actors/actors/builtin/miner" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" logging "github.com/ipfs/go-log/v2" @@ -22,7 +22,7 @@ func init() { _ = logging.SetLogLevel("*", "INFO") v0power.ConsensusMinerMinPower = big.NewInt(2048) - saminer.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ + v0miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } verifreg.MinVerifiedDealSize = big.NewInt(256) @@ -68,7 +68,7 @@ func TestAPIDealFlowReal(t *testing.T) { logging.SetLogLevel("sub", "ERROR") logging.SetLogLevel("storageminer", "ERROR") - saminer.PreCommitChallengeDelay = 5 + v0miner.PreCommitChallengeDelay = 5 t.Run("basic", func(t *testing.T) { test.TestDealFlow(t, builder.Builder, time.Second, false, false) diff --git a/node/test/builder.go b/node/test/builder.go index de2071e7a..2b26c13fc 100644 --- a/node/test/builder.go +++ b/node/test/builder.go @@ -37,7 +37,7 @@ import ( "github.com/filecoin-project/lotus/node/repo" "github.com/filecoin-project/lotus/storage/mockstorage" "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/ipfs/go-datastore" "github.com/libp2p/go-libp2p-core/crypto" "github.com/libp2p/go-libp2p-core/peer" @@ -83,7 +83,7 @@ func CreateTestStorageNode(ctx context.Context, t *testing.T, waddr address.Addr peerid, err := peer.IDFromPrivateKey(pk) require.NoError(t, err) - enc, err := actors.SerializeParams(&miner.ChangePeerIDParams{NewID: abi.PeerID(peerid)}) + enc, err := actors.SerializeParams(&v0miner.ChangePeerIDParams{NewID: abi.PeerID(peerid)}) require.NoError(t, err) msg := &types.Message{ diff --git a/storage/adapter_storage_miner.go b/storage/adapter_storage_miner.go index ef917b758..8b64789ad 100644 --- a/storage/adapter_storage_miner.go +++ b/storage/adapter_storage_miner.go @@ -4,7 +4,7 @@ import ( "bytes" "context" - "github.com/filecoin-project/go-bitfield" + "github.com/filecoin-project/go-state-types/network" "github.com/ipfs/go-cid" cbg "github.com/whyrusleeping/cbor-gen" @@ -16,7 +16,6 @@ import ( "github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin/market" - "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/api/apibstore" @@ -84,7 +83,7 @@ func (s SealingAPIAdapter) StateMinerWorkerAddress(ctx context.Context, maddr ad return mi.Worker, nil } -func (s SealingAPIAdapter) StateMinerDeadlines(ctx context.Context, maddr address.Address, tok sealing.TipSetToken) ([]*miner.Deadline, error) { +func (s SealingAPIAdapter) StateMinerDeadlines(ctx context.Context, maddr address.Address, tok sealing.TipSetToken) ([]miner.Deadline, error) { tsk, err := types.TipSetKeyFromBytes(tok) if err != nil { return nil, xerrors.Errorf("failed to unmarshal TipSetToken to TipSetKey: %w", err) @@ -185,23 +184,13 @@ func (s SealingAPIAdapter) StateSectorPreCommitInfo(ctx context.Context, maddr a if err != nil { return nil, xerrors.Errorf("handleSealFailed(%d): temp error: loading miner state: %+v", sectorNumber, err) } - stor := store.ActorStore(ctx, apibstore.NewAPIBlockstore(s.delegate)) - precommits, err := adt.AsMap(stor, state.PreCommittedSectors) - if err != nil { - return nil, err - } - var pci miner.SectorPreCommitOnChainInfo - ok, err := precommits.Get(abi.UIntKey(uint64(sectorNumber)), &pci) + pci, err := state.GetPrecommittedSector(sectorNumber) if err != nil { return nil, err } - if !ok { - var allocated bitfield.BitField - if err := stor.Get(ctx, state.AllocatedSectors, &allocated); err != nil { - return nil, xerrors.Errorf("loading allocated sector bitfield: %w", err) - } - set, err := allocated.IsSet(uint64(sectorNumber)) + if pci != nil { + set, err := state.IsAllocated(sectorNumber) if err != nil { return nil, xerrors.Errorf("checking if sector is allocated: %w", err) } @@ -212,7 +201,7 @@ func (s SealingAPIAdapter) StateSectorPreCommitInfo(ctx context.Context, maddr a return nil, nil } - return &pci, nil + return pci, nil } func (s SealingAPIAdapter) StateSectorGetInfo(ctx context.Context, maddr address.Address, sectorNumber abi.SectorNumber, tok sealing.TipSetToken) (*miner.SectorOnChainInfo, error) { @@ -258,6 +247,15 @@ func (s SealingAPIAdapter) StateMarketStorageDeal(ctx context.Context, dealID ab return deal.Proposal, nil } +func (s SealingAPIAdapter) StateNetworkVersion(ctx context.Context, tok sealing.TipSetToken) (network.Version, error) { + tsk, err := types.TipSetKeyFromBytes(tok) + if err != nil { + return -1, err + } + + return s.delegate.StateNetworkVersion(ctx, tsk) +} + func (s SealingAPIAdapter) SendMsg(ctx context.Context, from, to address.Address, method abi.MethodNum, value, maxFee abi.TokenAmount, params []byte) (cid.Cid, error) { msg := types.Message{ To: to, diff --git a/storage/miner.go b/storage/miner.go index 3485dba03..693ad7c05 100644 --- a/storage/miner.go +++ b/storage/miner.go @@ -5,6 +5,10 @@ import ( "errors" "time" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + + "github.com/filecoin-project/go-state-types/network" + "github.com/filecoin-project/go-state-types/dline" "github.com/filecoin-project/go-bitfield" @@ -71,7 +75,8 @@ type storageMinerApi interface { StateSectorPreCommitInfo(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (miner.SectorPreCommitOnChainInfo, error) StateSectorGetInfo(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (*miner.SectorOnChainInfo, error) StateSectorPartition(ctx context.Context, maddr address.Address, sectorNumber abi.SectorNumber, tok types.TipSetKey) (*miner.SectorLocation, error) - StateMinerInfo(context.Context, address.Address, types.TipSetKey) (api.MinerInfo, error) + StateMinerInfo(context.Context, address.Address, types.TipSetKey) (miner.MinerInfo, error) + StateMinerDeadlines(context.Context, address.Address, types.TipSetKey) ([]miner.Deadline, error) StateMinerProvingDeadline(context.Context, address.Address, types.TipSetKey) (*dline.Info, error) StateMinerPreCommitDepositForPower(context.Context, address.Address, miner.SectorPreCommitInfo, types.TipSetKey) (types.BigInt, error) StateMinerInitialPledgeCollateral(context.Context, address.Address, miner.SectorPreCommitInfo, types.TipSetKey) (types.BigInt, error) @@ -83,6 +88,7 @@ type storageMinerApi interface { StateMinerFaults(context.Context, address.Address, types.TipSetKey) (bitfield.BitField, error) StateMinerRecoveries(context.Context, address.Address, types.TipSetKey) (bitfield.BitField, error) StateAccountKey(context.Context, address.Address, types.TipSetKey) (address.Address, error) + StateNetworkVersion(context.Context, types.TipSetKey) (network.Version, error) MpoolPushMessage(context.Context, *types.Message, *api.MessageSendSpec) (*types.SignedMessage, error) @@ -139,7 +145,8 @@ func (m *Miner) Run(ctx context.Context) error { evts := events.NewEvents(ctx, m.api) adaptedAPI := NewSealingAPIAdapter(m.api) - pcp := sealing.NewBasicPreCommitPolicy(adaptedAPI, miner.MaxSectorExpirationExtension-(miner.WPoStProvingPeriod*2), md.PeriodStart%miner.WPoStProvingPeriod) + // TODO: Maybe we update this policy after actor upgrades? + pcp := sealing.NewBasicPreCommitPolicy(adaptedAPI, v0miner.MaxSectorExpirationExtension-(v0miner.WPoStProvingPeriod*2), md.PeriodStart%v0miner.WPoStProvingPeriod) m.sealing = sealing.New(adaptedAPI, fc, NewEventsAdapter(evts), m.maddr, m.ds, m.sealer, m.sc, m.verif, &pcp, sealing.GetSealingConfigFunc(m.getSealConfig), m.handleSealingNotifications) go m.sealing.Run(ctx) //nolint:errcheck // logged intside the function diff --git a/storage/wdpost_journal.go b/storage/wdpost_journal.go index c1a4d4817..48eb2f2b1 100644 --- a/storage/wdpost_journal.go +++ b/storage/wdpost_journal.go @@ -3,7 +3,7 @@ package storage import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/dline" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/ipfs/go-cid" ) diff --git a/storage/wdpost_run.go b/storage/wdpost_run.go index aa2706455..bfc2bc95e 100644 --- a/storage/wdpost_run.go +++ b/storage/wdpost_run.go @@ -14,20 +14,18 @@ import ( "github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/go-state-types/dline" "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/ipfs/go-cid" "go.opencensus.io/trace" "golang.org/x/xerrors" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/specs-actors/actors/runtime/proof" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/api/apibstore" "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/actors" - iminer "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/store" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/journal" @@ -155,7 +153,7 @@ func (s *WindowPoStScheduler) checkSectors(ctx context.Context, check bitfield.B return sbf, nil } -func (s *WindowPoStScheduler) checkNextRecoveries(ctx context.Context, dlIdx uint64, partitions []iminer.Partition) ([]miner.RecoveryDeclaration, *types.SignedMessage, error) { +func (s *WindowPoStScheduler) checkNextRecoveries(ctx context.Context, dlIdx uint64, partitions []miner.Partition) ([]miner.RecoveryDeclaration, *types.SignedMessage, error) { ctx, span := trace.StartSpan(ctx, "storage.checkNextRecoveries") defer span.End() @@ -167,11 +165,11 @@ func (s *WindowPoStScheduler) checkNextRecoveries(ctx context.Context, dlIdx uin for partIdx, partition := range partitions { faults, err := partition.FaultySectors() if err != nil { - return xerrors.Errorf("getting faults: %w", err) + return nil, nil, xerrors.Errorf("getting faults: %w", err) } recovering, err := partition.RecoveringSectors() if err != nil { - return xerrors.Errorf("getting recovering: %w", err) + return nil, nil, xerrors.Errorf("getting recovering: %w", err) } unrecovered, err := bitfield.SubtractBitField(faults, recovering) if err != nil { @@ -254,7 +252,7 @@ func (s *WindowPoStScheduler) checkNextRecoveries(ctx context.Context, dlIdx uin return recoveries, sm, nil } -func (s *WindowPoStScheduler) checkNextFaults(ctx context.Context, dlIdx uint64, partitions []iminer.Partition) ([]miner.FaultDeclaration, *types.SignedMessage, error) { +func (s *WindowPoStScheduler) checkNextFaults(ctx context.Context, dlIdx uint64, partitions []miner.Partition) ([]miner.FaultDeclaration, *types.SignedMessage, error) { ctx, span := trace.StartSpan(ctx, "storage.checkNextFaults") defer span.End() @@ -348,7 +346,7 @@ func (s *WindowPoStScheduler) runPost(ctx context.Context, di dline.Info, ts *ty return nil, xerrors.Errorf("resolving actor: %w", err) } - mas, err := iminer.Load(stor, act) + mas, err := miner.Load(stor, act) if err != nil { return nil, xerrors.Errorf("getting miner state: %w", err) } @@ -365,8 +363,8 @@ func (s *WindowPoStScheduler) runPost(ctx context.Context, di dline.Info, ts *ty log.Errorf("loading deadline: %v", err) return } - var partitions []iminer.Partition - err = dl.ForEachPartition(func(_ uint64, part iminer.Partition) error { + var partitions []miner.Partition + err = dl.ForEachPartition(func(_ uint64, part miner.Partition) error { partitions = append(partitions, part) return nil }) @@ -435,9 +433,9 @@ func (s *WindowPoStScheduler) runPost(ctx context.Context, di dline.Info, ts *ty return nil, xerrors.Errorf("loading deadline: %w", err) } - var partitions []iminer.Partitions - err = dl.ForEachPartition(func(_ uint64, part iminer.Partition) error { - partitions = apppend(partitions, part) + var partitions []miner.Partition + err = dl.ForEachPartition(func(_ uint64, part miner.Partition) error { + partitions = append(partitions, part) return nil }) if err != nil { @@ -465,7 +463,11 @@ func (s *WindowPoStScheduler) runPost(ctx context.Context, di dline.Info, ts *ty return nil, xerrors.Errorf("getting active sectors: %w", err) } - toProve, err = bitfield.MergeBitFields(toProve, partition.Recoveries) + recs, err := partition.RecoveringSectors() + if err != nil { + return nil, xerrors.Errorf("getting recovering sectors: %w", err) + } + toProve, err = bitfield.MergeBitFields(toProve, recs) if err != nil { return nil, xerrors.Errorf("adding recoveries to set of sectors to prove: %w", err) } @@ -492,7 +494,12 @@ func (s *WindowPoStScheduler) runPost(ctx context.Context, di dline.Info, ts *ty skipCount += sc - ssi, err := s.sectorsForProof(ctx, good, partition.Sectors, ts) + partitionSectors, err := partition.AllSectors() + if err != nil { + return nil, xerrors.Errorf("getting partition sectors: %w", err) + } + + ssi, err := s.sectorsForProof(ctx, good, partitionSectors, ts) if err != nil { return nil, xerrors.Errorf("getting sorted sector info: %w", err) } From 9e48dd211ac1e6de6a6be5eef434fea7dd5fc1ef Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Thu, 17 Sep 2020 02:34:15 -0400 Subject: [PATCH 051/303] Fixups --- chain/actors/builtin/miner/miner.go | 2 +- chain/events/state/predicates.go | 8 ++--- chain/stmgr/utils.go | 41 +++++++++++++++++++++--- extern/storage-sealing/states_sealing.go | 5 --- 4 files changed, 42 insertions(+), 14 deletions(-) diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index 90c44eff3..4acb41dae 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -39,7 +39,7 @@ type State interface { GetSectorExpiration(abi.SectorNumber) (*SectorExpiration, error) GetPrecommittedSector(abi.SectorNumber) (*SectorPreCommitOnChainInfo, error) LoadSectorsFromSet(filter *bitfield.BitField, filterOut bool) (adt.Array, error) - LoadPreCommittedSectorsFromSet(filter *bitfield.BitField, filterOut bool) (adt.Map, error) + LoadPreCommittedSectors() (adt.Map, error) IsAllocated(abi.SectorNumber) (bool, error) LoadDeadline(idx uint64) (Deadline, error) diff --git a/chain/events/state/predicates.go b/chain/events/state/predicates.go index 5a885504f..3e515e6a4 100644 --- a/chain/events/state/predicates.go +++ b/chain/events/state/predicates.go @@ -302,7 +302,7 @@ func (sp *StatePredicates) AvailableBalanceChangedForAddresses(getAddrs func() [ } } -type DiffMinerActorStateFunc func(ctx context.Context, oldState *miner.State, newState *miner.State) (changed bool, user UserData, err error) +type DiffMinerActorStateFunc func(ctx context.Context, oldState miner.State, newState miner.State) (changed bool, user UserData, err error) func (sp *StatePredicates) OnInitActorChange(diffInitActorState DiffInitActorStateFunc) DiffTipSetKeyFunc { return sp.OnActorStateChanged(builtin.InitActorAddr, func(ctx context.Context, oldActorState, newActorState *types.Actor) (changed bool, user UserData, err error) { @@ -329,7 +329,7 @@ func (sp *StatePredicates) OnMinerActorChange(minerAddr address.Address, diffMin if err := sp.cst.Get(ctx, newActorState.Head, &newState); err != nil { return false, nil, err } - return diffMinerActorState(ctx, &oldState, &newState) + return diffMinerActorState(ctx, oldState, newState) }) } @@ -389,7 +389,7 @@ func (m *MinerSectorChanges) Remove(key uint64, val *typegen.Deferred) error { } func (sp *StatePredicates) OnMinerSectorChange() DiffMinerActorStateFunc { - return func(ctx context.Context, oldState, newState *miner.State) (changed bool, user UserData, err error) { + return func(ctx context.Context, oldState, newState miner.State) (changed bool, user UserData, err error) { sectorChanges := &MinerSectorChanges{ Added: []miner.SectorOnChainInfo{}, Extended: []SectorExtensions{}, @@ -457,7 +457,7 @@ func (m *MinerPreCommitChanges) Remove(key string, val *typegen.Deferred) error } func (sp *StatePredicates) OnMinerPreCommitChange() DiffMinerActorStateFunc { - return func(ctx context.Context, oldState, newState *miner.State) (changed bool, user UserData, err error) { + return func(ctx context.Context, oldState, newState miner.State) (changed bool, user UserData, err error) { precommitChanges := &MinerPreCommitChanges{ Added: []miner.SectorPreCommitOnChainInfo{}, Removed: []miner.SectorPreCommitOnChainInfo{}, diff --git a/chain/stmgr/utils.go b/chain/stmgr/utils.go index e58d69156..16167af75 100644 --- a/chain/stmgr/utils.go +++ b/chain/stmgr/utils.go @@ -9,6 +9,8 @@ import ( "runtime" "strings" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + saruntime "github.com/filecoin-project/specs-actors/actors/runtime" "github.com/filecoin-project/specs-actors/actors/runtime/proof" @@ -156,7 +158,29 @@ func GetMinerSectorSet(ctx context.Context, sm *StateManager, ts *types.TipSet, return nil, xerrors.Errorf("(get sset) failed to load miner actor state: %w", err) } - return mas.LoadSectorsFromSet(filter, filterOut) + sectors, err := mas.LoadSectorsFromSet(filter, filterOut) + if err != nil { + return nil, xerrors.Errorf("(get sset) failed to load sectors: %w", err) + } + + var sset []*miner.ChainSectorInfo + var v cbg.Deferred + if err := sectors.ForEach(&v, func(i int64) error { + var oci v0miner.SectorOnChainInfo + if err := oci.UnmarshalCBOR(bytes.NewReader(v.Raw)); err != nil { + return err + } + sset = append(sset, &miner.ChainSectorInfo{ + Info: oci, + ID: abi.SectorNumber(i), + }) + + return nil + }); err != nil { + return nil, err + } + + return sset, nil } func GetSectorsForWinningPoSt(ctx context.Context, pv ffiwrapper.Verifier, sm *StateManager, st cid.Cid, maddr address.Address, rand abi.PoStRandomness) ([]proof.SectorInfo, error) { @@ -220,12 +244,21 @@ func GetSectorsForWinningPoSt(ctx context.Context, pv ffiwrapper.Verifier, sm *S out := make([]proof.SectorInfo, len(ids)) for i, n := range ids { - s := sectors[n] + var sinfo miner.SectorOnChainInfo + found, err := sectors.Get(n, &sinfo) + + if err != nil { + return nil, xerrors.Errorf("loading sector info: %w", err) + } + + if !found { + return nil, xerrors.Errorf("didn't find sector info for sector %d", n) + } out[i] = proof.SectorInfo{ SealProof: spt, - SectorNumber: s.ID, - SealedCID: s.Info.SealedCID, + SectorNumber: sinfo.SectorNumber, + SealedCID: sinfo.SealedCID, } } diff --git a/extern/storage-sealing/states_sealing.go b/extern/storage-sealing/states_sealing.go index e7a3d7450..f0ff4025d 100644 --- a/extern/storage-sealing/states_sealing.go +++ b/extern/storage-sealing/states_sealing.go @@ -282,11 +282,6 @@ func (m *Sealing) handleWaitSeed(ctx statemachine.Context, sector SectorInfo) er return ctx.Send(SectorChainPreCommitFailed{error: xerrors.Errorf("precommit info not found on chain")}) } - nv, err := m.api.StateNetworkVersion(ctx.Context(), tok) - if err != nil { - return ctx.Send(SectorChainPreCommitFailed{xerrors.Errorf("failed to get network version: %w", err)}) - } - pccd, err := m.getPreCommitChallengeDelay(ctx.Context(), tok) if err != nil { return ctx.Send(SectorChainPreCommitFailed{xerrors.Errorf("failed to get precommit challenge delay: %w", err)}) From b60614982ea91a51e128c175da43d1d4e425a0bb Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Thu, 17 Sep 2020 02:42:39 -0400 Subject: [PATCH 052/303] Migrate reward actor --- chain/actors/builtin/reward/reward.go | 2 ++ chain/actors/builtin/reward/v0.go | 5 +++++ chain/gen/genesis/miners.go | 10 ++++----- chain/gen/genesis/t02_reward.go | 4 ++-- chain/stmgr/stmgr.go | 30 +++++++++++++++++---------- chain/stmgr/utils.go | 4 ++-- chain/vm/invoker.go | 4 ++-- 7 files changed, 37 insertions(+), 22 deletions(-) diff --git a/chain/actors/builtin/reward/reward.go b/chain/actors/builtin/reward/reward.go index ba03feced..d400258df 100644 --- a/chain/actors/builtin/reward/reward.go +++ b/chain/actors/builtin/reward/reward.go @@ -1,6 +1,7 @@ package reward import ( + "github.com/filecoin-project/go-state-types/abi" "golang.org/x/xerrors" "github.com/filecoin-project/go-state-types/cbor" @@ -30,4 +31,5 @@ type State interface { cbor.Marshaler RewardSmoothed() (builtin.FilterEstimate, error) + TotalStoragePowerReward() abi.TokenAmount } diff --git a/chain/actors/builtin/reward/v0.go b/chain/actors/builtin/reward/v0.go index a894fa752..b0558f0ae 100644 --- a/chain/actors/builtin/reward/v0.go +++ b/chain/actors/builtin/reward/v0.go @@ -1,6 +1,7 @@ package reward import ( + "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/lotus/chain/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin/reward" "github.com/filecoin-project/specs-actors/actors/util/adt" @@ -14,3 +15,7 @@ type v0State struct { func (s *v0State) RewardSmoothed() (builtin.FilterEstimate, error) { return *s.State.ThisEpochRewardSmoothed, nil } + +func (s *v0State) TotalStoragePowerReward() abi.TokenAmount { + return s.State.TotalMined +} diff --git a/chain/gen/genesis/miners.go b/chain/gen/genesis/miners.go index f6256ffbc..aff226882 100644 --- a/chain/gen/genesis/miners.go +++ b/chain/gen/genesis/miners.go @@ -22,7 +22,7 @@ import ( "github.com/filecoin-project/specs-actors/actors/builtin/market" v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" - "github.com/filecoin-project/specs-actors/actors/builtin/reward" + v0reward "github.com/filecoin-project/specs-actors/actors/builtin/reward" "github.com/filecoin-project/specs-actors/actors/runtime" "github.com/filecoin-project/lotus/chain/state" @@ -222,8 +222,8 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid return cid.Undef, xerrors.Errorf("mutating state: %w", err) } - err = vm.MutateState(ctx, builtin.RewardActorAddr, func(sct cbor.IpldStore, st *reward.State) error { - *st = *reward.ConstructState(qaPow) + err = vm.MutateState(ctx, builtin.RewardActorAddr, func(sct cbor.IpldStore, st *v0reward.State) error { + *st = *v0reward.ConstructState(qaPow) return nil }) if err != nil { @@ -381,13 +381,13 @@ func dealWeight(ctx context.Context, vm *vm.VM, maddr address.Address, dealIDs [ return dealWeights, nil } -func currentEpochBlockReward(ctx context.Context, vm *vm.VM, maddr address.Address) (*reward.ThisEpochRewardReturn, error) { +func currentEpochBlockReward(ctx context.Context, vm *vm.VM, maddr address.Address) (*v0reward.ThisEpochRewardReturn, error) { rwret, err := doExecValue(ctx, vm, builtin.RewardActorAddr, maddr, big.Zero(), builtin.MethodsReward.ThisEpochReward, nil) if err != nil { return nil, err } - var epochReward reward.ThisEpochRewardReturn + var epochReward v0reward.ThisEpochRewardReturn if err := epochReward.UnmarshalCBOR(bytes.NewReader(rwret)); err != nil { return nil, err } diff --git a/chain/gen/genesis/t02_reward.go b/chain/gen/genesis/t02_reward.go index d499b24d0..e29e390f9 100644 --- a/chain/gen/genesis/t02_reward.go +++ b/chain/gen/genesis/t02_reward.go @@ -6,7 +6,7 @@ import ( "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/reward" + v0reward "github.com/filecoin-project/specs-actors/actors/builtin/reward" cbor "github.com/ipfs/go-ipld-cbor" "github.com/filecoin-project/lotus/build" @@ -17,7 +17,7 @@ import ( func SetupRewardActor(bs bstore.Blockstore, qaPower big.Int) (*types.Actor, error) { cst := cbor.NewCborStore(bs) - st := reward.ConstructState(qaPower) + st := v0reward.ConstructState(qaPower) hcid, err := cst.Put(context.TODO(), st) if err != nil { diff --git a/chain/stmgr/stmgr.go b/chain/stmgr/stmgr.go index 8cb1329d2..8a72b4ba4 100644 --- a/chain/stmgr/stmgr.go +++ b/chain/stmgr/stmgr.go @@ -5,6 +5,8 @@ import ( "fmt" "sync" + "github.com/filecoin-project/lotus/chain/actors/builtin/reward" + "github.com/ipfs/go-cid" cbor "github.com/ipfs/go-ipld-cbor" logging "github.com/ipfs/go-log/v2" @@ -18,7 +20,7 @@ import ( "github.com/filecoin-project/go-state-types/network" "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin/multisig" - "github.com/filecoin-project/specs-actors/actors/builtin/reward" + v0reward "github.com/filecoin-project/specs-actors/actors/builtin/reward" "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/filecoin-project/lotus/api" @@ -242,15 +244,21 @@ func (sm *StateManager) ApplyBlocks(ctx context.Context, parentEpoch abi.ChainEp processedMsgs[m.Cid()] = true } - var err error - params, err := actors.SerializeParams(&reward.AwardBlockRewardParams{ - Miner: b.Miner, - Penalty: penalty, - GasReward: gasReward, - WinCount: b.WinCount, - }) - if err != nil { - return cid.Undef, cid.Undef, xerrors.Errorf("failed to serialize award params: %w", err) + var params []byte + + nv := sm.GetNtwkVersion(ctx, epoch) + if nv < build.ActorUpgradeNetworkVersion { + params, err = actors.SerializeParams(&v0reward.AwardBlockRewardParams{ + Miner: b.Miner, + Penalty: penalty, + GasReward: gasReward, + WinCount: b.WinCount, + }) + if err != nil { + return cid.Undef, cid.Undef, xerrors.Errorf("failed to serialize award params: %w", err) + } + } else { + // TODO: ActorUpgrade } sysAct, err := vmi.StateTree().GetActor(builtin.SystemActorAddr) @@ -1018,7 +1026,7 @@ func GetFilMined(ctx context.Context, st *state.StateTree) (abi.TokenAmount, err return big.Zero(), xerrors.Errorf("failed to load reward state: %w", err) } - return rst.TotalMined, nil + return rst.TotalStoragePowerReward(), nil } func getFilMarketLocked(ctx context.Context, st *state.StateTree) (abi.TokenAmount, error) { diff --git a/chain/stmgr/utils.go b/chain/stmgr/utils.go index 16167af75..b000a62e1 100644 --- a/chain/stmgr/utils.go +++ b/chain/stmgr/utils.go @@ -29,7 +29,7 @@ import ( "github.com/filecoin-project/specs-actors/actors/builtin/cron" "github.com/filecoin-project/specs-actors/actors/builtin/multisig" "github.com/filecoin-project/specs-actors/actors/builtin/paych" - "github.com/filecoin-project/specs-actors/actors/builtin/reward" + v0reward "github.com/filecoin-project/specs-actors/actors/builtin/reward" "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/lotus/api" @@ -555,7 +555,7 @@ func init() { builtin.StorageMarketActorCodeID: {builtin.MethodsMarket, market.Actor{}}, builtin.PaymentChannelActorCodeID: {builtin.MethodsPaych, paych.Actor{}}, builtin.MultisigActorCodeID: {builtin.MethodsMultisig, multisig.Actor{}}, - builtin.RewardActorCodeID: {builtin.MethodsReward, reward.Actor{}}, + builtin.RewardActorCodeID: {builtin.MethodsReward, v0reward.Actor{}}, builtin.VerifiedRegistryActorCodeID: {builtin.MethodsVerifiedRegistry, verifreg.Actor{}}, } diff --git a/chain/vm/invoker.go b/chain/vm/invoker.go index 5024164a7..a86a0f03c 100644 --- a/chain/vm/invoker.go +++ b/chain/vm/invoker.go @@ -24,7 +24,7 @@ import ( "github.com/filecoin-project/specs-actors/actors/builtin/multisig" "github.com/filecoin-project/specs-actors/actors/builtin/paych" v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" - "github.com/filecoin-project/specs-actors/actors/builtin/reward" + v0reward "github.com/filecoin-project/specs-actors/actors/builtin/reward" "github.com/filecoin-project/specs-actors/actors/builtin/system" "github.com/filecoin-project/specs-actors/actors/runtime" vmr "github.com/filecoin-project/specs-actors/actors/runtime" @@ -48,7 +48,7 @@ func NewInvoker() *Invoker { // NETUPGRADE: register code IDs for v2, etc. inv.Register(builtin.SystemActorCodeID, system.Actor{}, abi.EmptyValue{}) inv.Register(builtin.InitActorCodeID, init_.Actor{}, init_.State{}) - inv.Register(builtin.RewardActorCodeID, reward.Actor{}, reward.State{}) + inv.Register(builtin.RewardActorCodeID, v0reward.Actor{}, v0reward.State{}) inv.Register(builtin.CronActorCodeID, cron.Actor{}, cron.State{}) inv.Register(builtin.StoragePowerActorCodeID, v0power.Actor{}, v0power.State{}) inv.Register(builtin.StorageMarketActorCodeID, market.Actor{}, market.State{}) From e2295c372ab2ed0504bda3bb96a502cc3222b8ab Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Thu, 17 Sep 2020 02:50:59 -0400 Subject: [PATCH 053/303] Migrate multisig actor --- chain/actors/builtin/multisig/multisig.go | 3 +++ chain/actors/builtin/multisig/v0.go | 14 +++++++++++++- chain/stmgr/stmgr.go | 23 +++++++++++++---------- chain/stmgr/utils.go | 4 ++-- chain/vm/invoker.go | 4 ++-- cli/multisig.go | 14 +++++++------- 6 files changed, 40 insertions(+), 22 deletions(-) diff --git a/chain/actors/builtin/multisig/multisig.go b/chain/actors/builtin/multisig/multisig.go index 676dbe75f..fc58599a9 100644 --- a/chain/actors/builtin/multisig/multisig.go +++ b/chain/actors/builtin/multisig/multisig.go @@ -28,4 +28,7 @@ type State interface { cbor.Marshaler LockedBalance(epoch abi.ChainEpoch) (abi.TokenAmount, error) + StartEpoch() abi.ChainEpoch + UnlockDuration() abi.ChainEpoch + InitialBalance() abi.TokenAmount } diff --git a/chain/actors/builtin/multisig/v0.go b/chain/actors/builtin/multisig/v0.go index 3bc7e70b2..dc464d9af 100644 --- a/chain/actors/builtin/multisig/v0.go +++ b/chain/actors/builtin/multisig/v0.go @@ -12,5 +12,17 @@ type v0State struct { } func (s *v0State) LockedBalance(currEpoch abi.ChainEpoch) (abi.TokenAmount, error) { - return s.State.AmountLocked(currEpoch - s.StartEpoch), nil + return s.State.AmountLocked(currEpoch - s.State.StartEpoch), nil +} + +func (s *v0State) StartEpoch() abi.ChainEpoch { + return s.State.StartEpoch +} + +func (s *v0State) UnlockDuration() abi.ChainEpoch { + return s.State.UnlockDuration +} + +func (s *v0State) InitialBalance() abi.TokenAmount { + return s.State.InitialBalance } diff --git a/chain/stmgr/stmgr.go b/chain/stmgr/stmgr.go index 8a72b4ba4..18c67b5f0 100644 --- a/chain/stmgr/stmgr.go +++ b/chain/stmgr/stmgr.go @@ -5,6 +5,10 @@ import ( "fmt" "sync" + v0msig "github.com/filecoin-project/specs-actors/actors/builtin/multisig" + + "github.com/filecoin-project/lotus/chain/actors/builtin/multisig" + "github.com/filecoin-project/lotus/chain/actors/builtin/reward" "github.com/ipfs/go-cid" @@ -19,7 +23,6 @@ import ( "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/network" "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/multisig" v0reward "github.com/filecoin-project/specs-actors/actors/builtin/reward" "github.com/filecoin-project/specs-actors/actors/util/adt" @@ -793,7 +796,7 @@ func (sm *StateManager) SetVMConstructor(nvm func(context.Context, *vm.VMOpts) ( } type genesisInfo struct { - genesisMsigs []multisig.State + genesisMsigs []v0msig.State // info about the Accounts in the genesis state genesisActors []genesisActor genesisPledge abi.TokenAmount @@ -856,15 +859,15 @@ func (sm *StateManager) setupGenesisActors(ctx context.Context) error { return err } - if s.StartEpoch != 0 { + if s.StartEpoch() != 0 { return xerrors.New("genesis multisig doesn't start vesting at epoch 0!") } - ot, f := totalsByEpoch[s.UnlockDuration] + ot, f := totalsByEpoch[s.UnlockDuration()] if f { - totalsByEpoch[s.UnlockDuration] = big.Add(ot, s.InitialBalance) + totalsByEpoch[s.UnlockDuration()] = big.Add(ot, s.InitialBalance()) } else { - totalsByEpoch[s.UnlockDuration] = s.InitialBalance + totalsByEpoch[s.UnlockDuration()] = s.InitialBalance() } } else if act.Code == builtin.AccountActorCodeID { @@ -894,9 +897,9 @@ func (sm *StateManager) setupGenesisActors(ctx context.Context) error { return xerrors.Errorf("error setting up genesis infos: %w", err) } - gi.genesisMsigs = make([]multisig.State, 0, len(totalsByEpoch)) + gi.genesisMsigs = make([]v0msig.State, 0, len(totalsByEpoch)) for k, v := range totalsByEpoch { - ns := multisig.State{ + ns := v0msig.State{ InitialBalance: v, UnlockDuration: k, PendingTxns: cid.Undef, @@ -971,9 +974,9 @@ func (sm *StateManager) setupGenesisActorsTestnet(ctx context.Context) error { totalsByEpoch[sixYears] = big.NewInt(100_000_000) totalsByEpoch[sixYears] = big.Add(totalsByEpoch[sixYears], big.NewInt(300_000_000)) - gi.genesisMsigs = make([]multisig.State, 0, len(totalsByEpoch)) + gi.genesisMsigs = make([]v0msig.State, 0, len(totalsByEpoch)) for k, v := range totalsByEpoch { - ns := multisig.State{ + ns := v0msig.State{ InitialBalance: v, UnlockDuration: k, PendingTxns: cid.Undef, diff --git a/chain/stmgr/utils.go b/chain/stmgr/utils.go index b000a62e1..afd790a74 100644 --- a/chain/stmgr/utils.go +++ b/chain/stmgr/utils.go @@ -27,7 +27,7 @@ import ( "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin/account" "github.com/filecoin-project/specs-actors/actors/builtin/cron" - "github.com/filecoin-project/specs-actors/actors/builtin/multisig" + v0msig "github.com/filecoin-project/specs-actors/actors/builtin/multisig" "github.com/filecoin-project/specs-actors/actors/builtin/paych" v0reward "github.com/filecoin-project/specs-actors/actors/builtin/reward" "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" @@ -554,7 +554,7 @@ func init() { builtin.StorageMinerActorCodeID: {builtin.MethodsMiner, miner.Actor{}}, builtin.StorageMarketActorCodeID: {builtin.MethodsMarket, market.Actor{}}, builtin.PaymentChannelActorCodeID: {builtin.MethodsPaych, paych.Actor{}}, - builtin.MultisigActorCodeID: {builtin.MethodsMultisig, multisig.Actor{}}, + builtin.MultisigActorCodeID: {builtin.MethodsMultisig, v0msig.Actor{}}, builtin.RewardActorCodeID: {builtin.MethodsReward, v0reward.Actor{}}, builtin.VerifiedRegistryActorCodeID: {builtin.MethodsVerifiedRegistry, verifreg.Actor{}}, } diff --git a/chain/vm/invoker.go b/chain/vm/invoker.go index a86a0f03c..4cda32c44 100644 --- a/chain/vm/invoker.go +++ b/chain/vm/invoker.go @@ -21,7 +21,7 @@ import ( init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" "github.com/filecoin-project/specs-actors/actors/builtin/market" v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/filecoin-project/specs-actors/actors/builtin/multisig" + v0msig "github.com/filecoin-project/specs-actors/actors/builtin/multisig" "github.com/filecoin-project/specs-actors/actors/builtin/paych" v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" v0reward "github.com/filecoin-project/specs-actors/actors/builtin/reward" @@ -53,7 +53,7 @@ func NewInvoker() *Invoker { inv.Register(builtin.StoragePowerActorCodeID, v0power.Actor{}, v0power.State{}) inv.Register(builtin.StorageMarketActorCodeID, market.Actor{}, market.State{}) inv.Register(builtin.StorageMinerActorCodeID, v0miner.Actor{}, v0miner.State{}) - inv.Register(builtin.MultisigActorCodeID, multisig.Actor{}, multisig.State{}) + inv.Register(builtin.MultisigActorCodeID, v0msig.Actor{}, v0msig.State{}) inv.Register(builtin.PaymentChannelActorCodeID, paych.Actor{}, paych.State{}) inv.Register(builtin.VerifiedRegistryActorCodeID, verifreg.Actor{}, verifreg.State{}) inv.Register(builtin.AccountActorCodeID, account.Actor{}, account.State{}) diff --git a/cli/multisig.go b/cli/multisig.go index 4596628f4..ffbbd733b 100644 --- a/cli/multisig.go +++ b/cli/multisig.go @@ -17,7 +17,7 @@ import ( "github.com/filecoin-project/go-address" init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" - samsig "github.com/filecoin-project/specs-actors/actors/builtin/multisig" + v0msig "github.com/filecoin-project/specs-actors/actors/builtin/multisig" cid "github.com/ipfs/go-cid" cbor "github.com/ipfs/go-ipld-cbor" "github.com/urfave/cli/v2" @@ -199,7 +199,7 @@ var msigInspectCmd = &cli.Command{ return err } - var mstate samsig.State + var mstate v0msig.State if err := mstate.UnmarshalCBOR(bytes.NewReader(obj)); err != nil { return err } @@ -251,7 +251,7 @@ var msigInspectCmd = &cli.Command{ }, } -func GetMultisigPending(ctx context.Context, lapi api.FullNode, hroot cid.Cid) (map[int64]*samsig.Transaction, error) { +func GetMultisigPending(ctx context.Context, lapi api.FullNode, hroot cid.Cid) (map[int64]*v0msig.Transaction, error) { bs := apibstore.NewAPIBlockstore(lapi) store := adt.WrapStore(ctx, cbor.NewCborStore(bs)) @@ -260,8 +260,8 @@ func GetMultisigPending(ctx context.Context, lapi api.FullNode, hroot cid.Cid) ( return nil, err } - txs := make(map[int64]*samsig.Transaction) - var tx samsig.Transaction + txs := make(map[int64]*v0msig.Transaction) + var tx v0msig.Transaction err = nd.ForEach(&tx, func(k string) error { txid, _ := binary.Varint([]byte(k)) @@ -276,7 +276,7 @@ func GetMultisigPending(ctx context.Context, lapi api.FullNode, hroot cid.Cid) ( return txs, nil } -func state(tx *samsig.Transaction) string { +func state(tx *v0msig.Transaction) string { /* // TODO(why): I strongly disagree with not having these... but i need to move forward if tx.Complete { return "done" @@ -385,7 +385,7 @@ var msigProposeCmd = &cli.Command{ return fmt.Errorf("proposal returned exit %d", wait.Receipt.ExitCode) } - var retval samsig.ProposeReturn + var retval v0msig.ProposeReturn if err := retval.UnmarshalCBOR(bytes.NewReader(wait.Receipt.Return)); err != nil { return fmt.Errorf("failed to unmarshal propose return value: %w", err) } From 691bd9f442c80bbf0cce178e265706a90c2520ce Mon Sep 17 00:00:00 2001 From: hannahhoward Date: Thu, 17 Sep 2020 00:32:10 -0700 Subject: [PATCH 054/303] feat(markets): complete markets conversion complete markets conversion to using chain/actors types, also replacing DealProposal/DealState interfaces with structs --- api/api_full.go | 2 +- api/api_storage.go | 4 +- api/apistruct/struct.go | 8 +- chain/actors/builtin/market/market.go | 40 +++++-- chain/actors/builtin/market/v0.go | 144 +++++++++++++++++--------- chain/events/state/predicates.go | 19 ++-- chain/events/state/predicates_test.go | 14 +-- chain/gen/gen.go | 9 +- chain/stmgr/stmgr.go | 20 ++++ chain/stmgr/utils.go | 22 ++-- cli/client.go | 8 +- extern/storage-sealing/sealing.go | 2 +- go.mod | 2 +- go.sum | 4 + markets/storageadapter/client.go | 23 ---- markets/storageadapter/provider.go | 22 ---- markets/utils/converters.go | 8 -- node/impl/full/gas.go | 10 +- node/impl/full/state.go | 95 ++++++++--------- node/impl/storminer.go | 30 +++++- storage/adapter_storage_miner.go | 5 +- 21 files changed, 269 insertions(+), 222 deletions(-) diff --git a/api/api_full.go b/api/api_full.go index b472febe0..f565ad543 100644 --- a/api/api_full.go +++ b/api/api_full.go @@ -19,8 +19,8 @@ import ( "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/go-state-types/dline" + "github.com/filecoin-project/lotus/chain/actors/builtin/market" "github.com/filecoin-project/lotus/chain/actors/builtin/miner" - "github.com/filecoin-project/specs-actors/actors/builtin/market" "github.com/filecoin-project/specs-actors/actors/builtin/paych" "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/specs-actors/actors/runtime/proof" diff --git a/api/api_storage.go b/api/api_storage.go index 37bef2d6c..824772181 100644 --- a/api/api_storage.go +++ b/api/api_storage.go @@ -71,7 +71,7 @@ type StorageMiner interface { stores.SectorIndex MarketImportDealData(ctx context.Context, propcid cid.Cid, path string) error - MarketListDeals(ctx context.Context) ([]storagemarket.StorageDeal, error) + MarketListDeals(ctx context.Context) ([]MarketDeal, error) MarketListRetrievalDeals(ctx context.Context) ([]retrievalmarket.ProviderDealState, error) MarketGetDealUpdates(ctx context.Context) (<-chan storagemarket.MinerDeal, error) MarketListIncompleteDeals(ctx context.Context) ([]storagemarket.MinerDeal, error) @@ -83,7 +83,7 @@ type StorageMiner interface { MarketDataTransferUpdates(ctx context.Context) (<-chan DataTransferChannel, error) DealsImportData(ctx context.Context, dealPropCid cid.Cid, file string) error - DealsList(ctx context.Context) ([]storagemarket.StorageDeal, error) + DealsList(ctx context.Context) ([]MarketDeal, error) DealsConsiderOnlineStorageDeals(context.Context) (bool, error) DealsSetConsiderOnlineStorageDeals(context.Context, bool) error DealsConsiderOnlineRetrievalDeals(context.Context) (bool, error) diff --git a/api/apistruct/struct.go b/api/apistruct/struct.go index 26f7a8708..8bf8f1997 100644 --- a/api/apistruct/struct.go +++ b/api/apistruct/struct.go @@ -251,7 +251,7 @@ type StorageMinerStruct struct { MiningBase func(context.Context) (*types.TipSet, error) `perm:"read"` MarketImportDealData func(context.Context, cid.Cid, string) error `perm:"write"` - MarketListDeals func(ctx context.Context) ([]storagemarket.StorageDeal, error) `perm:"read"` + MarketListDeals func(ctx context.Context) ([]api.MarketDeal, error) `perm:"read"` MarketListRetrievalDeals func(ctx context.Context) ([]retrievalmarket.ProviderDealState, error) `perm:"read"` MarketGetDealUpdates func(ctx context.Context) (<-chan storagemarket.MinerDeal, error) `perm:"read"` MarketListIncompleteDeals func(ctx context.Context) ([]storagemarket.MinerDeal, error) `perm:"read"` @@ -296,7 +296,7 @@ type StorageMinerStruct struct { StorageTryLock func(ctx context.Context, sector abi.SectorID, read stores.SectorFileType, write stores.SectorFileType) (bool, error) `perm:"admin"` DealsImportData func(ctx context.Context, dealPropCid cid.Cid, file string) error `perm:"write"` - DealsList func(ctx context.Context) ([]storagemarket.StorageDeal, error) `perm:"read"` + DealsList func(ctx context.Context) ([]api.MarketDeal, error) `perm:"read"` DealsConsiderOnlineStorageDeals func(context.Context) (bool, error) `perm:"read"` DealsSetConsiderOnlineStorageDeals func(context.Context, bool) error `perm:"admin"` DealsConsiderOnlineRetrievalDeals func(context.Context) (bool, error) `perm:"read"` @@ -1128,7 +1128,7 @@ func (c *StorageMinerStruct) MarketImportDealData(ctx context.Context, propcid c return c.Internal.MarketImportDealData(ctx, propcid, path) } -func (c *StorageMinerStruct) MarketListDeals(ctx context.Context) ([]storagemarket.StorageDeal, error) { +func (c *StorageMinerStruct) MarketListDeals(ctx context.Context) ([]api.MarketDeal, error) { return c.Internal.MarketListDeals(ctx) } @@ -1172,7 +1172,7 @@ func (c *StorageMinerStruct) DealsImportData(ctx context.Context, dealPropCid ci return c.Internal.DealsImportData(ctx, dealPropCid, file) } -func (c *StorageMinerStruct) DealsList(ctx context.Context) ([]storagemarket.StorageDeal, error) { +func (c *StorageMinerStruct) DealsList(ctx context.Context) ([]api.MarketDeal, error) { return c.Internal.DealsList(ctx) } diff --git a/chain/actors/builtin/market/market.go b/chain/actors/builtin/market/market.go index 051c46dbe..73c2528d0 100644 --- a/chain/actors/builtin/market/market.go +++ b/chain/actors/builtin/market/market.go @@ -7,6 +7,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/cbor" v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" + "github.com/ipfs/go-cid" "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/types" @@ -43,26 +44,39 @@ type State interface { } type BalanceTable interface { + ForEach(cb func(address.Address, abi.TokenAmount) error) error Get(key address.Address) (abi.TokenAmount, error) } type DealStates interface { - GetDeal(key abi.DealID) (DealState, error) + Get(id abi.DealID) (*DealState, bool, error) Diff(DealStates) (*DealStateChanges, error) } type DealProposals interface { + ForEach(cb func(id abi.DealID, dp DealProposal) error) error + Get(id abi.DealID) (*DealProposal, bool, error) Diff(DealProposals) (*DealProposalChanges, error) } -type DealState interface { - SectorStartEpoch() abi.ChainEpoch - SlashEpoch() abi.ChainEpoch - LastUpdatedEpoch() abi.ChainEpoch - Equals(DealState) bool +type DealState struct { + SectorStartEpoch abi.ChainEpoch // -1 if not yet included in proven sector + LastUpdatedEpoch abi.ChainEpoch // -1 if deal state never updated + SlashEpoch abi.ChainEpoch // -1 if deal never slashed } -type DealProposal interface { +type DealProposal struct { + PieceCID cid.Cid + PieceSize abi.PaddedPieceSize + VerifiedDeal bool + Client address.Address + Provider address.Address + Label string + StartEpoch abi.ChainEpoch + EndEpoch abi.ChainEpoch + StoragePricePerEpoch abi.TokenAmount + ProviderCollateral abi.TokenAmount + ClientCollateral abi.TokenAmount } type DealStateChanges struct { @@ -79,8 +93,8 @@ type DealIDState struct { // DealStateChange is a change in deal state from -> to type DealStateChange struct { ID abi.DealID - From DealState - To DealState + From *DealState + To *DealState } type DealProposalChanges struct { @@ -92,3 +106,11 @@ type ProposalIDState struct { ID abi.DealID Proposal DealProposal } + +func EmptyDealState() *DealState { + return &DealState{ + SectorStartEpoch: -1, + SlashEpoch: -1, + LastUpdatedEpoch: -1, + } +} diff --git a/chain/actors/builtin/market/v0.go b/chain/actors/builtin/market/v0.go index 8f0aa0594..92ebb59ba 100644 --- a/chain/actors/builtin/market/v0.go +++ b/chain/actors/builtin/market/v0.go @@ -72,11 +72,19 @@ func (s *v0State) Proposals() (DealProposals, error) { } func (s *v0State) EscrowTable() (BalanceTable, error) { - return v0adt.AsBalanceTable(s.store, s.State.EscrowTable) + bt, err := v0adt.AsBalanceTable(s.store, s.State.EscrowTable) + if err != nil { + return nil, err + } + return &v0BalanceTable{bt}, nil } func (s *v0State) LockedTable() (BalanceTable, error) { - return v0adt.AsBalanceTable(s.store, s.State.LockedTable) + bt, err := v0adt.AsBalanceTable(s.store, s.State.LockedTable) + if err != nil { + return nil, err + } + return &v0BalanceTable{bt}, nil } func (s *v0State) VerifyDealsForActivation( @@ -85,20 +93,37 @@ func (s *v0State) VerifyDealsForActivation( return market.ValidateDealsForActivation(&s.State, s.store, deals, minerAddr, sectorExpiry, currEpoch) } +type v0BalanceTable struct { + *v0adt.BalanceTable +} + +func (bt *v0BalanceTable) ForEach(cb func(address.Address, abi.TokenAmount) error) error { + asMap := (*v0adt.Map)(bt.BalanceTable) + var ta abi.TokenAmount + return asMap.ForEach(&ta, func(key string) error { + a, err := address.NewFromBytes([]byte(key)) + if err != nil { + return err + } + return cb(a, ta) + }) +} + type v0DealStates struct { adt.Array } -func (s *v0DealStates) GetDeal(dealID abi.DealID) (DealState, error) { - var deal market.DealState - found, err := s.Array.Get(uint64(dealID), &deal) +func (s *v0DealStates) Get(dealID abi.DealID) (*DealState, bool, error) { + var v0deal market.DealState + found, err := s.Array.Get(uint64(dealID), &v0deal) if err != nil { - return nil, err + return nil, false, err } if !found { - return nil, nil + return nil, false, nil } - return &v0DealState{deal}, nil + deal := fromV0DealState(v0deal) + return &deal, true, nil } func (s *v0DealStates) Diff(other DealStates) (*DealStateChanges, error) { @@ -108,7 +133,7 @@ func (s *v0DealStates) Diff(other DealStates) (*DealStateChanges, error) { return nil, errors.New("cannot compare deal states across versions") } results := new(DealStateChanges) - if err := adt.DiffAdtArray(s, v0other, &v0MarketStatesDiffer{results}); err != nil { + if err := adt.DiffAdtArray(s.Array, v0other.Array, &v0MarketStatesDiffer{results}); err != nil { return nil, fmt.Errorf("diffing deal states: %w", err) } @@ -120,61 +145,50 @@ type v0MarketStatesDiffer struct { } func (d *v0MarketStatesDiffer) Add(key uint64, val *typegen.Deferred) error { - ds := new(v0DealState) - err := ds.UnmarshalCBOR(bytes.NewReader(val.Raw)) + v0ds := new(market.DealState) + err := v0ds.UnmarshalCBOR(bytes.NewReader(val.Raw)) if err != nil { return err } - d.Results.Added = append(d.Results.Added, DealIDState{abi.DealID(key), ds}) + d.Results.Added = append(d.Results.Added, DealIDState{abi.DealID(key), fromV0DealState(*v0ds)}) return nil } func (d *v0MarketStatesDiffer) Modify(key uint64, from, to *typegen.Deferred) error { - dsFrom := new(v0DealState) - if err := dsFrom.UnmarshalCBOR(bytes.NewReader(from.Raw)); err != nil { + v0dsFrom := new(market.DealState) + if err := v0dsFrom.UnmarshalCBOR(bytes.NewReader(from.Raw)); err != nil { return err } - dsTo := new(v0DealState) - if err := dsTo.UnmarshalCBOR(bytes.NewReader(to.Raw)); err != nil { + v0dsTo := new(market.DealState) + if err := v0dsTo.UnmarshalCBOR(bytes.NewReader(to.Raw)); err != nil { return err } - if *dsFrom != *dsTo { - d.Results.Modified = append(d.Results.Modified, DealStateChange{abi.DealID(key), dsFrom, dsTo}) + if *v0dsFrom != *v0dsTo { + dsFrom := fromV0DealState(*v0dsFrom) + dsTo := fromV0DealState(*v0dsTo) + d.Results.Modified = append(d.Results.Modified, DealStateChange{abi.DealID(key), &dsFrom, &dsTo}) } return nil } func (d *v0MarketStatesDiffer) Remove(key uint64, val *typegen.Deferred) error { - ds := new(v0DealState) - err := ds.UnmarshalCBOR(bytes.NewReader(val.Raw)) + v0ds := new(market.DealState) + err := v0ds.UnmarshalCBOR(bytes.NewReader(val.Raw)) if err != nil { return err } - d.Results.Removed = append(d.Results.Removed, DealIDState{abi.DealID(key), ds}) + d.Results.Removed = append(d.Results.Removed, DealIDState{abi.DealID(key), fromV0DealState(*v0ds)}) return nil } -type v0DealState struct { - market.DealState -} - -func (ds *v0DealState) SectorStartEpoch() abi.ChainEpoch { - return ds.DealState.SectorStartEpoch -} - -func (ds *v0DealState) SlashEpoch() abi.ChainEpoch { - return ds.DealState.SlashEpoch -} - -func (ds *v0DealState) LastUpdatedEpoch() abi.ChainEpoch { - return ds.DealState.LastUpdatedEpoch -} - -func (ds *v0DealState) Equals(other DealState) bool { - v0other, ok := other.(*v0DealState) - return ok && *ds == *v0other +func fromV0DealState(v0 market.DealState) DealState { + return DealState{ + SectorStartEpoch: v0.SectorStartEpoch, + SlashEpoch: v0.SlashEpoch, + LastUpdatedEpoch: v0.LastUpdatedEpoch, + } } type v0DealProposals struct { @@ -188,28 +202,60 @@ func (s *v0DealProposals) Diff(other DealProposals) (*DealProposalChanges, error return nil, errors.New("cannot compare deal proposals across versions") } results := new(DealProposalChanges) - if err := adt.DiffAdtArray(s, v0other, &v0MarketProposalsDiffer{results}); err != nil { + if err := adt.DiffAdtArray(s.Array, v0other.Array, &v0MarketProposalsDiffer{results}); err != nil { return nil, fmt.Errorf("diffing deal proposals: %w", err) } return results, nil } +func (s *v0DealProposals) Get(dealID abi.DealID) (*DealProposal, bool, error) { + var v0proposal market.DealProposal + found, err := s.Array.Get(uint64(dealID), &v0proposal) + if err != nil { + return nil, false, err + } + if !found { + return nil, false, nil + } + proposal := fromV0DealProposal(v0proposal) + return &proposal, true, nil +} + +func (s *v0DealProposals) ForEach(cb func(dealID abi.DealID, dp DealProposal) error) error { + var v0dp market.DealProposal + return s.Array.ForEach(&v0dp, func(idx int64) error { + return cb(abi.DealID(idx), fromV0DealProposal(v0dp)) + }) +} + type v0MarketProposalsDiffer struct { Results *DealProposalChanges } -type v0DealProposal struct { - market.DealProposal +func fromV0DealProposal(v0 market.DealProposal) DealProposal { + return DealProposal{ + PieceCID: v0.PieceCID, + PieceSize: v0.PieceSize, + VerifiedDeal: v0.VerifiedDeal, + Client: v0.Client, + Provider: v0.Provider, + Label: v0.Label, + StartEpoch: v0.StartEpoch, + EndEpoch: v0.EndEpoch, + StoragePricePerEpoch: v0.StoragePricePerEpoch, + ProviderCollateral: v0.ProviderCollateral, + ClientCollateral: v0.ClientCollateral, + } } func (d *v0MarketProposalsDiffer) Add(key uint64, val *typegen.Deferred) error { - dp := new(v0DealProposal) - err := dp.UnmarshalCBOR(bytes.NewReader(val.Raw)) + v0dp := new(market.DealProposal) + err := v0dp.UnmarshalCBOR(bytes.NewReader(val.Raw)) if err != nil { return err } - d.Results.Added = append(d.Results.Added, ProposalIDState{abi.DealID(key), dp}) + d.Results.Added = append(d.Results.Added, ProposalIDState{abi.DealID(key), fromV0DealProposal(*v0dp)}) return nil } @@ -219,11 +265,11 @@ func (d *v0MarketProposalsDiffer) Modify(key uint64, from, to *typegen.Deferred) } func (d *v0MarketProposalsDiffer) Remove(key uint64, val *typegen.Deferred) error { - dp := new(v0DealProposal) - err := dp.UnmarshalCBOR(bytes.NewReader(val.Raw)) + v0dp := new(market.DealProposal) + err := v0dp.UnmarshalCBOR(bytes.NewReader(val.Raw)) if err != nil { return err } - d.Results.Removed = append(d.Results.Removed, ProposalIDState{abi.DealID(key), dp}) + d.Results.Removed = append(d.Results.Removed, ProposalIDState{abi.DealID(key), fromV0DealProposal(*v0dp)}) return nil } diff --git a/chain/events/state/predicates.go b/chain/events/state/predicates.go index 3e515e6a4..7a7609823 100644 --- a/chain/events/state/predicates.go +++ b/chain/events/state/predicates.go @@ -212,14 +212,7 @@ func (sp *StatePredicates) OnDealStateAmtChanged() DiffDealStatesFunc { } // ChangedDeals is a set of changes to deal state -type ChangedDeals map[abi.DealID]DealStateChange - -// DealStateChange is a change in deal state from -> to -type DealStateChange struct { - ID abi.DealID - From market.DealState - To market.DealState -} +type ChangedDeals map[abi.DealID]market.DealStateChange // DealStateChangedForIDs detects changes in the deal state AMT for the given deal IDs func (sp *StatePredicates) DealStateChangedForIDs(dealIds []abi.DealID) DiffDealStatesFunc { @@ -228,20 +221,20 @@ func (sp *StatePredicates) DealStateChangedForIDs(dealIds []abi.DealID) DiffDeal for _, dealID := range dealIds { // If the deal has been removed, we just set it to nil - oldDeal, err := oldDealStates.GetDeal(dealID) + oldDeal, oldFound, err := oldDealStates.Get(dealID) if err != nil { return false, nil, err } - newDeal, err := newDealStates.GetDeal(dealID) + newDeal, newFound, err := newDealStates.Get(dealID) if err != nil { return false, nil, err } - existenceChanged := (oldDeal == nil) != (newDeal == nil) - valueChanged := (oldDeal != nil && newDeal != nil) && !oldDeal.Equals(newDeal) + existenceChanged := oldFound != newFound + valueChanged := (oldFound && newFound) && *oldDeal != *newDeal if existenceChanged || valueChanged { - changedDeals[dealID] = DealStateChange{dealID, oldDeal, newDeal} + changedDeals[dealID] = market.DealStateChange{ID: dealID, From: oldDeal, To: newDeal} } } if len(changedDeals) > 0 { diff --git a/chain/events/state/predicates_test.go b/chain/events/state/predicates_test.go index 25f25334d..6541aa3b4 100644 --- a/chain/events/state/predicates_test.go +++ b/chain/events/state/predicates_test.go @@ -208,11 +208,11 @@ func TestMarketPredicates(t *testing.T) { require.Contains(t, changedDealIDs, abi.DealID(1)) require.Contains(t, changedDealIDs, abi.DealID(2)) deal1 := changedDealIDs[abi.DealID(1)] - if deal1.From.LastUpdatedEpoch() != 2 || deal1.To.LastUpdatedEpoch() != 3 { + if deal1.From.LastUpdatedEpoch != 2 || deal1.To.LastUpdatedEpoch != 3 { t.Fatal("Unexpected change to LastUpdatedEpoch") } deal2 := changedDealIDs[abi.DealID(2)] - if deal2.From.LastUpdatedEpoch() != 5 || deal2.To != nil { + if deal2.From.LastUpdatedEpoch != 5 || deal2.To != nil { t.Fatal("Expected To to be nil") } @@ -273,8 +273,8 @@ func TestMarketPredicates(t *testing.T) { require.Len(t, changedDeals.Modified, 1) require.Equal(t, abi.DealID(1), changedDeals.Modified[0].ID) - require.True(t, dealEquality(*newDeal1, changedDeals.Modified[0].To)) - require.True(t, dealEquality(*oldDeal1, changedDeals.Modified[0].From)) + require.True(t, dealEquality(*newDeal1, *changedDeals.Modified[0].To)) + require.True(t, dealEquality(*oldDeal1, *changedDeals.Modified[0].From)) require.Equal(t, abi.DealID(2), changedDeals.Removed[0].ID) }) @@ -624,7 +624,7 @@ func newSectorPreCommitInfo(sectorNo abi.SectorNumber, sealed cid.Cid, expiratio } func dealEquality(expected v0market.DealState, actual market.DealState) bool { - return expected.LastUpdatedEpoch == actual.LastUpdatedEpoch() && - expected.SectorStartEpoch == actual.SectorStartEpoch() && - expected.SlashEpoch == actual.SlashEpoch() + return expected.LastUpdatedEpoch == actual.LastUpdatedEpoch && + expected.SectorStartEpoch == actual.SectorStartEpoch && + expected.SlashEpoch == actual.SlashEpoch } diff --git a/chain/gen/gen.go b/chain/gen/gen.go index 4cae19082..4163f0b2d 100644 --- a/chain/gen/gen.go +++ b/chain/gen/gen.go @@ -489,13 +489,16 @@ func (cg *ChainGen) makeBlock(parents *types.TipSet, m address.Address, vrfticke // ResyncBankerNonce is used for dealing with messages made when // simulating forks func (cg *ChainGen) ResyncBankerNonce(ts *types.TipSet) error { - var act types.Actor - err := cg.sm.WithParentState(ts, cg.sm.WithActor(cg.banker, stmgr.GetActor(&act))) + st, err := cg.sm.ParentState(ts) + if err != nil { + return err + } + act, err := st.GetActor(cg.banker) if err != nil { return err } - cg.bankerNonce = act.Nonce + return nil } diff --git a/chain/stmgr/stmgr.go b/chain/stmgr/stmgr.go index 18c67b5f0..2a6737e2c 100644 --- a/chain/stmgr/stmgr.go +++ b/chain/stmgr/stmgr.go @@ -1175,3 +1175,23 @@ func (sm *StateManager) GetPaychState(ctx context.Context, addr address.Address, } return act, actState, nil } + +func (sm *StateManager) GetMarketState(ctx context.Context, ts *types.TipSet) (market.State, error) { + st, err := sm.ParentState(ts) + if err != nil { + return nil, err + } + + // TODO maybe there needs to be code here to differentiate address based on ts height? + addr := builtin.StorageMarketActorAddr + act, err := st.GetActor(addr) + if err != nil { + return nil, err + } + + actState, err := market.Load(sm.cs.Store(ctx), act) + if err != nil { + return nil, err + } + return actState, nil +} diff --git a/chain/stmgr/utils.go b/chain/stmgr/utils.go index afd790a74..38b66c512 100644 --- a/chain/stmgr/utils.go +++ b/chain/stmgr/utils.go @@ -34,7 +34,6 @@ import ( "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" - "github.com/filecoin-project/lotus/chain/actors/adt" init_ "github.com/filecoin-project/lotus/chain/actors/builtin/init" "github.com/filecoin-project/lotus/chain/actors/builtin/market" "github.com/filecoin-project/lotus/chain/actors/builtin/miner" @@ -318,40 +317,35 @@ func GetStorageDeal(ctx context.Context, sm *StateManager, dealID abi.DealID, ts return nil, xerrors.Errorf("failed to load market actor state: %w", err) } - store := sm.ChainStore().Store(ctx) - - da, err := adt.AsArray(store, state.Proposals) + proposals, err := state.Proposals() if err != nil { return nil, err } - var dp market.DealProposal - if found, err := da.Get(uint64(dealID), &dp); err != nil { + proposal, found, err := proposals.Get(dealID) + + if err != nil { return nil, err } else if !found { return nil, xerrors.Errorf("deal %d not found", dealID) } - sa, err := market.AsDealStateArray(store, state.States) + states, err := state.States() if err != nil { return nil, err } - st, found, err := sa.Get(dealID) + st, found, err := states.Get(dealID) if err != nil { return nil, err } if !found { - st = &market.DealState{ - SectorStartEpoch: -1, - LastUpdatedEpoch: -1, - SlashEpoch: -1, - } + st = market.EmptyDealState() } return &api.MarketDeal{ - Proposal: dp, + Proposal: *proposal, State: *st, }, nil } diff --git a/cli/client.go b/cli/client.go index e68f98791..eda5ffae8 100644 --- a/cli/client.go +++ b/cli/client.go @@ -29,13 +29,13 @@ import ( "github.com/filecoin-project/go-multistore" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" - "github.com/filecoin-project/specs-actors/actors/builtin/market" "github.com/filecoin-project/lotus/api" lapi "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/lib/tablewriter" + "github.com/filecoin-project/lotus/chain/actors/builtin/market" ) var CidBaseFlag = cli.StringFlag{ @@ -1045,11 +1045,7 @@ func dealFromDealInfo(ctx context.Context, full api.FullNode, head *types.TipSet if v.DealID == 0 { return deal{ LocalDeal: v, - OnChainDealState: market.DealState{ - SectorStartEpoch: -1, - LastUpdatedEpoch: -1, - SlashEpoch: -1, - }, + OnChainDealState: *market.EmptyDealState() } } diff --git a/extern/storage-sealing/sealing.go b/extern/storage-sealing/sealing.go index 0fe754217..e9a98fec9 100644 --- a/extern/storage-sealing/sealing.go +++ b/extern/storage-sealing/sealing.go @@ -25,9 +25,9 @@ import ( "github.com/filecoin-project/go-state-types/crypto" statemachine "github.com/filecoin-project/go-statemachine" "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + "github.com/filecoin-project/lotus/chain/actors/builtin/market" sectorstorage "github.com/filecoin-project/lotus/extern/sector-storage" "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" - "github.com/filecoin-project/specs-actors/actors/builtin/market" ) const SectorStorePrefix = "/sectors" diff --git a/go.mod b/go.mod index 65c2addb8..0397ff275 100644 --- a/go.mod +++ b/go.mod @@ -27,7 +27,7 @@ require ( github.com/filecoin-project/go-crypto v0.0.0-20191218222705-effae4ea9f03 github.com/filecoin-project/go-data-transfer v0.6.3 github.com/filecoin-project/go-fil-commcid v0.0.0-20200716160307-8f644712406f - github.com/filecoin-project/go-fil-markets v0.6.1-0.20200911011457-2959ccca6a3c + github.com/filecoin-project/go-fil-markets v0.6.1-0.20200917052354-ee0af754c6e9 github.com/filecoin-project/go-jsonrpc v0.1.2-0.20200822201400-474f4fdccc52 github.com/filecoin-project/go-multistore v0.0.3 github.com/filecoin-project/go-padreader v0.0.0-20200903213702-ed5fae088b20 diff --git a/go.sum b/go.sum index b6b724767..3d012da92 100644 --- a/go.sum +++ b/go.sum @@ -228,6 +228,10 @@ github.com/filecoin-project/go-fil-commcid v0.0.0-20200716160307-8f644712406f h1 github.com/filecoin-project/go-fil-commcid v0.0.0-20200716160307-8f644712406f/go.mod h1:Eaox7Hvus1JgPrL5+M3+h7aSPHc0cVqpSxA+TxIEpZQ= github.com/filecoin-project/go-fil-markets v0.6.1-0.20200911011457-2959ccca6a3c h1:YGoyYmELQ0LHwDj/WcOvY3oYt+3iM0wdrAhqJQUAIy4= github.com/filecoin-project/go-fil-markets v0.6.1-0.20200911011457-2959ccca6a3c/go.mod h1:PLr9svZxsnHkae1Ky7+66g7fP9AlneVxIVu+oSMq56A= +github.com/filecoin-project/go-fil-markets v0.6.1-0.20200917050751-2af52e9606c6 h1:k97Z2JP3WpDVGU/7Bz3RtnqrYtn9X428Ps8OkoFq61I= +github.com/filecoin-project/go-fil-markets v0.6.1-0.20200917050751-2af52e9606c6/go.mod h1:PLr9svZxsnHkae1Ky7+66g7fP9AlneVxIVu+oSMq56A= +github.com/filecoin-project/go-fil-markets v0.6.1-0.20200917052354-ee0af754c6e9 h1:SnCUC9wHDId9TtV8PsQp8q1OOsi+NOLOwitIDnAgUa4= +github.com/filecoin-project/go-fil-markets v0.6.1-0.20200917052354-ee0af754c6e9/go.mod h1:PLr9svZxsnHkae1Ky7+66g7fP9AlneVxIVu+oSMq56A= github.com/filecoin-project/go-hamt-ipld v0.1.5 h1:uoXrKbCQZ49OHpsTCkrThPNelC4W3LPEk0OrS/ytIBM= github.com/filecoin-project/go-hamt-ipld v0.1.5 h1:uoXrKbCQZ49OHpsTCkrThPNelC4W3LPEk0OrS/ytIBM= github.com/filecoin-project/go-hamt-ipld v0.1.5/go.mod h1:6Is+ONR5Cd5R6XZoCse1CWaXZc0Hdb/JeX+EQCQzX24= diff --git a/markets/storageadapter/client.go b/markets/storageadapter/client.go index 0c9e66eda..781715903 100644 --- a/markets/storageadapter/client.go +++ b/markets/storageadapter/client.go @@ -98,29 +98,6 @@ func (c *ClientNodeAdapter) VerifySignature(ctx context.Context, sig crypto.Sign return err == nil, err } -func (c *ClientNodeAdapter) ListClientDeals(ctx context.Context, addr address.Address, encodedTs shared.TipSetToken) ([]storagemarket.StorageDeal, error) { - tsk, err := types.TipSetKeyFromBytes(encodedTs) - if err != nil { - return nil, err - } - - allDeals, err := c.StateMarketDeals(ctx, tsk) - if err != nil { - return nil, err - } - - var out []storagemarket.StorageDeal - - for _, deal := range allDeals { - storageDeal := utils.FromOnChainDeal(deal.Proposal, deal.State) - if storageDeal.Client == addr { - out = append(out, storageDeal) - } - } - - return out, nil -} - // Adds funds with the StorageMinerActor for a storage participant. Used by both providers and clients. func (c *ClientNodeAdapter) AddFunds(ctx context.Context, addr address.Address, amount abi.TokenAmount) (cid.Cid, error) { // (Provider Node API) diff --git a/markets/storageadapter/provider.go b/markets/storageadapter/provider.go index 22d6c1e1d..98935b30a 100644 --- a/markets/storageadapter/provider.go +++ b/markets/storageadapter/provider.go @@ -142,28 +142,6 @@ func (n *ProviderNodeAdapter) VerifySignature(ctx context.Context, sig crypto.Si return err == nil, err } -func (n *ProviderNodeAdapter) ListProviderDeals(ctx context.Context, addr address.Address, encodedTs shared.TipSetToken) ([]storagemarket.StorageDeal, error) { - tsk, err := types.TipSetKeyFromBytes(encodedTs) - if err != nil { - return nil, err - } - allDeals, err := n.StateMarketDeals(ctx, tsk) - if err != nil { - return nil, err - } - - var out []storagemarket.StorageDeal - - for _, deal := range allDeals { - sharedDeal := utils.FromOnChainDeal(deal.Proposal, deal.State) - if sharedDeal.Provider == addr { - out = append(out, sharedDeal) - } - } - - return out, nil -} - func (n *ProviderNodeAdapter) GetMinerWorkerAddress(ctx context.Context, miner address.Address, tok shared.TipSetToken) (address.Address, error) { tsk, err := types.TipSetKeyFromBytes(tok) if err != nil { diff --git a/markets/utils/converters.go b/markets/utils/converters.go index 05472801d..4a3d21140 100644 --- a/markets/utils/converters.go +++ b/markets/utils/converters.go @@ -4,7 +4,6 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/lotus/api" - "github.com/filecoin-project/specs-actors/actors/builtin/market" peer "github.com/libp2p/go-libp2p-core/peer" "github.com/multiformats/go-multiaddr" @@ -31,13 +30,6 @@ func NewStorageProviderInfo(address address.Address, miner address.Address, sect } } -func FromOnChainDeal(prop market.DealProposal, state market.DealState) storagemarket.StorageDeal { - return storagemarket.StorageDeal{ - DealProposal: prop, - DealState: state, - } -} - func ToSharedBalance(bal api.MarketBalance) storagemarket.Balance { return storagemarket.Balance{ Locked: bal.Locked, diff --git a/node/impl/full/gas.go b/node/impl/full/gas.go index 536bef360..b207a1f6d 100644 --- a/node/impl/full/gas.go +++ b/node/impl/full/gas.go @@ -166,8 +166,14 @@ func (a *GasAPI) GasEstimateGasLimit(ctx context.Context, msgIn *types.Message, } // Special case for PaymentChannel collect, which is deleting actor - var act types.Actor - err = a.Stmgr.WithParentState(ts, a.Stmgr.WithActor(msg.To, stmgr.GetActor(&act))) + st, err := a.Stmgr.ParentState(ts) + if err != nil { + _ = err + // somewhat ignore it as it can happen and we just want to detect + // an existing PaymentChannel actor + return res.MsgRct.GasUsed, nil + } + act, err := st.GetActor(msg.To) if err != nil { _ = err // somewhat ignore it as it can happen and we just want to detect diff --git a/node/impl/full/state.go b/node/impl/full/state.go index 1b29a93a9..241561a9f 100644 --- a/node/impl/full/state.go +++ b/node/impl/full/state.go @@ -4,10 +4,10 @@ import ( "bytes" "context" "errors" - "fmt" - "github.com/filecoin-project/go-state-types/network" "strconv" + "github.com/filecoin-project/go-state-types/network" + "github.com/filecoin-project/go-state-types/dline" cid "github.com/ipfs/go-cid" @@ -28,6 +28,7 @@ import ( "github.com/filecoin-project/specs-actors/actors/util/smoothing" "github.com/filecoin-project/lotus/api" + "github.com/filecoin-project/lotus/chain/actors/builtin/market" "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/actors/builtin/multisig" "github.com/filecoin-project/lotus/chain/actors/builtin/power" @@ -42,7 +43,6 @@ import ( "github.com/filecoin-project/lotus/chain/wallet" "github.com/filecoin-project/lotus/lib/bufbstore" "github.com/filecoin-project/lotus/node/modules/dtypes" - "github.com/filecoin-project/lotus/chain/actors/builtin/market" ) var errBreakForeach = errors.New("break") @@ -259,8 +259,8 @@ func (a *StateAPI) StateMinerPower(ctx context.Context, addr address.Address, ts } return &api.MinerPower{ - MinerPower: m, - TotalPower: net, + MinerPower: m, + TotalPower: net, HasMinPower: hmp, }, nil } @@ -489,37 +489,31 @@ func (a *StateAPI) StateMarketBalance(ctx context.Context, addr address.Address, func (a *StateAPI) StateMarketParticipants(ctx context.Context, tsk types.TipSetKey) (map[string]api.MarketBalance, error) { out := map[string]api.MarketBalance{} - var state market.State ts, err := a.Chain.GetTipSetFromKey(tsk) if err != nil { return nil, xerrors.Errorf("loading tipset %s: %w", tsk, err) } - if _, err := a.StateManager.LoadActorState(ctx, builtin.StorageMarketActorAddr, &state, ts); err != nil { - return nil, err - } - store := a.StateManager.ChainStore().Store(ctx) - escrow, err := adt.AsMap(store, state.EscrowTable) + + state, err := a.StateManager.GetMarketState(ctx, ts) if err != nil { return nil, err } - locked, err := adt.AsMap(store, state.LockedTable) + escrow, err := state.EscrowTable() + if err != nil { + return nil, err + } + locked, err := state.LockedTable() if err != nil { return nil, err } - var es, lk abi.TokenAmount - err = escrow.ForEach(&es, func(k string) error { - a, err := address.NewFromBytes([]byte(k)) + err = escrow.ForEach(func(a address.Address, es abi.TokenAmount) error { + + lk, err := locked.Get(a) if err != nil { return err } - if found, err := locked.Get(abi.AddrKey(a), &lk); err != nil { - return err - } else if !found { - return fmt.Errorf("locked funds not found") - } - out[a.String()] = api.MarketBalance{ Escrow: es, Locked: lk, @@ -535,37 +529,36 @@ func (a *StateAPI) StateMarketParticipants(ctx context.Context, tsk types.TipSet func (a *StateAPI) StateMarketDeals(ctx context.Context, tsk types.TipSetKey) (map[string]api.MarketDeal, error) { out := map[string]api.MarketDeal{} - var state market.State ts, err := a.Chain.GetTipSetFromKey(tsk) if err != nil { return nil, xerrors.Errorf("loading tipset %s: %w", tsk, err) } - if _, err := a.StateManager.LoadActorState(ctx, builtin.StorageMarketActorAddr, &state, ts); err != nil { - return nil, err - } - store := a.StateManager.ChainStore().Store(ctx) - da, err := adt.AsArray(store, state.Proposals) + state, err := a.StateManager.GetMarketState(ctx, ts) if err != nil { return nil, err } - sa, err := adt.AsArray(store, state.States) + da, err := state.Proposals() if err != nil { return nil, err } - var d market.DealProposal - if err := da.ForEach(&d, func(i int64) error { - var s market.DealState - if found, err := sa.Get(uint64(i), &s); err != nil { + sa, err := state.States() + if err != nil { + return nil, err + } + + if err := da.ForEach(func(dealID abi.DealID, d market.DealProposal) error { + s, found, err := sa.Get(dealID) + if err != nil { return xerrors.Errorf("failed to get state for deal in proposals array: %w", err) } else if !found { - s.SectorStartEpoch = -1 + s = market.EmptyDealState() } - out[strconv.FormatInt(i, 10)] = api.MarketDeal{ + out[strconv.FormatInt(int64(dealID), 10)] = api.MarketDeal{ Proposal: d, - State: s, + State: *s, } return nil }); err != nil { @@ -872,10 +865,10 @@ func (a *StateAPI) StateMinerPreCommitDepositForPower(ctx context.Context, maddr var sectorWeight abi.StoragePower if act, err := state.GetActor(market.Address); err != nil { return types.EmptyInt, xerrors.Errorf("loading miner actor %s: %w", maddr, err) - } else s, err := market.Load(store, act); err != nil { + } else if s, err := market.Load(store, act); err != nil { return types.EmptyInt, xerrors.Errorf("loading market actor state %s: %w", maddr, err) } else if w, vw, err := s.VerifyDealsForActivation(maddr, pci.DealIDs, ts.Height(), pci.Expiration); err != nil { - return types.EmptyInt, xerrors.Errorf("verifying deals for activation: %w", err) + return types.EmptyInt, xerrors.Errorf("verifying deals for activation: %w", err) } else { // NB: not exactly accurate, but should always lead us to *over* estimate, not under duration := pci.Expiration - ts.Height() @@ -887,9 +880,9 @@ func (a *StateAPI) StateMinerPreCommitDepositForPower(ctx context.Context, maddr var powerSmoothed smoothing.FilterEstimate if act, err := state.GetActor(power.Address); err != nil { return types.EmptyInt, xerrors.Errorf("loading miner actor: %w", err) - } else s, err := power.Load(store, act); err != nil { + } else if s, err := power.Load(store, act); err != nil { return types.EmptyInt, xerrors.Errorf("loading power actor state: %w", err) - } else p, err := s.TotalPowerSmoothed(); err != nil { + } else if p, err := s.TotalPowerSmoothed(); err != nil { return types.EmptyInt, xerrors.Errorf("failed to determine total power: %w", err) } else { powerSmoothed = p @@ -898,9 +891,9 @@ func (a *StateAPI) StateMinerPreCommitDepositForPower(ctx context.Context, maddr var rewardSmoothed smoothing.FilterEstimate if act, err := state.GetActor(reward.Address); err != nil { return types.EmptyInt, xerrors.Errorf("loading miner actor: %w", err) - } else s, err := reward.Load(store, act); err != nil { + } else if s, err := reward.Load(store, act); err != nil { return types.EmptyInt, xerrors.Errorf("loading reward actor state: %w", err) - } else r, err := s.RewardSmoothed(); err != nil { + } else if r, err := s.RewardSmoothed(); err != nil { return types.EmptyInt, xerrors.Errorf("failed to determine total reward: %w", err) } else { rewardSmoothed = r @@ -934,10 +927,10 @@ func (a *StateAPI) StateMinerInitialPledgeCollateral(ctx context.Context, maddr var sectorWeight abi.StoragePower if act, err := state.GetActor(market.Address); err != nil { return types.EmptyInt, xerrors.Errorf("loading miner actor %s: %w", maddr, err) - } else s, err := market.Load(store, act); err != nil { + } else if s, err := market.Load(store, act); err != nil { return types.EmptyInt, xerrors.Errorf("loading market actor state %s: %w", maddr, err) } else if w, vw, err := s.VerifyDealsForActivation(maddr, pci.DealIDs, ts.Height(), pci.Expiration); err != nil { - return types.EmptyInt, xerrors.Errorf("verifying deals for activation: %w", err) + return types.EmptyInt, xerrors.Errorf("verifying deals for activation: %w", err) } else { // NB: not exactly accurate, but should always lead us to *over* estimate, not under duration := pci.Expiration - ts.Height() @@ -947,16 +940,16 @@ func (a *StateAPI) StateMinerInitialPledgeCollateral(ctx context.Context, maddr } var ( - powerSmoothed smoothing.FilterEstimate + powerSmoothed smoothing.FilterEstimate pledgeCollerateral abi.TokenAmount ) if act, err := state.GetActor(power.Address); err != nil { return types.EmptyInt, xerrors.Errorf("loading miner actor: %w", err) - } else s, err := power.Load(store, act); err != nil { + } else if s, err := power.Load(store, act); err != nil { return types.EmptyInt, xerrors.Errorf("loading power actor state: %w", err) - } else p, err := s.TotalPowerSmoothed(); err != nil { + } else if p, err := s.TotalPowerSmoothed(); err != nil { return types.EmptyInt, xerrors.Errorf("failed to determine total power: %w", err) - } else c, err := s.TotalLocked(); err != nil { + } else if c, err := s.TotalLocked(); err != nil { return types.EmptyInt, xerrors.Errorf("failed to determine pledge collateral: %w", err) } else { powerSmoothed = p @@ -965,15 +958,15 @@ func (a *StateAPI) StateMinerInitialPledgeCollateral(ctx context.Context, maddr var ( rewardSmoothed smoothing.FilterEstimate - baselinePower abi.StoragePower + baselinePower abi.StoragePower ) if act, err := state.GetActor(reward.Address); err != nil { return types.EmptyInt, xerrors.Errorf("loading miner actor: %w", err) - } else s, err := reward.Load(store, act); err != nil { + } else if s, err := reward.Load(store, act); err != nil { return types.EmptyInt, xerrors.Errorf("loading reward actor state: %w", err) - } else r, err := s.RewardSmoothed(); err != nil { + } else if r, err := s.RewardSmoothed(); err != nil { return types.EmptyInt, xerrors.Errorf("failed to determine total reward: %w", err) - } else p, err := s.BaselinePower(); err != nil { + } else if p, err := s.BaselinePower(); err != nil { return types.EmptyInt, xerrors.Errorf("failed to determine baseline power: %w", err) } else { rewardSmoothed = r diff --git a/node/impl/storminer.go b/node/impl/storminer.go index 6eedc9f54..89dd7c2c2 100644 --- a/node/impl/storminer.go +++ b/node/impl/storminer.go @@ -305,8 +305,30 @@ func (sm *StorageMinerAPI) MarketImportDealData(ctx context.Context, propCid cid return sm.StorageProvider.ImportDataForDeal(ctx, propCid, fi) } -func (sm *StorageMinerAPI) MarketListDeals(ctx context.Context) ([]storagemarket.StorageDeal, error) { - return sm.StorageProvider.ListDeals(ctx) +func (sm *StorageMinerAPI) listDeals(ctx context.Context) ([]api.MarketDeal, error) { + ts, err := sm.Full.ChainHead(ctx) + if err != nil { + return nil, err + } + tsk := ts.Key() + allDeals, err := sm.Full.StateMarketDeals(ctx, tsk) + if err != nil { + return nil, err + } + + var out []api.MarketDeal + + for _, deal := range allDeals { + if deal.Proposal.Provider == sm.Miner.Address() { + out = append(out, deal) + } + } + + return out, nil +} + +func (sm *StorageMinerAPI) MarketListDeals(ctx context.Context) ([]api.MarketDeal, error) { + return sm.StorageProvider.listDeals(ctx) } func (sm *StorageMinerAPI) MarketListRetrievalDeals(ctx context.Context) ([]retrievalmarket.ProviderDealState, error) { @@ -395,8 +417,8 @@ func (sm *StorageMinerAPI) MarketDataTransferUpdates(ctx context.Context) (<-cha return channels, nil } -func (sm *StorageMinerAPI) DealsList(ctx context.Context) ([]storagemarket.StorageDeal, error) { - return sm.StorageProvider.ListDeals(ctx) +func (sm *StorageMinerAPI) DealsList(ctx context.Context) ([]api.MarketDeal, error) { + return sm.listDeals(ctx) } func (sm *StorageMinerAPI) RetrievalDealsList(ctx context.Context) (map[retrievalmarket.ProviderDealIdentifier]retrievalmarket.ProviderDealState, error) { diff --git a/storage/adapter_storage_miner.go b/storage/adapter_storage_miner.go index 8b64789ad..7dced4331 100644 --- a/storage/adapter_storage_miner.go +++ b/storage/adapter_storage_miner.go @@ -15,12 +15,13 @@ import ( "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/market" + v0market "github.com/filecoin-project/specs-actors/actors/builtin/market" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/api/apibstore" "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/actors" + "github.com/filecoin-project/lotus/chain/actors/builtin/market" "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/store" "github.com/filecoin-project/lotus/chain/types" @@ -136,7 +137,7 @@ func (s SealingAPIAdapter) StateComputeDataCommitment(ctx context.Context, maddr return cid.Undef, xerrors.Errorf("failed to unmarshal TipSetToken to TipSetKey: %w", err) } - ccparams, err := actors.SerializeParams(&market.ComputeDataCommitmentParams{ + ccparams, err := actors.SerializeParams(&v0market.ComputeDataCommitmentParams{ DealIDs: deals, SectorType: sectorType, }) From 7bf165c73a37025307619ea49ae8fc6aaa36b2b9 Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Thu, 17 Sep 2020 03:07:01 -0400 Subject: [PATCH 055/303] Remove miner-related specs actors types from API --- api/api_full.go | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/api/api_full.go b/api/api_full.go index f565ad543..e575c5bdd 100644 --- a/api/api_full.go +++ b/api/api_full.go @@ -25,7 +25,6 @@ import ( "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/specs-actors/actors/runtime/proof" - miner2 "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/actors/builtin/power" "github.com/filecoin-project/lotus/chain/types" marketevents "github.com/filecoin-project/lotus/markets/loggers" @@ -317,16 +316,16 @@ type FullNode interface { // StateMinerSectors returns info about the given miner's sectors. If the filter bitfield is nil, all sectors are included. // If the filterOut boolean is set to true, any sectors in the filter are excluded. // If false, only those sectors in the filter are included. - StateMinerSectors(context.Context, address.Address, *bitfield.BitField, bool, types.TipSetKey) ([]*miner2.ChainSectorInfo, error) + StateMinerSectors(context.Context, address.Address, *bitfield.BitField, bool, types.TipSetKey) ([]*miner.ChainSectorInfo, error) // StateMinerActiveSectors returns info about sectors that a given miner is actively proving. - StateMinerActiveSectors(context.Context, address.Address, types.TipSetKey) ([]*miner2.ChainSectorInfo, error) + StateMinerActiveSectors(context.Context, address.Address, types.TipSetKey) ([]*miner.ChainSectorInfo, error) // StateMinerProvingDeadline calculates the deadline at some epoch for a proving period // and returns the deadline-related calculations. StateMinerProvingDeadline(context.Context, address.Address, types.TipSetKey) (*dline.Info, error) // StateMinerPower returns the power of the indicated miner StateMinerPower(context.Context, address.Address, types.TipSetKey) (*MinerPower, error) // StateMinerInfo returns info about the indicated miner - StateMinerInfo(context.Context, address.Address, types.TipSetKey) (miner2.MinerInfo, error) + StateMinerInfo(context.Context, address.Address, types.TipSetKey) (miner.MinerInfo, error) // StateMinerFaults returns a bitfield indicating the faulty sectors of the given miner StateMinerFaults(context.Context, address.Address, types.TipSetKey) (bitfield.BitField, error) // StateAllMinerFaults returns all non-expired Faults that occur within lookback epochs of the given tipset From 053cfc1cc7f5935d616d19813862c3c38bde6cb8 Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Thu, 17 Sep 2020 03:48:39 -0400 Subject: [PATCH 056/303] Migrate verifreg actor --- api/api_full.go | 3 +-- api/apistruct/struct.go | 5 ++--- build/params_2k.go | 4 ++-- chain/gen/gen_test.go | 4 ++-- chain/gen/genesis/t06_vreg.go | 4 ++-- chain/stmgr/forks_test.go | 4 ++-- chain/stmgr/utils.go | 4 ++-- chain/store/store_test.go | 4 ++-- chain/sync_test.go | 4 ++-- chain/vectors/gen/main.go | 4 ++-- chain/vm/invoker.go | 4 ++-- cli/paych_test.go | 4 ++-- markets/storageadapter/provider.go | 7 ++++--- node/impl/full/state.go | 33 +++++++++++------------------- node/node_test.go | 4 ++-- 15 files changed, 41 insertions(+), 51 deletions(-) diff --git a/api/api_full.go b/api/api_full.go index e575c5bdd..d570da7de 100644 --- a/api/api_full.go +++ b/api/api_full.go @@ -22,7 +22,6 @@ import ( "github.com/filecoin-project/lotus/chain/actors/builtin/market" "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/specs-actors/actors/builtin/paych" - "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/specs-actors/actors/runtime/proof" "github.com/filecoin-project/lotus/chain/actors/builtin/power" @@ -382,7 +381,7 @@ type FullNode interface { // StateVerifiedClientStatus returns the data cap for the given address. // Returns nil if there is no entry in the data cap table for the // address. - StateVerifiedClientStatus(ctx context.Context, addr address.Address, tsk types.TipSetKey) (*verifreg.DataCap, error) + StateVerifiedClientStatus(ctx context.Context, addr address.Address, tsk types.TipSetKey) (abi.StoragePower, error) // StateDealProviderCollateralBounds returns the min and max collateral a storage provider // can issue. It takes the deal size and verified status as parameters. StateDealProviderCollateralBounds(context.Context, abi.PaddedPieceSize, bool, types.TipSetKey) (DealCollateralBounds, error) diff --git a/api/apistruct/struct.go b/api/apistruct/struct.go index 8bf8f1997..837400b65 100644 --- a/api/apistruct/struct.go +++ b/api/apistruct/struct.go @@ -30,7 +30,6 @@ import ( "github.com/filecoin-project/lotus/extern/sector-storage/storiface" marketevents "github.com/filecoin-project/lotus/markets/loggers" "github.com/filecoin-project/specs-actors/actors/builtin/paych" - "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/specs-storage/storage" "github.com/filecoin-project/lotus/api" @@ -197,7 +196,7 @@ type FullNodeStruct struct { StateMinerSectorCount func(context.Context, address.Address, types.TipSetKey) (api.MinerSectors, error) `perm:"read"` StateListMessages func(ctx context.Context, match *types.Message, tsk types.TipSetKey, toht abi.ChainEpoch) ([]cid.Cid, error) `perm:"read"` StateCompute func(context.Context, abi.ChainEpoch, []*types.Message, types.TipSetKey) (*api.ComputeStateOutput, error) `perm:"read"` - StateVerifiedClientStatus func(context.Context, address.Address, types.TipSetKey) (*verifreg.DataCap, error) `perm:"read"` + StateVerifiedClientStatus func(context.Context, address.Address, types.TipSetKey) (abi.StoragePower, error) `perm:"read"` StateDealProviderCollateralBounds func(context.Context, abi.PaddedPieceSize, bool, types.TipSetKey) (api.DealCollateralBounds, error) `perm:"read"` StateCirculatingSupply func(context.Context, types.TipSetKey) (api.CirculatingSupply, error) `perm:"read"` StateNetworkVersion func(context.Context, types.TipSetKey) (stnetwork.Version, error) `perm:"read"` @@ -864,7 +863,7 @@ func (c *FullNodeStruct) StateCompute(ctx context.Context, height abi.ChainEpoch return c.Internal.StateCompute(ctx, height, msgs, tsk) } -func (c *FullNodeStruct) StateVerifiedClientStatus(ctx context.Context, addr address.Address, tsk types.TipSetKey) (*verifreg.DataCap, error) { +func (c *FullNodeStruct) StateVerifiedClientStatus(ctx context.Context, addr address.Address, tsk types.TipSetKey) (abi.StoragePower, error) { return c.Internal.StateVerifiedClientStatus(ctx, addr, tsk) } diff --git a/build/params_2k.go b/build/params_2k.go index cf34706e5..9c8a591d1 100644 --- a/build/params_2k.go +++ b/build/params_2k.go @@ -7,7 +7,7 @@ import ( "github.com/filecoin-project/go-state-types/big" v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" - "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" ) const UpgradeBreezeHeight = -1 @@ -24,7 +24,7 @@ func init() { v0miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } - verifreg.MinVerifiedDealSize = big.NewInt(256) + v0verifreg.MinVerifiedDealSize = big.NewInt(256) BuildType |= Build2k } diff --git a/chain/gen/gen_test.go b/chain/gen/gen_test.go index 496bb016b..9d1262f77 100644 --- a/chain/gen/gen_test.go +++ b/chain/gen/gen_test.go @@ -7,7 +7,7 @@ import ( "github.com/filecoin-project/go-state-types/big" v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" - "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" _ "github.com/filecoin-project/lotus/lib/sigs/bls" _ "github.com/filecoin-project/lotus/lib/sigs/secp" @@ -18,7 +18,7 @@ func init() { abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } v0power.ConsensusMinerMinPower = big.NewInt(2048) - verifreg.MinVerifiedDealSize = big.NewInt(256) + v0verifreg.MinVerifiedDealSize = big.NewInt(256) } func testGeneration(t testing.TB, n int, msgs int, sectors int) { diff --git a/chain/gen/genesis/t06_vreg.go b/chain/gen/genesis/t06_vreg.go index 6636fa05f..d91cdf7b1 100644 --- a/chain/gen/genesis/t06_vreg.go +++ b/chain/gen/genesis/t06_vreg.go @@ -7,7 +7,7 @@ import ( cbor "github.com/ipfs/go-ipld-cbor" "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/filecoin-project/lotus/chain/types" @@ -34,7 +34,7 @@ func SetupVerifiedRegistryActor(bs bstore.Blockstore) (*types.Actor, error) { return nil, err } - sms := verifreg.ConstructState(h, RootVerifierID) + sms := v0verifreg.ConstructState(h, RootVerifierID) stcid, err := store.Put(store.Context(), sms) if err != nil { diff --git a/chain/stmgr/forks_test.go b/chain/stmgr/forks_test.go index 2db11e832..c4fb1b3be 100644 --- a/chain/stmgr/forks_test.go +++ b/chain/stmgr/forks_test.go @@ -13,7 +13,7 @@ import ( init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" - "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/specs-actors/actors/runtime" "golang.org/x/xerrors" @@ -37,7 +37,7 @@ func init() { abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } v0power.ConsensusMinerMinPower = big.NewInt(2048) - verifreg.MinVerifiedDealSize = big.NewInt(256) + v0verifreg.MinVerifiedDealSize = big.NewInt(256) } const testForkHeight = 40 diff --git a/chain/stmgr/utils.go b/chain/stmgr/utils.go index 38b66c512..b7c888a36 100644 --- a/chain/stmgr/utils.go +++ b/chain/stmgr/utils.go @@ -30,7 +30,7 @@ import ( v0msig "github.com/filecoin-project/specs-actors/actors/builtin/multisig" "github.com/filecoin-project/specs-actors/actors/builtin/paych" v0reward "github.com/filecoin-project/specs-actors/actors/builtin/reward" - "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" @@ -550,7 +550,7 @@ func init() { builtin.PaymentChannelActorCodeID: {builtin.MethodsPaych, paych.Actor{}}, builtin.MultisigActorCodeID: {builtin.MethodsMultisig, v0msig.Actor{}}, builtin.RewardActorCodeID: {builtin.MethodsReward, v0reward.Actor{}}, - builtin.VerifiedRegistryActorCodeID: {builtin.MethodsVerifiedRegistry, verifreg.Actor{}}, + builtin.VerifiedRegistryActorCodeID: {builtin.MethodsVerifiedRegistry, v0verifreg.Actor{}}, } for c, m := range cidToMethods { diff --git a/chain/store/store_test.go b/chain/store/store_test.go index 7da8d219d..83238a67d 100644 --- a/chain/store/store_test.go +++ b/chain/store/store_test.go @@ -12,7 +12,7 @@ import ( "github.com/filecoin-project/go-state-types/crypto" v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" - "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/lotus/chain/gen" "github.com/filecoin-project/lotus/chain/store" @@ -26,7 +26,7 @@ func init() { abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } v0power.ConsensusMinerMinPower = big.NewInt(2048) - verifreg.MinVerifiedDealSize = big.NewInt(256) + v0verifreg.MinVerifiedDealSize = big.NewInt(256) } func BenchmarkGetRandomness(b *testing.B) { diff --git a/chain/sync_test.go b/chain/sync_test.go index e8df32c56..d98663fb1 100644 --- a/chain/sync_test.go +++ b/chain/sync_test.go @@ -22,7 +22,7 @@ import ( "github.com/filecoin-project/go-state-types/big" v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" - "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" @@ -47,7 +47,7 @@ func init() { abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } v0power.ConsensusMinerMinPower = big.NewInt(2048) - verifreg.MinVerifiedDealSize = big.NewInt(256) + v0verifreg.MinVerifiedDealSize = big.NewInt(256) } const source = 0 diff --git a/chain/vectors/gen/main.go b/chain/vectors/gen/main.go index 4bf2c420e..36b770f03 100644 --- a/chain/vectors/gen/main.go +++ b/chain/vectors/gen/main.go @@ -19,14 +19,14 @@ import ( "github.com/filecoin-project/lotus/chain/types/mock" "github.com/filecoin-project/lotus/chain/vectors" "github.com/filecoin-project/lotus/chain/wallet" - "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" _ "github.com/filecoin-project/lotus/lib/sigs/bls" _ "github.com/filecoin-project/lotus/lib/sigs/secp" ) func init() { - verifreg.MinVerifiedDealSize = big.NewInt(2048) + v0verifreg.MinVerifiedDealSize = big.NewInt(2048) v0power.ConsensusMinerMinPower = big.NewInt(2048) } diff --git a/chain/vm/invoker.go b/chain/vm/invoker.go index 4cda32c44..b31b45767 100644 --- a/chain/vm/invoker.go +++ b/chain/vm/invoker.go @@ -8,7 +8,7 @@ import ( "github.com/filecoin-project/go-state-types/exitcode" "github.com/filecoin-project/specs-actors/actors/builtin/account" - "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/ipfs/go-cid" cbg "github.com/whyrusleeping/cbor-gen" @@ -55,7 +55,7 @@ func NewInvoker() *Invoker { inv.Register(builtin.StorageMinerActorCodeID, v0miner.Actor{}, v0miner.State{}) inv.Register(builtin.MultisigActorCodeID, v0msig.Actor{}, v0msig.State{}) inv.Register(builtin.PaymentChannelActorCodeID, paych.Actor{}, paych.State{}) - inv.Register(builtin.VerifiedRegistryActorCodeID, verifreg.Actor{}, verifreg.State{}) + inv.Register(builtin.VerifiedRegistryActorCodeID, v0verifreg.Actor{}, v0verifreg.State{}) inv.Register(builtin.AccountActorCodeID, account.Actor{}, account.State{}) return inv diff --git a/cli/paych_test.go b/cli/paych_test.go index 1cf95ef6c..598c178eb 100644 --- a/cli/paych_test.go +++ b/cli/paych_test.go @@ -17,7 +17,7 @@ import ( "github.com/filecoin-project/go-state-types/big" v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" - "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/multiformats/go-multiaddr" @@ -44,7 +44,7 @@ func init() { v0miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } - verifreg.MinVerifiedDealSize = big.NewInt(256) + v0verifreg.MinVerifiedDealSize = big.NewInt(256) } // TestPaymentChannels does a basic test to exercise the payment channel CLI diff --git a/markets/storageadapter/provider.go b/markets/storageadapter/provider.go index 98935b30a..fb93a1e72 100644 --- a/markets/storageadapter/provider.go +++ b/markets/storageadapter/provider.go @@ -8,6 +8,8 @@ import ( "io" "time" + "github.com/filecoin-project/go-state-types/big" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/ipfs/go-cid" @@ -22,7 +24,6 @@ import ( "github.com/filecoin-project/go-state-types/exitcode" "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin/market" - "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" @@ -361,10 +362,10 @@ func (n *ProviderNodeAdapter) WaitForMessage(ctx context.Context, mcid cid.Cid, return cb(receipt.Receipt.ExitCode, receipt.Receipt.Return, receipt.Message, nil) } -func (n *ProviderNodeAdapter) GetDataCap(ctx context.Context, addr address.Address, encodedTs shared.TipSetToken) (*verifreg.DataCap, error) { +func (n *ProviderNodeAdapter) GetDataCap(ctx context.Context, addr address.Address, encodedTs shared.TipSetToken) (abi.StoragePower, error) { tsk, err := types.TipSetKeyFromBytes(encodedTs) if err != nil { - return nil, err + return big.Zero(), err } return n.StateVerifiedClientStatus(ctx, addr, tsk) } diff --git a/node/impl/full/state.go b/node/impl/full/state.go index 241561a9f..a21f0cf80 100644 --- a/node/impl/full/state.go +++ b/node/impl/full/state.go @@ -6,9 +6,10 @@ import ( "errors" "strconv" - "github.com/filecoin-project/go-state-types/network" + "github.com/filecoin-project/lotus/chain/actors/builtin/verifreg" "github.com/filecoin-project/go-state-types/dline" + "github.com/filecoin-project/go-state-types/network" cid "github.com/ipfs/go-cid" cbor "github.com/ipfs/go-ipld-cbor" @@ -23,7 +24,6 @@ import ( "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" "github.com/filecoin-project/specs-actors/actors/builtin" v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/filecoin-project/specs-actors/actors/util/smoothing" @@ -1018,40 +1018,31 @@ func (a *StateAPI) StateMinerAvailableBalance(ctx context.Context, maddr address } // StateVerifiedClientStatus returns the data cap for the given address. -// Returns nil if there is no entry in the data cap table for the +// Returns zero if there is no entry in the data cap table for the // address. -func (a *StateAPI) StateVerifiedClientStatus(ctx context.Context, addr address.Address, tsk types.TipSetKey) (*verifreg.DataCap, error) { +func (a *StateAPI) StateVerifiedClientStatus(ctx context.Context, addr address.Address, tsk types.TipSetKey) (abi.StoragePower, error) { act, err := a.StateGetActor(ctx, builtin.VerifiedRegistryActorAddr, tsk) if err != nil { - return nil, err + return big.Zero(), err } aid, err := a.StateLookupID(ctx, addr, tsk) if err != nil { log.Warnf("lookup failure %v", err) - return nil, err + return big.Zero(), err } - store := a.StateManager.ChainStore().Store(ctx) - - var st verifreg.State - if err := store.Get(ctx, act.Head, &st); err != nil { - return nil, err - } - - vh, err := adt.AsMap(store, st.VerifiedClients) + vrs, err := verifreg.Load(a.StateManager.ChainStore().Store(ctx), act) if err != nil { - return nil, err + return big.Zero(), xerrors.Errorf("failed to load verified registry state: %w", err) } - var dcap verifreg.DataCap - if found, err := vh.Get(abi.AddrKey(aid), &dcap); err != nil { - return nil, err - } else if !found { - return nil, nil + _, dcap, err := vrs.VerifiedClientDataCap(aid) + if err != nil { + return big.Zero(), xerrors.Errorf("looking up verified client: %w", err) } - return &dcap, nil + return dcap, nil } var dealProviderCollateralNum = types.NewInt(110) diff --git a/node/node_test.go b/node/node_test.go index 92b741f73..68ee178fc 100644 --- a/node/node_test.go +++ b/node/node_test.go @@ -12,7 +12,7 @@ import ( "github.com/filecoin-project/lotus/lib/lotuslog" v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" - "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" logging "github.com/ipfs/go-log/v2" "github.com/filecoin-project/lotus/api/test" @@ -25,7 +25,7 @@ func init() { v0miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } - verifreg.MinVerifiedDealSize = big.NewInt(256) + v0verifreg.MinVerifiedDealSize = big.NewInt(256) } func TestAPI(t *testing.T) { From 31ff5230bbf3506bc69f86c0f30daa53e01c7867 Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Thu, 17 Sep 2020 04:17:14 -0400 Subject: [PATCH 057/303] Get State API almost working --- api/api_full.go | 2 + api/apistruct/struct.go | 5 + chain/actors/builtin/miner/miner.go | 3 + chain/actors/builtin/miner/v0.go | 8 ++ chain/actors/builtin/reward/reward.go | 4 +- chain/actors/builtin/reward/v0.go | 12 +- chain/actors/builtin/verifreg/v0.go | 37 ++++++ chain/actors/builtin/verifreg/verifreg.go | 34 ++++++ chain/stmgr/read.go | 1 + chain/stmgr/stmgr.go | 2 +- chain/stmgr/utils.go | 12 +- chain/sub/incoming.go | 1 - cli/client.go | 8 +- cmd/lotus-storage-miner/proving.go | 10 +- markets/storageadapter/provider.go | 10 +- node/impl/full/state.go | 136 +++++++++++++--------- node/impl/storminer.go | 2 +- storage/adapter_storage_miner.go | 4 +- storage/addresses.go | 5 +- storage/miner.go | 2 +- storage/wdpost_sched.go | 2 - 21 files changed, 215 insertions(+), 85 deletions(-) create mode 100644 chain/actors/builtin/verifreg/v0.go create mode 100644 chain/actors/builtin/verifreg/verifreg.go diff --git a/api/api_full.go b/api/api_full.go index d570da7de..1adcc5c19 100644 --- a/api/api_full.go +++ b/api/api_full.go @@ -325,6 +325,8 @@ type FullNode interface { StateMinerPower(context.Context, address.Address, types.TipSetKey) (*MinerPower, error) // StateMinerInfo returns info about the indicated miner StateMinerInfo(context.Context, address.Address, types.TipSetKey) (miner.MinerInfo, error) + // StateMinerDeadlines returns all the proving deadlines for the given miner + StateMinerDeadlines(context.Context, address.Address, types.TipSetKey) ([]*miner.Deadline, error) // StateMinerFaults returns a bitfield indicating the faulty sectors of the given miner StateMinerFaults(context.Context, address.Address, types.TipSetKey) (bitfield.BitField, error) // StateAllMinerFaults returns all non-expired Faults that occur within lookback epochs of the given tipset diff --git a/api/apistruct/struct.go b/api/apistruct/struct.go index 837400b65..ab86d7819 100644 --- a/api/apistruct/struct.go +++ b/api/apistruct/struct.go @@ -167,6 +167,7 @@ type FullNodeStruct struct { StateMinerProvingDeadline func(context.Context, address.Address, types.TipSetKey) (*dline.Info, error) `perm:"read"` StateMinerPower func(context.Context, address.Address, types.TipSetKey) (*api.MinerPower, error) `perm:"read"` StateMinerInfo func(context.Context, address.Address, types.TipSetKey) (miner.MinerInfo, error) `perm:"read"` + StateMinerDeadlines func(context.Context, address.Address, types.TipSetKey) ([]*miner.Deadline, error) `perm:"read"` StateMinerFaults func(context.Context, address.Address, types.TipSetKey) (bitfield.BitField, error) `perm:"read"` StateAllMinerFaults func(context.Context, abi.ChainEpoch, types.TipSetKey) ([]*api.Fault, error) `perm:"read"` StateMinerRecoveries func(context.Context, address.Address, types.TipSetKey) (bitfield.BitField, error) `perm:"read"` @@ -751,6 +752,10 @@ func (c *FullNodeStruct) StateMinerInfo(ctx context.Context, actor address.Addre return c.Internal.StateMinerInfo(ctx, actor, tsk) } +func (c *FullNodeStruct) StateMinerDeadlines(ctx context.Context, actor address.Address, tsk types.TipSetKey) ([]*miner.Deadline, error) { + return c.Internal.StateMinerDeadlines(ctx, actor, tsk) +} + func (c *FullNodeStruct) StateMinerFaults(ctx context.Context, actor address.Address, tsk types.TipSetKey) (bitfield.BitField, error) { return c.Internal.StateMinerFaults(ctx, actor, tsk) } diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index 4acb41dae..725c5f2ff 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -34,6 +34,9 @@ func Load(store adt.Store, act *types.Actor) (st State, err error) { type State interface { cbor.Marshaler + AvailableBalance(abi.TokenAmount) (abi.TokenAmount, error) + VestedFunds(abi.ChainEpoch) (abi.TokenAmount, error) + GetSector(abi.SectorNumber) (*SectorOnChainInfo, error) FindSector(abi.SectorNumber) (*SectorLocation, error) GetSectorExpiration(abi.SectorNumber) (*SectorExpiration, error) diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index b56fb1745..cbe42b3da 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -31,6 +31,14 @@ type v0Partition struct { store adt.Store } +func (s *v0State) AvailableBalance(bal abi.TokenAmount) (abi.TokenAmount, error) { + return s.GetAvailableBalance(bal), nil +} + +func (s *v0State) VestedFunds(epoch abi.ChainEpoch) (abi.TokenAmount, error) { + return s.CheckVestedFunds(s.store, epoch) +} + func (s *v0State) GetSector(num abi.SectorNumber) (*SectorOnChainInfo, error) { info, ok, err := s.State.GetSector(s.store, num) if !ok || err != nil { diff --git a/chain/actors/builtin/reward/reward.go b/chain/actors/builtin/reward/reward.go index d400258df..9093b33c6 100644 --- a/chain/actors/builtin/reward/reward.go +++ b/chain/actors/builtin/reward/reward.go @@ -31,5 +31,7 @@ type State interface { cbor.Marshaler RewardSmoothed() (builtin.FilterEstimate, error) - TotalStoragePowerReward() abi.TokenAmount + EffectiveBaselinePower() (abi.StoragePower, error) + ThisEpochBaselinePower() (abi.StoragePower, error) + TotalStoragePowerReward() (abi.TokenAmount, error) } diff --git a/chain/actors/builtin/reward/v0.go b/chain/actors/builtin/reward/v0.go index b0558f0ae..16ac2b071 100644 --- a/chain/actors/builtin/reward/v0.go +++ b/chain/actors/builtin/reward/v0.go @@ -16,6 +16,14 @@ func (s *v0State) RewardSmoothed() (builtin.FilterEstimate, error) { return *s.State.ThisEpochRewardSmoothed, nil } -func (s *v0State) TotalStoragePowerReward() abi.TokenAmount { - return s.State.TotalMined +func (s *v0State) TotalStoragePowerReward() (abi.TokenAmount, error) { + return s.State.TotalMined, nil +} + +func (s *v0State) EffectiveBaselinePower() (abi.StoragePower, error) { + return s.State.EffectiveBaselinePower, nil +} + +func (s *v0State) ThisEpochBaselinePower() (abi.StoragePower, error) { + return s.State.ThisEpochBaselinePower, nil } diff --git a/chain/actors/builtin/verifreg/v0.go b/chain/actors/builtin/verifreg/v0.go new file mode 100644 index 000000000..cbaf4d236 --- /dev/null +++ b/chain/actors/builtin/verifreg/v0.go @@ -0,0 +1,37 @@ +package verifreg + +import ( + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/big" + v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + v0adt "github.com/filecoin-project/specs-actors/actors/util/adt" + "golang.org/x/xerrors" + + "github.com/filecoin-project/lotus/chain/actors/adt" +) + +type v0State struct { + v0verifreg.State + store adt.Store +} + +func (s *v0State) VerifiedClientDataCap(addr address.Address) (bool, abi.StoragePower, error) { + if addr.Protocol() != address.ID { + return false, big.Zero(), xerrors.Errorf("can only look up ID addresses") + } + + vh, err := v0adt.AsMap(s.store, s.VerifiedClients) + if err != nil { + return false, big.Zero(), xerrors.Errorf("loading verified clients: %w", err) + } + + var dcap abi.StoragePower + if found, err := vh.Get(abi.AddrKey(addr), &dcap); err != nil { + return false, big.Zero(), xerrors.Errorf("looking up verified clients: %w", err) + } else if !found { + return false, big.Zero(), nil + } + + return true, dcap, nil +} diff --git a/chain/actors/builtin/verifreg/verifreg.go b/chain/actors/builtin/verifreg/verifreg.go new file mode 100644 index 000000000..4cb5bb55b --- /dev/null +++ b/chain/actors/builtin/verifreg/verifreg.go @@ -0,0 +1,34 @@ +package verifreg + +import ( + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + "golang.org/x/xerrors" + + "github.com/filecoin-project/go-state-types/cbor" + v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" + + "github.com/filecoin-project/lotus/chain/actors/adt" + "github.com/filecoin-project/lotus/chain/types" +) + +var Address = v0builtin.VerifiedRegistryActorAddr + +func Load(store adt.Store, act *types.Actor) (State, error) { + switch act.Code { + case v0builtin.VerifiedRegistryActorCodeID: + out := v0State{store: store} + err := store.Get(store.Context(), act.Head, &out) + if err != nil { + return nil, err + } + return &out, nil + } + return nil, xerrors.Errorf("unknown actor code %s", act.Code) +} + +type State interface { + cbor.Marshaler + + VerifiedClientDataCap(address.Address) (bool, abi.StoragePower, error) +} diff --git a/chain/stmgr/read.go b/chain/stmgr/read.go index 53eb8d384..9a9b80265 100644 --- a/chain/stmgr/read.go +++ b/chain/stmgr/read.go @@ -2,6 +2,7 @@ package stmgr import ( "context" + "golang.org/x/xerrors" "github.com/ipfs/go-cid" diff --git a/chain/stmgr/stmgr.go b/chain/stmgr/stmgr.go index 2a6737e2c..89ad6edd9 100644 --- a/chain/stmgr/stmgr.go +++ b/chain/stmgr/stmgr.go @@ -1029,7 +1029,7 @@ func GetFilMined(ctx context.Context, st *state.StateTree) (abi.TokenAmount, err return big.Zero(), xerrors.Errorf("failed to load reward state: %w", err) } - return rst.TotalStoragePowerReward(), nil + return rst.TotalStoragePowerReward() } func getFilMarketLocked(ctx context.Context, st *state.StateTree) (abi.TokenAmount, error) { diff --git a/chain/stmgr/utils.go b/chain/stmgr/utils.go index b7c888a36..4fabefbff 100644 --- a/chain/stmgr/utils.go +++ b/chain/stmgr/utils.go @@ -9,6 +9,10 @@ import ( "runtime" "strings" + v0init "github.com/filecoin-project/specs-actors/actors/builtin/init" + v0market "github.com/filecoin-project/specs-actors/actors/builtin/market" + v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" saruntime "github.com/filecoin-project/specs-actors/actors/runtime" @@ -541,12 +545,12 @@ var MethodsMap = map[cid.Cid]map[abi.MethodNum]MethodMeta{} func init() { cidToMethods := map[cid.Cid][2]interface{}{ // builtin.SystemActorCodeID: {builtin.MethodsSystem, system.Actor{} }- apparently it doesn't have methods - builtin.InitActorCodeID: {builtin.MethodsInit, init_.Actor{}}, + builtin.InitActorCodeID: {builtin.MethodsInit, v0init.Actor{}}, builtin.CronActorCodeID: {builtin.MethodsCron, cron.Actor{}}, builtin.AccountActorCodeID: {builtin.MethodsAccount, account.Actor{}}, - builtin.StoragePowerActorCodeID: {builtin.MethodsPower, power.Actor{}}, - builtin.StorageMinerActorCodeID: {builtin.MethodsMiner, miner.Actor{}}, - builtin.StorageMarketActorCodeID: {builtin.MethodsMarket, market.Actor{}}, + builtin.StoragePowerActorCodeID: {builtin.MethodsPower, v0power.Actor{}}, + builtin.StorageMinerActorCodeID: {builtin.MethodsMiner, v0miner.Actor{}}, + builtin.StorageMarketActorCodeID: {builtin.MethodsMarket, v0market.Actor{}}, builtin.PaymentChannelActorCodeID: {builtin.MethodsPaych, paych.Actor{}}, builtin.MultisigActorCodeID: {builtin.MethodsMultisig, v0msig.Actor{}}, builtin.RewardActorCodeID: {builtin.MethodsReward, v0reward.Actor{}}, diff --git a/chain/sub/incoming.go b/chain/sub/incoming.go index 1af5d8188..c6e0c8b80 100644 --- a/chain/sub/incoming.go +++ b/chain/sub/incoming.go @@ -1,7 +1,6 @@ package sub import ( - "bytes" "context" "errors" "fmt" diff --git a/cli/client.go b/cli/client.go index eda5ffae8..f6d529943 100644 --- a/cli/client.go +++ b/cli/client.go @@ -33,9 +33,9 @@ import ( "github.com/filecoin-project/lotus/api" lapi "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" + "github.com/filecoin-project/lotus/chain/actors/builtin/market" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/lib/tablewriter" - "github.com/filecoin-project/lotus/chain/actors/builtin/market" ) var CidBaseFlag = cli.StringFlag{ @@ -417,7 +417,7 @@ var clientDealCmd = &cli.Command{ return err } - isVerified := dcap != nil + isVerified := dcap != types.EmptyInt // If the user has explicitly set the --verified-deal flag if cctx.IsSet("verified-deal") { @@ -1044,8 +1044,8 @@ var clientListDeals = &cli.Command{ func dealFromDealInfo(ctx context.Context, full api.FullNode, head *types.TipSet, v api.DealInfo) deal { if v.DealID == 0 { return deal{ - LocalDeal: v, - OnChainDealState: *market.EmptyDealState() + LocalDeal: v, + OnChainDealState: *market.EmptyDealState(), } } diff --git a/cmd/lotus-storage-miner/proving.go b/cmd/lotus-storage-miner/proving.go index d9bf81376..d3e213752 100644 --- a/cmd/lotus-storage-miner/proving.go +++ b/cmd/lotus-storage-miner/proving.go @@ -74,7 +74,7 @@ var provingFaultsCmd = &cli.Command{ _, _ = fmt.Fprintln(tw, "deadline\tpartition\tsectors") err = mas.ForEachDeadline(func(dlIdx uint64, dl miner.Deadline) error { dl.ForEachPartition(func(partIdx uint64, part miner.Partition) error { - faults, err := part.Faults() + faults, err := part.FaultySectors() if err != nil { return err } @@ -158,7 +158,7 @@ var provingInfoCmd = &cli.Command{ } } - if bf, err := part.Faults(); err != nil { + if bf, err := part.FaultySectors(); err != nil { return err } else if count, err := bf.Count(); err != nil { return err @@ -166,7 +166,7 @@ var provingInfoCmd = &cli.Command{ faults += count } - if bf, err := part.Recovering(); err != nil { + if bf, err := part.RecoveringSectors(); err != nil { return err } else if count, err := bf.Count(); err != nil { return err @@ -286,14 +286,14 @@ var provingDeadlinesCmd = &cli.Command{ faults := uint64(0) for _, partition := range partitions { - sc, err := partition.Sectors.Count() + sc, err := partition.AllSectors.Count() if err != nil { return err } sectors += sc - fc, err := partition.Faults.Count() + fc, err := partition.FaultySectors.Count() if err != nil { return err } diff --git a/markets/storageadapter/provider.go b/markets/storageadapter/provider.go index fb93a1e72..90bf28b41 100644 --- a/markets/storageadapter/provider.go +++ b/markets/storageadapter/provider.go @@ -8,8 +8,6 @@ import ( "io" "time" - "github.com/filecoin-project/go-state-types/big" - "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/ipfs/go-cid" @@ -362,12 +360,14 @@ func (n *ProviderNodeAdapter) WaitForMessage(ctx context.Context, mcid cid.Cid, return cb(receipt.Receipt.ExitCode, receipt.Receipt.Return, receipt.Message, nil) } -func (n *ProviderNodeAdapter) GetDataCap(ctx context.Context, addr address.Address, encodedTs shared.TipSetToken) (abi.StoragePower, error) { +func (n *ProviderNodeAdapter) GetDataCap(ctx context.Context, addr address.Address, encodedTs shared.TipSetToken) (*abi.StoragePower, error) { tsk, err := types.TipSetKeyFromBytes(encodedTs) if err != nil { - return big.Zero(), err + return nil, err } - return n.StateVerifiedClientStatus(ctx, addr, tsk) + + sp, err := n.StateVerifiedClientStatus(ctx, addr, tsk) + return &sp, err } func (n *ProviderNodeAdapter) OnDealExpiredOrSlashed(ctx context.Context, dealID abi.DealID, onDealExpired storagemarket.DealExpiredCallback, onDealSlashed storagemarket.DealSlashedCallback) error { diff --git a/node/impl/full/state.go b/node/impl/full/state.go index a21f0cf80..48f9d503c 100644 --- a/node/impl/full/state.go +++ b/node/impl/full/state.go @@ -6,6 +6,8 @@ import ( "errors" "strconv" + v0market "github.com/filecoin-project/specs-actors/actors/builtin/market" + "github.com/filecoin-project/lotus/chain/actors/builtin/verifreg" "github.com/filecoin-project/go-state-types/dline" @@ -73,6 +75,11 @@ func (a *StateAPI) StateMinerSectors(ctx context.Context, addr address.Address, } func (a *StateAPI) StateMinerActiveSectors(ctx context.Context, maddr address.Address, tsk types.TipSetKey) ([]*miner.ChainSectorInfo, error) { // TODO: only used in cli + ts, err := a.Chain.GetTipSetFromKey(tsk) + if err != nil { + return nil, xerrors.Errorf("loading tipset %s: %w", tsk, err) + } + act, err := a.StateManager.LoadActorTsk(ctx, maddr, tsk) if err != nil { return nil, xerrors.Errorf("failed to load miner actor: %w", err) @@ -88,7 +95,7 @@ func (a *StateAPI) StateMinerActiveSectors(ctx context.Context, maddr address.Ad return nil, xerrors.Errorf("merge partition active sets: %w", err) } - return mas.LoadSectorsFromSet(&activeSectors, false) + return stmgr.GetMinerSectorSet(ctx, a.StateManager, ts, maddr, &activeSectors, false) } func (a *StateAPI) StateMinerInfo(ctx context.Context, actor address.Address, tsk types.TipSetKey) (miner.MinerInfo, error) { @@ -105,7 +112,7 @@ func (a *StateAPI) StateMinerInfo(ctx context.Context, actor address.Address, ts return mas.Info() } -func (a *StateAPI) StateMinerDeadlines(ctx context.Context, m address.Address, tsk types.TipSetKey) ([]miner.Deadline, error) { +func (a *StateAPI) StateMinerDeadlines(ctx context.Context, m address.Address, tsk types.TipSetKey) ([]*miner.Deadline, error) { act, err := a.StateManager.LoadActorTsk(ctx, m, tsk) if err != nil { return nil, xerrors.Errorf("failed to load miner actor: %w", err) @@ -121,9 +128,9 @@ func (a *StateAPI) StateMinerDeadlines(ctx context.Context, m address.Address, t return nil, xerrors.Errorf("getting deadline count: %w", err) } - out := make([]miner.Deadline, deadlines) + out := make([]*miner.Deadline, deadlines) if err := mas.ForEachDeadline(func(i uint64, dl miner.Deadline) error { - out[i] = dl + out[i] = &dl return nil }); err != nil { return nil, err @@ -671,12 +678,18 @@ func (a *StateAPI) StateMinerSectorCount(ctx context.Context, addr address.Addre return api.MinerSectors{Live: liveCount, Active: activeCount, Faulty: faultyCount}, nil } -func (a *StateAPI) StateSectorPreCommitInfo(ctx context.Context, maddr address.Address, n abi.SectorNumber, tsk types.TipSetKey) (*miner.SectorPreCommitOnChainInfo, error) { +func (a *StateAPI) StateSectorPreCommitInfo(ctx context.Context, maddr address.Address, n abi.SectorNumber, tsk types.TipSetKey) (miner.SectorPreCommitOnChainInfo, error) { ts, err := a.Chain.GetTipSetFromKey(tsk) if err != nil { - return nil, xerrors.Errorf("loading tipset %s: %w", tsk, err) + return miner.SectorPreCommitOnChainInfo{}, xerrors.Errorf("loading tipset %s: %w", tsk, err) } - return stmgr.PreCommitInfo(ctx, a.StateManager, maddr, n, ts) + + pci, err := stmgr.PreCommitInfo(ctx, a.StateManager, maddr, n, ts) + if err != nil { + return miner.SectorPreCommitOnChainInfo{}, err + } + + return *pci, err } func (a *StateAPI) StateSectorGetInfo(ctx context.Context, maddr address.Address, n abi.SectorNumber, tsk types.TipSetKey) (*miner.SectorOnChainInfo, error) { @@ -873,7 +886,7 @@ func (a *StateAPI) StateMinerPreCommitDepositForPower(ctx context.Context, maddr // NB: not exactly accurate, but should always lead us to *over* estimate, not under duration := pci.Expiration - ts.Height() - // TODO: handle changes to this function across actor upgrades. + // TODO: ActorUpgrade sectorWeight = v0miner.QAPowerForWeight(ssize, duration, w, vw) } @@ -899,8 +912,8 @@ func (a *StateAPI) StateMinerPreCommitDepositForPower(ctx context.Context, maddr rewardSmoothed = r } - // TODO: abstract over network upgrades. - deposit := v0miner.PreCommitDepositForPower(rewardSmoothed, powerSmoothed, sectorWeight) + // TODO: ActorUpgrade + deposit := v0miner.PreCommitDepositForPower(&rewardSmoothed, &powerSmoothed, sectorWeight) return types.BigDiv(types.BigMul(deposit, initialPledgeNum), initialPledgeDen), nil } @@ -940,8 +953,8 @@ func (a *StateAPI) StateMinerInitialPledgeCollateral(ctx context.Context, maddr } var ( - powerSmoothed smoothing.FilterEstimate - pledgeCollerateral abi.TokenAmount + powerSmoothed smoothing.FilterEstimate + pledgeCollateral abi.TokenAmount ) if act, err := state.GetActor(power.Address); err != nil { return types.EmptyInt, xerrors.Errorf("loading miner actor: %w", err) @@ -966,26 +979,26 @@ func (a *StateAPI) StateMinerInitialPledgeCollateral(ctx context.Context, maddr return types.EmptyInt, xerrors.Errorf("loading reward actor state: %w", err) } else if r, err := s.RewardSmoothed(); err != nil { return types.EmptyInt, xerrors.Errorf("failed to determine total reward: %w", err) - } else if p, err := s.BaselinePower(); err != nil { + } else if p, err := s.ThisEpochBaselinePower(); err != nil { return types.EmptyInt, xerrors.Errorf("failed to determine baseline power: %w", err) } else { rewardSmoothed = r baselinePower = p } - // TODO: abstract over network upgrades. - circSupply, err := a.StateCirculatingSupply(ctx, ts.Key()) if err != nil { return big.Zero(), xerrors.Errorf("getting circulating supply: %w", err) } - initialPledge := miner.InitialPledgeForPower( + // TODO: ActorUpgrade + + initialPledge := v0miner.InitialPledgeForPower( sectorWeight, baselinePower, pledgeCollateral, - rewardSmoothed, - powerSmoothed, + &rewardSmoothed, + &powerSmoothed, circSupply.FilCirculating, ) @@ -998,23 +1011,27 @@ func (a *StateAPI) StateMinerAvailableBalance(ctx context.Context, maddr address return types.EmptyInt, xerrors.Errorf("loading tipset %s: %w", tsk, err) } - var act *types.Actor - var mas miner.State - - if err := a.StateManager.WithParentState(ts, a.StateManager.WithActor(maddr, func(actor *types.Actor) error { - act = actor - return a.StateManager.WithActorState(ctx, &mas)(actor) - })); err != nil { - return types.BigInt{}, xerrors.Errorf("getting miner state: %w", err) + act, err := a.StateManager.LoadActor(ctx, maddr, ts) + if err != nil { + return types.EmptyInt, xerrors.Errorf("failed to load miner actor: %w", err) } - as := store.ActorStore(ctx, a.Chain.Blockstore()) - vested, err := mas.CheckVestedFunds(as, ts.Height()) + mas, err := miner.Load(a.StateManager.ChainStore().Store(ctx), act) + if err != nil { + return types.EmptyInt, xerrors.Errorf("failed to load miner actor state: %w", err) + } + + vested, err := mas.VestedFunds(ts.Height()) if err != nil { return types.EmptyInt, err } - return types.BigAdd(mas.GetAvailableBalance(act.Balance), vested), nil + abal, err := mas.AvailableBalance(act.Balance) + if err != nil { + return types.EmptyInt, err + } + + return types.BigAdd(abal, vested), nil } // StateVerifiedClientStatus returns the data cap for the given address. @@ -1023,23 +1040,23 @@ func (a *StateAPI) StateMinerAvailableBalance(ctx context.Context, maddr address func (a *StateAPI) StateVerifiedClientStatus(ctx context.Context, addr address.Address, tsk types.TipSetKey) (abi.StoragePower, error) { act, err := a.StateGetActor(ctx, builtin.VerifiedRegistryActorAddr, tsk) if err != nil { - return big.Zero(), err + return types.EmptyInt, err } aid, err := a.StateLookupID(ctx, addr, tsk) if err != nil { log.Warnf("lookup failure %v", err) - return big.Zero(), err + return types.EmptyInt, err } vrs, err := verifreg.Load(a.StateManager.ChainStore().Store(ctx), act) if err != nil { - return big.Zero(), xerrors.Errorf("failed to load verified registry state: %w", err) + return types.EmptyInt, xerrors.Errorf("failed to load verified registry state: %w", err) } _, dcap, err := vrs.VerifiedClientDataCap(aid) if err != nil { - return big.Zero(), xerrors.Errorf("looking up verified client: %w", err) + return types.EmptyInt, xerrors.Errorf("looking up verified client: %w", err) } return dcap, nil @@ -1056,23 +1073,24 @@ func (a *StateAPI) StateDealProviderCollateralBounds(ctx context.Context, size a return api.DealCollateralBounds{}, xerrors.Errorf("loading tipset %s: %w", tsk, err) } - var powerState power.State - var rewardState reward.State - - err = a.StateManager.WithParentStateTsk(ts.Key(), func(state *state.StateTree) error { - if err := a.StateManager.WithActor(builtin.StoragePowerActorAddr, a.StateManager.WithActorState(ctx, &powerState))(state); err != nil { - return xerrors.Errorf("getting power state: %w", err) - } - - if err := a.StateManager.WithActor(builtin.RewardActorAddr, a.StateManager.WithActorState(ctx, &rewardState))(state); err != nil { - return xerrors.Errorf("getting reward state: %w", err) - } - - return nil - }) - + pact, err := a.StateGetActor(ctx, builtin.StoragePowerActorAddr, tsk) if err != nil { - return api.DealCollateralBounds{}, xerrors.Errorf("getting power and reward actor states: %w", err) + return api.DealCollateralBounds{}, xerrors.Errorf("failed to load power actor: %w", err) + } + + ract, err := a.StateGetActor(ctx, builtin.RewardActorAddr, tsk) + if err != nil { + return api.DealCollateralBounds{}, xerrors.Errorf("failed to load reward actor: %w", err) + } + + pst, err := power.Load(a.StateManager.ChainStore().Store(ctx), pact) + if err != nil { + return api.DealCollateralBounds{}, xerrors.Errorf("failed to load power actor state: %w", err) + } + + rst, err := reward.Load(a.StateManager.ChainStore().Store(ctx), ract) + if err != nil { + return api.DealCollateralBounds{}, xerrors.Errorf("failed to load reward actor state: %w", err) } circ, err := a.StateCirculatingSupply(ctx, ts.Key()) @@ -1080,11 +1098,21 @@ func (a *StateAPI) StateDealProviderCollateralBounds(ctx context.Context, size a return api.DealCollateralBounds{}, xerrors.Errorf("getting total circulating supply: %w", err) } - min, max := market.DealProviderCollateralBounds(size, + powClaim, err := pst.TotalPower() + if err != nil { + return api.DealCollateralBounds{}, xerrors.Errorf("getting total power: %w", err) + } + + rewPow, err := rst.ThisEpochBaselinePower() + if err != nil { + return api.DealCollateralBounds{}, xerrors.Errorf("getting reward baseline power: %w", err) + } + + min, max := v0market.DealProviderCollateralBounds(size, verified, - powerState.TotalRawBytePower, - powerState.ThisEpochQualityAdjPower, - rewardState.ThisEpochBaselinePower, + powClaim.RawBytePower, + powClaim.QualityAdjPower, + rewPow, circ.FilCirculating, a.StateManager.GetNtwkVersion(ctx, ts.Height())) return api.DealCollateralBounds{ @@ -1109,7 +1137,7 @@ func (a *StateAPI) StateCirculatingSupply(ctx context.Context, tsk types.TipSetK func (a *StateAPI) StateNetworkVersion(ctx context.Context, tsk types.TipSetKey) (network.Version, error) { ts, err := a.Chain.GetTipSetFromKey(tsk) if err != nil { - return -1, xerrors.Errorf("loading tipset %s: %w", tsk, err) + return network.VersionMax, xerrors.Errorf("loading tipset %s: %w", tsk, err) } return a.StateManager.GetNtwkVersion(ctx, ts.Height()), nil diff --git a/node/impl/storminer.go b/node/impl/storminer.go index 89dd7c2c2..5634c140b 100644 --- a/node/impl/storminer.go +++ b/node/impl/storminer.go @@ -328,7 +328,7 @@ func (sm *StorageMinerAPI) listDeals(ctx context.Context) ([]api.MarketDeal, err } func (sm *StorageMinerAPI) MarketListDeals(ctx context.Context) ([]api.MarketDeal, error) { - return sm.StorageProvider.listDeals(ctx) + return sm.listDeals(ctx) } func (sm *StorageMinerAPI) MarketListRetrievalDeals(ctx context.Context) ([]retrievalmarket.ProviderDealState, error) { diff --git a/storage/adapter_storage_miner.go b/storage/adapter_storage_miner.go index 7dced4331..8db977d2c 100644 --- a/storage/adapter_storage_miner.go +++ b/storage/adapter_storage_miner.go @@ -84,7 +84,7 @@ func (s SealingAPIAdapter) StateMinerWorkerAddress(ctx context.Context, maddr ad return mi.Worker, nil } -func (s SealingAPIAdapter) StateMinerDeadlines(ctx context.Context, maddr address.Address, tok sealing.TipSetToken) ([]miner.Deadline, error) { +func (s SealingAPIAdapter) StateMinerDeadlines(ctx context.Context, maddr address.Address, tok sealing.TipSetToken) ([]*miner.Deadline, error) { tsk, err := types.TipSetKeyFromBytes(tok) if err != nil { return nil, xerrors.Errorf("failed to unmarshal TipSetToken to TipSetKey: %w", err) @@ -251,7 +251,7 @@ func (s SealingAPIAdapter) StateMarketStorageDeal(ctx context.Context, dealID ab func (s SealingAPIAdapter) StateNetworkVersion(ctx context.Context, tok sealing.TipSetToken) (network.Version, error) { tsk, err := types.TipSetKeyFromBytes(tok) if err != nil { - return -1, err + return network.VersionMax, err } return s.delegate.StateNetworkVersion(ctx, tsk) diff --git a/storage/addresses.go b/storage/addresses.go index bef845367..639e996e3 100644 --- a/storage/addresses.go +++ b/storage/addresses.go @@ -3,12 +3,13 @@ package storage import ( "context" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + "golang.org/x/xerrors" "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/chain/types" ) @@ -27,7 +28,7 @@ type addrSelectApi interface { StateAccountKey(context.Context, address.Address, types.TipSetKey) (address.Address, error) } -func AddressFor(ctx context.Context, a addrSelectApi, mi api.MinerInfo, use AddrUse, minFunds abi.TokenAmount) (address.Address, error) { +func AddressFor(ctx context.Context, a addrSelectApi, mi miner.MinerInfo, use AddrUse, minFunds abi.TokenAmount) (address.Address, error) { switch use { case PreCommitAddr, CommitAddr: // always use worker, at least for now diff --git a/storage/miner.go b/storage/miner.go index 693ad7c05..227c51961 100644 --- a/storage/miner.go +++ b/storage/miner.go @@ -76,7 +76,7 @@ type storageMinerApi interface { StateSectorGetInfo(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (*miner.SectorOnChainInfo, error) StateSectorPartition(ctx context.Context, maddr address.Address, sectorNumber abi.SectorNumber, tok types.TipSetKey) (*miner.SectorLocation, error) StateMinerInfo(context.Context, address.Address, types.TipSetKey) (miner.MinerInfo, error) - StateMinerDeadlines(context.Context, address.Address, types.TipSetKey) ([]miner.Deadline, error) + StateMinerDeadlines(context.Context, address.Address, types.TipSetKey) ([]*miner.Deadline, error) StateMinerProvingDeadline(context.Context, address.Address, types.TipSetKey) (*dline.Info, error) StateMinerPreCommitDepositForPower(context.Context, address.Address, miner.SectorPreCommitInfo, types.TipSetKey) (types.BigInt, error) StateMinerInitialPledgeCollateral(context.Context, address.Address, miner.SectorPreCommitInfo, types.TipSetKey) (types.BigInt, error) diff --git a/storage/wdpost_sched.go b/storage/wdpost_sched.go index c927a1547..112210baf 100644 --- a/storage/wdpost_sched.go +++ b/storage/wdpost_sched.go @@ -4,8 +4,6 @@ import ( "context" "time" - "github.com/filecoin-project/go-state-types/dline" - "golang.org/x/xerrors" "github.com/filecoin-project/go-address" From 12e76bc1afd9a33a8e10be62c7d332e83d4852bc Mon Sep 17 00:00:00 2001 From: Marius Darila <3396463+kenshyx@users.noreply.github.com> Date: Thu, 17 Sep 2020 12:17:18 +0200 Subject: [PATCH 058/303] replace Requires with Wants Prevent lotus-miner shutdown when daemon restarts. --- scripts/lotus-miner.service | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/lotus-miner.service b/scripts/lotus-miner.service index c079f44a9..54c48d411 100644 --- a/scripts/lotus-miner.service +++ b/scripts/lotus-miner.service @@ -2,7 +2,7 @@ Description=Lotus Miner After=network.target After=lotus-daemon.service -Requires=lotus-daemon.service +Wants=lotus-daemon.service [Service] ExecStart=/usr/local/bin/lotus-miner run From e6326438013bfe0c30cc1f86c04f398b3c681dd0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Thu, 17 Sep 2020 12:22:56 +0200 Subject: [PATCH 059/303] api: Test return types --- api/api_full.go | 2 +- api/api_test.go | 69 +++++++++++++++++++ api/apistruct/struct.go | 4 +- cli/wallet.go | 6 +- .../sector-storage/ffiwrapper/sealer_test.go | 12 ++++ node/impl/full/wallet.go | 4 +- 6 files changed, 91 insertions(+), 6 deletions(-) diff --git a/api/api_full.go b/api/api_full.go index 1adcc5c19..778b458a8 100644 --- a/api/api_full.go +++ b/api/api_full.go @@ -230,7 +230,7 @@ type FullNode interface { WalletSignMessage(context.Context, address.Address, *types.Message) (*types.SignedMessage, error) // WalletVerify takes an address, a signature, and some bytes, and indicates whether the signature is valid. // The address does not have to be in the wallet. - WalletVerify(context.Context, address.Address, []byte, *crypto.Signature) bool + WalletVerify(context.Context, address.Address, []byte, *crypto.Signature) (bool, error) // WalletDefaultAddress returns the address marked as default in the wallet. WalletDefaultAddress(context.Context) (address.Address, error) // WalletSetDefault marks the given address as as the default one. diff --git a/api/api_test.go b/api/api_test.go index 1b438258a..065141426 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -1,12 +1,16 @@ package api import ( + "encoding/json" "os" "os/exec" "path/filepath" + "reflect" "runtime" "strings" "testing" + + "github.com/stretchr/testify/require" ) func goCmd() string { @@ -32,3 +36,68 @@ func TestDoesntDependOnFFI(t *testing.T) { } } } + +func TestReturnTypes(t *testing.T) { + errType := reflect.TypeOf(new(error)).Elem() + bareIface := reflect.TypeOf(new(interface{})).Elem() + jmarsh := reflect.TypeOf(new(json.Marshaler)).Elem() + + tst := func(api interface{}) func(t *testing.T) { + return func(t *testing.T) { + ra := reflect.TypeOf(api).Elem() + for i := 0; i < ra.NumMethod(); i++ { + m := ra.Method(i) + switch m.Type.NumOut() { + case 1: // if 1 return value, it must be an error + require.Equal(t, errType, m.Type.Out(0), m.Name) + + case 2: // if 2 return values, first cant be an interface/function, second must be an error + seen := map[reflect.Type]struct{}{} + todo := []reflect.Type{m.Type.Out(0)} + for len(todo) > 0 { + typ := todo[len(todo) - 1] + todo = todo[:len(todo)-1] + + if _, ok := seen[typ]; ok { + continue + } + seen[typ] = struct{}{} + + if typ.Kind() == reflect.Interface && typ != bareIface && !typ.Implements(jmarsh) { + t.Error("methods can't return interfaces", m.Name) + } + + switch typ.Kind() { + case reflect.Ptr: + fallthrough + case reflect.Array: + fallthrough + case reflect.Slice: + fallthrough + case reflect.Chan: + todo = append(todo, typ.Elem()) + case reflect.Map: + todo = append(todo, typ.Elem()) + todo = append(todo, typ.Key()) + case reflect.Struct: + for i := 0; i < typ.NumField(); i++ { + todo = append(todo, typ.Field(i).Type) + } + } + } + + require.NotEqual(t, reflect.Func.String(), m.Type.Out(0).Kind().String(), m.Name) + require.Equal(t, errType, m.Type.Out(1), m.Name) + + default: + t.Error("methods can only have 1 or 2 return values", m.Name) + } + } + } + } + + t.Run("common", tst(new(Common))) + t.Run("full", tst(new(FullNode))) + t.Run("miner", tst(new(StorageMiner))) + t.Run("worker", tst(new(WorkerAPI))) +} diff --git a/api/apistruct/struct.go b/api/apistruct/struct.go index ab86d7819..c8a2b91ac 100644 --- a/api/apistruct/struct.go +++ b/api/apistruct/struct.go @@ -134,7 +134,7 @@ type FullNodeStruct struct { WalletBalance func(context.Context, address.Address) (types.BigInt, error) `perm:"read"` WalletSign func(context.Context, address.Address, []byte) (*crypto.Signature, error) `perm:"sign"` WalletSignMessage func(context.Context, address.Address, *types.Message) (*types.SignedMessage, error) `perm:"sign"` - WalletVerify func(context.Context, address.Address, []byte, *crypto.Signature) bool `perm:"read"` + WalletVerify func(context.Context, address.Address, []byte, *crypto.Signature) (bool, error) `perm:"read"` WalletDefaultAddress func(context.Context) (address.Address, error) `perm:"write"` WalletSetDefault func(context.Context, address.Address) error `perm:"admin"` WalletExport func(context.Context, address.Address) (*types.KeyInfo, error) `perm:"admin"` @@ -604,7 +604,7 @@ func (c *FullNodeStruct) WalletSignMessage(ctx context.Context, k address.Addres return c.Internal.WalletSignMessage(ctx, k, msg) } -func (c *FullNodeStruct) WalletVerify(ctx context.Context, k address.Address, msg []byte, sig *crypto.Signature) bool { +func (c *FullNodeStruct) WalletVerify(ctx context.Context, k address.Address, msg []byte, sig *crypto.Signature) (bool, error) { return c.Internal.WalletVerify(ctx, k, msg, sig) } diff --git a/cli/wallet.go b/cli/wallet.go index 4339a1fb6..27993a1ba 100644 --- a/cli/wallet.go +++ b/cli/wallet.go @@ -382,7 +382,11 @@ var walletVerify = &cli.Command{ return err } - if api.WalletVerify(ctx, addr, msg, &sig) { + ok, err := api.WalletVerify(ctx, addr, msg, &sig) + if err != nil { + return err + } + if ok { fmt.Println("valid") return nil } diff --git a/extern/sector-storage/ffiwrapper/sealer_test.go b/extern/sector-storage/ffiwrapper/sealer_test.go index d59de2cab..bb26adb77 100644 --- a/extern/sector-storage/ffiwrapper/sealer_test.go +++ b/extern/sector-storage/ffiwrapper/sealer_test.go @@ -245,6 +245,10 @@ func TestDownloadParams(t *testing.T) { } func TestSealAndVerify(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode") + } + defer requireFDsClosed(t, openFDs(t)) if runtime.NumCPU() < 10 && os.Getenv("CI") == "" { // don't bother on slow hardware @@ -314,6 +318,10 @@ func TestSealAndVerify(t *testing.T) { } func TestSealPoStNoCommit(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode") + } + defer requireFDsClosed(t, openFDs(t)) if runtime.NumCPU() < 10 && os.Getenv("CI") == "" { // don't bother on slow hardware @@ -375,6 +383,10 @@ func TestSealPoStNoCommit(t *testing.T) { } func TestSealAndVerify3(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode") + } + defer requireFDsClosed(t, openFDs(t)) if runtime.NumCPU() < 10 && os.Getenv("CI") == "" { // don't bother on slow hardware diff --git a/node/impl/full/wallet.go b/node/impl/full/wallet.go index bda8824e7..64231b74e 100644 --- a/node/impl/full/wallet.go +++ b/node/impl/full/wallet.go @@ -67,8 +67,8 @@ func (a *WalletAPI) WalletSignMessage(ctx context.Context, k address.Address, ms }, nil } -func (a *WalletAPI) WalletVerify(ctx context.Context, k address.Address, msg []byte, sig *crypto.Signature) bool { - return sigs.Verify(sig, k, msg) == nil +func (a *WalletAPI) WalletVerify(ctx context.Context, k address.Address, msg []byte, sig *crypto.Signature) (bool, error) { + return sigs.Verify(sig, k, msg) == nil, nil } func (a *WalletAPI) WalletDefaultAddress(ctx context.Context) (address.Address, error) { From 61c0b8c3db61ccb1d97fe05fd856c74fda0d0451 Mon Sep 17 00:00:00 2001 From: vyzo Date: Wed, 16 Sep 2020 10:14:28 +0300 Subject: [PATCH 060/303] properly close streams in blocksync we were leaking streams right and left... --- chain/exchange/client.go | 7 +++++++ chain/exchange/server.go | 5 ++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/chain/exchange/client.go b/chain/exchange/client.go index 22f7a9457..57563d5b2 100644 --- a/chain/exchange/client.go +++ b/chain/exchange/client.go @@ -7,6 +7,7 @@ import ( "math/rand" "time" + "github.com/libp2p/go-libp2p-core/helpers" "github.com/libp2p/go-libp2p-core/host" "github.com/libp2p/go-libp2p-core/network" "github.com/libp2p/go-libp2p-core/peer" @@ -357,6 +358,12 @@ func (c *client) sendRequestToPeer(ctx context.Context, peer peer.ID, req *Reque return nil, xerrors.Errorf("failed to open stream to peer: %w", err) } + defer func() { + // Note: this will become just stream.Close once we've completed the go-libp2p migration to + // go-libp2p-core 0.7.0 + go helpers.FullClose(stream) //nolint:errcheck + }() + // Write request. _ = stream.SetWriteDeadline(time.Now().Add(WriteReqDeadline)) if err := cborutil.WriteCborRPC(stream, req); err != nil { diff --git a/chain/exchange/server.go b/chain/exchange/server.go index 54e169b3f..dcdb5b3a5 100644 --- a/chain/exchange/server.go +++ b/chain/exchange/server.go @@ -15,6 +15,7 @@ import ( "github.com/filecoin-project/lotus/chain/types" "github.com/ipfs/go-cid" + "github.com/libp2p/go-libp2p-core/helpers" inet "github.com/libp2p/go-libp2p-core/network" ) @@ -39,7 +40,9 @@ func (s *server) HandleStream(stream inet.Stream) { ctx, span := trace.StartSpan(context.Background(), "chainxchg.HandleStream") defer span.End() - defer stream.Close() //nolint:errcheck + // Note: this will become just stream.Close once we've completed the go-libp2p migration to + // go-libp2p-core 0.7.0 + defer helpers.FullClose(stream) //nolint:errcheck var req Request if err := cborutil.ReadCborRPC(bufio.NewReader(stream), &req); err != nil { From 35f6e1064620f05f29f8ec775f453b2e56c3e9ae Mon Sep 17 00:00:00 2001 From: vyzo Date: Wed, 16 Sep 2020 21:04:44 +0300 Subject: [PATCH 061/303] parallel chain sync --- chain/sync.go | 114 +++++++++++++++++++++++++++----------------------- 1 file changed, 62 insertions(+), 52 deletions(-) diff --git a/chain/sync.go b/chain/sync.go index b5716a343..882fb1d95 100644 --- a/chain/sync.go +++ b/chain/sync.go @@ -7,7 +7,6 @@ import ( "fmt" "os" "sort" - "strconv" "strings" "sync" "time" @@ -63,20 +62,12 @@ var ( // where the Syncer publishes candidate chain heads to be synced. LocalIncoming = "incoming" - log = logging.Logger("chain") - defaultMessageFetchWindowSize = 200 -) + log = logging.Logger("chain") -func init() { - if s := os.Getenv("LOTUS_BSYNC_MSG_WINDOW"); s != "" { - val, err := strconv.Atoi(s) - if err != nil { - log.Errorf("failed to parse LOTUS_BSYNC_MSG_WINDOW: %s", err) - return - } - defaultMessageFetchWindowSize = val - } -} + concurrentSyncRequests = 16 + syncRequestBatchSize = 4 + syncRequestRetries = 5 +) // Syncer is in charge of running the chain synchronization logic. As such, it // is tasked with these functions, amongst others: @@ -132,8 +123,6 @@ type Syncer struct { verifier ffiwrapper.Verifier - windowSize int - tickerCtxCancel context.CancelFunc checkptLk sync.Mutex @@ -175,7 +164,6 @@ func NewSyncer(ds dtypes.MetadataDS, sm *stmgr.StateManager, exchange exchange.C receiptTracker: newBlockReceiptTracker(), connmgr: connmgr, verifier: verifier, - windowSize: defaultMessageFetchWindowSize, incoming: pubsub.New(50), } @@ -1483,8 +1471,6 @@ func (syncer *Syncer) iterFullTipsets(ctx context.Context, headers []*types.TipS span.AddAttributes(trace.Int64Attribute("num_headers", int64(len(headers)))) - windowSize := syncer.windowSize -mainLoop: for i := len(headers) - 1; i >= 0; { fts, err := syncer.store.TryFillTipSet(headers[i]) if err != nil { @@ -1498,35 +1484,73 @@ mainLoop: continue } - batchSize := windowSize + batchSize := concurrentSyncRequests * syncRequestBatchSize if i < batchSize { - batchSize = i + if i == 0 { + batchSize = 1 + } else { + batchSize = i + } } - nextI := (i + 1) - batchSize // want to fetch batchSize values, 'i' points to last one we want to fetch, so its 'inclusive' of our request, thus we need to add one to our request start index - ss.SetStage(api.StageFetchingMessages) - var bstout []*exchange.CompactedMessages - for len(bstout) < batchSize { - next := headers[nextI] + bstout := make([]*exchange.CompactedMessages, batchSize) + var wg sync.WaitGroup + var mx sync.Mutex + var batchErr error + for j := 0; j < batchSize; j += syncRequestBatchSize { + wg.Add(1) + go func(j int) { + defer wg.Done() - nreq := batchSize - len(bstout) - bstips, err := syncer.Exchange.GetChainMessages(ctx, next, uint64(nreq)) - if err != nil { - // TODO check errors for temporary nature - if windowSize > 1 { - windowSize /= 2 - log.Infof("error fetching messages: %s; reducing window size to %d and trying again", err, windowSize) - continue mainLoop + nreq := syncRequestBatchSize + if j*syncRequestBatchSize+nreq > batchSize { + nreq = batchSize - j*syncRequestBatchSize } - return xerrors.Errorf("message processing failed: %w", err) - } - bstout = append(bstout, bstips...) - nextI += len(bstips) + failed := false + for offset := 0; !failed && offset < nreq; { + nextI := (i + 1) - batchSize + j*syncRequestBatchSize + offset + nextHeader := headers[nextI] + + var requestErr error + var requestResult []*exchange.CompactedMessages + for retry := 0; requestResult == nil && retry < syncRequestRetries; retry++ { + if retry > 0 { + log.Infof("fetching messages at %d (retry %d)", nextI, retry) + } else { + log.Infof("fetching messages at %d", nextI) + } + + result, err := syncer.Exchange.GetChainMessages(ctx, nextHeader, uint64(nreq-offset)) + if err != nil { + requestErr = multierror.Append(requestErr, err) + } else { + requestResult = result + } + } + + mx.Lock() + if requestResult == nil { + // we failed! + log.Errorf("error fetching messages at %d: %s", nextI, requestErr) + batchErr = multierror.Append(batchErr, requestErr) + failed = true + } else { + copy(bstout[j*syncRequestBatchSize+offset:], requestResult) + offset += len(requestResult) + } + mx.Unlock() + } + }(j) } + wg.Wait() ss.SetStage(api.StageMessages) + if batchErr != nil { + return xerrors.Errorf("failed to fetch messages: %w", err) + } + for bsi := 0; bsi < len(bstout); bsi++ { // temp storage so we don't persist data we dont want to bs := bstore.NewTemporary() @@ -1555,23 +1579,9 @@ mainLoop: } } - if i >= windowSize { - newWindowSize := windowSize + 10 - if newWindowSize > int(exchange.MaxRequestLength) { - newWindowSize = int(exchange.MaxRequestLength) - } - if newWindowSize > windowSize { - windowSize = newWindowSize - log.Infof("successfully fetched %d messages; increasing window size to %d", len(bstout), windowSize) - } - } - i -= batchSize } - // remember our window size - syncer.windowSize = windowSize - return nil } From 05a233f84d6de0916b1135f46eef3a61c7aa02ae Mon Sep 17 00:00:00 2001 From: vyzo Date: Wed, 16 Sep 2020 21:43:35 +0300 Subject: [PATCH 062/303] add some more logging --- chain/sync.go | 1 + 1 file changed, 1 insertion(+) diff --git a/chain/sync.go b/chain/sync.go index 882fb1d95..87d2cf6f4 100644 --- a/chain/sync.go +++ b/chain/sync.go @@ -1537,6 +1537,7 @@ func (syncer *Syncer) iterFullTipsets(ctx context.Context, headers []*types.TipS batchErr = multierror.Append(batchErr, requestErr) failed = true } else { + log.Infof("fetched messages for %d tipsets", len(requestResult)) copy(bstout[j*syncRequestBatchSize+offset:], requestResult) offset += len(requestResult) } From b984e94a87237b14ef1eb90df95d5979b4c665bf Mon Sep 17 00:00:00 2001 From: vyzo Date: Wed, 16 Sep 2020 21:52:08 +0300 Subject: [PATCH 063/303] fix bug --- chain/sync.go | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/chain/sync.go b/chain/sync.go index 87d2cf6f4..80a5ad423 100644 --- a/chain/sync.go +++ b/chain/sync.go @@ -1504,13 +1504,13 @@ func (syncer *Syncer) iterFullTipsets(ctx context.Context, headers []*types.TipS defer wg.Done() nreq := syncRequestBatchSize - if j*syncRequestBatchSize+nreq > batchSize { - nreq = batchSize - j*syncRequestBatchSize + if j+nreq > batchSize { + nreq = batchSize - j } failed := false for offset := 0; !failed && offset < nreq; { - nextI := (i + 1) - batchSize + j*syncRequestBatchSize + offset + nextI := (i + 1) - batchSize + j + offset nextHeader := headers[nextI] var requestErr error @@ -1537,8 +1537,7 @@ func (syncer *Syncer) iterFullTipsets(ctx context.Context, headers []*types.TipS batchErr = multierror.Append(batchErr, requestErr) failed = true } else { - log.Infof("fetched messages for %d tipsets", len(requestResult)) - copy(bstout[j*syncRequestBatchSize+offset:], requestResult) + copy(bstout[j+offset:], requestResult) offset += len(requestResult) } mx.Unlock() From 8a4b629f407a9b0ff1e39e9eeb5ba7d541c4adfc Mon Sep 17 00:00:00 2001 From: vyzo Date: Wed, 16 Sep 2020 21:55:51 +0300 Subject: [PATCH 064/303] increase sync request batch size to 8 --- chain/sync.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chain/sync.go b/chain/sync.go index 80a5ad423..554f81ee9 100644 --- a/chain/sync.go +++ b/chain/sync.go @@ -65,7 +65,7 @@ var ( log = logging.Logger("chain") concurrentSyncRequests = 16 - syncRequestBatchSize = 4 + syncRequestBatchSize = 8 syncRequestRetries = 5 ) From 2a428f09e67f01bdd927f09e9e40f758b2bd60e1 Mon Sep 17 00:00:00 2001 From: vyzo Date: Wed, 16 Sep 2020 22:09:36 +0300 Subject: [PATCH 065/303] increase exchange ShufflePeersPrefix to 16, use that as the value of concurrent sync requests --- chain/exchange/protocol.go | 2 +- chain/sync.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/chain/exchange/protocol.go b/chain/exchange/protocol.go index ca4b61836..ac02cf60f 100644 --- a/chain/exchange/protocol.go +++ b/chain/exchange/protocol.go @@ -40,7 +40,7 @@ const ( WriteReqDeadline = 5 * time.Second ReadResDeadline = WriteReqDeadline ReadResMinSpeed = 50 << 10 - ShufflePeersPrefix = 5 + ShufflePeersPrefix = 16 WriteResDeadline = 60 * time.Second ) diff --git a/chain/sync.go b/chain/sync.go index 554f81ee9..0ab8ac183 100644 --- a/chain/sync.go +++ b/chain/sync.go @@ -64,7 +64,7 @@ var ( log = logging.Logger("chain") - concurrentSyncRequests = 16 + concurrentSyncRequests = exchange.ShufflePeersPrefix syncRequestBatchSize = 8 syncRequestRetries = 5 ) From fb605f6d7fedea4704882a631d3155b0c280c599 Mon Sep 17 00:00:00 2001 From: vyzo Date: Thu, 17 Sep 2020 17:21:26 +0300 Subject: [PATCH 066/303] refactor parallel fetch logic into a separate function --- chain/sync.go | 118 ++++++++++++++++++++++++++++---------------------- 1 file changed, 67 insertions(+), 51 deletions(-) diff --git a/chain/sync.go b/chain/sync.go index 0ab8ac183..95c2e2e84 100644 --- a/chain/sync.go +++ b/chain/sync.go @@ -1494,57 +1494,8 @@ func (syncer *Syncer) iterFullTipsets(ctx context.Context, headers []*types.TipS } ss.SetStage(api.StageFetchingMessages) - bstout := make([]*exchange.CompactedMessages, batchSize) - var wg sync.WaitGroup - var mx sync.Mutex - var batchErr error - for j := 0; j < batchSize; j += syncRequestBatchSize { - wg.Add(1) - go func(j int) { - defer wg.Done() - - nreq := syncRequestBatchSize - if j+nreq > batchSize { - nreq = batchSize - j - } - - failed := false - for offset := 0; !failed && offset < nreq; { - nextI := (i + 1) - batchSize + j + offset - nextHeader := headers[nextI] - - var requestErr error - var requestResult []*exchange.CompactedMessages - for retry := 0; requestResult == nil && retry < syncRequestRetries; retry++ { - if retry > 0 { - log.Infof("fetching messages at %d (retry %d)", nextI, retry) - } else { - log.Infof("fetching messages at %d", nextI) - } - - result, err := syncer.Exchange.GetChainMessages(ctx, nextHeader, uint64(nreq-offset)) - if err != nil { - requestErr = multierror.Append(requestErr, err) - } else { - requestResult = result - } - } - - mx.Lock() - if requestResult == nil { - // we failed! - log.Errorf("error fetching messages at %d: %s", nextI, requestErr) - batchErr = multierror.Append(batchErr, requestErr) - failed = true - } else { - copy(bstout[j+offset:], requestResult) - offset += len(requestResult) - } - mx.Unlock() - } - }(j) - } - wg.Wait() + startOffset := i + 1 - batchSize + bstout, batchErr := syncer.fetchMessages(ctx, headers[startOffset:startOffset+batchSize], startOffset) ss.SetStage(api.StageMessages) if batchErr != nil { @@ -1585,6 +1536,71 @@ func (syncer *Syncer) iterFullTipsets(ctx context.Context, headers []*types.TipS return nil } +func (syncer *Syncer) fetchMessages(ctx context.Context, headers []*types.TipSet, startOffset int) ([]*exchange.CompactedMessages, error) { + batchSize := len(headers) + batch := make([]*exchange.CompactedMessages, batchSize) + + var wg sync.WaitGroup + var mx sync.Mutex + var batchErr error + + start := build.Clock.Now() + + for j := 0; j < batchSize; j += syncRequestBatchSize { + wg.Add(1) + go func(j int) { + defer wg.Done() + + nreq := syncRequestBatchSize + if j+nreq > batchSize { + nreq = batchSize - j + } + + failed := false + for offset := 0; !failed && offset < nreq; { + nextI := j + offset + nextHeader := headers[nextI] + + var requestErr error + var requestResult []*exchange.CompactedMessages + for retry := 0; requestResult == nil && retry < syncRequestRetries; retry++ { + if retry > 0 { + log.Infof("fetching messages at %d (retry %d)", startOffset+nextI, retry) + } else { + log.Infof("fetching messages at %d", startOffset+nextI) + } + + result, err := syncer.Exchange.GetChainMessages(ctx, nextHeader, uint64(nreq-offset)) + if err != nil { + requestErr = multierror.Append(requestErr, err) + } else { + requestResult = result + } + } + + mx.Lock() + if requestResult != nil { + copy(batch[j+offset:], requestResult) + offset += len(requestResult) + } else { + log.Errorf("error fetching messages at %d: %s", nextI, requestErr) + batchErr = multierror.Append(batchErr, requestErr) + failed = true + } + mx.Unlock() + } + }(j) + } + wg.Wait() + + if batchErr != nil { + dt := build.Clock.Since(start) + log.Infof("fetching messages for %d tipsets at %d done; took %s", batchSize, startOffset, dt) + } + + return batch, batchErr +} + func persistMessages(bs bstore.Blockstore, bst *exchange.CompactedMessages) error { for _, m := range bst.Bls { //log.Infof("putting BLS message: %s", m.Cid()) From d7948fcbcd687961f746d88ed55a2afc13024aeb Mon Sep 17 00:00:00 2001 From: vyzo Date: Thu, 17 Sep 2020 17:33:52 +0300 Subject: [PATCH 067/303] fix log; we want to log time when we succeed! --- chain/sync.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chain/sync.go b/chain/sync.go index 95c2e2e84..d09ba84de 100644 --- a/chain/sync.go +++ b/chain/sync.go @@ -1593,7 +1593,7 @@ func (syncer *Syncer) fetchMessages(ctx context.Context, headers []*types.TipSet } wg.Wait() - if batchErr != nil { + if batchErr == nil { dt := build.Clock.Since(start) log.Infof("fetching messages for %d tipsets at %d done; took %s", batchSize, startOffset, dt) } From 2946561decdb7bd7b9056cc256c6e32294a13279 Mon Sep 17 00:00:00 2001 From: vyzo Date: Thu, 17 Sep 2020 17:35:40 +0300 Subject: [PATCH 068/303] clean up return code --- chain/sync.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/chain/sync.go b/chain/sync.go index d09ba84de..9c9714447 100644 --- a/chain/sync.go +++ b/chain/sync.go @@ -1593,11 +1593,12 @@ func (syncer *Syncer) fetchMessages(ctx context.Context, headers []*types.TipSet } wg.Wait() - if batchErr == nil { - dt := build.Clock.Since(start) - log.Infof("fetching messages for %d tipsets at %d done; took %s", batchSize, startOffset, dt) + if batchErr != nil { + return nil, batchErr } + log.Infof("fetching messages for %d tipsets at %d done; took %s", batchSize, startOffset, build.Clock.Since(start)) + return batch, batchErr } From 6dfc40abc1c9152d3fb59061f2008b54b0b63872 Mon Sep 17 00:00:00 2001 From: vyzo Date: Thu, 17 Sep 2020 18:23:50 +0300 Subject: [PATCH 069/303] error is nil at end, so return batch, nil --- chain/sync.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chain/sync.go b/chain/sync.go index 9c9714447..03ae1cd4f 100644 --- a/chain/sync.go +++ b/chain/sync.go @@ -1599,7 +1599,7 @@ func (syncer *Syncer) fetchMessages(ctx context.Context, headers []*types.TipSet log.Infof("fetching messages for %d tipsets at %d done; took %s", batchSize, startOffset, build.Clock.Since(start)) - return batch, batchErr + return batch, nil } func persistMessages(bs bstore.Blockstore, bst *exchange.CompactedMessages) error { From 6eda53565f62f804b72522594b82396cb7aa2038 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Thu, 17 Sep 2020 17:30:15 +0200 Subject: [PATCH 070/303] Most tests passing --- api/api_full.go | 18 ++++- api/api_test.go | 2 +- api/apistruct/struct.go | 13 ++-- api/test/window_post.go | 4 +- chain/actors/builtin/builtin.go | 2 +- chain/actors/builtin/miner/miner.go | 1 + chain/actors/builtin/miner/v0.go | 4 ++ chain/actors/builtin/reward/reward.go | 2 +- chain/events/state/predicates.go | 26 +++---- chain/messagepool/selection_test.go | 3 + chain/state/statetree_test.go | 23 ++++--- chain/stmgr/stmgr.go | 6 +- chain/stmgr/utils.go | 12 +++- cli/client.go | 2 +- cmd/lotus-chainwatch/processor/market.go | 4 +- cmd/lotus-pcr/main.go | 8 +-- cmd/lotus-storage-miner/proving.go | 23 ++----- conformance/driver.go | 2 +- .../storage-sealing/precommit_policy_test.go | 6 ++ extern/storage-sealing/sealing.go | 2 +- markets/storageadapter/provider.go | 6 +- node/impl/full/state.go | 68 +++++++++++++++---- storage/adapter_storage_miner.go | 4 +- storage/miner.go | 2 +- 24 files changed, 159 insertions(+), 84 deletions(-) diff --git a/api/api_full.go b/api/api_full.go index 778b458a8..6454966a4 100644 --- a/api/api_full.go +++ b/api/api_full.go @@ -326,7 +326,9 @@ type FullNode interface { // StateMinerInfo returns info about the indicated miner StateMinerInfo(context.Context, address.Address, types.TipSetKey) (miner.MinerInfo, error) // StateMinerDeadlines returns all the proving deadlines for the given miner - StateMinerDeadlines(context.Context, address.Address, types.TipSetKey) ([]*miner.Deadline, error) + StateMinerDeadlines(context.Context, address.Address, types.TipSetKey) ([]Deadline, error) + // StateMinerPartitions returns all partitions in the specified deadline + StateMinerPartitions(ctx context.Context, m address.Address, dlIdx uint64, tsk types.TipSetKey) ([]Partition, error) // StateMinerFaults returns a bitfield indicating the faulty sectors of the given miner StateMinerFaults(context.Context, address.Address, types.TipSetKey) (bitfield.BitField, error) // StateAllMinerFaults returns all non-expired Faults that occur within lookback epochs of the given tipset @@ -383,7 +385,7 @@ type FullNode interface { // StateVerifiedClientStatus returns the data cap for the given address. // Returns nil if there is no entry in the data cap table for the // address. - StateVerifiedClientStatus(ctx context.Context, addr address.Address, tsk types.TipSetKey) (abi.StoragePower, error) + StateVerifiedClientStatus(ctx context.Context, addr address.Address, tsk types.TipSetKey) (*abi.StoragePower, error) // StateDealProviderCollateralBounds returns the min and max collateral a storage provider // can issue. It takes the deal size and verified status as parameters. StateDealProviderCollateralBounds(context.Context, abi.PaddedPieceSize, bool, types.TipSetKey) (DealCollateralBounds, error) @@ -816,6 +818,18 @@ const ( MsigCancel ) +type Deadline struct { + PostSubmissions bitfield.BitField +} + +type Partition struct { + AllSectors bitfield.BitField + FaultySectors bitfield.BitField + RecoveringSectors bitfield.BitField + LiveSectors bitfield.BitField + ActiveSectors bitfield.BitField +} + type Fault struct { Miner address.Address Epoch abi.ChainEpoch diff --git a/api/api_test.go b/api/api_test.go index 065141426..34c47f432 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -55,7 +55,7 @@ func TestReturnTypes(t *testing.T) { seen := map[reflect.Type]struct{}{} todo := []reflect.Type{m.Type.Out(0)} for len(todo) > 0 { - typ := todo[len(todo) - 1] + typ := todo[len(todo)-1] todo = todo[:len(todo)-1] if _, ok := seen[typ]; ok { diff --git a/api/apistruct/struct.go b/api/apistruct/struct.go index c8a2b91ac..397a0d60a 100644 --- a/api/apistruct/struct.go +++ b/api/apistruct/struct.go @@ -167,7 +167,8 @@ type FullNodeStruct struct { StateMinerProvingDeadline func(context.Context, address.Address, types.TipSetKey) (*dline.Info, error) `perm:"read"` StateMinerPower func(context.Context, address.Address, types.TipSetKey) (*api.MinerPower, error) `perm:"read"` StateMinerInfo func(context.Context, address.Address, types.TipSetKey) (miner.MinerInfo, error) `perm:"read"` - StateMinerDeadlines func(context.Context, address.Address, types.TipSetKey) ([]*miner.Deadline, error) `perm:"read"` + StateMinerDeadlines func(context.Context, address.Address, types.TipSetKey) ([]api.Deadline, error) `perm:"read"` + StateMinerPartitions func(ctx context.Context, m address.Address, dlIdx uint64, tsk types.TipSetKey) ([]api.Partition, error) `perm:"read"` StateMinerFaults func(context.Context, address.Address, types.TipSetKey) (bitfield.BitField, error) `perm:"read"` StateAllMinerFaults func(context.Context, abi.ChainEpoch, types.TipSetKey) ([]*api.Fault, error) `perm:"read"` StateMinerRecoveries func(context.Context, address.Address, types.TipSetKey) (bitfield.BitField, error) `perm:"read"` @@ -197,7 +198,7 @@ type FullNodeStruct struct { StateMinerSectorCount func(context.Context, address.Address, types.TipSetKey) (api.MinerSectors, error) `perm:"read"` StateListMessages func(ctx context.Context, match *types.Message, tsk types.TipSetKey, toht abi.ChainEpoch) ([]cid.Cid, error) `perm:"read"` StateCompute func(context.Context, abi.ChainEpoch, []*types.Message, types.TipSetKey) (*api.ComputeStateOutput, error) `perm:"read"` - StateVerifiedClientStatus func(context.Context, address.Address, types.TipSetKey) (abi.StoragePower, error) `perm:"read"` + StateVerifiedClientStatus func(context.Context, address.Address, types.TipSetKey) (*abi.StoragePower, error) `perm:"read"` StateDealProviderCollateralBounds func(context.Context, abi.PaddedPieceSize, bool, types.TipSetKey) (api.DealCollateralBounds, error) `perm:"read"` StateCirculatingSupply func(context.Context, types.TipSetKey) (api.CirculatingSupply, error) `perm:"read"` StateNetworkVersion func(context.Context, types.TipSetKey) (stnetwork.Version, error) `perm:"read"` @@ -752,10 +753,14 @@ func (c *FullNodeStruct) StateMinerInfo(ctx context.Context, actor address.Addre return c.Internal.StateMinerInfo(ctx, actor, tsk) } -func (c *FullNodeStruct) StateMinerDeadlines(ctx context.Context, actor address.Address, tsk types.TipSetKey) ([]*miner.Deadline, error) { +func (c *FullNodeStruct) StateMinerDeadlines(ctx context.Context, actor address.Address, tsk types.TipSetKey) ([]api.Deadline, error) { return c.Internal.StateMinerDeadlines(ctx, actor, tsk) } +func (c *FullNodeStruct) StateMinerPartitions(ctx context.Context, m address.Address, dlIdx uint64, tsk types.TipSetKey) ([]api.Partition, error) { + return c.Internal.StateMinerPartitions(ctx, m, dlIdx, tsk) +} + func (c *FullNodeStruct) StateMinerFaults(ctx context.Context, actor address.Address, tsk types.TipSetKey) (bitfield.BitField, error) { return c.Internal.StateMinerFaults(ctx, actor, tsk) } @@ -868,7 +873,7 @@ func (c *FullNodeStruct) StateCompute(ctx context.Context, height abi.ChainEpoch return c.Internal.StateCompute(ctx, height, msgs, tsk) } -func (c *FullNodeStruct) StateVerifiedClientStatus(ctx context.Context, addr address.Address, tsk types.TipSetKey) (abi.StoragePower, error) { +func (c *FullNodeStruct) StateVerifiedClientStatus(ctx context.Context, addr address.Address, tsk types.TipSetKey) (*abi.StoragePower, error) { return c.Internal.StateVerifiedClientStatus(ctx, addr, tsk) } diff --git a/api/test/window_post.go b/api/test/window_post.go index bdc390730..e2bf5f36e 100644 --- a/api/test/window_post.go +++ b/api/test/window_post.go @@ -200,7 +200,7 @@ func TestWindowPost(t *testing.T, b APIBuilder, blocktime time.Duration, nSector require.NoError(t, err) require.Greater(t, len(parts), 0) - secs, err := parts[0].AllSectors() + secs := parts[0].AllSectors require.NoError(t, err) n, err := secs.Count() require.NoError(t, err) @@ -224,7 +224,7 @@ func TestWindowPost(t *testing.T, b APIBuilder, blocktime time.Duration, nSector require.NoError(t, err) require.Greater(t, len(parts), 0) - secs, err := parts[0].AllSectors() + secs := parts[0].AllSectors require.NoError(t, err) n, err := secs.Count() require.NoError(t, err) diff --git a/chain/actors/builtin/builtin.go b/chain/actors/builtin/builtin.go index 517f0d70c..bee8e59d6 100644 --- a/chain/actors/builtin/builtin.go +++ b/chain/actors/builtin/builtin.go @@ -17,7 +17,7 @@ const ( // Converts a network version into a specs-actors version. func VersionForNetwork(version network.Version) Version { switch version { - case network.Version0, network.Version1: + case network.Version0, network.Version1, network.Version2: return Version0 default: panic(fmt.Sprintf("unsupported network version %d", version)) diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index 725c5f2ff..d754d0b74 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -57,6 +57,7 @@ type State interface { type Deadline interface { LoadPartition(idx uint64) (Partition, error) ForEachPartition(cb func(idx uint64, part Partition) error) error + PostSubmissions() (bitfield.BitField, error) } type Partition interface { diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index cbe42b3da..b3fe594d1 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -266,6 +266,10 @@ func (d *v0Deadline) ForEachPartition(cb func(uint64, Partition) error) error { }) } +func (d *v0Deadline) PostSubmissions() (bitfield.BitField, error) { + return d.Deadline.PostSubmissions, nil +} + func (p *v0Partition) AllSectors() (bitfield.BitField, error) { return p.Partition.Sectors, nil } diff --git a/chain/actors/builtin/reward/reward.go b/chain/actors/builtin/reward/reward.go index 9093b33c6..52a26ab15 100644 --- a/chain/actors/builtin/reward/reward.go +++ b/chain/actors/builtin/reward/reward.go @@ -28,7 +28,7 @@ func Load(store adt.Store, act *types.Actor) (st State, err error) { } type State interface { - cbor.Marshaler + cbor.Er RewardSmoothed() (builtin.FilterEstimate, error) EffectiveBaselinePower() (abi.StoragePower, error) diff --git a/chain/events/state/predicates.go b/chain/events/state/predicates.go index 7a7609823..f27b5dc8f 100644 --- a/chain/events/state/predicates.go +++ b/chain/events/state/predicates.go @@ -12,11 +12,10 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/lotus/chain/actors/adt" + init_ "github.com/filecoin-project/lotus/chain/actors/builtin/init" "github.com/filecoin-project/lotus/chain/actors/builtin/market" "github.com/filecoin-project/lotus/chain/actors/builtin/paych" "github.com/filecoin-project/specs-actors/actors/builtin" - init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" - v0adt "github.com/filecoin-project/specs-actors/actors/util/adt" cbor "github.com/ipfs/go-ipld-cbor" typegen "github.com/whyrusleeping/cbor-gen" @@ -299,12 +298,12 @@ type DiffMinerActorStateFunc func(ctx context.Context, oldState miner.State, new func (sp *StatePredicates) OnInitActorChange(diffInitActorState DiffInitActorStateFunc) DiffTipSetKeyFunc { return sp.OnActorStateChanged(builtin.InitActorAddr, func(ctx context.Context, oldActorState, newActorState *types.Actor) (changed bool, user UserData, err error) { - var oldState init_.State - if err := sp.cst.Get(ctx, oldActorState.Head, &oldState); err != nil { + oldState, err := init_.Load(adt.WrapStore(ctx, sp.cst), oldActorState) + if err != nil { return false, nil, err } - var newState init_.State - if err := sp.cst.Get(ctx, newActorState.Head, &newState); err != nil { + newState, err := init_.Load(adt.WrapStore(ctx, sp.cst), newActorState) + if err != nil { return false, nil, err } return diffInitActorState(ctx, &oldState, &newState) @@ -314,12 +313,12 @@ func (sp *StatePredicates) OnInitActorChange(diffInitActorState DiffInitActorSta func (sp *StatePredicates) OnMinerActorChange(minerAddr address.Address, diffMinerActorState DiffMinerActorStateFunc) DiffTipSetKeyFunc { return sp.OnActorStateChanged(minerAddr, func(ctx context.Context, oldActorState, newActorState *types.Actor) (changed bool, user UserData, err error) { - var oldState miner.State - if err := sp.cst.Get(ctx, oldActorState.Head, &oldState); err != nil { + oldState, err := miner.Load(adt.WrapStore(ctx, sp.cst), oldActorState) + if err != nil { return false, nil, err } - var newState miner.State - if err := sp.cst.Get(ctx, newActorState.Head, &newState); err != nil { + newState, err := miner.Load(adt.WrapStore(ctx, sp.cst), newActorState) + if err != nil { return false, nil, err } return diffMinerActorState(ctx, oldState, newState) @@ -620,7 +619,7 @@ func (i *InitActorAddressChanges) Remove(key string, val *typegen.Deferred) erro func (sp *StatePredicates) OnAddressMapChange() DiffInitActorStateFunc { return func(ctx context.Context, oldState, newState *init_.State) (changed bool, user UserData, err error) { - ctxStore := &contextStore{ + /*ctxStore := &contextStore{ ctx: ctx, cst: sp.cst, } @@ -653,6 +652,9 @@ func (sp *StatePredicates) OnAddressMapChange() DiffInitActorStateFunc { return false, nil, nil } - return true, addressChanges, nil + return true, addressChanges, nil*/ + + panic("TODO") + return false, nil, nil } } diff --git a/chain/messagepool/selection_test.go b/chain/messagepool/selection_test.go index 5e372fc85..ea19dad9c 100644 --- a/chain/messagepool/selection_test.go +++ b/chain/messagepool/selection_test.go @@ -1216,6 +1216,9 @@ func makeZipfPremiumDistribution(rng *rand.Rand) func() uint64 { } func TestCompetitiveMessageSelectionExp(t *testing.T) { + if testing.Short() { + t.Skip("skipping in short mode") + } var capacityBoost, rewardBoost, tqReward float64 seeds := []int64{1947, 1976, 2020, 2100, 10000, 143324, 432432, 131, 32, 45} for _, seed := range seeds { diff --git a/chain/state/statetree_test.go b/chain/state/statetree_test.go index e45090d1a..79ab20606 100644 --- a/chain/state/statetree_test.go +++ b/chain/state/statetree_test.go @@ -5,17 +5,20 @@ import ( "fmt" "testing" - "github.com/filecoin-project/specs-actors/actors/builtin" - - address "github.com/filecoin-project/go-address" - "github.com/filecoin-project/lotus/chain/types" "github.com/ipfs/go-cid" cbor "github.com/ipfs/go-ipld-cbor" + + address "github.com/filecoin-project/go-address" + "github.com/filecoin-project/specs-actors/actors/builtin" + + "github.com/filecoin-project/lotus/build" + builtin2 "github.com/filecoin-project/lotus/chain/actors/builtin" + "github.com/filecoin-project/lotus/chain/types" ) func BenchmarkStateTreeSet(b *testing.B) { cst := cbor.NewMemCborStore() - st, err := NewStateTree(cst) + st, err := NewStateTree(cst, builtin2.VersionForNetwork(build.NewestNetworkVersion)) if err != nil { b.Fatal(err) } @@ -42,7 +45,7 @@ func BenchmarkStateTreeSet(b *testing.B) { func BenchmarkStateTreeSetFlush(b *testing.B) { cst := cbor.NewMemCborStore() - st, err := NewStateTree(cst) + st, err := NewStateTree(cst, builtin2.VersionForNetwork(build.NewestNetworkVersion)) if err != nil { b.Fatal(err) } @@ -72,7 +75,7 @@ func BenchmarkStateTreeSetFlush(b *testing.B) { func BenchmarkStateTree10kGetActor(b *testing.B) { cst := cbor.NewMemCborStore() - st, err := NewStateTree(cst) + st, err := NewStateTree(cst, builtin2.VersionForNetwork(build.NewestNetworkVersion)) if err != nil { b.Fatal(err) } @@ -114,7 +117,7 @@ func BenchmarkStateTree10kGetActor(b *testing.B) { func TestSetCache(t *testing.T) { cst := cbor.NewMemCborStore() - st, err := NewStateTree(cst) + st, err := NewStateTree(cst, builtin2.VersionForNetwork(build.NewestNetworkVersion)) if err != nil { t.Fatal(err) } @@ -151,7 +154,7 @@ func TestSetCache(t *testing.T) { func TestSnapshots(t *testing.T) { ctx := context.Background() cst := cbor.NewMemCborStore() - st, err := NewStateTree(cst) + st, err := NewStateTree(cst, builtin2.VersionForNetwork(build.NewestNetworkVersion)) if err != nil { t.Fatal(err) } @@ -234,7 +237,7 @@ func assertNotHas(t *testing.T, st *StateTree, addr address.Address) { func TestStateTreeConsistency(t *testing.T) { cst := cbor.NewMemCborStore() - st, err := NewStateTree(cst) + st, err := NewStateTree(cst, builtin2.VersionForNetwork(build.NewestNetworkVersion)) if err != nil { t.Fatal(err) } diff --git a/chain/stmgr/stmgr.go b/chain/stmgr/stmgr.go index 89ad6edd9..90154868e 100644 --- a/chain/stmgr/stmgr.go +++ b/chain/stmgr/stmgr.go @@ -1024,9 +1024,9 @@ func GetFilMined(ctx context.Context, st *state.StateTree) (abi.TokenAmount, err return big.Zero(), xerrors.Errorf("failed to load reward actor state: %w", err) } - var rst reward.State - if err := st.Store.Get(ctx, ractor.Head, &rst); err != nil { - return big.Zero(), xerrors.Errorf("failed to load reward state: %w", err) + rst, err := reward.Load(adt.WrapStore(ctx, st.Store), ractor) + if err != nil { + return big.Zero(), err } return rst.TotalStoragePowerReward() diff --git a/chain/stmgr/utils.go b/chain/stmgr/utils.go index 4fabefbff..8f39216c6 100644 --- a/chain/stmgr/utils.go +++ b/chain/stmgr/utils.go @@ -247,8 +247,18 @@ func GetSectorsForWinningPoSt(ctx context.Context, pv ffiwrapper.Verifier, sm *S out := make([]proof.SectorInfo, len(ids)) for i, n := range ids { + sb, err := provingSectors.Slice(n, 1) + if err != nil { + return nil, err + } + + sid, err := sb.First() + if err != nil { + return nil, err + } + var sinfo miner.SectorOnChainInfo - found, err := sectors.Get(n, &sinfo) + found, err := sectors.Get(sid, &sinfo) if err != nil { return nil, xerrors.Errorf("loading sector info: %w", err) diff --git a/cli/client.go b/cli/client.go index f6d529943..333938790 100644 --- a/cli/client.go +++ b/cli/client.go @@ -417,7 +417,7 @@ var clientDealCmd = &cli.Command{ return err } - isVerified := dcap != types.EmptyInt + isVerified := dcap != nil // If the user has explicitly set the --verified-deal flag if cctx.IsSet("verified-deal") { diff --git a/cmd/lotus-chainwatch/processor/market.go b/cmd/lotus-chainwatch/processor/market.go index a4bae4b20..17aa1c37b 100644 --- a/cmd/lotus-chainwatch/processor/market.go +++ b/cmd/lotus-chainwatch/processor/market.go @@ -300,8 +300,8 @@ func (p *Processor) updateMarketActorDealProposals(ctx context.Context, marketTi } for _, modified := range changes.Modified { - if modified.From.SlashEpoch() != modified.To.SlashEpoch() { - if _, err := stmt.Exec(modified.To.SlashEpoch(), modified.ID); err != nil { + if modified.From.SlashEpoch != modified.To.SlashEpoch { + if _, err := stmt.Exec(modified.To.SlashEpoch, modified.ID); err != nil { return err } } diff --git a/cmd/lotus-pcr/main.go b/cmd/lotus-pcr/main.go index d265bdd49..aa467e38a 100644 --- a/cmd/lotus-pcr/main.go +++ b/cmd/lotus-pcr/main.go @@ -417,24 +417,24 @@ func (r *refunder) ProcessTipset(ctx context.Context, tipset *types.TipSet, refu // We use the parent tipset key because precommit information is removed when ProveCommitSector is executed precommitChainInfo, err := r.api.StateSectorPreCommitInfo(ctx, m.To, sn, tipset.Parents()) if err != nil { - log.Warnw("failed to get precommit info for sector", "err", err, "method", messageMethod, "cid", msg.Cid, "miner", m.To, "sector_number", proveCommitSector.SectorNumber) + log.Warnw("failed to get precommit info for sector", "err", err, "method", messageMethod, "cid", msg.Cid, "miner", m.To, "sector_number", sn) continue } precommitTipset, err := r.api.ChainGetTipSetByHeight(ctx, precommitChainInfo.PreCommitEpoch, tipset.Key()) if err != nil { - log.Warnf("failed to lookup precommit epoch", "err", err, "method", messageMethod, "cid", msg.Cid, "miner", m.To, "sector_number", proveCommitSector.SectorNumber) + log.Warnf("failed to lookup precommit epoch", "err", err, "method", messageMethod, "cid", msg.Cid, "miner", m.To, "sector_number", sn) continue } collateral, err := r.api.StateMinerInitialPledgeCollateral(ctx, m.To, precommitChainInfo.Info, precommitTipset.Key()) if err != nil { - log.Warnw("failed to get initial pledge collateral", "err", err, "method", messageMethod, "cid", msg.Cid, "miner", m.To, "sector_number", proveCommitSector.SectorNumber) + log.Warnw("failed to get initial pledge collateral", "err", err, "method", messageMethod, "cid", msg.Cid, "miner", m.To, "sector_number", sn) } collateral = big.Sub(collateral, precommitChainInfo.PreCommitDeposit) if collateral.LessThan(big.Zero()) { - log.Debugw("skipping zero pledge collateral difference", "method", messageMethod, "cid", msg.Cid, "miner", m.To, "sector_number", proveCommitSector.SectorNumber) + log.Debugw("skipping zero pledge collateral difference", "method", messageMethod, "cid", msg.Cid, "miner", m.To, "sector_number", sn) continue } diff --git a/cmd/lotus-storage-miner/proving.go b/cmd/lotus-storage-miner/proving.go index d3e213752..ffc0946e3 100644 --- a/cmd/lotus-storage-miner/proving.go +++ b/cmd/lotus-storage-miner/proving.go @@ -1,7 +1,6 @@ package main import ( - "bytes" "fmt" "os" "text/tabwriter" @@ -73,12 +72,12 @@ var provingFaultsCmd = &cli.Command{ tw := tabwriter.NewWriter(os.Stdout, 2, 4, 2, ' ', 0) _, _ = fmt.Fprintln(tw, "deadline\tpartition\tsectors") err = mas.ForEachDeadline(func(dlIdx uint64, dl miner.Deadline) error { - dl.ForEachPartition(func(partIdx uint64, part miner.Partition) error { + return dl.ForEachPartition(func(partIdx uint64, part miner.Partition) error { faults, err := part.FaultySectors() if err != nil { return err } - faults.ForEach(func(num uint64) error { + return faults.ForEach(func(num uint64) error { _, _ = fmt.Fprintf(tw, "%d\t%d\t%d\n", dlIdx, partIdx, num) return nil }) @@ -173,6 +172,8 @@ var provingInfoCmd = &cli.Command{ } else { recovering += count } + + return nil }) }); err != nil { return xerrors.Errorf("walking miner deadlines and partitions: %w", err) @@ -250,22 +251,6 @@ var provingDeadlinesCmd = &cli.Command{ return xerrors.Errorf("getting deadlines: %w", err) } - var mas miner.State - { - mact, err := api.StateGetActor(ctx, maddr, types.EmptyTSK) - if err != nil { - return err - } - miner.Load - rmas, err := api.ChainReadObj(ctx, mact.Head) - if err != nil { - return err - } - if err := mas.UnmarshalCBOR(bytes.NewReader(rmas)); err != nil { - return err - } - } - fmt.Printf("Miner: %s\n", color.BlueString("%s", maddr)) tw := tabwriter.NewWriter(os.Stdout, 2, 4, 2, ' ', 0) diff --git a/conformance/driver.go b/conformance/driver.go index a33637837..66b6d0f8a 100644 --- a/conformance/driver.go +++ b/conformance/driver.go @@ -132,7 +132,7 @@ func (d *Driver) ExecuteMessage(bs blockstore.Blockstore, preroot cid.Cid, epoch BaseFee: BaseFee, } - lvm, err := vm.NewVM(vmOpts) + lvm, err := vm.NewVM(context.TODO(), vmOpts) if err != nil { return nil, cid.Undef, err } diff --git a/extern/storage-sealing/precommit_policy_test.go b/extern/storage-sealing/precommit_policy_test.go index b9c3ec49b..30b538a88 100644 --- a/extern/storage-sealing/precommit_policy_test.go +++ b/extern/storage-sealing/precommit_policy_test.go @@ -2,6 +2,8 @@ package sealing_test import ( "context" + "github.com/filecoin-project/go-state-types/network" + "github.com/filecoin-project/lotus/build" "testing" "github.com/ipfs/go-cid" @@ -18,6 +20,10 @@ type fakeChain struct { h abi.ChainEpoch } +func (f *fakeChain) StateNetworkVersion(ctx context.Context, tok sealing.TipSetToken) (network.Version, error) { + return build.NewestNetworkVersion, nil +} + func (f *fakeChain) ChainHead(ctx context.Context) (sealing.TipSetToken, abi.ChainEpoch, error) { return []byte{1, 2, 3}, f.h, nil } diff --git a/extern/storage-sealing/sealing.go b/extern/storage-sealing/sealing.go index e9a98fec9..6d60e7a6e 100644 --- a/extern/storage-sealing/sealing.go +++ b/extern/storage-sealing/sealing.go @@ -24,8 +24,8 @@ import ( "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" statemachine "github.com/filecoin-project/go-statemachine" - "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/actors/builtin/market" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" sectorstorage "github.com/filecoin-project/lotus/extern/sector-storage" "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" ) diff --git a/markets/storageadapter/provider.go b/markets/storageadapter/provider.go index 90bf28b41..04c1055df 100644 --- a/markets/storageadapter/provider.go +++ b/markets/storageadapter/provider.go @@ -108,7 +108,9 @@ func (n *ProviderNodeAdapter) OnDealComplete(ctx context.Context, deal storagema curTime := time.Now() for time.Since(curTime) < addPieceRetryTimeout { if !xerrors.Is(err, sealing.ErrTooManySectorsSealing) { - log.Errorf("failed to addPiece for deal %d, err: %w", deal.DealID, err) + if err != nil { + log.Errorf("failed to addPiece for deal %d, err: %w", deal.DealID, err) + } break } select { @@ -367,7 +369,7 @@ func (n *ProviderNodeAdapter) GetDataCap(ctx context.Context, addr address.Addre } sp, err := n.StateVerifiedClientStatus(ctx, addr, tsk) - return &sp, err + return sp, err } func (n *ProviderNodeAdapter) OnDealExpiredOrSlashed(ctx context.Context, dealID abi.DealID, onDealExpired storagemarket.DealExpiredCallback, onDealSlashed storagemarket.DealSlashedCallback) error { diff --git a/node/impl/full/state.go b/node/impl/full/state.go index 48f9d503c..04055043a 100644 --- a/node/impl/full/state.go +++ b/node/impl/full/state.go @@ -112,7 +112,7 @@ func (a *StateAPI) StateMinerInfo(ctx context.Context, actor address.Address, ts return mas.Info() } -func (a *StateAPI) StateMinerDeadlines(ctx context.Context, m address.Address, tsk types.TipSetKey) ([]*miner.Deadline, error) { +func (a *StateAPI) StateMinerDeadlines(ctx context.Context, m address.Address, tsk types.TipSetKey) ([]api.Deadline, error) { act, err := a.StateManager.LoadActorTsk(ctx, m, tsk) if err != nil { return nil, xerrors.Errorf("failed to load miner actor: %w", err) @@ -128,9 +128,16 @@ func (a *StateAPI) StateMinerDeadlines(ctx context.Context, m address.Address, t return nil, xerrors.Errorf("getting deadline count: %w", err) } - out := make([]*miner.Deadline, deadlines) + out := make([]api.Deadline, deadlines) if err := mas.ForEachDeadline(func(i uint64, dl miner.Deadline) error { - out[i] = &dl + ps, err := dl.PostSubmissions() + if err != nil { + return err + } + + out[i] = api.Deadline{ + PostSubmissions: ps, + } return nil }); err != nil { return nil, err @@ -138,7 +145,7 @@ func (a *StateAPI) StateMinerDeadlines(ctx context.Context, m address.Address, t return out, nil } -func (a *StateAPI) StateMinerPartitions(ctx context.Context, m address.Address, dlIdx uint64, tsk types.TipSetKey) ([]*miner.Partition, error) { +func (a *StateAPI) StateMinerPartitions(ctx context.Context, m address.Address, dlIdx uint64, tsk types.TipSetKey) ([]api.Partition, error) { act, err := a.StateManager.LoadActorTsk(ctx, m, tsk) if err != nil { return nil, xerrors.Errorf("failed to load miner actor: %w", err) @@ -154,10 +161,40 @@ func (a *StateAPI) StateMinerPartitions(ctx context.Context, m address.Address, return nil, xerrors.Errorf("failed to load the deadline: %w", err) } - var out []*miner.Partition + var out []api.Partition err = dl.ForEachPartition(func(_ uint64, part miner.Partition) error { - p := part - out = append(out, &p) + allSectors, err := part.AllSectors() + if err != nil { + return xerrors.Errorf("getting AllSectors: %w", err) + } + + faultySectors, err := part.FaultySectors() + if err != nil { + return xerrors.Errorf("getting FaultySectors: %w", err) + } + + recoveringSectors, err := part.RecoveringSectors() + if err != nil { + return xerrors.Errorf("getting RecoveringSectors: %w", err) + } + + liveSectors, err := part.LiveSectors() + if err != nil { + return xerrors.Errorf("getting LiveSectors: %w", err) + } + + activeSectors, err := part.ActiveSectors() + if err != nil { + return xerrors.Errorf("getting ActiveSectors: %w", err) + } + + out = append(out, api.Partition{ + AllSectors: allSectors, + FaultySectors: faultySectors, + RecoveringSectors: recoveringSectors, + LiveSectors: liveSectors, + ActiveSectors: activeSectors, + }) return nil }) @@ -1037,29 +1074,32 @@ func (a *StateAPI) StateMinerAvailableBalance(ctx context.Context, maddr address // StateVerifiedClientStatus returns the data cap for the given address. // Returns zero if there is no entry in the data cap table for the // address. -func (a *StateAPI) StateVerifiedClientStatus(ctx context.Context, addr address.Address, tsk types.TipSetKey) (abi.StoragePower, error) { +func (a *StateAPI) StateVerifiedClientStatus(ctx context.Context, addr address.Address, tsk types.TipSetKey) (*abi.StoragePower, error) { act, err := a.StateGetActor(ctx, builtin.VerifiedRegistryActorAddr, tsk) if err != nil { - return types.EmptyInt, err + return nil, err } aid, err := a.StateLookupID(ctx, addr, tsk) if err != nil { log.Warnf("lookup failure %v", err) - return types.EmptyInt, err + return nil, err } vrs, err := verifreg.Load(a.StateManager.ChainStore().Store(ctx), act) if err != nil { - return types.EmptyInt, xerrors.Errorf("failed to load verified registry state: %w", err) + return nil, xerrors.Errorf("failed to load verified registry state: %w", err) } - _, dcap, err := vrs.VerifiedClientDataCap(aid) + verified, dcap, err := vrs.VerifiedClientDataCap(aid) if err != nil { - return types.EmptyInt, xerrors.Errorf("looking up verified client: %w", err) + return nil, xerrors.Errorf("looking up verified client: %w", err) + } + if !verified { + return nil, nil } - return dcap, nil + return &dcap, nil } var dealProviderCollateralNum = types.NewInt(110) diff --git a/storage/adapter_storage_miner.go b/storage/adapter_storage_miner.go index 8db977d2c..efbd95817 100644 --- a/storage/adapter_storage_miner.go +++ b/storage/adapter_storage_miner.go @@ -84,7 +84,7 @@ func (s SealingAPIAdapter) StateMinerWorkerAddress(ctx context.Context, maddr ad return mi.Worker, nil } -func (s SealingAPIAdapter) StateMinerDeadlines(ctx context.Context, maddr address.Address, tok sealing.TipSetToken) ([]*miner.Deadline, error) { +func (s SealingAPIAdapter) StateMinerDeadlines(ctx context.Context, maddr address.Address, tok sealing.TipSetToken) ([]api.Deadline, error) { tsk, err := types.TipSetKeyFromBytes(tok) if err != nil { return nil, xerrors.Errorf("failed to unmarshal TipSetToken to TipSetKey: %w", err) @@ -190,7 +190,7 @@ func (s SealingAPIAdapter) StateSectorPreCommitInfo(ctx context.Context, maddr a if err != nil { return nil, err } - if pci != nil { + if pci == nil { set, err := state.IsAllocated(sectorNumber) if err != nil { return nil, xerrors.Errorf("checking if sector is allocated: %w", err) diff --git a/storage/miner.go b/storage/miner.go index 227c51961..d7780898d 100644 --- a/storage/miner.go +++ b/storage/miner.go @@ -76,7 +76,7 @@ type storageMinerApi interface { StateSectorGetInfo(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (*miner.SectorOnChainInfo, error) StateSectorPartition(ctx context.Context, maddr address.Address, sectorNumber abi.SectorNumber, tok types.TipSetKey) (*miner.SectorLocation, error) StateMinerInfo(context.Context, address.Address, types.TipSetKey) (miner.MinerInfo, error) - StateMinerDeadlines(context.Context, address.Address, types.TipSetKey) ([]*miner.Deadline, error) + StateMinerDeadlines(context.Context, address.Address, types.TipSetKey) ([]api.Deadline, error) StateMinerProvingDeadline(context.Context, address.Address, types.TipSetKey) (*dline.Info, error) StateMinerPreCommitDepositForPower(context.Context, address.Address, miner.SectorPreCommitInfo, types.TipSetKey) (types.BigInt, error) StateMinerInitialPledgeCollateral(context.Context, address.Address, miner.SectorPreCommitInfo, types.TipSetKey) (types.BigInt, error) From 68e884ee441f2ea3b02103536c0947788630612c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Thu, 17 Sep 2020 17:31:09 +0200 Subject: [PATCH 071/303] docsgen --- api/docgen/docgen.go | 1 + documentation/en/api-methods.md | 35 ++++++++++++++++++++++++++++----- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/api/docgen/docgen.go b/api/docgen/docgen.go index d00643a02..ced536cc3 100644 --- a/api/docgen/docgen.go +++ b/api/docgen/docgen.go @@ -114,6 +114,7 @@ func init() { addExample(retrievalmarket.ClientEventDealAccepted) addExample(retrievalmarket.DealStatusNew) addExample(network.ReachabilityPublic) + addExample(build.NewestNetworkVersion) addExample(&types.ExecutionTrace{ Msg: exampleValue(reflect.TypeOf(&types.Message{}), nil).(*types.Message), MsgRct: exampleValue(reflect.TypeOf(&types.MessageReceipt{}), nil).(*types.MessageReceipt), diff --git a/documentation/en/api-methods.md b/documentation/en/api-methods.md index 27875eca1..364a0f1be 100644 --- a/documentation/en/api-methods.md +++ b/documentation/en/api-methods.md @@ -149,6 +149,7 @@ * [StateMinerSectorCount](#StateMinerSectorCount) * [StateMinerSectors](#StateMinerSectors) * [StateNetworkName](#StateNetworkName) + * [StateNetworkVersion](#StateNetworkVersion) * [StateReadState](#StateReadState) * [StateReplay](#StateReplay) * [StateSearchMsg](#StateSearchMsg) @@ -211,7 +212,7 @@ Response: ```json { "Version": "string value", - "APIVersion": 3584, + "APIVersion": 3840, "BlockDelay": 42 } ``` @@ -3509,7 +3510,7 @@ Inputs: Response: `"0"` ### StateMinerPartitions -StateMinerPartitions loads miner partitions for the specified miner/deadline +StateMinerPartitions returns all partitions in the specified deadline Perms: read @@ -3563,7 +3564,8 @@ Response: "TotalPower": { "RawBytePower": "0", "QualityAdjPower": "0" - } + }, + "HasMinPower": true } ``` @@ -3697,8 +3699,9 @@ Inputs: Response: ```json { - "Sectors": 42, - "Active": 42 + "Live": 42, + "Active": 42, + "Faulty": 42 } ``` @@ -3741,6 +3744,28 @@ Inputs: `null` Response: `"lotus"` +### StateNetworkVersion +StateNetworkVersion returns the network version at the given tipset + + +Perms: read + +Inputs: +```json +[ + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: `2` + ### StateReadState StateReadState returns the indicated actor's state. From 82b95e34b790d300c273ce765fdd4f3704f610cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Thu, 17 Sep 2020 17:37:16 +0200 Subject: [PATCH 072/303] cbor gen --- chain/exchange/cbor_gen.go | 12 +-- chain/types/cbor_gen.go | 128 +++++++++++++++++++++++++ lotuspond/front/src/chain/methods.json | 3 +- 3 files changed, 136 insertions(+), 7 deletions(-) diff --git a/chain/exchange/cbor_gen.go b/chain/exchange/cbor_gen.go index dc91babe3..29b258081 100644 --- a/chain/exchange/cbor_gen.go +++ b/chain/exchange/cbor_gen.go @@ -146,7 +146,7 @@ func (t *Response) MarshalCBOR(w io.Writer) error { scratch := make([]byte, 9) - // t.Status (blocksync.status) (uint64) + // t.Status (exchange.status) (uint64) if err := cbg.WriteMajorTypeHeaderBuf(scratch, w, cbg.MajUnsignedInt, uint64(t.Status)); err != nil { return err @@ -164,7 +164,7 @@ func (t *Response) MarshalCBOR(w io.Writer) error { return err } - // t.Chain ([]*blocksync.BSTipSet) (slice) + // t.Chain ([]*exchange.BSTipSet) (slice) if len(t.Chain) > cbg.MaxLength { return xerrors.Errorf("Slice value in field t.Chain was too long") } @@ -198,7 +198,7 @@ func (t *Response) UnmarshalCBOR(r io.Reader) error { return fmt.Errorf("cbor input had wrong number of fields") } - // t.Status (blocksync.status) (uint64) + // t.Status (exchange.status) (uint64) { @@ -222,7 +222,7 @@ func (t *Response) UnmarshalCBOR(r io.Reader) error { t.ErrorMessage = string(sval) } - // t.Chain ([]*blocksync.BSTipSet) (slice) + // t.Chain ([]*exchange.BSTipSet) (slice) maj, extra, err = cbg.CborReadHeaderBuf(br, scratch) if err != nil { @@ -567,7 +567,7 @@ func (t *BSTipSet) MarshalCBOR(w io.Writer) error { } } - // t.Messages (blocksync.CompactedMessages) (struct) + // t.Messages (exchange.CompactedMessages) (struct) if err := t.Messages.MarshalCBOR(w); err != nil { return err } @@ -621,7 +621,7 @@ func (t *BSTipSet) UnmarshalCBOR(r io.Reader) error { t.Blocks[i] = &v } - // t.Messages (blocksync.CompactedMessages) (struct) + // t.Messages (exchange.CompactedMessages) (struct) { diff --git a/chain/types/cbor_gen.go b/chain/types/cbor_gen.go index 676ae7054..f95df33bc 100644 --- a/chain/types/cbor_gen.go +++ b/chain/types/cbor_gen.go @@ -1634,3 +1634,131 @@ func (t *BeaconEntry) UnmarshalCBOR(r io.Reader) error { } return nil } + +var lengthBufStateRoot = []byte{131} + +func (t *StateRoot) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + if _, err := w.Write(lengthBufStateRoot); err != nil { + return err + } + + scratch := make([]byte, 9) + + // t.Version (uint64) (uint64) + + if err := cbg.WriteMajorTypeHeaderBuf(scratch, w, cbg.MajUnsignedInt, uint64(t.Version)); err != nil { + return err + } + + // t.Actors (cid.Cid) (struct) + + if err := cbg.WriteCidBuf(scratch, w, t.Actors); err != nil { + return xerrors.Errorf("failed to write cid field t.Actors: %w", err) + } + + // t.Info (cid.Cid) (struct) + + if err := cbg.WriteCidBuf(scratch, w, t.Info); err != nil { + return xerrors.Errorf("failed to write cid field t.Info: %w", err) + } + + return nil +} + +func (t *StateRoot) UnmarshalCBOR(r io.Reader) error { + *t = StateRoot{} + + br := cbg.GetPeeker(r) + scratch := make([]byte, 8) + + maj, extra, err := cbg.CborReadHeaderBuf(br, scratch) + if err != nil { + return err + } + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 3 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Version (uint64) (uint64) + + { + + maj, extra, err = cbg.CborReadHeaderBuf(br, scratch) + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Version = uint64(extra) + + } + // t.Actors (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(br) + if err != nil { + return xerrors.Errorf("failed to read cid field t.Actors: %w", err) + } + + t.Actors = c + + } + // t.Info (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(br) + if err != nil { + return xerrors.Errorf("failed to read cid field t.Info: %w", err) + } + + t.Info = c + + } + return nil +} + +var lengthBufStateInfo = []byte{128} + +func (t *StateInfo) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + if _, err := w.Write(lengthBufStateInfo); err != nil { + return err + } + + return nil +} + +func (t *StateInfo) UnmarshalCBOR(r io.Reader) error { + *t = StateInfo{} + + br := cbg.GetPeeker(r) + scratch := make([]byte, 8) + + maj, extra, err := cbg.CborReadHeaderBuf(br, scratch) + if err != nil { + return err + } + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 0 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + return nil +} diff --git a/lotuspond/front/src/chain/methods.json b/lotuspond/front/src/chain/methods.json index ad1076c84..ce4919cc4 100644 --- a/lotuspond/front/src/chain/methods.json +++ b/lotuspond/front/src/chain/methods.json @@ -23,7 +23,8 @@ "AddSigner", "RemoveSigner", "SwapSigner", - "ChangeNumApprovalsThreshold" + "ChangeNumApprovalsThreshold", + "LockBalance" ], "fil/1/paymentchannel": [ "Send", From c40c1361f0307f888d3812d78aff70883aa550c4 Mon Sep 17 00:00:00 2001 From: Dirk McCormick Date: Thu, 17 Sep 2020 18:14:07 +0200 Subject: [PATCH 073/303] fix: paych To() --- chain/actors/builtin/paych/v0.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chain/actors/builtin/paych/v0.go b/chain/actors/builtin/paych/v0.go index 16a65bc9b..7d63b8913 100644 --- a/chain/actors/builtin/paych/v0.go +++ b/chain/actors/builtin/paych/v0.go @@ -22,7 +22,7 @@ func (s *v0State) From() address.Address { // Recipient of payouts from channel func (s *v0State) To() address.Address { - return s.State.From + return s.State.To } // Height at which the channel can be `Collected` From 14a4acec8cefd4e64ba7919b7b0539f49c0e9ef7 Mon Sep 17 00:00:00 2001 From: jennijuju Date: Wed, 16 Sep 2020 17:43:55 -0400 Subject: [PATCH 074/303] Add an option to hide sectors in Removed for `sectors list`. --- cmd/lotus-storage-miner/sectors.go | 33 +++++++++++++++++++----------- 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/cmd/lotus-storage-miner/sectors.go b/cmd/lotus-storage-miner/sectors.go index 06f09fe20..0e6fe8435 100644 --- a/cmd/lotus-storage-miner/sectors.go +++ b/cmd/lotus-storage-miner/sectors.go @@ -2,6 +2,7 @@ package main import ( "fmt" + sealing "github.com/filecoin-project/lotus/extern/storage-sealing" "os" "sort" "strconv" @@ -136,6 +137,12 @@ var sectorsStatusCmd = &cli.Command{ var sectorsListCmd = &cli.Command{ Name: "list", Usage: "List sectors", + Flags: []cli.Flag{ + &cli.BoolFlag{ + Name: "hide-removed", + Usage: "to hide Removed sectors", + }, + }, Action: func(cctx *cli.Context) error { nodeApi, closer, err := lcli.GetStorageMinerAPI(cctx) if err != nil { @@ -192,19 +199,21 @@ var sectorsListCmd = &cli.Command{ continue } - _, inSSet := commitedIDs[s] - _, inASet := activeIDs[s] + if !cctx.Bool("hide-removed") || st.State != api.SectorState(sealing.Removed) { + _, inSSet := commitedIDs[s] + _, inASet := activeIDs[s] - fmt.Fprintf(w, "%d: %s\tsSet: %s\tactive: %s\ttktH: %d\tseedH: %d\tdeals: %v\t toUpgrade:%t\n", - s, - st.State, - yesno(inSSet), - yesno(inASet), - st.Ticket.Epoch, - st.Seed.Epoch, - st.Deals, - st.ToUpgrade, - ) + fmt.Fprintf(w, "%d: %s\tsSet: %s\tactive: %s\ttktH: %d\tseedH: %d\tdeals: %v\t toUpgrade:%t\n", + s, + st.State, + yesno(inSSet), + yesno(inASet), + st.Ticket.Epoch, + st.Seed.Epoch, + st.Deals, + st.ToUpgrade, + ) + } } return w.Flush() From a4fd356fcbc20f38657c128ceb291c2db42f150a Mon Sep 17 00:00:00 2001 From: Hector Sanjuan Date: Thu, 17 Sep 2020 20:35:19 +0200 Subject: [PATCH 075/303] Delete most docs. Update about page with links to docs.filecoin.io --- documentation/en/.glossary.json | 147 +- documentation/en/.library.json | 202 +- documentation/en/about.md | 19 +- documentation/en/building/api-methods.md | 4567 ----------------- .../en/building/api-troubleshooting.md | 36 - documentation/en/building/api.md | 38 - documentation/en/building/building.md | 5 - documentation/en/building/jaeger-tracing.md | 26 - documentation/en/building/local-devnet.md | 54 - documentation/en/building/payment-channels.md | 111 - documentation/en/building/remote-api.md | 69 - .../en/getting-started/getting-started.md | 3 - .../getting-started/setup-troubleshooting.md | 57 - documentation/en/getting-started/setup.md | 169 - documentation/en/getting-started/wallet.md | 58 - .../en/installation/install-linux.md | 129 - .../en/installation/install-macos.md | 62 - documentation/en/installation/installation.md | 39 - documentation/en/installation/update.md | 72 - documentation/en/mining/gpus.md | 17 - documentation/en/mining/lotus-seal-worker.md | 99 - documentation/en/mining/managing-deals.md | 19 - documentation/en/mining/miner-setup.md | 241 - .../en/mining/mining-troubleshooting.md | 59 - documentation/en/mining/mining.md | 8 - documentation/en/store/adding-from-ipfs.md | 20 - documentation/en/store/making-deals.md | 71 - documentation/en/store/retrieve.md | 27 - .../en/store/storage-troubleshooting.md | 30 - documentation/en/store/store.md | 11 - 30 files changed, 14 insertions(+), 6451 deletions(-) delete mode 100644 documentation/en/building/api-methods.md delete mode 100644 documentation/en/building/api-troubleshooting.md delete mode 100644 documentation/en/building/api.md delete mode 100644 documentation/en/building/building.md delete mode 100644 documentation/en/building/jaeger-tracing.md delete mode 100644 documentation/en/building/local-devnet.md delete mode 100644 documentation/en/building/payment-channels.md delete mode 100644 documentation/en/building/remote-api.md delete mode 100644 documentation/en/getting-started/getting-started.md delete mode 100644 documentation/en/getting-started/setup-troubleshooting.md delete mode 100644 documentation/en/getting-started/setup.md delete mode 100644 documentation/en/getting-started/wallet.md delete mode 100644 documentation/en/installation/install-linux.md delete mode 100644 documentation/en/installation/install-macos.md delete mode 100644 documentation/en/installation/installation.md delete mode 100644 documentation/en/installation/update.md delete mode 100644 documentation/en/mining/gpus.md delete mode 100644 documentation/en/mining/lotus-seal-worker.md delete mode 100644 documentation/en/mining/managing-deals.md delete mode 100644 documentation/en/mining/miner-setup.md delete mode 100644 documentation/en/mining/mining-troubleshooting.md delete mode 100644 documentation/en/mining/mining.md delete mode 100644 documentation/en/store/adding-from-ipfs.md delete mode 100644 documentation/en/store/making-deals.md delete mode 100644 documentation/en/store/retrieve.md delete mode 100644 documentation/en/store/storage-troubleshooting.md delete mode 100644 documentation/en/store/store.md diff --git a/documentation/en/.glossary.json b/documentation/en/.glossary.json index e8a9e0846..0967ef424 100644 --- a/documentation/en/.glossary.json +++ b/documentation/en/.glossary.json @@ -1,146 +1 @@ -{ - "bellman": { - "title": "Bellman", - "value": "Bellman is a rust crate for building zk-SNARK circuits. It provides circuit traits and primitive structures, as well as basic gadget implementations such as booleans and number abstractions." - }, - "nvme": { - "title": "NVMe", - "value": "(non-volatile memory express) is a host controller interface and storage protocol created to accelerate the transfer of data between enterprise and client systems and solid-state drives (SSDs) over a computer's high-speed Peripheral Component Interconnect Express (PCIe) bus." - }, - "multiaddr": { - "title": "Multiaddr", - "value": "Multiaddr is a format for encoding addresses from various well-established network protocols. It is useful to write applications that future-proof their use of addresses, and allow multiple transport protocols and addresses to coexist." - }, - "attofil": { - "title": "attoFIL", - "value": "AttoFIL is a word used to describe 10^-18 FIL. The word atto comes from the Norwegian and Danish term: atten eighteen." - }, - "fil": { - "title": "FIL", - "value": "A ticker symbol is an abbreviation used to uniquely identify Filecoin when it is used in a wallet exchange or a cryptocurrency exchange." - }, - "epost": { - "title": "Election Proof-of-Spacetime", - "value": "Election Proof-of-Spacetime couples the Proof-of-Spacetime process with block production, meaning that in order to produce a block, the miner must produce a valid Proof-of-Spacetime proof (snark output)." - }, - "jwt": { - "title": "JWT", - "value": "JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties." - }, - "json-rpc": { - "title": "JSON-RPC", - "value": "JSON-RPC is a remote procedure call protocol encoded in JSON. It is a very simple protocol (and very similar to XML-RPC), defining only a few data types and commands." - }, - "bls-address": { - "title": "BLS Signature (Address)", - "value": "A Boneh–Lynn–Shacham (BLS) signature is a digital signature scheme that allows a user to determine the authenticity of a signer, and is a commonly used signature scheme in the Filecoin Distributed Storage Network." - }, - "faucet": { - "title": "Filecoin Test Faucet", - "value": "A webpage where you can get free test Filecoin to participate in the Testnet." - }, - "chain": { - "title": "Chain", - "value": "The Filecoin Blockchain is a distributed virtual machine that achieves consensus, processes messages, accounts for storage, and maintains security in the Filecoin Protocol. It is the main interface linking various actors in the Filecoin system." - }, - "miner-power": { - "title": "Miner Power", - "value": "Miner storage in relation to network storage, tracked in the power table." - }, - "sector": { - "title": "Sector", - "value": "A fixed-size block of data of SECTOR_SIZE bytes which generally contains client's data." - }, - "sealing": { - "title": "Sealing", - "value": "A slow encoding process that returns commitments and proofs for data being stored in a sector." - }, - "seal": { - "title": "Seal", - "value": "A slow encoding process that returns commitments and proofs for data being stored in a sector." - }, - "posts": { - "title": "Proof-of-Spacetime(s)", - "value": "Filecoin is a protocol token whose blockchain runs on a novel proof, called Proof-of-Spacetime, where blocks are created by miners that are storing data." - }, - "filecoin-testnet": { - "title": "Filecoin Testnet", - "value": "Until we launch, we are making lots of changes to Lotus. The Testnet is expected to bring a few significant fixes/improvements. During Testnet, you can retrieve test filecoin from our network faucet to use as collateral to start mining. Test filecoin do not have any value – the official filecoin tokens will not be released until Mainnet launch." - }, - "filecoin-decentralized-storage-market": { - "title": "Filecoin Decentralized Storage Market", - "value": "Storage Market subsystem is the data entry point into the network. Miners only earn power from data stored in a storage deal and all deals live on the Filecoin network." - }, - "filecoin-proof-parameters": { - "title": "Filecoin Proof Parameters", - "value": "The proving algorithms rely on a large binary parameter file." - }, - "lotus-devnet": { - "title": "DevNet", - "value": "On the DevNets, you can store data as a storage client and also try how Filecoin mining works. The devnets are an important development tool for those who anticipate building applications on top of the Filecoin protocol or storing data on the decentralized storage market. " - }, - "filecoin-distributed-storage-network": { - "title": "Filecoin Distributed Storage Network", - "value": "Filecoin is a distributed storage network based on a blockchain mechanism. Filecoin miners can elect to provide storage capacity for the network, and thereby earn units of the Filecoin cryptocurrency (FIL) by periodically producing cryptographic proofs that certify that they are providing the capacity specified." - }, - "lotus-node": { - "title": "Lotus Node", - "value": "The Lotus Node is full of capabilities. It runs the Blockchain system, makes retrieval deals, does data transfer, supports block producer logic, and syncs and validates the chain." - }, - "block-rewards": { - "title": "Block Reward", - "value": "Over the entire lifetime of the protocol, 1,400,000,000 FIL (TotalIssuance) will be given out to miners. The rate at which the funds are given out is set to halve every six years, smoothly (not a fixed jump like in Bitcoin)." - }, - "block-producer-miner": { - "title": "Miner (Block Producer)", - "value": "The Block Producer Miner's logic. It currently shares an interface and process with the Lotus Node. A Block Producer chooses which messages to include in a block and is rewarded according to each message’s gas price and consumption, forming a market." - }, - "lotus-miner": { - "title": "Miner (lotus-miner)", - "value": "The Miner's logic. It has its own dedicated process. Contributes to the network through Sector commitments and Proofs of Spacetime to prove that it is storing the sectors it has commited to." - }, - "swarm-port": { - "title": "Swarm Port (Libp2p)", - "value": "The LibP2P Swarm manages groups of connections to peers, handles incoming and outgoing streams, and is part of the miners implementation. The port value is part of the Host interface." - }, - "daemon": { - "title": "Lotus Daemon", - "value": "A Daemon is a program that runs as a background process. A Daemon in the context of the Filecoin Distributed Storage Network may enable applications to communicate with peers, handle protocols, participate in pubsub, and interact with a distributed hash table (DHT)." - }, - "storage-deal": { - "title": "Storage deal", - "value": "One of the two types of deals in Filecoin markets. Storage deals are recorded on the blockchain and enforced by the protocol." - }, - "retrieval-deal": { - "title": "Retrieval deal", - "value": "One of the two types of deals in Filecoin markets. Retrieval deals are off chain and enabled by micropayment channel by transacting parties." - }, - "deal-cid": { - "title": "Deal CID", - "value": "CID is a format for referencing content in distributed information systems, it is a way to store information so it can be retrieved based on its content, not its location. DealCID specifically is used in storage deals." - }, - "data-cid": { - "title": "Data CID", - "value": "CID is a format for referencing content in distributed information systems, it is a way to store information so it can be retrieved based on its content, not its location. DataCID specifically is used to represent the file that is stored in the Filecoin Distributed Storage Network." - }, - "cid": { - "title": "CID", - "value": "A CID is a self-describing content-addressed identifier. It uses cryptographic hashes to achieve content addressing. It uses several multiformats to achieve flexible self-description, namely multihash for hashes, multicodec for data content types, and multibase to encode the CID itself into strings." - }, - "total-network-power": { - "title": "Total Network Power", - "value": "A reference to all the Power Tables for every subchain, accounting for each Lotus Miner on chain." - }, - "chain-block-height": { - "title": "Chain Block Height", - "value": "Chain block height is defined as the number of blocks in the chain between any given block and the very first block in the blockchain." - }, - "block-height": { - "title": "Block Height", - "value": "Height of the Merkle Tree of a sector. A sector is a contiguous array of bytes that a miner puts together, seals, and performs Proofs of Spacetime on." - }, - "blocktime": { - "title": "Blocktime", - "value": "The time it takes for a Block to propagate to the whole network." - } -} +{} diff --git a/documentation/en/.library.json b/documentation/en/.library.json index 59cc01e29..e31f09950 100644 --- a/documentation/en/.library.json +++ b/documentation/en/.library.json @@ -2,194 +2,11 @@ "posts": [ { "title": "About Lotus", - "slug": "en+lotus", + "slug": "", "github": "en/about.md", "value": null, "posts": [] }, - { - "title": "Installation", - "slug": "en+install", - "github": "en/installation/installation.md", - "value": null, - "posts": [ - { - "title": "Linux installation", - "slug": "en+install-linux", - "github": "en/installation/install-linux.md", - "value": null - }, - { - "title": "MacOS installation", - "slug": "en+install-macos", - "github": "en/installation/install-macos.md", - "value": null - }, - { - "title": "Updating Lotus", - "slug": "en+update", - "github": "en/installation/update.md", - "value": null - } - ] - }, - { - "title": "Getting started", - "slug": "en+getting-started", - "github": "en/getting-started/getting-started.md", - "value": null, - "posts": [ - { - "title": "Setting up Lotus", - "slug": "en+setup", - "github": "en/getting-started/setup.md", - "value": null - }, - { - - "title": "Obtaining and sending FIL", - "slug": "en+wallet", - "github": "en/getting-started/wallet.md", - "value": null - }, - { - "title": "Setup troubleshooting", - "slug": "en+setup-troubleshooting", - "github": "en/getting-started/setup-troubleshooting.md", - "value": null - } - ] - }, - { - "title": "Storing and retrieving data", - "slug": "en+store", - "github": "en/store/store.md", - "value": null, - "posts": [ - { - "title": "Making storage deals", - "slug": "en+making-deals", - "github": "en/store/making-deals.md", - "value": null - }, - { - "title": "Adding data from IPFS", - "slug": "en+adding-from-ipfs", - "github": "en/store/adding-from-ipfs.md", - "value": null - }, - { - "title": "Retrieving data", - "slug": "en+retriving", - "github": "en/store/retrieve.md", - "value": null - }, - { - "title": "Storage Troubleshooting", - "slug": "en+storage-troubleshooting", - "github": "en/store/storage-troubleshooting.md", - "value": null - } - ] - }, - { - "title": "Storage mining", - "slug": "en+mining", - "github": "en/mining/mining.md", - "value": null, - "posts": [ - { - "title": "Miner setup", - "slug": "en+miner-setup", - "github": "en/mining/miner-setup.md", - "value": null - }, - { - "title": "Managing deals", - "slug": "en+managing-deals", - "github": "en/mining/managing-deals.md", - "value": null - }, - { - "title": "Lotus Worker", - "slug": "en+lotus-worker", - "github": "en/mining/lotus-seal-worker.md", - "value": null - }, - { - "title": "Benchmarking GPUs", - "slug": "en+gpus", - "github": "en/mining/gpus.md", - "value": null - }, - { - "title": "Mining Troubleshooting", - "slug": "en+mining-troubleshooting", - "github": "en/mining/mining-troubleshooting.md", - "value": null - } - ] - }, - { - "title": "Building", - "slug": "en+building", - "github": "en/building/building.md", - "value": null, - "posts": [ - { - "title": "Setting up remote API access", - "slug": "en+remote-api", - "github": "en/building/remote-api.md", - "value": null, - "posts": [] - }, - { - "title": "API endpoints and methods", - "slug": "en+api", - "github": "en/building/api.md", - "value": null, - "posts": [] - }, - { - "title": "API Reference", - "slug": "en+api-methods", - "github": "en/building/api-methods.md", - "value": null, - "posts": [] - }, - - { - "title": "Payment Channels", - "slug": "en+payment-channels", - "github": "en/building/payment-channels.md", - "value": null, - "posts": [] - }, - - { - "title": "Running a local devnet", - "slug": "en+local-devnet", - "github": "en/building/local-devnet.md", - "value": null, - "posts": [] - }, - { - "title": "Jaeger Tracing", - "slug": "en+jaeger-tracing", - "github": "en/building/jaeger-tracing.md", - "value": null, - "posts": [] - }, - - { - "title": "API Troubleshooting", - "slug": "en+api-troubleshooting", - "github": "en/building/api-troubleshooting.md", - "value": null, - "posts": [] - } - ] - }, { "title": "Lotus Architecture (WIP)", "slug": "en+arch", @@ -203,23 +20,6 @@ "value": null } ] - }, - { - "title": "FAQs", - "slug": "en+faqs", - "github": "en/faqs.md", - "value": null, - "posts": [] - }, - { - "title": "Glossary", - "slug": "en+glossary", - "github": "en/.glossary.json", - "value": null, - "custom": { - "glossary": true - }, - "posts": [] } ] } diff --git a/documentation/en/about.md b/documentation/en/about.md index ee8536ac9..f2051e00b 100644 --- a/documentation/en/about.md +++ b/documentation/en/about.md @@ -2,13 +2,18 @@ Lotus is an implementation of the **Filecoin Distributed Storage Network**. -The **Lotus Node** (and the mining applications) can be built to join any of the [Filecoin networks](https://docs.filecoin.io/how-to/networks/). +It is written in Go and provides a suite of command-line applications: -For more details about Filecoin, check out the [Filecoin Docs](https://docs.filecoin.io) and [Filecoin Spec](https://filecoin-project.github.io/specs/). +- Lotus Node (`lotus`): a Filecoin Node: validates network transactions, manages a FIL wallet, can perform storage and retrieval deals. +- Lotus Miner (`lotus-miner`): a Filecoin miner. See the the respective Lotus Miner section in the Mine documentation. +- Lotus Worker (`lotus-worker`): a worker that assists miners to perform mining-related tasks. See its respective guide for more information. -## What can I learn here? +The [Lotus user documentation](https://docs.filecoin.io/get-started/lotus) is part of the [Filecoin documentation site](https://docs.filecoin.io): + +* To install and get started with Lotus, visit the [Get Started section](https://docs.filecoin.io/get-started/lotus). +* Information about how to perform deals on the Filecoin network using Lotus can be found in the [Store section](https://docs.filecoin.io/store/lotus). +* Miners looking to provide storage to the Network can find the latest guides in the [Mine section](https://docs.filecoin.io/mine/lotus). +* Developers and integrators that wish to use the Lotus APIs can start in the [Build section](https://docs.filecoin.io/mine/lotus). + +For more details about Filecoin, check out the [Filecoin Docs](https://docs.filecoin.io) and [Filecoin Spec](https://spec.filecoin.io/). -* How to [install](en+installation) and [setup](en+setup) the Lotus software -* How to [store data on the Filecoin network](en+store) -* How to [setup a high performance FIL miner](en+miner-setup) -* How to [configure and access Lotus APIs](en+remote-api) diff --git a/documentation/en/building/api-methods.md b/documentation/en/building/api-methods.md deleted file mode 100644 index 2f3164bb7..000000000 --- a/documentation/en/building/api-methods.md +++ /dev/null @@ -1,4567 +0,0 @@ -# Groups -* [](#) - * [Closing](#Closing) - * [Shutdown](#Shutdown) - * [Version](#Version) -* [Auth](#Auth) - * [AuthNew](#AuthNew) - * [AuthVerify](#AuthVerify) -* [Beacon](#Beacon) - * [BeaconGetEntry](#BeaconGetEntry) -* [Chain](#Chain) - * [ChainExport](#ChainExport) - * [ChainGetBlock](#ChainGetBlock) - * [ChainGetBlockMessages](#ChainGetBlockMessages) - * [ChainGetGenesis](#ChainGetGenesis) - * [ChainGetMessage](#ChainGetMessage) - * [ChainGetNode](#ChainGetNode) - * [ChainGetParentMessages](#ChainGetParentMessages) - * [ChainGetParentReceipts](#ChainGetParentReceipts) - * [ChainGetPath](#ChainGetPath) - * [ChainGetRandomnessFromBeacon](#ChainGetRandomnessFromBeacon) - * [ChainGetRandomnessFromTickets](#ChainGetRandomnessFromTickets) - * [ChainGetTipSet](#ChainGetTipSet) - * [ChainGetTipSetByHeight](#ChainGetTipSetByHeight) - * [ChainHasObj](#ChainHasObj) - * [ChainHead](#ChainHead) - * [ChainNotify](#ChainNotify) - * [ChainReadObj](#ChainReadObj) - * [ChainSetHead](#ChainSetHead) - * [ChainStatObj](#ChainStatObj) - * [ChainTipSetWeight](#ChainTipSetWeight) -* [Client](#Client) - * [ClientCalcCommP](#ClientCalcCommP) - * [ClientDataTransferUpdates](#ClientDataTransferUpdates) - * [ClientDealSize](#ClientDealSize) - * [ClientFindData](#ClientFindData) - * [ClientGenCar](#ClientGenCar) - * [ClientGetDealInfo](#ClientGetDealInfo) - * [ClientGetDealUpdates](#ClientGetDealUpdates) - * [ClientHasLocal](#ClientHasLocal) - * [ClientImport](#ClientImport) - * [ClientListDataTransfers](#ClientListDataTransfers) - * [ClientListDeals](#ClientListDeals) - * [ClientListImports](#ClientListImports) - * [ClientMinerQueryOffer](#ClientMinerQueryOffer) - * [ClientQueryAsk](#ClientQueryAsk) - * [ClientRemoveImport](#ClientRemoveImport) - * [ClientRetrieve](#ClientRetrieve) - * [ClientRetrieveTryRestartInsufficientFunds](#ClientRetrieveTryRestartInsufficientFunds) - * [ClientRetrieveWithEvents](#ClientRetrieveWithEvents) - * [ClientStartDeal](#ClientStartDeal) -* [Gas](#Gas) - * [GasEstimateFeeCap](#GasEstimateFeeCap) - * [GasEstimateGasLimit](#GasEstimateGasLimit) - * [GasEstimateGasPremium](#GasEstimateGasPremium) - * [GasEstimateMessageGas](#GasEstimateMessageGas) -* [I](#I) - * [ID](#ID) -* [Log](#Log) - * [LogList](#LogList) - * [LogSetLevel](#LogSetLevel) -* [Market](#Market) - * [MarketEnsureAvailable](#MarketEnsureAvailable) -* [Miner](#Miner) - * [MinerCreateBlock](#MinerCreateBlock) - * [MinerGetBaseInfo](#MinerGetBaseInfo) -* [Mpool](#Mpool) - * [MpoolClear](#MpoolClear) - * [MpoolGetConfig](#MpoolGetConfig) - * [MpoolGetNonce](#MpoolGetNonce) - * [MpoolPending](#MpoolPending) - * [MpoolPush](#MpoolPush) - * [MpoolPushMessage](#MpoolPushMessage) - * [MpoolSelect](#MpoolSelect) - * [MpoolSetConfig](#MpoolSetConfig) - * [MpoolSub](#MpoolSub) -* [Msig](#Msig) - * [MsigAddApprove](#MsigAddApprove) - * [MsigAddCancel](#MsigAddCancel) - * [MsigAddPropose](#MsigAddPropose) - * [MsigApprove](#MsigApprove) - * [MsigCancel](#MsigCancel) - * [MsigCreate](#MsigCreate) - * [MsigGetAvailableBalance](#MsigGetAvailableBalance) - * [MsigGetVested](#MsigGetVested) - * [MsigPropose](#MsigPropose) - * [MsigSwapApprove](#MsigSwapApprove) - * [MsigSwapCancel](#MsigSwapCancel) - * [MsigSwapPropose](#MsigSwapPropose) -* [Net](#Net) - * [NetAddrsListen](#NetAddrsListen) - * [NetAgentVersion](#NetAgentVersion) - * [NetAutoNatStatus](#NetAutoNatStatus) - * [NetBandwidthStats](#NetBandwidthStats) - * [NetBandwidthStatsByPeer](#NetBandwidthStatsByPeer) - * [NetBandwidthStatsByProtocol](#NetBandwidthStatsByProtocol) - * [NetConnect](#NetConnect) - * [NetConnectedness](#NetConnectedness) - * [NetDisconnect](#NetDisconnect) - * [NetFindPeer](#NetFindPeer) - * [NetPeers](#NetPeers) - * [NetPubsubScores](#NetPubsubScores) -* [Paych](#Paych) - * [PaychAllocateLane](#PaychAllocateLane) - * [PaychAvailableFunds](#PaychAvailableFunds) - * [PaychAvailableFundsByFromTo](#PaychAvailableFundsByFromTo) - * [PaychCollect](#PaychCollect) - * [PaychGet](#PaychGet) - * [PaychGetWaitReady](#PaychGetWaitReady) - * [PaychList](#PaychList) - * [PaychNewPayment](#PaychNewPayment) - * [PaychSettle](#PaychSettle) - * [PaychStatus](#PaychStatus) - * [PaychVoucherAdd](#PaychVoucherAdd) - * [PaychVoucherCheckSpendable](#PaychVoucherCheckSpendable) - * [PaychVoucherCheckValid](#PaychVoucherCheckValid) - * [PaychVoucherCreate](#PaychVoucherCreate) - * [PaychVoucherList](#PaychVoucherList) - * [PaychVoucherSubmit](#PaychVoucherSubmit) -* [State](#State) - * [StateAccountKey](#StateAccountKey) - * [StateAllMinerFaults](#StateAllMinerFaults) - * [StateCall](#StateCall) - * [StateChangedActors](#StateChangedActors) - * [StateCirculatingSupply](#StateCirculatingSupply) - * [StateCompute](#StateCompute) - * [StateDealProviderCollateralBounds](#StateDealProviderCollateralBounds) - * [StateGetActor](#StateGetActor) - * [StateGetReceipt](#StateGetReceipt) - * [StateListActors](#StateListActors) - * [StateListMessages](#StateListMessages) - * [StateListMiners](#StateListMiners) - * [StateLookupID](#StateLookupID) - * [StateMarketBalance](#StateMarketBalance) - * [StateMarketDeals](#StateMarketDeals) - * [StateMarketParticipants](#StateMarketParticipants) - * [StateMarketStorageDeal](#StateMarketStorageDeal) - * [StateMinerActiveSectors](#StateMinerActiveSectors) - * [StateMinerAvailableBalance](#StateMinerAvailableBalance) - * [StateMinerDeadlines](#StateMinerDeadlines) - * [StateMinerFaults](#StateMinerFaults) - * [StateMinerInfo](#StateMinerInfo) - * [StateMinerInitialPledgeCollateral](#StateMinerInitialPledgeCollateral) - * [StateMinerPartitions](#StateMinerPartitions) - * [StateMinerPower](#StateMinerPower) - * [StateMinerPreCommitDepositForPower](#StateMinerPreCommitDepositForPower) - * [StateMinerProvingDeadline](#StateMinerProvingDeadline) - * [StateMinerRecoveries](#StateMinerRecoveries) - * [StateMinerSectorCount](#StateMinerSectorCount) - * [StateMinerSectors](#StateMinerSectors) - * [StateMsgGasCost](#StateMsgGasCost) - * [StateNetworkName](#StateNetworkName) - * [StateReadState](#StateReadState) - * [StateReplay](#StateReplay) - * [StateSearchMsg](#StateSearchMsg) - * [StateSectorExpiration](#StateSectorExpiration) - * [StateSectorGetInfo](#StateSectorGetInfo) - * [StateSectorPartition](#StateSectorPartition) - * [StateSectorPreCommitInfo](#StateSectorPreCommitInfo) - * [StateVerifiedClientStatus](#StateVerifiedClientStatus) - * [StateWaitMsg](#StateWaitMsg) -* [Sync](#Sync) - * [SyncCheckBad](#SyncCheckBad) - * [SyncCheckpoint](#SyncCheckpoint) - * [SyncIncomingBlocks](#SyncIncomingBlocks) - * [SyncMarkBad](#SyncMarkBad) - * [SyncState](#SyncState) - * [SyncSubmitBlock](#SyncSubmitBlock) - * [SyncUnmarkBad](#SyncUnmarkBad) -* [Wallet](#Wallet) - * [WalletBalance](#WalletBalance) - * [WalletDefaultAddress](#WalletDefaultAddress) - * [WalletDelete](#WalletDelete) - * [WalletExport](#WalletExport) - * [WalletHas](#WalletHas) - * [WalletImport](#WalletImport) - * [WalletList](#WalletList) - * [WalletNew](#WalletNew) - * [WalletSetDefault](#WalletSetDefault) - * [WalletSign](#WalletSign) - * [WalletSignMessage](#WalletSignMessage) - * [WalletVerify](#WalletVerify) -## - - -### Closing - - -Perms: read - -Inputs: `null` - -Response: `{}` - -### Shutdown - - -Perms: admin - -Inputs: `null` - -Response: `{}` - -### Version - - -Perms: read - -Inputs: `null` - -Response: -```json -{ - "Version": "string value", - "APIVersion": 3584, - "BlockDelay": 42 -} -``` - -## Auth - - -### AuthNew - - -Perms: admin - -Inputs: -```json -[ - null -] -``` - -Response: `"Ynl0ZSBhcnJheQ=="` - -### AuthVerify - - -Perms: read - -Inputs: -```json -[ - "string value" -] -``` - -Response: `null` - -## Beacon -The Beacon method group contains methods for interacting with the random beacon (DRAND) - - -### BeaconGetEntry -BeaconGetEntry returns the beacon entry for the given filecoin epoch. If -the entry has not yet been produced, the call will block until the entry -becomes available - - -Perms: read - -Inputs: -```json -[ - 10101 -] -``` - -Response: -```json -{ - "Round": 42, - "Data": "Ynl0ZSBhcnJheQ==" -} -``` - -## Chain -The Chain method group contains methods for interacting with the -blockchain, but that do not require any form of state computation. - - -### ChainExport -ChainExport returns a stream of bytes with CAR dump of chain data. -The exported chain data includes the header chain from the given tipset -back to genesis, the entire genesis state, and the most recent 'nroots' -state trees. -If oldmsgskip is set, messages from before the requested roots are also not included. - - -Perms: read - -Inputs: -```json -[ - 10101, - true, - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: `"Ynl0ZSBhcnJheQ=="` - -### ChainGetBlock -ChainGetBlock returns the block specified by the given CID. - - -Perms: read - -Inputs: -```json -[ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - } -] -``` - -Response: -```json -{ - "Miner": "t01234", - "Ticket": { - "VRFProof": "Ynl0ZSBhcnJheQ==" - }, - "ElectionProof": { - "WinCount": 9, - "VRFProof": "Ynl0ZSBhcnJheQ==" - }, - "BeaconEntries": null, - "WinPoStProof": null, - "Parents": null, - "ParentWeight": "0", - "Height": 10101, - "ParentStateRoot": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "ParentMessageReceipts": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "Messages": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "BLSAggregate": { - "Type": 2, - "Data": "Ynl0ZSBhcnJheQ==" - }, - "Timestamp": 42, - "BlockSig": { - "Type": 2, - "Data": "Ynl0ZSBhcnJheQ==" - }, - "ForkSignaling": 42, - "ParentBaseFee": "0" -} -``` - -### ChainGetBlockMessages -ChainGetBlockMessages returns messages stored in the specified block. - - -Perms: read - -Inputs: -```json -[ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - } -] -``` - -Response: -```json -{ - "BlsMessages": null, - "SecpkMessages": null, - "Cids": null -} -``` - -### ChainGetGenesis -ChainGetGenesis returns the genesis tipset. - - -Perms: read - -Inputs: `null` - -Response: -```json -{ - "Cids": null, - "Blocks": null, - "Height": 0 -} -``` - -### ChainGetMessage -ChainGetMessage reads a message referenced by the specified CID from the -chain blockstore. - - -Perms: read - -Inputs: -```json -[ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - } -] -``` - -Response: -```json -{ - "Version": 42, - "To": "t01234", - "From": "t01234", - "Nonce": 42, - "Value": "0", - "GasLimit": 9, - "GasFeeCap": "0", - "GasPremium": "0", - "Method": 1, - "Params": "Ynl0ZSBhcnJheQ==" -} -``` - -### ChainGetNode -There are not yet any comments for this method. - -Perms: read - -Inputs: -```json -[ - "string value" -] -``` - -Response: -```json -{ - "Cid": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "Obj": {} -} -``` - -### ChainGetParentMessages -ChainGetParentMessages returns messages stored in parent tipset of the -specified block. - - -Perms: read - -Inputs: -```json -[ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - } -] -``` - -Response: `null` - -### ChainGetParentReceipts -ChainGetParentReceipts returns receipts for messages in parent tipset of -the specified block. - - -Perms: read - -Inputs: -```json -[ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - } -] -``` - -Response: `null` - -### ChainGetPath -ChainGetPath returns a set of revert/apply operations needed to get from -one tipset to another, for example: -``` - to - ^ -from tAA - ^ ^ -tBA tAB - ^---*--^ - ^ - tRR -``` -Would return `[revert(tBA), apply(tAB), apply(tAA)]` - - -Perms: read - -Inputs: -```json -[ - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ], - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: `null` - -### ChainGetRandomnessFromBeacon -ChainGetRandomnessFromBeacon is used to sample the beacon for randomness. - - -Perms: read - -Inputs: -```json -[ - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ], - 2, - 10101, - "Ynl0ZSBhcnJheQ==" -] -``` - -Response: `null` - -### ChainGetRandomnessFromTickets -ChainGetRandomnessFromTickets is used to sample the chain for randomness. - - -Perms: read - -Inputs: -```json -[ - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ], - 2, - 10101, - "Ynl0ZSBhcnJheQ==" -] -``` - -Response: `null` - -### ChainGetTipSet -ChainGetTipSet returns the tipset specified by the given TipSetKey. - - -Perms: read - -Inputs: -```json -[ - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: -```json -{ - "Cids": null, - "Blocks": null, - "Height": 0 -} -``` - -### ChainGetTipSetByHeight -ChainGetTipSetByHeight looks back for a tipset at the specified epoch. -If there are no blocks at the specified epoch, a tipset at an earlier epoch -will be returned. - - -Perms: read - -Inputs: -```json -[ - 10101, - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: -```json -{ - "Cids": null, - "Blocks": null, - "Height": 0 -} -``` - -### ChainHasObj -ChainHasObj checks if a given CID exists in the chain blockstore. - - -Perms: read - -Inputs: -```json -[ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - } -] -``` - -Response: `true` - -### ChainHead -ChainHead returns the current head of the chain. - - -Perms: read - -Inputs: `null` - -Response: -```json -{ - "Cids": null, - "Blocks": null, - "Height": 0 -} -``` - -### ChainNotify -ChainNotify returns channel with chain head updates. -First message is guaranteed to be of len == 1, and type == 'current'. - - -Perms: read - -Inputs: `null` - -Response: `null` - -### ChainReadObj -ChainReadObj reads ipld nodes referenced by the specified CID from chain -blockstore and returns raw bytes. - - -Perms: read - -Inputs: -```json -[ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - } -] -``` - -Response: `"Ynl0ZSBhcnJheQ=="` - -### ChainSetHead -ChainSetHead forcefully sets current chain head. Use with caution. - - -Perms: admin - -Inputs: -```json -[ - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: `{}` - -### ChainStatObj -ChainStatObj returns statistics about the graph referenced by 'obj'. -If 'base' is also specified, then the returned stat will be a diff -between the two objects. - - -Perms: read - -Inputs: -```json -[ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - } -] -``` - -Response: -```json -{ - "Size": 42, - "Links": 42 -} -``` - -### ChainTipSetWeight -ChainTipSetWeight computes weight for the specified tipset. - - -Perms: read - -Inputs: -```json -[ - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: `"0"` - -## Client -The Client methods all have to do with interacting with the storage and -retrieval markets as a client - - -### ClientCalcCommP -ClientCalcCommP calculates the CommP for a specified file - - -Perms: read - -Inputs: -```json -[ - "string value" -] -``` - -Response: -```json -{ - "Root": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "Size": 1024 -} -``` - -### ClientDataTransferUpdates -There are not yet any comments for this method. - -Perms: write - -Inputs: `null` - -Response: -```json -{ - "TransferID": 3, - "Status": 1, - "BaseCID": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "IsInitiator": true, - "IsSender": true, - "Voucher": "string value", - "Message": "string value", - "OtherPeer": "12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf", - "Transferred": 42 -} -``` - -### ClientDealSize -ClientDealSize calculates real deal data size - - -Perms: read - -Inputs: -```json -[ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - } -] -``` - -Response: -```json -{ - "PayloadSize": 9, - "PieceSize": 1032 -} -``` - -### ClientFindData -ClientFindData identifies peers that have a certain file, and returns QueryOffers (one per peer). - - -Perms: read - -Inputs: -```json -[ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - null -] -``` - -Response: `null` - -### ClientGenCar -ClientGenCar generates a CAR file for the specified file. - - -Perms: write - -Inputs: -```json -[ - { - "Path": "string value", - "IsCAR": true - }, - "string value" -] -``` - -Response: `{}` - -### ClientGetDealInfo -ClientGetDealInfo returns the latest information about a given deal. - - -Perms: read - -Inputs: -```json -[ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - } -] -``` - -Response: -```json -{ - "ProposalCid": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "State": 42, - "Message": "string value", - "Provider": "t01234", - "DataRef": { - "TransferType": "string value", - "Root": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "PieceCid": null, - "PieceSize": 1024 - }, - "PieceCID": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "Size": 42, - "PricePerEpoch": "0", - "Duration": 42, - "DealID": 5432, - "CreationTime": "0001-01-01T00:00:00Z" -} -``` - -### ClientGetDealUpdates -ClientGetDealUpdates returns the status of updated deals - - -Perms: read - -Inputs: `null` - -Response: -```json -{ - "ProposalCid": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "State": 42, - "Message": "string value", - "Provider": "t01234", - "DataRef": { - "TransferType": "string value", - "Root": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "PieceCid": null, - "PieceSize": 1024 - }, - "PieceCID": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "Size": 42, - "PricePerEpoch": "0", - "Duration": 42, - "DealID": 5432, - "CreationTime": "0001-01-01T00:00:00Z" -} -``` - -### ClientHasLocal -ClientHasLocal indicates whether a certain CID is locally stored. - - -Perms: write - -Inputs: -```json -[ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - } -] -``` - -Response: `true` - -### ClientImport -ClientImport imports file under the specified path into filestore. - - -Perms: admin - -Inputs: -```json -[ - { - "Path": "string value", - "IsCAR": true - } -] -``` - -Response: -```json -{ - "Root": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "ImportID": 50 -} -``` - -### ClientListDataTransfers -ClientListTransfers returns the status of all ongoing transfers of data - - -Perms: write - -Inputs: `null` - -Response: `null` - -### ClientListDeals -ClientListDeals returns information about the deals made by the local client. - - -Perms: write - -Inputs: `null` - -Response: `null` - -### ClientListImports -ClientListImports lists imported files and their root CIDs - - -Perms: write - -Inputs: `null` - -Response: `null` - -### ClientMinerQueryOffer -ClientMinerQueryOffer returns a QueryOffer for the specific miner and file. - - -Perms: read - -Inputs: -```json -[ - "t01234", - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - null -] -``` - -Response: -```json -{ - "Err": "string value", - "Root": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "Piece": null, - "Size": 42, - "MinPrice": "0", - "UnsealPrice": "0", - "PaymentInterval": 42, - "PaymentIntervalIncrease": 42, - "Miner": "t01234", - "MinerPeer": { - "Address": "t01234", - "ID": "12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf", - "PieceCID": null - } -} -``` - -### ClientQueryAsk -ClientQueryAsk returns a signed StorageAsk from the specified miner. - - -Perms: read - -Inputs: -```json -[ - "12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf", - "t01234" -] -``` - -Response: -```json -{ - "Ask": { - "Price": "0", - "VerifiedPrice": "0", - "MinPieceSize": 1032, - "MaxPieceSize": 1032, - "Miner": "t01234", - "Timestamp": 10101, - "Expiry": 10101, - "SeqNo": 42 - }, - "Signature": { - "Type": 2, - "Data": "Ynl0ZSBhcnJheQ==" - } -} -``` - -### ClientRemoveImport -ClientRemoveImport removes file import - - -Perms: admin - -Inputs: -```json -[ - 50 -] -``` - -Response: `{}` - -### ClientRetrieve -ClientRetrieve initiates the retrieval of a file, as specified in the order. - - -Perms: admin - -Inputs: -```json -[ - { - "Root": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "Piece": null, - "Size": 42, - "Total": "0", - "UnsealPrice": "0", - "PaymentInterval": 42, - "PaymentIntervalIncrease": 42, - "Client": "t01234", - "Miner": "t01234", - "MinerPeer": { - "Address": "t01234", - "ID": "12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf", - "PieceCID": null - } - }, - { - "Path": "string value", - "IsCAR": true - } -] -``` - -Response: `{}` - -### ClientRetrieveTryRestartInsufficientFunds -ClientRetrieveTryRestartInsufficientFunds attempts to restart stalled retrievals on a given payment channel -which are stuck due to insufficient funds - - -Perms: write - -Inputs: -```json -[ - "t01234" -] -``` - -Response: `{}` - -### ClientRetrieveWithEvents -ClientRetrieveWithEvents initiates the retrieval of a file, as specified in the order, and provides a channel -of status updates. - - -Perms: admin - -Inputs: -```json -[ - { - "Root": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "Piece": null, - "Size": 42, - "Total": "0", - "UnsealPrice": "0", - "PaymentInterval": 42, - "PaymentIntervalIncrease": 42, - "Client": "t01234", - "Miner": "t01234", - "MinerPeer": { - "Address": "t01234", - "ID": "12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf", - "PieceCID": null - } - }, - { - "Path": "string value", - "IsCAR": true - } -] -``` - -Response: -```json -{ - "Event": 5, - "Status": 0, - "BytesReceived": 42, - "FundsSpent": "0", - "Err": "string value" -} -``` - -### ClientStartDeal -ClientStartDeal proposes a deal with a miner. - - -Perms: admin - -Inputs: -```json -[ - { - "Data": { - "TransferType": "string value", - "Root": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "PieceCid": null, - "PieceSize": 1024 - }, - "Wallet": "t01234", - "Miner": "t01234", - "EpochPrice": "0", - "MinBlocksDuration": 42, - "ProviderCollateral": "0", - "DealStartEpoch": 10101, - "FastRetrieval": true, - "VerifiedDeal": true - } -] -``` - -Response: `null` - -## Gas - - -### GasEstimateFeeCap -GasEstimateFeeCap estimates gas fee cap - - -Perms: read - -Inputs: -```json -[ - { - "Version": 42, - "To": "t01234", - "From": "t01234", - "Nonce": 42, - "Value": "0", - "GasLimit": 9, - "GasFeeCap": "0", - "GasPremium": "0", - "Method": 1, - "Params": "Ynl0ZSBhcnJheQ==" - }, - 9, - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: `"0"` - -### GasEstimateGasLimit -GasEstimateGasLimit estimates gas used by the message and returns it. -It fails if message fails to execute. - - -Perms: read - -Inputs: -```json -[ - { - "Version": 42, - "To": "t01234", - "From": "t01234", - "Nonce": 42, - "Value": "0", - "GasLimit": 9, - "GasFeeCap": "0", - "GasPremium": "0", - "Method": 1, - "Params": "Ynl0ZSBhcnJheQ==" - }, - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: `9` - -### GasEstimateGasPremium -GasEstimateGasPremium estimates what gas price should be used for a -message to have high likelihood of inclusion in `nblocksincl` epochs. - - -Perms: read - -Inputs: -```json -[ - 42, - "t01234", - 9, - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: `"0"` - -### GasEstimateMessageGas -GasEstimateMessageGas estimates gas values for unset message gas fields - - -Perms: read - -Inputs: -```json -[ - { - "Version": 42, - "To": "t01234", - "From": "t01234", - "Nonce": 42, - "Value": "0", - "GasLimit": 9, - "GasFeeCap": "0", - "GasPremium": "0", - "Method": 1, - "Params": "Ynl0ZSBhcnJheQ==" - }, - { - "MaxFee": "0" - }, - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: -```json -{ - "Version": 42, - "To": "t01234", - "From": "t01234", - "Nonce": 42, - "Value": "0", - "GasLimit": 9, - "GasFeeCap": "0", - "GasPremium": "0", - "Method": 1, - "Params": "Ynl0ZSBhcnJheQ==" -} -``` - -## I - - -### ID - - -Perms: read - -Inputs: `null` - -Response: `"12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf"` - -## Log - - -### LogList - - -Perms: write - -Inputs: `null` - -Response: `null` - -### LogSetLevel - - -Perms: write - -Inputs: -```json -[ - "string value", - "string value" -] -``` - -Response: `{}` - -## Market - - -### MarketEnsureAvailable -MarketFreeBalance - - -Perms: sign - -Inputs: -```json -[ - "t01234", - "t01234", - "0" -] -``` - -Response: -```json -{ - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" -} -``` - -## Miner - - -### MinerCreateBlock -There are not yet any comments for this method. - -Perms: write - -Inputs: -```json -[ - { - "Miner": "t01234", - "Parents": [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ], - "Ticket": { - "VRFProof": "Ynl0ZSBhcnJheQ==" - }, - "Eproof": { - "WinCount": 9, - "VRFProof": "Ynl0ZSBhcnJheQ==" - }, - "BeaconValues": null, - "Messages": null, - "Epoch": 10101, - "Timestamp": 42, - "WinningPoStProof": null - } -] -``` - -Response: -```json -{ - "Header": { - "Miner": "t01234", - "Ticket": { - "VRFProof": "Ynl0ZSBhcnJheQ==" - }, - "ElectionProof": { - "WinCount": 9, - "VRFProof": "Ynl0ZSBhcnJheQ==" - }, - "BeaconEntries": null, - "WinPoStProof": null, - "Parents": null, - "ParentWeight": "0", - "Height": 10101, - "ParentStateRoot": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "ParentMessageReceipts": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "Messages": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "BLSAggregate": { - "Type": 2, - "Data": "Ynl0ZSBhcnJheQ==" - }, - "Timestamp": 42, - "BlockSig": { - "Type": 2, - "Data": "Ynl0ZSBhcnJheQ==" - }, - "ForkSignaling": 42, - "ParentBaseFee": "0" - }, - "BlsMessages": null, - "SecpkMessages": null -} -``` - -### MinerGetBaseInfo -There are not yet any comments for this method. - -Perms: read - -Inputs: -```json -[ - "t01234", - 10101, - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: -```json -{ - "MinerPower": "0", - "NetworkPower": "0", - "Sectors": null, - "WorkerKey": "t01234", - "SectorSize": 34359738368, - "PrevBeaconEntry": { - "Round": 42, - "Data": "Ynl0ZSBhcnJheQ==" - }, - "BeaconEntries": null, - "HasMinPower": true -} -``` - -## Mpool -The Mpool methods are for interacting with the message pool. The message pool -manages all incoming and outgoing 'messages' going over the network. - - -### MpoolClear -MpoolClear clears pending messages from the mpool - - -Perms: write - -Inputs: -```json -[ - true -] -``` - -Response: `{}` - -### MpoolGetConfig -MpoolGetConfig returns (a copy of) the current mpool config - - -Perms: read - -Inputs: `null` - -Response: -```json -{ - "PriorityAddrs": null, - "SizeLimitHigh": 123, - "SizeLimitLow": 123, - "ReplaceByFeeRatio": 12.3, - "PruneCooldown": 60000000000, - "GasLimitOverestimation": 12.3 -} -``` - -### MpoolGetNonce -MpoolGetNonce gets next nonce for the specified sender. -Note that this method may not be atomic. Use MpoolPushMessage instead. - - -Perms: read - -Inputs: -```json -[ - "t01234" -] -``` - -Response: `42` - -### MpoolPending -MpoolPending returns pending mempool messages. - - -Perms: read - -Inputs: -```json -[ - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: `null` - -### MpoolPush -MpoolPush pushes a signed message to mempool. - - -Perms: write - -Inputs: -```json -[ - { - "Message": { - "Version": 42, - "To": "t01234", - "From": "t01234", - "Nonce": 42, - "Value": "0", - "GasLimit": 9, - "GasFeeCap": "0", - "GasPremium": "0", - "Method": 1, - "Params": "Ynl0ZSBhcnJheQ==" - }, - "Signature": { - "Type": 2, - "Data": "Ynl0ZSBhcnJheQ==" - } - } -] -``` - -Response: -```json -{ - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" -} -``` - -### MpoolPushMessage -MpoolPushMessage atomically assigns a nonce, signs, and pushes a message -to mempool. -maxFee is only used when GasFeeCap/GasPremium fields aren't specified - -When maxFee is set to 0, MpoolPushMessage will guess appropriate fee -based on current chain conditions - - -Perms: sign - -Inputs: -```json -[ - { - "Version": 42, - "To": "t01234", - "From": "t01234", - "Nonce": 42, - "Value": "0", - "GasLimit": 9, - "GasFeeCap": "0", - "GasPremium": "0", - "Method": 1, - "Params": "Ynl0ZSBhcnJheQ==" - }, - { - "MaxFee": "0" - } -] -``` - -Response: -```json -{ - "Message": { - "Version": 42, - "To": "t01234", - "From": "t01234", - "Nonce": 42, - "Value": "0", - "GasLimit": 9, - "GasFeeCap": "0", - "GasPremium": "0", - "Method": 1, - "Params": "Ynl0ZSBhcnJheQ==" - }, - "Signature": { - "Type": 2, - "Data": "Ynl0ZSBhcnJheQ==" - } -} -``` - -### MpoolSelect -MpoolSelect returns a list of pending messages for inclusion in the next block - - -Perms: read - -Inputs: -```json -[ - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ], - 12.3 -] -``` - -Response: `null` - -### MpoolSetConfig -MpoolSetConfig sets the mpool config to (a copy of) the supplied config - - -Perms: write - -Inputs: -```json -[ - { - "PriorityAddrs": null, - "SizeLimitHigh": 123, - "SizeLimitLow": 123, - "ReplaceByFeeRatio": 12.3, - "PruneCooldown": 60000000000, - "GasLimitOverestimation": 12.3 - } -] -``` - -Response: `{}` - -### MpoolSub -There are not yet any comments for this method. - -Perms: read - -Inputs: `null` - -Response: -```json -{ - "Type": 0, - "Message": { - "Message": { - "Version": 42, - "To": "t01234", - "From": "t01234", - "Nonce": 42, - "Value": "0", - "GasLimit": 9, - "GasFeeCap": "0", - "GasPremium": "0", - "Method": 1, - "Params": "Ynl0ZSBhcnJheQ==" - }, - "Signature": { - "Type": 2, - "Data": "Ynl0ZSBhcnJheQ==" - } - } -} -``` - -## Msig -The Msig methods are used to interact with multisig wallets on the -filecoin network - - -### MsigAddApprove -MsigAddApprove approves a previously proposed AddSigner message -It takes the following params: , , , -, , - - -Perms: sign - -Inputs: -```json -[ - "t01234", - "t01234", - 42, - "t01234", - "t01234", - true -] -``` - -Response: -```json -{ - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" -} -``` - -### MsigAddCancel -MsigAddCancel cancels a previously proposed AddSigner message -It takes the following params: , , , -, - - -Perms: sign - -Inputs: -```json -[ - "t01234", - "t01234", - 42, - "t01234", - true -] -``` - -Response: -```json -{ - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" -} -``` - -### MsigAddPropose -MsigAddPropose proposes adding a signer in the multisig -It takes the following params: , , -, - - -Perms: sign - -Inputs: -```json -[ - "t01234", - "t01234", - "t01234", - true -] -``` - -Response: -```json -{ - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" -} -``` - -### MsigApprove -MsigApprove approves a previously-proposed multisig message -It takes the following params: , , , , , -, , - - -Perms: sign - -Inputs: -```json -[ - "t01234", - 42, - "t01234", - "t01234", - "0", - "t01234", - 42, - "Ynl0ZSBhcnJheQ==" -] -``` - -Response: -```json -{ - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" -} -``` - -### MsigCancel -MsigCancel cancels a previously-proposed multisig message -It takes the following params: , , , , -, , - - -Perms: sign - -Inputs: -```json -[ - "t01234", - 42, - "t01234", - "0", - "t01234", - 42, - "Ynl0ZSBhcnJheQ==" -] -``` - -Response: -```json -{ - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" -} -``` - -### MsigCreate -MsigCreate creates a multisig wallet -It takes the following params: , , -, , - - -Perms: sign - -Inputs: -```json -[ - 42, - null, - 10101, - "0", - "t01234", - "0" -] -``` - -Response: -```json -{ - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" -} -``` - -### MsigGetAvailableBalance -MsigGetAvailableBalance returns the portion of a multisig's balance that can be withdrawn or spent - - -Perms: read - -Inputs: -```json -[ - "t01234", - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: `"0"` - -### MsigGetVested -MsigGetVested returns the amount of FIL that vested in a multisig in a certain period. -It takes the following params: , , - - -Perms: read - -Inputs: -```json -[ - "t01234", - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ], - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: `"0"` - -### MsigPropose -MsigPropose proposes a multisig message -It takes the following params: , , , -, , - - -Perms: sign - -Inputs: -```json -[ - "t01234", - "t01234", - "0", - "t01234", - 42, - "Ynl0ZSBhcnJheQ==" -] -``` - -Response: -```json -{ - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" -} -``` - -### MsigSwapApprove -MsigSwapApprove approves a previously proposed SwapSigner -It takes the following params: , , , -, , - - -Perms: sign - -Inputs: -```json -[ - "t01234", - "t01234", - 42, - "t01234", - "t01234", - "t01234" -] -``` - -Response: -```json -{ - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" -} -``` - -### MsigSwapCancel -MsigSwapCancel cancels a previously proposed SwapSigner message -It takes the following params: , , , -, - - -Perms: sign - -Inputs: -```json -[ - "t01234", - "t01234", - 42, - "t01234", - "t01234" -] -``` - -Response: -```json -{ - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" -} -``` - -### MsigSwapPropose -MsigSwapPropose proposes swapping 2 signers in the multisig -It takes the following params: , , -, - - -Perms: sign - -Inputs: -```json -[ - "t01234", - "t01234", - "t01234", - "t01234" -] -``` - -Response: -```json -{ - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" -} -``` - -## Net - - -### NetAddrsListen - - -Perms: read - -Inputs: `null` - -Response: -```json -{ - "Addrs": null, - "ID": "12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf" -} -``` - -### NetAgentVersion - - -Perms: read - -Inputs: -```json -[ - "12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf" -] -``` - -Response: `"string value"` - -### NetAutoNatStatus - - -Perms: read - -Inputs: `null` - -Response: -```json -{ - "Reachability": 1, - "PublicAddr": "string value" -} -``` - -### NetBandwidthStats - - -Perms: read - -Inputs: `null` - -Response: -```json -{ - "TotalIn": 9, - "TotalOut": 9, - "RateIn": 12.3, - "RateOut": 12.3 -} -``` - -### NetBandwidthStatsByPeer - - -Perms: read - -Inputs: `null` - -Response: -```json -{ - "12D3KooWSXmXLJmBR1M7i9RW9GQPNUhZSzXKzxDHWtAgNuJAbyEJ": { - "TotalIn": 174000, - "TotalOut": 12500, - "RateIn": 100, - "RateOut": 50 - } -} -``` - -### NetBandwidthStatsByProtocol - - -Perms: read - -Inputs: `null` - -Response: -```json -{ - "/fil/hello/1.0.0": { - "TotalIn": 174000, - "TotalOut": 12500, - "RateIn": 100, - "RateOut": 50 - } -} -``` - -### NetConnect - - -Perms: write - -Inputs: -```json -[ - { - "Addrs": null, - "ID": "12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf" - } -] -``` - -Response: `{}` - -### NetConnectedness - - -Perms: read - -Inputs: -```json -[ - "12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf" -] -``` - -Response: `1` - -### NetDisconnect - - -Perms: write - -Inputs: -```json -[ - "12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf" -] -``` - -Response: `{}` - -### NetFindPeer - - -Perms: read - -Inputs: -```json -[ - "12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf" -] -``` - -Response: -```json -{ - "Addrs": null, - "ID": "12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf" -} -``` - -### NetPeers - - -Perms: read - -Inputs: `null` - -Response: `null` - -### NetPubsubScores - - -Perms: read - -Inputs: `null` - -Response: `null` - -## Paych -The Paych methods are for interacting with and managing payment channels - - -### PaychAllocateLane -There are not yet any comments for this method. - -Perms: sign - -Inputs: -```json -[ - "t01234" -] -``` - -Response: `42` - -### PaychAvailableFunds -There are not yet any comments for this method. - -Perms: sign - -Inputs: -```json -[ - "t01234" -] -``` - -Response: -```json -{ - "Channel": "\u003cempty\u003e", - "From": "t01234", - "To": "t01234", - "ConfirmedAmt": "0", - "PendingAmt": "0", - "PendingWaitSentinel": null, - "QueuedAmt": "0", - "VoucherReedeemedAmt": "0" -} -``` - -### PaychAvailableFundsByFromTo -There are not yet any comments for this method. - -Perms: sign - -Inputs: -```json -[ - "t01234", - "t01234" -] -``` - -Response: -```json -{ - "Channel": "\u003cempty\u003e", - "From": "t01234", - "To": "t01234", - "ConfirmedAmt": "0", - "PendingAmt": "0", - "PendingWaitSentinel": null, - "QueuedAmt": "0", - "VoucherReedeemedAmt": "0" -} -``` - -### PaychCollect -There are not yet any comments for this method. - -Perms: sign - -Inputs: -```json -[ - "t01234" -] -``` - -Response: -```json -{ - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" -} -``` - -### PaychGet -There are not yet any comments for this method. - -Perms: sign - -Inputs: -```json -[ - "t01234", - "t01234", - "0" -] -``` - -Response: -```json -{ - "Channel": "t01234", - "WaitSentinel": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - } -} -``` - -### PaychGetWaitReady -There are not yet any comments for this method. - -Perms: sign - -Inputs: -```json -[ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - } -] -``` - -Response: `"t01234"` - -### PaychList -There are not yet any comments for this method. - -Perms: read - -Inputs: `null` - -Response: `null` - -### PaychNewPayment -There are not yet any comments for this method. - -Perms: sign - -Inputs: -```json -[ - "t01234", - "t01234", - null -] -``` - -Response: -```json -{ - "Channel": "t01234", - "WaitSentinel": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "Vouchers": null -} -``` - -### PaychSettle -There are not yet any comments for this method. - -Perms: sign - -Inputs: -```json -[ - "t01234" -] -``` - -Response: -```json -{ - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" -} -``` - -### PaychStatus -There are not yet any comments for this method. - -Perms: read - -Inputs: -```json -[ - "t01234" -] -``` - -Response: -```json -{ - "ControlAddr": "t01234", - "Direction": 1 -} -``` - -### PaychVoucherAdd -There are not yet any comments for this method. - -Perms: write - -Inputs: -```json -[ - "t01234", - { - "ChannelAddr": "t01234", - "TimeLockMin": 10101, - "TimeLockMax": 10101, - "SecretPreimage": "Ynl0ZSBhcnJheQ==", - "Extra": { - "Actor": "t01234", - "Method": 1, - "Data": "Ynl0ZSBhcnJheQ==" - }, - "Lane": 42, - "Nonce": 42, - "Amount": "0", - "MinSettleHeight": 10101, - "Merges": null, - "Signature": { - "Type": 2, - "Data": "Ynl0ZSBhcnJheQ==" - } - }, - "Ynl0ZSBhcnJheQ==", - "0" -] -``` - -Response: `"0"` - -### PaychVoucherCheckSpendable -There are not yet any comments for this method. - -Perms: read - -Inputs: -```json -[ - "t01234", - { - "ChannelAddr": "t01234", - "TimeLockMin": 10101, - "TimeLockMax": 10101, - "SecretPreimage": "Ynl0ZSBhcnJheQ==", - "Extra": { - "Actor": "t01234", - "Method": 1, - "Data": "Ynl0ZSBhcnJheQ==" - }, - "Lane": 42, - "Nonce": 42, - "Amount": "0", - "MinSettleHeight": 10101, - "Merges": null, - "Signature": { - "Type": 2, - "Data": "Ynl0ZSBhcnJheQ==" - } - }, - "Ynl0ZSBhcnJheQ==", - "Ynl0ZSBhcnJheQ==" -] -``` - -Response: `true` - -### PaychVoucherCheckValid -There are not yet any comments for this method. - -Perms: read - -Inputs: -```json -[ - "t01234", - { - "ChannelAddr": "t01234", - "TimeLockMin": 10101, - "TimeLockMax": 10101, - "SecretPreimage": "Ynl0ZSBhcnJheQ==", - "Extra": { - "Actor": "t01234", - "Method": 1, - "Data": "Ynl0ZSBhcnJheQ==" - }, - "Lane": 42, - "Nonce": 42, - "Amount": "0", - "MinSettleHeight": 10101, - "Merges": null, - "Signature": { - "Type": 2, - "Data": "Ynl0ZSBhcnJheQ==" - } - } -] -``` - -Response: `{}` - -### PaychVoucherCreate -There are not yet any comments for this method. - -Perms: sign - -Inputs: -```json -[ - "t01234", - "0", - 42 -] -``` - -Response: -```json -{ - "Voucher": { - "ChannelAddr": "t01234", - "TimeLockMin": 10101, - "TimeLockMax": 10101, - "SecretPreimage": "Ynl0ZSBhcnJheQ==", - "Extra": { - "Actor": "t01234", - "Method": 1, - "Data": "Ynl0ZSBhcnJheQ==" - }, - "Lane": 42, - "Nonce": 42, - "Amount": "0", - "MinSettleHeight": 10101, - "Merges": null, - "Signature": { - "Type": 2, - "Data": "Ynl0ZSBhcnJheQ==" - } - }, - "Shortfall": "0" -} -``` - -### PaychVoucherList -There are not yet any comments for this method. - -Perms: write - -Inputs: -```json -[ - "t01234" -] -``` - -Response: `null` - -### PaychVoucherSubmit -There are not yet any comments for this method. - -Perms: sign - -Inputs: -```json -[ - "t01234", - { - "ChannelAddr": "t01234", - "TimeLockMin": 10101, - "TimeLockMax": 10101, - "SecretPreimage": "Ynl0ZSBhcnJheQ==", - "Extra": { - "Actor": "t01234", - "Method": 1, - "Data": "Ynl0ZSBhcnJheQ==" - }, - "Lane": 42, - "Nonce": 42, - "Amount": "0", - "MinSettleHeight": 10101, - "Merges": null, - "Signature": { - "Type": 2, - "Data": "Ynl0ZSBhcnJheQ==" - } - }, - "Ynl0ZSBhcnJheQ==", - "Ynl0ZSBhcnJheQ==" -] -``` - -Response: -```json -{ - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" -} -``` - -## State -The State methods are used to query, inspect, and interact with chain state. -All methods take a TipSetKey as a parameter. The state looked up is the state at that tipset. -A nil TipSetKey can be provided as a param, this will cause the heaviest tipset in the chain to be used. - - -### StateAccountKey -StateAccountKey returns the public key address of the given ID address - - -Perms: read - -Inputs: -```json -[ - "t01234", - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: `"t01234"` - -### StateAllMinerFaults -StateAllMinerFaults returns all non-expired Faults that occur within lookback epochs of the given tipset - - -Perms: read - -Inputs: -```json -[ - 10101, - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: `null` - -### StateCall -StateCall runs the given message and returns its result without any persisted changes. - - -Perms: read - -Inputs: -```json -[ - { - "Version": 42, - "To": "t01234", - "From": "t01234", - "Nonce": 42, - "Value": "0", - "GasLimit": 9, - "GasFeeCap": "0", - "GasPremium": "0", - "Method": 1, - "Params": "Ynl0ZSBhcnJheQ==" - }, - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: -```json -{ - "Msg": { - "Version": 42, - "To": "t01234", - "From": "t01234", - "Nonce": 42, - "Value": "0", - "GasLimit": 9, - "GasFeeCap": "0", - "GasPremium": "0", - "Method": 1, - "Params": "Ynl0ZSBhcnJheQ==" - }, - "MsgRct": { - "ExitCode": 0, - "Return": "Ynl0ZSBhcnJheQ==", - "GasUsed": 9 - }, - "ExecutionTrace": { - "Msg": { - "Version": 42, - "To": "t01234", - "From": "t01234", - "Nonce": 42, - "Value": "0", - "GasLimit": 9, - "GasFeeCap": "0", - "GasPremium": "0", - "Method": 1, - "Params": "Ynl0ZSBhcnJheQ==" - }, - "MsgRct": { - "ExitCode": 0, - "Return": "Ynl0ZSBhcnJheQ==", - "GasUsed": 9 - }, - "Error": "string value", - "Duration": 60000000000, - "GasCharges": null, - "Subcalls": null - }, - "Error": "string value", - "Duration": 60000000000 -} -``` - -### StateChangedActors -StateChangedActors returns all the actors whose states change between the two given state CIDs -TODO: Should this take tipset keys instead? - - -Perms: read - -Inputs: -```json -[ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - } -] -``` - -Response: -```json -{ - "t01236": { - "Code": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "Head": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "Nonce": 42, - "Balance": "0" - } -} -``` - -### StateCirculatingSupply -StateCirculatingSupply returns the circulating supply of Filecoin at the given tipset - - -Perms: read - -Inputs: -```json -[ - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: -```json -{ - "FilVested": "0", - "FilMined": "0", - "FilBurnt": "0", - "FilLocked": "0", - "FilCirculating": "0" -} -``` - -### StateCompute -StateCompute is a flexible command that applies the given messages on the given tipset. -The messages are run as though the VM were at the provided height. - - -Perms: read - -Inputs: -```json -[ - 10101, - null, - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: -```json -{ - "Root": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "Trace": null -} -``` - -### StateDealProviderCollateralBounds -StateDealProviderCollateralBounds returns the min and max collateral a storage provider -can issue. It takes the deal size and verified status as parameters. - - -Perms: read - -Inputs: -```json -[ - 1032, - true, - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: -```json -{ - "Min": "0", - "Max": "0" -} -``` - -### StateGetActor -StateGetActor returns the indicated actor's nonce and balance. - - -Perms: read - -Inputs: -```json -[ - "t01234", - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: -```json -{ - "Code": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "Head": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "Nonce": 42, - "Balance": "0" -} -``` - -### StateGetReceipt -StateGetReceipt returns the message receipt for the given message - - -Perms: read - -Inputs: -```json -[ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: -```json -{ - "ExitCode": 0, - "Return": "Ynl0ZSBhcnJheQ==", - "GasUsed": 9 -} -``` - -### StateListActors -StateListActors returns the addresses of every actor in the state - - -Perms: read - -Inputs: -```json -[ - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: `null` - -### StateListMessages -StateListMessages looks back and returns all messages with a matching to or from address, stopping at the given height. - - -Perms: read - -Inputs: -```json -[ - { - "Version": 42, - "To": "t01234", - "From": "t01234", - "Nonce": 42, - "Value": "0", - "GasLimit": 9, - "GasFeeCap": "0", - "GasPremium": "0", - "Method": 1, - "Params": "Ynl0ZSBhcnJheQ==" - }, - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ], - 10101 -] -``` - -Response: `null` - -### StateListMiners -StateListMiners returns the addresses of every miner that has claimed power in the Power Actor - - -Perms: read - -Inputs: -```json -[ - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: `null` - -### StateLookupID -StateLookupID retrieves the ID address of the given address - - -Perms: read - -Inputs: -```json -[ - "t01234", - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: `"t01234"` - -### StateMarketBalance -StateMarketBalance looks up the Escrow and Locked balances of the given address in the Storage Market - - -Perms: read - -Inputs: -```json -[ - "t01234", - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: -```json -{ - "Escrow": "0", - "Locked": "0" -} -``` - -### StateMarketDeals -StateMarketDeals returns information about every deal in the Storage Market - - -Perms: read - -Inputs: -```json -[ - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: -```json -{ - "t026363": { - "Proposal": { - "PieceCID": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "PieceSize": 1032, - "VerifiedDeal": true, - "Client": "t01234", - "Provider": "t01234", - "Label": "string value", - "StartEpoch": 10101, - "EndEpoch": 10101, - "StoragePricePerEpoch": "0", - "ProviderCollateral": "0", - "ClientCollateral": "0" - }, - "State": { - "SectorStartEpoch": 10101, - "LastUpdatedEpoch": 10101, - "SlashEpoch": 10101 - } - } -} -``` - -### StateMarketParticipants -StateMarketParticipants returns the Escrow and Locked balances of every participant in the Storage Market - - -Perms: read - -Inputs: -```json -[ - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: -```json -{ - "t026363": { - "Escrow": "0", - "Locked": "0" - } -} -``` - -### StateMarketStorageDeal -StateMarketStorageDeal returns information about the indicated deal - - -Perms: read - -Inputs: -```json -[ - 5432, - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: -```json -{ - "Proposal": { - "PieceCID": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "PieceSize": 1032, - "VerifiedDeal": true, - "Client": "t01234", - "Provider": "t01234", - "Label": "string value", - "StartEpoch": 10101, - "EndEpoch": 10101, - "StoragePricePerEpoch": "0", - "ProviderCollateral": "0", - "ClientCollateral": "0" - }, - "State": { - "SectorStartEpoch": 10101, - "LastUpdatedEpoch": 10101, - "SlashEpoch": 10101 - } -} -``` - -### StateMinerActiveSectors -StateMinerActiveSectors returns info about sectors that a given miner is actively proving. - - -Perms: read - -Inputs: -```json -[ - "t01234", - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: `null` - -### StateMinerAvailableBalance -StateMinerAvailableBalance returns the portion of a miner's balance that can be withdrawn or spent - - -Perms: read - -Inputs: -```json -[ - "t01234", - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: `"0"` - -### StateMinerDeadlines -StateMinerDeadlines returns all the proving deadlines for the given miner - - -Perms: read - -Inputs: -```json -[ - "t01234", - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: `null` - -### StateMinerFaults -StateMinerFaults returns a bitfield indicating the faulty sectors of the given miner - - -Perms: read - -Inputs: -```json -[ - "t01234", - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: -```json -[ - 5, - 1 -] -``` - -### StateMinerInfo -StateMinerInfo returns info about the indicated miner - - -Perms: read - -Inputs: -```json -[ - "t01234", - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: -```json -{ - "Owner": "t01234", - "Worker": "t01234", - "NewWorker": "t01234", - "ControlAddresses": null, - "WorkerChangeEpoch": 10101, - "PeerId": "12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf", - "Multiaddrs": null, - "SealProofType": 3, - "SectorSize": 34359738368, - "WindowPoStPartitionSectors": 42 -} -``` - -### StateMinerInitialPledgeCollateral -StateMinerInitialPledgeCollateral returns the initial pledge collateral for the specified miner's sector - - -Perms: read - -Inputs: -```json -[ - "t01234", - { - "SealProof": 3, - "SectorNumber": 9, - "SealedCID": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "SealRandEpoch": 10101, - "DealIDs": null, - "Expiration": 10101, - "ReplaceCapacity": true, - "ReplaceSectorDeadline": 42, - "ReplaceSectorPartition": 42, - "ReplaceSectorNumber": 9 - }, - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: `"0"` - -### StateMinerPartitions -StateMinerPartitions loads miner partitions for the specified miner/deadline - - -Perms: read - -Inputs: -```json -[ - "t01234", - 42, - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: `null` - -### StateMinerPower -StateMinerPower returns the power of the indicated miner - - -Perms: read - -Inputs: -```json -[ - "t01234", - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: -```json -{ - "MinerPower": { - "RawBytePower": "0", - "QualityAdjPower": "0" - }, - "TotalPower": { - "RawBytePower": "0", - "QualityAdjPower": "0" - } -} -``` - -### StateMinerPreCommitDepositForPower -StateMinerInitialPledgeCollateral returns the precommit deposit for the specified miner's sector - - -Perms: read - -Inputs: -```json -[ - "t01234", - { - "SealProof": 3, - "SectorNumber": 9, - "SealedCID": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "SealRandEpoch": 10101, - "DealIDs": null, - "Expiration": 10101, - "ReplaceCapacity": true, - "ReplaceSectorDeadline": 42, - "ReplaceSectorPartition": 42, - "ReplaceSectorNumber": 9 - }, - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: `"0"` - -### StateMinerProvingDeadline -StateMinerProvingDeadline calculates the deadline at some epoch for a proving period -and returns the deadline-related calculations. - - -Perms: read - -Inputs: -```json -[ - "t01234", - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: -```json -{ - "CurrentEpoch": 10101, - "PeriodStart": 10101, - "Index": 42, - "Open": 10101, - "Close": 10101, - "Challenge": 10101, - "FaultCutoff": 10101, - "WPoStPeriodDeadlines": 42, - "WPoStProvingPeriod": 10101, - "WPoStChallengeWindow": 10101, - "WPoStChallengeLookback": 10101, - "FaultDeclarationCutoff": 10101 -} -``` - -### StateMinerRecoveries -StateMinerRecoveries returns a bitfield indicating the recovering sectors of the given miner - - -Perms: read - -Inputs: -```json -[ - "t01234", - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: -```json -[ - 5, - 1 -] -``` - -### StateMinerSectorCount -StateMinerSectorCount returns the number of sectors in a miner's sector set and proving set - - -Perms: read - -Inputs: -```json -[ - "t01234", - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: -```json -{ - "Sectors": 42, - "Active": 42 -} -``` - -### StateMinerSectors -StateMinerSectors returns info about the given miner's sectors. If the filter bitfield is nil, all sectors are included. -If the filterOut boolean is set to true, any sectors in the filter are excluded. -If false, only those sectors in the filter are included. - - -Perms: read - -Inputs: -```json -[ - "t01234", - [ - 0 - ], - true, - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: `null` - -### StateMsgGasCost -StateMsgGasCost searches for a message in the chain, and returns details of the messages gas costs, including the penalty and miner tip - - -Perms: read - -Inputs: -```json -[ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: -```json -{ - "Message": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "GasUsed": "0", - "BaseFeeBurn": "0", - "OverEstimationBurn": "0", - "MinerPenalty": "0", - "MinerTip": "0", - "Refund": "0", - "TotalCost": "0" -} -``` - -### StateNetworkName -StateNetworkName returns the name of the network the node is synced to - - -Perms: read - -Inputs: `null` - -Response: `"lotus"` - -### StateReadState -StateReadState returns the indicated actor's state. - - -Perms: read - -Inputs: -```json -[ - "t01234", - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: -```json -{ - "Balance": "0", - "State": {} -} -``` - -### StateReplay -StateReplay returns the result of executing the indicated message, assuming it was executed in the indicated tipset. - - -Perms: read - -Inputs: -```json -[ - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ], - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - } -] -``` - -Response: -```json -{ - "Msg": { - "Version": 42, - "To": "t01234", - "From": "t01234", - "Nonce": 42, - "Value": "0", - "GasLimit": 9, - "GasFeeCap": "0", - "GasPremium": "0", - "Method": 1, - "Params": "Ynl0ZSBhcnJheQ==" - }, - "MsgRct": { - "ExitCode": 0, - "Return": "Ynl0ZSBhcnJheQ==", - "GasUsed": 9 - }, - "ExecutionTrace": { - "Msg": { - "Version": 42, - "To": "t01234", - "From": "t01234", - "Nonce": 42, - "Value": "0", - "GasLimit": 9, - "GasFeeCap": "0", - "GasPremium": "0", - "Method": 1, - "Params": "Ynl0ZSBhcnJheQ==" - }, - "MsgRct": { - "ExitCode": 0, - "Return": "Ynl0ZSBhcnJheQ==", - "GasUsed": 9 - }, - "Error": "string value", - "Duration": 60000000000, - "GasCharges": null, - "Subcalls": null - }, - "Error": "string value", - "Duration": 60000000000 -} -``` - -### StateSearchMsg -StateSearchMsg searches for a message in the chain, and returns its receipt and the tipset where it was executed - - -Perms: read - -Inputs: -```json -[ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - } -] -``` - -Response: -```json -{ - "Message": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "Receipt": { - "ExitCode": 0, - "Return": "Ynl0ZSBhcnJheQ==", - "GasUsed": 9 - }, - "ReturnDec": {}, - "TipSet": [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ], - "Height": 10101 -} -``` - -### StateSectorExpiration -StateSectorExpiration returns epoch at which given sector will expire - - -Perms: read - -Inputs: -```json -[ - "t01234", - 9, - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: -```json -{ - "OnTime": 10101, - "Early": 10101 -} -``` - -### StateSectorGetInfo -StateSectorGetInfo returns the on-chain info for the specified miner's sector. Returns null in case the sector info isn't found -NOTE: returned info.Expiration may not be accurate in some cases, use StateSectorExpiration to get accurate -expiration epoch - - -Perms: read - -Inputs: -```json -[ - "t01234", - 9, - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: -```json -{ - "SectorNumber": 9, - "SealProof": 3, - "SealedCID": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "DealIDs": null, - "Activation": 10101, - "Expiration": 10101, - "DealWeight": "0", - "VerifiedDealWeight": "0", - "InitialPledge": "0", - "ExpectedDayReward": "0", - "ExpectedStoragePledge": "0" -} -``` - -### StateSectorPartition -StateSectorPartition finds deadline/partition with the specified sector - - -Perms: read - -Inputs: -```json -[ - "t01234", - 9, - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: -```json -{ - "Deadline": 42, - "Partition": 42 -} -``` - -### StateSectorPreCommitInfo -StateSectorPreCommitInfo returns the PreCommit info for the specified miner's sector - - -Perms: read - -Inputs: -```json -[ - "t01234", - 9, - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: -```json -{ - "Info": { - "SealProof": 3, - "SectorNumber": 9, - "SealedCID": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "SealRandEpoch": 10101, - "DealIDs": null, - "Expiration": 10101, - "ReplaceCapacity": true, - "ReplaceSectorDeadline": 42, - "ReplaceSectorPartition": 42, - "ReplaceSectorNumber": 9 - }, - "PreCommitDeposit": "0", - "PreCommitEpoch": 10101, - "DealWeight": "0", - "VerifiedDealWeight": "0" -} -``` - -### StateVerifiedClientStatus -StateVerifiedClientStatus returns the data cap for the given address. -Returns nil if there is no entry in the data cap table for the -address. - - -Perms: read - -Inputs: -```json -[ - "t01234", - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: `"0"` - -### StateWaitMsg -StateWaitMsg looks back in the chain for a message. If not found, it blocks until the -message arrives on chain, and gets to the indicated confidence depth. - - -Perms: read - -Inputs: -```json -[ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - 42 -] -``` - -Response: -```json -{ - "Message": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "Receipt": { - "ExitCode": 0, - "Return": "Ynl0ZSBhcnJheQ==", - "GasUsed": 9 - }, - "ReturnDec": {}, - "TipSet": [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ], - "Height": 10101 -} -``` - -## Sync -The Sync method group contains methods for interacting with and -observing the lotus sync service. - - -### SyncCheckBad -SyncCheckBad checks if a block was marked as bad, and if it was, returns -the reason. - - -Perms: read - -Inputs: -```json -[ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - } -] -``` - -Response: `"string value"` - -### SyncCheckpoint -SyncCheckpoint marks a blocks as checkpointed, meaning that it won't ever fork away from it. - - -Perms: admin - -Inputs: -```json -[ - [ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - { - "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" - } - ] -] -``` - -Response: `{}` - -### SyncIncomingBlocks -SyncIncomingBlocks returns a channel streaming incoming, potentially not -yet synced block headers. - - -Perms: read - -Inputs: `null` - -Response: -```json -{ - "Miner": "t01234", - "Ticket": { - "VRFProof": "Ynl0ZSBhcnJheQ==" - }, - "ElectionProof": { - "WinCount": 9, - "VRFProof": "Ynl0ZSBhcnJheQ==" - }, - "BeaconEntries": null, - "WinPoStProof": null, - "Parents": null, - "ParentWeight": "0", - "Height": 10101, - "ParentStateRoot": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "ParentMessageReceipts": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "Messages": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "BLSAggregate": { - "Type": 2, - "Data": "Ynl0ZSBhcnJheQ==" - }, - "Timestamp": 42, - "BlockSig": { - "Type": 2, - "Data": "Ynl0ZSBhcnJheQ==" - }, - "ForkSignaling": 42, - "ParentBaseFee": "0" -} -``` - -### SyncMarkBad -SyncMarkBad marks a blocks as bad, meaning that it won't ever by synced. -Use with extreme caution. - - -Perms: admin - -Inputs: -```json -[ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - } -] -``` - -Response: `{}` - -### SyncState -SyncState returns the current status of the lotus sync system. - - -Perms: read - -Inputs: `null` - -Response: -```json -{ - "ActiveSyncs": null -} -``` - -### SyncSubmitBlock -SyncSubmitBlock can be used to submit a newly created block to the. -network through this node - - -Perms: write - -Inputs: -```json -[ - { - "Header": { - "Miner": "t01234", - "Ticket": { - "VRFProof": "Ynl0ZSBhcnJheQ==" - }, - "ElectionProof": { - "WinCount": 9, - "VRFProof": "Ynl0ZSBhcnJheQ==" - }, - "BeaconEntries": null, - "WinPoStProof": null, - "Parents": null, - "ParentWeight": "0", - "Height": 10101, - "ParentStateRoot": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "ParentMessageReceipts": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "Messages": { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - }, - "BLSAggregate": { - "Type": 2, - "Data": "Ynl0ZSBhcnJheQ==" - }, - "Timestamp": 42, - "BlockSig": { - "Type": 2, - "Data": "Ynl0ZSBhcnJheQ==" - }, - "ForkSignaling": 42, - "ParentBaseFee": "0" - }, - "BlsMessages": null, - "SecpkMessages": null - } -] -``` - -Response: `{}` - -### SyncUnmarkBad -SyncUnmarkBad unmarks a blocks as bad, making it possible to be validated and synced again. - - -Perms: admin - -Inputs: -```json -[ - { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" - } -] -``` - -Response: `{}` - -## Wallet - - -### WalletBalance -WalletBalance returns the balance of the given address at the current head of the chain. - - -Perms: read - -Inputs: -```json -[ - "t01234" -] -``` - -Response: `"0"` - -### WalletDefaultAddress -WalletDefaultAddress returns the address marked as default in the wallet. - - -Perms: write - -Inputs: `null` - -Response: `"t01234"` - -### WalletDelete -WalletDelete deletes an address from the wallet. - - -Perms: write - -Inputs: -```json -[ - "t01234" -] -``` - -Response: `{}` - -### WalletExport -WalletExport returns the private key of an address in the wallet. - - -Perms: admin - -Inputs: -```json -[ - "t01234" -] -``` - -Response: -```json -{ - "Type": "string value", - "PrivateKey": "Ynl0ZSBhcnJheQ==" -} -``` - -### WalletHas -WalletHas indicates whether the given address is in the wallet. - - -Perms: write - -Inputs: -```json -[ - "t01234" -] -``` - -Response: `true` - -### WalletImport -WalletImport receives a KeyInfo, which includes a private key, and imports it into the wallet. - - -Perms: admin - -Inputs: -```json -[ - { - "Type": "string value", - "PrivateKey": "Ynl0ZSBhcnJheQ==" - } -] -``` - -Response: `"t01234"` - -### WalletList -WalletList lists all the addresses in the wallet. - - -Perms: write - -Inputs: `null` - -Response: `null` - -### WalletNew -WalletNew creates a new address in the wallet with the given sigType. - - -Perms: write - -Inputs: -```json -[ - 2 -] -``` - -Response: `"t01234"` - -### WalletSetDefault -WalletSetDefault marks the given address as as the default one. - - -Perms: admin - -Inputs: -```json -[ - "t01234" -] -``` - -Response: `{}` - -### WalletSign -WalletSign signs the given bytes using the given address. - - -Perms: sign - -Inputs: -```json -[ - "t01234", - "Ynl0ZSBhcnJheQ==" -] -``` - -Response: -```json -{ - "Type": 2, - "Data": "Ynl0ZSBhcnJheQ==" -} -``` - -### WalletSignMessage -WalletSignMessage signs the given message using the given address. - - -Perms: sign - -Inputs: -```json -[ - "t01234", - { - "Version": 42, - "To": "t01234", - "From": "t01234", - "Nonce": 42, - "Value": "0", - "GasLimit": 9, - "GasFeeCap": "0", - "GasPremium": "0", - "Method": 1, - "Params": "Ynl0ZSBhcnJheQ==" - } -] -``` - -Response: -```json -{ - "Message": { - "Version": 42, - "To": "t01234", - "From": "t01234", - "Nonce": 42, - "Value": "0", - "GasLimit": 9, - "GasFeeCap": "0", - "GasPremium": "0", - "Method": 1, - "Params": "Ynl0ZSBhcnJheQ==" - }, - "Signature": { - "Type": 2, - "Data": "Ynl0ZSBhcnJheQ==" - } -} -``` - -### WalletVerify -WalletVerify takes an address, a signature, and some bytes, and indicates whether the signature is valid. -The address does not have to be in the wallet. - - -Perms: read - -Inputs: -```json -[ - "t01234", - "Ynl0ZSBhcnJheQ==", - { - "Type": 2, - "Data": "Ynl0ZSBhcnJheQ==" - } -] -``` - -Response: `true` - diff --git a/documentation/en/building/api-troubleshooting.md b/documentation/en/building/api-troubleshooting.md deleted file mode 100644 index 0cb3a6800..000000000 --- a/documentation/en/building/api-troubleshooting.md +++ /dev/null @@ -1,36 +0,0 @@ -# API Troubleshooting - -## Types: params - -`params` must be an array. If there are no `params` you should still pass an empty array. - -## Types: TipSet - -For methods such as `Filecoin.StateMinerPower`, where the method accepts the argument of the type `TipSet`, you can pass `null` to use the current chain head. - -```sh -curl -X POST \ - -H "Content-Type: application/json" \ - --data '{ "jsonrpc": "2.0", "method": "Filecoin.StateMinerPower", "params": ["t0101", null], "id": 3 }' \ - 'http://127.0.0.1:1234/rpc/v0' -``` - -## Types: Sending a CID - -If you do not serialize the CID as a [JSON IPLD link](https://did-ipid.github.io/ipid-did-method/#txref), you will receive an error. Here is an example of a broken CURL request: - -```sh -curl -X POST \ - -H "Content-Type: application/json" \ - --data '{ "jsonrpc": "2.0", "method":"Filecoin.ClientGetDealInfo", "params": ["bafyreiaxl446wlnu6t6dpq4ivrjf4gda4gvsoi4rr6mpxau7z25xvk5pl4"], "id": 0 }' \ - 'http://127.0.0.1:1234/rpc/v0' -``` - -To fix it, change the `params` property to: - -```sh -curl -X POST \ - -H "Content-Type: application/json" \ - --data '{ "jsonrpc": "2.0", "method":"Filecoin.ClientGetDealInfo", "params": [{"/": "bafyreiaxl446wlnu6t6dpq4ivrjf4gda4gvsoi4rr6mpxau7z25xvk5pl4"}], "id": 0 }' \ - 'http://127.0.0.1:1234/rpc/v0' -``` diff --git a/documentation/en/building/api.md b/documentation/en/building/api.md deleted file mode 100644 index 3a2c2902b..000000000 --- a/documentation/en/building/api.md +++ /dev/null @@ -1,38 +0,0 @@ -# API endpoints and methods - -The API can be accessed on: - -- `http://[api:port]/rpc/v0` - HTTP RPC-API endpoint -- `ws://[api:port]/rpc/v0` - Websocket RPC-API endpoint -- `PUT http://[api:port]/rest/v0/import` - REST endpoint for file import (multipart upload). It requires write permissions. - -The RPC methods can be found in the [Reference](en+api-methods) and directly in the source code: - -- [Both Lotus node + miner APIs](https://github.com/filecoin-project/lotus/blob/master/api/api_common.go) -- [Lotus node API](https://github.com/filecoin-project/lotus/blob/master/api/api_full.go) -- [Lotus miner API](https://github.com/filecoin-project/lotus/blob/master/api/api_storage.go) - - -## JSON-RPC client - -Lotus uses its own Go library implementation of [JSON-RPC](https://github.com/filecoin-project/go-jsonrpc). - -## cURL example - -To demonstrate making an API request, we will take the method `ChainHead` from [api/api_full.go](https://github.com/filecoin-project/lotus/blob/master/api/api_full.go). - -```go -ChainHead(context.Context) (*types.TipSet, error) -``` - -And create a CURL command. In this command, `ChainHead` is included as `{ "method": "Filecoin.ChainHead" }`: - -```sh -curl -X POST \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $(cat ~/.lotusminer/token)" \ - --data '{ "jsonrpc": "2.0", "method": "Filecoin.ChainHead", "params": [], "id": 3 }' \ - 'http://127.0.0.1:1234/rpc/v0' -``` - -(See [this section](en+remote-api) to learn how to generate authorization tokens). diff --git a/documentation/en/building/building.md b/documentation/en/building/building.md deleted file mode 100644 index 5194f8314..000000000 --- a/documentation/en/building/building.md +++ /dev/null @@ -1,5 +0,0 @@ -# Building with Lotus - -Lotus applications provide HTTP (JSON-RPC) APIs that allow developers to control Lotus programatically. - -This section dives into how to setup and use these APIs, additionally providing information on advanced Lotus features and workflows, like Payment Channels or how to setup a fully local Lotus development network. diff --git a/documentation/en/building/jaeger-tracing.md b/documentation/en/building/jaeger-tracing.md deleted file mode 100644 index bbe4d3052..000000000 --- a/documentation/en/building/jaeger-tracing.md +++ /dev/null @@ -1,26 +0,0 @@ -# Jaeger Tracing - -Lotus has tracing built into many of its internals. To view the traces, first download [Jaeger](https://www.jaegertracing.io/download/) (Choose the 'all-in-one' binary). Then run it somewhere, start up the lotus daemon, and open up localhost:16686 in your browser. - -## Open Census - -Lotus uses [OpenCensus](https://opencensus.io/) for tracing application flow. This generates spans through the execution of annotated code paths. - -Currently it is set up to use Jaeger, though other tracing backends should be fairly easy to swap in. - -## Running Locally - -To easily run and view tracing locally, first, install jaeger. The easiest way to do this is to [download the binaries](https://www.jaegertracing.io/download/) and then run the `jaeger-all-in-one` binary. This will start up jaeger, listen for spans on `localhost:6831`, and expose a web UI for viewing traces on `http://localhost:16686/`. - -Now, to start sending traces from Lotus to Jaeger, set the environment variable `LOTUS_JAEGER` to `localhost:6831`, and start the `lotus daemon`. - -Now, to view any generated traces, open up `http://localhost:16686/` in your browser. - -## Adding Spans - -To annotate a new codepath with spans, add the following lines to the top of the function you wish to trace: - -```go -ctx, span := trace.StartSpan(ctx, "put function name here") -defer span.End() -``` diff --git a/documentation/en/building/local-devnet.md b/documentation/en/building/local-devnet.md deleted file mode 100644 index 3382b6471..000000000 --- a/documentation/en/building/local-devnet.md +++ /dev/null @@ -1,54 +0,0 @@ -# Setup Local Devnet - -Build the Lotus Binaries in debug mode, This enables the use of 2048 byte sectors. - -```sh -make 2k -``` - -Set the `LOTUS_SKIP_GENESIS_CHECK` environment variable to `_yes_`. This tells your -Lotus node that it's okay if the genesis being used doesn't match any baked-in -genesis. - -```sh -export LOTUS_SKIP_GENESIS_CHECK=_yes_ -``` - -Download the 2048 byte parameters: -```sh -./lotus fetch-params 2048 -``` - -Pre-seal some sectors: - -```sh -./lotus-seed pre-seal --sector-size 2KiB --num-sectors 2 -``` - -Create the genesis block and start up the first node: - -```sh -./lotus-seed genesis new localnet.json -./lotus-seed genesis add-miner localnet.json ~/.genesis-sectors/pre-seal-t01000.json -./lotus daemon --lotus-make-genesis=devgen.car --genesis-template=localnet.json --bootstrap=false -``` - -Then, in another console, import the genesis miner key: - -```sh -./lotus wallet import --as-default ~/.genesis-sectors/pre-seal-t01000.key -``` - -Set up the genesis miner: - -```sh -./lotus-miner init --genesis-miner --actor=t01000 --sector-size=2KiB --pre-sealed-sectors=~/.genesis-sectors --pre-sealed-metadata=~/.genesis-sectors/pre-seal-t01000.json --nosync -``` - -Now, finally, start up the miner: - -```sh -./lotus-miner run --nosync -``` - -If all went well, you will have your own local Lotus Devnet running. diff --git a/documentation/en/building/payment-channels.md b/documentation/en/building/payment-channels.md deleted file mode 100644 index afddcdc40..000000000 --- a/documentation/en/building/payment-channels.md +++ /dev/null @@ -1,111 +0,0 @@ -# Payment Channels - -Payment channels are used to transfer funds between two actors. - -For example in lotus a payment channel is created when a client wants to fetch data from a provider. -The client sends vouchers for the payment channel, and the provider sends data in response. - -The payment channel is created on-chain with an initial amount. -Vouchers allow the client and the provider to exchange funds incrementally off-chain. -The provider can submit vouchers to chain at any stage. -Either party to the payment channel can settle the payment channel on chain. -After a settlement period (currently 12 hours) either party to the payment channel can call collect on chain. -Collect sends the value of submitted vouchers to the channel recipient (the provider), and refunds the remaining channel balance to the channel creator (the client). - -Vouchers have a lane, a nonce and a value, where vouchers with a higher nonce supersede vouchers with a lower nonce in the same lane. -Each deal is created on a different lane. - -Note that payment channels and vouchers can be used for any situation in which two parties need to incrementally transfer value between each other off-chain. - -## Using the CLI - -For example a client creates a payment channel to a provider with value 10 FIL. - -```sh -$ lotus paych add-funds 10 - -``` - -The client creates a voucher in lane 0 (implied) with nonce 1 (implied) and value 2. - -```sh -$ lotus paych voucher create 2 - -``` - -The client sends the voucher to the provider and the provider adds the voucher to their local store. - -```sh -$ lotus paych voucher add -``` - -The provider sends some data to the client. - -The client creates a voucher in lane 0 (implied) with nonce 2 (implied) and value 4. - -```sh -$ lotus paych voucher create 4 - -``` - -The client sends the voucher to the provider and the provider adds the voucher and sends back more data. -etc. - -The client can add value to the channel after it has been created by calling `paych add-funds` with the same client and provider addresses. - -```sh -$ lotus paych add-funds 5 - # Same address as above. Channel now has 15 -``` - -Once the client has received all their data, they may settle the channel. -Note that settlement doesn't have to be done immediately. -For example the client may keep the channel open as long as it wants to continue making deals with the provider. - -```sh -$ lotus paych settle -``` - -The provider can submit vouchers to chain (note that lotus does this automatically when it sees a settle message appear on chain). -The provider may have received many vouchers with incrementally higher values. -The provider should submit the best vouchers. Note that there will be one best voucher for each lane. - -```sh -$ lotus paych voucher best-spendable - - - - -$ lotus paych voucher submit -``` - -Once the settlement period is over, either the client or provider can call collect to disburse funds. - -```sh -$ lotus paych collect -``` - -Check the status of a channel that is still being created using `lotus paych status-by-from-to`. - -```sh -$ lotus paych status-by-from-to -Creating channel - From: t3sb6xzvs6rhlziatagevxpp3dwapdolurtkpn4kyh3kgoo4tn5o7lutjqlsnvpceztlhxu3lzzfe34rvpsjgq - To: t1zip4sblhyrn4oxygzsm6nafbsynp2avmk3xafea - Pending Amt: 10000 - Wait Sentinel: bafy2bzacedk2jidsyxcynusted35t5ipkhu2kpiodtwyjr3pimrhke6f5pqbm -``` - -Check the status of a channel that has been created using `lotus paych status`. - -```sh -$ lotus paych status -Channel exists - Channel: t2nydpzhmeqkmid5smtqnowlr2mr5az6rexpmyv6i - From: t3sb6xzvs6rhlziatagevxpp3dwapdolurtkpn4kyh3kgoo4tn5o7lutjqlsnvpceztlhxu3lzzfe34rvpsjgq - To: t1zip4sblhyrn4oxygzsm6nafbsynp2avmk3xafea - Confirmed Amt: 10000 - Pending Amt: 6000 - Queued Amt: 3000 - Voucher Redeemed Amt: 2000 -``` diff --git a/documentation/en/building/remote-api.md b/documentation/en/building/remote-api.md deleted file mode 100644 index d0fedb51b..000000000 --- a/documentation/en/building/remote-api.md +++ /dev/null @@ -1,69 +0,0 @@ -# Setting up remote API access - -The **Lotus Miner** and the **Lotus Node** applications come with their own local API endpoints setup by default when they are running. - -These endpoints are used by `lotus` and `lotus-miner` to interact with the running process. In this section we will explain how to enable remote access to the Lotus APIs. - -Note that instructions are the same for `lotus` and `lotus-miner`. For simplicity, we will just show how to do it with `lotus`. - -## Setting the listening interface for the API endpoint - -By default, the API listens on the local "loopback" interface (`127.0.0.1`). This is configured in the `config.toml` file: - -```toml -[API] -# ListenAddress = "/ip4/127.0.0.1/tcp/1234/http" -# RemoteListenAddress = "" -# Timeout = "30s" -``` - -To access the API remotely, Lotus needs to listen on the right IP/interface. The IP associated to each interface can be usually found with the command `ip a`. Once the right IP is known, it can be set in the configuration: - -```toml -[API] -ListenAddress = "/ip4//tcp/3453/http" # port is an example - -# Only relevant for lotus-miner -# This should be the IP:Port pair where the miner is reachable from anyone trying to dial to it. -# If you have placed a reverse proxy or a NAT'ing device in front of it, this may be different from -# the EXTERNAL_INTERFACE_IP. -RemoteListenAddress = "" -``` - -> `0.0.0.0` can be used too. This is a wildcard that means "all interfaces". Depending on the network setup, this may affect security (listening on the wrong, exposed interface). - -After making these changes, please restart the affected process. - -## Issuing tokens - -Any client wishing to talk to the API endpoints will need a token. Tokens can be generated with: - -```sh -lotus auth create-token --perm -``` - -(similarly for the Lotus Miner). - -The permissions work as follows: - -- `read` - Read node state, no private data. -- `write` - Write to local store / chain, and `read` permissions. -- `sign` - Use private keys stored in wallet for signing, `read` and `write` permissions. -- `admin` - Manage permissions, `read`, `write`, and `sign` permissions. - - -Tokens can then be used in applications by setting an Authorization header as: - -``` -Authorization: Bearer -``` - - -## Environment variables - -`lotus`, `lotus-miner` and `lotus-worker` can actually interact with their respective applications running on a different node. All is needed to configure them are the following the *environment variables*: - -```sh -FULLNODE_API_INFO="TOKEN:/ip4//tcp//http" -MINER_API_INFO="TOKEN:/ip4//tcp//http" -``` diff --git a/documentation/en/getting-started/getting-started.md b/documentation/en/getting-started/getting-started.md deleted file mode 100644 index 99b4095d4..000000000 --- a/documentation/en/getting-started/getting-started.md +++ /dev/null @@ -1,3 +0,0 @@ -# Getting started - -This section will get you started with Lotus. We will setup the Lotus daemon (that should already be [installed](en+install)), start it, create a wallet and use it to send and receive some Filecoin. diff --git a/documentation/en/getting-started/setup-troubleshooting.md b/documentation/en/getting-started/setup-troubleshooting.md deleted file mode 100644 index f27a3faa5..000000000 --- a/documentation/en/getting-started/setup-troubleshooting.md +++ /dev/null @@ -1,57 +0,0 @@ -# Setup Troubleshooting - - -## Error: initializing node error: cbor input had wrong number of fields - -This happens when you are starting Lotus which has been compiled for one network, but it encounters data in the Lotus data folder which is for a different network, or for an older incompatible version. - -The solution is to clear the data folder (see below). - -## Config: Clearing data - -Here is a command that will delete your chain data, stored wallets, stored data and any miners you have set up: - -```sh -rm -rf ~/.lotus ~/.lotusminer -``` - -Note you do not always need to clear your data for [updating](en+update). - -## Error: Failed to connect bootstrap peer - -```sh -WARN peermgr peermgr/peermgr.go:131 failed to connect to bootstrap peer: failed to dial : all dials failed - * [/ip4/147.75.80.17/tcp/1347] failed to negotiate security protocol: connected to wrong peer -``` - -- Try running the build steps again and make sure that you have the latest code from GitHub. - -```sh -ERROR hello hello/hello.go:81 other peer has different genesis! -``` - -- Try deleting your file system's `~/.lotus` directory. Check that it exists with `ls ~/.lotus`. - -```sh -- repo is already locked -``` - -- You already have another lotus daemon running. - -## Config: Open files limit - -Lotus will attempt to set up the file descriptor (FD) limit automatically. If that does not work, you can still configure your system to allow higher than the default values. - -On most systems you can check the open files limit with: - -```sh -ulimit -n -``` - -You can also modify this number by using the `ulimit` command. It gives you the ability to control the resources available for the shell or process started by it. If the number is below 10000, you can change it with the following command prior to starting the Lotus daemon: - -```sh -ulimit -n 10000 -``` - -Note that this is not persisted and that systemd manages its own FD limits for services. Please use your favourite search engine to find instructions on how to persist and configure FD limits for your system. diff --git a/documentation/en/getting-started/setup.md b/documentation/en/getting-started/setup.md deleted file mode 100644 index e751da80b..000000000 --- a/documentation/en/getting-started/setup.md +++ /dev/null @@ -1,169 +0,0 @@ -# Setting up Lotus - -Your Lotus binaries have been installed and you are ready to start participating in the Filecoin network. - -## Selecting the right network - -You should have built the Lotus binaries from the right Github branch and Lotus will be fully setup to join the matching [Filecoin network](https://docs.filecoin.io/how-to/networks/). For more information on switching networks, check the [updating Lotus section](en+update). - -## Starting the daemon - -To start the daemon simply run: - -```sh -lotus daemon -``` - -or if you are using the provided systemd service files, do: - -```sh -systemctl start lotus-daemon -``` - -__If you are using Lotus from China__, make sure you set the following environment variable before running Lotus: - -``` -export IPFS_GATEWAY="https://proof-parameters.s3.cn-south-1.jdcloud-oss.com/ipfs/" -``` - - -During the first start, Lotus: - -* Will setup its data folder at `~/.lotus` -* Will download the necessary parameters -* Start syncing the Lotus chain - -If you started lotus using systemd, the logs will appear in `/var/log/lotus/daemon.log` (not in journalctl as usual), otherwise you will see them in your screen. - -Do not be appalled by the amount of warnings and sometimes errors showing in the logs, there are usually part of the usual functioning of the daemon as part of a distributed network. - -## Waiting to sync - -After the first start, the chain will start syncing until it has reached the tip. You can check how far the syncing process is with: - -```sh -lotus sync status -``` - -You can also interactively wait for the chain to be fully synced with: - -```sh -lotus sync wait -``` - -## Interacting with the Lotus daemon - -As shown above, the `lotus` command allows to interact with the running daemon. You will see it getting used in many of the documentation examples. - -This command-line-interface is self-documenting: - -```sh -# Show general help -lotus --help -# Show specific help for the "client" subcommand -lotus client --help -``` - -For example, after your Lotus daemon has been running for a few minutes, use `lotus` to check the number of other peers that it is connected to in the Filecoin network: - -```sh -lotus net peers -``` - -## Controlling the logging level - -```sh -lotus log set-level -``` -This command can be used to toggle the logging levels of the different -systems of a Lotus node. In decreasing order -of logging detail, the levels are `debug`, `info`, `warn`, and `error`. - -As an example, -to set the `chain` and `blocksync` to log at the `debug` level, run -`lotus log set-level --system chain --system blocksync debug`. - -To see the various logging system, run `lotus log list`. - - -## Configuration - -### Configuration file - -The Lotus daemon stores a configuration file in `~/.lotus/config.toml`. Note that by default all settings are commented. Here is an example configuration: - -```toml -[API] - # Binding address for the Lotus API - ListenAddress = "/ip4/127.0.0.1/tcp/1234/http" - # Not used by lotus daemon - RemoteListenAddress = "" - # General network timeout value - Timeout = "30s" - -# Libp2p provides connectivity to other Filecoin network nodes -[Libp2p] - # Binding address swarm - 0 means random port. - ListenAddresses = ["/ip4/0.0.0.0/tcp/0", "/ip6/::/tcp/0"] - # Insert any addresses you want to explicitally - # announce to other peers here. Otherwise, they are - # guessed. - AnnounceAddresses = [] - # Insert any addresses to avoid announcing here. - NoAnnounceAddresses = [] - # Connection manager settings, decrease if your - # machine is overwhelmed by connections. - ConnMgrLow = 150 - ConnMgrHigh = 180 - ConnMgrGrace = "20s" - -# Pubsub is used to broadcast information in the network -[Pubsub] - Bootstrapper = false - RemoteTracer = "/dns4/pubsub-tracer.filecoin.io/tcp/4001/p2p/QmTd6UvR47vUidRNZ1ZKXHrAFhqTJAD27rKL9XYghEKgKX" - -# This section can be used to enable adding and retriving files from IPFS -[Client] - UseIpfs = false - IpfsMAddr = "" - IpfsUseForRetrieval = false - -# Metrics configuration -[Metrics] - Nickname = "" - HeadNotifs = false -``` - -### Ensuring connectivity to your Lotus daemon - -Usually your lotus daemon will establish connectivity with others in the network and try to make itself diallable using uPnP. If you wish to manually ensure that your daemon is reachable: - -* Set a fixed port of your choice in the `ListenAddresses` in the Libp2p section (i.e. 6665). -* Open a port in your router that is forwarded to this port. This is usually called featured as "Port forwarding" and the instructions differ from router model to model but there are many guides online. -* Add your public IP/port to `AnnounceAddresses`. i.e. `/ip4//tcp/6665/`. - -Note that it is not a requirement to use Lotus as a client to the network to be fully reachable, as your node already connects to others directly. - - -### Environment variables - -Common to most Lotus binaries: - -* `LOTUS_FD_MAX`: Sets the file descriptor limit for the process -* `LOTUS_JAEGER`: Sets the Jaeger URL to send traces. See TODO. -* `LOTUS_DEV`: Any non-empty value will enable more verbose logging, useful only for developers. - -Specific to the *Lotus daemon*: - -* `LOTUS_PATH`: Location to store Lotus data (defaults to `~/.lotus`). -* `LOTUS_SKIP_GENESIS_CHECK=_yes_`: Set only if you wish to run a lotus network with a different genesis block. -* `LOTUS_CHAIN_TIPSET_CACHE`: Sets the size for the chainstore tipset cache. Defaults to `8192`. Increase if you perform frequent arbitrary tipset lookups. -* `LOTUS_CHAIN_INDEX_CACHE`: Sets the size for the epoch index cache. Defaults to `32768`. Increase if you perform frequent deep chain lookups for block heights far from the latest height. -* `LOTUS_BSYNC_MSG_WINDOW`: Set the initial maximum window size for message fetching blocksync request. Set to 10-20 if you have an internet connection with low bandwidth. - -Specific to the *Lotus miner*: - -* `LOTUS_MINER_PATH`: Location for the miner's on-disk repo. Defaults to `./lotusminer`. -* A number of environment variables are respected for configuring the behaviour of the Filecoin proving subsystem. [See here](en+miner-setup). - - diff --git a/documentation/en/getting-started/wallet.md b/documentation/en/getting-started/wallet.md deleted file mode 100644 index 25a67fb09..000000000 --- a/documentation/en/getting-started/wallet.md +++ /dev/null @@ -1,58 +0,0 @@ -# Obtaining and sending FIL - -In order to receive and send FIL with Lotus you will need to have installed the program and be running the Lotus daemon. - -## Creating a wallet - - -```sh -lotus wallet new bls -``` - -This will print your Filecoin address. - -Your wallet information is stored in the `~/.lotus/keystore` (or `$LOTUS_PATH/keystore`). For instructions on export/import, see below. - -You can create multiple wallets and list them with: - -```sh -lotus wallet list -``` - -## Obtaining FIL - -FIL can be obtained either by using one of the Faucets (available for the test networks) or by buying it from an exchange supporting FIL trading (once mainnet has launched). - -Once you have received some FIL you can check your balance with: - -```sh -lotus wallet balance -``` - -Remember that your will only see the latest balance when your daemon is fully synced to the chain. - -## Sending FIL - -Sending some FIL can be achieved by running: - -```sh -lotus wallet send
-``` - -Make sure to check `lotus wallet send --help` for additional options. - -## Exporting and importing a wallet - -You can export and re-import a wallet with: - -```sh -lotus wallet export
> wallet.private -``` - -and: - -```sh -lotus wallet import wallet.private -``` - -Keep your wallet's private key safe! diff --git a/documentation/en/installation/install-linux.md b/documentation/en/installation/install-linux.md deleted file mode 100644 index 6fe12996e..000000000 --- a/documentation/en/installation/install-linux.md +++ /dev/null @@ -1,129 +0,0 @@ -# Linux installation - -This page will show you the steps to build and install Lotus in your Linux computer. - -## Dependencies - -### System dependencies - -First of all, building Lotus will require installing some system dependencies, usually provided by your distribution. - -For Arch Linux: - -```sh -sudo pacman -Syu opencl-icd-loader gcc git bzr jq pkg-config opencl-icd-loader opencl-headers -``` - -For Ubuntu: - -```sh -sudo apt update -sudo apt install mesa-opencl-icd ocl-icd-opencl-dev gcc git bzr jq pkg-config curl -sudo apt upgrade -``` - -For Fedora: - -```sh -sudo dnf -y update -sudo dnf -y install gcc git bzr jq pkgconfig mesa-libOpenCL mesa-libOpenCL-devel opencl-headers ocl-icd ocl-icd-devel clang llvm -``` - -For OpenSUSE: - -```sh -sudo zypper in gcc git jq make libOpenCL1 opencl-headers ocl-icd-devel clang llvm -sudo ln -s /usr/lib64/libOpenCL.so.1 /usr/lib64/libOpenCL.so -``` - -### Rustup - -Lotus needs [rustup](https://rustup.rs/): - -```sh -curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -``` - -Please make sure your `$PATH` variable is correctly configured after the rustup installation so that `cargo` and `rustc` are found in their rustup-configured locations. - -### Go - -To build lotus you will need a working installation of **[Go1.14](https://golang.org/dl/)**. Follow the [installation instructions](https://golang.org/doc/install), which generally amount to: - -```sh -# Example! Check the installation instructions. -wget -c https://dl.google.com/go/go1.14.7.linux-amd64.tar.gz -O - | sudo tar -xz -C /usr/local -``` - -## Build and install Lotus - -With all the above, you are ready to build and install the Lotus suite (`lotus`, `lotus-miner` and `lotus-worker`): - -```sh -git clone https://github.com/filecoin-project/lotus.git -cd lotus/ -``` - -__IF YOU ARE IN CHINA__, set `export GOPROXY=https://goproxy.cn` before building - -Now, choose the network that you will be joining: - -* For `testnet`: `git checkout master` -* For `nerpa`: `git checkout ntwk-nerpa` -* For `butterfly`: `git checkout ntwk-butterfly` - -Once on the right branch, do: - -```sh -make clean install -sudo make install -``` - -This will put `lotus`, `lotus-miner` and `lotus-worker` in `/usr/local/bin`. `lotus` will use the `$HOME/.lotus` folder by default for storage (configuration, chain data, wallets...). `lotus-miner` will use `$HOME/.lotusminer` respectively. See the *environment variables* section below for how to customize these. - -> Remeber to [move your Lotus folder](en+update) if you are switching between different networks, or there has been a network reset. - - -### Native Filecoin FFI - -Some newer processors (AMD Zen (and later), Intel Ice Lake) have support SHA extensions. To make full use of your processor's capabilities, make sure you set the following variables BEFORE building from source (as described above): - -```sh -export RUSTFLAGS="-C target-cpu=native -g" -export FFI_BUILD_FROM_SOURCE=1 -``` - -> __NOTE__: This method of building does not produce portable binaries! Make sure you run the binary in the same machine as you built it. - -### systemd service files - -Lotus provides Systemd service files. They can be installed with: - -```sh -make install-daemon-service -make install-miner-service -``` - -After that, you should be able to control Lotus using `systemctl`. - -## Troubleshooting - -This section mentions some of the common pitfalls for building Lotus. Check the [getting started](en+getting-started) section for more tips on issues when running the lotus daemon. - -### Build errors - -Please check the build logs closely. If you have a dirty state in your git branch make sure to: - -```sh -git checkout -git reset origin/ --hard -make clean -``` - -### Slow builds from China - -Users from China can speed up their builds by setting: - -```sh -export GOPROXY=https://goproxy.cn -``` diff --git a/documentation/en/installation/install-macos.md b/documentation/en/installation/install-macos.md deleted file mode 100644 index ea9ecb8ca..000000000 --- a/documentation/en/installation/install-macos.md +++ /dev/null @@ -1,62 +0,0 @@ -# MacOS Instructions - -## Get XCode Command Line Tools - -To check if you already have the XCode Command Line Tools installed via the CLI, run: - -```sh -xcode-select -p -``` - -If this command returns a path, you can move on to the next step. Otherwise, to install via the CLI, run: - -```sh -xcode-select --install -``` - -To update, run: - -```sh -sudo rm -rf /Library/Developer/CommandLineTools -xcode-select --install -``` - -## Get HomeBrew - -We recommend that MacOS users use [HomeBrew](https://brew.sh) to install each the necessary packages. - -Check if you have HomeBrew: - -```sh -brew -v -``` - -This command returns a version number if you have HomeBrew installed and nothing otherwise. - -In your terminal, enter this command to install Homebrew: - -```sh -/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" -``` - -Use the command `brew install` to install the following packages: - -```sh -brew install go bzr jq pkg-config rustup -``` - -Clone - -```sh -git clone https://github.com/filecoin-project/lotus.git -cd lotus/ -``` - -Build - -```sh -make clean && make all -sudo make install -``` - -After intalling Lotus you will be ready to [setup and run the daemon](en+setup.md). diff --git a/documentation/en/installation/installation.md b/documentation/en/installation/installation.md deleted file mode 100644 index 98534da92..000000000 --- a/documentation/en/installation/installation.md +++ /dev/null @@ -1,39 +0,0 @@ -# Installation - -Lotus can be installed in [Linux](en-install-linux) and [MacOS](en-install-macos) machines by building it from source. Windows is not supported yet. - -This section contains guides to install Lotus in the supported platforms. - -Lotus is made of 3 binaries: - -* `lotus`: the main [Lotus node](en+setup) (Lotus client) -* `lotus-miner`: an application specifically for [Filecoin mining](en+miner-setup) -* `lotus-worker`: an additional [application to offload some heavy-processing tasks](en+lotus-worker) from the Lotus Miner. - -These applications are written in Go, but also import several Rust libraries. Lotus does not distribute -pre-compiled builds. - -## Hardware requirements - -### For client nodes - -* 8GiB of RAM -* Recommended for syncing speed: CPU with support for *Intel SHA Extensions* (AMD since Zen microarchitecture, Intel since Ice Lake). -* Recommended for speed: SSD hard drive (the bigger the better) - -### For miners - -The following correspond to the latest testing configuration: - -* 2 TB of hard drive space -* 8 core CPU -* 128 GiB of RAM with 256 GiB of NVMe SSD storage for swap (or simply, more RAM). -* Recommended for speed: CPU with support for *Intel SHA Extensions* (AMD since Zen microarchitecture, Intel since Ice Lake). -* GPU for block mining. The following have been [confirmed to be fast enough](en+gpus): - -- GeForce RTX 2080 Ti -- GeForce RTX 2080 SUPER -- GeForce RTX 2080 -- GeForce GTX 1080 Ti -- GeForce GTX 1080 -- GeForce GTX 1060 diff --git a/documentation/en/installation/update.md b/documentation/en/installation/update.md deleted file mode 100644 index 5d76592c9..000000000 --- a/documentation/en/installation/update.md +++ /dev/null @@ -1,72 +0,0 @@ -# Updating and restarting Lotus - -Updating Lotus is as simple as rebuilding and re-installing the software as explained in the previous sections. - -You can verify which version of Lotus you are running with: - -```sh -lotus version -``` - -Make sure that you `git pull` the branch that corresponds to the network that your Lotus daemon is using: - -```sh -git pull origin -make clean -make all -sudo make install # if necessary -``` - -Finally, restart the Lotus Node and/or Lotus Miner(s). - -__CAVEAT__: If you are running miners: check if your miner is safe to shut down and restart: `lotus-miner proving info`. If any deadline shows a block height in the past, do not restart: - -In the following example, Deadline Open is 454 which is earlier than Current Epoch of 500. This miner should **not** be shut down or restarted. - -``` -$ sudo lotus-miner proving info -Miner: t01001 -Current Epoch: 500 -Proving Period Boundary: 154 -Proving Period Start: 154 (2h53m0s ago) -Next Period Start: 3034 (in 21h7m0s) -Faults: 768 (100.00%) -Recovering: 768 -Deadline Index: 5 -Deadline Sectors: 0 -Deadline Open: 454 (23m0s ago) -Deadline Close: 514 (in 7m0s) -Deadline Challenge: 434 (33m0s ago) -Deadline FaultCutoff: 384 (58m0s ago) -``` - -In this next example, the miner can be safely restarted because no Deadlines are earlier than Current Epoch of 497. You have ~45 minutes before the miner must be back online to declare faults (FaultCutoff). If the miner has no faults, you have about an hour. - -``` -$ sudo lotus-miner proving info -Miner: t01000 -Current Epoch: 497 -Proving Period Boundary: 658 -Proving Period Start: 658 (in 1h20m30s) -Next Period Start: 3538 (in 25h20m30s) -Faults: 0 (0.00%) -Recovering: 0 -Deadline Index: 0 -Deadline Sectors: 768 -Deadline Open: 658 (in 1h20m30s) -Deadline Close: 718 (in 1h50m30s) -Deadline Challenge: 638 (in 1h10m30s) -Deadline FaultCutoff: 588 (in 45m30s) -``` - -## Switching networks and network resets - -If you wish to switch to a different lotus network or there has been a network reset, you will need to: - -* Checkout the appropiate repository branch and rebuild -* Ensure you do not mix Lotus data (`LOTUS_PATH`, usually `~/.lotus`) from a previous or different network. For this, either: - * Rename the folder to something else or, - * Set a different `LOTUS_PATH` for the new network. -* Same for `~/.lotusminer` if you are running a miner. - -Note that deleting the Lotus data folder will wipe all the chain data, wallets and configuration, so think twice before taking any non-reversible action. diff --git a/documentation/en/mining/gpus.md b/documentation/en/mining/gpus.md deleted file mode 100644 index ad0ed4f66..000000000 --- a/documentation/en/mining/gpus.md +++ /dev/null @@ -1,17 +0,0 @@ -# Benchmarking additional GPUs - -If you want to test a GPU that is not explicitly supported, set the following *environment variable*: - -```sh -BELLMAN_CUSTOM_GPU=":" -``` - -Here is an example of trying a GeForce GTX 1660 Ti with 1536 cores. - -```sh -BELLMAN_CUSTOM_GPU="GeForce GTX 1660 Ti:1536" -``` - -To get the number of cores for your GPU, you will need to check your card’s specifications. - -To perform the benchmark you can use Lotus' [benchmarking tool](https://github.com/filecoin-project/lotus/tree/master/cmd/lotus-bench). Results and discussion are tracked in a [GitHub issue thread](https://github.com/filecoin-project/lotus/issues/694). diff --git a/documentation/en/mining/lotus-seal-worker.md b/documentation/en/mining/lotus-seal-worker.md deleted file mode 100644 index 47e201ca5..000000000 --- a/documentation/en/mining/lotus-seal-worker.md +++ /dev/null @@ -1,99 +0,0 @@ -# Lotus Worker - -The **Lotus Worker** is an extra process that can offload heavy processing tasks from your **Lotus Miner**. The sealing process automatically runs in the **Lotus Miner** process, but you can use the Worker on another machine communicating over a fast network to free up resources on the machine running the mining process. - -## Installation - -The `lotus-worker` application is installed along with the others when running `sudo make install` as shown in the [Installation section](en+install-linux). For simplicity, we recommend following the same procedure in the machines that will run the Lotus Workers (even if the Lotus miner and the Lotus daemon are not used there). - -## Setting up the Miner - -### Allow external connections to the miner API - -First, you will need to ensure your `lotus-miner`'s API is accessible over the network. - -To do this, open up `~/.lotusminer/config.toml` (Or if you manually set `LOTUS_MINER_PATH`, look under that directory) and look for the API field. - -Default config: - -```toml -[API] -ListenAddress = "/ip4/127.0.0.1/tcp/2345/http" -RemoteListenAddress = "127.0.0.1:2345" -``` - -To make your node accessible over the local area network, you will need to determine your machine's IP on the LAN (`ip a`), and change the `127.0.0.1` in the file to that address. - -A more permissive and less secure option is to change it to `0.0.0.0`. This will allow anyone who can connect to your computer on that port to access the miner's API, though they will still need an auth token. - -`RemoteListenAddress` must be set to an address which other nodes on your network will be able to reach. - -### Create an authentication token - -Write down the output of: - -```sh -lotus-miner auth api-info --perm admin -``` - -The Lotus Workers will need this token to connect to the miner. - -## Connecting the Lotus Workers - -On each machine that will run the `lotus-worker` application you will need to define the following *environment variable*: - -```sh -export MINER_API_INFO::/ip4//tcp/2345` -``` - -If you are trying to use `lotus-worker` from China. You should additionally set: - -```sh -export IPFS_GATEWAY="https://proof-parameters.s3.cn-south-1.jdcloud-oss.com/ipfs/" -``` - - -Once that is done, you can run the Worker with: - -```sh -lotus-worker run -``` - -> If you are running multiple workers on the same host, you will need to specify the `--listen` flag and ensure each worker is on a different port. - -On your Lotus miner, check that the workers are correctly connected: - -```sh -lotus-miner sealing workers -Worker 0, host computer - CPU: [ ] 0 core(s) in use - RAM: [|||||||||||||||||| ] 28% 18.1 GiB/62.7 GiB - VMEM: [|||||||||||||||||| ] 28% 18.1 GiB/62.7 GiB - GPU: GeForce RTX 2080, not used - -Worker 1, host othercomputer - CPU: [ ] 0 core(s) in use - RAM: [|||||||||||||| ] 23% 14 GiB/62.7 GiB - VMEM: [|||||||||||||| ] 23% 14 GiB/62.7 GiB - GPU: GeForce RTX 2080, not used -``` - -## Running locally for manually managing process priority - -You can also run the **Lotus Worker** on the same machine as your **Lotus Miner**, so you can manually manage the process priority. - -To do so you have to first __disable all seal task types__ in the miner config. This is important to prevent conflicts between the two processes: - -```toml -[Storage] - AllowPreCommit1 = false - AllowPreCommit2 = false - AllowCommit = false - AllowUnseal = false -``` - -You can then run the miner on your local-loopback interface; - -```sh -lotus-worker run -``` diff --git a/documentation/en/mining/managing-deals.md b/documentation/en/mining/managing-deals.md deleted file mode 100644 index 5f73a6a2d..000000000 --- a/documentation/en/mining/managing-deals.md +++ /dev/null @@ -1,19 +0,0 @@ -# Managing deals - - -While the Lotus Miner is running as a daemon, the `lotus-miner` application can be used to manage and configure the miner: - - -```sh -lotus-miner storage-deals --help -``` - -Running the above command will show the different options related to deals. For example, `lotus-miner storage-deals set-ask` allows to set the price for storage that your miner uses to respond ask requests from clients. - -If deals are ongoing, you can check the data transfers with: - -```sh -lotus-miner data-transfers list -``` - -Make sure you explore the `lotus-miner` CLI. Every command is self-documented and takes a `--help` flag that offers specific information about it. diff --git a/documentation/en/mining/miner-setup.md b/documentation/en/mining/miner-setup.md deleted file mode 100644 index cafa1e7b1..000000000 --- a/documentation/en/mining/miner-setup.md +++ /dev/null @@ -1,241 +0,0 @@ -# Miner setup - -This page will guide you through all you need to know to sucessfully run a **Lotus Miner**. Before proceeding, remember that you should be running the Lotus daemon on a fully synced chain. - -## Performance tweaks - -This is a list of performance tweaks to consider before starting the miner: - -### Building - -As [explained already](en+install-linux#native-filecoin-ffi-10) should have exported the following variables before building the Lotus applications: - -```sh -export RUSTFLAGS="-C target-cpu=native -g" -export FFI_BUILD_FROM_SOURCE=1 -``` - -### Environment - -For high performance mining, we recommend setting the following variables in your environment so that they are available when running any of the Lotus applications: - -```sh -# See https://github.com/filecoin-project/bellman -export BELLMAN_CPU_UTILIZATION=0.875 - -# See https://github.com/filecoin-project/rust-fil-proofs/ -export FIL_PROOFS_MAXIMIZE_CACHING=1 # More speed at RAM cost (1x sector-size of RAM - 32 GB). -export FIL_PROOFS_USE_GPU_COLUMN_BUILDER=1 # precommit2 GPU acceleration -export FIL_PROOFS_USE_GPU_TREE_BUILDER=1 -``` - -IF YOU ARE RUNNING FROM CHINA: - -```sh -export IPFS_GATEWAY="https://proof-parameters.s3.cn-south-1.jdcloud-oss.com/ipfs/" -``` - -IF YOUR MINER RUNS IN A DIFFERENT MACHINE AS THE LOTUS DAEMON: - -```sh -export FULLNODE_API_INFO=:/ip4//tcp//http -``` - -If you will be using systemd service files to run the Lotus daemon and miner, make sure you include these variables manually in the service files. - -### Adding swap - -If you have only 128GiB of RAM, you will need to make sure your system provides at least an extra 256GiB of fast swap (preferably NVMe SSD): - -```sh -sudo fallocate -l 256G /swapfile -sudo chmod 600 /swapfile -sudo mkswap /swapfile -sudo swapon /swapfile -# show current swap spaces and take note of the current highest priority -swapon --show -# append the following line to /etc/fstab (ensure highest priority) and then reboot -# /swapfile swap swap pri=50 0 0 -sudo reboot -# check a 256GB swap file is automatically mounted and has the highest priority -swapon --show -``` - -## Creating a new BLS wallet - -You will need a BLS wallet (`t3...`) for mining. To create it, if you don't have one already, run: - -```sh -lotus wallet new bls -``` - -Next make sure to [send some funds](en+wallet) to this address so that the miner setup can be completed. - -## Initializing the miner - -> SPACE RACE: -> To participate in the Space race, please register your miner: -> -> - Visit the [faucet](http://spacerace.faucet.glif.io/) -> - Paste the address you created under REQUEST. -> - Press the Request button. - -Now that you have a miner address you can initialize the Lotus Miner: - -```sh -lotus-miner init --owner= --no-local-storage -``` - -* The `--no-local-storage` flag is used so that we configure specific locations for storage later below. -* The init process will download over 100GiB of initialization parameters to /var/tmp/filecoin-proof-parameters. Make sure there is space or set `FIL_PROOFS_PARAMETER_CACHE` to somewhere else. -* The Lotus Miner configuration folder is created at `~/.lotusminer/` or `$LOTUS_MINER_PATH` if set. - -## Reachability - -Before you start your miner, it is __very important__ to configure it so that it is reachable from any peer in the Filecoin network. For this you will need a stable public IP and edit your `~/.lotusminer/config.toml` as follows: - -```toml -... -[Libp2p] - ListenAddresses = ["/ip4/0.0.0.0/tcp/24001"] # choose a fixed port - AnnounceAddresses = ["/ip4//tcp/24001"] # important! -... -``` - -Once you start your miner, make sure you can connect to its public IP/port (you can use `telnet`, `nc` for the task...). If you have an active firewall or some sort, you may need to additionally open ports in it. - - -## Starting the miner - -You are now ready to start your Lotus miner: - -```sh -lotus-miner run -``` - -or if you are using the systemd service file: - -```sh -systemctl start lotus-miner -``` - -> __Do not proceed__ from here until you have verified that your miner not only is running, but also __reachable on its public IP address__. - -## Publishing the miner addresses - -Once the miner is up and running, publish your miner address (which you configured above) on the chain (please ensure it is dialable): - -```sh -lotus-miner actor set-addrs /ip4//tcp/24001 -``` - -## Setting locations for sealing and long-term storage - -If you used the `--no-local-storage` flag during initialization, you can now specify the disk locations for sealing (SSD recommended) and long-term storage (otherwise you can skip this): - -``` -lotus-miner storage attach --init --seal -lotus-miner storage attach --init --store -lotus-miner storage list -``` - -## Pledging sectors - -If you would like to compete for block rewards by increasing your power in the network as soon as possible, you can optionally pledge one or several sectors, depending on your storage. It can also be used to test that the sealing process works correctly. Pledging is equivalent to storing random data instead of real data obtained through storage deals. - -> Note that pledging sectors to the mainnet network makes most sense when trying to obtain a reasonable amount of total power in the network, thus obtaining real chances to mine new blocks. Otherwise it is only useful for testing purposes. - -If you decide to go ahead, then do: - -```sh -lotus-miner sectors pledge -``` - -This will write data to `$TMPDIR` so make sure that there is enough space available. - -You shoud check that your sealing job has started with: - -```sh -lotus-miner sealing jobs -``` - -This will be accommpanied by a file in `/unsealed`. - -After some minutes, you can check the sealing progress with: - -```sh -lotus-miner sectors list -# and -lotus-miner sealing workers -``` - -When sealing for the new is complete, `pSet: NO` will become `pSet: YES`. - -Once the sealing is finished, you will want to configure how long it took your miner to seal this sector and configure the miner accordingly. To find out how long it took use: - -``` -lotus-miner sectors status --log 0 -``` - -Once you know, you can edit the Miner's `~/.lotusminer/config.toml` accordingly: - -``` -... -[Dealmaking] -... - ExpectedSealDuration = "12h0m0s" # The time it took your miner -``` - -You can also take the chance to edit other values, such as `WaitForDealsDelay` which specifies the delay between accepting the first deal and sealing, allowing to place multiple deals in the same sector. - -Once you are done editing the configuration, [restart your miner](en+update). - -If you wish to be able to re-use a pledged sector for real storage deals before the pledged period of 6 months ends, you will need to mark them for upgrade: - -```sh -lotus-miner sectors mark-for-upgrade -``` - -The sector should become inactive within 24 hours. From that point, the pledged storage can be re-used to store real data associated with real storage deals. - -## Separate address for windowPoSt messages - -WindowPoSt is the mechanism through which storage is verified in Filecoin. It requires miners to submit proofs for all sectors every 24h, which require sending messages to the chain. - -Because many other mining related actions require sending messages to the chain, and not all of those are "high value", it may be desirable to use a separate account to send PoSt messages from. This allows for setting lower GasFeeCaps on the lower value messages without creating head-of-line blocking problems for the PoSt messages in congested chain conditions - -To set this up, first create a new account, and send it some funds for gas fees: - -```sh -lotus wallet new bls -t3defg... - -lotus send t3defg... 100 -``` - -Next add the control address: - -```sh -lotus-miner actor control set --really-do-it t3defg... -Add t3defg... -Message CID: bafy2.. -``` - -Wait for the message to land on chain: - -```sh -lotus state wait-msg bafy2.. -... -Exit Code: 0 -... -``` - -Finally, check the miner control address list to make sure the address was correctly setup: - -```sh -lotus-miner actor control list -name ID key use balance -owner t01111 t3abcd... other 300 FIL -worker t01111 t3abcd... other 300 FIL -control-0 t02222 t3defg... post 100 FIL -``` diff --git a/documentation/en/mining/mining-troubleshooting.md b/documentation/en/mining/mining-troubleshooting.md deleted file mode 100644 index a9972c2bd..000000000 --- a/documentation/en/mining/mining-troubleshooting.md +++ /dev/null @@ -1,59 +0,0 @@ -# Mining Troubleshooting - -## Config: Filecoin Proof Parameters directory - -If you want to put the **Filecoin Proof Parameters** in a different directory, use the following environment variable: - -```sh -FIL_PROOFS_PARAMETER_CACHE -``` - -## Error: Can't acquire bellman.lock - -The **Bellman** lockfile is created to lock a GPU for a process. This bug can occur when this file isn't properly cleaned up: - -```sh -mining block failed: computing election proof: github.com/filecoin-project/lotus/miner.(*Miner).mineOne -``` - -This bug occurs when the miner can't acquire the `bellman.lock`. To fix it you need to stop the `lotus-miner` and remove `/tmp/bellman.lock`. - -## Error: Failed to get api endpoint - -```sh -lotus-miner info -# WARN main lotus-miner/main.go:73 failed to get api endpoint: (/Users/myrmidon/.lotusminer) %!w(*errors.errorString=&{API not running (no endpoint)}): -``` - -If you see this, that means your **Lotus Miner** isn't ready yet. You need to finish [syncing the chain](en+setup#waiting-to-sync-370). - -## Error: Your computer may not be fast enough - -```sh -CAUTION: block production took longer than the block delay. Your computer may not be fast enough to keep up -``` - -If you see this, that means your computer is too slow and your blocks are not included in the chain, and you will not receive any rewards. - -## Error: No space left on device - -```sh -lotus-miner sectors pledge -# No space left on device (os error 28) -``` - -If you see this, that means `pledge-sector` wrote too much data to `$TMPDIR` which by default is the root partition (This is common for Linux setups). Usually your root partition does not get the largest partition of storage so you will need to change the environment variable to something else. - -## Error: GPU unused - -If you suspect that your GPU is not being used, first make sure it is properly configured as described in the [testing configuration page](hardware-mining.md). Once you've done that (and set the `BELLMAN_CUSTOM_GPU` as appropriate if necessary) you can verify your GPU is being used by running a quick lotus-bench benchmark. - -First, to watch GPU utilization run `nvtop` in one terminal, then in a separate terminal, run: - -```sh -make bench -./bench sealing --sector-size=2KiB -``` - -This process uses a fair amount of GPU, and generally takes ~4 minutes to complete. If you do not see any activity in nvtop from lotus during the entire process, it is likely something is misconfigured with your GPU. - diff --git a/documentation/en/mining/mining.md b/documentation/en/mining/mining.md deleted file mode 100644 index b1b944c6e..000000000 --- a/documentation/en/mining/mining.md +++ /dev/null @@ -1,8 +0,0 @@ -# Storage Mining - -This section of the documentation explains how to do storage mining with Lotus. Please note that not everyone can do storage mining, and that you should not attempt it on on networks where sector sizes are 32GB+ unless you meet the [hardware requirements](en+install#hardware-requirements-1). - -From this point we assume that you have setup and are running the [Lotus Node](en+setup), that it has fully synced the Filecoin chain and that you are familiar with how to interact with it using the `lotus` command-line interface. - -In order to perform storage mining, apart from the Lotus daemon, you will be additionally interacting with the `lotus-miner` and potentially the `lotus-worker` applications (which you should have [installed](en+install-linux) along the `lotus` application already). - diff --git a/documentation/en/store/adding-from-ipfs.md b/documentation/en/store/adding-from-ipfs.md deleted file mode 100644 index 2f6b097cc..000000000 --- a/documentation/en/store/adding-from-ipfs.md +++ /dev/null @@ -1,20 +0,0 @@ -# Adding data from IPFS - -Lotus supports making deals with data stored in IPFS, without having to re-import it into lotus. - -To enable this integration, you need to have an IPFS daemon running in the background. - -Then, open up `~/.lotus/config.toml` (or if you manually set `LOTUS_PATH`, look under that directory) and look for the Client field, and set `UseIpfs` to `true`. - -```toml -[Client] -UseIpfs = true -``` - -After restarting the lotus daemon, you should be able to make deals with data in your IPFS node: - -```sh -$ ipfs add -r SomeData -QmSomeData -$ ./lotus client deal QmSomeData t01000 0.0000000001 80000 -``` diff --git a/documentation/en/store/making-deals.md b/documentation/en/store/making-deals.md deleted file mode 100644 index ca3a47182..000000000 --- a/documentation/en/store/making-deals.md +++ /dev/null @@ -1,71 +0,0 @@ -# Making storage deals - -## Adding a file to Lotus - -Before sending data to a Filecoin miner for storage, the data needs to be correctly formatted and packed. This can be achieved by locally importing the data into Lotus with: - -```sh -lotus client import ./your-example-file.txt -``` - -Upon success, this command will return a **Data CID**. This is a very important piece of information, as it will be used to make deals to both store and retrieve the data in the future. - -You can list the data CIDs of the files you locally imported with: - -```sh -lotus client local -``` - -## Storing data in the network - -To store data in the network you will need to: - -* Find a Filecoin miner willing to store it -* Make a deal with the miner agreeing on the price to pay and the duration for which the data should be stored. - -You can obtain a list of all miners in the network with: - -```sh -lotus state list-miners -t0xxxx -t0xxxy -t0xxxz -... -``` - -This will print a list of miner IDs. In order to ask for the terms offered by a particular miner, you can then run: - -```sh -lotus client query-ask -``` - -If you are satisfied with the terms, you can proceed to propose a deal to the miner, using the **Data CID** that you obtained during the import step: - - -```sh -lotus client deal -``` - -This command will interactively ask you for the CID, miner ID and duration in days for the deal. You can also call it with arguments: - -```sh -lotus client deal -``` - -where the `duration` is expressed in blocks (1 block is equivalent to 30s). - -## Checking the status of the deals - -You can list deals with: - -```sh -lotus client list-deals -``` - -Among other things, this will give you information about the current state on your deals, whether they have been published on chain (by the miners) and whether the miners have been slashed for not honoring them. - -For a deal to succeed, the miner needs to be correctly configured and running, accept the deal and *seal* the file correctly. Otherwise, the deal will appear in error state. - -You can make deals with multiple miners for the same data. - -Once a deal is sucessful and the data is *sealed*, it can be [retrieved](en+retrieving). diff --git a/documentation/en/store/retrieve.md b/documentation/en/store/retrieve.md deleted file mode 100644 index 1e8db65af..000000000 --- a/documentation/en/store/retrieve.md +++ /dev/null @@ -1,27 +0,0 @@ -# Retrieving Data - -Once data has been succesfully [stored](en+making-deals) and sealed by a Filecoin miner, it can be retrieved. - -In order to do this we will need to create a **retrieval deal**. - -## Finding data by CID - -In order to retrieve some data you will need the **Data CID** that was used to create the storage deal. - -You can find who is storing the data by running: - -```sh -lotus client find -``` - -## Making a retrieval deal - -You can then make a retrieval deal with: - -```sh -lotus client retrieve -``` - -This commands take other optional flags (check `--help`). - -If the outfile does not exist it will be created in the Lotus repository directory. This process may take 2 to 10 minutes. diff --git a/documentation/en/store/storage-troubleshooting.md b/documentation/en/store/storage-troubleshooting.md deleted file mode 100644 index 7087ec3d0..000000000 --- a/documentation/en/store/storage-troubleshooting.md +++ /dev/null @@ -1,30 +0,0 @@ -# Storage Troubleshooting - -## Error: Routing: not found - -``` -WARN main lotus/main.go:72 routing: not found -``` - -This error means that the miner is offline. - -## Error: Failed to start deal - -```sh -WARN main lotus/main.go:72 failed to start deal: computing commP failed: generating CommP: Piece must be at least 127 bytes -``` - -This error means that there is a minimum file size of 127 bytes. - -## Error: 0kb file response during retrieval - -This means that the file to be retrieved may have not yet been sealed and is thus, not retrievable yet. - -Miners can check sealing progress with this command: - -```sh -lotus-miner sectors list -``` - -When sealing is complete, `pSet: NO` will become `pSet: YES`. - diff --git a/documentation/en/store/store.md b/documentation/en/store/store.md deleted file mode 100644 index 205bd0e23..000000000 --- a/documentation/en/store/store.md +++ /dev/null @@ -1,11 +0,0 @@ -# Storing and retrieving data - -Lotus enables you to store any data on the Filecoin network and retrieve it later. This is achieved by making *deals* with miners. - -A *storage deal* specifies that a miner should store ceratin data for a previously agreed period and price. - -Once a deal is made, the data is then sent to the miners, which regularly proves that it is storing it. If they fail to do so, the miner is penalized (slashed). - -The data can be retrieved with a *retrieval deal*. - -This section explains how to use Lotus to [store](en+making-deals) and [retrieve](en+retrieving) data from the Filecoin network. From 591e32af487204f58d092015a8ce25439b884718 Mon Sep 17 00:00:00 2001 From: Hector Sanjuan Date: Thu, 17 Sep 2020 20:41:46 +0200 Subject: [PATCH 076/303] Remove circle_ci docs-check. --- .circleci/config.yml | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index acd447f69..d8f149889 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -346,15 +346,6 @@ jobs: - run: git --no-pager diff - run: git --no-pager diff --quiet - docs-check: - executor: golang - steps: - - install-deps - - prepare - - run: make docsgen - - run: git --no-pager diff - - run: git --no-pager diff --quiet - lint: &lint description: | Run golangci-lint. @@ -424,7 +415,6 @@ workflows: - mod-tidy-check - gofmt - cbor-gen-check - - docs-check - test: codecov-upload: true test-suite-name: full From bc9232544c7f5d68c737b9d7887ae05f0232ff34 Mon Sep 17 00:00:00 2001 From: Hector Sanjuan Date: Thu, 17 Sep 2020 20:48:09 +0200 Subject: [PATCH 077/303] Remove faqs too --- documentation/en/faqs.md | 132 --------------------------------------- 1 file changed, 132 deletions(-) delete mode 100644 documentation/en/faqs.md diff --git a/documentation/en/faqs.md b/documentation/en/faqs.md deleted file mode 100644 index 74119a5b6..000000000 --- a/documentation/en/faqs.md +++ /dev/null @@ -1,132 +0,0 @@ -# Frequently Asked Questions - -Here are some FAQs concerning the Lotus implementation and participation in -Testnet. -For questions concerning the broader Filecoin project, please -go [here](https://filecoin.io/faqs/). - -## Introduction to Lotus - -### What is Lotus? - -Lotus is an implementation of the **Filecoin Distributed Storage Network**, written in Go. -It is designed to be modular and interoperable with any other implementation of the Filecoin Protocol. - -### What are the components of Lotus? - -Lotus is composed of two separate pieces that can talk to each other: - -The Lotus Node can sync the blockchain, validating all blocks, transfers, and deals -along the way. It can also facilitate the creation of new storage deals. If you are not -interested in providing your own storage to the network, and do not want to produce blocks -yourself, then the Lotus Node is all you need! - -The Lotus Miner does everything you need for the registration of storage, and the -production of new blocks. The Lotus Miner communicates with the network by talking -to a Lotus Node over the JSON-RPC API. - -## Setting up a Lotus Node - -### How do I set up a Lotus Node? - -Follow the instructions found [here](en+install) and [here](en+setup). - -### Where can I get the latest version of Lotus? - -Download the binary tagged as the `Latest Release` from the [Lotus Github repo](https://github.com/filecoin-project/lotus/releases) or checkout the `master` branch of the source repository. - -### What operating systems can Lotus run on? - -Lotus can build and run on most Linux and MacOS systems with [at least 8GB of RAM](en+install#hardware-requirements-1). Windows is not yet supported. - -### How can I update to the latest version of Lotus? - -To update Lotus, follow the instructions [here](en+update). - -### How do I prepare a fresh installation of Lotus? - -Stop the Lotus daemon, and delete all related files, including sealed and chain data by -running `rm ~/.lotus ~/.lotusminer`. - -Then, install Lotus afresh by following the instructions -found [here](en+install). - -### Can I configure where the node's config and data goes? - -Yes! The `LOTUS_PATH` variable sets the path for where the Lotus node's data is written. -The `LOTUS_MINER_PATH` variable does the same for miner-specific information. - -## Interacting with a Lotus Node - -### How can I communicate with a Lotus Node? - -Lotus Nodes have a command-line interface, as well as a JSON-RPC API. - -### What are the commands I can send using the command-line interface? - -The command-line interface is self-documenting, try running `lotus --help` from the `lotus` home -directory for more. - -### How can I send a request over the JSON-RPC API? - -Information on how to send a `cURL` request to the JSON-RPC API can be found -[here](en+api). - -### What are the requests I can send over the JSON-RPC API? - -Please have a look [here](en+api). - - -## The Test Network - -### What is Testnet? - -Testnet is a live network of Lotus Nodes run by the -community for testing purposes. - -### Is FIL on the Testnet worth anything? - -Nothing at all! - -### How can I see the status of Testnet? - -The [dashboard](https://stats.testnet.filecoin.io/) displays the status of the network as -well as a ton of other metrics you might find interesting. - -## Mining with a Lotus Node on Testnet - -### How do I get started mining with Lotus? - -Follow the instructions found [here](en+mining). - -### What are the minimum hardware requirements? - -An example test configuration, and minimum hardware requirements can be found -[here](en+install#hardware-requirements-8). - -Note that these might NOT be the minimum requirements for mining on Mainnet. - -### What are some GPUs that have been tested? - -See previous question. - -### Why is my GPU not being used when sealing a sector? - -Sealing a sector does not involve constant GPU operations. It's possible -that your GPU simply isn't necessary at the moment you checked. - -## Advanced questions - -### Is there a Docker image for lotus? - -Community-contributed Docker and Docker Compose examples are available -[here](https://github.com/filecoin-project/lotus/tree/master/tools/dockers/docker-examples). - -### How can I run two miners on the same machine? - -You can do so by changing the storage path variable for the second miner, e.g., -`LOTUS_MINER_PATH=~/.lotusminer2`. You will also need to make sure that no ports collide. - -### How do I setup my own local devnet? - -Follow the instructions found [here](en+local-devnet). From 784399738a49f282bc8002771e080d2eba5a33f9 Mon Sep 17 00:00:00 2001 From: Hector Sanjuan Date: Thu, 17 Sep 2020 20:50:37 +0200 Subject: [PATCH 078/303] Keep api-methods.md even if not part of the docs --- Makefile | 2 +- documentation/en/api-methods.md | 4567 +++++++++++++++++++++++++++++++ 2 files changed, 4568 insertions(+), 1 deletion(-) create mode 100644 documentation/en/api-methods.md diff --git a/Makefile b/Makefile index 245d8a9a0..56ab361ec 100644 --- a/Makefile +++ b/Makefile @@ -286,7 +286,7 @@ method-gen: gen: type-gen method-gen docsgen: - go run ./api/docgen > documentation/en/building/api-methods.md + go run ./api/docgen > documentation/en/api-methods.md print-%: @echo $*=$($*) diff --git a/documentation/en/api-methods.md b/documentation/en/api-methods.md new file mode 100644 index 000000000..2f3164bb7 --- /dev/null +++ b/documentation/en/api-methods.md @@ -0,0 +1,4567 @@ +# Groups +* [](#) + * [Closing](#Closing) + * [Shutdown](#Shutdown) + * [Version](#Version) +* [Auth](#Auth) + * [AuthNew](#AuthNew) + * [AuthVerify](#AuthVerify) +* [Beacon](#Beacon) + * [BeaconGetEntry](#BeaconGetEntry) +* [Chain](#Chain) + * [ChainExport](#ChainExport) + * [ChainGetBlock](#ChainGetBlock) + * [ChainGetBlockMessages](#ChainGetBlockMessages) + * [ChainGetGenesis](#ChainGetGenesis) + * [ChainGetMessage](#ChainGetMessage) + * [ChainGetNode](#ChainGetNode) + * [ChainGetParentMessages](#ChainGetParentMessages) + * [ChainGetParentReceipts](#ChainGetParentReceipts) + * [ChainGetPath](#ChainGetPath) + * [ChainGetRandomnessFromBeacon](#ChainGetRandomnessFromBeacon) + * [ChainGetRandomnessFromTickets](#ChainGetRandomnessFromTickets) + * [ChainGetTipSet](#ChainGetTipSet) + * [ChainGetTipSetByHeight](#ChainGetTipSetByHeight) + * [ChainHasObj](#ChainHasObj) + * [ChainHead](#ChainHead) + * [ChainNotify](#ChainNotify) + * [ChainReadObj](#ChainReadObj) + * [ChainSetHead](#ChainSetHead) + * [ChainStatObj](#ChainStatObj) + * [ChainTipSetWeight](#ChainTipSetWeight) +* [Client](#Client) + * [ClientCalcCommP](#ClientCalcCommP) + * [ClientDataTransferUpdates](#ClientDataTransferUpdates) + * [ClientDealSize](#ClientDealSize) + * [ClientFindData](#ClientFindData) + * [ClientGenCar](#ClientGenCar) + * [ClientGetDealInfo](#ClientGetDealInfo) + * [ClientGetDealUpdates](#ClientGetDealUpdates) + * [ClientHasLocal](#ClientHasLocal) + * [ClientImport](#ClientImport) + * [ClientListDataTransfers](#ClientListDataTransfers) + * [ClientListDeals](#ClientListDeals) + * [ClientListImports](#ClientListImports) + * [ClientMinerQueryOffer](#ClientMinerQueryOffer) + * [ClientQueryAsk](#ClientQueryAsk) + * [ClientRemoveImport](#ClientRemoveImport) + * [ClientRetrieve](#ClientRetrieve) + * [ClientRetrieveTryRestartInsufficientFunds](#ClientRetrieveTryRestartInsufficientFunds) + * [ClientRetrieveWithEvents](#ClientRetrieveWithEvents) + * [ClientStartDeal](#ClientStartDeal) +* [Gas](#Gas) + * [GasEstimateFeeCap](#GasEstimateFeeCap) + * [GasEstimateGasLimit](#GasEstimateGasLimit) + * [GasEstimateGasPremium](#GasEstimateGasPremium) + * [GasEstimateMessageGas](#GasEstimateMessageGas) +* [I](#I) + * [ID](#ID) +* [Log](#Log) + * [LogList](#LogList) + * [LogSetLevel](#LogSetLevel) +* [Market](#Market) + * [MarketEnsureAvailable](#MarketEnsureAvailable) +* [Miner](#Miner) + * [MinerCreateBlock](#MinerCreateBlock) + * [MinerGetBaseInfo](#MinerGetBaseInfo) +* [Mpool](#Mpool) + * [MpoolClear](#MpoolClear) + * [MpoolGetConfig](#MpoolGetConfig) + * [MpoolGetNonce](#MpoolGetNonce) + * [MpoolPending](#MpoolPending) + * [MpoolPush](#MpoolPush) + * [MpoolPushMessage](#MpoolPushMessage) + * [MpoolSelect](#MpoolSelect) + * [MpoolSetConfig](#MpoolSetConfig) + * [MpoolSub](#MpoolSub) +* [Msig](#Msig) + * [MsigAddApprove](#MsigAddApprove) + * [MsigAddCancel](#MsigAddCancel) + * [MsigAddPropose](#MsigAddPropose) + * [MsigApprove](#MsigApprove) + * [MsigCancel](#MsigCancel) + * [MsigCreate](#MsigCreate) + * [MsigGetAvailableBalance](#MsigGetAvailableBalance) + * [MsigGetVested](#MsigGetVested) + * [MsigPropose](#MsigPropose) + * [MsigSwapApprove](#MsigSwapApprove) + * [MsigSwapCancel](#MsigSwapCancel) + * [MsigSwapPropose](#MsigSwapPropose) +* [Net](#Net) + * [NetAddrsListen](#NetAddrsListen) + * [NetAgentVersion](#NetAgentVersion) + * [NetAutoNatStatus](#NetAutoNatStatus) + * [NetBandwidthStats](#NetBandwidthStats) + * [NetBandwidthStatsByPeer](#NetBandwidthStatsByPeer) + * [NetBandwidthStatsByProtocol](#NetBandwidthStatsByProtocol) + * [NetConnect](#NetConnect) + * [NetConnectedness](#NetConnectedness) + * [NetDisconnect](#NetDisconnect) + * [NetFindPeer](#NetFindPeer) + * [NetPeers](#NetPeers) + * [NetPubsubScores](#NetPubsubScores) +* [Paych](#Paych) + * [PaychAllocateLane](#PaychAllocateLane) + * [PaychAvailableFunds](#PaychAvailableFunds) + * [PaychAvailableFundsByFromTo](#PaychAvailableFundsByFromTo) + * [PaychCollect](#PaychCollect) + * [PaychGet](#PaychGet) + * [PaychGetWaitReady](#PaychGetWaitReady) + * [PaychList](#PaychList) + * [PaychNewPayment](#PaychNewPayment) + * [PaychSettle](#PaychSettle) + * [PaychStatus](#PaychStatus) + * [PaychVoucherAdd](#PaychVoucherAdd) + * [PaychVoucherCheckSpendable](#PaychVoucherCheckSpendable) + * [PaychVoucherCheckValid](#PaychVoucherCheckValid) + * [PaychVoucherCreate](#PaychVoucherCreate) + * [PaychVoucherList](#PaychVoucherList) + * [PaychVoucherSubmit](#PaychVoucherSubmit) +* [State](#State) + * [StateAccountKey](#StateAccountKey) + * [StateAllMinerFaults](#StateAllMinerFaults) + * [StateCall](#StateCall) + * [StateChangedActors](#StateChangedActors) + * [StateCirculatingSupply](#StateCirculatingSupply) + * [StateCompute](#StateCompute) + * [StateDealProviderCollateralBounds](#StateDealProviderCollateralBounds) + * [StateGetActor](#StateGetActor) + * [StateGetReceipt](#StateGetReceipt) + * [StateListActors](#StateListActors) + * [StateListMessages](#StateListMessages) + * [StateListMiners](#StateListMiners) + * [StateLookupID](#StateLookupID) + * [StateMarketBalance](#StateMarketBalance) + * [StateMarketDeals](#StateMarketDeals) + * [StateMarketParticipants](#StateMarketParticipants) + * [StateMarketStorageDeal](#StateMarketStorageDeal) + * [StateMinerActiveSectors](#StateMinerActiveSectors) + * [StateMinerAvailableBalance](#StateMinerAvailableBalance) + * [StateMinerDeadlines](#StateMinerDeadlines) + * [StateMinerFaults](#StateMinerFaults) + * [StateMinerInfo](#StateMinerInfo) + * [StateMinerInitialPledgeCollateral](#StateMinerInitialPledgeCollateral) + * [StateMinerPartitions](#StateMinerPartitions) + * [StateMinerPower](#StateMinerPower) + * [StateMinerPreCommitDepositForPower](#StateMinerPreCommitDepositForPower) + * [StateMinerProvingDeadline](#StateMinerProvingDeadline) + * [StateMinerRecoveries](#StateMinerRecoveries) + * [StateMinerSectorCount](#StateMinerSectorCount) + * [StateMinerSectors](#StateMinerSectors) + * [StateMsgGasCost](#StateMsgGasCost) + * [StateNetworkName](#StateNetworkName) + * [StateReadState](#StateReadState) + * [StateReplay](#StateReplay) + * [StateSearchMsg](#StateSearchMsg) + * [StateSectorExpiration](#StateSectorExpiration) + * [StateSectorGetInfo](#StateSectorGetInfo) + * [StateSectorPartition](#StateSectorPartition) + * [StateSectorPreCommitInfo](#StateSectorPreCommitInfo) + * [StateVerifiedClientStatus](#StateVerifiedClientStatus) + * [StateWaitMsg](#StateWaitMsg) +* [Sync](#Sync) + * [SyncCheckBad](#SyncCheckBad) + * [SyncCheckpoint](#SyncCheckpoint) + * [SyncIncomingBlocks](#SyncIncomingBlocks) + * [SyncMarkBad](#SyncMarkBad) + * [SyncState](#SyncState) + * [SyncSubmitBlock](#SyncSubmitBlock) + * [SyncUnmarkBad](#SyncUnmarkBad) +* [Wallet](#Wallet) + * [WalletBalance](#WalletBalance) + * [WalletDefaultAddress](#WalletDefaultAddress) + * [WalletDelete](#WalletDelete) + * [WalletExport](#WalletExport) + * [WalletHas](#WalletHas) + * [WalletImport](#WalletImport) + * [WalletList](#WalletList) + * [WalletNew](#WalletNew) + * [WalletSetDefault](#WalletSetDefault) + * [WalletSign](#WalletSign) + * [WalletSignMessage](#WalletSignMessage) + * [WalletVerify](#WalletVerify) +## + + +### Closing + + +Perms: read + +Inputs: `null` + +Response: `{}` + +### Shutdown + + +Perms: admin + +Inputs: `null` + +Response: `{}` + +### Version + + +Perms: read + +Inputs: `null` + +Response: +```json +{ + "Version": "string value", + "APIVersion": 3584, + "BlockDelay": 42 +} +``` + +## Auth + + +### AuthNew + + +Perms: admin + +Inputs: +```json +[ + null +] +``` + +Response: `"Ynl0ZSBhcnJheQ=="` + +### AuthVerify + + +Perms: read + +Inputs: +```json +[ + "string value" +] +``` + +Response: `null` + +## Beacon +The Beacon method group contains methods for interacting with the random beacon (DRAND) + + +### BeaconGetEntry +BeaconGetEntry returns the beacon entry for the given filecoin epoch. If +the entry has not yet been produced, the call will block until the entry +becomes available + + +Perms: read + +Inputs: +```json +[ + 10101 +] +``` + +Response: +```json +{ + "Round": 42, + "Data": "Ynl0ZSBhcnJheQ==" +} +``` + +## Chain +The Chain method group contains methods for interacting with the +blockchain, but that do not require any form of state computation. + + +### ChainExport +ChainExport returns a stream of bytes with CAR dump of chain data. +The exported chain data includes the header chain from the given tipset +back to genesis, the entire genesis state, and the most recent 'nroots' +state trees. +If oldmsgskip is set, messages from before the requested roots are also not included. + + +Perms: read + +Inputs: +```json +[ + 10101, + true, + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: `"Ynl0ZSBhcnJheQ=="` + +### ChainGetBlock +ChainGetBlock returns the block specified by the given CID. + + +Perms: read + +Inputs: +```json +[ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + } +] +``` + +Response: +```json +{ + "Miner": "t01234", + "Ticket": { + "VRFProof": "Ynl0ZSBhcnJheQ==" + }, + "ElectionProof": { + "WinCount": 9, + "VRFProof": "Ynl0ZSBhcnJheQ==" + }, + "BeaconEntries": null, + "WinPoStProof": null, + "Parents": null, + "ParentWeight": "0", + "Height": 10101, + "ParentStateRoot": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "ParentMessageReceipts": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "Messages": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "BLSAggregate": { + "Type": 2, + "Data": "Ynl0ZSBhcnJheQ==" + }, + "Timestamp": 42, + "BlockSig": { + "Type": 2, + "Data": "Ynl0ZSBhcnJheQ==" + }, + "ForkSignaling": 42, + "ParentBaseFee": "0" +} +``` + +### ChainGetBlockMessages +ChainGetBlockMessages returns messages stored in the specified block. + + +Perms: read + +Inputs: +```json +[ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + } +] +``` + +Response: +```json +{ + "BlsMessages": null, + "SecpkMessages": null, + "Cids": null +} +``` + +### ChainGetGenesis +ChainGetGenesis returns the genesis tipset. + + +Perms: read + +Inputs: `null` + +Response: +```json +{ + "Cids": null, + "Blocks": null, + "Height": 0 +} +``` + +### ChainGetMessage +ChainGetMessage reads a message referenced by the specified CID from the +chain blockstore. + + +Perms: read + +Inputs: +```json +[ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + } +] +``` + +Response: +```json +{ + "Version": 42, + "To": "t01234", + "From": "t01234", + "Nonce": 42, + "Value": "0", + "GasLimit": 9, + "GasFeeCap": "0", + "GasPremium": "0", + "Method": 1, + "Params": "Ynl0ZSBhcnJheQ==" +} +``` + +### ChainGetNode +There are not yet any comments for this method. + +Perms: read + +Inputs: +```json +[ + "string value" +] +``` + +Response: +```json +{ + "Cid": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "Obj": {} +} +``` + +### ChainGetParentMessages +ChainGetParentMessages returns messages stored in parent tipset of the +specified block. + + +Perms: read + +Inputs: +```json +[ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + } +] +``` + +Response: `null` + +### ChainGetParentReceipts +ChainGetParentReceipts returns receipts for messages in parent tipset of +the specified block. + + +Perms: read + +Inputs: +```json +[ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + } +] +``` + +Response: `null` + +### ChainGetPath +ChainGetPath returns a set of revert/apply operations needed to get from +one tipset to another, for example: +``` + to + ^ +from tAA + ^ ^ +tBA tAB + ^---*--^ + ^ + tRR +``` +Would return `[revert(tBA), apply(tAB), apply(tAA)]` + + +Perms: read + +Inputs: +```json +[ + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ], + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: `null` + +### ChainGetRandomnessFromBeacon +ChainGetRandomnessFromBeacon is used to sample the beacon for randomness. + + +Perms: read + +Inputs: +```json +[ + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ], + 2, + 10101, + "Ynl0ZSBhcnJheQ==" +] +``` + +Response: `null` + +### ChainGetRandomnessFromTickets +ChainGetRandomnessFromTickets is used to sample the chain for randomness. + + +Perms: read + +Inputs: +```json +[ + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ], + 2, + 10101, + "Ynl0ZSBhcnJheQ==" +] +``` + +Response: `null` + +### ChainGetTipSet +ChainGetTipSet returns the tipset specified by the given TipSetKey. + + +Perms: read + +Inputs: +```json +[ + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: +```json +{ + "Cids": null, + "Blocks": null, + "Height": 0 +} +``` + +### ChainGetTipSetByHeight +ChainGetTipSetByHeight looks back for a tipset at the specified epoch. +If there are no blocks at the specified epoch, a tipset at an earlier epoch +will be returned. + + +Perms: read + +Inputs: +```json +[ + 10101, + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: +```json +{ + "Cids": null, + "Blocks": null, + "Height": 0 +} +``` + +### ChainHasObj +ChainHasObj checks if a given CID exists in the chain blockstore. + + +Perms: read + +Inputs: +```json +[ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + } +] +``` + +Response: `true` + +### ChainHead +ChainHead returns the current head of the chain. + + +Perms: read + +Inputs: `null` + +Response: +```json +{ + "Cids": null, + "Blocks": null, + "Height": 0 +} +``` + +### ChainNotify +ChainNotify returns channel with chain head updates. +First message is guaranteed to be of len == 1, and type == 'current'. + + +Perms: read + +Inputs: `null` + +Response: `null` + +### ChainReadObj +ChainReadObj reads ipld nodes referenced by the specified CID from chain +blockstore and returns raw bytes. + + +Perms: read + +Inputs: +```json +[ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + } +] +``` + +Response: `"Ynl0ZSBhcnJheQ=="` + +### ChainSetHead +ChainSetHead forcefully sets current chain head. Use with caution. + + +Perms: admin + +Inputs: +```json +[ + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: `{}` + +### ChainStatObj +ChainStatObj returns statistics about the graph referenced by 'obj'. +If 'base' is also specified, then the returned stat will be a diff +between the two objects. + + +Perms: read + +Inputs: +```json +[ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + } +] +``` + +Response: +```json +{ + "Size": 42, + "Links": 42 +} +``` + +### ChainTipSetWeight +ChainTipSetWeight computes weight for the specified tipset. + + +Perms: read + +Inputs: +```json +[ + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: `"0"` + +## Client +The Client methods all have to do with interacting with the storage and +retrieval markets as a client + + +### ClientCalcCommP +ClientCalcCommP calculates the CommP for a specified file + + +Perms: read + +Inputs: +```json +[ + "string value" +] +``` + +Response: +```json +{ + "Root": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "Size": 1024 +} +``` + +### ClientDataTransferUpdates +There are not yet any comments for this method. + +Perms: write + +Inputs: `null` + +Response: +```json +{ + "TransferID": 3, + "Status": 1, + "BaseCID": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "IsInitiator": true, + "IsSender": true, + "Voucher": "string value", + "Message": "string value", + "OtherPeer": "12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf", + "Transferred": 42 +} +``` + +### ClientDealSize +ClientDealSize calculates real deal data size + + +Perms: read + +Inputs: +```json +[ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + } +] +``` + +Response: +```json +{ + "PayloadSize": 9, + "PieceSize": 1032 +} +``` + +### ClientFindData +ClientFindData identifies peers that have a certain file, and returns QueryOffers (one per peer). + + +Perms: read + +Inputs: +```json +[ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + null +] +``` + +Response: `null` + +### ClientGenCar +ClientGenCar generates a CAR file for the specified file. + + +Perms: write + +Inputs: +```json +[ + { + "Path": "string value", + "IsCAR": true + }, + "string value" +] +``` + +Response: `{}` + +### ClientGetDealInfo +ClientGetDealInfo returns the latest information about a given deal. + + +Perms: read + +Inputs: +```json +[ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + } +] +``` + +Response: +```json +{ + "ProposalCid": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "State": 42, + "Message": "string value", + "Provider": "t01234", + "DataRef": { + "TransferType": "string value", + "Root": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "PieceCid": null, + "PieceSize": 1024 + }, + "PieceCID": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "Size": 42, + "PricePerEpoch": "0", + "Duration": 42, + "DealID": 5432, + "CreationTime": "0001-01-01T00:00:00Z" +} +``` + +### ClientGetDealUpdates +ClientGetDealUpdates returns the status of updated deals + + +Perms: read + +Inputs: `null` + +Response: +```json +{ + "ProposalCid": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "State": 42, + "Message": "string value", + "Provider": "t01234", + "DataRef": { + "TransferType": "string value", + "Root": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "PieceCid": null, + "PieceSize": 1024 + }, + "PieceCID": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "Size": 42, + "PricePerEpoch": "0", + "Duration": 42, + "DealID": 5432, + "CreationTime": "0001-01-01T00:00:00Z" +} +``` + +### ClientHasLocal +ClientHasLocal indicates whether a certain CID is locally stored. + + +Perms: write + +Inputs: +```json +[ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + } +] +``` + +Response: `true` + +### ClientImport +ClientImport imports file under the specified path into filestore. + + +Perms: admin + +Inputs: +```json +[ + { + "Path": "string value", + "IsCAR": true + } +] +``` + +Response: +```json +{ + "Root": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "ImportID": 50 +} +``` + +### ClientListDataTransfers +ClientListTransfers returns the status of all ongoing transfers of data + + +Perms: write + +Inputs: `null` + +Response: `null` + +### ClientListDeals +ClientListDeals returns information about the deals made by the local client. + + +Perms: write + +Inputs: `null` + +Response: `null` + +### ClientListImports +ClientListImports lists imported files and their root CIDs + + +Perms: write + +Inputs: `null` + +Response: `null` + +### ClientMinerQueryOffer +ClientMinerQueryOffer returns a QueryOffer for the specific miner and file. + + +Perms: read + +Inputs: +```json +[ + "t01234", + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + null +] +``` + +Response: +```json +{ + "Err": "string value", + "Root": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "Piece": null, + "Size": 42, + "MinPrice": "0", + "UnsealPrice": "0", + "PaymentInterval": 42, + "PaymentIntervalIncrease": 42, + "Miner": "t01234", + "MinerPeer": { + "Address": "t01234", + "ID": "12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf", + "PieceCID": null + } +} +``` + +### ClientQueryAsk +ClientQueryAsk returns a signed StorageAsk from the specified miner. + + +Perms: read + +Inputs: +```json +[ + "12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf", + "t01234" +] +``` + +Response: +```json +{ + "Ask": { + "Price": "0", + "VerifiedPrice": "0", + "MinPieceSize": 1032, + "MaxPieceSize": 1032, + "Miner": "t01234", + "Timestamp": 10101, + "Expiry": 10101, + "SeqNo": 42 + }, + "Signature": { + "Type": 2, + "Data": "Ynl0ZSBhcnJheQ==" + } +} +``` + +### ClientRemoveImport +ClientRemoveImport removes file import + + +Perms: admin + +Inputs: +```json +[ + 50 +] +``` + +Response: `{}` + +### ClientRetrieve +ClientRetrieve initiates the retrieval of a file, as specified in the order. + + +Perms: admin + +Inputs: +```json +[ + { + "Root": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "Piece": null, + "Size": 42, + "Total": "0", + "UnsealPrice": "0", + "PaymentInterval": 42, + "PaymentIntervalIncrease": 42, + "Client": "t01234", + "Miner": "t01234", + "MinerPeer": { + "Address": "t01234", + "ID": "12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf", + "PieceCID": null + } + }, + { + "Path": "string value", + "IsCAR": true + } +] +``` + +Response: `{}` + +### ClientRetrieveTryRestartInsufficientFunds +ClientRetrieveTryRestartInsufficientFunds attempts to restart stalled retrievals on a given payment channel +which are stuck due to insufficient funds + + +Perms: write + +Inputs: +```json +[ + "t01234" +] +``` + +Response: `{}` + +### ClientRetrieveWithEvents +ClientRetrieveWithEvents initiates the retrieval of a file, as specified in the order, and provides a channel +of status updates. + + +Perms: admin + +Inputs: +```json +[ + { + "Root": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "Piece": null, + "Size": 42, + "Total": "0", + "UnsealPrice": "0", + "PaymentInterval": 42, + "PaymentIntervalIncrease": 42, + "Client": "t01234", + "Miner": "t01234", + "MinerPeer": { + "Address": "t01234", + "ID": "12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf", + "PieceCID": null + } + }, + { + "Path": "string value", + "IsCAR": true + } +] +``` + +Response: +```json +{ + "Event": 5, + "Status": 0, + "BytesReceived": 42, + "FundsSpent": "0", + "Err": "string value" +} +``` + +### ClientStartDeal +ClientStartDeal proposes a deal with a miner. + + +Perms: admin + +Inputs: +```json +[ + { + "Data": { + "TransferType": "string value", + "Root": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "PieceCid": null, + "PieceSize": 1024 + }, + "Wallet": "t01234", + "Miner": "t01234", + "EpochPrice": "0", + "MinBlocksDuration": 42, + "ProviderCollateral": "0", + "DealStartEpoch": 10101, + "FastRetrieval": true, + "VerifiedDeal": true + } +] +``` + +Response: `null` + +## Gas + + +### GasEstimateFeeCap +GasEstimateFeeCap estimates gas fee cap + + +Perms: read + +Inputs: +```json +[ + { + "Version": 42, + "To": "t01234", + "From": "t01234", + "Nonce": 42, + "Value": "0", + "GasLimit": 9, + "GasFeeCap": "0", + "GasPremium": "0", + "Method": 1, + "Params": "Ynl0ZSBhcnJheQ==" + }, + 9, + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: `"0"` + +### GasEstimateGasLimit +GasEstimateGasLimit estimates gas used by the message and returns it. +It fails if message fails to execute. + + +Perms: read + +Inputs: +```json +[ + { + "Version": 42, + "To": "t01234", + "From": "t01234", + "Nonce": 42, + "Value": "0", + "GasLimit": 9, + "GasFeeCap": "0", + "GasPremium": "0", + "Method": 1, + "Params": "Ynl0ZSBhcnJheQ==" + }, + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: `9` + +### GasEstimateGasPremium +GasEstimateGasPremium estimates what gas price should be used for a +message to have high likelihood of inclusion in `nblocksincl` epochs. + + +Perms: read + +Inputs: +```json +[ + 42, + "t01234", + 9, + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: `"0"` + +### GasEstimateMessageGas +GasEstimateMessageGas estimates gas values for unset message gas fields + + +Perms: read + +Inputs: +```json +[ + { + "Version": 42, + "To": "t01234", + "From": "t01234", + "Nonce": 42, + "Value": "0", + "GasLimit": 9, + "GasFeeCap": "0", + "GasPremium": "0", + "Method": 1, + "Params": "Ynl0ZSBhcnJheQ==" + }, + { + "MaxFee": "0" + }, + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: +```json +{ + "Version": 42, + "To": "t01234", + "From": "t01234", + "Nonce": 42, + "Value": "0", + "GasLimit": 9, + "GasFeeCap": "0", + "GasPremium": "0", + "Method": 1, + "Params": "Ynl0ZSBhcnJheQ==" +} +``` + +## I + + +### ID + + +Perms: read + +Inputs: `null` + +Response: `"12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf"` + +## Log + + +### LogList + + +Perms: write + +Inputs: `null` + +Response: `null` + +### LogSetLevel + + +Perms: write + +Inputs: +```json +[ + "string value", + "string value" +] +``` + +Response: `{}` + +## Market + + +### MarketEnsureAvailable +MarketFreeBalance + + +Perms: sign + +Inputs: +```json +[ + "t01234", + "t01234", + "0" +] +``` + +Response: +```json +{ + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" +} +``` + +## Miner + + +### MinerCreateBlock +There are not yet any comments for this method. + +Perms: write + +Inputs: +```json +[ + { + "Miner": "t01234", + "Parents": [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ], + "Ticket": { + "VRFProof": "Ynl0ZSBhcnJheQ==" + }, + "Eproof": { + "WinCount": 9, + "VRFProof": "Ynl0ZSBhcnJheQ==" + }, + "BeaconValues": null, + "Messages": null, + "Epoch": 10101, + "Timestamp": 42, + "WinningPoStProof": null + } +] +``` + +Response: +```json +{ + "Header": { + "Miner": "t01234", + "Ticket": { + "VRFProof": "Ynl0ZSBhcnJheQ==" + }, + "ElectionProof": { + "WinCount": 9, + "VRFProof": "Ynl0ZSBhcnJheQ==" + }, + "BeaconEntries": null, + "WinPoStProof": null, + "Parents": null, + "ParentWeight": "0", + "Height": 10101, + "ParentStateRoot": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "ParentMessageReceipts": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "Messages": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "BLSAggregate": { + "Type": 2, + "Data": "Ynl0ZSBhcnJheQ==" + }, + "Timestamp": 42, + "BlockSig": { + "Type": 2, + "Data": "Ynl0ZSBhcnJheQ==" + }, + "ForkSignaling": 42, + "ParentBaseFee": "0" + }, + "BlsMessages": null, + "SecpkMessages": null +} +``` + +### MinerGetBaseInfo +There are not yet any comments for this method. + +Perms: read + +Inputs: +```json +[ + "t01234", + 10101, + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: +```json +{ + "MinerPower": "0", + "NetworkPower": "0", + "Sectors": null, + "WorkerKey": "t01234", + "SectorSize": 34359738368, + "PrevBeaconEntry": { + "Round": 42, + "Data": "Ynl0ZSBhcnJheQ==" + }, + "BeaconEntries": null, + "HasMinPower": true +} +``` + +## Mpool +The Mpool methods are for interacting with the message pool. The message pool +manages all incoming and outgoing 'messages' going over the network. + + +### MpoolClear +MpoolClear clears pending messages from the mpool + + +Perms: write + +Inputs: +```json +[ + true +] +``` + +Response: `{}` + +### MpoolGetConfig +MpoolGetConfig returns (a copy of) the current mpool config + + +Perms: read + +Inputs: `null` + +Response: +```json +{ + "PriorityAddrs": null, + "SizeLimitHigh": 123, + "SizeLimitLow": 123, + "ReplaceByFeeRatio": 12.3, + "PruneCooldown": 60000000000, + "GasLimitOverestimation": 12.3 +} +``` + +### MpoolGetNonce +MpoolGetNonce gets next nonce for the specified sender. +Note that this method may not be atomic. Use MpoolPushMessage instead. + + +Perms: read + +Inputs: +```json +[ + "t01234" +] +``` + +Response: `42` + +### MpoolPending +MpoolPending returns pending mempool messages. + + +Perms: read + +Inputs: +```json +[ + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: `null` + +### MpoolPush +MpoolPush pushes a signed message to mempool. + + +Perms: write + +Inputs: +```json +[ + { + "Message": { + "Version": 42, + "To": "t01234", + "From": "t01234", + "Nonce": 42, + "Value": "0", + "GasLimit": 9, + "GasFeeCap": "0", + "GasPremium": "0", + "Method": 1, + "Params": "Ynl0ZSBhcnJheQ==" + }, + "Signature": { + "Type": 2, + "Data": "Ynl0ZSBhcnJheQ==" + } + } +] +``` + +Response: +```json +{ + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" +} +``` + +### MpoolPushMessage +MpoolPushMessage atomically assigns a nonce, signs, and pushes a message +to mempool. +maxFee is only used when GasFeeCap/GasPremium fields aren't specified + +When maxFee is set to 0, MpoolPushMessage will guess appropriate fee +based on current chain conditions + + +Perms: sign + +Inputs: +```json +[ + { + "Version": 42, + "To": "t01234", + "From": "t01234", + "Nonce": 42, + "Value": "0", + "GasLimit": 9, + "GasFeeCap": "0", + "GasPremium": "0", + "Method": 1, + "Params": "Ynl0ZSBhcnJheQ==" + }, + { + "MaxFee": "0" + } +] +``` + +Response: +```json +{ + "Message": { + "Version": 42, + "To": "t01234", + "From": "t01234", + "Nonce": 42, + "Value": "0", + "GasLimit": 9, + "GasFeeCap": "0", + "GasPremium": "0", + "Method": 1, + "Params": "Ynl0ZSBhcnJheQ==" + }, + "Signature": { + "Type": 2, + "Data": "Ynl0ZSBhcnJheQ==" + } +} +``` + +### MpoolSelect +MpoolSelect returns a list of pending messages for inclusion in the next block + + +Perms: read + +Inputs: +```json +[ + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ], + 12.3 +] +``` + +Response: `null` + +### MpoolSetConfig +MpoolSetConfig sets the mpool config to (a copy of) the supplied config + + +Perms: write + +Inputs: +```json +[ + { + "PriorityAddrs": null, + "SizeLimitHigh": 123, + "SizeLimitLow": 123, + "ReplaceByFeeRatio": 12.3, + "PruneCooldown": 60000000000, + "GasLimitOverestimation": 12.3 + } +] +``` + +Response: `{}` + +### MpoolSub +There are not yet any comments for this method. + +Perms: read + +Inputs: `null` + +Response: +```json +{ + "Type": 0, + "Message": { + "Message": { + "Version": 42, + "To": "t01234", + "From": "t01234", + "Nonce": 42, + "Value": "0", + "GasLimit": 9, + "GasFeeCap": "0", + "GasPremium": "0", + "Method": 1, + "Params": "Ynl0ZSBhcnJheQ==" + }, + "Signature": { + "Type": 2, + "Data": "Ynl0ZSBhcnJheQ==" + } + } +} +``` + +## Msig +The Msig methods are used to interact with multisig wallets on the +filecoin network + + +### MsigAddApprove +MsigAddApprove approves a previously proposed AddSigner message +It takes the following params: , , , +, , + + +Perms: sign + +Inputs: +```json +[ + "t01234", + "t01234", + 42, + "t01234", + "t01234", + true +] +``` + +Response: +```json +{ + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" +} +``` + +### MsigAddCancel +MsigAddCancel cancels a previously proposed AddSigner message +It takes the following params: , , , +, + + +Perms: sign + +Inputs: +```json +[ + "t01234", + "t01234", + 42, + "t01234", + true +] +``` + +Response: +```json +{ + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" +} +``` + +### MsigAddPropose +MsigAddPropose proposes adding a signer in the multisig +It takes the following params: , , +, + + +Perms: sign + +Inputs: +```json +[ + "t01234", + "t01234", + "t01234", + true +] +``` + +Response: +```json +{ + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" +} +``` + +### MsigApprove +MsigApprove approves a previously-proposed multisig message +It takes the following params: , , , , , +, , + + +Perms: sign + +Inputs: +```json +[ + "t01234", + 42, + "t01234", + "t01234", + "0", + "t01234", + 42, + "Ynl0ZSBhcnJheQ==" +] +``` + +Response: +```json +{ + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" +} +``` + +### MsigCancel +MsigCancel cancels a previously-proposed multisig message +It takes the following params: , , , , +, , + + +Perms: sign + +Inputs: +```json +[ + "t01234", + 42, + "t01234", + "0", + "t01234", + 42, + "Ynl0ZSBhcnJheQ==" +] +``` + +Response: +```json +{ + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" +} +``` + +### MsigCreate +MsigCreate creates a multisig wallet +It takes the following params: , , +, , + + +Perms: sign + +Inputs: +```json +[ + 42, + null, + 10101, + "0", + "t01234", + "0" +] +``` + +Response: +```json +{ + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" +} +``` + +### MsigGetAvailableBalance +MsigGetAvailableBalance returns the portion of a multisig's balance that can be withdrawn or spent + + +Perms: read + +Inputs: +```json +[ + "t01234", + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: `"0"` + +### MsigGetVested +MsigGetVested returns the amount of FIL that vested in a multisig in a certain period. +It takes the following params: , , + + +Perms: read + +Inputs: +```json +[ + "t01234", + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ], + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: `"0"` + +### MsigPropose +MsigPropose proposes a multisig message +It takes the following params: , , , +, , + + +Perms: sign + +Inputs: +```json +[ + "t01234", + "t01234", + "0", + "t01234", + 42, + "Ynl0ZSBhcnJheQ==" +] +``` + +Response: +```json +{ + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" +} +``` + +### MsigSwapApprove +MsigSwapApprove approves a previously proposed SwapSigner +It takes the following params: , , , +, , + + +Perms: sign + +Inputs: +```json +[ + "t01234", + "t01234", + 42, + "t01234", + "t01234", + "t01234" +] +``` + +Response: +```json +{ + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" +} +``` + +### MsigSwapCancel +MsigSwapCancel cancels a previously proposed SwapSigner message +It takes the following params: , , , +, + + +Perms: sign + +Inputs: +```json +[ + "t01234", + "t01234", + 42, + "t01234", + "t01234" +] +``` + +Response: +```json +{ + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" +} +``` + +### MsigSwapPropose +MsigSwapPropose proposes swapping 2 signers in the multisig +It takes the following params: , , +, + + +Perms: sign + +Inputs: +```json +[ + "t01234", + "t01234", + "t01234", + "t01234" +] +``` + +Response: +```json +{ + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" +} +``` + +## Net + + +### NetAddrsListen + + +Perms: read + +Inputs: `null` + +Response: +```json +{ + "Addrs": null, + "ID": "12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf" +} +``` + +### NetAgentVersion + + +Perms: read + +Inputs: +```json +[ + "12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf" +] +``` + +Response: `"string value"` + +### NetAutoNatStatus + + +Perms: read + +Inputs: `null` + +Response: +```json +{ + "Reachability": 1, + "PublicAddr": "string value" +} +``` + +### NetBandwidthStats + + +Perms: read + +Inputs: `null` + +Response: +```json +{ + "TotalIn": 9, + "TotalOut": 9, + "RateIn": 12.3, + "RateOut": 12.3 +} +``` + +### NetBandwidthStatsByPeer + + +Perms: read + +Inputs: `null` + +Response: +```json +{ + "12D3KooWSXmXLJmBR1M7i9RW9GQPNUhZSzXKzxDHWtAgNuJAbyEJ": { + "TotalIn": 174000, + "TotalOut": 12500, + "RateIn": 100, + "RateOut": 50 + } +} +``` + +### NetBandwidthStatsByProtocol + + +Perms: read + +Inputs: `null` + +Response: +```json +{ + "/fil/hello/1.0.0": { + "TotalIn": 174000, + "TotalOut": 12500, + "RateIn": 100, + "RateOut": 50 + } +} +``` + +### NetConnect + + +Perms: write + +Inputs: +```json +[ + { + "Addrs": null, + "ID": "12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf" + } +] +``` + +Response: `{}` + +### NetConnectedness + + +Perms: read + +Inputs: +```json +[ + "12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf" +] +``` + +Response: `1` + +### NetDisconnect + + +Perms: write + +Inputs: +```json +[ + "12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf" +] +``` + +Response: `{}` + +### NetFindPeer + + +Perms: read + +Inputs: +```json +[ + "12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf" +] +``` + +Response: +```json +{ + "Addrs": null, + "ID": "12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf" +} +``` + +### NetPeers + + +Perms: read + +Inputs: `null` + +Response: `null` + +### NetPubsubScores + + +Perms: read + +Inputs: `null` + +Response: `null` + +## Paych +The Paych methods are for interacting with and managing payment channels + + +### PaychAllocateLane +There are not yet any comments for this method. + +Perms: sign + +Inputs: +```json +[ + "t01234" +] +``` + +Response: `42` + +### PaychAvailableFunds +There are not yet any comments for this method. + +Perms: sign + +Inputs: +```json +[ + "t01234" +] +``` + +Response: +```json +{ + "Channel": "\u003cempty\u003e", + "From": "t01234", + "To": "t01234", + "ConfirmedAmt": "0", + "PendingAmt": "0", + "PendingWaitSentinel": null, + "QueuedAmt": "0", + "VoucherReedeemedAmt": "0" +} +``` + +### PaychAvailableFundsByFromTo +There are not yet any comments for this method. + +Perms: sign + +Inputs: +```json +[ + "t01234", + "t01234" +] +``` + +Response: +```json +{ + "Channel": "\u003cempty\u003e", + "From": "t01234", + "To": "t01234", + "ConfirmedAmt": "0", + "PendingAmt": "0", + "PendingWaitSentinel": null, + "QueuedAmt": "0", + "VoucherReedeemedAmt": "0" +} +``` + +### PaychCollect +There are not yet any comments for this method. + +Perms: sign + +Inputs: +```json +[ + "t01234" +] +``` + +Response: +```json +{ + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" +} +``` + +### PaychGet +There are not yet any comments for this method. + +Perms: sign + +Inputs: +```json +[ + "t01234", + "t01234", + "0" +] +``` + +Response: +```json +{ + "Channel": "t01234", + "WaitSentinel": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + } +} +``` + +### PaychGetWaitReady +There are not yet any comments for this method. + +Perms: sign + +Inputs: +```json +[ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + } +] +``` + +Response: `"t01234"` + +### PaychList +There are not yet any comments for this method. + +Perms: read + +Inputs: `null` + +Response: `null` + +### PaychNewPayment +There are not yet any comments for this method. + +Perms: sign + +Inputs: +```json +[ + "t01234", + "t01234", + null +] +``` + +Response: +```json +{ + "Channel": "t01234", + "WaitSentinel": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "Vouchers": null +} +``` + +### PaychSettle +There are not yet any comments for this method. + +Perms: sign + +Inputs: +```json +[ + "t01234" +] +``` + +Response: +```json +{ + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" +} +``` + +### PaychStatus +There are not yet any comments for this method. + +Perms: read + +Inputs: +```json +[ + "t01234" +] +``` + +Response: +```json +{ + "ControlAddr": "t01234", + "Direction": 1 +} +``` + +### PaychVoucherAdd +There are not yet any comments for this method. + +Perms: write + +Inputs: +```json +[ + "t01234", + { + "ChannelAddr": "t01234", + "TimeLockMin": 10101, + "TimeLockMax": 10101, + "SecretPreimage": "Ynl0ZSBhcnJheQ==", + "Extra": { + "Actor": "t01234", + "Method": 1, + "Data": "Ynl0ZSBhcnJheQ==" + }, + "Lane": 42, + "Nonce": 42, + "Amount": "0", + "MinSettleHeight": 10101, + "Merges": null, + "Signature": { + "Type": 2, + "Data": "Ynl0ZSBhcnJheQ==" + } + }, + "Ynl0ZSBhcnJheQ==", + "0" +] +``` + +Response: `"0"` + +### PaychVoucherCheckSpendable +There are not yet any comments for this method. + +Perms: read + +Inputs: +```json +[ + "t01234", + { + "ChannelAddr": "t01234", + "TimeLockMin": 10101, + "TimeLockMax": 10101, + "SecretPreimage": "Ynl0ZSBhcnJheQ==", + "Extra": { + "Actor": "t01234", + "Method": 1, + "Data": "Ynl0ZSBhcnJheQ==" + }, + "Lane": 42, + "Nonce": 42, + "Amount": "0", + "MinSettleHeight": 10101, + "Merges": null, + "Signature": { + "Type": 2, + "Data": "Ynl0ZSBhcnJheQ==" + } + }, + "Ynl0ZSBhcnJheQ==", + "Ynl0ZSBhcnJheQ==" +] +``` + +Response: `true` + +### PaychVoucherCheckValid +There are not yet any comments for this method. + +Perms: read + +Inputs: +```json +[ + "t01234", + { + "ChannelAddr": "t01234", + "TimeLockMin": 10101, + "TimeLockMax": 10101, + "SecretPreimage": "Ynl0ZSBhcnJheQ==", + "Extra": { + "Actor": "t01234", + "Method": 1, + "Data": "Ynl0ZSBhcnJheQ==" + }, + "Lane": 42, + "Nonce": 42, + "Amount": "0", + "MinSettleHeight": 10101, + "Merges": null, + "Signature": { + "Type": 2, + "Data": "Ynl0ZSBhcnJheQ==" + } + } +] +``` + +Response: `{}` + +### PaychVoucherCreate +There are not yet any comments for this method. + +Perms: sign + +Inputs: +```json +[ + "t01234", + "0", + 42 +] +``` + +Response: +```json +{ + "Voucher": { + "ChannelAddr": "t01234", + "TimeLockMin": 10101, + "TimeLockMax": 10101, + "SecretPreimage": "Ynl0ZSBhcnJheQ==", + "Extra": { + "Actor": "t01234", + "Method": 1, + "Data": "Ynl0ZSBhcnJheQ==" + }, + "Lane": 42, + "Nonce": 42, + "Amount": "0", + "MinSettleHeight": 10101, + "Merges": null, + "Signature": { + "Type": 2, + "Data": "Ynl0ZSBhcnJheQ==" + } + }, + "Shortfall": "0" +} +``` + +### PaychVoucherList +There are not yet any comments for this method. + +Perms: write + +Inputs: +```json +[ + "t01234" +] +``` + +Response: `null` + +### PaychVoucherSubmit +There are not yet any comments for this method. + +Perms: sign + +Inputs: +```json +[ + "t01234", + { + "ChannelAddr": "t01234", + "TimeLockMin": 10101, + "TimeLockMax": 10101, + "SecretPreimage": "Ynl0ZSBhcnJheQ==", + "Extra": { + "Actor": "t01234", + "Method": 1, + "Data": "Ynl0ZSBhcnJheQ==" + }, + "Lane": 42, + "Nonce": 42, + "Amount": "0", + "MinSettleHeight": 10101, + "Merges": null, + "Signature": { + "Type": 2, + "Data": "Ynl0ZSBhcnJheQ==" + } + }, + "Ynl0ZSBhcnJheQ==", + "Ynl0ZSBhcnJheQ==" +] +``` + +Response: +```json +{ + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" +} +``` + +## State +The State methods are used to query, inspect, and interact with chain state. +All methods take a TipSetKey as a parameter. The state looked up is the state at that tipset. +A nil TipSetKey can be provided as a param, this will cause the heaviest tipset in the chain to be used. + + +### StateAccountKey +StateAccountKey returns the public key address of the given ID address + + +Perms: read + +Inputs: +```json +[ + "t01234", + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: `"t01234"` + +### StateAllMinerFaults +StateAllMinerFaults returns all non-expired Faults that occur within lookback epochs of the given tipset + + +Perms: read + +Inputs: +```json +[ + 10101, + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: `null` + +### StateCall +StateCall runs the given message and returns its result without any persisted changes. + + +Perms: read + +Inputs: +```json +[ + { + "Version": 42, + "To": "t01234", + "From": "t01234", + "Nonce": 42, + "Value": "0", + "GasLimit": 9, + "GasFeeCap": "0", + "GasPremium": "0", + "Method": 1, + "Params": "Ynl0ZSBhcnJheQ==" + }, + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: +```json +{ + "Msg": { + "Version": 42, + "To": "t01234", + "From": "t01234", + "Nonce": 42, + "Value": "0", + "GasLimit": 9, + "GasFeeCap": "0", + "GasPremium": "0", + "Method": 1, + "Params": "Ynl0ZSBhcnJheQ==" + }, + "MsgRct": { + "ExitCode": 0, + "Return": "Ynl0ZSBhcnJheQ==", + "GasUsed": 9 + }, + "ExecutionTrace": { + "Msg": { + "Version": 42, + "To": "t01234", + "From": "t01234", + "Nonce": 42, + "Value": "0", + "GasLimit": 9, + "GasFeeCap": "0", + "GasPremium": "0", + "Method": 1, + "Params": "Ynl0ZSBhcnJheQ==" + }, + "MsgRct": { + "ExitCode": 0, + "Return": "Ynl0ZSBhcnJheQ==", + "GasUsed": 9 + }, + "Error": "string value", + "Duration": 60000000000, + "GasCharges": null, + "Subcalls": null + }, + "Error": "string value", + "Duration": 60000000000 +} +``` + +### StateChangedActors +StateChangedActors returns all the actors whose states change between the two given state CIDs +TODO: Should this take tipset keys instead? + + +Perms: read + +Inputs: +```json +[ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + } +] +``` + +Response: +```json +{ + "t01236": { + "Code": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "Head": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "Nonce": 42, + "Balance": "0" + } +} +``` + +### StateCirculatingSupply +StateCirculatingSupply returns the circulating supply of Filecoin at the given tipset + + +Perms: read + +Inputs: +```json +[ + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: +```json +{ + "FilVested": "0", + "FilMined": "0", + "FilBurnt": "0", + "FilLocked": "0", + "FilCirculating": "0" +} +``` + +### StateCompute +StateCompute is a flexible command that applies the given messages on the given tipset. +The messages are run as though the VM were at the provided height. + + +Perms: read + +Inputs: +```json +[ + 10101, + null, + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: +```json +{ + "Root": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "Trace": null +} +``` + +### StateDealProviderCollateralBounds +StateDealProviderCollateralBounds returns the min and max collateral a storage provider +can issue. It takes the deal size and verified status as parameters. + + +Perms: read + +Inputs: +```json +[ + 1032, + true, + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: +```json +{ + "Min": "0", + "Max": "0" +} +``` + +### StateGetActor +StateGetActor returns the indicated actor's nonce and balance. + + +Perms: read + +Inputs: +```json +[ + "t01234", + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: +```json +{ + "Code": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "Head": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "Nonce": 42, + "Balance": "0" +} +``` + +### StateGetReceipt +StateGetReceipt returns the message receipt for the given message + + +Perms: read + +Inputs: +```json +[ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: +```json +{ + "ExitCode": 0, + "Return": "Ynl0ZSBhcnJheQ==", + "GasUsed": 9 +} +``` + +### StateListActors +StateListActors returns the addresses of every actor in the state + + +Perms: read + +Inputs: +```json +[ + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: `null` + +### StateListMessages +StateListMessages looks back and returns all messages with a matching to or from address, stopping at the given height. + + +Perms: read + +Inputs: +```json +[ + { + "Version": 42, + "To": "t01234", + "From": "t01234", + "Nonce": 42, + "Value": "0", + "GasLimit": 9, + "GasFeeCap": "0", + "GasPremium": "0", + "Method": 1, + "Params": "Ynl0ZSBhcnJheQ==" + }, + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ], + 10101 +] +``` + +Response: `null` + +### StateListMiners +StateListMiners returns the addresses of every miner that has claimed power in the Power Actor + + +Perms: read + +Inputs: +```json +[ + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: `null` + +### StateLookupID +StateLookupID retrieves the ID address of the given address + + +Perms: read + +Inputs: +```json +[ + "t01234", + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: `"t01234"` + +### StateMarketBalance +StateMarketBalance looks up the Escrow and Locked balances of the given address in the Storage Market + + +Perms: read + +Inputs: +```json +[ + "t01234", + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: +```json +{ + "Escrow": "0", + "Locked": "0" +} +``` + +### StateMarketDeals +StateMarketDeals returns information about every deal in the Storage Market + + +Perms: read + +Inputs: +```json +[ + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: +```json +{ + "t026363": { + "Proposal": { + "PieceCID": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "PieceSize": 1032, + "VerifiedDeal": true, + "Client": "t01234", + "Provider": "t01234", + "Label": "string value", + "StartEpoch": 10101, + "EndEpoch": 10101, + "StoragePricePerEpoch": "0", + "ProviderCollateral": "0", + "ClientCollateral": "0" + }, + "State": { + "SectorStartEpoch": 10101, + "LastUpdatedEpoch": 10101, + "SlashEpoch": 10101 + } + } +} +``` + +### StateMarketParticipants +StateMarketParticipants returns the Escrow and Locked balances of every participant in the Storage Market + + +Perms: read + +Inputs: +```json +[ + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: +```json +{ + "t026363": { + "Escrow": "0", + "Locked": "0" + } +} +``` + +### StateMarketStorageDeal +StateMarketStorageDeal returns information about the indicated deal + + +Perms: read + +Inputs: +```json +[ + 5432, + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: +```json +{ + "Proposal": { + "PieceCID": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "PieceSize": 1032, + "VerifiedDeal": true, + "Client": "t01234", + "Provider": "t01234", + "Label": "string value", + "StartEpoch": 10101, + "EndEpoch": 10101, + "StoragePricePerEpoch": "0", + "ProviderCollateral": "0", + "ClientCollateral": "0" + }, + "State": { + "SectorStartEpoch": 10101, + "LastUpdatedEpoch": 10101, + "SlashEpoch": 10101 + } +} +``` + +### StateMinerActiveSectors +StateMinerActiveSectors returns info about sectors that a given miner is actively proving. + + +Perms: read + +Inputs: +```json +[ + "t01234", + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: `null` + +### StateMinerAvailableBalance +StateMinerAvailableBalance returns the portion of a miner's balance that can be withdrawn or spent + + +Perms: read + +Inputs: +```json +[ + "t01234", + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: `"0"` + +### StateMinerDeadlines +StateMinerDeadlines returns all the proving deadlines for the given miner + + +Perms: read + +Inputs: +```json +[ + "t01234", + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: `null` + +### StateMinerFaults +StateMinerFaults returns a bitfield indicating the faulty sectors of the given miner + + +Perms: read + +Inputs: +```json +[ + "t01234", + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: +```json +[ + 5, + 1 +] +``` + +### StateMinerInfo +StateMinerInfo returns info about the indicated miner + + +Perms: read + +Inputs: +```json +[ + "t01234", + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: +```json +{ + "Owner": "t01234", + "Worker": "t01234", + "NewWorker": "t01234", + "ControlAddresses": null, + "WorkerChangeEpoch": 10101, + "PeerId": "12D3KooWGzxzKZYveHXtpG6AsrUJBcWxHBFS2HsEoGTxrMLvKXtf", + "Multiaddrs": null, + "SealProofType": 3, + "SectorSize": 34359738368, + "WindowPoStPartitionSectors": 42 +} +``` + +### StateMinerInitialPledgeCollateral +StateMinerInitialPledgeCollateral returns the initial pledge collateral for the specified miner's sector + + +Perms: read + +Inputs: +```json +[ + "t01234", + { + "SealProof": 3, + "SectorNumber": 9, + "SealedCID": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "SealRandEpoch": 10101, + "DealIDs": null, + "Expiration": 10101, + "ReplaceCapacity": true, + "ReplaceSectorDeadline": 42, + "ReplaceSectorPartition": 42, + "ReplaceSectorNumber": 9 + }, + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: `"0"` + +### StateMinerPartitions +StateMinerPartitions loads miner partitions for the specified miner/deadline + + +Perms: read + +Inputs: +```json +[ + "t01234", + 42, + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: `null` + +### StateMinerPower +StateMinerPower returns the power of the indicated miner + + +Perms: read + +Inputs: +```json +[ + "t01234", + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: +```json +{ + "MinerPower": { + "RawBytePower": "0", + "QualityAdjPower": "0" + }, + "TotalPower": { + "RawBytePower": "0", + "QualityAdjPower": "0" + } +} +``` + +### StateMinerPreCommitDepositForPower +StateMinerInitialPledgeCollateral returns the precommit deposit for the specified miner's sector + + +Perms: read + +Inputs: +```json +[ + "t01234", + { + "SealProof": 3, + "SectorNumber": 9, + "SealedCID": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "SealRandEpoch": 10101, + "DealIDs": null, + "Expiration": 10101, + "ReplaceCapacity": true, + "ReplaceSectorDeadline": 42, + "ReplaceSectorPartition": 42, + "ReplaceSectorNumber": 9 + }, + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: `"0"` + +### StateMinerProvingDeadline +StateMinerProvingDeadline calculates the deadline at some epoch for a proving period +and returns the deadline-related calculations. + + +Perms: read + +Inputs: +```json +[ + "t01234", + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: +```json +{ + "CurrentEpoch": 10101, + "PeriodStart": 10101, + "Index": 42, + "Open": 10101, + "Close": 10101, + "Challenge": 10101, + "FaultCutoff": 10101, + "WPoStPeriodDeadlines": 42, + "WPoStProvingPeriod": 10101, + "WPoStChallengeWindow": 10101, + "WPoStChallengeLookback": 10101, + "FaultDeclarationCutoff": 10101 +} +``` + +### StateMinerRecoveries +StateMinerRecoveries returns a bitfield indicating the recovering sectors of the given miner + + +Perms: read + +Inputs: +```json +[ + "t01234", + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: +```json +[ + 5, + 1 +] +``` + +### StateMinerSectorCount +StateMinerSectorCount returns the number of sectors in a miner's sector set and proving set + + +Perms: read + +Inputs: +```json +[ + "t01234", + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: +```json +{ + "Sectors": 42, + "Active": 42 +} +``` + +### StateMinerSectors +StateMinerSectors returns info about the given miner's sectors. If the filter bitfield is nil, all sectors are included. +If the filterOut boolean is set to true, any sectors in the filter are excluded. +If false, only those sectors in the filter are included. + + +Perms: read + +Inputs: +```json +[ + "t01234", + [ + 0 + ], + true, + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: `null` + +### StateMsgGasCost +StateMsgGasCost searches for a message in the chain, and returns details of the messages gas costs, including the penalty and miner tip + + +Perms: read + +Inputs: +```json +[ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: +```json +{ + "Message": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "GasUsed": "0", + "BaseFeeBurn": "0", + "OverEstimationBurn": "0", + "MinerPenalty": "0", + "MinerTip": "0", + "Refund": "0", + "TotalCost": "0" +} +``` + +### StateNetworkName +StateNetworkName returns the name of the network the node is synced to + + +Perms: read + +Inputs: `null` + +Response: `"lotus"` + +### StateReadState +StateReadState returns the indicated actor's state. + + +Perms: read + +Inputs: +```json +[ + "t01234", + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: +```json +{ + "Balance": "0", + "State": {} +} +``` + +### StateReplay +StateReplay returns the result of executing the indicated message, assuming it was executed in the indicated tipset. + + +Perms: read + +Inputs: +```json +[ + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ], + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + } +] +``` + +Response: +```json +{ + "Msg": { + "Version": 42, + "To": "t01234", + "From": "t01234", + "Nonce": 42, + "Value": "0", + "GasLimit": 9, + "GasFeeCap": "0", + "GasPremium": "0", + "Method": 1, + "Params": "Ynl0ZSBhcnJheQ==" + }, + "MsgRct": { + "ExitCode": 0, + "Return": "Ynl0ZSBhcnJheQ==", + "GasUsed": 9 + }, + "ExecutionTrace": { + "Msg": { + "Version": 42, + "To": "t01234", + "From": "t01234", + "Nonce": 42, + "Value": "0", + "GasLimit": 9, + "GasFeeCap": "0", + "GasPremium": "0", + "Method": 1, + "Params": "Ynl0ZSBhcnJheQ==" + }, + "MsgRct": { + "ExitCode": 0, + "Return": "Ynl0ZSBhcnJheQ==", + "GasUsed": 9 + }, + "Error": "string value", + "Duration": 60000000000, + "GasCharges": null, + "Subcalls": null + }, + "Error": "string value", + "Duration": 60000000000 +} +``` + +### StateSearchMsg +StateSearchMsg searches for a message in the chain, and returns its receipt and the tipset where it was executed + + +Perms: read + +Inputs: +```json +[ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + } +] +``` + +Response: +```json +{ + "Message": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "Receipt": { + "ExitCode": 0, + "Return": "Ynl0ZSBhcnJheQ==", + "GasUsed": 9 + }, + "ReturnDec": {}, + "TipSet": [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ], + "Height": 10101 +} +``` + +### StateSectorExpiration +StateSectorExpiration returns epoch at which given sector will expire + + +Perms: read + +Inputs: +```json +[ + "t01234", + 9, + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: +```json +{ + "OnTime": 10101, + "Early": 10101 +} +``` + +### StateSectorGetInfo +StateSectorGetInfo returns the on-chain info for the specified miner's sector. Returns null in case the sector info isn't found +NOTE: returned info.Expiration may not be accurate in some cases, use StateSectorExpiration to get accurate +expiration epoch + + +Perms: read + +Inputs: +```json +[ + "t01234", + 9, + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: +```json +{ + "SectorNumber": 9, + "SealProof": 3, + "SealedCID": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "DealIDs": null, + "Activation": 10101, + "Expiration": 10101, + "DealWeight": "0", + "VerifiedDealWeight": "0", + "InitialPledge": "0", + "ExpectedDayReward": "0", + "ExpectedStoragePledge": "0" +} +``` + +### StateSectorPartition +StateSectorPartition finds deadline/partition with the specified sector + + +Perms: read + +Inputs: +```json +[ + "t01234", + 9, + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: +```json +{ + "Deadline": 42, + "Partition": 42 +} +``` + +### StateSectorPreCommitInfo +StateSectorPreCommitInfo returns the PreCommit info for the specified miner's sector + + +Perms: read + +Inputs: +```json +[ + "t01234", + 9, + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: +```json +{ + "Info": { + "SealProof": 3, + "SectorNumber": 9, + "SealedCID": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "SealRandEpoch": 10101, + "DealIDs": null, + "Expiration": 10101, + "ReplaceCapacity": true, + "ReplaceSectorDeadline": 42, + "ReplaceSectorPartition": 42, + "ReplaceSectorNumber": 9 + }, + "PreCommitDeposit": "0", + "PreCommitEpoch": 10101, + "DealWeight": "0", + "VerifiedDealWeight": "0" +} +``` + +### StateVerifiedClientStatus +StateVerifiedClientStatus returns the data cap for the given address. +Returns nil if there is no entry in the data cap table for the +address. + + +Perms: read + +Inputs: +```json +[ + "t01234", + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: `"0"` + +### StateWaitMsg +StateWaitMsg looks back in the chain for a message. If not found, it blocks until the +message arrives on chain, and gets to the indicated confidence depth. + + +Perms: read + +Inputs: +```json +[ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + 42 +] +``` + +Response: +```json +{ + "Message": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "Receipt": { + "ExitCode": 0, + "Return": "Ynl0ZSBhcnJheQ==", + "GasUsed": 9 + }, + "ReturnDec": {}, + "TipSet": [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ], + "Height": 10101 +} +``` + +## Sync +The Sync method group contains methods for interacting with and +observing the lotus sync service. + + +### SyncCheckBad +SyncCheckBad checks if a block was marked as bad, and if it was, returns +the reason. + + +Perms: read + +Inputs: +```json +[ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + } +] +``` + +Response: `"string value"` + +### SyncCheckpoint +SyncCheckpoint marks a blocks as checkpointed, meaning that it won't ever fork away from it. + + +Perms: admin + +Inputs: +```json +[ + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: `{}` + +### SyncIncomingBlocks +SyncIncomingBlocks returns a channel streaming incoming, potentially not +yet synced block headers. + + +Perms: read + +Inputs: `null` + +Response: +```json +{ + "Miner": "t01234", + "Ticket": { + "VRFProof": "Ynl0ZSBhcnJheQ==" + }, + "ElectionProof": { + "WinCount": 9, + "VRFProof": "Ynl0ZSBhcnJheQ==" + }, + "BeaconEntries": null, + "WinPoStProof": null, + "Parents": null, + "ParentWeight": "0", + "Height": 10101, + "ParentStateRoot": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "ParentMessageReceipts": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "Messages": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "BLSAggregate": { + "Type": 2, + "Data": "Ynl0ZSBhcnJheQ==" + }, + "Timestamp": 42, + "BlockSig": { + "Type": 2, + "Data": "Ynl0ZSBhcnJheQ==" + }, + "ForkSignaling": 42, + "ParentBaseFee": "0" +} +``` + +### SyncMarkBad +SyncMarkBad marks a blocks as bad, meaning that it won't ever by synced. +Use with extreme caution. + + +Perms: admin + +Inputs: +```json +[ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + } +] +``` + +Response: `{}` + +### SyncState +SyncState returns the current status of the lotus sync system. + + +Perms: read + +Inputs: `null` + +Response: +```json +{ + "ActiveSyncs": null +} +``` + +### SyncSubmitBlock +SyncSubmitBlock can be used to submit a newly created block to the. +network through this node + + +Perms: write + +Inputs: +```json +[ + { + "Header": { + "Miner": "t01234", + "Ticket": { + "VRFProof": "Ynl0ZSBhcnJheQ==" + }, + "ElectionProof": { + "WinCount": 9, + "VRFProof": "Ynl0ZSBhcnJheQ==" + }, + "BeaconEntries": null, + "WinPoStProof": null, + "Parents": null, + "ParentWeight": "0", + "Height": 10101, + "ParentStateRoot": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "ParentMessageReceipts": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "Messages": { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + "BLSAggregate": { + "Type": 2, + "Data": "Ynl0ZSBhcnJheQ==" + }, + "Timestamp": 42, + "BlockSig": { + "Type": 2, + "Data": "Ynl0ZSBhcnJheQ==" + }, + "ForkSignaling": 42, + "ParentBaseFee": "0" + }, + "BlsMessages": null, + "SecpkMessages": null + } +] +``` + +Response: `{}` + +### SyncUnmarkBad +SyncUnmarkBad unmarks a blocks as bad, making it possible to be validated and synced again. + + +Perms: admin + +Inputs: +```json +[ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + } +] +``` + +Response: `{}` + +## Wallet + + +### WalletBalance +WalletBalance returns the balance of the given address at the current head of the chain. + + +Perms: read + +Inputs: +```json +[ + "t01234" +] +``` + +Response: `"0"` + +### WalletDefaultAddress +WalletDefaultAddress returns the address marked as default in the wallet. + + +Perms: write + +Inputs: `null` + +Response: `"t01234"` + +### WalletDelete +WalletDelete deletes an address from the wallet. + + +Perms: write + +Inputs: +```json +[ + "t01234" +] +``` + +Response: `{}` + +### WalletExport +WalletExport returns the private key of an address in the wallet. + + +Perms: admin + +Inputs: +```json +[ + "t01234" +] +``` + +Response: +```json +{ + "Type": "string value", + "PrivateKey": "Ynl0ZSBhcnJheQ==" +} +``` + +### WalletHas +WalletHas indicates whether the given address is in the wallet. + + +Perms: write + +Inputs: +```json +[ + "t01234" +] +``` + +Response: `true` + +### WalletImport +WalletImport receives a KeyInfo, which includes a private key, and imports it into the wallet. + + +Perms: admin + +Inputs: +```json +[ + { + "Type": "string value", + "PrivateKey": "Ynl0ZSBhcnJheQ==" + } +] +``` + +Response: `"t01234"` + +### WalletList +WalletList lists all the addresses in the wallet. + + +Perms: write + +Inputs: `null` + +Response: `null` + +### WalletNew +WalletNew creates a new address in the wallet with the given sigType. + + +Perms: write + +Inputs: +```json +[ + 2 +] +``` + +Response: `"t01234"` + +### WalletSetDefault +WalletSetDefault marks the given address as as the default one. + + +Perms: admin + +Inputs: +```json +[ + "t01234" +] +``` + +Response: `{}` + +### WalletSign +WalletSign signs the given bytes using the given address. + + +Perms: sign + +Inputs: +```json +[ + "t01234", + "Ynl0ZSBhcnJheQ==" +] +``` + +Response: +```json +{ + "Type": 2, + "Data": "Ynl0ZSBhcnJheQ==" +} +``` + +### WalletSignMessage +WalletSignMessage signs the given message using the given address. + + +Perms: sign + +Inputs: +```json +[ + "t01234", + { + "Version": 42, + "To": "t01234", + "From": "t01234", + "Nonce": 42, + "Value": "0", + "GasLimit": 9, + "GasFeeCap": "0", + "GasPremium": "0", + "Method": 1, + "Params": "Ynl0ZSBhcnJheQ==" + } +] +``` + +Response: +```json +{ + "Message": { + "Version": 42, + "To": "t01234", + "From": "t01234", + "Nonce": 42, + "Value": "0", + "GasLimit": 9, + "GasFeeCap": "0", + "GasPremium": "0", + "Method": 1, + "Params": "Ynl0ZSBhcnJheQ==" + }, + "Signature": { + "Type": 2, + "Data": "Ynl0ZSBhcnJheQ==" + } +} +``` + +### WalletVerify +WalletVerify takes an address, a signature, and some bytes, and indicates whether the signature is valid. +The address does not have to be in the wallet. + + +Perms: read + +Inputs: +```json +[ + "t01234", + "Ynl0ZSBhcnJheQ==", + { + "Type": 2, + "Data": "Ynl0ZSBhcnJheQ==" + } +] +``` + +Response: `true` + From dfd28ab0c44d7f032d6dff4e994b38491268ff0e Mon Sep 17 00:00:00 2001 From: Hector Sanjuan Date: Thu, 17 Sep 2020 20:56:43 +0200 Subject: [PATCH 079/303] Fix links in READMEs. --- README.md | 4 ++-- tools/dockers/docker-examples/README.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 6c1e23efa..fa432bf7d 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@

- + Project Lotus Logo

@@ -18,7 +18,7 @@ Lotus is an implementation of the Filecoin Distributed Storage Network. For more ## Building & Documentation -For instructions on how to build lotus from source, please visit [https://lotu.sh](https://lotu.sh) or read the source [here](https://github.com/filecoin-project/lotus/tree/master/documentation). +For instructions on how to build, install and setup lotus, please visit [https://docs.filecoin.io/get-started/lotus](https://docs.filecoin.io/get-started/lotus/). ## Reporting a Vulnerability diff --git a/tools/dockers/docker-examples/README.md b/tools/dockers/docker-examples/README.md index 28553653c..3b8c34480 100644 --- a/tools/dockers/docker-examples/README.md +++ b/tools/dockers/docker-examples/README.md @@ -11,7 +11,7 @@ In this `docker-examples/` directory are community-contributed Docker and Docker - local node for a developer (`api-local-`) - hosted endpoint for apps / multiple developers (`api-hosted-`) - **For a local devnet or shared devnet** - - basic local devnet (also see [lotus docs on setting up a local devnet](https://lotu.sh/en+setup-local-dev-net)) + - basic local devnet (also see [lotus docs on setting up a local devnet](https://docs.filecoin.io/build/local-devnet/)) - shared devnet From 18bc59b93befe07fa4fe9f76652616f743c71fa2 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Thu, 17 Sep 2020 13:52:16 -0700 Subject: [PATCH 080/303] uncruft --- api/types.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/api/types.go b/api/types.go index 53c0fe203..a69aa28d9 100644 --- a/api/types.go +++ b/api/types.go @@ -107,5 +107,3 @@ func NewDataTransferChannel(hostID peer.ID, channelState datatransfer.ChannelSta } return channel } - -// type TODO (stebalien): this was here, why was this here? From 708aa368e1d6867647c2424fc4b1290ce3226d81 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Thu, 17 Sep 2020 13:53:18 -0700 Subject: [PATCH 081/303] remove dep on v0 miner --- api/test/window_post.go | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/api/test/window_post.go b/api/test/window_post.go index e2bf5f36e..6b41ba6c6 100644 --- a/api/test/window_post.go +++ b/api/test/window_post.go @@ -9,8 +9,6 @@ import ( lotusminer "github.com/filecoin-project/lotus/chain/actors/builtin/miner" cbor "github.com/ipfs/go-ipld-cbor" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "os" "strings" "testing" @@ -165,7 +163,7 @@ func TestWindowPost(t *testing.T, b APIBuilder, blocktime time.Duration, nSector head, err := client.ChainHead(ctx) require.NoError(t, err) - if head.Height() > di.PeriodStart+(v0miner.WPoStProvingPeriod)+2 { + if head.Height() > di.PeriodStart+(di.WPoStProvingPeriod)+2 { break } From ae38970526b3ea65713333a74ae89f0697ef7e90 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Thu, 17 Sep 2020 14:53:57 -0700 Subject: [PATCH 082/303] remove WpostProvignPeriod function --- api/test/window_post.go | 17 ++--------------- chain/actors/builtin/miner/miner.go | 1 - chain/actors/builtin/miner/v0.go | 3 --- 3 files changed, 2 insertions(+), 19 deletions(-) diff --git a/api/test/window_post.go b/api/test/window_post.go index 6b41ba6c6..683489a91 100644 --- a/api/test/window_post.go +++ b/api/test/window_post.go @@ -4,11 +4,6 @@ import ( "context" "fmt" - "github.com/filecoin-project/lotus/api/apibstore" - "github.com/filecoin-project/lotus/chain/actors/adt" - lotusminer "github.com/filecoin-project/lotus/chain/actors/builtin/miner" - cbor "github.com/ipfs/go-ipld-cbor" - "os" "strings" "testing" @@ -182,14 +177,6 @@ func TestWindowPost(t *testing.T, b APIBuilder, blocktime time.Duration, nSector require.Equal(t, p.MinerPower, p.TotalPower) require.Equal(t, p.MinerPower.RawBytePower, types.NewInt(uint64(ssz)*uint64(nSectors+GenesisPreseals))) - store := cbor.NewCborStore(apibstore.NewAPIBlockstore(client)) - - mact, err := client.StateGetActor(ctx, maddr, types.EmptyTSK) - require.NoError(t, err) - - minState, err := lotusminer.Load(adt.WrapStore(ctx, store), mact) - require.NoError(t, err) - fmt.Printf("Drop some sectors\n") // Drop 2 sectors from deadline 2 partition 0 (full partition / deadline) @@ -254,7 +241,7 @@ func TestWindowPost(t *testing.T, b APIBuilder, blocktime time.Duration, nSector head, err := client.ChainHead(ctx) require.NoError(t, err) - if head.Height() > di.PeriodStart+(minState.WpostProvingPeriod())+2 { + if head.Height() > di.PeriodStart+(di.WPoStProvingPeriod)+2 { break } @@ -284,7 +271,7 @@ func TestWindowPost(t *testing.T, b APIBuilder, blocktime time.Duration, nSector head, err := client.ChainHead(ctx) require.NoError(t, err) - if head.Height() > di.PeriodStart+(minState.WpostProvingPeriod())+2 { + if head.Height() > di.PeriodStart+di.WPoStProvingPeriod+2 { break } diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index d754d0b74..cb34dd557 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -51,7 +51,6 @@ type State interface { Info() (MinerInfo, error) DeadlineInfo(epoch abi.ChainEpoch) *dline.Info - WpostProvingPeriod() abi.ChainEpoch } type Deadline interface { diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index b3fe594d1..74812e85a 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -243,9 +243,6 @@ func (s *v0State) Info() (MinerInfo, error) { func (s *v0State) DeadlineInfo(epoch abi.ChainEpoch) *dline.Info { return s.State.DeadlineInfo(epoch) } -func (s *v0State) WpostProvingPeriod() abi.ChainEpoch { - return v0miner.WPoStProvingPeriod -} func (d *v0Deadline) LoadPartition(idx uint64) (Partition, error) { p, err := d.Deadline.LoadPartition(d.store, idx) From dc58f71604b6dbf63c21da966a2d4e146b36abeb Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Thu, 17 Sep 2020 14:59:10 -0700 Subject: [PATCH 083/303] remove unnecessary code Go does have some nice features, once in a while. --- chain/actors/builtin/market/v0.go | 20 ++------------------ 1 file changed, 2 insertions(+), 18 deletions(-) diff --git a/chain/actors/builtin/market/v0.go b/chain/actors/builtin/market/v0.go index 92ebb59ba..d2e77fa92 100644 --- a/chain/actors/builtin/market/v0.go +++ b/chain/actors/builtin/market/v0.go @@ -184,11 +184,7 @@ func (d *v0MarketStatesDiffer) Remove(key uint64, val *typegen.Deferred) error { } func fromV0DealState(v0 market.DealState) DealState { - return DealState{ - SectorStartEpoch: v0.SectorStartEpoch, - SlashEpoch: v0.SlashEpoch, - LastUpdatedEpoch: v0.LastUpdatedEpoch, - } + return (DealState)(v0) } type v0DealProposals struct { @@ -234,19 +230,7 @@ type v0MarketProposalsDiffer struct { } func fromV0DealProposal(v0 market.DealProposal) DealProposal { - return DealProposal{ - PieceCID: v0.PieceCID, - PieceSize: v0.PieceSize, - VerifiedDeal: v0.VerifiedDeal, - Client: v0.Client, - Provider: v0.Provider, - Label: v0.Label, - StartEpoch: v0.StartEpoch, - EndEpoch: v0.EndEpoch, - StoragePricePerEpoch: v0.StoragePricePerEpoch, - ProviderCollateral: v0.ProviderCollateral, - ClientCollateral: v0.ClientCollateral, - } + return (DealProposal)(v0) } func (d *v0MarketProposalsDiffer) Add(key uint64, val *typegen.Deferred) error { From 5bcfee00425c28988db1ef95c5633788bde7dea1 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Thu, 17 Sep 2020 16:08:54 -0700 Subject: [PATCH 084/303] make market diffs work across version upgrades --- chain/actors/builtin/market/market.go | 7 ++ chain/actors/builtin/market/util.go | 91 ++++++++++++++++++++ chain/actors/builtin/market/v0.go | 114 ++++++-------------------- 3 files changed, 121 insertions(+), 91 deletions(-) create mode 100644 chain/actors/builtin/market/util.go diff --git a/chain/actors/builtin/market/market.go b/chain/actors/builtin/market/market.go index 73c2528d0..1c11c027e 100644 --- a/chain/actors/builtin/market/market.go +++ b/chain/actors/builtin/market/market.go @@ -8,6 +8,7 @@ import ( "github.com/filecoin-project/go-state-types/cbor" v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/types" @@ -51,12 +52,18 @@ type BalanceTable interface { type DealStates interface { Get(id abi.DealID) (*DealState, bool, error) Diff(DealStates) (*DealStateChanges, error) + + array() adt.Array + decode(*cbg.Deferred) (*DealState, error) } type DealProposals interface { ForEach(cb func(id abi.DealID, dp DealProposal) error) error Get(id abi.DealID) (*DealProposal, bool, error) Diff(DealProposals) (*DealProposalChanges, error) + + array() adt.Array + decode(*cbg.Deferred) (*DealProposal, error) } type DealState struct { diff --git a/chain/actors/builtin/market/util.go b/chain/actors/builtin/market/util.go new file mode 100644 index 000000000..92fdd6823 --- /dev/null +++ b/chain/actors/builtin/market/util.go @@ -0,0 +1,91 @@ +package market + +import ( + "fmt" + + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/lotus/chain/actors/adt" + cbg "github.com/whyrusleeping/cbor-gen" +) + +func diffDealProposals(pre, cur DealProposals) (*DealProposalChanges, error) { + results := new(DealProposalChanges) + if err := adt.DiffAdtArray(pre.array(), cur.array(), &marketProposalsDiffer{results, pre, cur}); err != nil { + return nil, fmt.Errorf("diffing deal states: %w", err) + } + return results, nil +} + +type marketProposalsDiffer struct { + Results *DealProposalChanges + pre, cur DealProposals +} + +func (d *marketProposalsDiffer) Add(key uint64, val *cbg.Deferred) error { + dp, err := d.cur.decode(val) + if err != nil { + return err + } + d.Results.Added = append(d.Results.Added, ProposalIDState{abi.DealID(key), *dp}) + return nil +} + +func (d *marketProposalsDiffer) Modify(key uint64, from, to *cbg.Deferred) error { + // short circuit, DealProposals are static + return nil +} + +func (d *marketProposalsDiffer) Remove(key uint64, val *cbg.Deferred) error { + dp, err := d.pre.decode(val) + if err != nil { + return err + } + d.Results.Removed = append(d.Results.Removed, ProposalIDState{abi.DealID(key), *dp}) + return nil +} + +func diffDealStates(pre, cur DealStates) (*DealStateChanges, error) { + results := new(DealStateChanges) + if err := adt.DiffAdtArray(pre.array(), cur.array(), &marketStatesDiffer{results, pre, cur}); err != nil { + return nil, fmt.Errorf("diffing deal states: %w", err) + } + return results, nil +} + +type marketStatesDiffer struct { + Results *DealStateChanges + pre, cur DealStates +} + +func (d *marketStatesDiffer) Add(key uint64, val *cbg.Deferred) error { + ds, err := d.cur.decode(val) + if err != nil { + return err + } + d.Results.Added = append(d.Results.Added, DealIDState{abi.DealID(key), *ds}) + return nil +} + +func (d *marketStatesDiffer) Modify(key uint64, from, to *cbg.Deferred) error { + dsFrom, err := d.pre.decode(from) + if err != nil { + return err + } + dsTo, err := d.cur.decode(to) + if err != nil { + return err + } + if *dsFrom != *dsTo { + d.Results.Modified = append(d.Results.Modified, DealStateChange{abi.DealID(key), dsFrom, dsTo}) + } + return nil +} + +func (d *marketStatesDiffer) Remove(key uint64, val *cbg.Deferred) error { + ds, err := d.pre.decode(val) + if err != nil { + return err + } + d.Results.Removed = append(d.Results.Removed, DealIDState{abi.DealID(key), *ds}) + return nil +} diff --git a/chain/actors/builtin/market/v0.go b/chain/actors/builtin/market/v0.go index d2e77fa92..587446749 100644 --- a/chain/actors/builtin/market/v0.go +++ b/chain/actors/builtin/market/v0.go @@ -2,8 +2,6 @@ package market import ( "bytes" - "errors" - "fmt" "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" @@ -11,7 +9,7 @@ import ( "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/specs-actors/actors/builtin/market" v0adt "github.com/filecoin-project/specs-actors/actors/util/adt" - typegen "github.com/whyrusleeping/cbor-gen" + cbg "github.com/whyrusleeping/cbor-gen" ) type v0State struct { @@ -127,60 +125,20 @@ func (s *v0DealStates) Get(dealID abi.DealID) (*DealState, bool, error) { } func (s *v0DealStates) Diff(other DealStates) (*DealStateChanges, error) { - v0other, ok := other.(*v0DealStates) - if !ok { - // TODO handle this if possible on a case by case basis but for now, just fail - return nil, errors.New("cannot compare deal states across versions") - } - results := new(DealStateChanges) - if err := adt.DiffAdtArray(s.Array, v0other.Array, &v0MarketStatesDiffer{results}); err != nil { - return nil, fmt.Errorf("diffing deal states: %w", err) - } - - return results, nil + return diffDealStates(s, other) } -type v0MarketStatesDiffer struct { - Results *DealStateChanges +func (s *v0DealStates) decode(val *cbg.Deferred) (*DealState, error) { + var v0ds market.DealState + if err := v0ds.UnmarshalCBOR(bytes.NewReader(val.Raw)); err != nil { + return nil, err + } + ds := fromV0DealState(v0ds) + return &ds, nil } -func (d *v0MarketStatesDiffer) Add(key uint64, val *typegen.Deferred) error { - v0ds := new(market.DealState) - err := v0ds.UnmarshalCBOR(bytes.NewReader(val.Raw)) - if err != nil { - return err - } - d.Results.Added = append(d.Results.Added, DealIDState{abi.DealID(key), fromV0DealState(*v0ds)}) - return nil -} - -func (d *v0MarketStatesDiffer) Modify(key uint64, from, to *typegen.Deferred) error { - v0dsFrom := new(market.DealState) - if err := v0dsFrom.UnmarshalCBOR(bytes.NewReader(from.Raw)); err != nil { - return err - } - - v0dsTo := new(market.DealState) - if err := v0dsTo.UnmarshalCBOR(bytes.NewReader(to.Raw)); err != nil { - return err - } - - if *v0dsFrom != *v0dsTo { - dsFrom := fromV0DealState(*v0dsFrom) - dsTo := fromV0DealState(*v0dsTo) - d.Results.Modified = append(d.Results.Modified, DealStateChange{abi.DealID(key), &dsFrom, &dsTo}) - } - return nil -} - -func (d *v0MarketStatesDiffer) Remove(key uint64, val *typegen.Deferred) error { - v0ds := new(market.DealState) - err := v0ds.UnmarshalCBOR(bytes.NewReader(val.Raw)) - if err != nil { - return err - } - d.Results.Removed = append(d.Results.Removed, DealIDState{abi.DealID(key), fromV0DealState(*v0ds)}) - return nil +func (s *v0DealStates) array() adt.Array { + return s.Array } func fromV0DealState(v0 market.DealState) DealState { @@ -192,17 +150,7 @@ type v0DealProposals struct { } func (s *v0DealProposals) Diff(other DealProposals) (*DealProposalChanges, error) { - v0other, ok := other.(*v0DealProposals) - if !ok { - // TODO handle this if possible on a case by case basis but for now, just fail - return nil, errors.New("cannot compare deal proposals across versions") - } - results := new(DealProposalChanges) - if err := adt.DiffAdtArray(s.Array, v0other.Array, &v0MarketProposalsDiffer{results}); err != nil { - return nil, fmt.Errorf("diffing deal proposals: %w", err) - } - - return results, nil + return diffDealProposals(s, other) } func (s *v0DealProposals) Get(dealID abi.DealID) (*DealProposal, bool, error) { @@ -225,35 +173,19 @@ func (s *v0DealProposals) ForEach(cb func(dealID abi.DealID, dp DealProposal) er }) } -type v0MarketProposalsDiffer struct { - Results *DealProposalChanges +func (s *v0DealProposals) decode(val *cbg.Deferred) (*DealProposal, error) { + var v0dp market.DealProposal + if err := v0dp.UnmarshalCBOR(bytes.NewReader(val.Raw)); err != nil { + return nil, err + } + dp := fromV0DealProposal(v0dp) + return &dp, nil +} + +func (s *v0DealProposals) array() adt.Array { + return s.Array } func fromV0DealProposal(v0 market.DealProposal) DealProposal { return (DealProposal)(v0) } - -func (d *v0MarketProposalsDiffer) Add(key uint64, val *typegen.Deferred) error { - v0dp := new(market.DealProposal) - err := v0dp.UnmarshalCBOR(bytes.NewReader(val.Raw)) - if err != nil { - return err - } - d.Results.Added = append(d.Results.Added, ProposalIDState{abi.DealID(key), fromV0DealProposal(*v0dp)}) - return nil -} - -func (d *v0MarketProposalsDiffer) Modify(key uint64, from, to *typegen.Deferred) error { - // short circuit, DealProposals are static - return nil -} - -func (d *v0MarketProposalsDiffer) Remove(key uint64, val *typegen.Deferred) error { - v0dp := new(market.DealProposal) - err := v0dp.UnmarshalCBOR(bytes.NewReader(val.Raw)) - if err != nil { - return err - } - d.Results.Removed = append(d.Results.Removed, ProposalIDState{abi.DealID(key), fromV0DealProposal(*v0dp)}) - return nil -} From db2a20da6cb8343a2a8c7a45f3d6e91b48928c01 Mon Sep 17 00:00:00 2001 From: Travis Person Date: Thu, 17 Sep 2020 23:09:12 +0000 Subject: [PATCH 085/303] lotus-shed: add keyinfo verify --- cmd/lotus-shed/keyinfo.go | 90 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) diff --git a/cmd/lotus-shed/keyinfo.go b/cmd/lotus-shed/keyinfo.go index f397bd4c7..6090b7a0f 100644 --- a/cmd/lotus-shed/keyinfo.go +++ b/cmd/lotus-shed/keyinfo.go @@ -9,16 +9,22 @@ import ( "io" "io/ioutil" "os" + "path" "strings" "text/template" "github.com/urfave/cli/v2" + "golang.org/x/xerrors" + + "github.com/multiformats/go-base32" + "github.com/libp2p/go-libp2p-core/crypto" "github.com/libp2p/go-libp2p-core/peer" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/wallet" + "github.com/filecoin-project/lotus/node/modules" "github.com/filecoin-project/lotus/node/modules/lp2p" "github.com/filecoin-project/lotus/node/repo" @@ -43,6 +49,90 @@ var keyinfoCmd = &cli.Command{ keyinfoNewCmd, keyinfoInfoCmd, keyinfoImportCmd, + keyinfoVerifyCmd, + }, +} + +var keyinfoVerifyCmd = &cli.Command{ + Name: "verify", + Usage: "verify the filename of a keystore object on disk with it's contents", + Description: `Keystore objects are base32 enocded strings, with wallets being dynamically named via + the wallet address. This command can ensure that the naming of these keystore objects are correct`, + Action: func(cctx *cli.Context) error { + filePath := cctx.Args().First() + fileName := path.Base(filePath) + + inputFile, err := os.Open(filePath) + if err != nil { + return err + } + defer inputFile.Close() //nolint:errcheck + input := bufio.NewReader(inputFile) + + keyContent, err := ioutil.ReadAll(input) + if err != nil { + return err + } + + var keyInfo types.KeyInfo + if err := json.Unmarshal(keyContent, &keyInfo); err != nil { + return err + } + + switch keyInfo.Type { + case lp2p.KTLibp2pHost: + name, err := base32.RawStdEncoding.DecodeString(fileName) + if err != nil { + return xerrors.Errorf("decoding key: '%s': %w", fileName, err) + } + + if string(name) != keyInfo.Type { + return fmt.Errorf("%s of type %s is incorrect", fileName, keyInfo.Type) + } + case modules.KTJwtHmacSecret: + name, err := base32.RawStdEncoding.DecodeString(fileName) + if err != nil { + return xerrors.Errorf("decoding key: '%s': %w", fileName, err) + } + + if string(name) != modules.JWTSecretName { + return fmt.Errorf("%s of type %s is incorrect", fileName, keyInfo.Type) + } + case wallet.KTSecp256k1, wallet.KTBLS: + keystore := wallet.NewMemKeyStore() + w, err := wallet.NewWallet(keystore) + if err != nil { + return err + } + + if _, err := w.Import(&keyInfo); err != nil { + return err + } + + list, err := keystore.List() + if err != nil { + return err + } + + if len(list) != 1 { + return fmt.Errorf("Unexpected number of keys, expected 1, found %d", len(list)) + } + + name, err := base32.RawStdEncoding.DecodeString(fileName) + if err != nil { + return xerrors.Errorf("decoding key: '%s': %w", fileName, err) + } + + if string(name) != list[0] { + return fmt.Errorf("%s of type %s; file is named for %s, but key is actually %s", fileName, keyInfo.Type, string(name), list[0]) + } + + break + default: + return fmt.Errorf("Unknown keytype %s", keyInfo.Type) + } + + return nil }, } From ac7007d1d010d31a970b5f4706045976e43ab796 Mon Sep 17 00:00:00 2001 From: Travis Person Date: Fri, 18 Sep 2020 00:40:46 +0000 Subject: [PATCH 086/303] lotus-shed: add jwt token command --- cmd/lotus-shed/jwt.go | 99 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) diff --git a/cmd/lotus-shed/jwt.go b/cmd/lotus-shed/jwt.go index d37359f71..7fa1a18dd 100644 --- a/cmd/lotus-shed/jwt.go +++ b/cmd/lotus-shed/jwt.go @@ -1,6 +1,7 @@ package main import ( + "bufio" "crypto/rand" "encoding/hex" "encoding/json" @@ -8,10 +9,12 @@ import ( "io" "io/ioutil" "os" + "strings" "github.com/gbrlsnchs/jwt/v3" "github.com/urfave/cli/v2" + "github.com/filecoin-project/go-jsonrpc/auth" "github.com/filecoin-project/lotus/api/apistruct" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/node/modules" @@ -24,6 +27,102 @@ var jwtCmd = &cli.Command{ having to run the lotus daemon.`, Subcommands: []*cli.Command{ jwtNewCmd, + jwtTokenCmd, + }, +} + +var jwtTokenCmd = &cli.Command{ + Name: "token", + Usage: "create a token for a given jwt secret", + ArgsUsage: "", + Description: `The jwt tokens have four different levels of permissions that provide some ability + to control access to what methods can be invoked by the holder of the token. + + This command only works on jwt secrets that are base16 encoded files, such as those produced by the + sibling 'new' command. + `, + Flags: []cli.Flag{ + &cli.StringFlag{ + Name: "output", + Value: "token", + Usage: "specify a name", + }, + &cli.BoolFlag{ + Name: "read", + Value: false, + Usage: "add read permissions to the token", + }, + &cli.BoolFlag{ + Name: "write", + Value: false, + Usage: "add write permissions to the token", + }, + &cli.BoolFlag{ + Name: "sign", + Value: false, + Usage: "add sign permissions to the token", + }, + &cli.BoolFlag{ + Name: "admin", + Value: false, + Usage: "add admin permissions to the token", + }, + }, + Action: func(cctx *cli.Context) error { + if !cctx.Args().Present() { + return fmt.Errorf("please specify a name") + } + + inputFile, err := os.Open(cctx.Args().First()) + if err != nil { + return err + } + defer inputFile.Close() //nolint:errcheck + input := bufio.NewReader(inputFile) + + encoded, err := ioutil.ReadAll(input) + if err != nil { + return err + } + + decoded, err := hex.DecodeString(strings.TrimSpace(string(encoded))) + if err != nil { + return err + } + + var keyInfo types.KeyInfo + if err := json.Unmarshal(decoded, &keyInfo); err != nil { + return err + } + + perms := []auth.Permission{} + + if cctx.Bool("read") { + perms = append(perms, apistruct.PermRead) + } + + if cctx.Bool("write") { + perms = append(perms, apistruct.PermWrite) + } + + if cctx.Bool("sign") { + perms = append(perms, apistruct.PermSign) + } + + if cctx.Bool("admin") { + perms = append(perms, apistruct.PermAdmin) + } + + p := modules.JwtPayload{ + Allow: perms, + } + + token, err := jwt.Sign(&p, jwt.NewHS256(keyInfo.PrivateKey)) + if err != nil { + return err + } + + return ioutil.WriteFile(cctx.String("output"), token, 0600) }, } From b2ee59024f935721f6f277f8ae381afb05a70d91 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Thu, 17 Sep 2020 21:39:34 -0700 Subject: [PATCH 087/303] improve diff logic * Make diffing work across versions. * Start porting more chainwatch logic. --- chain/actors/builtin/miner/diff.go | 127 ++++++++++ chain/actors/builtin/miner/miner.go | 28 +- chain/actors/builtin/miner/v0.go | 41 +++ chain/events/state/predicates.go | 128 +--------- chain/events/state/predicates_test.go | 4 +- cmd/lotus-chainwatch/processor/miner.go | 323 ++++++++++++------------ 6 files changed, 364 insertions(+), 287 deletions(-) create mode 100644 chain/actors/builtin/miner/diff.go diff --git a/chain/actors/builtin/miner/diff.go b/chain/actors/builtin/miner/diff.go new file mode 100644 index 000000000..dde4db890 --- /dev/null +++ b/chain/actors/builtin/miner/diff.go @@ -0,0 +1,127 @@ +package miner + +import ( + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/lotus/chain/actors/adt" + cbg "github.com/whyrusleeping/cbor-gen" +) + +func DiffPreCommits(pre, cur State) (*PreCommitChanges, error) { + results := new(PreCommitChanges) + + prep, err := pre.precommits() + if err != nil { + return nil, err + } + + curp, err := cur.precommits() + if err != nil { + return nil, err + } + + err = adt.DiffAdtMap(prep, curp, &preCommitDiffer{results, pre, cur}) + if err != nil { + return nil, err + } + + return results, nil +} + +type preCommitDiffer struct { + Results *PreCommitChanges + pre, after State +} + +func (m *preCommitDiffer) AsKey(key string) (abi.Keyer, error) { + sector, err := abi.ParseUIntKey(key) + if err != nil { + return nil, err + } + return abi.UIntKey(sector), nil +} + +func (m *preCommitDiffer) Add(key string, val *cbg.Deferred) error { + sp, err := m.after.decodeSectorPreCommitOnChainInfo(val) + if err != nil { + return err + } + m.Results.Added = append(m.Results.Added, sp) + return nil +} + +func (m *preCommitDiffer) Modify(key string, from, to *cbg.Deferred) error { + return nil +} + +func (m *preCommitDiffer) Remove(key string, val *cbg.Deferred) error { + sp, err := m.pre.decodeSectorPreCommitOnChainInfo(val) + if err != nil { + return err + } + m.Results.Removed = append(m.Results.Removed, sp) + return nil +} + +func DiffSectors(pre, cur State) (*SectorChanges, error) { + results := new(SectorChanges) + + pres, err := pre.sectors() + if err != nil { + return nil, err + } + + curs, err := cur.sectors() + if err != nil { + return nil, err + } + + err = adt.DiffAdtArray(pres, curs, §orDiffer{results, pre, cur}) + if err != nil { + return nil, err + } + + return results, nil +} + +type sectorDiffer struct { + Results *SectorChanges + pre, after State +} + +func (m *sectorDiffer) Add(key uint64, val *cbg.Deferred) error { + si, err := m.after.decodeSectorOnChainInfo(val) + if err != nil { + return err + } + m.Results.Added = append(m.Results.Added, si) + return nil +} + +func (m *sectorDiffer) Modify(key uint64, from, to *cbg.Deferred) error { + siFrom, err := m.pre.decodeSectorOnChainInfo(from) + if err != nil { + return err + } + + siTo, err := m.after.decodeSectorOnChainInfo(to) + if err != nil { + return err + } + + if siFrom.Expiration != siTo.Expiration { + m.Results.Extended = append(m.Results.Extended, SectorExtensions{ + From: siFrom, + To: siTo, + }) + } + return nil +} + +func (m *sectorDiffer) Remove(key uint64, val *cbg.Deferred) error { + si, err := m.pre.decodeSectorOnChainInfo(val) + if err != nil { + return err + } + m.Results.Removed = append(m.Results.Removed, si) + return nil +} diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index cb34dd557..793c4badc 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -3,6 +3,7 @@ package miner import ( "github.com/filecoin-project/go-state-types/dline" "github.com/libp2p/go-libp2p-core/peer" + cbg "github.com/whyrusleeping/cbor-gen" "golang.org/x/xerrors" "github.com/filecoin-project/go-address" @@ -42,21 +43,30 @@ type State interface { GetSectorExpiration(abi.SectorNumber) (*SectorExpiration, error) GetPrecommittedSector(abi.SectorNumber) (*SectorPreCommitOnChainInfo, error) LoadSectorsFromSet(filter *bitfield.BitField, filterOut bool) (adt.Array, error) - LoadPreCommittedSectors() (adt.Map, error) IsAllocated(abi.SectorNumber) (bool, error) LoadDeadline(idx uint64) (Deadline, error) ForEachDeadline(cb func(idx uint64, dl Deadline) error) error NumDeadlines() (uint64, error) + DeadlinesChanged(State) bool + Info() (MinerInfo, error) DeadlineInfo(epoch abi.ChainEpoch) *dline.Info + + // Diff helpers. Used by Diff* functions internally. + sectors() (adt.Array, error) + decodeSectorOnChainInfo(*cbg.Deferred) (SectorOnChainInfo, error) + precommits() (adt.Map, error) + decodeSectorPreCommitOnChainInfo(*cbg.Deferred) (SectorPreCommitOnChainInfo, error) } type Deadline interface { LoadPartition(idx uint64) (Partition, error) ForEachPartition(cb func(idx uint64, part Partition) error) error PostSubmissions() (bitfield.BitField, error) + + PartitionsChanged(Deadline) bool } type Partition interface { @@ -110,3 +120,19 @@ type SectorLocation struct { Deadline uint64 Partition uint64 } + +type SectorChanges struct { + Added []SectorOnChainInfo + Extended []SectorExtensions + Removed []SectorOnChainInfo +} + +type SectorExtensions struct { + From SectorOnChainInfo + To SectorOnChainInfo +} + +type PreCommitChanges struct { + Added []SectorPreCommitOnChainInfo + Removed []SectorPreCommitOnChainInfo +} diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index 74812e85a..9f4cea6ce 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -1,6 +1,7 @@ package miner import ( + "bytes" "errors" "github.com/filecoin-project/go-address" @@ -206,6 +207,16 @@ func (s *v0State) NumDeadlines() (uint64, error) { return v0miner.WPoStPeriodDeadlines, nil } +func (s *v0State) DeadlinesChanged(other State) bool { + v0other, ok := other.(*v0State) + if !ok { + // treat an upgrade as a change, always + return true + } + + return s.State.Deadlines.Equals(v0other.Deadlines) +} + func (s *v0State) Info() (MinerInfo, error) { info, err := s.State.GetInfo(s.store) if err != nil { @@ -244,6 +255,26 @@ func (s *v0State) DeadlineInfo(epoch abi.ChainEpoch) *dline.Info { return s.State.DeadlineInfo(epoch) } +func (s *v0State) sectors() (adt.Array, error) { + return v0adt.AsArray(s.store, s.Sectors) +} + +func (s *v0State) decodeSectorOnChainInfo(val *cbg.Deferred) (SectorOnChainInfo, error) { + var si v0miner.SectorOnChainInfo + err := si.UnmarshalCBOR(bytes.NewReader(val.Raw)) + return si, err +} + +func (s *v0State) precommits() (adt.Map, error) { + return v0adt.AsMap(s.store, s.PreCommittedSectors) +} + +func (s *v0State) decodeSectorPreCommitOnChainInfo(val *cbg.Deferred) (SectorPreCommitOnChainInfo, error) { + var sp v0miner.SectorPreCommitOnChainInfo + err := sp.UnmarshalCBOR(bytes.NewReader(val.Raw)) + return sp, err +} + func (d *v0Deadline) LoadPartition(idx uint64) (Partition, error) { p, err := d.Deadline.LoadPartition(d.store, idx) if err != nil { @@ -263,6 +294,16 @@ func (d *v0Deadline) ForEachPartition(cb func(uint64, Partition) error) error { }) } +func (s *v0Deadline) PartitionsChanged(other Deadline) bool { + v0other, ok := other.(*v0Deadline) + if !ok { + // treat an upgrade as a change, always + return true + } + + return s.Deadline.Partitions.Equals(v0other.Deadline.Partitions) +} + func (d *v0Deadline) PostSubmissions() (bitfield.BitField, error) { return d.Deadline.PostSubmissions, nil } diff --git a/chain/events/state/predicates.go b/chain/events/state/predicates.go index f27b5dc8f..721de9dd2 100644 --- a/chain/events/state/predicates.go +++ b/chain/events/state/predicates.go @@ -4,8 +4,6 @@ import ( "bytes" "context" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/go-address" @@ -325,83 +323,12 @@ func (sp *StatePredicates) OnMinerActorChange(minerAddr address.Address, diffMin }) } -type MinerSectorChanges struct { - Added []miner.SectorOnChainInfo - Extended []SectorExtensions - Removed []miner.SectorOnChainInfo -} - -var _ adt.AdtArrayDiff = &MinerSectorChanges{} - -type SectorExtensions struct { - From miner.SectorOnChainInfo - To miner.SectorOnChainInfo -} - -func (m *MinerSectorChanges) Add(key uint64, val *typegen.Deferred) error { - si := new(miner.SectorOnChainInfo) - err := si.UnmarshalCBOR(bytes.NewReader(val.Raw)) - if err != nil { - return err - } - m.Added = append(m.Added, *si) - return nil -} - -func (m *MinerSectorChanges) Modify(key uint64, from, to *typegen.Deferred) error { - siFrom := new(miner.SectorOnChainInfo) - err := siFrom.UnmarshalCBOR(bytes.NewReader(from.Raw)) - if err != nil { - return err - } - - siTo := new(miner.SectorOnChainInfo) - err = siTo.UnmarshalCBOR(bytes.NewReader(to.Raw)) - if err != nil { - return err - } - - if siFrom.Expiration != siTo.Expiration { - m.Extended = append(m.Extended, SectorExtensions{ - From: *siFrom, - To: *siTo, - }) - } - return nil -} - -func (m *MinerSectorChanges) Remove(key uint64, val *typegen.Deferred) error { - si := new(miner.SectorOnChainInfo) - err := si.UnmarshalCBOR(bytes.NewReader(val.Raw)) - if err != nil { - return err - } - m.Removed = append(m.Removed, *si) - return nil -} - func (sp *StatePredicates) OnMinerSectorChange() DiffMinerActorStateFunc { return func(ctx context.Context, oldState, newState miner.State) (changed bool, user UserData, err error) { - sectorChanges := &MinerSectorChanges{ - Added: []miner.SectorOnChainInfo{}, - Extended: []SectorExtensions{}, - Removed: []miner.SectorOnChainInfo{}, - } - - oldSectors, err := oldState.LoadSectorsFromSet(nil, false) + sectorChanges, err := miner.DiffSectors(oldState, newState) if err != nil { return false, nil, err } - - newSectors, err := newState.LoadSectorsFromSet(nil, false) - if err != nil { - return false, nil, err - } - - if err := adt.DiffAdtArray(oldSectors, newSectors, sectorChanges); err != nil { - return false, nil, err - } - // nothing changed if len(sectorChanges.Added)+len(sectorChanges.Extended)+len(sectorChanges.Removed) == 0 { return false, nil, nil @@ -411,64 +338,13 @@ func (sp *StatePredicates) OnMinerSectorChange() DiffMinerActorStateFunc { } } -type MinerPreCommitChanges struct { - Added []miner.SectorPreCommitOnChainInfo - Removed []miner.SectorPreCommitOnChainInfo -} - -func (m *MinerPreCommitChanges) AsKey(key string) (abi.Keyer, error) { - sector, err := abi.ParseUIntKey(key) - if err != nil { - return nil, err - } - return v0miner.SectorKey(abi.SectorNumber(sector)), nil -} - -func (m *MinerPreCommitChanges) Add(key string, val *typegen.Deferred) error { - sp := new(miner.SectorPreCommitOnChainInfo) - err := sp.UnmarshalCBOR(bytes.NewReader(val.Raw)) - if err != nil { - return err - } - m.Added = append(m.Added, *sp) - return nil -} - -func (m *MinerPreCommitChanges) Modify(key string, from, to *typegen.Deferred) error { - return nil -} - -func (m *MinerPreCommitChanges) Remove(key string, val *typegen.Deferred) error { - sp := new(miner.SectorPreCommitOnChainInfo) - err := sp.UnmarshalCBOR(bytes.NewReader(val.Raw)) - if err != nil { - return err - } - m.Removed = append(m.Removed, *sp) - return nil -} - func (sp *StatePredicates) OnMinerPreCommitChange() DiffMinerActorStateFunc { return func(ctx context.Context, oldState, newState miner.State) (changed bool, user UserData, err error) { - precommitChanges := &MinerPreCommitChanges{ - Added: []miner.SectorPreCommitOnChainInfo{}, - Removed: []miner.SectorPreCommitOnChainInfo{}, - } - - oldPrecommits, err := oldState.LoadPreCommittedSectors() + precommitChanges, err := miner.DiffPreCommits(oldState, newState) if err != nil { return false, nil, err } - newPrecommits, err := newState.LoadPreCommittedSectors() - if err != nil { - return false, nil, err - } - - if err := adt.DiffAdtMap(oldPrecommits, newPrecommits, precommitChanges); err != nil { - return false, nil, err - } - if len(precommitChanges.Added)+len(precommitChanges.Removed) == 0 { return false, nil, nil } diff --git a/chain/events/state/predicates_test.go b/chain/events/state/predicates_test.go index 6541aa3b4..243d8814e 100644 --- a/chain/events/state/predicates_test.go +++ b/chain/events/state/predicates_test.go @@ -409,7 +409,7 @@ func TestMinerSectorChange(t *testing.T) { require.True(t, change) require.NotNil(t, val) - sectorChanges, ok := val.(*MinerSectorChanges) + sectorChanges, ok := val.(*miner.SectorChanges) require.True(t, ok) require.Equal(t, len(sectorChanges.Added), 1) @@ -433,7 +433,7 @@ func TestMinerSectorChange(t *testing.T) { require.True(t, change) require.NotNil(t, val) - sectorChanges, ok = val.(*MinerSectorChanges) + sectorChanges, ok = val.(*miner.SectorChanges) require.True(t, ok) require.Equal(t, 1, len(sectorChanges.Added)) diff --git a/cmd/lotus-chainwatch/processor/miner.go b/cmd/lotus-chainwatch/processor/miner.go index 71d881927..1fd2a119f 100644 --- a/cmd/lotus-chainwatch/processor/miner.go +++ b/cmd/lotus-chainwatch/processor/miner.go @@ -16,12 +16,14 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/filecoin-project/lotus/api" + "github.com/filecoin-project/lotus/api/apibstore" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/events/state" + "github.com/filecoin-project/lotus/chain/store" "github.com/filecoin-project/lotus/chain/types" cw_util "github.com/filecoin-project/lotus/cmd/lotus-chainwatch/util" ) @@ -204,6 +206,8 @@ func (p *Processor) processMiners(ctx context.Context, minerTips map[types.TipSe log.Debugw("Processed Miners", "duration", time.Since(start).String()) }() + stor := store.ActorStore(ctx, apibstore.NewAPIBlockstore(p.node)) + var out []minerActorInfo // TODO add parallel calls if this becomes slow for tipset, miners := range minerTips { @@ -230,15 +234,13 @@ func (p *Processor) processMiners(ctx context.Context, minerTips map[types.TipSe mi.rawPower = claim.RawBytePower } - // Get the miner state info - astb, err := p.node.ChainReadObj(ctx, act.act.Head) + // Get the miner state + mas, err := miner.Load(stor, &act.act) if err != nil { log.Warnw("failed to find miner actor state", "address", act.addr, "error", err) continue } - if err := mi.state.UnmarshalCBOR(bytes.NewReader(astb)); err != nil { - return nil, err - } + mi.state = mas out = append(out, mi) } } @@ -322,11 +324,6 @@ func (p *Processor) storeMinerPreCommitInfo(ctx context.Context, miners []minerA for _, m := range miners { m := m grp.Go(func() error { - minerSectors, err := adt.AsArray(p.ctxStore, m.state.Sectors) - if err != nil { - return err - } - changes, err := p.getMinerPreCommitChanges(ctx, m) if err != nil { if strings.Contains(err.Error(), types.ErrActorNotFound.Error()) { @@ -399,10 +396,12 @@ func (p *Processor) storeMinerPreCommitInfo(ctx context.Context, miners []minerA } var preCommitExpired []uint64 for _, removed := range changes.Removed { - var sector miner.SectorOnChainInfo - if found, err := minerSectors.Get(uint64(removed.Info.SectorNumber), §or); err != nil { + // TODO: we can optimize this to not load the AMT every time, if necessary. + si, err := m.state.GetSector(removed.Info.SectorNumber) + if err != nil { return err - } else if !found { + } + if si == nil { preCommitExpired = append(preCommitExpired, uint64(removed.Info.SectorNumber)) } } @@ -653,21 +652,12 @@ func (p *Processor) storeMinerSectorEvents(ctx context.Context, sectorEvents, pr func (p *Processor) getMinerStateAt(ctx context.Context, maddr address.Address, tskey types.TipSetKey) (miner.State, error) { prevActor, err := p.node.StateGetActor(ctx, maddr, tskey) if err != nil { - return miner.State{}, err + return nil, err } - var out miner.State - // Get the miner state info - astb, err := p.node.ChainReadObj(ctx, prevActor.Head) - if err != nil { - return miner.State{}, err - } - if err := out.UnmarshalCBOR(bytes.NewReader(astb)); err != nil { - return miner.State{}, err - } - return out, nil + return miner.Load(store.ActorStore(ctx, apibstore.NewAPIBlockstore(p.node)), prevActor) } -func (p *Processor) getMinerPreCommitChanges(ctx context.Context, m minerActorInfo) (*state.MinerPreCommitChanges, error) { +func (p *Processor) getMinerPreCommitChanges(ctx context.Context, m minerActorInfo) (*miner.PreCommitChanges, error) { pred := state.NewStatePredicates(p.node) changed, val, err := pred.OnMinerActorChange(m.common.addr, pred.OnMinerPreCommitChange())(ctx, m.common.parentTsKey, m.common.tsKey) if err != nil { @@ -676,11 +666,11 @@ func (p *Processor) getMinerPreCommitChanges(ctx context.Context, m minerActorIn if !changed { return nil, nil } - out := val.(*state.MinerPreCommitChanges) + out := val.(*miner.PreCommitChanges) return out, nil } -func (p *Processor) getMinerSectorChanges(ctx context.Context, m minerActorInfo) (*state.MinerSectorChanges, error) { +func (p *Processor) getMinerSectorChanges(ctx context.Context, m minerActorInfo) (*miner.SectorChanges, error) { pred := state.NewStatePredicates(p.node) changed, val, err := pred.OnMinerActorChange(m.common.addr, pred.OnMinerSectorChange())(ctx, m.common.parentTsKey, m.common.tsKey) if err != nil { @@ -689,7 +679,7 @@ func (p *Processor) getMinerSectorChanges(ctx context.Context, m minerActorInfo) if !changed { return nil, nil } - out := val.(*state.MinerSectorChanges) + out := val.(*miner.SectorChanges) return out, nil } @@ -698,179 +688,196 @@ func (p *Processor) diffMinerPartitions(ctx context.Context, m minerActorInfo, e if err != nil { return err } - dlIdx := prevMiner.CurrentDeadline curMiner := m.state - - // load the old deadline - prevDls, err := prevMiner.LoadDeadlines(p.ctxStore) - if err != nil { - return err - } - var prevDl miner.Deadline - if err := p.ctxStore.Get(ctx, prevDls.Due[dlIdx], &prevDl); err != nil { - return err + if !prevMiner.DeadlinesChanged(curMiner) { + return nil } + panic("TODO") - prevPartitions, err := prevDl.PartitionsArray(p.ctxStore) - if err != nil { - return err - } + // FIXME: This code doesn't work. + // 1. We need to diff all deadlines, not just the "current" deadline. + // 2. We need to handle the case where we _add_ a partition. (i.e., + // where len(newPartitions) != len(oldPartitions). + /* - // load the new deadline - curDls, err := curMiner.LoadDeadlines(p.ctxStore) - if err != nil { - return err - } + // NOTE: If we change the number of deadlines in an upgrade, this will + // break. - var curDl miner.Deadline - if err := p.ctxStore.Get(ctx, curDls.Due[dlIdx], &curDl); err != nil { - return err - } + // load the old deadline + prevDls, err := prevMiner.LoadDeadlines(p.ctxStore) + if err != nil { + return err + } + var prevDl miner.Deadline + if err := p.ctxStore.Get(ctx, prevDls.Due[dlIdx], &prevDl); err != nil { + return err + } - curPartitions, err := curDl.PartitionsArray(p.ctxStore) - if err != nil { - return err - } + prevPartitions, err := prevDl.PartitionsArray(p.ctxStore) + if err != nil { + return err + } - // TODO this can be optimized by inspecting the miner state for partitions that have changed and only inspecting those. - var prevPart miner.Partition - if err := prevPartitions.ForEach(&prevPart, func(i int64) error { - var curPart miner.Partition - if found, err := curPartitions.Get(uint64(i), &curPart); err != nil { - return err - } else if !found { - log.Fatal("I don't know what this means, are partitions ever removed?") - } - partitionDiff, err := p.diffPartition(prevPart, curPart) - if err != nil { - return err - } + // load the new deadline + curDls, err := curMiner.LoadDeadlines(p.ctxStore) + if err != nil { + return err + } - recovered, err := partitionDiff.Recovered.All(miner.SectorsMax) - if err != nil { - return err - } - events <- &MinerSectorsEvent{ - MinerID: m.common.addr, - StateRoot: m.common.stateroot, - SectorIDs: recovered, - Event: SectorRecovered, - } - inRecovery, err := partitionDiff.InRecovery.All(miner.SectorsMax) - if err != nil { - return err - } - events <- &MinerSectorsEvent{ - MinerID: m.common.addr, - StateRoot: m.common.stateroot, - SectorIDs: inRecovery, - Event: SectorRecovering, - } - faulted, err := partitionDiff.Faulted.All(miner.SectorsMax) - if err != nil { - return err - } - events <- &MinerSectorsEvent{ - MinerID: m.common.addr, - StateRoot: m.common.stateroot, - SectorIDs: faulted, - Event: SectorFaulted, - } - terminated, err := partitionDiff.Terminated.All(miner.SectorsMax) - if err != nil { - return err - } - events <- &MinerSectorsEvent{ - MinerID: m.common.addr, - StateRoot: m.common.stateroot, - SectorIDs: terminated, - Event: SectorTerminated, - } - expired, err := partitionDiff.Expired.All(miner.SectorsMax) - if err != nil { - return err - } - events <- &MinerSectorsEvent{ - MinerID: m.common.addr, - StateRoot: m.common.stateroot, - SectorIDs: expired, - Event: SectorExpired, - } + var curDl miner.Deadline + if err := p.ctxStore.Get(ctx, curDls.Due[dlIdx], &curDl); err != nil { + return err + } + + curPartitions, err := curDl.PartitionsArray(p.ctxStore) + if err != nil { + return err + } + + // TODO this can be optimized by inspecting the miner state for partitions that have changed and only inspecting those. + var prevPart miner.Partition + if err := prevPartitions.ForEach(&prevPart, func(i int64) error { + var curPart miner.Partition + if found, err := curPartitions.Get(uint64(i), &curPart); err != nil { + return err + } else if !found { + log.Fatal("I don't know what this means, are partitions ever removed?") + } + partitionDiff, err := p.diffPartition(prevPart, curPart) + if err != nil { + return err + } + + recovered, err := partitionDiff.Recovered.All(miner.SectorsMax) + if err != nil { + return err + } + events <- &MinerSectorsEvent{ + MinerID: m.common.addr, + StateRoot: m.common.stateroot, + SectorIDs: recovered, + Event: SectorRecovered, + } + inRecovery, err := partitionDiff.InRecovery.All(miner.SectorsMax) + if err != nil { + return err + } + events <- &MinerSectorsEvent{ + MinerID: m.common.addr, + StateRoot: m.common.stateroot, + SectorIDs: inRecovery, + Event: SectorRecovering, + } + faulted, err := partitionDiff.Faulted.All(miner.SectorsMax) + if err != nil { + return err + } + events <- &MinerSectorsEvent{ + MinerID: m.common.addr, + StateRoot: m.common.stateroot, + SectorIDs: faulted, + Event: SectorFaulted, + } + terminated, err := partitionDiff.Terminated.All(miner.SectorsMax) + if err != nil { + return err + } + events <- &MinerSectorsEvent{ + MinerID: m.common.addr, + StateRoot: m.common.stateroot, + SectorIDs: terminated, + Event: SectorTerminated, + } + expired, err := partitionDiff.Expired.All(miner.SectorsMax) + if err != nil { + return err + } + events <- &MinerSectorsEvent{ + MinerID: m.common.addr, + StateRoot: m.common.stateroot, + SectorIDs: expired, + Event: SectorExpired, + } + + return nil + }); err != nil { + return err + } return nil - }); err != nil { - return err - } - - return nil + */ } func (p *Processor) diffPartition(prevPart, curPart miner.Partition) (*PartitionStatus, error) { - // all the sectors that were in previous but not in current - allRemovedSectors, err := bitfield.SubtractBitField(prevPart.Sectors, curPart.Sectors) + prevLiveSectors, err := prevPart.LiveSectors() + if err != nil { + return nil, err + } + curLiveSectors, err := curPart.LiveSectors() if err != nil { return nil, err } - // list of sectors that were terminated before their expiration. - terminatedEarlyArr, err := adt.AsArray(p.ctxStore, curPart.EarlyTerminated) + removedSectors, err := bitfield.SubtractBitField(prevLiveSectors, curLiveSectors) if err != nil { return nil, err } - expired := bitfield.New() - var bf bitfield.BitField - if err := terminatedEarlyArr.ForEach(&bf, func(i int64) error { - // expired = all removals - termination - expirations, err := bitfield.SubtractBitField(allRemovedSectors, bf) - if err != nil { - return err - } - // merge with expired sectors from other epochs - expired, err = bitfield.MergeBitFields(expirations, expired) - if err != nil { - return nil - } - return nil - }); err != nil { - return nil, err - } - - // terminated = all removals - expired - terminated, err := bitfield.SubtractBitField(allRemovedSectors, expired) + prevRecoveries, err := prevPart.RecoveringSectors() if err != nil { return nil, err } - // faults in current but not previous - faults, err := bitfield.SubtractBitField(curPart.Recoveries, prevPart.Recoveries) + curRecoveries, err := curPart.RecoveringSectors() if err != nil { return nil, err } - // recoveries in current but not previous - inRecovery, err := bitfield.SubtractBitField(curPart.Recoveries, prevPart.Recoveries) + newRecoveries, err := bitfield.SubtractBitField(curRecoveries, prevRecoveries) + if err != nil { + return nil, err + } + + prevFaults, err := prevPart.FaultySectors() + if err != nil { + return nil, err + } + + curFaults, err := curPart.FaultySectors() + if err != nil { + return nil, err + } + + newFaults, err := bitfield.SubtractBitField(curFaults, prevFaults) if err != nil { return nil, err } // all current good sectors - newActiveSectors, err := curPart.ActiveSectors() + curActiveSectors, err := curPart.ActiveSectors() if err != nil { return nil, err } // sectors that were previously fault and are now currently active are considered recovered. - recovered, err := bitfield.IntersectBitField(prevPart.Faults, newActiveSectors) + recovered, err := bitfield.IntersectBitField(prevFaults, curActiveSectors) if err != nil { return nil, err } + // TODO: distinguish between "terminated" and "expired" sectors. The + // previous code here never had a chance of working in the first place, + // so I'm not going to try to replicate it right now. + // + // How? If the sector expires before it should (according to sector + // info) and it wasn't replaced by a pre-commit deleted in this change + // set, it was "early terminated". + return &PartitionStatus{ - Terminated: terminated, - Expired: expired, - Faulted: faults, - InRecovery: inRecovery, + Terminated: bitfield.New(), + Expired: removedSectors, + Faulted: newFaults, + InRecovery: newRecoveries, Recovered: recovered, }, nil } From f2a0779bb9a6c4e5f9768c3d6ef3da30027c24cb Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Thu, 17 Sep 2020 21:41:36 -0700 Subject: [PATCH 088/303] remove specs-actors import --- chain/events/state/predicates.go | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/chain/events/state/predicates.go b/chain/events/state/predicates.go index 721de9dd2..e0e977772 100644 --- a/chain/events/state/predicates.go +++ b/chain/events/state/predicates.go @@ -9,15 +9,14 @@ import ( "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/lotus/chain/actors/adt" - init_ "github.com/filecoin-project/lotus/chain/actors/builtin/init" - "github.com/filecoin-project/lotus/chain/actors/builtin/market" - "github.com/filecoin-project/lotus/chain/actors/builtin/paych" - "github.com/filecoin-project/specs-actors/actors/builtin" cbor "github.com/ipfs/go-ipld-cbor" typegen "github.com/whyrusleeping/cbor-gen" "github.com/filecoin-project/lotus/api/apibstore" + "github.com/filecoin-project/lotus/chain/actors/adt" + init_ "github.com/filecoin-project/lotus/chain/actors/builtin/init" + "github.com/filecoin-project/lotus/chain/actors/builtin/market" + "github.com/filecoin-project/lotus/chain/actors/builtin/paych" "github.com/filecoin-project/lotus/chain/types" ) @@ -74,7 +73,7 @@ type DiffStorageMarketStateFunc func(ctx context.Context, oldState market.State, // OnStorageMarketActorChanged calls diffStorageMarketState when the state changes for the market actor func (sp *StatePredicates) OnStorageMarketActorChanged(diffStorageMarketState DiffStorageMarketStateFunc) DiffTipSetKeyFunc { - return sp.OnActorStateChanged(builtin.StorageMarketActorAddr, func(ctx context.Context, oldActorState, newActorState *types.Actor) (changed bool, user UserData, err error) { + return sp.OnActorStateChanged(market.Address, func(ctx context.Context, oldActorState, newActorState *types.Actor) (changed bool, user UserData, err error) { oldState, err := market.Load(adt.WrapStore(ctx, sp.cst), oldActorState) if err != nil { return false, nil, err @@ -295,7 +294,7 @@ func (sp *StatePredicates) AvailableBalanceChangedForAddresses(getAddrs func() [ type DiffMinerActorStateFunc func(ctx context.Context, oldState miner.State, newState miner.State) (changed bool, user UserData, err error) func (sp *StatePredicates) OnInitActorChange(diffInitActorState DiffInitActorStateFunc) DiffTipSetKeyFunc { - return sp.OnActorStateChanged(builtin.InitActorAddr, func(ctx context.Context, oldActorState, newActorState *types.Actor) (changed bool, user UserData, err error) { + return sp.OnActorStateChanged(init_.Address, func(ctx context.Context, oldActorState, newActorState *types.Actor) (changed bool, user UserData, err error) { oldState, err := init_.Load(adt.WrapStore(ctx, sp.cst), oldActorState) if err != nil { return false, nil, err From 8bd6791e58d8420ce4434e8a92ff87768895e274 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Thu, 17 Sep 2020 21:44:10 -0700 Subject: [PATCH 089/303] more fixups --- tools/stats/metrics.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tools/stats/metrics.go b/tools/stats/metrics.go index 4f11d2476..86dbe6780 100644 --- a/tools/stats/metrics.go +++ b/tools/stats/metrics.go @@ -12,13 +12,13 @@ import ( "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" + "github.com/filecoin-project/lotus/chain/actors/builtin/reward" "github.com/filecoin-project/lotus/chain/store" "github.com/filecoin-project/lotus/chain/types" - "github.com/filecoin-project/specs-actors/actors/builtin" - "golang.org/x/xerrors" "github.com/ipfs/go-cid" "github.com/multiformats/go-multihash" + "golang.org/x/xerrors" cbg "github.com/whyrusleeping/cbor-gen" @@ -242,7 +242,7 @@ func RecordTipsetStatePoints(ctx context.Context, api api.FullNode, pl *PointLis //p := NewPoint("chain.pledge_collateral", pcFilFloat) //pl.AddPoint(p) - netBal, err := api.WalletBalance(ctx, builtin.RewardActorAddr) + netBal, err := api.WalletBalance(ctx, reward.Address) if err != nil { return err } From daa441b989514f549a1ea5d5bc28bf51e9d3c901 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Thu, 17 Sep 2020 21:48:50 -0700 Subject: [PATCH 090/303] simplify market diff --- chain/actors/builtin/market/{util.go => diff.go} | 4 ++-- chain/actors/builtin/market/market.go | 2 -- chain/actors/builtin/market/v0.go | 8 -------- chain/events/state/predicates.go | 4 ++-- 4 files changed, 4 insertions(+), 14 deletions(-) rename chain/actors/builtin/market/{util.go => diff.go} (94%) diff --git a/chain/actors/builtin/market/util.go b/chain/actors/builtin/market/diff.go similarity index 94% rename from chain/actors/builtin/market/util.go rename to chain/actors/builtin/market/diff.go index 92fdd6823..d0b4a2fd3 100644 --- a/chain/actors/builtin/market/util.go +++ b/chain/actors/builtin/market/diff.go @@ -8,7 +8,7 @@ import ( cbg "github.com/whyrusleeping/cbor-gen" ) -func diffDealProposals(pre, cur DealProposals) (*DealProposalChanges, error) { +func DiffDealProposals(pre, cur DealProposals) (*DealProposalChanges, error) { results := new(DealProposalChanges) if err := adt.DiffAdtArray(pre.array(), cur.array(), &marketProposalsDiffer{results, pre, cur}); err != nil { return nil, fmt.Errorf("diffing deal states: %w", err) @@ -44,7 +44,7 @@ func (d *marketProposalsDiffer) Remove(key uint64, val *cbg.Deferred) error { return nil } -func diffDealStates(pre, cur DealStates) (*DealStateChanges, error) { +func DiffDealStates(pre, cur DealStates) (*DealStateChanges, error) { results := new(DealStateChanges) if err := adt.DiffAdtArray(pre.array(), cur.array(), &marketStatesDiffer{results, pre, cur}); err != nil { return nil, fmt.Errorf("diffing deal states: %w", err) diff --git a/chain/actors/builtin/market/market.go b/chain/actors/builtin/market/market.go index 1c11c027e..c65fa093d 100644 --- a/chain/actors/builtin/market/market.go +++ b/chain/actors/builtin/market/market.go @@ -51,7 +51,6 @@ type BalanceTable interface { type DealStates interface { Get(id abi.DealID) (*DealState, bool, error) - Diff(DealStates) (*DealStateChanges, error) array() adt.Array decode(*cbg.Deferred) (*DealState, error) @@ -60,7 +59,6 @@ type DealStates interface { type DealProposals interface { ForEach(cb func(id abi.DealID, dp DealProposal) error) error Get(id abi.DealID) (*DealProposal, bool, error) - Diff(DealProposals) (*DealProposalChanges, error) array() adt.Array decode(*cbg.Deferred) (*DealProposal, error) diff --git a/chain/actors/builtin/market/v0.go b/chain/actors/builtin/market/v0.go index 587446749..671907ad4 100644 --- a/chain/actors/builtin/market/v0.go +++ b/chain/actors/builtin/market/v0.go @@ -124,10 +124,6 @@ func (s *v0DealStates) Get(dealID abi.DealID) (*DealState, bool, error) { return &deal, true, nil } -func (s *v0DealStates) Diff(other DealStates) (*DealStateChanges, error) { - return diffDealStates(s, other) -} - func (s *v0DealStates) decode(val *cbg.Deferred) (*DealState, error) { var v0ds market.DealState if err := v0ds.UnmarshalCBOR(bytes.NewReader(val.Raw)); err != nil { @@ -149,10 +145,6 @@ type v0DealProposals struct { adt.Array } -func (s *v0DealProposals) Diff(other DealProposals) (*DealProposalChanges, error) { - return diffDealProposals(s, other) -} - func (s *v0DealProposals) Get(dealID abi.DealID) (*DealProposal, bool, error) { var v0proposal market.DealProposal found, err := s.Array.Get(uint64(dealID), &v0proposal) diff --git a/chain/events/state/predicates.go b/chain/events/state/predicates.go index e0e977772..4e821633e 100644 --- a/chain/events/state/predicates.go +++ b/chain/events/state/predicates.go @@ -175,7 +175,7 @@ func (sp *StatePredicates) OnDealProposalChanged(diffDealProps DiffDealProposals // - Removed Proposals func (sp *StatePredicates) OnDealProposalAmtChanged() DiffDealProposalsFunc { return func(ctx context.Context, oldDealProps, newDealProps market.DealProposals) (changed bool, user UserData, err error) { - proposalChanges, err := oldDealProps.Diff(newDealProps) + proposalChanges, err := market.DiffDealProposals(oldDealProps, newDealProps) if err != nil { return false, nil, err } @@ -194,7 +194,7 @@ func (sp *StatePredicates) OnDealProposalAmtChanged() DiffDealProposalsFunc { // - Removed Deals func (sp *StatePredicates) OnDealStateAmtChanged() DiffDealStatesFunc { return func(ctx context.Context, oldDealStates, newDealStates market.DealStates) (changed bool, user UserData, err error) { - dealStateChanges, err := oldDealStates.Diff(newDealStates) + dealStateChanges, err := market.DiffDealStates(oldDealStates, newDealStates) if err != nil { return false, nil, err } From 37de154a7cefe4eac620273464fb53b12dc0d190 Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Fri, 18 Sep 2020 01:12:45 -0400 Subject: [PATCH 091/303] Fixup tests --- api/test/ccupgrade.go | 1 + chain/actors/builtin/miner/v0.go | 11 ++++++----- chain/events/state/predicates_test.go | 4 ++-- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/api/test/ccupgrade.go b/api/test/ccupgrade.go index 130b55cb8..b281f30a0 100644 --- a/api/test/ccupgrade.go +++ b/api/test/ccupgrade.go @@ -85,6 +85,7 @@ func TestCCUpgrade(t *testing.T, b APIBuilder, blocktime time.Duration) { { exp, err := client.StateSectorExpiration(ctx, maddr, CC, types.EmptyTSK) require.NoError(t, err) + require.NotNil(t, exp) require.Greater(t, 50000, int(exp.OnTime)) } { diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index 9f4cea6ce..e0ae2594a 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -65,7 +65,7 @@ func (s *v0State) FindSector(num abi.SectorNumber) (*SectorLocation, error) { // If the sector isn't found or has already been terminated, this method returns // nil and no error. If the sector does not expire early, the Early expiration // field is 0. -func (s *v0State) GetSectorExpiration(num abi.SectorNumber) (out *SectorExpiration, err error) { +func (s *v0State) GetSectorExpiration(num abi.SectorNumber) (*SectorExpiration, error) { dls, err := s.State.LoadDeadlines(s.store) if err != nil { return nil, err @@ -77,6 +77,7 @@ func (s *v0State) GetSectorExpiration(num abi.SectorNumber) (out *SectorExpirati // 2. If it's faulty, it will expire early within the first 14 entries // of the expiration queue. stopErr := errors.New("stop") + out := SectorExpiration{} err = dls.ForEach(s.store, func(dlIdx uint64, dl *v0miner.Deadline) error { partitions, err := dl.PartitionsArray(s.store) if err != nil { @@ -97,7 +98,7 @@ func (s *v0State) GetSectorExpiration(num abi.SectorNumber) (out *SectorExpirati return stopErr } - q, err := v0miner.LoadExpirationQueue(s.store, part.EarlyTerminated, quant) + q, err := v0miner.LoadExpirationQueue(s.store, part.ExpirationsEpochs, quant) if err != nil { return err } @@ -128,7 +129,7 @@ func (s *v0State) GetSectorExpiration(num abi.SectorNumber) (out *SectorExpirati if out.Early == 0 && out.OnTime == 0 { return nil, nil } - return out, nil + return &out, nil } func (s *v0State) GetPrecommittedSector(num abi.SectorNumber) (*SectorPreCommitOnChainInfo, error) { @@ -294,14 +295,14 @@ func (d *v0Deadline) ForEachPartition(cb func(uint64, Partition) error) error { }) } -func (s *v0Deadline) PartitionsChanged(other Deadline) bool { +func (d *v0Deadline) PartitionsChanged(other Deadline) bool { v0other, ok := other.(*v0Deadline) if !ok { // treat an upgrade as a change, always return true } - return s.Deadline.Partitions.Equals(v0other.Deadline.Partitions) + return d.Deadline.Partitions.Equals(v0other.Deadline.Partitions) } func (d *v0Deadline) PostSubmissions() (bitfield.BitField, error) { diff --git a/chain/events/state/predicates_test.go b/chain/events/state/predicates_test.go index 243d8814e..0412c6421 100644 --- a/chain/events/state/predicates_test.go +++ b/chain/events/state/predicates_test.go @@ -398,8 +398,8 @@ func TestMinerSectorChange(t *testing.T) { require.NoError(t, err) api := newMockAPI(bs) - api.setActor(oldState.Key(), &types.Actor{Head: oldMinerC}) - api.setActor(newState.Key(), &types.Actor{Head: newMinerC}) + api.setActor(oldState.Key(), &types.Actor{Head: oldMinerC, Code: v0builtin.StorageMinerActorCodeID}) + api.setActor(newState.Key(), &types.Actor{Head: newMinerC, Code: v0builtin.StorageMinerActorCodeID}) preds := NewStatePredicates(api) From fce423c7431d2d48cea876ffdbe95a5747f320dd Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Fri, 18 Sep 2020 02:14:18 -0400 Subject: [PATCH 092/303] Appease the linter and get everything building --- build/params_testground.go | 3 ++- extern/storage-sealing/checks.go | 1 + extern/storage-sealing/precommit_policy.go | 1 + extern/storage-sealing/precommit_policy_test.go | 3 ++- extern/storage-sealing/sealing.go | 5 ++--- extern/storage-sealing/states_sealing.go | 3 +++ go.sum | 4 ---- node/impl/full/state.go | 3 --- 8 files changed, 11 insertions(+), 12 deletions(-) diff --git a/build/params_testground.go b/build/params_testground.go index 77e312ac2..1b30ae2e9 100644 --- a/build/params_testground.go +++ b/build/params_testground.go @@ -80,5 +80,6 @@ var ( 0: DrandMainnet, } - NewestNetworkVersion = network.Version2 + NewestNetworkVersion = network.Version2 + ActorUpgradeNetworkVersion = network.Version3 ) diff --git a/extern/storage-sealing/checks.go b/extern/storage-sealing/checks.go index ae5ce0d33..677cef1e9 100644 --- a/extern/storage-sealing/checks.go +++ b/extern/storage-sealing/checks.go @@ -105,6 +105,7 @@ func checkPrecommit(ctx context.Context, maddr address.Address, si SectorInfo, t msd = v0miner.MaxSealDuration[si.SectorType] } else { // TODO: ActorUpgrade + msd = 0 } if height-(si.TicketEpoch+SealRandomnessLookback) > msd { diff --git a/extern/storage-sealing/precommit_policy.go b/extern/storage-sealing/precommit_policy.go index e36b8251a..76d867144 100644 --- a/extern/storage-sealing/precommit_policy.go +++ b/extern/storage-sealing/precommit_policy.go @@ -90,6 +90,7 @@ func (p *BasicPreCommitPolicy) Expiration(ctx context.Context, ps ...Piece) (abi wpp = v0miner.WPoStProvingPeriod } else { // TODO: ActorUpgrade + wpp = 0 } *end += wpp - (*end % wpp) + p.provingBoundary - 1 diff --git a/extern/storage-sealing/precommit_policy_test.go b/extern/storage-sealing/precommit_policy_test.go index 30b538a88..52814167a 100644 --- a/extern/storage-sealing/precommit_policy_test.go +++ b/extern/storage-sealing/precommit_policy_test.go @@ -2,9 +2,10 @@ package sealing_test import ( "context" + "testing" + "github.com/filecoin-project/go-state-types/network" "github.com/filecoin-project/lotus/build" - "testing" "github.com/ipfs/go-cid" "github.com/stretchr/testify/assert" diff --git a/extern/storage-sealing/sealing.go b/extern/storage-sealing/sealing.go index 6d60e7a6e..01551e6d7 100644 --- a/extern/storage-sealing/sealing.go +++ b/extern/storage-sealing/sealing.go @@ -431,9 +431,8 @@ func (m *Sealing) getPreCommitChallengeDelay(ctx context.Context, tok TipSetToke if nv < build.ActorUpgradeNetworkVersion { return v0miner.PreCommitChallengeDelay, nil - } else { - // TODO: ActorUpgrade - return -1, nil } + // TODO: ActorUpgrade + return -1, nil } diff --git a/extern/storage-sealing/states_sealing.go b/extern/storage-sealing/states_sealing.go index f0ff4025d..6ae42a91f 100644 --- a/extern/storage-sealing/states_sealing.go +++ b/extern/storage-sealing/states_sealing.go @@ -195,6 +195,8 @@ func (m *Sealing) handlePreCommitting(ctx statemachine.Context, sector SectorInf mse = v0miner.MinSectorExpiration } else { // TODO: ActorUpgrade + msd = 0 + mse = 0 } if minExpiration := height + msd + mse + 10; expiration < minExpiration { @@ -395,6 +397,7 @@ func (m *Sealing) handleSubmitCommit(ctx statemachine.Context, sector SectorInfo } } else { // TODO: ActorUpgrade + enc = nil } waddr, err := m.api.StateMinerWorkerAddress(ctx.Context(), m.maddr, tok) diff --git a/go.sum b/go.sum index 3d012da92..5ebec6cbf 100644 --- a/go.sum +++ b/go.sum @@ -226,10 +226,6 @@ github.com/filecoin-project/go-data-transfer v0.6.3 h1:7TLwm8nuodHYD/uiwJjKc/PGR github.com/filecoin-project/go-data-transfer v0.6.3/go.mod h1:PmBKVXkhh67/tnEdJXQwDHl5mT+7Tbcwe1NPninqhnM= github.com/filecoin-project/go-fil-commcid v0.0.0-20200716160307-8f644712406f h1:GxJzR3oRIMTPtpZ0b7QF8FKPK6/iPAc7trhlL5k/g+s= github.com/filecoin-project/go-fil-commcid v0.0.0-20200716160307-8f644712406f/go.mod h1:Eaox7Hvus1JgPrL5+M3+h7aSPHc0cVqpSxA+TxIEpZQ= -github.com/filecoin-project/go-fil-markets v0.6.1-0.20200911011457-2959ccca6a3c h1:YGoyYmELQ0LHwDj/WcOvY3oYt+3iM0wdrAhqJQUAIy4= -github.com/filecoin-project/go-fil-markets v0.6.1-0.20200911011457-2959ccca6a3c/go.mod h1:PLr9svZxsnHkae1Ky7+66g7fP9AlneVxIVu+oSMq56A= -github.com/filecoin-project/go-fil-markets v0.6.1-0.20200917050751-2af52e9606c6 h1:k97Z2JP3WpDVGU/7Bz3RtnqrYtn9X428Ps8OkoFq61I= -github.com/filecoin-project/go-fil-markets v0.6.1-0.20200917050751-2af52e9606c6/go.mod h1:PLr9svZxsnHkae1Ky7+66g7fP9AlneVxIVu+oSMq56A= github.com/filecoin-project/go-fil-markets v0.6.1-0.20200917052354-ee0af754c6e9 h1:SnCUC9wHDId9TtV8PsQp8q1OOsi+NOLOwitIDnAgUa4= github.com/filecoin-project/go-fil-markets v0.6.1-0.20200917052354-ee0af754c6e9/go.mod h1:PLr9svZxsnHkae1Ky7+66g7fP9AlneVxIVu+oSMq56A= github.com/filecoin-project/go-hamt-ipld v0.1.5 h1:uoXrKbCQZ49OHpsTCkrThPNelC4W3LPEk0OrS/ytIBM= diff --git a/node/impl/full/state.go b/node/impl/full/state.go index 04055043a..729baef2c 100644 --- a/node/impl/full/state.go +++ b/node/impl/full/state.go @@ -3,7 +3,6 @@ package full import ( "bytes" "context" - "errors" "strconv" v0market "github.com/filecoin-project/specs-actors/actors/builtin/market" @@ -47,8 +46,6 @@ import ( "github.com/filecoin-project/lotus/node/modules/dtypes" ) -var errBreakForeach = errors.New("break") - type StateAPI struct { fx.In From 694463ffbe63f2f48985c391bdf98f388155fabc Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Fri, 18 Sep 2020 03:06:28 -0400 Subject: [PATCH 093/303] More lint fixes --- chain/events/state/predicates.go | 1 - chain/events/state/predicates_test.go | 2 ++ chain/stmgr/stmgr.go | 1 + cmd/lotus-pcr/main.go | 1 + 4 files changed, 4 insertions(+), 1 deletion(-) diff --git a/chain/events/state/predicates.go b/chain/events/state/predicates.go index 4e821633e..21e1720e6 100644 --- a/chain/events/state/predicates.go +++ b/chain/events/state/predicates.go @@ -530,6 +530,5 @@ func (sp *StatePredicates) OnAddressMapChange() DiffInitActorStateFunc { return true, addressChanges, nil*/ panic("TODO") - return false, nil, nil } } diff --git a/chain/events/state/predicates_test.go b/chain/events/state/predicates_test.go index 0412c6421..604eec75d 100644 --- a/chain/events/state/predicates_test.go +++ b/chain/events/state/predicates_test.go @@ -246,6 +246,7 @@ func TestMarketPredicates(t *testing.T) { Code: v0builtin.StorageMarketActorCodeID, Head: marketCid, }) + require.NoError(t, err) changed, _, err = diffDealStateFn(ctx, marketState, marketState) require.NoError(t, err) require.False(t, changed) @@ -358,6 +359,7 @@ func TestMarketPredicates(t *testing.T) { Code: v0builtin.StorageMarketActorCodeID, Head: marketCid, }) + require.NoError(t, err) changed, _, err = diffDealBalancesFn(ctx, marketState, marketState) require.NoError(t, err) require.False(t, changed) diff --git a/chain/stmgr/stmgr.go b/chain/stmgr/stmgr.go index 90154868e..d1adbbc62 100644 --- a/chain/stmgr/stmgr.go +++ b/chain/stmgr/stmgr.go @@ -262,6 +262,7 @@ func (sm *StateManager) ApplyBlocks(ctx context.Context, parentEpoch abi.ChainEp } } else { // TODO: ActorUpgrade + params = nil } sysAct, err := vmi.StateTree().GetActor(builtin.SystemActorAddr) diff --git a/cmd/lotus-pcr/main.go b/cmd/lotus-pcr/main.go index aa467e38a..3dedb24fc 100644 --- a/cmd/lotus-pcr/main.go +++ b/cmd/lotus-pcr/main.go @@ -412,6 +412,7 @@ func (r *refunder) ProcessTipset(ctx context.Context, tipset *types.TipSet, refu sn = proveCommitSector.SectorNumber } else { // TODO: ActorUpgrade + sn = -1 } // We use the parent tipset key because precommit information is removed when ProveCommitSector is executed From 37108ebf8fa9f5fc6f78e9fe4b50ee1d72b4e17a Mon Sep 17 00:00:00 2001 From: Jennifer <42981373+jennijuju@users.noreply.github.com> Date: Fri, 18 Sep 2020 04:36:27 -0400 Subject: [PATCH 094/303] Update build and setup instruction link Update the link since we deprecated lotus.sh and migrates it to doc.Filecoin --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6c1e23efa..766317e4f 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ Lotus is an implementation of the Filecoin Distributed Storage Network. For more ## Building & Documentation -For instructions on how to build lotus from source, please visit [https://lotu.sh](https://lotu.sh) or read the source [here](https://github.com/filecoin-project/lotus/tree/master/documentation). +For instructions on how to build lotus from source, please visit [Lotus build and setup instruction](https://docs.filecoin.io/get-started/lotus/installation/#minimal-requirements) or read the source [here](https://github.com/filecoin-project/lotus/tree/master/documentation). ## Reporting a Vulnerability From eadc61c37a81ca999ff1c2a021352a82f4df067a Mon Sep 17 00:00:00 2001 From: Travis Person Date: Fri, 18 Sep 2020 18:07:58 +0000 Subject: [PATCH 095/303] log shutdown method for lotus daemon and miner --- cmd/lotus-storage-miner/run.go | 4 +++- cmd/lotus/rpc.go | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/cmd/lotus-storage-miner/run.go b/cmd/lotus-storage-miner/run.go index 83d78172e..a5d996f78 100644 --- a/cmd/lotus-storage-miner/run.go +++ b/cmd/lotus-storage-miner/run.go @@ -163,8 +163,10 @@ var runCmd = &cli.Command{ sigChan := make(chan os.Signal, 2) go func() { select { - case <-sigChan: + case sig := <-sigChan: + log.Warnw("received shutdown", "signal", sig) case <-shutdownChan: + log.Warn("received shutdown") } log.Warn("Shutting down...") diff --git a/cmd/lotus/rpc.go b/cmd/lotus/rpc.go index fbe05e938..9718deb3a 100644 --- a/cmd/lotus/rpc.go +++ b/cmd/lotus/rpc.go @@ -66,8 +66,10 @@ func serveRPC(a api.FullNode, stop node.StopFunc, addr multiaddr.Multiaddr, shut shutdownDone := make(chan struct{}) go func() { select { - case <-sigCh: + case sig := <-sigCh: + log.Warnw("received shutdown", "signal", sig) case <-shutdownCh: + log.Warn("received shutdown") } log.Warn("Shutting down...") From ccd0a67b01c31da932c2a3b052269ba4d703df17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Fri, 18 Sep 2020 20:34:23 +0200 Subject: [PATCH 096/303] wip fixing wdpost tests --- storage/wdpost_run_test.go | 61 ++++++++++++++++++++++++-------------- 1 file changed, 38 insertions(+), 23 deletions(-) diff --git a/storage/wdpost_run_test.go b/storage/wdpost_run_test.go index af529a75e..1a930b41a 100644 --- a/storage/wdpost_run_test.go +++ b/storage/wdpost_run_test.go @@ -7,8 +7,6 @@ import ( "github.com/filecoin-project/go-state-types/dline" - "golang.org/x/xerrors" - "github.com/stretchr/testify/require" "github.com/filecoin-project/go-address" @@ -17,17 +15,20 @@ import ( "github.com/filecoin-project/lotus/chain/types" "github.com/ipfs/go-cid" - "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/filecoin-project/specs-actors/actors/runtime/proof" - "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/crypto" + "github.com/filecoin-project/go-state-types/network" + "github.com/filecoin-project/specs-actors/actors/builtin" + v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + "github.com/filecoin-project/specs-actors/actors/runtime/proof" tutils "github.com/filecoin-project/specs-actors/support/testing" + + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" ) type mockStorageMinerAPI struct { - partitions []*miner.Partition + partitions []api.Partition pushedMessages chan *types.Message } @@ -37,6 +38,14 @@ func newMockStorageMinerAPI() *mockStorageMinerAPI { } } +func (m *mockStorageMinerAPI) StateMinerInfo(ctx context.Context, a address.Address, key types.TipSetKey) (miner.MinerInfo, error) { + panic("implement me") +} + +func (m *mockStorageMinerAPI) StateNetworkVersion(ctx context.Context, key types.TipSetKey) (network.Version, error) { + panic("implement me") +} + func (m *mockStorageMinerAPI) ChainGetRandomnessFromTickets(ctx context.Context, tsk types.TipSetKey, personalization crypto.DomainSeparationTag, randEpoch abi.ChainEpoch, entropy []byte) (abi.Randomness, error) { return abi.Randomness("ticket rand"), nil } @@ -45,18 +54,18 @@ func (m *mockStorageMinerAPI) ChainGetRandomnessFromBeacon(ctx context.Context, return abi.Randomness("beacon rand"), nil } -func (m *mockStorageMinerAPI) setPartitions(ps []*miner.Partition) { +func (m *mockStorageMinerAPI) setPartitions(ps []api.Partition) { m.partitions = append(m.partitions, ps...) } -func (m *mockStorageMinerAPI) StateMinerPartitions(ctx context.Context, address address.Address, u uint64, key types.TipSetKey) ([]*miner.Partition, error) { +func (m *mockStorageMinerAPI) StateMinerPartitions(ctx context.Context, a address.Address, dlIdx uint64, tsk types.TipSetKey) ([]api.Partition, error) { return m.partitions, nil } -func (m *mockStorageMinerAPI) StateMinerSectors(ctx context.Context, address address.Address, field *bitfield.BitField, b bool, key types.TipSetKey) ([]*api.ChainSectorInfo, error) { - var sis []*api.ChainSectorInfo +func (m *mockStorageMinerAPI) StateMinerSectors(ctx context.Context, address address.Address, field *bitfield.BitField, b bool, key types.TipSetKey) ([]*miner.ChainSectorInfo, error) { + var sis []*miner.ChainSectorInfo _ = field.ForEach(func(i uint64) error { - sis = append(sis, &api.ChainSectorInfo{ + sis = append(sis, &miner.ChainSectorInfo{ Info: miner.SectorOnChainInfo{ SectorNumber: abi.SectorNumber(i), }, @@ -67,10 +76,6 @@ func (m *mockStorageMinerAPI) StateMinerSectors(ctx context.Context, address add return sis, nil } -func (m *mockStorageMinerAPI) StateMinerInfo(ctx context.Context, address address.Address, key types.TipSetKey) (api.MinerInfo, error) { - return api.MinerInfo{}, xerrors.Errorf("err") -} - func (m *mockStorageMinerAPI) MpoolPushMessage(ctx context.Context, message *types.Message, spec *api.MessageSendSpec) (*types.SignedMessage, error) { m.pushedMessages <- message return &types.SignedMessage{ @@ -127,21 +132,27 @@ func TestWDPostDoPost(t *testing.T) { require.NoError(t, err) // Work out the number of partitions that can be included in a message // without exceeding the message sector limit - partitionsPerMsg := int(miner.AddressedSectorsMax / sectorsPerPartition) + + require.NoError(t, err) + partitionsPerMsg := int(v0miner.AddressedSectorsMax / sectorsPerPartition) // Enough partitions to fill expectedMsgCount-1 messages partitionCount := (expectedMsgCount - 1) * partitionsPerMsg // Add an extra partition that should be included in the last message partitionCount++ - var partitions []*miner.Partition + var partitions []api.Partition for p := 0; p < partitionCount; p++ { sectors := bitfield.New() for s := uint64(0); s < sectorsPerPartition; s++ { sectors.Set(s) } - partitions = append(partitions, &miner.Partition{ - Sectors: sectors, + partitions = append(partitions, api.Partition{ + AllSectors: sectors, + FaultySectors: bitfield.New(), + RecoveringSectors: bitfield.New(), + LiveSectors: sectors, + ActiveSectors: sectors, }) } mockStgMinerAPI.setPartitions(partitions) @@ -204,7 +215,7 @@ func (m *mockStorageMinerAPI) StateCall(ctx context.Context, message *types.Mess panic("implement me") } -func (m *mockStorageMinerAPI) StateMinerDeadlines(ctx context.Context, maddr address.Address, tok types.TipSetKey) ([]*miner.Deadline, error) { +func (m *mockStorageMinerAPI) StateMinerDeadlines(ctx context.Context, maddr address.Address, tok types.TipSetKey) ([]api.Deadline, error) { panic("implement me") } @@ -216,7 +227,7 @@ func (m *mockStorageMinerAPI) StateSectorGetInfo(ctx context.Context, address ad panic("implement me") } -func (m *mockStorageMinerAPI) StateSectorPartition(ctx context.Context, maddr address.Address, sectorNumber abi.SectorNumber, tok types.TipSetKey) (*api.SectorLocation, error) { +func (m *mockStorageMinerAPI) StateSectorPartition(ctx context.Context, maddr address.Address, sectorNumber abi.SectorNumber, tok types.TipSetKey) (*miner.SectorLocation, error) { panic("implement me") } @@ -237,7 +248,9 @@ func (m *mockStorageMinerAPI) StateSearchMsg(ctx context.Context, cid cid.Cid) ( } func (m *mockStorageMinerAPI) StateGetActor(ctx context.Context, actor address.Address, ts types.TipSetKey) (*types.Actor, error) { - panic("implement me") + return &types.Actor{ + Code: v0builtin.StorageMinerActorCodeID, + }, nil } func (m *mockStorageMinerAPI) StateGetReceipt(ctx context.Context, cid cid.Cid, key types.TipSetKey) (*types.MessageReceipt, error) { @@ -303,3 +316,5 @@ func (m *mockStorageMinerAPI) WalletBalance(ctx context.Context, address address func (m *mockStorageMinerAPI) WalletHas(ctx context.Context, address address.Address) (bool, error) { panic("implement me") } + +var _ storageMinerApi = &mockStorageMinerAPI{} From c3046f487cf01a0a4d06c42510f04c33ddd3965a Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Fri, 18 Sep 2020 14:41:03 -0400 Subject: [PATCH 097/303] Don't use -1 as default sector number --- cmd/lotus-pcr/main.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/lotus-pcr/main.go b/cmd/lotus-pcr/main.go index 3dedb24fc..53c8223ed 100644 --- a/cmd/lotus-pcr/main.go +++ b/cmd/lotus-pcr/main.go @@ -412,7 +412,7 @@ func (r *refunder) ProcessTipset(ctx context.Context, tipset *types.TipSet, refu sn = proveCommitSector.SectorNumber } else { // TODO: ActorUpgrade - sn = -1 + sn = 0 } // We use the parent tipset key because precommit information is removed when ProveCommitSector is executed From fb2b25c2975b9f996646d71e9fd0b3410d7572b0 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Fri, 18 Sep 2020 13:43:14 -0700 Subject: [PATCH 098/303] finish upgrading chainwatch --- chain/actors/builtin/init/init.go | 3 + chain/actors/builtin/init/v0.go | 19 ++++ chain/actors/builtin/power/power.go | 4 + chain/actors/builtin/power/v0.go | 12 +++ chain/actors/builtin/reward/reward.go | 11 ++- chain/actors/builtin/reward/v0.go | 22 ++++- .../processor/common_actors.go | 29 ++---- cmd/lotus-chainwatch/processor/miner.go | 29 ++---- cmd/lotus-chainwatch/processor/power.go | 76 +++++++------- cmd/lotus-chainwatch/processor/reward.go | 99 ++++++++++++------- node/impl/full/state.go | 4 +- 11 files changed, 185 insertions(+), 123 deletions(-) diff --git a/chain/actors/builtin/init/init.go b/chain/actors/builtin/init/init.go index 3b1a49564..7485c599f 100644 --- a/chain/actors/builtin/init/init.go +++ b/chain/actors/builtin/init/init.go @@ -4,6 +4,7 @@ import ( "golang.org/x/xerrors" "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/cbor" v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" @@ -33,4 +34,6 @@ type State interface { ResolveAddress(address address.Address) (address.Address, bool, error) MapAddressToNewID(address address.Address) (address.Address, error) NetworkName() (dtypes.NetworkName, error) + + ForEachActor(func(id abi.ActorID, address address.Address) error) error } diff --git a/chain/actors/builtin/init/v0.go b/chain/actors/builtin/init/v0.go index 711b702e2..e286e1ef2 100644 --- a/chain/actors/builtin/init/v0.go +++ b/chain/actors/builtin/init/v0.go @@ -2,11 +2,15 @@ package init import ( "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + cbg "github.com/whyrusleeping/cbor-gen" init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/node/modules/dtypes" + + v0adt "github.com/filecoin-project/specs-actors/actors/util/adt" ) type v0State struct { @@ -22,6 +26,21 @@ func (s *v0State) MapAddressToNewID(address address.Address) (address.Address, e return s.State.MapAddressToNewID(s.store, address) } +func (s *v0State) ForEachActor(cb func(id abi.ActorID, address address.Address) error) error { + addrs, err := v0adt.AsMap(s.store, s.State.AddressMap) + if err != nil { + return err + } + var actorID cbg.CborInt + return addrs.ForEach(&actorID, func(key string) error { + addr, err := address.NewFromBytes([]byte(key)) + if err != nil { + return err + } + return cb(abi.ActorID(actorID), addr) + }) +} + func (s *v0State) NetworkName() (dtypes.NetworkName, error) { return dtypes.NetworkName(s.State.NetworkName), nil } diff --git a/chain/actors/builtin/power/power.go b/chain/actors/builtin/power/power.go index 65148f0a5..7170526bf 100644 --- a/chain/actors/builtin/power/power.go +++ b/chain/actors/builtin/power/power.go @@ -33,8 +33,12 @@ type State interface { TotalLocked() (abi.TokenAmount, error) TotalPower() (Claim, error) + TotalCommitted() (Claim, error) TotalPowerSmoothed() (builtin.FilterEstimate, error) + // MinerCounts returns the number of miners. Participating is the number + // with power above the minimum miner threshold. + MinerCounts() (participating, total uint64, err error) MinerPower(address.Address) (Claim, bool, error) MinerNominalPowerMeetsConsensusMinimum(address.Address) (bool, error) ListAllMiners() ([]address.Address, error) diff --git a/chain/actors/builtin/power/v0.go b/chain/actors/builtin/power/v0.go index 5cf6920c8..9730be893 100644 --- a/chain/actors/builtin/power/v0.go +++ b/chain/actors/builtin/power/v0.go @@ -24,6 +24,14 @@ func (s *v0State) TotalPower() (Claim, error) { }, nil } +// Committed power to the network. Includes miners below the minimum threshold. +func (s *v0State) TotalCommitted() (Claim, error) { + return Claim{ + RawBytePower: s.TotalBytesCommitted, + QualityAdjPower: s.TotalQABytesCommitted, + }, nil +} + func (s *v0State) MinerPower(addr address.Address) (Claim, bool, error) { claims, err := adt.AsMap(s.store, s.Claims) if err != nil { @@ -48,6 +56,10 @@ func (s *v0State) TotalPowerSmoothed() (builtin.FilterEstimate, error) { return *s.State.ThisEpochQAPowerSmoothed, nil } +func (s *v0State) MinerCounts() (uint64, uint64, error) { + return uint64(s.State.MinerAboveMinPowerCount), uint64(s.State.MinerCount), nil +} + func (s *v0State) ListAllMiners() ([]address.Address, error) { claims, err := adt.AsMap(s.store, s.Claims) if err != nil { diff --git a/chain/actors/builtin/reward/reward.go b/chain/actors/builtin/reward/reward.go index 52a26ab15..66df887fc 100644 --- a/chain/actors/builtin/reward/reward.go +++ b/chain/actors/builtin/reward/reward.go @@ -30,8 +30,15 @@ func Load(store adt.Store, act *types.Actor) (st State, err error) { type State interface { cbor.Er - RewardSmoothed() (builtin.FilterEstimate, error) - EffectiveBaselinePower() (abi.StoragePower, error) ThisEpochBaselinePower() (abi.StoragePower, error) + ThisEpochReward() (abi.StoragePower, error) + ThisEpochRewardSmoothed() (builtin.FilterEstimate, error) + + EffectiveBaselinePower() (abi.StoragePower, error) + EffectiveNetworkTime() (abi.ChainEpoch, error) + TotalStoragePowerReward() (abi.TokenAmount, error) + + CumsumBaseline() (abi.StoragePower, error) + CumsumRealized() (abi.StoragePower, error) } diff --git a/chain/actors/builtin/reward/v0.go b/chain/actors/builtin/reward/v0.go index 16ac2b071..d12eccf59 100644 --- a/chain/actors/builtin/reward/v0.go +++ b/chain/actors/builtin/reward/v0.go @@ -12,10 +12,18 @@ type v0State struct { store adt.Store } -func (s *v0State) RewardSmoothed() (builtin.FilterEstimate, error) { +func (s *v0State) ThisEpochReward() (abi.StoragePower, error) { + return s.State.ThisEpochReward, nil +} + +func (s *v0State) ThisEpochRewardSmoothed() (builtin.FilterEstimate, error) { return *s.State.ThisEpochRewardSmoothed, nil } +func (s *v0State) ThisEpochBaselinePower() (abi.StoragePower, error) { + return s.State.ThisEpochBaselinePower, nil +} + func (s *v0State) TotalStoragePowerReward() (abi.TokenAmount, error) { return s.State.TotalMined, nil } @@ -24,6 +32,14 @@ func (s *v0State) EffectiveBaselinePower() (abi.StoragePower, error) { return s.State.EffectiveBaselinePower, nil } -func (s *v0State) ThisEpochBaselinePower() (abi.StoragePower, error) { - return s.State.ThisEpochBaselinePower, nil +func (s *v0State) EffectiveNetworkTime() (abi.ChainEpoch, error) { + return s.State.EffectiveNetworkTime, nil +} + +func (s *v0State) CumsumBaseline() (abi.StoragePower, error) { + return s.State.CumsumBaseline, nil +} + +func (s *v0State) CumsumRealized() (abi.StoragePower, error) { + return s.State.CumsumBaseline, nil } diff --git a/cmd/lotus-chainwatch/processor/common_actors.go b/cmd/lotus-chainwatch/processor/common_actors.go index d6aec7f90..56520880c 100644 --- a/cmd/lotus-chainwatch/processor/common_actors.go +++ b/cmd/lotus-chainwatch/processor/common_actors.go @@ -1,7 +1,6 @@ package processor import ( - "bytes" "context" "time" @@ -9,14 +8,13 @@ import ( "golang.org/x/xerrors" "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + _init "github.com/filecoin-project/lotus/chain/actors/builtin/init" "github.com/filecoin-project/lotus/chain/events/state" "github.com/filecoin-project/lotus/chain/types" cw_util "github.com/filecoin-project/lotus/cmd/lotus-chainwatch/util" "github.com/filecoin-project/specs-actors/actors/builtin" - _init "github.com/filecoin-project/specs-actors/actors/builtin/init" - "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/ipfs/go-cid" - typegen "github.com/whyrusleeping/cbor-gen" ) func (p *Processor) setupCommonActors() error { @@ -150,32 +148,17 @@ func (p Processor) storeActorAddresses(ctx context.Context, actors map[cid.Cid]A return err } - initActorRaw, err := p.node.ChainReadObj(ctx, initActor.Head) - if err != nil { - return err - } - - var initActorState _init.State - if err := initActorState.UnmarshalCBOR(bytes.NewReader(initActorRaw)); err != nil { - return err - } - ctxStore := cw_util.NewAPIIpldStore(ctx, p.node) - addrMap, err := adt.AsMap(ctxStore, initActorState.AddressMap) + initActorState, err := _init.Load(cw_util.NewAPIIpldStore(ctx, p.node), initActor) if err != nil { return err } // gross.. - var actorID typegen.CborInt - if err := addrMap.ForEach(&actorID, func(key string) error { - longAddr, err := address.NewFromBytes([]byte(key)) + if err := initActorState.ForEachActor(func(id abi.ActorID, addr address.Address) error { + idAddr, err := address.NewIDAddress(uint64(id)) if err != nil { return err } - shortAddr, err := address.NewIDAddress(uint64(actorID)) - if err != nil { - return err - } - addressToID[longAddr] = shortAddr + addressToID[addr] = idAddr return nil }); err != nil { return err diff --git a/cmd/lotus-chainwatch/processor/miner.go b/cmd/lotus-chainwatch/processor/miner.go index 1fd2a119f..17eef3afa 100644 --- a/cmd/lotus-chainwatch/processor/miner.go +++ b/cmd/lotus-chainwatch/processor/miner.go @@ -1,9 +1,7 @@ package processor import ( - "bytes" "context" - "fmt" "strings" "time" @@ -15,13 +13,11 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" - "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/power" - "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/api/apibstore" "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + "github.com/filecoin-project/lotus/chain/actors/builtin/power" "github.com/filecoin-project/lotus/chain/events/state" "github.com/filecoin-project/lotus/chain/store" "github.com/filecoin-project/lotus/chain/types" @@ -212,7 +208,7 @@ func (p *Processor) processMiners(ctx context.Context, minerTips map[types.TipSe // TODO add parallel calls if this becomes slow for tipset, miners := range minerTips { // get the power actors claims map - minersClaims, err := getPowerActorClaimsMap(ctx, p.node, tipset) + powerState, err := getPowerActorState(ctx, p.node, tipset) if err != nil { return nil, err } @@ -222,10 +218,9 @@ func (p *Processor) processMiners(ctx context.Context, minerTips map[types.TipSe var mi minerActorInfo mi.common = act - var claim power.Claim // get miner claim from power actors claim map and store if found, else the miner had no claim at // this tipset - found, err := minersClaims.Get(abi.AddrKey(act.addr), &claim) + claim, found, err := powerState.MinerPower(act.addr) if err != nil { return nil, err } @@ -1027,22 +1022,10 @@ func (p *Processor) storeMinersPower(miners []minerActorInfo) error { } // load the power actor state clam as an adt.Map at the tipset `ts`. -func getPowerActorClaimsMap(ctx context.Context, api api.FullNode, ts types.TipSetKey) (*adt.Map, error) { - powerActor, err := api.StateGetActor(ctx, builtin.StoragePowerActorAddr, ts) +func getPowerActorState(ctx context.Context, api api.FullNode, ts types.TipSetKey) (power.State, error) { + powerActor, err := api.StateGetActor(ctx, power.Address, ts) if err != nil { return nil, err } - - powerRaw, err := api.ChainReadObj(ctx, powerActor.Head) - if err != nil { - return nil, err - } - - var powerActorState power.State - if err := powerActorState.UnmarshalCBOR(bytes.NewReader(powerRaw)); err != nil { - return nil, fmt.Errorf("failed to unmarshal power actor state: %w", err) - } - - s := cw_util.NewAPIIpldStore(ctx, api) - return adt.AsMap(s, powerActorState.Claims) + return power.Load(cw_util.NewAPIIpldStore(ctx, api), powerActor) } diff --git a/cmd/lotus-chainwatch/processor/power.go b/cmd/lotus-chainwatch/processor/power.go index dfd7eddd7..403580e3b 100644 --- a/cmd/lotus-chainwatch/processor/power.go +++ b/cmd/lotus-chainwatch/processor/power.go @@ -1,16 +1,14 @@ package processor import ( - "bytes" "context" "time" "golang.org/x/xerrors" "github.com/filecoin-project/go-state-types/big" - "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/power" - "github.com/filecoin-project/specs-actors/actors/util/smoothing" + + "github.com/filecoin-project/lotus/chain/actors/builtin" ) type powerActorInfo struct { @@ -22,10 +20,7 @@ type powerActorInfo struct { totalQualityAdjustedBytesCommitted big.Int totalPledgeCollateral big.Int - newRawBytes big.Int - newQualityAdjustedBytes big.Int - newPledgeCollateral big.Int - newQAPowerSmoothed *smoothing.FilterEstimate + qaPowerSmoothed builtin.FilterEstimate minerCount int64 minerCountAboveMinimumPower int64 @@ -44,10 +39,6 @@ create table if not exists chain_power constraint power_smoothing_estimates_pk primary key, - new_raw_bytes_power text not null, - new_qa_bytes_power text not null, - new_pledge_collateral text not null, - total_raw_bytes_power text not null, total_raw_bytes_committed text not null, total_qa_bytes_power text not null, @@ -92,35 +83,49 @@ func (p *Processor) processPowerActors(ctx context.Context, powerTips ActorTips) var pw powerActorInfo pw.common = act - powerActor, err := p.node.StateGetActor(ctx, builtin.StoragePowerActorAddr, tipset) + powerActorState, err := getPowerActorState(ctx, p.node, tipset) if err != nil { return nil, xerrors.Errorf("get power state (@ %s): %w", pw.common.stateroot.String(), err) } - powerStateRaw, err := p.node.ChainReadObj(ctx, powerActor.Head) - if err != nil { - return nil, xerrors.Errorf("read state obj (@ %s): %w", pw.common.stateroot.String(), err) + if totalPower, err := powerActorState.TotalPower(); err != nil { + return nil, xerrors.Errorf("failed to compute total power: %w", err) + } else { + pw.totalRawBytes = totalPower.RawBytePower + pw.totalQualityAdjustedBytes = totalPower.QualityAdjPower } - var powerActorState power.State - if err := powerActorState.UnmarshalCBOR(bytes.NewReader(powerStateRaw)); err != nil { - return nil, xerrors.Errorf("unmarshal state (@ %s): %w", pw.common.stateroot.String(), err) + if totalCommitted, err := powerActorState.TotalCommitted(); err != nil { + return nil, xerrors.Errorf("failed to compute total committed: %w", err) + } else { + pw.totalRawBytesCommitted = totalCommitted.RawBytePower + pw.totalQualityAdjustedBytesCommitted = totalCommitted.QualityAdjPower } - pw.totalRawBytes = powerActorState.TotalRawBytePower - pw.totalRawBytesCommitted = powerActorState.TotalBytesCommitted - pw.totalQualityAdjustedBytes = powerActorState.TotalQualityAdjPower - pw.totalQualityAdjustedBytesCommitted = powerActorState.TotalQABytesCommitted - pw.totalPledgeCollateral = powerActorState.TotalPledgeCollateral + if totalLocked, err := powerActorState.TotalLocked(); err != nil { + return nil, xerrors.Errorf("failed to compute total locked: %w", err) + } else { + pw.totalPledgeCollateral = totalLocked + } - pw.newRawBytes = powerActorState.ThisEpochRawBytePower - pw.newQualityAdjustedBytes = powerActorState.ThisEpochQualityAdjPower - pw.newPledgeCollateral = powerActorState.ThisEpochPledgeCollateral - pw.newQAPowerSmoothed = powerActorState.ThisEpochQAPowerSmoothed + if powerSmoothed, err := powerActorState.TotalPowerSmoothed(); err != nil { + return nil, xerrors.Errorf("failed to determine smoothed power: %w", err) + } else { + pw.qaPowerSmoothed = powerSmoothed + } - pw.minerCount = powerActorState.MinerCount - pw.minerCountAboveMinimumPower = powerActorState.MinerAboveMinPowerCount - out = append(out, pw) + // NOTE: this doesn't set new* fields. Previously, we + // filled these using ThisEpoch* fields from the actor + // state, but these fields are effectively internal + // state and don't represent "new" power, as was + // assumed. + + if participating, total, err := powerActorState.MinerCounts(); err != nil { + return nil, xerrors.Errorf("failed to count miners: %w", err) + } else { + pw.minerCountAboveMinimumPower = int64(participating) + pw.minerCount = int64(total) + } } } @@ -142,7 +147,7 @@ func (p *Processor) storePowerSmoothingEstimates(powerStates []powerActorInfo) e return xerrors.Errorf("prep chain_power: %w", err) } - stmt, err := tx.Prepare(`copy cp (state_root, new_raw_bytes_power, new_qa_bytes_power, new_pledge_collateral, total_raw_bytes_power, total_raw_bytes_committed, total_qa_bytes_power, total_qa_bytes_committed, total_pledge_collateral, qa_smoothed_position_estimate, qa_smoothed_velocity_estimate, miner_count, minimum_consensus_miner_count) from stdin;`) + stmt, err := tx.Prepare(`copy cp (state_root, total_raw_bytes_power, total_raw_bytes_committed, total_qa_bytes_power, total_qa_bytes_committed, total_pledge_collateral, qa_smoothed_position_estimate, qa_smoothed_velocity_estimate, miner_count, minimum_consensus_miner_count) from stdin;`) if err != nil { return xerrors.Errorf("prepare tmp chain_power: %w", err) } @@ -150,9 +155,6 @@ func (p *Processor) storePowerSmoothingEstimates(powerStates []powerActorInfo) e for _, ps := range powerStates { if _, err := stmt.Exec( ps.common.stateroot.String(), - ps.newRawBytes.String(), - ps.newQualityAdjustedBytes.String(), - ps.newPledgeCollateral.String(), ps.totalRawBytes.String(), ps.totalRawBytesCommitted.String(), @@ -160,8 +162,8 @@ func (p *Processor) storePowerSmoothingEstimates(powerStates []powerActorInfo) e ps.totalQualityAdjustedBytesCommitted.String(), ps.totalPledgeCollateral.String(), - ps.newQAPowerSmoothed.PositionEstimate.String(), - ps.newQAPowerSmoothed.VelocityEstimate.String(), + ps.qaPowerSmoothed.PositionEstimate.String(), + ps.qaPowerSmoothed.VelocityEstimate.String(), ps.minerCount, ps.minerCountAboveMinimumPower, diff --git a/cmd/lotus-chainwatch/processor/reward.go b/cmd/lotus-chainwatch/processor/reward.go index 5bdb478df..35d4bbf01 100644 --- a/cmd/lotus-chainwatch/processor/reward.go +++ b/cmd/lotus-chainwatch/processor/reward.go @@ -1,18 +1,18 @@ package processor import ( - "bytes" "context" "time" "golang.org/x/xerrors" "github.com/filecoin-project/go-state-types/big" - "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/reward" - "github.com/filecoin-project/specs-actors/actors/util/smoothing" + "github.com/filecoin-project/lotus/chain/actors/builtin" + "github.com/filecoin-project/lotus/chain/actors/builtin/reward" "github.com/filecoin-project/lotus/chain/types" + + cw_util "github.com/filecoin-project/lotus/cmd/lotus-chainwatch/util" ) type rewardActorInfo struct { @@ -24,13 +24,66 @@ type rewardActorInfo struct { effectiveNetworkTime int64 effectiveBaselinePower big.Int + // NOTE: These variables are wrong. Talk to @ZX about fixing. These _do + // not_ represent "new" anything. newBaselinePower big.Int newBaseReward big.Int - newSmoothingEstimate *smoothing.FilterEstimate + newSmoothingEstimate builtin.FilterEstimate totalMinedReward big.Int } +func (rw *rewardActorInfo) set(s reward.State) error { + if p, err := s.CumsumBaseline(); err != nil { + return xerrors.Errorf("getting cumsum baseline power (@ %s): %w", rw.common.stateroot.String(), err) + } else { + rw.cumSumBaselinePower = p + } + + if p, err := s.CumsumRealized(); err != nil { + return xerrors.Errorf("getting cumsum realized power (@ %s): %w", rw.common.stateroot.String(), err) + } else { + rw.cumSumRealizedPower = p + } + + if t, err := s.EffectiveNetworkTime(); err != nil { + return xerrors.Errorf("getting effective network time (@ %s): %w", rw.common.stateroot.String(), err) + } else { + rw.effectiveNetworkTime = int64(t) + } + + if p, err := s.EffectiveBaselinePower(); err != nil { + return xerrors.Errorf("getting effective baseline power (@ %s): %w", rw.common.stateroot.String(), err) + } else { + rw.effectiveBaselinePower = p + } + + if t, err := s.TotalStoragePowerReward(); err != nil { + return xerrors.Errorf("getting total mined (@ %s): %w", rw.common.stateroot.String(), err) + } else { + rw.totalMinedReward = t + } + + if p, err := s.ThisEpochBaselinePower(); err != nil { + return xerrors.Errorf("getting this epoch baseline power (@ %s): %w", rw.common.stateroot.String(), err) + } else { + rw.newBaselinePower = p + } + + if t, err := s.ThisEpochReward(); err != nil { + return xerrors.Errorf("getting this epoch baseline power (@ %s): %w", rw.common.stateroot.String(), err) + } else { + rw.newBaseReward = t + } + + if e, err := s.ThisEpochRewardSmoothed(); err != nil { + return xerrors.Errorf("getting this epoch baseline power (@ %s): %w", rw.common.stateroot.String(), err) + } else { + rw.newSmoothingEstimate = e + } + return nil +} + func (p *Processor) setupRewards() error { tx, err := p.db.Begin() if err != nil { @@ -89,29 +142,19 @@ func (p *Processor) processRewardActors(ctx context.Context, rewardTips ActorTip rw.common = act // get reward actor states at each tipset once for all updates - rewardActor, err := p.node.StateGetActor(ctx, builtin.RewardActorAddr, tipset) + rewardActor, err := p.node.StateGetActor(ctx, reward.Address, tipset) if err != nil { return nil, xerrors.Errorf("get reward state (@ %s): %w", rw.common.stateroot.String(), err) } - rewardStateRaw, err := p.node.ChainReadObj(ctx, rewardActor.Head) + rewardActorState, err := reward.Load(cw_util.NewAPIIpldStore(ctx, p.node), rewardActor) if err != nil { return nil, xerrors.Errorf("read state obj (@ %s): %w", rw.common.stateroot.String(), err) } - - var rewardActorState reward.State - if err := rewardActorState.UnmarshalCBOR(bytes.NewReader(rewardStateRaw)); err != nil { - return nil, xerrors.Errorf("unmarshal state (@ %s): %w", rw.common.stateroot.String(), err) + if err := rw.set(rewardActorState); err != nil { + return nil, err } - rw.cumSumBaselinePower = rewardActorState.CumsumBaseline - rw.cumSumRealizedPower = rewardActorState.CumsumRealized - rw.effectiveNetworkTime = int64(rewardActorState.EffectiveNetworkTime) - rw.effectiveBaselinePower = rewardActorState.EffectiveBaselinePower - rw.newBaselinePower = rewardActorState.ThisEpochBaselinePower - rw.newBaseReward = rewardActorState.ThisEpochReward - rw.newSmoothingEstimate = rewardActorState.ThisEpochRewardSmoothed - rw.totalMinedReward = rewardActorState.TotalMined out = append(out, rw) } } @@ -126,29 +169,19 @@ func (p *Processor) processRewardActors(ctx context.Context, rewardTips ActorTip rw.common.stateroot = tipset.ParentState() rw.common.parentTsKey = tipset.Parents() // get reward actor states at each tipset once for all updates - rewardActor, err := p.node.StateGetActor(ctx, builtin.RewardActorAddr, tsKey) + rewardActor, err := p.node.StateGetActor(ctx, reward.Address, tsKey) if err != nil { return nil, err } - rewardStateRaw, err := p.node.ChainReadObj(ctx, rewardActor.Head) + rewardActorState, err := reward.Load(cw_util.NewAPIIpldStore(ctx, p.node), rewardActor) if err != nil { - return nil, err + return nil, xerrors.Errorf("read state obj (@ %s): %w", rw.common.stateroot.String(), err) } - var rewardActorState reward.State - if err := rewardActorState.UnmarshalCBOR(bytes.NewReader(rewardStateRaw)); err != nil { + if err := rw.set(rewardActorState); err != nil { return nil, err } - - rw.cumSumBaselinePower = rewardActorState.CumsumBaseline - rw.cumSumRealizedPower = rewardActorState.CumsumRealized - rw.effectiveNetworkTime = int64(rewardActorState.EffectiveNetworkTime) - rw.effectiveBaselinePower = rewardActorState.EffectiveBaselinePower - rw.newBaselinePower = rewardActorState.ThisEpochBaselinePower - rw.newBaseReward = rewardActorState.ThisEpochReward - rw.newSmoothingEstimate = rewardActorState.ThisEpochRewardSmoothed - rw.totalMinedReward = rewardActorState.TotalMined out = append(out, rw) } diff --git a/node/impl/full/state.go b/node/impl/full/state.go index 05fcc5171..3bed0dfbb 100644 --- a/node/impl/full/state.go +++ b/node/impl/full/state.go @@ -940,7 +940,7 @@ func (a *StateAPI) StateMinerPreCommitDepositForPower(ctx context.Context, maddr return types.EmptyInt, xerrors.Errorf("loading miner actor: %w", err) } else if s, err := reward.Load(store, act); err != nil { return types.EmptyInt, xerrors.Errorf("loading reward actor state: %w", err) - } else if r, err := s.RewardSmoothed(); err != nil { + } else if r, err := s.ThisEpochRewardSmoothed(); err != nil { return types.EmptyInt, xerrors.Errorf("failed to determine total reward: %w", err) } else { rewardSmoothed = r @@ -1011,7 +1011,7 @@ func (a *StateAPI) StateMinerInitialPledgeCollateral(ctx context.Context, maddr return types.EmptyInt, xerrors.Errorf("loading miner actor: %w", err) } else if s, err := reward.Load(store, act); err != nil { return types.EmptyInt, xerrors.Errorf("loading reward actor state: %w", err) - } else if r, err := s.RewardSmoothed(); err != nil { + } else if r, err := s.ThisEpochRewardSmoothed(); err != nil { return types.EmptyInt, xerrors.Errorf("failed to determine total reward: %w", err) } else if p, err := s.ThisEpochBaselinePower(); err != nil { return types.EmptyInt, xerrors.Errorf("failed to determine baseline power: %w", err) From 298efa221cf8908e7aefb2476b997420e18c554a Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Fri, 18 Sep 2020 13:52:07 -0700 Subject: [PATCH 099/303] fix lint errors --- cmd/lotus-chainwatch/processor/power.go | 37 ++++++++++--------- cmd/lotus-chainwatch/processor/reward.go | 47 ++++++++++-------------- 2 files changed, 39 insertions(+), 45 deletions(-) diff --git a/cmd/lotus-chainwatch/processor/power.go b/cmd/lotus-chainwatch/processor/power.go index 403580e3b..726a46706 100644 --- a/cmd/lotus-chainwatch/processor/power.go +++ b/cmd/lotus-chainwatch/processor/power.go @@ -88,30 +88,24 @@ func (p *Processor) processPowerActors(ctx context.Context, powerTips ActorTips) return nil, xerrors.Errorf("get power state (@ %s): %w", pw.common.stateroot.String(), err) } - if totalPower, err := powerActorState.TotalPower(); err != nil { + totalPower, err := powerActorState.TotalPower() + if err != nil { return nil, xerrors.Errorf("failed to compute total power: %w", err) - } else { - pw.totalRawBytes = totalPower.RawBytePower - pw.totalQualityAdjustedBytes = totalPower.QualityAdjPower } - if totalCommitted, err := powerActorState.TotalCommitted(); err != nil { + totalCommitted, err := powerActorState.TotalCommitted() + if err != nil { return nil, xerrors.Errorf("failed to compute total committed: %w", err) - } else { - pw.totalRawBytesCommitted = totalCommitted.RawBytePower - pw.totalQualityAdjustedBytesCommitted = totalCommitted.QualityAdjPower } - if totalLocked, err := powerActorState.TotalLocked(); err != nil { + totalLocked, err := powerActorState.TotalLocked() + if err != nil { return nil, xerrors.Errorf("failed to compute total locked: %w", err) - } else { - pw.totalPledgeCollateral = totalLocked } - if powerSmoothed, err := powerActorState.TotalPowerSmoothed(); err != nil { + powerSmoothed, err := powerActorState.TotalPowerSmoothed() + if err != nil { return nil, xerrors.Errorf("failed to determine smoothed power: %w", err) - } else { - pw.qaPowerSmoothed = powerSmoothed } // NOTE: this doesn't set new* fields. Previously, we @@ -120,12 +114,19 @@ func (p *Processor) processPowerActors(ctx context.Context, powerTips ActorTips) // state and don't represent "new" power, as was // assumed. - if participating, total, err := powerActorState.MinerCounts(); err != nil { + participatingMiners, totalMiners, err := powerActorState.MinerCounts() + if err != nil { return nil, xerrors.Errorf("failed to count miners: %w", err) - } else { - pw.minerCountAboveMinimumPower = int64(participating) - pw.minerCount = int64(total) } + + pw.totalRawBytes = totalPower.RawBytePower + pw.totalQualityAdjustedBytes = totalPower.QualityAdjPower + pw.totalRawBytesCommitted = totalCommitted.RawBytePower + pw.totalQualityAdjustedBytesCommitted = totalCommitted.QualityAdjPower + pw.totalPledgeCollateral = totalLocked + pw.qaPowerSmoothed = powerSmoothed + pw.minerCountAboveMinimumPower = int64(participatingMiners) + pw.minerCount = int64(totalMiners) } } diff --git a/cmd/lotus-chainwatch/processor/reward.go b/cmd/lotus-chainwatch/processor/reward.go index 35d4bbf01..72a329c87 100644 --- a/cmd/lotus-chainwatch/processor/reward.go +++ b/cmd/lotus-chainwatch/processor/reward.go @@ -6,6 +6,7 @@ import ( "golang.org/x/xerrors" + "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/lotus/chain/actors/builtin" @@ -21,7 +22,7 @@ type rewardActorInfo struct { cumSumBaselinePower big.Int cumSumRealizedPower big.Int - effectiveNetworkTime int64 + effectiveNetworkTime abi.ChainEpoch effectiveBaselinePower big.Int // NOTE: These variables are wrong. Talk to @ZX about fixing. These _do @@ -33,53 +34,45 @@ type rewardActorInfo struct { totalMinedReward big.Int } -func (rw *rewardActorInfo) set(s reward.State) error { - if p, err := s.CumsumBaseline(); err != nil { +func (rw *rewardActorInfo) set(s reward.State) (err error) { + rw.cumSumBaselinePower, err = s.CumsumBaseline() + if err != nil { return xerrors.Errorf("getting cumsum baseline power (@ %s): %w", rw.common.stateroot.String(), err) - } else { - rw.cumSumBaselinePower = p } - if p, err := s.CumsumRealized(); err != nil { + rw.cumSumRealizedPower, err = s.CumsumRealized() + if err != nil { return xerrors.Errorf("getting cumsum realized power (@ %s): %w", rw.common.stateroot.String(), err) - } else { - rw.cumSumRealizedPower = p } - if t, err := s.EffectiveNetworkTime(); err != nil { + rw.effectiveNetworkTime, err = s.EffectiveNetworkTime() + if err != nil { return xerrors.Errorf("getting effective network time (@ %s): %w", rw.common.stateroot.String(), err) - } else { - rw.effectiveNetworkTime = int64(t) } - if p, err := s.EffectiveBaselinePower(); err != nil { + rw.effectiveBaselinePower, err = s.EffectiveBaselinePower() + if err != nil { return xerrors.Errorf("getting effective baseline power (@ %s): %w", rw.common.stateroot.String(), err) - } else { - rw.effectiveBaselinePower = p } - if t, err := s.TotalStoragePowerReward(); err != nil { + rw.totalMinedReward, err = s.TotalStoragePowerReward() + if err != nil { return xerrors.Errorf("getting total mined (@ %s): %w", rw.common.stateroot.String(), err) - } else { - rw.totalMinedReward = t } - if p, err := s.ThisEpochBaselinePower(); err != nil { + rw.newBaselinePower, err = s.ThisEpochBaselinePower() + if err != nil { return xerrors.Errorf("getting this epoch baseline power (@ %s): %w", rw.common.stateroot.String(), err) - } else { - rw.newBaselinePower = p } - if t, err := s.ThisEpochReward(); err != nil { + rw.newBaseReward, err = s.ThisEpochReward() + if err != nil { return xerrors.Errorf("getting this epoch baseline power (@ %s): %w", rw.common.stateroot.String(), err) - } else { - rw.newBaseReward = t } - if e, err := s.ThisEpochRewardSmoothed(); err != nil { + rw.newSmoothingEstimate, err = s.ThisEpochRewardSmoothed() + if err != nil { return xerrors.Errorf("getting this epoch baseline power (@ %s): %w", rw.common.stateroot.String(), err) - } else { - rw.newSmoothingEstimate = e } return nil } @@ -213,7 +206,7 @@ func (p *Processor) persistRewardActors(ctx context.Context, rewards []rewardAct rewardState.common.stateroot.String(), rewardState.cumSumBaselinePower.String(), rewardState.cumSumRealizedPower.String(), - rewardState.effectiveNetworkTime, + uint64(rewardState.effectiveNetworkTime), rewardState.effectiveBaselinePower.String(), rewardState.newBaselinePower.String(), rewardState.newBaseReward.String(), From 8747c6083e6ecc1c60620c8dcf67bb07a304d8d4 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Fri, 18 Sep 2020 14:20:53 -0700 Subject: [PATCH 100/303] abstract over account actor --- chain/actors/builtin/account/account.go | 31 +++++++++++++++++++++++++ chain/actors/builtin/account/v0.go | 16 +++++++++++++ chain/vm/vm.go | 13 ++++------- 3 files changed, 52 insertions(+), 8 deletions(-) create mode 100644 chain/actors/builtin/account/account.go create mode 100644 chain/actors/builtin/account/v0.go diff --git a/chain/actors/builtin/account/account.go b/chain/actors/builtin/account/account.go new file mode 100644 index 000000000..d4cbe4177 --- /dev/null +++ b/chain/actors/builtin/account/account.go @@ -0,0 +1,31 @@ +package account + +import ( + "golang.org/x/xerrors" + + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/cbor" + v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" + + "github.com/filecoin-project/lotus/chain/actors/adt" + "github.com/filecoin-project/lotus/chain/types" +) + +func Load(store adt.Store, act *types.Actor) (State, error) { + switch act.Code { + case v0builtin.AccountActorCodeID: + out := v0State{store: store} + err := store.Get(store.Context(), act.Head, &out) + if err != nil { + return nil, err + } + return &out, nil + } + return nil, xerrors.Errorf("unknown actor code %s", act.Code) +} + +type State interface { + cbor.Marshaler + + PubkeyAddress() (address.Address, error) +} diff --git a/chain/actors/builtin/account/v0.go b/chain/actors/builtin/account/v0.go new file mode 100644 index 000000000..6001dd7bf --- /dev/null +++ b/chain/actors/builtin/account/v0.go @@ -0,0 +1,16 @@ +package account + +import ( + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/lotus/chain/actors/adt" + "github.com/filecoin-project/specs-actors/actors/builtin/account" +) + +type v0State struct { + account.State + store adt.Store +} + +func (s *v0State) PubkeyAddress() (address.Address, error) { + return s.Address, nil +} diff --git a/chain/vm/vm.go b/chain/vm/vm.go index 542dfee69..25c937ca3 100644 --- a/chain/vm/vm.go +++ b/chain/vm/vm.go @@ -23,10 +23,11 @@ import ( "github.com/filecoin-project/go-state-types/exitcode" "github.com/filecoin-project/go-state-types/network" "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/account" "github.com/filecoin-project/lotus/build" + "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/actors/aerrors" + "github.com/filecoin-project/lotus/chain/actors/builtin/account" "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/lib/blockstore" @@ -49,16 +50,12 @@ func ResolveToKeyAddr(state types.StateTree, cst cbor.IpldStore, addr address.Ad return address.Undef, xerrors.Errorf("failed to find actor: %s", addr) } - if act.Code != builtin.AccountActorCodeID { - return address.Undef, xerrors.Errorf("address %s was not for an account actor", addr) - } - - var aast account.State - if err := cst.Get(context.TODO(), act.Head, &aast); err != nil { + aast, err := account.Load(adt.WrapStore(context.TODO(), cst), act) + if err != nil { return address.Undef, xerrors.Errorf("failed to get account actor state for %s: %w", addr, err) } - return aast.Address, nil + return aast.PubkeyAddress() } var _ cbor.IpldBlockstore = (*gasChargingBlocks)(nil) From 24df873498f0af9ec38672a7c6c9024ec6546b5f Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Fri, 18 Sep 2020 14:21:05 -0700 Subject: [PATCH 101/303] rename imports --- chain/vm/invoker.go | 54 ++++++++++++++++++++++----------------------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/chain/vm/invoker.go b/chain/vm/invoker.go index b31b45767..501b933e2 100644 --- a/chain/vm/invoker.go +++ b/chain/vm/invoker.go @@ -6,28 +6,28 @@ import ( "fmt" "reflect" - "github.com/filecoin-project/go-state-types/exitcode" - "github.com/filecoin-project/specs-actors/actors/builtin/account" - v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" - "github.com/ipfs/go-cid" cbg "github.com/whyrusleeping/cbor-gen" "golang.org/x/xerrors" - "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/lotus/chain/actors/aerrors" - "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/cron" - init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" - "github.com/filecoin-project/specs-actors/actors/builtin/market" + v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" + v0account "github.com/filecoin-project/specs-actors/actors/builtin/account" + v0cron "github.com/filecoin-project/specs-actors/actors/builtin/cron" + v0init "github.com/filecoin-project/specs-actors/actors/builtin/init" + v0market "github.com/filecoin-project/specs-actors/actors/builtin/market" v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" v0msig "github.com/filecoin-project/specs-actors/actors/builtin/multisig" - "github.com/filecoin-project/specs-actors/actors/builtin/paych" + v0paych "github.com/filecoin-project/specs-actors/actors/builtin/paych" v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" v0reward "github.com/filecoin-project/specs-actors/actors/builtin/reward" - "github.com/filecoin-project/specs-actors/actors/builtin/system" - "github.com/filecoin-project/specs-actors/actors/runtime" + v0system "github.com/filecoin-project/specs-actors/actors/builtin/system" + v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" vmr "github.com/filecoin-project/specs-actors/actors/runtime" + + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/exitcode" + + "github.com/filecoin-project/lotus/chain/actors/aerrors" ) type Invoker struct { @@ -35,7 +35,7 @@ type Invoker struct { builtInState map[cid.Cid]reflect.Type } -type invokeFunc func(rt runtime.Runtime, params []byte) ([]byte, aerrors.ActorError) +type invokeFunc func(rt vmr.Runtime, params []byte) ([]byte, aerrors.ActorError) type nativeCode []invokeFunc func NewInvoker() *Invoker { @@ -46,22 +46,22 @@ func NewInvoker() *Invoker { // add builtInCode using: register(cid, singleton) // NETUPGRADE: register code IDs for v2, etc. - inv.Register(builtin.SystemActorCodeID, system.Actor{}, abi.EmptyValue{}) - inv.Register(builtin.InitActorCodeID, init_.Actor{}, init_.State{}) - inv.Register(builtin.RewardActorCodeID, v0reward.Actor{}, v0reward.State{}) - inv.Register(builtin.CronActorCodeID, cron.Actor{}, cron.State{}) - inv.Register(builtin.StoragePowerActorCodeID, v0power.Actor{}, v0power.State{}) - inv.Register(builtin.StorageMarketActorCodeID, market.Actor{}, market.State{}) - inv.Register(builtin.StorageMinerActorCodeID, v0miner.Actor{}, v0miner.State{}) - inv.Register(builtin.MultisigActorCodeID, v0msig.Actor{}, v0msig.State{}) - inv.Register(builtin.PaymentChannelActorCodeID, paych.Actor{}, paych.State{}) - inv.Register(builtin.VerifiedRegistryActorCodeID, v0verifreg.Actor{}, v0verifreg.State{}) - inv.Register(builtin.AccountActorCodeID, account.Actor{}, account.State{}) + inv.Register(v0builtin.SystemActorCodeID, v0system.Actor{}, abi.EmptyValue{}) + inv.Register(v0builtin.InitActorCodeID, v0init.Actor{}, v0init.State{}) + inv.Register(v0builtin.RewardActorCodeID, v0reward.Actor{}, v0reward.State{}) + inv.Register(v0builtin.CronActorCodeID, v0cron.Actor{}, v0cron.State{}) + inv.Register(v0builtin.StoragePowerActorCodeID, v0power.Actor{}, v0power.State{}) + inv.Register(v0builtin.StorageMarketActorCodeID, v0market.Actor{}, v0market.State{}) + inv.Register(v0builtin.StorageMinerActorCodeID, v0miner.Actor{}, v0miner.State{}) + inv.Register(v0builtin.MultisigActorCodeID, v0msig.Actor{}, v0msig.State{}) + inv.Register(v0builtin.PaymentChannelActorCodeID, v0paych.Actor{}, v0paych.State{}) + inv.Register(v0builtin.VerifiedRegistryActorCodeID, v0verifreg.Actor{}, v0verifreg.State{}) + inv.Register(v0builtin.AccountActorCodeID, v0account.Actor{}, v0account.State{}) return inv } -func (inv *Invoker) Invoke(codeCid cid.Cid, rt runtime.Runtime, method abi.MethodNum, params []byte) ([]byte, aerrors.ActorError) { +func (inv *Invoker) Invoke(codeCid cid.Cid, rt vmr.Runtime, method abi.MethodNum, params []byte) ([]byte, aerrors.ActorError) { code, ok := inv.builtInCode[codeCid] if !ok { @@ -177,7 +177,7 @@ func DecodeParams(b []byte, out interface{}) error { } func DumpActorState(code cid.Cid, b []byte) (interface{}, error) { - if code == builtin.AccountActorCodeID { // Account code special case + if code == v0builtin.AccountActorCodeID { // Account code special case return nil, nil } From e60027c00af38a2dee6b3de14c4f28a582b21069 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Fri, 18 Sep 2020 14:22:38 -0700 Subject: [PATCH 102/303] remove todo --- chain/stmgr/stmgr.go | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/chain/stmgr/stmgr.go b/chain/stmgr/stmgr.go index fee76369a..d183b7ce2 100644 --- a/chain/stmgr/stmgr.go +++ b/chain/stmgr/stmgr.go @@ -1183,9 +1183,7 @@ func (sm *StateManager) GetMarketState(ctx context.Context, ts *types.TipSet) (m return nil, err } - // TODO maybe there needs to be code here to differentiate address based on ts height? - addr := builtin.StorageMarketActorAddr - act, err := st.GetActor(addr) + act, err := st.GetActor(market.Address) if err != nil { return nil, err } From 8285eda8e507358f5a64080e3894573f6b5b131c Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Fri, 18 Sep 2020 14:46:42 -0700 Subject: [PATCH 103/303] migrate storage miner info --- chain/actors/builtin/miner/miner.go | 10 +++++++ chain/actors/builtin/miner/v0.go | 16 +++++++++++ cmd/lotus-storage-miner/info.go | 44 +++++++++++++---------------- 3 files changed, 45 insertions(+), 25 deletions(-) diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index 82dc002ca..c67e773bf 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -35,8 +35,12 @@ func Load(store adt.Store, act *types.Actor) (st State, err error) { type State interface { cbor.Marshaler + // Total available balance to spend. AvailableBalance(abi.TokenAmount) (abi.TokenAmount, error) + // Funds that will vest by the given epoch. VestedFunds(abi.ChainEpoch) (abi.TokenAmount, error) + // Funds locked for various reasons. + LockedFunds() (LockedFunds, error) GetSector(abi.SectorNumber) (*SectorOnChainInfo, error) FindSector(abi.SectorNumber) (*SectorLocation, error) @@ -138,3 +142,9 @@ type PreCommitChanges struct { Added []SectorPreCommitOnChainInfo Removed []SectorPreCommitOnChainInfo } + +type LockedFunds struct { + VestingFunds abi.TokenAmount + InitialPledgeRequirement abi.TokenAmount + PreCommitDeposits abi.TokenAmount +} diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index d333dff76..0f27d7d7f 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -40,6 +40,22 @@ func (s *v0State) VestedFunds(epoch abi.ChainEpoch) (abi.TokenAmount, error) { return s.CheckVestedFunds(s.store, epoch) } +func (s *v0State) LockedFunds() (LockedFunds, error) { + return LockedFunds{ + VestingFunds: s.State.LockedFunds, + InitialPledgeRequirement: s.State.InitialPledgeRequirement, + PreCommitDeposits: s.State.PreCommitDeposits, + }, nil +} + +func (s *v0State) InitialPledge() (abi.TokenAmount, error) { + return s.State.InitialPledgeRequirement, nil +} + +func (s *v0State) PreCommitDeposits() (abi.TokenAmount, error) { + return s.State.PreCommitDeposits, nil +} + func (s *v0State) GetSector(num abi.SectorNumber) (*SectorOnChainInfo, error) { info, ok, err := s.State.GetSector(s.store, num) if !ok || err != nil { diff --git a/cmd/lotus-storage-miner/info.go b/cmd/lotus-storage-miner/info.go index 3a7720c52..3ccfd67da 100644 --- a/cmd/lotus-storage-miner/info.go +++ b/cmd/lotus-storage-miner/info.go @@ -1,7 +1,6 @@ package main import ( - "bytes" "context" "fmt" "sort" @@ -16,12 +15,12 @@ import ( "github.com/filecoin-project/go-fil-markets/storagemarket" "github.com/filecoin-project/go-state-types/abi" sealing "github.com/filecoin-project/lotus/extern/storage-sealing" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/api/apibstore" "github.com/filecoin-project/lotus/build" + "github.com/filecoin-project/lotus/chain/actors/adt" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/types" lcli "github.com/filecoin-project/lotus/cli" "github.com/filecoin-project/lotus/lib/blockstore" @@ -54,11 +53,6 @@ func infoCmdAct(cctx *cli.Context) error { ctx := lcli.ReqContext(cctx) - head, err := api.ChainHead(ctx) - if err != nil { - return xerrors.Errorf("getting chain head: %w", err) - } - maddr, err := getActorAddress(ctx, nodeApi, cctx.String("actor")) if err != nil { return err @@ -68,15 +62,11 @@ func infoCmdAct(cctx *cli.Context) error { if err != nil { return err } - var mas miner.State - { - rmas, err := api.ChainReadObj(ctx, mact.Head) - if err != nil { - return err - } - if err := mas.UnmarshalCBOR(bytes.NewReader(rmas)); err != nil { - return err - } + + tbs := bufbstore.NewTieredBstore(apibstore.NewAPIBlockstore(api), blockstore.NewTemporary()) + mas, err := miner.Load(adt.WrapStore(ctx, cbor.NewCborStore(tbs)), mact) + if err != nil { + return err } fmt.Printf("Miner: %s\n", color.BlueString("%s", maddr)) @@ -172,17 +162,21 @@ func infoCmdAct(cctx *cli.Context) error { fmt.Printf("\tActive: %d, %s (Verified: %d, %s)\n", nactiveDeals, types.SizeStr(types.NewInt(uint64(activeDealBytes))), nVerifDeals, types.SizeStr(types.NewInt(uint64(activeVerifDealBytes)))) fmt.Println() - tbs := bufbstore.NewTieredBstore(apibstore.NewAPIBlockstore(api), blockstore.NewTemporary()) - _, err = mas.UnlockVestedFunds(adt.WrapStore(ctx, cbor.NewCborStore(tbs)), head.Height()) + // NOTE: there's no need to unlock anything here. Funds only + // vest on deadline boundaries, and they're unlocked by cron. + lockedFunds, err := mas.LockedFunds() if err != nil { - return xerrors.Errorf("calculating vested funds: %w", err) + return xerrors.Errorf("getting locked funds: %w", err) + } + availBalance, err := mas.AvailableBalance(mact.Balance) + if err != nil { + return xerrors.Errorf("getting available balance: %w", err) } - fmt.Printf("Miner Balance: %s\n", color.YellowString("%s", types.FIL(mact.Balance))) - fmt.Printf("\tPreCommit: %s\n", types.FIL(mas.PreCommitDeposits)) - fmt.Printf("\tPledge: %s\n", types.FIL(mas.InitialPledgeRequirement)) - fmt.Printf("\tLocked: %s\n", types.FIL(mas.LockedFunds)) - color.Green("\tAvailable: %s", types.FIL(mas.GetAvailableBalance(mact.Balance))) + fmt.Printf("\tPreCommit: %s\n", types.FIL(lockedFunds.PreCommitDeposits)) + fmt.Printf("\tPledge: %s\n", types.FIL(lockedFunds.InitialPledgeRequirement)) + fmt.Printf("\tVesting: %s\n", types.FIL(lockedFunds.VestingFunds)) + color.Green("\tAvailable: %s", types.FIL(availBalance)) wb, err := api.WalletBalance(ctx, mi.Worker) if err != nil { return xerrors.Errorf("getting worker balance: %w", err) From 4a7055c32874a08f13ec850e63480dd30a30e66c Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Fri, 18 Sep 2020 14:46:55 -0700 Subject: [PATCH 104/303] fix state loading in vm --- chain/vm/syscalls.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/chain/vm/syscalls.go b/chain/vm/syscalls.go index aab1812d9..a7f5dab0c 100644 --- a/chain/vm/syscalls.go +++ b/chain/vm/syscalls.go @@ -7,8 +7,6 @@ import ( goruntime "runtime" "sync" - "github.com/filecoin-project/lotus/chain/actors/builtin/miner" - "github.com/filecoin-project/specs-actors/actors/runtime/proof" "github.com/filecoin-project/go-address" @@ -20,6 +18,8 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/crypto" + "github.com/filecoin-project/lotus/chain/actors/adt" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/lib/sigs" @@ -192,8 +192,8 @@ func (ss *syscallShim) VerifyBlockSig(blk *types.BlockHeader) error { } // use that to get the miner state - var mas miner.State - if err = ss.cst.Get(ss.ctx, act.Head, &mas); err != nil { + mas, err := miner.Load(adt.WrapStore(ss.ctx, ss.cst), act) + if err != nil { return err } From f741ce6e3090fefe18d8d480a507b435b54d9fb5 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Fri, 18 Sep 2020 14:51:18 -0700 Subject: [PATCH 105/303] fixup some more imports --- cmd/lotus-storage-miner/actor.go | 11 ++++++----- cmd/lotus-storage-miner/init.go | 17 +++++++++-------- cmd/lotus-storage-miner/sectors.go | 3 +-- 3 files changed, 16 insertions(+), 15 deletions(-) diff --git a/cmd/lotus-storage-miner/actor.go b/cmd/lotus-storage-miner/actor.go index c84e006d7..2493c5a1e 100644 --- a/cmd/lotus-storage-miner/actor.go +++ b/cmd/lotus-storage-miner/actor.go @@ -14,8 +14,9 @@ import ( "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/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/actors" "github.com/filecoin-project/lotus/chain/types" @@ -87,7 +88,7 @@ var actorSetAddrsCmd = &cli.Command{ return err } - params, err := actors.SerializeParams(&miner.ChangeMultiaddrsParams{NewMultiaddrs: addrs}) + params, err := actors.SerializeParams(&v0miner.ChangeMultiaddrsParams{NewMultiaddrs: addrs}) if err != nil { return err } @@ -152,7 +153,7 @@ var actorSetPeeridCmd = &cli.Command{ return err } - params, err := actors.SerializeParams(&miner.ChangePeerIDParams{NewID: abi.PeerID(pid)}) + params, err := actors.SerializeParams(&v0miner.ChangePeerIDParams{NewID: abi.PeerID(pid)}) if err != nil { return err } @@ -225,7 +226,7 @@ var actorWithdrawCmd = &cli.Command{ } } - params, err := actors.SerializeParams(&miner.WithdrawBalanceParams{ + params, err := actors.SerializeParams(&v0miner.WithdrawBalanceParams{ AmountRequested: amount, // Default to attempting to withdraw all the extra funds in the miner actor }) if err != nil { @@ -450,7 +451,7 @@ var actorControlSet = &cli.Command{ return nil } - cwp := &miner.ChangeWorkerAddressParams{ + cwp := &v0miner.ChangeWorkerAddressParams{ NewWorker: mi.Worker, NewControlAddrs: toSet, } diff --git a/cmd/lotus-storage-miner/init.go b/cmd/lotus-storage-miner/init.go index 8325aae8b..715daead8 100644 --- a/cmd/lotus-storage-miner/init.go +++ b/cmd/lotus-storage-miner/init.go @@ -31,9 +31,10 @@ import ( sectorstorage "github.com/filecoin-project/lotus/extern/sector-storage" "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" "github.com/filecoin-project/lotus/extern/sector-storage/stores" - "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/market" - miner2 "github.com/filecoin-project/specs-actors/actors/builtin/miner" + + v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" + v0market "github.com/filecoin-project/specs-actors/actors/builtin/market" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" lapi "github.com/filecoin-project/lotus/api" @@ -372,7 +373,7 @@ func migratePreSealMeta(ctx context.Context, api lapi.FullNode, metadata string, return mds.Put(datastore.NewKey(modules.StorageCounterDSPrefix), buf[:size]) } -func findMarketDealID(ctx context.Context, api lapi.FullNode, deal market.DealProposal) (abi.DealID, error) { +func findMarketDealID(ctx context.Context, api lapi.FullNode, deal v0market.DealProposal) (abi.DealID, error) { // TODO: find a better way // (this is only used by genesis miners) @@ -566,7 +567,7 @@ func configureStorageMiner(ctx context.Context, api lapi.FullNode, addr address. return xerrors.Errorf("getWorkerAddr returned bad address: %w", err) } - enc, err := actors.SerializeParams(&miner2.ChangePeerIDParams{NewID: abi.PeerID(peerid)}) + enc, err := actors.SerializeParams(&v0miner.ChangePeerIDParams{NewID: abi.PeerID(peerid)}) if err != nil { return err } @@ -574,7 +575,7 @@ func configureStorageMiner(ctx context.Context, api lapi.FullNode, addr address. msg := &types.Message{ To: addr, From: mi.Worker, - Method: builtin.MethodsMiner.ChangePeerID, + Method: v0builtin.MethodsMiner.ChangePeerID, Params: enc, Value: types.NewInt(0), GasPremium: gasPrice, @@ -653,11 +654,11 @@ func createStorageMiner(ctx context.Context, api lapi.FullNode, peerid peer.ID, } createStorageMinerMsg := &types.Message{ - To: builtin.StoragePowerActorAddr, + To: v0builtin.StoragePowerActorAddr, From: sender, Value: big.Zero(), - Method: builtin.MethodsPower.CreateMiner, + Method: v0builtin.MethodsPower.CreateMiner, Params: params, GasLimit: 0, diff --git a/cmd/lotus-storage-miner/sectors.go b/cmd/lotus-storage-miner/sectors.go index 06f09fe20..032a68ac2 100644 --- a/cmd/lotus-storage-miner/sectors.go +++ b/cmd/lotus-storage-miner/sectors.go @@ -8,14 +8,13 @@ import ( "text/tabwriter" "time" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/urfave/cli/v2" "golang.org/x/xerrors" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/lotus/api" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/types" lcli "github.com/filecoin-project/lotus/cli" ) From c130806c374905ec8afa1c25d0201bd1c2c9fe48 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Fri, 18 Sep 2020 14:59:14 -0700 Subject: [PATCH 106/303] compile fix --- cmd/lotus-storage-miner/sectors.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cmd/lotus-storage-miner/sectors.go b/cmd/lotus-storage-miner/sectors.go index 032a68ac2..5659bed79 100644 --- a/cmd/lotus-storage-miner/sectors.go +++ b/cmd/lotus-storage-miner/sectors.go @@ -13,6 +13,8 @@ import ( "github.com/filecoin-project/go-state-types/abi" + v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/types" @@ -378,7 +380,7 @@ var sectorsCapacityCollateralCmd = &cli.Command{ Expiration: abi.ChainEpoch(cctx.Uint64("expiration")), } if pci.Expiration == 0 { - pci.Expiration = miner.MaxSectorExpirationExtension + pci.Expiration = v0miner.MaxSectorExpirationExtension } pc, err := nApi.StateMinerInitialPledgeCollateral(ctx, maddr, pci, types.EmptyTSK) if err != nil { From 1bf3b4989dae6ddde14ed8ae5d81b15057901c0f Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Fri, 18 Sep 2020 14:59:27 -0700 Subject: [PATCH 107/303] rename imports to match actors code `sed -i 's/\bv0\(\w\)\(\w*\)/\L\1\E\20/g' **/*.go` --- build/params_2k.go | 12 +-- build/params_shared_funcs.go | 6 +- build/params_shared_vals.go | 4 +- build/params_testground.go | 4 +- build/params_testnet.go | 8 +- chain/actors/adt/adt.go | 8 +- chain/actors/adt/diff_adt_test.go | 10 +- chain/actors/builtin/account/account.go | 6 +- chain/actors/builtin/account/v0.go | 4 +- chain/actors/builtin/builtin.go | 4 +- chain/actors/builtin/init/init.go | 8 +- chain/actors/builtin/init/v0.go | 14 +-- chain/actors/builtin/market/market.go | 8 +- chain/actors/builtin/market/v0.go | 106 +++++++++--------- chain/actors/builtin/miner/miner.go | 30 +++--- chain/actors/builtin/miner/v0.go | 120 ++++++++++----------- chain/actors/builtin/multisig/multisig.go | 6 +- chain/actors/builtin/multisig/v0.go | 10 +- chain/actors/builtin/paych/paych.go | 6 +- chain/actors/builtin/paych/v0.go | 30 +++--- chain/actors/builtin/power/power.go | 8 +- chain/actors/builtin/power/v0.go | 24 ++--- chain/actors/builtin/reward/reward.go | 8 +- chain/actors/builtin/reward/v0.go | 18 ++-- chain/actors/builtin/verifreg/v0.go | 12 +-- chain/actors/builtin/verifreg/verifreg.go | 8 +- chain/events/state/predicates.go | 4 +- chain/events/state/predicates_test.go | 78 +++++++------- chain/gen/gen.go | 4 +- chain/gen/gen_test.go | 12 +-- chain/gen/genesis/genesis.go | 60 +++++------ chain/gen/genesis/miners.go | 42 ++++---- chain/gen/genesis/t02_reward.go | 4 +- chain/gen/genesis/t04_power.go | 4 +- chain/gen/genesis/t06_vreg.go | 4 +- chain/stmgr/forks.go | 14 +-- chain/stmgr/forks_test.go | 12 +-- chain/stmgr/stmgr.go | 16 +-- chain/stmgr/utils.go | 30 +++--- chain/store/store_test.go | 12 +-- chain/sync_test.go | 12 +-- chain/vectors/gen/main.go | 8 +- chain/vm/invoker.go | 48 ++++----- cli/multisig.go | 14 +-- cli/paych_test.go | 12 +-- cmd/lotus-pcr/main.go | 4 +- cmd/lotus-storage-miner/actor.go | 10 +- cmd/lotus-storage-miner/init.go | 22 ++-- cmd/lotus-storage-miner/sectors.go | 4 +- extern/storage-sealing/checks.go | 8 +- extern/storage-sealing/constants.go | 4 +- extern/storage-sealing/precommit_policy.go | 4 +- extern/storage-sealing/sealing.go | 4 +- extern/storage-sealing/states_sealing.go | 8 +- node/impl/client/client.go | 4 +- node/impl/full/state.go | 14 +-- node/node_test.go | 14 +-- node/test/builder.go | 4 +- paychmgr/manager.go | 14 +-- paychmgr/paych.go | 22 ++-- paychmgr/paych_test.go | 36 +++---- paychmgr/simple.go | 4 +- storage/adapter_storage_miner.go | 4 +- storage/miner.go | 4 +- storage/wdpost_run_test.go | 8 +- 65 files changed, 534 insertions(+), 534 deletions(-) diff --git a/build/params_2k.go b/build/params_2k.go index 61c5fd71d..4a49da22b 100644 --- a/build/params_2k.go +++ b/build/params_2k.go @@ -5,9 +5,9 @@ package build import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" - v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" - v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" + power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" + verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" ) const UpgradeBreezeHeight = -1 @@ -20,11 +20,11 @@ var DrandSchedule = map[abi.ChainEpoch]DrandEnum{ } func init() { - v0power.ConsensusMinerMinPower = big.NewInt(2048) - v0miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ + power0.ConsensusMinerMinPower = big.NewInt(2048) + miner0.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } - v0verifreg.MinVerifiedDealSize = big.NewInt(256) + verifreg0.MinVerifiedDealSize = big.NewInt(256) BuildType |= Build2k } diff --git a/build/params_shared_funcs.go b/build/params_shared_funcs.go index 08f16cefd..0e9739914 100644 --- a/build/params_shared_funcs.go +++ b/build/params_shared_funcs.go @@ -6,14 +6,14 @@ import ( "github.com/libp2p/go-libp2p-core/protocol" "github.com/filecoin-project/go-state-types/abi" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/lotus/node/modules/dtypes" ) func DefaultSectorSize() abi.SectorSize { - szs := make([]abi.SectorSize, 0, len(v0miner.SupportedProofTypes)) - for spt := range v0miner.SupportedProofTypes { + szs := make([]abi.SectorSize, 0, len(miner0.SupportedProofTypes)) + for spt := range miner0.SupportedProofTypes { ss, err := spt.SectorSize() if err != nil { panic(err) diff --git a/build/params_shared_vals.go b/build/params_shared_vals.go index ac7796ae7..3ee9f52ec 100644 --- a/build/params_shared_vals.go +++ b/build/params_shared_vals.go @@ -9,7 +9,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/specs-actors/actors/builtin" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" ) // ///// @@ -32,7 +32,7 @@ const ForkLengthThreshold = Finality var BlocksPerEpoch = uint64(builtin.ExpectedLeadersPerEpoch) // Epochs -const Finality = v0miner.ChainFinality +const Finality = miner0.ChainFinality const MessageConfidence = uint64(5) // constants for Weight calculation diff --git a/build/params_testground.go b/build/params_testground.go index 1b30ae2e9..954b5ccfd 100644 --- a/build/params_testground.go +++ b/build/params_testground.go @@ -13,7 +13,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/network" "github.com/filecoin-project/specs-actors/actors/builtin" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" ) var ( @@ -32,7 +32,7 @@ var ( AllowableClockDriftSecs = uint64(1) - Finality = v0miner.ChainFinality + Finality = miner0.ChainFinality ForkLengthThreshold = Finality SlashablePowerDelay = 20 diff --git a/build/params_testnet.go b/build/params_testnet.go index a879d3ba7..108aba20c 100644 --- a/build/params_testnet.go +++ b/build/params_testnet.go @@ -8,8 +8,8 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/specs-actors/actors/builtin" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" - v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" + power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" ) var DrandSchedule = map[abi.ChainEpoch]DrandEnum{ @@ -23,8 +23,8 @@ const BreezeGasTampingDuration = 120 const UpgradeSmokeHeight = 51000 func init() { - v0power.ConsensusMinerMinPower = big.NewInt(10 << 40) - v0miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ + power0.ConsensusMinerMinPower = big.NewInt(10 << 40) + miner0.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg32GiBV1: {}, abi.RegisteredSealProof_StackedDrg64GiBV1: {}, } diff --git a/chain/actors/adt/adt.go b/chain/actors/adt/adt.go index ebf32c3c4..fd5ee3f87 100644 --- a/chain/actors/adt/adt.go +++ b/chain/actors/adt/adt.go @@ -8,7 +8,7 @@ import ( "github.com/filecoin-project/go-state-types/cbor" "github.com/filecoin-project/go-state-types/network" "github.com/filecoin-project/lotus/chain/actors/builtin" - v0adt "github.com/filecoin-project/specs-actors/actors/util/adt" + adt0 "github.com/filecoin-project/specs-actors/actors/util/adt" ) type Map interface { @@ -24,7 +24,7 @@ type Map interface { func AsMap(store Store, root cid.Cid, version builtin.Version) (Map, error) { switch version { case builtin.Version0: - return v0adt.AsMap(store, root) + return adt0.AsMap(store, root) } return nil, xerrors.Errorf("unknown network version: %d", version) } @@ -32,7 +32,7 @@ func AsMap(store Store, root cid.Cid, version builtin.Version) (Map, error) { func NewMap(store Store, version builtin.Version) (Map, error) { switch version { case builtin.Version0: - return v0adt.MakeEmptyMap(store), nil + return adt0.MakeEmptyMap(store), nil } return nil, xerrors.Errorf("unknown network version: %d", version) } @@ -51,7 +51,7 @@ type Array interface { func AsArray(store Store, root cid.Cid, version network.Version) (Array, error) { switch builtin.VersionForNetwork(version) { case builtin.Version0: - return v0adt.AsArray(store, root) + return adt0.AsArray(store, root) } return nil, xerrors.Errorf("unknown network version: %d", version) } diff --git a/chain/actors/adt/diff_adt_test.go b/chain/actors/adt/diff_adt_test.go index 436e28bbf..1c0726003 100644 --- a/chain/actors/adt/diff_adt_test.go +++ b/chain/actors/adt/diff_adt_test.go @@ -13,7 +13,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/specs-actors/actors/runtime" - v0adt "github.com/filecoin-project/specs-actors/actors/util/adt" + adt0 "github.com/filecoin-project/specs-actors/actors/util/adt" bstore "github.com/filecoin-project/lotus/lib/blockstore" ) @@ -22,8 +22,8 @@ func TestDiffAdtArray(t *testing.T) { ctxstoreA := newContextStore() ctxstoreB := newContextStore() - arrA := v0adt.MakeEmptyArray(ctxstoreA) - arrB := v0adt.MakeEmptyArray(ctxstoreB) + arrA := adt0.MakeEmptyArray(ctxstoreA) + arrB := adt0.MakeEmptyArray(ctxstoreB) require.NoError(t, arrA.Set(0, runtime.CBORBytes([]byte{0}))) // delete @@ -76,8 +76,8 @@ func TestDiffAdtMap(t *testing.T) { ctxstoreA := newContextStore() ctxstoreB := newContextStore() - mapA := v0adt.MakeEmptyMap(ctxstoreA) - mapB := v0adt.MakeEmptyMap(ctxstoreB) + mapA := adt0.MakeEmptyMap(ctxstoreA) + mapB := adt0.MakeEmptyMap(ctxstoreB) require.NoError(t, mapA.Put(abi.UIntKey(0), runtime.CBORBytes([]byte{0}))) // delete diff --git a/chain/actors/builtin/account/account.go b/chain/actors/builtin/account/account.go index d4cbe4177..5b90580ec 100644 --- a/chain/actors/builtin/account/account.go +++ b/chain/actors/builtin/account/account.go @@ -5,7 +5,7 @@ import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/cbor" - v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/types" @@ -13,8 +13,8 @@ import ( func Load(store adt.Store, act *types.Actor) (State, error) { switch act.Code { - case v0builtin.AccountActorCodeID: - out := v0State{store: store} + case builtin0.AccountActorCodeID: + out := state0{store: store} err := store.Get(store.Context(), act.Head, &out) if err != nil { return nil, err diff --git a/chain/actors/builtin/account/v0.go b/chain/actors/builtin/account/v0.go index 6001dd7bf..535255d0e 100644 --- a/chain/actors/builtin/account/v0.go +++ b/chain/actors/builtin/account/v0.go @@ -6,11 +6,11 @@ import ( "github.com/filecoin-project/specs-actors/actors/builtin/account" ) -type v0State struct { +type state0 struct { account.State store adt.Store } -func (s *v0State) PubkeyAddress() (address.Address, error) { +func (s *state0) PubkeyAddress() (address.Address, error) { return s.Address, nil } diff --git a/chain/actors/builtin/builtin.go b/chain/actors/builtin/builtin.go index bee8e59d6..4ce77804c 100644 --- a/chain/actors/builtin/builtin.go +++ b/chain/actors/builtin/builtin.go @@ -5,7 +5,7 @@ import ( "github.com/filecoin-project/go-state-types/network" - v0smoothing "github.com/filecoin-project/specs-actors/actors/util/smoothing" + smoothing0 "github.com/filecoin-project/specs-actors/actors/util/smoothing" ) type Version int @@ -25,4 +25,4 @@ func VersionForNetwork(version network.Version) Version { } // TODO: find some way to abstract over this. -type FilterEstimate = v0smoothing.FilterEstimate +type FilterEstimate = smoothing0.FilterEstimate diff --git a/chain/actors/builtin/init/init.go b/chain/actors/builtin/init/init.go index 7485c599f..1164891f8 100644 --- a/chain/actors/builtin/init/init.go +++ b/chain/actors/builtin/init/init.go @@ -6,19 +6,19 @@ import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/cbor" - v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/node/modules/dtypes" ) -var Address = v0builtin.InitActorAddr +var Address = builtin0.InitActorAddr func Load(store adt.Store, act *types.Actor) (State, error) { switch act.Code { - case v0builtin.InitActorCodeID: - out := v0State{store: store} + case builtin0.InitActorCodeID: + out := state0{store: store} err := store.Get(store.Context(), act.Head, &out) if err != nil { return nil, err diff --git a/chain/actors/builtin/init/v0.go b/chain/actors/builtin/init/v0.go index e286e1ef2..0e8395a08 100644 --- a/chain/actors/builtin/init/v0.go +++ b/chain/actors/builtin/init/v0.go @@ -10,24 +10,24 @@ import ( "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/node/modules/dtypes" - v0adt "github.com/filecoin-project/specs-actors/actors/util/adt" + adt0 "github.com/filecoin-project/specs-actors/actors/util/adt" ) -type v0State struct { +type state0 struct { init_.State store adt.Store } -func (s *v0State) ResolveAddress(address address.Address) (address.Address, bool, error) { +func (s *state0) ResolveAddress(address address.Address) (address.Address, bool, error) { return s.State.ResolveAddress(s.store, address) } -func (s *v0State) MapAddressToNewID(address address.Address) (address.Address, error) { +func (s *state0) MapAddressToNewID(address address.Address) (address.Address, error) { return s.State.MapAddressToNewID(s.store, address) } -func (s *v0State) ForEachActor(cb func(id abi.ActorID, address address.Address) error) error { - addrs, err := v0adt.AsMap(s.store, s.State.AddressMap) +func (s *state0) ForEachActor(cb func(id abi.ActorID, address address.Address) error) error { + addrs, err := adt0.AsMap(s.store, s.State.AddressMap) if err != nil { return err } @@ -41,6 +41,6 @@ func (s *v0State) ForEachActor(cb func(id abi.ActorID, address address.Address) }) } -func (s *v0State) NetworkName() (dtypes.NetworkName, error) { +func (s *state0) NetworkName() (dtypes.NetworkName, error) { return dtypes.NetworkName(s.State.NetworkName), nil } diff --git a/chain/actors/builtin/market/market.go b/chain/actors/builtin/market/market.go index c65fa093d..fa5f027b3 100644 --- a/chain/actors/builtin/market/market.go +++ b/chain/actors/builtin/market/market.go @@ -6,7 +6,7 @@ import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/cbor" - v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/ipfs/go-cid" cbg "github.com/whyrusleeping/cbor-gen" @@ -14,12 +14,12 @@ import ( "github.com/filecoin-project/lotus/chain/types" ) -var Address = v0builtin.StorageMarketActorAddr +var Address = builtin0.StorageMarketActorAddr func Load(store adt.Store, act *types.Actor) (st State, err error) { switch act.Code { - case v0builtin.StorageMarketActorCodeID: - out := v0State{store: store} + case builtin0.StorageMarketActorCodeID: + out := state0{store: store} err := store.Get(store.Context(), act.Head, &out) if err != nil { return nil, err diff --git a/chain/actors/builtin/market/v0.go b/chain/actors/builtin/market/v0.go index 671907ad4..27eee4c50 100644 --- a/chain/actors/builtin/market/v0.go +++ b/chain/actors/builtin/market/v0.go @@ -8,95 +8,95 @@ import ( "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/specs-actors/actors/builtin/market" - v0adt "github.com/filecoin-project/specs-actors/actors/util/adt" + adt0 "github.com/filecoin-project/specs-actors/actors/util/adt" cbg "github.com/whyrusleeping/cbor-gen" ) -type v0State struct { +type state0 struct { market.State store adt.Store } -func (s *v0State) TotalLocked() (abi.TokenAmount, error) { +func (s *state0) TotalLocked() (abi.TokenAmount, error) { fml := types.BigAdd(s.TotalClientLockedCollateral, s.TotalProviderLockedCollateral) fml = types.BigAdd(fml, s.TotalClientStorageFee) return fml, nil } -func (s *v0State) BalancesChanged(otherState State) bool { - v0otherState, ok := otherState.(*v0State) +func (s *state0) BalancesChanged(otherState State) bool { + otherState0, ok := otherState.(*state0) if !ok { // there's no way to compare differnt versions of the state, so let's // just say that means the state of balances has changed return true } - return !s.State.EscrowTable.Equals(v0otherState.State.EscrowTable) || !s.State.LockedTable.Equals(v0otherState.State.LockedTable) + return !s.State.EscrowTable.Equals(otherState0.State.EscrowTable) || !s.State.LockedTable.Equals(otherState0.State.LockedTable) } -func (s *v0State) StatesChanged(otherState State) bool { - v0otherState, ok := otherState.(*v0State) +func (s *state0) StatesChanged(otherState State) bool { + otherState0, ok := otherState.(*state0) if !ok { // there's no way to compare differnt versions of the state, so let's // just say that means the state of balances has changed return true } - return !s.State.States.Equals(v0otherState.State.States) + return !s.State.States.Equals(otherState0.State.States) } -func (s *v0State) States() (DealStates, error) { - stateArray, err := v0adt.AsArray(s.store, s.State.States) +func (s *state0) States() (DealStates, error) { + stateArray, err := adt0.AsArray(s.store, s.State.States) if err != nil { return nil, err } - return &v0DealStates{stateArray}, nil + return &dealStates0{stateArray}, nil } -func (s *v0State) ProposalsChanged(otherState State) bool { - v0otherState, ok := otherState.(*v0State) +func (s *state0) ProposalsChanged(otherState State) bool { + otherState0, ok := otherState.(*state0) if !ok { // there's no way to compare differnt versions of the state, so let's // just say that means the state of balances has changed return true } - return !s.State.Proposals.Equals(v0otherState.State.Proposals) + return !s.State.Proposals.Equals(otherState0.State.Proposals) } -func (s *v0State) Proposals() (DealProposals, error) { - proposalArray, err := v0adt.AsArray(s.store, s.State.Proposals) +func (s *state0) Proposals() (DealProposals, error) { + proposalArray, err := adt0.AsArray(s.store, s.State.Proposals) if err != nil { return nil, err } - return &v0DealProposals{proposalArray}, nil + return &dealProposals0{proposalArray}, nil } -func (s *v0State) EscrowTable() (BalanceTable, error) { - bt, err := v0adt.AsBalanceTable(s.store, s.State.EscrowTable) +func (s *state0) EscrowTable() (BalanceTable, error) { + bt, err := adt0.AsBalanceTable(s.store, s.State.EscrowTable) if err != nil { return nil, err } - return &v0BalanceTable{bt}, nil + return &balanceTable0{bt}, nil } -func (s *v0State) LockedTable() (BalanceTable, error) { - bt, err := v0adt.AsBalanceTable(s.store, s.State.LockedTable) +func (s *state0) LockedTable() (BalanceTable, error) { + bt, err := adt0.AsBalanceTable(s.store, s.State.LockedTable) if err != nil { return nil, err } - return &v0BalanceTable{bt}, nil + return &balanceTable0{bt}, nil } -func (s *v0State) VerifyDealsForActivation( +func (s *state0) VerifyDealsForActivation( minerAddr address.Address, deals []abi.DealID, currEpoch, sectorExpiry abi.ChainEpoch, ) (weight, verifiedWeight abi.DealWeight, err error) { return market.ValidateDealsForActivation(&s.State, s.store, deals, minerAddr, sectorExpiry, currEpoch) } -type v0BalanceTable struct { - *v0adt.BalanceTable +type balanceTable0 struct { + *adt0.BalanceTable } -func (bt *v0BalanceTable) ForEach(cb func(address.Address, abi.TokenAmount) error) error { - asMap := (*v0adt.Map)(bt.BalanceTable) +func (bt *balanceTable0) ForEach(cb func(address.Address, abi.TokenAmount) error) error { + asMap := (*adt0.Map)(bt.BalanceTable) var ta abi.TokenAmount return asMap.ForEach(&ta, func(key string) error { a, err := address.NewFromBytes([]byte(key)) @@ -107,33 +107,33 @@ func (bt *v0BalanceTable) ForEach(cb func(address.Address, abi.TokenAmount) erro }) } -type v0DealStates struct { +type dealStates0 struct { adt.Array } -func (s *v0DealStates) Get(dealID abi.DealID) (*DealState, bool, error) { - var v0deal market.DealState - found, err := s.Array.Get(uint64(dealID), &v0deal) +func (s *dealStates0) Get(dealID abi.DealID) (*DealState, bool, error) { + var deal0 market.DealState + found, err := s.Array.Get(uint64(dealID), &deal0) if err != nil { return nil, false, err } if !found { return nil, false, nil } - deal := fromV0DealState(v0deal) + deal := fromV0DealState(deal0) return &deal, true, nil } -func (s *v0DealStates) decode(val *cbg.Deferred) (*DealState, error) { - var v0ds market.DealState - if err := v0ds.UnmarshalCBOR(bytes.NewReader(val.Raw)); err != nil { +func (s *dealStates0) decode(val *cbg.Deferred) (*DealState, error) { + var ds0 market.DealState + if err := ds0.UnmarshalCBOR(bytes.NewReader(val.Raw)); err != nil { return nil, err } - ds := fromV0DealState(v0ds) + ds := fromV0DealState(ds0) return &ds, nil } -func (s *v0DealStates) array() adt.Array { +func (s *dealStates0) array() adt.Array { return s.Array } @@ -141,40 +141,40 @@ func fromV0DealState(v0 market.DealState) DealState { return (DealState)(v0) } -type v0DealProposals struct { +type dealProposals0 struct { adt.Array } -func (s *v0DealProposals) Get(dealID abi.DealID) (*DealProposal, bool, error) { - var v0proposal market.DealProposal - found, err := s.Array.Get(uint64(dealID), &v0proposal) +func (s *dealProposals0) Get(dealID abi.DealID) (*DealProposal, bool, error) { + var proposal0 market.DealProposal + found, err := s.Array.Get(uint64(dealID), &proposal0) if err != nil { return nil, false, err } if !found { return nil, false, nil } - proposal := fromV0DealProposal(v0proposal) + proposal := fromV0DealProposal(proposal0) return &proposal, true, nil } -func (s *v0DealProposals) ForEach(cb func(dealID abi.DealID, dp DealProposal) error) error { - var v0dp market.DealProposal - return s.Array.ForEach(&v0dp, func(idx int64) error { - return cb(abi.DealID(idx), fromV0DealProposal(v0dp)) +func (s *dealProposals0) ForEach(cb func(dealID abi.DealID, dp DealProposal) error) error { + var dp0 market.DealProposal + return s.Array.ForEach(&dp0, func(idx int64) error { + return cb(abi.DealID(idx), fromV0DealProposal(dp0)) }) } -func (s *v0DealProposals) decode(val *cbg.Deferred) (*DealProposal, error) { - var v0dp market.DealProposal - if err := v0dp.UnmarshalCBOR(bytes.NewReader(val.Raw)); err != nil { +func (s *dealProposals0) decode(val *cbg.Deferred) (*DealProposal, error) { + var dp0 market.DealProposal + if err := dp0.UnmarshalCBOR(bytes.NewReader(val.Raw)); err != nil { return nil, err } - dp := fromV0DealProposal(v0dp) + dp := fromV0DealProposal(dp0) return &dp, nil } -func (s *v0DealProposals) array() adt.Array { +func (s *dealProposals0) array() adt.Array { return s.Array } diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index c67e773bf..b9cff99da 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -10,19 +10,19 @@ import ( "github.com/filecoin-project/go-bitfield" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/cbor" - v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/types" ) -var Address = v0builtin.InitActorAddr +var Address = builtin0.InitActorAddr func Load(store adt.Store, act *types.Actor) (st State, err error) { switch act.Code { - case v0builtin.StorageMinerActorCodeID: - out := v0State{store: store} + case builtin0.StorageMinerActorCodeID: + out := state0{store: store} err := store.Get(store.Context(), act.Head, &out) if err != nil { return nil, err @@ -83,18 +83,18 @@ type Partition interface { ActiveSectors() (bitfield.BitField, error) } -type SectorOnChainInfo = v0miner.SectorOnChainInfo -type SectorPreCommitInfo = v0miner.SectorPreCommitInfo -type SectorPreCommitOnChainInfo = v0miner.SectorPreCommitOnChainInfo -type PoStPartition = v0miner.PoStPartition -type RecoveryDeclaration = v0miner.RecoveryDeclaration -type FaultDeclaration = v0miner.FaultDeclaration +type SectorOnChainInfo = miner0.SectorOnChainInfo +type SectorPreCommitInfo = miner0.SectorPreCommitInfo +type SectorPreCommitOnChainInfo = miner0.SectorPreCommitOnChainInfo +type PoStPartition = miner0.PoStPartition +type RecoveryDeclaration = miner0.RecoveryDeclaration +type FaultDeclaration = miner0.FaultDeclaration // Params -type DeclareFaultsParams = v0miner.DeclareFaultsParams -type DeclareFaultsRecoveredParams = v0miner.DeclareFaultsRecoveredParams -type SubmitWindowedPoStParams = v0miner.SubmitWindowedPoStParams -type ProveCommitSectorParams = v0miner.ProveCommitSectorParams +type DeclareFaultsParams = miner0.DeclareFaultsParams +type DeclareFaultsRecoveredParams = miner0.DeclareFaultsRecoveredParams +type SubmitWindowedPoStParams = miner0.SubmitWindowedPoStParams +type ProveCommitSectorParams = miner0.ProveCommitSectorParams type MinerInfo struct { Owner address.Address // Must be an ID-address. diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index 0f27d7d7f..26a91edd1 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -9,38 +9,38 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/dline" "github.com/filecoin-project/lotus/chain/actors/adt" - v0adt "github.com/filecoin-project/specs-actors/actors/util/adt" + adt0 "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/libp2p/go-libp2p-core/peer" cbg "github.com/whyrusleeping/cbor-gen" "golang.org/x/xerrors" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" ) -type v0State struct { - v0miner.State +type state0 struct { + miner0.State store adt.Store } -type v0Deadline struct { - v0miner.Deadline +type deadline0 struct { + miner0.Deadline store adt.Store } -type v0Partition struct { - v0miner.Partition +type partition0 struct { + miner0.Partition store adt.Store } -func (s *v0State) AvailableBalance(bal abi.TokenAmount) (abi.TokenAmount, error) { +func (s *state0) AvailableBalance(bal abi.TokenAmount) (abi.TokenAmount, error) { return s.GetAvailableBalance(bal), nil } -func (s *v0State) VestedFunds(epoch abi.ChainEpoch) (abi.TokenAmount, error) { +func (s *state0) VestedFunds(epoch abi.ChainEpoch) (abi.TokenAmount, error) { return s.CheckVestedFunds(s.store, epoch) } -func (s *v0State) LockedFunds() (LockedFunds, error) { +func (s *state0) LockedFunds() (LockedFunds, error) { return LockedFunds{ VestingFunds: s.State.LockedFunds, InitialPledgeRequirement: s.State.InitialPledgeRequirement, @@ -48,15 +48,15 @@ func (s *v0State) LockedFunds() (LockedFunds, error) { }, nil } -func (s *v0State) InitialPledge() (abi.TokenAmount, error) { +func (s *state0) InitialPledge() (abi.TokenAmount, error) { return s.State.InitialPledgeRequirement, nil } -func (s *v0State) PreCommitDeposits() (abi.TokenAmount, error) { +func (s *state0) PreCommitDeposits() (abi.TokenAmount, error) { return s.State.PreCommitDeposits, nil } -func (s *v0State) GetSector(num abi.SectorNumber) (*SectorOnChainInfo, error) { +func (s *state0) GetSector(num abi.SectorNumber) (*SectorOnChainInfo, error) { info, ok, err := s.State.GetSector(s.store, num) if !ok || err != nil { return nil, err @@ -65,7 +65,7 @@ func (s *v0State) GetSector(num abi.SectorNumber) (*SectorOnChainInfo, error) { return info, nil } -func (s *v0State) FindSector(num abi.SectorNumber) (*SectorLocation, error) { +func (s *state0) FindSector(num abi.SectorNumber) (*SectorLocation, error) { dlIdx, partIdx, err := s.State.FindSector(s.store, num) if err != nil { return nil, err @@ -81,7 +81,7 @@ func (s *v0State) FindSector(num abi.SectorNumber) (*SectorLocation, error) { // If the sector isn't found or has already been terminated, this method returns // nil and no error. If the sector does not expire early, the Early expiration // field is 0. -func (s *v0State) GetSectorExpiration(num abi.SectorNumber) (*SectorExpiration, error) { +func (s *state0) GetSectorExpiration(num abi.SectorNumber) (*SectorExpiration, error) { dls, err := s.State.LoadDeadlines(s.store) if err != nil { return nil, err @@ -94,13 +94,13 @@ func (s *v0State) GetSectorExpiration(num abi.SectorNumber) (*SectorExpiration, // of the expiration queue. stopErr := errors.New("stop") out := SectorExpiration{} - err = dls.ForEach(s.store, func(dlIdx uint64, dl *v0miner.Deadline) error { + err = dls.ForEach(s.store, func(dlIdx uint64, dl *miner0.Deadline) error { partitions, err := dl.PartitionsArray(s.store) if err != nil { return err } quant := s.State.QuantSpecForDeadline(dlIdx) - var part v0miner.Partition + var part miner0.Partition return partitions.ForEach(&part, func(partIdx int64) error { if found, err := part.Sectors.IsSet(uint64(num)); err != nil { return err @@ -114,11 +114,11 @@ func (s *v0State) GetSectorExpiration(num abi.SectorNumber) (*SectorExpiration, return stopErr } - q, err := v0miner.LoadExpirationQueue(s.store, part.ExpirationsEpochs, quant) + q, err := miner0.LoadExpirationQueue(s.store, part.ExpirationsEpochs, quant) if err != nil { return err } - var exp v0miner.ExpirationSet + var exp miner0.ExpirationSet return q.ForEach(&exp, func(epoch int64) error { if early, err := exp.EarlySectors.IsSet(uint64(num)); err != nil { return err @@ -148,7 +148,7 @@ func (s *v0State) GetSectorExpiration(num abi.SectorNumber) (*SectorExpiration, return &out, nil } -func (s *v0State) GetPrecommittedSector(num abi.SectorNumber) (*SectorPreCommitOnChainInfo, error) { +func (s *state0) GetPrecommittedSector(num abi.SectorNumber) (*SectorPreCommitOnChainInfo, error) { info, ok, err := s.State.GetPrecommittedSector(s.store, num) if !ok || err != nil { return nil, err @@ -157,8 +157,8 @@ func (s *v0State) GetPrecommittedSector(num abi.SectorNumber) (*SectorPreCommitO return info, nil } -func (s *v0State) LoadSectorsFromSet(filter *bitfield.BitField, filterOut bool) (adt.Array, error) { - a, err := v0adt.AsArray(s.store, s.State.Sectors) +func (s *state0) LoadSectorsFromSet(filter *bitfield.BitField, filterOut bool) (adt.Array, error) { + a, err := adt0.AsArray(s.store, s.State.Sectors) if err != nil { return nil, err } @@ -185,11 +185,11 @@ func (s *v0State) LoadSectorsFromSet(filter *bitfield.BitField, filterOut bool) return a, nil } -func (s *v0State) LoadPreCommittedSectors() (adt.Map, error) { - return v0adt.AsMap(s.store, s.State.PreCommittedSectors) +func (s *state0) LoadPreCommittedSectors() (adt.Map, error) { + return adt0.AsMap(s.store, s.State.PreCommittedSectors) } -func (s *v0State) IsAllocated(num abi.SectorNumber) (bool, error) { +func (s *state0) IsAllocated(num abi.SectorNumber) (bool, error) { var allocatedSectors bitfield.BitField if err := s.store.Get(s.store.Context(), s.State.AllocatedSectors, &allocatedSectors); err != nil { return false, err @@ -198,7 +198,7 @@ func (s *v0State) IsAllocated(num abi.SectorNumber) (bool, error) { return allocatedSectors.IsSet(uint64(num)) } -func (s *v0State) LoadDeadline(idx uint64) (Deadline, error) { +func (s *state0) LoadDeadline(idx uint64) (Deadline, error) { dls, err := s.State.LoadDeadlines(s.store) if err != nil { return nil, err @@ -207,39 +207,39 @@ func (s *v0State) LoadDeadline(idx uint64) (Deadline, error) { if err != nil { return nil, err } - return &v0Deadline{*dl, s.store}, nil + return &deadline0{*dl, s.store}, nil } -func (s *v0State) ForEachDeadline(cb func(uint64, Deadline) error) error { +func (s *state0) ForEachDeadline(cb func(uint64, Deadline) error) error { dls, err := s.State.LoadDeadlines(s.store) if err != nil { return err } - return dls.ForEach(s.store, func(i uint64, dl *v0miner.Deadline) error { - return cb(i, &v0Deadline{*dl, s.store}) + return dls.ForEach(s.store, func(i uint64, dl *miner0.Deadline) error { + return cb(i, &deadline0{*dl, s.store}) }) } -func (s *v0State) NumDeadlines() (uint64, error) { - return v0miner.WPoStPeriodDeadlines, nil +func (s *state0) NumDeadlines() (uint64, error) { + return miner0.WPoStPeriodDeadlines, nil } // Max sectors per PoSt -func (s *v0State) MaxAddressedSectors() (uint64, error) { - return v0miner.AddressedSectorsMax, nil +func (s *state0) MaxAddressedSectors() (uint64, error) { + return miner0.AddressedSectorsMax, nil } -func (s *v0State) DeadlinesChanged(other State) bool { - v0other, ok := other.(*v0State) +func (s *state0) DeadlinesChanged(other State) bool { + other0, ok := other.(*state0) if !ok { // treat an upgrade as a change, always return true } - return s.State.Deadlines.Equals(v0other.Deadlines) + return s.State.Deadlines.Equals(other0.Deadlines) } -func (s *v0State) Info() (MinerInfo, error) { +func (s *state0) Info() (MinerInfo, error) { info, err := s.State.GetInfo(s.store) if err != nil { return MinerInfo{}, err @@ -273,71 +273,71 @@ func (s *v0State) Info() (MinerInfo, error) { return mi, nil } -func (s *v0State) DeadlineInfo(epoch abi.ChainEpoch) *dline.Info { +func (s *state0) DeadlineInfo(epoch abi.ChainEpoch) *dline.Info { return s.State.DeadlineInfo(epoch) } -func (s *v0State) sectors() (adt.Array, error) { - return v0adt.AsArray(s.store, s.Sectors) +func (s *state0) sectors() (adt.Array, error) { + return adt0.AsArray(s.store, s.Sectors) } -func (s *v0State) decodeSectorOnChainInfo(val *cbg.Deferred) (SectorOnChainInfo, error) { - var si v0miner.SectorOnChainInfo +func (s *state0) decodeSectorOnChainInfo(val *cbg.Deferred) (SectorOnChainInfo, error) { + var si miner0.SectorOnChainInfo err := si.UnmarshalCBOR(bytes.NewReader(val.Raw)) return si, err } -func (s *v0State) precommits() (adt.Map, error) { - return v0adt.AsMap(s.store, s.PreCommittedSectors) +func (s *state0) precommits() (adt.Map, error) { + return adt0.AsMap(s.store, s.PreCommittedSectors) } -func (s *v0State) decodeSectorPreCommitOnChainInfo(val *cbg.Deferred) (SectorPreCommitOnChainInfo, error) { - var sp v0miner.SectorPreCommitOnChainInfo +func (s *state0) decodeSectorPreCommitOnChainInfo(val *cbg.Deferred) (SectorPreCommitOnChainInfo, error) { + var sp miner0.SectorPreCommitOnChainInfo err := sp.UnmarshalCBOR(bytes.NewReader(val.Raw)) return sp, err } -func (d *v0Deadline) LoadPartition(idx uint64) (Partition, error) { +func (d *deadline0) LoadPartition(idx uint64) (Partition, error) { p, err := d.Deadline.LoadPartition(d.store, idx) if err != nil { return nil, err } - return &v0Partition{*p, d.store}, nil + return &partition0{*p, d.store}, nil } -func (d *v0Deadline) ForEachPartition(cb func(uint64, Partition) error) error { +func (d *deadline0) ForEachPartition(cb func(uint64, Partition) error) error { ps, err := d.Deadline.PartitionsArray(d.store) if err != nil { return err } - var part v0miner.Partition + var part miner0.Partition return ps.ForEach(&part, func(i int64) error { - return cb(uint64(i), &v0Partition{part, d.store}) + return cb(uint64(i), &partition0{part, d.store}) }) } -func (d *v0Deadline) PartitionsChanged(other Deadline) bool { - v0other, ok := other.(*v0Deadline) +func (d *deadline0) PartitionsChanged(other Deadline) bool { + other0, ok := other.(*deadline0) if !ok { // treat an upgrade as a change, always return true } - return d.Deadline.Partitions.Equals(v0other.Deadline.Partitions) + return d.Deadline.Partitions.Equals(other0.Deadline.Partitions) } -func (d *v0Deadline) PostSubmissions() (bitfield.BitField, error) { +func (d *deadline0) PostSubmissions() (bitfield.BitField, error) { return d.Deadline.PostSubmissions, nil } -func (p *v0Partition) AllSectors() (bitfield.BitField, error) { +func (p *partition0) AllSectors() (bitfield.BitField, error) { return p.Partition.Sectors, nil } -func (p *v0Partition) FaultySectors() (bitfield.BitField, error) { +func (p *partition0) FaultySectors() (bitfield.BitField, error) { return p.Partition.Faults, nil } -func (p *v0Partition) RecoveringSectors() (bitfield.BitField, error) { +func (p *partition0) RecoveringSectors() (bitfield.BitField, error) { return p.Partition.Recoveries, nil } diff --git a/chain/actors/builtin/multisig/multisig.go b/chain/actors/builtin/multisig/multisig.go index fc58599a9..86a68c178 100644 --- a/chain/actors/builtin/multisig/multisig.go +++ b/chain/actors/builtin/multisig/multisig.go @@ -5,7 +5,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/cbor" - v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/types" @@ -13,8 +13,8 @@ import ( func Load(store adt.Store, act *types.Actor) (State, error) { switch act.Code { - case v0builtin.MultisigActorCodeID: - out := v0State{store: store} + case builtin0.MultisigActorCodeID: + out := state0{store: store} err := store.Get(store.Context(), act.Head, &out) if err != nil { return nil, err diff --git a/chain/actors/builtin/multisig/v0.go b/chain/actors/builtin/multisig/v0.go index dc464d9af..ded834d5f 100644 --- a/chain/actors/builtin/multisig/v0.go +++ b/chain/actors/builtin/multisig/v0.go @@ -6,23 +6,23 @@ import ( "github.com/filecoin-project/specs-actors/actors/builtin/multisig" ) -type v0State struct { +type state0 struct { multisig.State store adt.Store } -func (s *v0State) LockedBalance(currEpoch abi.ChainEpoch) (abi.TokenAmount, error) { +func (s *state0) LockedBalance(currEpoch abi.ChainEpoch) (abi.TokenAmount, error) { return s.State.AmountLocked(currEpoch - s.State.StartEpoch), nil } -func (s *v0State) StartEpoch() abi.ChainEpoch { +func (s *state0) StartEpoch() abi.ChainEpoch { return s.State.StartEpoch } -func (s *v0State) UnlockDuration() abi.ChainEpoch { +func (s *state0) UnlockDuration() abi.ChainEpoch { return s.State.UnlockDuration } -func (s *v0State) InitialBalance() abi.TokenAmount { +func (s *state0) InitialBalance() abi.TokenAmount { return s.State.InitialBalance } diff --git a/chain/actors/builtin/paych/paych.go b/chain/actors/builtin/paych/paych.go index 974d64fde..5eec5f08b 100644 --- a/chain/actors/builtin/paych/paych.go +++ b/chain/actors/builtin/paych/paych.go @@ -7,7 +7,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" big "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/cbor" - v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/types" @@ -16,8 +16,8 @@ import ( // Load returns an abstract copy of payment channel state, irregardless of actor version func Load(store adt.Store, act *types.Actor) (State, error) { switch act.Code { - case v0builtin.PaymentChannelActorCodeID: - out := v0State{store: store} + case builtin0.PaymentChannelActorCodeID: + out := state0{store: store} err := store.Get(store.Context(), act.Head, &out) if err != nil { return nil, err diff --git a/chain/actors/builtin/paych/v0.go b/chain/actors/builtin/paych/v0.go index 7d63b8913..0c4b2f218 100644 --- a/chain/actors/builtin/paych/v0.go +++ b/chain/actors/builtin/paych/v0.go @@ -6,42 +6,42 @@ import ( big "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/specs-actors/actors/builtin/paych" - v0adt "github.com/filecoin-project/specs-actors/actors/util/adt" + adt0 "github.com/filecoin-project/specs-actors/actors/util/adt" ) -type v0State struct { +type state0 struct { paych.State store adt.Store - lsAmt *v0adt.Array + lsAmt *adt0.Array } // Channel owner, who has funded the actor -func (s *v0State) From() address.Address { +func (s *state0) From() address.Address { return s.State.From } // Recipient of payouts from channel -func (s *v0State) To() address.Address { +func (s *state0) To() address.Address { return s.State.To } // Height at which the channel can be `Collected` -func (s *v0State) SettlingAt() abi.ChainEpoch { +func (s *state0) SettlingAt() abi.ChainEpoch { return s.State.SettlingAt } // Amount successfully redeemed through the payment channel, paid out on `Collect()` -func (s *v0State) ToSend() abi.TokenAmount { +func (s *state0) ToSend() abi.TokenAmount { return s.State.ToSend } -func (s *v0State) getOrLoadLsAmt() (*v0adt.Array, error) { +func (s *state0) getOrLoadLsAmt() (*adt0.Array, error) { if s.lsAmt != nil { return s.lsAmt, nil } // Get the lane state from the chain - lsamt, err := v0adt.AsArray(s.store, s.State.LaneStates) + lsamt, err := adt0.AsArray(s.store, s.State.LaneStates) if err != nil { return nil, err } @@ -51,7 +51,7 @@ func (s *v0State) getOrLoadLsAmt() (*v0adt.Array, error) { } // Get total number of lanes -func (s *v0State) LaneCount() (uint64, error) { +func (s *state0) LaneCount() (uint64, error) { lsamt, err := s.getOrLoadLsAmt() if err != nil { return 0, err @@ -60,7 +60,7 @@ func (s *v0State) LaneCount() (uint64, error) { } // Iterate lane states -func (s *v0State) ForEachLaneState(cb func(idx uint64, dl LaneState) error) error { +func (s *state0) ForEachLaneState(cb func(idx uint64, dl LaneState) error) error { // Get the lane state from the chain lsamt, err := s.getOrLoadLsAmt() if err != nil { @@ -72,18 +72,18 @@ func (s *v0State) ForEachLaneState(cb func(idx uint64, dl LaneState) error) erro // very large index. var ls paych.LaneState return lsamt.ForEach(&ls, func(i int64) error { - return cb(uint64(i), &v0LaneState{ls}) + return cb(uint64(i), &laneState0{ls}) }) } -type v0LaneState struct { +type laneState0 struct { paych.LaneState } -func (ls *v0LaneState) Redeemed() big.Int { +func (ls *laneState0) Redeemed() big.Int { return ls.LaneState.Redeemed } -func (ls *v0LaneState) Nonce() uint64 { +func (ls *laneState0) Nonce() uint64 { return ls.LaneState.Nonce } diff --git a/chain/actors/builtin/power/power.go b/chain/actors/builtin/power/power.go index 7170526bf..e4bb52d44 100644 --- a/chain/actors/builtin/power/power.go +++ b/chain/actors/builtin/power/power.go @@ -6,19 +6,19 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/cbor" - v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/actors/builtin" "github.com/filecoin-project/lotus/chain/types" ) -var Address = v0builtin.StoragePowerActorAddr +var Address = builtin0.StoragePowerActorAddr func Load(store adt.Store, act *types.Actor) (st State, err error) { switch act.Code { - case v0builtin.StoragePowerActorCodeID: - out := v0State{store: store} + case builtin0.StoragePowerActorCodeID: + out := state0{store: store} err := store.Get(store.Context(), act.Head, &out) if err != nil { return nil, err diff --git a/chain/actors/builtin/power/v0.go b/chain/actors/builtin/power/v0.go index 9730be893..1d5a93d2b 100644 --- a/chain/actors/builtin/power/v0.go +++ b/chain/actors/builtin/power/v0.go @@ -4,20 +4,20 @@ import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/lotus/chain/actors/builtin" - v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" + power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/util/adt" ) -type v0State struct { - v0power.State +type state0 struct { + power0.State store adt.Store } -func (s *v0State) TotalLocked() (abi.TokenAmount, error) { +func (s *state0) TotalLocked() (abi.TokenAmount, error) { return s.TotalPledgeCollateral, nil } -func (s *v0State) TotalPower() (Claim, error) { +func (s *state0) TotalPower() (Claim, error) { return Claim{ RawBytePower: s.TotalRawBytePower, QualityAdjPower: s.TotalQualityAdjPower, @@ -25,19 +25,19 @@ func (s *v0State) TotalPower() (Claim, error) { } // Committed power to the network. Includes miners below the minimum threshold. -func (s *v0State) TotalCommitted() (Claim, error) { +func (s *state0) TotalCommitted() (Claim, error) { return Claim{ RawBytePower: s.TotalBytesCommitted, QualityAdjPower: s.TotalQABytesCommitted, }, nil } -func (s *v0State) MinerPower(addr address.Address) (Claim, bool, error) { +func (s *state0) MinerPower(addr address.Address) (Claim, bool, error) { claims, err := adt.AsMap(s.store, s.Claims) if err != nil { return Claim{}, false, err } - var claim v0power.Claim + var claim power0.Claim ok, err := claims.Get(abi.AddrKey(addr), &claim) if err != nil { return Claim{}, false, err @@ -48,19 +48,19 @@ func (s *v0State) MinerPower(addr address.Address) (Claim, bool, error) { }, ok, nil } -func (s *v0State) MinerNominalPowerMeetsConsensusMinimum(a address.Address) (bool, error) { +func (s *state0) MinerNominalPowerMeetsConsensusMinimum(a address.Address) (bool, error) { return s.State.MinerNominalPowerMeetsConsensusMinimum(s.store, a) } -func (s *v0State) TotalPowerSmoothed() (builtin.FilterEstimate, error) { +func (s *state0) TotalPowerSmoothed() (builtin.FilterEstimate, error) { return *s.State.ThisEpochQAPowerSmoothed, nil } -func (s *v0State) MinerCounts() (uint64, uint64, error) { +func (s *state0) MinerCounts() (uint64, uint64, error) { return uint64(s.State.MinerAboveMinPowerCount), uint64(s.State.MinerCount), nil } -func (s *v0State) ListAllMiners() ([]address.Address, error) { +func (s *state0) ListAllMiners() ([]address.Address, error) { claims, err := adt.AsMap(s.store, s.Claims) if err != nil { return nil, err diff --git a/chain/actors/builtin/reward/reward.go b/chain/actors/builtin/reward/reward.go index 66df887fc..b56292fff 100644 --- a/chain/actors/builtin/reward/reward.go +++ b/chain/actors/builtin/reward/reward.go @@ -5,19 +5,19 @@ import ( "golang.org/x/xerrors" "github.com/filecoin-project/go-state-types/cbor" - v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/actors/builtin" "github.com/filecoin-project/lotus/chain/types" ) -var Address = v0builtin.RewardActorAddr +var Address = builtin0.RewardActorAddr func Load(store adt.Store, act *types.Actor) (st State, err error) { switch act.Code { - case v0builtin.RewardActorCodeID: - out := v0State{store: store} + case builtin0.RewardActorCodeID: + out := state0{store: store} err := store.Get(store.Context(), act.Head, &out) if err != nil { return nil, err diff --git a/chain/actors/builtin/reward/v0.go b/chain/actors/builtin/reward/v0.go index d12eccf59..50ad49971 100644 --- a/chain/actors/builtin/reward/v0.go +++ b/chain/actors/builtin/reward/v0.go @@ -7,39 +7,39 @@ import ( "github.com/filecoin-project/specs-actors/actors/util/adt" ) -type v0State struct { +type state0 struct { reward.State store adt.Store } -func (s *v0State) ThisEpochReward() (abi.StoragePower, error) { +func (s *state0) ThisEpochReward() (abi.StoragePower, error) { return s.State.ThisEpochReward, nil } -func (s *v0State) ThisEpochRewardSmoothed() (builtin.FilterEstimate, error) { +func (s *state0) ThisEpochRewardSmoothed() (builtin.FilterEstimate, error) { return *s.State.ThisEpochRewardSmoothed, nil } -func (s *v0State) ThisEpochBaselinePower() (abi.StoragePower, error) { +func (s *state0) ThisEpochBaselinePower() (abi.StoragePower, error) { return s.State.ThisEpochBaselinePower, nil } -func (s *v0State) TotalStoragePowerReward() (abi.TokenAmount, error) { +func (s *state0) TotalStoragePowerReward() (abi.TokenAmount, error) { return s.State.TotalMined, nil } -func (s *v0State) EffectiveBaselinePower() (abi.StoragePower, error) { +func (s *state0) EffectiveBaselinePower() (abi.StoragePower, error) { return s.State.EffectiveBaselinePower, nil } -func (s *v0State) EffectiveNetworkTime() (abi.ChainEpoch, error) { +func (s *state0) EffectiveNetworkTime() (abi.ChainEpoch, error) { return s.State.EffectiveNetworkTime, nil } -func (s *v0State) CumsumBaseline() (abi.StoragePower, error) { +func (s *state0) CumsumBaseline() (abi.StoragePower, error) { return s.State.CumsumBaseline, nil } -func (s *v0State) CumsumRealized() (abi.StoragePower, error) { +func (s *state0) CumsumRealized() (abi.StoragePower, error) { return s.State.CumsumBaseline, nil } diff --git a/chain/actors/builtin/verifreg/v0.go b/chain/actors/builtin/verifreg/v0.go index cbaf4d236..c397d6679 100644 --- a/chain/actors/builtin/verifreg/v0.go +++ b/chain/actors/builtin/verifreg/v0.go @@ -4,24 +4,24 @@ import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" - v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" - v0adt "github.com/filecoin-project/specs-actors/actors/util/adt" + verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + adt0 "github.com/filecoin-project/specs-actors/actors/util/adt" "golang.org/x/xerrors" "github.com/filecoin-project/lotus/chain/actors/adt" ) -type v0State struct { - v0verifreg.State +type state0 struct { + verifreg0.State store adt.Store } -func (s *v0State) VerifiedClientDataCap(addr address.Address) (bool, abi.StoragePower, error) { +func (s *state0) VerifiedClientDataCap(addr address.Address) (bool, abi.StoragePower, error) { if addr.Protocol() != address.ID { return false, big.Zero(), xerrors.Errorf("can only look up ID addresses") } - vh, err := v0adt.AsMap(s.store, s.VerifiedClients) + vh, err := adt0.AsMap(s.store, s.VerifiedClients) if err != nil { return false, big.Zero(), xerrors.Errorf("loading verified clients: %w", err) } diff --git a/chain/actors/builtin/verifreg/verifreg.go b/chain/actors/builtin/verifreg/verifreg.go index 4cb5bb55b..000a94349 100644 --- a/chain/actors/builtin/verifreg/verifreg.go +++ b/chain/actors/builtin/verifreg/verifreg.go @@ -6,18 +6,18 @@ import ( "golang.org/x/xerrors" "github.com/filecoin-project/go-state-types/cbor" - v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/types" ) -var Address = v0builtin.VerifiedRegistryActorAddr +var Address = builtin0.VerifiedRegistryActorAddr func Load(store adt.Store, act *types.Actor) (State, error) { switch act.Code { - case v0builtin.VerifiedRegistryActorCodeID: - out := v0State{store: store} + case builtin0.VerifiedRegistryActorCodeID: + out := state0{store: store} err := store.Get(store.Context(), act.Head, &out) if err != nil { return nil, err diff --git a/chain/events/state/predicates.go b/chain/events/state/predicates.go index 21e1720e6..56dfb981d 100644 --- a/chain/events/state/predicates.go +++ b/chain/events/state/predicates.go @@ -509,12 +509,12 @@ func (sp *StatePredicates) OnAddressMapChange() DiffInitActorStateFunc { return false, nil, nil } - oldAddrs, err := v0adt.AsMap(ctxStore, oldState.AddressMap) + oldAddrs, err := adt0.AsMap(ctxStore, oldState.AddressMap) if err != nil { return false, nil, err } - newAddrs, err := v0adt.AsMap(ctxStore, newState.AddressMap) + newAddrs, err := adt0.AsMap(ctxStore, newState.AddressMap) if err != nil { return false, nil, err } diff --git a/chain/events/state/predicates_test.go b/chain/events/state/predicates_test.go index 604eec75d..832f6a0a7 100644 --- a/chain/events/state/predicates_test.go +++ b/chain/events/state/predicates_test.go @@ -19,10 +19,10 @@ import ( "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/lotus/chain/actors/builtin/market" - v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" - v0market "github.com/filecoin-project/specs-actors/actors/builtin/market" + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" + market0 "github.com/filecoin-project/specs-actors/actors/builtin/market" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/specs-actors/actors/util/adt" tutils "github.com/filecoin-project/specs-actors/support/testing" @@ -74,22 +74,22 @@ func TestMarketPredicates(t *testing.T) { bs := bstore.NewTemporarySync() store := adt.WrapStore(ctx, cbornode.NewCborStore(bs)) - oldDeal1 := &v0market.DealState{ + oldDeal1 := &market0.DealState{ SectorStartEpoch: 1, LastUpdatedEpoch: 2, SlashEpoch: 0, } - oldDeal2 := &v0market.DealState{ + oldDeal2 := &market0.DealState{ SectorStartEpoch: 4, LastUpdatedEpoch: 5, SlashEpoch: 0, } - oldDeals := map[abi.DealID]*v0market.DealState{ + oldDeals := map[abi.DealID]*market0.DealState{ abi.DealID(1): oldDeal1, abi.DealID(2): oldDeal2, } - oldProp1 := &v0market.DealProposal{ + oldProp1 := &market0.DealProposal{ PieceCID: dummyCid, PieceSize: 0, VerifiedDeal: false, @@ -101,7 +101,7 @@ func TestMarketPredicates(t *testing.T) { ProviderCollateral: big.Zero(), ClientCollateral: big.Zero(), } - oldProp2 := &v0market.DealProposal{ + oldProp2 := &market0.DealProposal{ PieceCID: dummyCid, PieceSize: 0, VerifiedDeal: false, @@ -113,7 +113,7 @@ func TestMarketPredicates(t *testing.T) { ProviderCollateral: big.Zero(), ClientCollateral: big.Zero(), } - oldProps := map[abi.DealID]*v0market.DealProposal{ + oldProps := map[abi.DealID]*market0.DealProposal{ abi.DealID(1): oldProp1, abi.DealID(2): oldProp2, } @@ -127,7 +127,7 @@ func TestMarketPredicates(t *testing.T) { oldStateC := createMarketState(ctx, t, store, oldDeals, oldProps, oldBalances) - newDeal1 := &v0market.DealState{ + newDeal1 := &market0.DealState{ SectorStartEpoch: 1, LastUpdatedEpoch: 3, SlashEpoch: 0, @@ -136,19 +136,19 @@ func TestMarketPredicates(t *testing.T) { // deal 2 removed // added - newDeal3 := &v0market.DealState{ + newDeal3 := &market0.DealState{ SectorStartEpoch: 1, LastUpdatedEpoch: 2, SlashEpoch: 3, } - newDeals := map[abi.DealID]*v0market.DealState{ + newDeals := map[abi.DealID]*market0.DealState{ abi.DealID(1): newDeal1, // deal 2 was removed abi.DealID(3): newDeal3, } // added - newProp3 := &v0market.DealProposal{ + newProp3 := &market0.DealProposal{ PieceCID: dummyCid, PieceSize: 0, VerifiedDeal: false, @@ -160,7 +160,7 @@ func TestMarketPredicates(t *testing.T) { ProviderCollateral: big.Zero(), ClientCollateral: big.Zero(), } - newProps := map[abi.DealID]*v0market.DealProposal{ + newProps := map[abi.DealID]*market0.DealProposal{ abi.DealID(1): oldProp1, // 1 was persisted // prop 2 was removed abi.DealID(3): newProp3, // new @@ -183,8 +183,8 @@ func TestMarketPredicates(t *testing.T) { require.NoError(t, err) api := newMockAPI(bs) - api.setActor(oldState.Key(), &types.Actor{Code: v0builtin.StorageMarketActorCodeID, Head: oldStateC}) - api.setActor(newState.Key(), &types.Actor{Code: v0builtin.StorageMarketActorCodeID, Head: newStateC}) + api.setActor(oldState.Key(), &types.Actor{Code: builtin0.StorageMarketActorCodeID, Head: oldStateC}) + api.setActor(newState.Key(), &types.Actor{Code: builtin0.StorageMarketActorCodeID, Head: newStateC}) t.Run("deal ID predicate", func(t *testing.T) { preds := NewStatePredicates(api) @@ -239,11 +239,11 @@ func TestMarketPredicates(t *testing.T) { t.Fatal("No state change so this should not be called") return false, nil, nil }) - v0marketState := createEmptyMarketState(t, store) - marketCid, err := store.Put(ctx, v0marketState) + marketState0 := createEmptyMarketState(t, store) + marketCid, err := store.Put(ctx, marketState0) require.NoError(t, err) marketState, err := market.Load(store, &types.Actor{ - Code: v0builtin.StorageMarketActorCodeID, + Code: builtin0.StorageMarketActorCodeID, Head: marketCid, }) require.NoError(t, err) @@ -352,11 +352,11 @@ func TestMarketPredicates(t *testing.T) { t.Fatal("No state change so this should not be called") return false, nil, nil }) - v0marketState := createEmptyMarketState(t, store) - marketCid, err := store.Put(ctx, v0marketState) + marketState0 := createEmptyMarketState(t, store) + marketCid, err := store.Put(ctx, marketState0) require.NoError(t, err) marketState, err := market.Load(store, &types.Actor{ - Code: v0builtin.StorageMarketActorCodeID, + Code: builtin0.StorageMarketActorCodeID, Head: marketCid, }) require.NoError(t, err) @@ -379,12 +379,12 @@ func TestMinerSectorChange(t *testing.T) { } owner, worker := nextIDAddrF(), nextIDAddrF() - si0 := newSectorOnChainInfo(0, tutils.MakeCID("0", &v0miner.SealedCIDPrefix), big.NewInt(0), abi.ChainEpoch(0), abi.ChainEpoch(10)) - si1 := newSectorOnChainInfo(1, tutils.MakeCID("1", &v0miner.SealedCIDPrefix), big.NewInt(1), abi.ChainEpoch(1), abi.ChainEpoch(11)) - si2 := newSectorOnChainInfo(2, tutils.MakeCID("2", &v0miner.SealedCIDPrefix), big.NewInt(2), abi.ChainEpoch(2), abi.ChainEpoch(11)) + si0 := newSectorOnChainInfo(0, tutils.MakeCID("0", &miner0.SealedCIDPrefix), big.NewInt(0), abi.ChainEpoch(0), abi.ChainEpoch(10)) + si1 := newSectorOnChainInfo(1, tutils.MakeCID("1", &miner0.SealedCIDPrefix), big.NewInt(1), abi.ChainEpoch(1), abi.ChainEpoch(11)) + si2 := newSectorOnChainInfo(2, tutils.MakeCID("2", &miner0.SealedCIDPrefix), big.NewInt(2), abi.ChainEpoch(2), abi.ChainEpoch(11)) oldMinerC := createMinerState(ctx, t, store, owner, worker, []miner.SectorOnChainInfo{si0, si1, si2}) - si3 := newSectorOnChainInfo(3, tutils.MakeCID("3", &v0miner.SealedCIDPrefix), big.NewInt(3), abi.ChainEpoch(3), abi.ChainEpoch(12)) + si3 := newSectorOnChainInfo(3, tutils.MakeCID("3", &miner0.SealedCIDPrefix), big.NewInt(3), abi.ChainEpoch(3), abi.ChainEpoch(12)) // 0 delete // 1 extend // 2 same @@ -400,8 +400,8 @@ func TestMinerSectorChange(t *testing.T) { require.NoError(t, err) api := newMockAPI(bs) - api.setActor(oldState.Key(), &types.Actor{Head: oldMinerC, Code: v0builtin.StorageMinerActorCodeID}) - api.setActor(newState.Key(), &types.Actor{Head: newMinerC, Code: v0builtin.StorageMinerActorCodeID}) + api.setActor(oldState.Key(), &types.Actor{Head: oldMinerC, Code: builtin0.StorageMinerActorCodeID}) + api.setActor(newState.Key(), &types.Actor{Head: newMinerC, Code: builtin0.StorageMinerActorCodeID}) preds := NewStatePredicates(api) @@ -467,7 +467,7 @@ type balance struct { locked abi.TokenAmount } -func createMarketState(ctx context.Context, t *testing.T, store adt.Store, deals map[abi.DealID]*v0market.DealState, props map[abi.DealID]*v0market.DealProposal, balances map[address.Address]balance) cid.Cid { +func createMarketState(ctx context.Context, t *testing.T, store adt.Store, deals map[abi.DealID]*market0.DealState, props map[abi.DealID]*market0.DealProposal, balances map[address.Address]balance) cid.Cid { dealRootCid := createDealAMT(ctx, t, store, deals) propRootCid := createProposalAMT(ctx, t, store, props) balancesCids := createBalanceTable(ctx, t, store, balances) @@ -482,15 +482,15 @@ func createMarketState(ctx context.Context, t *testing.T, store adt.Store, deals return stateC } -func createEmptyMarketState(t *testing.T, store adt.Store) *v0market.State { +func createEmptyMarketState(t *testing.T, store adt.Store) *market0.State { emptyArrayCid, err := adt.MakeEmptyArray(store).Root() require.NoError(t, err) emptyMap, err := adt.MakeEmptyMap(store).Root() require.NoError(t, err) - return v0market.ConstructState(emptyArrayCid, emptyMap, emptyMap) + return market0.ConstructState(emptyArrayCid, emptyMap, emptyMap) } -func createDealAMT(ctx context.Context, t *testing.T, store adt.Store, deals map[abi.DealID]*v0market.DealState) cid.Cid { +func createDealAMT(ctx context.Context, t *testing.T, store adt.Store, deals map[abi.DealID]*market0.DealState) cid.Cid { root := adt.MakeEmptyArray(store) for dealID, dealState := range deals { err := root.Set(uint64(dealID), dealState) @@ -501,7 +501,7 @@ func createDealAMT(ctx context.Context, t *testing.T, store adt.Store, deals map return rootCid } -func createProposalAMT(ctx context.Context, t *testing.T, store adt.Store, props map[abi.DealID]*v0market.DealProposal) cid.Cid { +func createProposalAMT(ctx context.Context, t *testing.T, store adt.Store, props map[abi.DealID]*market0.DealProposal) cid.Cid { root := adt.MakeEmptyArray(store) for dealID, prop := range props { err := root.Set(uint64(dealID), prop) @@ -549,20 +549,20 @@ func createMinerState(ctx context.Context, t *testing.T, store adt.Store, owner, return stateC } -func createEmptyMinerState(ctx context.Context, t *testing.T, store adt.Store, owner, worker address.Address) *v0miner.State { +func createEmptyMinerState(ctx context.Context, t *testing.T, store adt.Store, owner, worker address.Address) *miner0.State { emptyArrayCid, err := adt.MakeEmptyArray(store).Root() require.NoError(t, err) emptyMap, err := adt.MakeEmptyMap(store).Root() require.NoError(t, err) - emptyDeadline, err := store.Put(store.Context(), v0miner.ConstructDeadline(emptyArrayCid)) + emptyDeadline, err := store.Put(store.Context(), miner0.ConstructDeadline(emptyArrayCid)) require.NoError(t, err) - emptyVestingFunds := v0miner.ConstructVestingFunds() + emptyVestingFunds := miner0.ConstructVestingFunds() emptyVestingFundsCid, err := store.Put(store.Context(), emptyVestingFunds) require.NoError(t, err) - emptyDeadlines := v0miner.ConstructDeadlines(emptyDeadline) + emptyDeadlines := miner0.ConstructDeadlines(emptyDeadline) emptyDeadlinesCid, err := store.Put(store.Context(), emptyDeadlines) require.NoError(t, err) @@ -572,7 +572,7 @@ func createEmptyMinerState(ctx context.Context, t *testing.T, store adt.Store, o emptyBitfieldCid, err := store.Put(store.Context(), emptyBitfield) require.NoError(t, err) - state, err := v0miner.ConstructState(minerInfo, 123, emptyBitfieldCid, emptyArrayCid, emptyMap, emptyDeadlinesCid, emptyVestingFundsCid) + state, err := miner0.ConstructState(minerInfo, 123, emptyBitfieldCid, emptyArrayCid, emptyMap, emptyDeadlinesCid, emptyVestingFundsCid) require.NoError(t, err) return state @@ -625,7 +625,7 @@ func newSectorPreCommitInfo(sectorNo abi.SectorNumber, sealed cid.Cid, expiratio } } -func dealEquality(expected v0market.DealState, actual market.DealState) bool { +func dealEquality(expected market0.DealState, actual market.DealState) bool { return expected.LastUpdatedEpoch == actual.LastUpdatedEpoch && expected.SectorStartEpoch == actual.SectorStartEpoch && expected.SlashEpoch == actual.SlashEpoch diff --git a/chain/gen/gen.go b/chain/gen/gen.go index 4163f0b2d..c4ecf1d41 100644 --- a/chain/gen/gen.go +++ b/chain/gen/gen.go @@ -14,7 +14,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" block "github.com/ipfs/go-block-format" "github.com/ipfs/go-blockservice" "github.com/ipfs/go-cid" @@ -121,7 +121,7 @@ var DefaultRemainderAccountActor = genesis.Actor{ } func NewGeneratorWithSectors(numSectors int) (*ChainGen, error) { - v0miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ + miner0.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } diff --git a/chain/gen/gen_test.go b/chain/gen/gen_test.go index 9d1262f77..be913f5f2 100644 --- a/chain/gen/gen_test.go +++ b/chain/gen/gen_test.go @@ -5,20 +5,20 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" - v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" - v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" + power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" + verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" _ "github.com/filecoin-project/lotus/lib/sigs/bls" _ "github.com/filecoin-project/lotus/lib/sigs/secp" ) func init() { - v0miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ + miner0.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } - v0power.ConsensusMinerMinPower = big.NewInt(2048) - v0verifreg.MinVerifiedDealSize = big.NewInt(256) + power0.ConsensusMinerMinPower = big.NewInt(2048) + verifreg0.MinVerifiedDealSize = big.NewInt(256) } func testGeneration(t testing.TB, n int, msgs int, sectors int) { diff --git a/chain/gen/genesis/genesis.go b/chain/gen/genesis/genesis.go index be2ed70aa..039e284cd 100644 --- a/chain/gen/genesis/genesis.go +++ b/chain/gen/genesis/genesis.go @@ -17,11 +17,11 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" - v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" - v0account "github.com/filecoin-project/specs-actors/actors/builtin/account" - v0multisig "github.com/filecoin-project/specs-actors/actors/builtin/multisig" - v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" - v0adt "github.com/filecoin-project/specs-actors/actors/util/adt" + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" + account0 "github.com/filecoin-project/specs-actors/actors/builtin/account" + multisig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig" + verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + adt0 "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/actors/builtin" @@ -126,7 +126,7 @@ func MakeInitialStateTree(ctx context.Context, bs bstore.Blockstore, template ge if err != nil { return nil, nil, xerrors.Errorf("setup init actor: %w", err) } - if err := state.SetActor(v0builtin.SystemActorAddr, sysact); err != nil { + if err := state.SetActor(builtin0.SystemActorAddr, sysact); err != nil { return nil, nil, xerrors.Errorf("set init actor: %w", err) } @@ -136,7 +136,7 @@ func MakeInitialStateTree(ctx context.Context, bs bstore.Blockstore, template ge if err != nil { return nil, nil, xerrors.Errorf("setup init actor: %w", err) } - if err := state.SetActor(v0builtin.InitActorAddr, initact); err != nil { + if err := state.SetActor(builtin0.InitActorAddr, initact); err != nil { return nil, nil, xerrors.Errorf("set init actor: %w", err) } @@ -147,7 +147,7 @@ func MakeInitialStateTree(ctx context.Context, bs bstore.Blockstore, template ge return nil, nil, xerrors.Errorf("setup init actor: %w", err) } - err = state.SetActor(v0builtin.RewardActorAddr, rewact) + err = state.SetActor(builtin0.RewardActorAddr, rewact) if err != nil { return nil, nil, xerrors.Errorf("set network account actor: %w", err) } @@ -157,7 +157,7 @@ func MakeInitialStateTree(ctx context.Context, bs bstore.Blockstore, template ge if err != nil { return nil, nil, xerrors.Errorf("setup cron actor: %w", err) } - if err := state.SetActor(v0builtin.CronActorAddr, cronact); err != nil { + if err := state.SetActor(builtin0.CronActorAddr, cronact); err != nil { return nil, nil, xerrors.Errorf("set cron actor: %w", err) } @@ -166,7 +166,7 @@ func MakeInitialStateTree(ctx context.Context, bs bstore.Blockstore, template ge if err != nil { return nil, nil, xerrors.Errorf("setup storage market actor: %w", err) } - if err := state.SetActor(v0builtin.StoragePowerActorAddr, spact); err != nil { + if err := state.SetActor(builtin0.StoragePowerActorAddr, spact); err != nil { return nil, nil, xerrors.Errorf("set storage market actor: %w", err) } @@ -175,7 +175,7 @@ func MakeInitialStateTree(ctx context.Context, bs bstore.Blockstore, template ge if err != nil { return nil, nil, xerrors.Errorf("setup storage market actor: %w", err) } - if err := state.SetActor(v0builtin.StorageMarketActorAddr, marketact); err != nil { + if err := state.SetActor(builtin0.StorageMarketActorAddr, marketact); err != nil { return nil, nil, xerrors.Errorf("set market actor: %w", err) } @@ -184,20 +184,20 @@ func MakeInitialStateTree(ctx context.Context, bs bstore.Blockstore, template ge if err != nil { return nil, nil, xerrors.Errorf("setup storage market actor: %w", err) } - if err := state.SetActor(v0builtin.VerifiedRegistryActorAddr, verifact); err != nil { + if err := state.SetActor(builtin0.VerifiedRegistryActorAddr, verifact); err != nil { return nil, nil, xerrors.Errorf("set market actor: %w", err) } - burntRoot, err := cst.Put(ctx, &v0account.State{ - Address: v0builtin.BurntFundsActorAddr, + burntRoot, err := cst.Put(ctx, &account0.State{ + Address: builtin0.BurntFundsActorAddr, }) if err != nil { return nil, nil, xerrors.Errorf("failed to setup burnt funds actor state: %w", err) } // Setup burnt-funds - err = state.SetActor(v0builtin.BurntFundsActorAddr, &types.Actor{ - Code: v0builtin.AccountActorCodeID, + err = state.SetActor(builtin0.BurntFundsActorAddr, &types.Actor{ + Code: builtin0.AccountActorCodeID, Balance: types.NewInt(0), Head: burntRoot, }) @@ -262,13 +262,13 @@ func MakeInitialStateTree(ctx context.Context, bs bstore.Blockstore, template ge return nil, nil, err } - verifierState, err := cst.Put(ctx, &v0account.State{Address: verifierAd}) + verifierState, err := cst.Put(ctx, &account0.State{Address: verifierAd}) if err != nil { return nil, nil, err } err = state.SetActor(verifierId, &types.Actor{ - Code: v0builtin.AccountActorCodeID, + Code: builtin0.AccountActorCodeID, Balance: types.NewInt(0), Head: verifierState, }) @@ -315,7 +315,7 @@ func createAccountActor(ctx context.Context, cst cbor.IpldStore, state *state.St if err := json.Unmarshal(info.Meta, &ainfo); err != nil { return xerrors.Errorf("unmarshaling account meta: %w", err) } - st, err := cst.Put(ctx, &v0account.State{Address: ainfo.Owner}) + st, err := cst.Put(ctx, &account0.State{Address: ainfo.Owner}) if err != nil { return err } @@ -326,7 +326,7 @@ func createAccountActor(ctx context.Context, cst cbor.IpldStore, state *state.St } err = state.SetActor(ida, &types.Actor{ - Code: v0builtin.AccountActorCodeID, + Code: builtin0.AccountActorCodeID, Balance: info.Balance, Head: st, }) @@ -344,7 +344,7 @@ func createMultisigAccount(ctx context.Context, bs bstore.Blockstore, cst cbor.I if err := json.Unmarshal(info.Meta, &ainfo); err != nil { return xerrors.Errorf("unmarshaling account meta: %w", err) } - pending, err := v0adt.MakeEmptyMap(v0adt.WrapStore(ctx, cst)).Root() + pending, err := adt0.MakeEmptyMap(adt0.WrapStore(ctx, cst)).Root() if err != nil { return xerrors.Errorf("failed to create empty map: %v", err) } @@ -364,12 +364,12 @@ func createMultisigAccount(ctx context.Context, bs bstore.Blockstore, cst cbor.I continue } - st, err := cst.Put(ctx, &v0account.State{Address: e}) + st, err := cst.Put(ctx, &account0.State{Address: e}) if err != nil { return err } err = state.SetActor(idAddress, &types.Actor{ - Code: v0builtin.AccountActorCodeID, + Code: builtin0.AccountActorCodeID, Balance: types.NewInt(0), Head: st, }) @@ -379,7 +379,7 @@ func createMultisigAccount(ctx context.Context, bs bstore.Blockstore, cst cbor.I signers = append(signers, idAddress) } - st, err := cst.Put(ctx, &v0multisig.State{ + st, err := cst.Put(ctx, &multisig0.State{ Signers: signers, NumApprovalsThreshold: uint64(ainfo.Threshold), StartEpoch: abi.ChainEpoch(ainfo.VestingStart), @@ -391,7 +391,7 @@ func createMultisigAccount(ctx context.Context, bs bstore.Blockstore, cst cbor.I return err } err = state.SetActor(ida, &types.Actor{ - Code: v0builtin.MultisigActorCodeID, + Code: builtin0.MultisigActorCodeID, Balance: info.Balance, Head: st, }) @@ -442,7 +442,7 @@ func VerifyPreSealedData(ctx context.Context, cs *store.ChainStore, stateroot ci return cid.Undef, err } - _, err = doExecValue(ctx, vm, v0builtin.VerifiedRegistryActorAddr, verifregRoot, types.NewInt(0), v0builtin.MethodsVerifiedRegistry.AddVerifier, mustEnc(&v0verifreg.AddVerifierParams{ + _, err = doExecValue(ctx, vm, builtin0.VerifiedRegistryActorAddr, verifregRoot, types.NewInt(0), builtin0.MethodsVerifiedRegistry.AddVerifier, mustEnc(&verifreg0.AddVerifierParams{ Address: verifier, Allowance: abi.NewStoragePower(int64(sum)), // eh, close enough @@ -453,7 +453,7 @@ func VerifyPreSealedData(ctx context.Context, cs *store.ChainStore, stateroot ci } for c, amt := range verifNeeds { - _, err := doExecValue(ctx, vm, v0builtin.VerifiedRegistryActorAddr, verifier, types.NewInt(0), v0builtin.MethodsVerifiedRegistry.AddVerifiedClient, mustEnc(&v0verifreg.AddVerifiedClientParams{ + _, err := doExecValue(ctx, vm, builtin0.VerifiedRegistryActorAddr, verifier, types.NewInt(0), builtin0.MethodsVerifiedRegistry.AddVerifiedClient, mustEnc(&verifreg0.AddVerifiedClientParams{ Address: c, Allowance: abi.NewStoragePower(int64(amt)), })) @@ -495,8 +495,8 @@ func MakeGenesisBlock(ctx context.Context, bs bstore.Blockstore, sys vm.SyscallB return nil, xerrors.Errorf("setup miners failed: %w", err) } - store := v0adt.WrapStore(ctx, cbor.NewCborStore(bs)) - emptyroot, err := v0adt.MakeEmptyArray(store).Root() + store := adt0.WrapStore(ctx, cbor.NewCborStore(bs)) + emptyroot, err := adt0.MakeEmptyArray(store).Root() if err != nil { return nil, xerrors.Errorf("amt build failed: %w", err) } @@ -544,7 +544,7 @@ func MakeGenesisBlock(ctx context.Context, bs bstore.Blockstore, sys vm.SyscallB } b := &types.BlockHeader{ - Miner: v0builtin.SystemActorAddr, + Miner: builtin0.SystemActorAddr, Ticket: genesisticket, Parents: []cid.Cid{filecoinGenesisCid}, Height: 0, diff --git a/chain/gen/genesis/miners.go b/chain/gen/genesis/miners.go index aff226882..853c9c4a0 100644 --- a/chain/gen/genesis/miners.go +++ b/chain/gen/genesis/miners.go @@ -20,9 +20,9 @@ import ( "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin/market" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" - v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" - v0reward "github.com/filecoin-project/specs-actors/actors/builtin/reward" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" + power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" + reward0 "github.com/filecoin-project/specs-actors/actors/builtin/reward" "github.com/filecoin-project/specs-actors/actors/runtime" "github.com/filecoin-project/lotus/chain/state" @@ -101,7 +101,7 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid } { - constructorParams := &v0power.CreateMinerParams{ + constructorParams := &power0.CreateMinerParams{ Owner: m.Worker, Worker: m.Worker, Peer: []byte(m.PeerId), @@ -114,7 +114,7 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid return cid.Undef, xerrors.Errorf("failed to create genesis miner: %w", err) } - var ma v0power.CreateMinerReturn + var ma power0.CreateMinerReturn if err := ma.UnmarshalCBOR(bytes.NewReader(rval)); err != nil { return cid.Undef, xerrors.Errorf("unmarshaling CreateMinerReturn: %w", err) } @@ -126,9 +126,9 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid minerInfos[i].maddr = ma.IDAddress // TODO: ActorUpgrade - err = vm.MutateState(ctx, minerInfos[i].maddr, func(cst cbor.IpldStore, st *v0miner.State) error { - maxPeriods := v0miner.MaxSectorExpirationExtension / v0miner.WPoStProvingPeriod - minerInfos[i].presealExp = (maxPeriods-1)*v0miner.WPoStProvingPeriod + st.ProvingPeriodStart - 1 + err = vm.MutateState(ctx, minerInfos[i].maddr, func(cst cbor.IpldStore, st *miner0.State) error { + maxPeriods := miner0.MaxSectorExpirationExtension / miner0.WPoStProvingPeriod + minerInfos[i].presealExp = (maxPeriods-1)*miner0.WPoStProvingPeriod + st.ProvingPeriodStart - 1 return nil }) @@ -204,13 +204,13 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid return cid.Undef, xerrors.Errorf("getting deal weight: %w", err) } - sectorWeight := v0miner.QAPowerForWeight(m.SectorSize, minerInfos[i].presealExp, dweight.DealWeight, dweight.VerifiedDealWeight) + sectorWeight := miner0.QAPowerForWeight(m.SectorSize, minerInfos[i].presealExp, dweight.DealWeight, dweight.VerifiedDealWeight) qaPow = types.BigAdd(qaPow, sectorWeight) } } - err = vm.MutateState(ctx, builtin.StoragePowerActorAddr, func(cst cbor.IpldStore, st *v0power.State) error { + err = vm.MutateState(ctx, builtin.StoragePowerActorAddr, func(cst cbor.IpldStore, st *power0.State) error { st.TotalQualityAdjPower = qaPow st.TotalRawBytePower = rawPow @@ -222,8 +222,8 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid return cid.Undef, xerrors.Errorf("mutating state: %w", err) } - err = vm.MutateState(ctx, builtin.RewardActorAddr, func(sct cbor.IpldStore, st *v0reward.State) error { - *st = *v0reward.ConstructState(qaPow) + err = vm.MutateState(ctx, builtin.RewardActorAddr, func(sct cbor.IpldStore, st *reward0.State) error { + *st = *reward0.ConstructState(qaPow) return nil }) if err != nil { @@ -249,10 +249,10 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid return cid.Undef, xerrors.Errorf("getting deal weight: %w", err) } - sectorWeight := v0miner.QAPowerForWeight(m.SectorSize, minerInfos[i].presealExp, dweight.DealWeight, dweight.VerifiedDealWeight) + sectorWeight := miner0.QAPowerForWeight(m.SectorSize, minerInfos[i].presealExp, dweight.DealWeight, dweight.VerifiedDealWeight) // we've added fake power for this sector above, remove it now - err = vm.MutateState(ctx, builtin.StoragePowerActorAddr, func(cst cbor.IpldStore, st *v0power.State) error { + err = vm.MutateState(ctx, builtin.StoragePowerActorAddr, func(cst cbor.IpldStore, st *power0.State) error { st.TotalQualityAdjPower = types.BigSub(st.TotalQualityAdjPower, sectorWeight) //nolint:scopelint st.TotalRawBytePower = types.BigSub(st.TotalRawBytePower, types.NewInt(uint64(m.SectorSize))) return nil @@ -271,9 +271,9 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid return cid.Undef, xerrors.Errorf("getting current total power: %w", err) } - pcd := v0miner.PreCommitDepositForPower(epochReward.ThisEpochRewardSmoothed, tpow.QualityAdjPowerSmoothed, sectorWeight) + pcd := miner0.PreCommitDepositForPower(epochReward.ThisEpochRewardSmoothed, tpow.QualityAdjPowerSmoothed, sectorWeight) - pledge := v0miner.InitialPledgeForPower( + pledge := miner0.InitialPledgeForPower( sectorWeight, epochReward.ThisEpochBaselinePower, tpow.PledgeCollateral, @@ -304,7 +304,7 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid } // Sanity-check total network power - err = vm.MutateState(ctx, builtin.StoragePowerActorAddr, func(cst cbor.IpldStore, st *v0power.State) error { + err = vm.MutateState(ctx, builtin.StoragePowerActorAddr, func(cst cbor.IpldStore, st *power0.State) error { if !st.TotalRawBytePower.Equals(rawPow) { return xerrors.Errorf("st.TotalRawBytePower doesn't match previously calculated rawPow") } @@ -343,12 +343,12 @@ func (fr *fakeRand) GetBeaconRandomness(ctx context.Context, personalization cry return out, nil } -func currentTotalPower(ctx context.Context, vm *vm.VM, maddr address.Address) (*v0power.CurrentTotalPowerReturn, error) { +func currentTotalPower(ctx context.Context, vm *vm.VM, maddr address.Address) (*power0.CurrentTotalPowerReturn, error) { pwret, err := doExecValue(ctx, vm, builtin.StoragePowerActorAddr, maddr, big.Zero(), builtin.MethodsPower.CurrentTotalPower, nil) if err != nil { return nil, err } - var pwr v0power.CurrentTotalPowerReturn + var pwr power0.CurrentTotalPowerReturn if err := pwr.UnmarshalCBOR(bytes.NewReader(pwret)); err != nil { return nil, err } @@ -381,13 +381,13 @@ func dealWeight(ctx context.Context, vm *vm.VM, maddr address.Address, dealIDs [ return dealWeights, nil } -func currentEpochBlockReward(ctx context.Context, vm *vm.VM, maddr address.Address) (*v0reward.ThisEpochRewardReturn, error) { +func currentEpochBlockReward(ctx context.Context, vm *vm.VM, maddr address.Address) (*reward0.ThisEpochRewardReturn, error) { rwret, err := doExecValue(ctx, vm, builtin.RewardActorAddr, maddr, big.Zero(), builtin.MethodsReward.ThisEpochReward, nil) if err != nil { return nil, err } - var epochReward v0reward.ThisEpochRewardReturn + var epochReward reward0.ThisEpochRewardReturn if err := epochReward.UnmarshalCBOR(bytes.NewReader(rwret)); err != nil { return nil, err } diff --git a/chain/gen/genesis/t02_reward.go b/chain/gen/genesis/t02_reward.go index e29e390f9..92531051b 100644 --- a/chain/gen/genesis/t02_reward.go +++ b/chain/gen/genesis/t02_reward.go @@ -6,7 +6,7 @@ import ( "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/specs-actors/actors/builtin" - v0reward "github.com/filecoin-project/specs-actors/actors/builtin/reward" + reward0 "github.com/filecoin-project/specs-actors/actors/builtin/reward" cbor "github.com/ipfs/go-ipld-cbor" "github.com/filecoin-project/lotus/build" @@ -17,7 +17,7 @@ import ( func SetupRewardActor(bs bstore.Blockstore, qaPower big.Int) (*types.Actor, error) { cst := cbor.NewCborStore(bs) - st := v0reward.ConstructState(qaPower) + st := reward0.ConstructState(qaPower) hcid, err := cst.Put(context.TODO(), st) if err != nil { diff --git a/chain/gen/genesis/t04_power.go b/chain/gen/genesis/t04_power.go index 40ea68079..2f1303ba4 100644 --- a/chain/gen/genesis/t04_power.go +++ b/chain/gen/genesis/t04_power.go @@ -6,7 +6,7 @@ import ( "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/util/adt" - v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" + power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" cbor "github.com/ipfs/go-ipld-cbor" "github.com/filecoin-project/lotus/chain/types" @@ -30,7 +30,7 @@ func SetupStoragePowerActor(bs bstore.Blockstore) (*types.Actor, error) { return nil, err } - sms := v0power.ConstructState(emptyMap, emptyMultiMap) + sms := power0.ConstructState(emptyMap, emptyMultiMap) stcid, err := store.Put(store.Context(), sms) if err != nil { diff --git a/chain/gen/genesis/t06_vreg.go b/chain/gen/genesis/t06_vreg.go index d91cdf7b1..1709b205f 100644 --- a/chain/gen/genesis/t06_vreg.go +++ b/chain/gen/genesis/t06_vreg.go @@ -7,7 +7,7 @@ import ( cbor "github.com/ipfs/go-ipld-cbor" "github.com/filecoin-project/specs-actors/actors/builtin" - v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/filecoin-project/lotus/chain/types" @@ -34,7 +34,7 @@ func SetupVerifiedRegistryActor(bs bstore.Blockstore) (*types.Actor, error) { return nil, err } - sms := v0verifreg.ConstructState(h, RootVerifierID) + sms := verifreg0.ConstructState(h, RootVerifierID) stcid, err := store.Put(store.Context(), sms) if err != nil { diff --git a/chain/stmgr/forks.go b/chain/stmgr/forks.go index 650536718..bb496849b 100644 --- a/chain/stmgr/forks.go +++ b/chain/stmgr/forks.go @@ -9,8 +9,8 @@ import ( "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/specs-actors/actors/builtin" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" - v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" + power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/specs-actors/actors/util/adt" cbor "github.com/ipfs/go-ipld-cbor" "golang.org/x/xerrors" @@ -135,7 +135,7 @@ func UpgradeFaucetBurnRecovery(ctx context.Context, sm *StateManager, tree types }) } case builtin.StorageMinerActorCodeID: - var st v0miner.State + var st miner0.State if err := sm.ChainStore().Store(ctx).Get(ctx, act.Head, &st); err != nil { return xerrors.Errorf("failed to load miner state: %w", err) } @@ -172,7 +172,7 @@ func UpgradeFaucetBurnRecovery(ctx context.Context, sm *StateManager, tree types } // pull up power table to give miners back some funds proportional to their power - var ps v0power.State + var ps power0.State powAct, err := tree.GetActor(builtin.StoragePowerActorAddr) if err != nil { return xerrors.Errorf("failed to load power actor: %w", err) @@ -211,12 +211,12 @@ func UpgradeFaucetBurnRecovery(ctx context.Context, sm *StateManager, tree types }) } case builtin.StorageMinerActorCodeID: - var st v0miner.State + var st miner0.State if err := sm.ChainStore().Store(ctx).Get(ctx, act.Head, &st); err != nil { return xerrors.Errorf("failed to load miner state: %w", err) } - var minfo v0miner.MinerInfo + var minfo miner0.MinerInfo if err := cst.Get(ctx, st.Info, &minfo); err != nil { return xerrors.Errorf("failed to get miner info: %w", err) } @@ -240,7 +240,7 @@ func UpgradeFaucetBurnRecovery(ctx context.Context, sm *StateManager, tree types // Now make sure to give each miner who had power at the lookback some FIL lbact, err := lbtree.GetActor(addr) if err == nil { - var lbst v0miner.State + var lbst miner0.State if err := sm.ChainStore().Store(ctx).Get(ctx, lbact.Head, &lbst); err != nil { return xerrors.Errorf("failed to load miner state: %w", err) } diff --git a/chain/stmgr/forks_test.go b/chain/stmgr/forks_test.go index c4fb1b3be..87d328ce1 100644 --- a/chain/stmgr/forks_test.go +++ b/chain/stmgr/forks_test.go @@ -11,9 +11,9 @@ import ( "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/specs-actors/actors/builtin" init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" - v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" - v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" + power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" + verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/specs-actors/actors/runtime" "golang.org/x/xerrors" @@ -33,11 +33,11 @@ import ( ) func init() { - v0miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ + miner0.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } - v0power.ConsensusMinerMinPower = big.NewInt(2048) - v0verifreg.MinVerifiedDealSize = big.NewInt(256) + power0.ConsensusMinerMinPower = big.NewInt(2048) + verifreg0.MinVerifiedDealSize = big.NewInt(256) } const testForkHeight = 40 diff --git a/chain/stmgr/stmgr.go b/chain/stmgr/stmgr.go index d183b7ce2..e6e557930 100644 --- a/chain/stmgr/stmgr.go +++ b/chain/stmgr/stmgr.go @@ -5,7 +5,7 @@ import ( "fmt" "sync" - v0msig "github.com/filecoin-project/specs-actors/actors/builtin/multisig" + msig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig" "github.com/filecoin-project/lotus/chain/actors/builtin/multisig" @@ -23,7 +23,7 @@ import ( "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/network" "github.com/filecoin-project/specs-actors/actors/builtin" - v0reward "github.com/filecoin-project/specs-actors/actors/builtin/reward" + reward0 "github.com/filecoin-project/specs-actors/actors/builtin/reward" "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/filecoin-project/lotus/api" @@ -251,7 +251,7 @@ func (sm *StateManager) ApplyBlocks(ctx context.Context, parentEpoch abi.ChainEp nv := sm.GetNtwkVersion(ctx, epoch) if nv < build.ActorUpgradeNetworkVersion { - params, err = actors.SerializeParams(&v0reward.AwardBlockRewardParams{ + params, err = actors.SerializeParams(&reward0.AwardBlockRewardParams{ Miner: b.Miner, Penalty: penalty, GasReward: gasReward, @@ -797,7 +797,7 @@ func (sm *StateManager) SetVMConstructor(nvm func(context.Context, *vm.VMOpts) ( } type genesisInfo struct { - genesisMsigs []v0msig.State + genesisMsigs []msig0.State // info about the Accounts in the genesis state genesisActors []genesisActor genesisPledge abi.TokenAmount @@ -898,9 +898,9 @@ func (sm *StateManager) setupGenesisActors(ctx context.Context) error { return xerrors.Errorf("error setting up genesis infos: %w", err) } - gi.genesisMsigs = make([]v0msig.State, 0, len(totalsByEpoch)) + gi.genesisMsigs = make([]msig0.State, 0, len(totalsByEpoch)) for k, v := range totalsByEpoch { - ns := v0msig.State{ + ns := msig0.State{ InitialBalance: v, UnlockDuration: k, PendingTxns: cid.Undef, @@ -975,9 +975,9 @@ func (sm *StateManager) setupGenesisActorsTestnet(ctx context.Context) error { totalsByEpoch[sixYears] = big.NewInt(100_000_000) totalsByEpoch[sixYears] = big.Add(totalsByEpoch[sixYears], big.NewInt(300_000_000)) - gi.genesisMsigs = make([]v0msig.State, 0, len(totalsByEpoch)) + gi.genesisMsigs = make([]msig0.State, 0, len(totalsByEpoch)) for k, v := range totalsByEpoch { - ns := v0msig.State{ + ns := msig0.State{ InitialBalance: v, UnlockDuration: k, PendingTxns: cid.Undef, diff --git a/chain/stmgr/utils.go b/chain/stmgr/utils.go index 8c55fc1f2..3684b9e77 100644 --- a/chain/stmgr/utils.go +++ b/chain/stmgr/utils.go @@ -9,11 +9,11 @@ import ( "runtime" "strings" - v0init "github.com/filecoin-project/specs-actors/actors/builtin/init" - v0market "github.com/filecoin-project/specs-actors/actors/builtin/market" - v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" + init0 "github.com/filecoin-project/specs-actors/actors/builtin/init" + market0 "github.com/filecoin-project/specs-actors/actors/builtin/market" + power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" saruntime "github.com/filecoin-project/specs-actors/actors/runtime" "github.com/filecoin-project/specs-actors/actors/runtime/proof" @@ -31,10 +31,10 @@ import ( "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin/account" "github.com/filecoin-project/specs-actors/actors/builtin/cron" - v0msig "github.com/filecoin-project/specs-actors/actors/builtin/multisig" + msig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig" "github.com/filecoin-project/specs-actors/actors/builtin/paych" - v0reward "github.com/filecoin-project/specs-actors/actors/builtin/reward" - v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + reward0 "github.com/filecoin-project/specs-actors/actors/builtin/reward" + verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" @@ -169,7 +169,7 @@ func GetMinerSectorSet(ctx context.Context, sm *StateManager, ts *types.TipSet, var sset []*miner.ChainSectorInfo var v cbg.Deferred if err := sectors.ForEach(&v, func(i int64) error { - var oci v0miner.SectorOnChainInfo + var oci miner0.SectorOnChainInfo if err := oci.UnmarshalCBOR(bytes.NewReader(v.Raw)); err != nil { return err } @@ -555,16 +555,16 @@ var MethodsMap = map[cid.Cid]map[abi.MethodNum]MethodMeta{} func init() { cidToMethods := map[cid.Cid][2]interface{}{ // builtin.SystemActorCodeID: {builtin.MethodsSystem, system.Actor{} }- apparently it doesn't have methods - builtin.InitActorCodeID: {builtin.MethodsInit, v0init.Actor{}}, + builtin.InitActorCodeID: {builtin.MethodsInit, init0.Actor{}}, builtin.CronActorCodeID: {builtin.MethodsCron, cron.Actor{}}, builtin.AccountActorCodeID: {builtin.MethodsAccount, account.Actor{}}, - builtin.StoragePowerActorCodeID: {builtin.MethodsPower, v0power.Actor{}}, - builtin.StorageMinerActorCodeID: {builtin.MethodsMiner, v0miner.Actor{}}, - builtin.StorageMarketActorCodeID: {builtin.MethodsMarket, v0market.Actor{}}, + builtin.StoragePowerActorCodeID: {builtin.MethodsPower, power0.Actor{}}, + builtin.StorageMinerActorCodeID: {builtin.MethodsMiner, miner0.Actor{}}, + builtin.StorageMarketActorCodeID: {builtin.MethodsMarket, market0.Actor{}}, builtin.PaymentChannelActorCodeID: {builtin.MethodsPaych, paych.Actor{}}, - builtin.MultisigActorCodeID: {builtin.MethodsMultisig, v0msig.Actor{}}, - builtin.RewardActorCodeID: {builtin.MethodsReward, v0reward.Actor{}}, - builtin.VerifiedRegistryActorCodeID: {builtin.MethodsVerifiedRegistry, v0verifreg.Actor{}}, + builtin.MultisigActorCodeID: {builtin.MethodsMultisig, msig0.Actor{}}, + builtin.RewardActorCodeID: {builtin.MethodsReward, reward0.Actor{}}, + builtin.VerifiedRegistryActorCodeID: {builtin.MethodsVerifiedRegistry, verifreg0.Actor{}}, } for c, m := range cidToMethods { diff --git a/chain/store/store_test.go b/chain/store/store_test.go index 83238a67d..d5e092559 100644 --- a/chain/store/store_test.go +++ b/chain/store/store_test.go @@ -10,9 +10,9 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" - v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" - v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" + power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" + verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/lotus/chain/gen" "github.com/filecoin-project/lotus/chain/store" @@ -22,11 +22,11 @@ import ( ) func init() { - v0miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ + miner0.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } - v0power.ConsensusMinerMinPower = big.NewInt(2048) - v0verifreg.MinVerifiedDealSize = big.NewInt(256) + power0.ConsensusMinerMinPower = big.NewInt(2048) + verifreg0.MinVerifiedDealSize = big.NewInt(256) } func BenchmarkGetRandomness(b *testing.B) { diff --git a/chain/sync_test.go b/chain/sync_test.go index 2baa5d8a4..53001caf8 100644 --- a/chain/sync_test.go +++ b/chain/sync_test.go @@ -20,9 +20,9 @@ import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" - v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" - v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" + power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" + verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" @@ -43,11 +43,11 @@ func init() { if err != nil { panic(err) } - v0miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ + miner0.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } - v0power.ConsensusMinerMinPower = big.NewInt(2048) - v0verifreg.MinVerifiedDealSize = big.NewInt(256) + power0.ConsensusMinerMinPower = big.NewInt(2048) + verifreg0.MinVerifiedDealSize = big.NewInt(256) } const source = 0 diff --git a/chain/vectors/gen/main.go b/chain/vectors/gen/main.go index 36b770f03..2b1c6f340 100644 --- a/chain/vectors/gen/main.go +++ b/chain/vectors/gen/main.go @@ -6,7 +6,7 @@ import ( "math/rand" "os" - v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" + power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" "github.com/filecoin-project/go-address" "golang.org/x/xerrors" @@ -19,15 +19,15 @@ import ( "github.com/filecoin-project/lotus/chain/types/mock" "github.com/filecoin-project/lotus/chain/vectors" "github.com/filecoin-project/lotus/chain/wallet" - v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" _ "github.com/filecoin-project/lotus/lib/sigs/bls" _ "github.com/filecoin-project/lotus/lib/sigs/secp" ) func init() { - v0verifreg.MinVerifiedDealSize = big.NewInt(2048) - v0power.ConsensusMinerMinPower = big.NewInt(2048) + verifreg0.MinVerifiedDealSize = big.NewInt(2048) + power0.ConsensusMinerMinPower = big.NewInt(2048) } func MakeHeaderVectors() []vectors.HeaderVector { diff --git a/chain/vm/invoker.go b/chain/vm/invoker.go index 501b933e2..0a83e273d 100644 --- a/chain/vm/invoker.go +++ b/chain/vm/invoker.go @@ -10,18 +10,18 @@ import ( cbg "github.com/whyrusleeping/cbor-gen" "golang.org/x/xerrors" - v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" - v0account "github.com/filecoin-project/specs-actors/actors/builtin/account" - v0cron "github.com/filecoin-project/specs-actors/actors/builtin/cron" - v0init "github.com/filecoin-project/specs-actors/actors/builtin/init" - v0market "github.com/filecoin-project/specs-actors/actors/builtin/market" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" - v0msig "github.com/filecoin-project/specs-actors/actors/builtin/multisig" - v0paych "github.com/filecoin-project/specs-actors/actors/builtin/paych" - v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" - v0reward "github.com/filecoin-project/specs-actors/actors/builtin/reward" - v0system "github.com/filecoin-project/specs-actors/actors/builtin/system" - v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" + account0 "github.com/filecoin-project/specs-actors/actors/builtin/account" + cron0 "github.com/filecoin-project/specs-actors/actors/builtin/cron" + init0 "github.com/filecoin-project/specs-actors/actors/builtin/init" + market0 "github.com/filecoin-project/specs-actors/actors/builtin/market" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" + msig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig" + paych0 "github.com/filecoin-project/specs-actors/actors/builtin/paych" + power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" + reward0 "github.com/filecoin-project/specs-actors/actors/builtin/reward" + system0 "github.com/filecoin-project/specs-actors/actors/builtin/system" + verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" vmr "github.com/filecoin-project/specs-actors/actors/runtime" "github.com/filecoin-project/go-state-types/abi" @@ -46,17 +46,17 @@ func NewInvoker() *Invoker { // add builtInCode using: register(cid, singleton) // NETUPGRADE: register code IDs for v2, etc. - inv.Register(v0builtin.SystemActorCodeID, v0system.Actor{}, abi.EmptyValue{}) - inv.Register(v0builtin.InitActorCodeID, v0init.Actor{}, v0init.State{}) - inv.Register(v0builtin.RewardActorCodeID, v0reward.Actor{}, v0reward.State{}) - inv.Register(v0builtin.CronActorCodeID, v0cron.Actor{}, v0cron.State{}) - inv.Register(v0builtin.StoragePowerActorCodeID, v0power.Actor{}, v0power.State{}) - inv.Register(v0builtin.StorageMarketActorCodeID, v0market.Actor{}, v0market.State{}) - inv.Register(v0builtin.StorageMinerActorCodeID, v0miner.Actor{}, v0miner.State{}) - inv.Register(v0builtin.MultisigActorCodeID, v0msig.Actor{}, v0msig.State{}) - inv.Register(v0builtin.PaymentChannelActorCodeID, v0paych.Actor{}, v0paych.State{}) - inv.Register(v0builtin.VerifiedRegistryActorCodeID, v0verifreg.Actor{}, v0verifreg.State{}) - inv.Register(v0builtin.AccountActorCodeID, v0account.Actor{}, v0account.State{}) + inv.Register(builtin0.SystemActorCodeID, system0.Actor{}, abi.EmptyValue{}) + inv.Register(builtin0.InitActorCodeID, init0.Actor{}, init0.State{}) + inv.Register(builtin0.RewardActorCodeID, reward0.Actor{}, reward0.State{}) + inv.Register(builtin0.CronActorCodeID, cron0.Actor{}, cron0.State{}) + inv.Register(builtin0.StoragePowerActorCodeID, power0.Actor{}, power0.State{}) + inv.Register(builtin0.StorageMarketActorCodeID, market0.Actor{}, market0.State{}) + inv.Register(builtin0.StorageMinerActorCodeID, miner0.Actor{}, miner0.State{}) + inv.Register(builtin0.MultisigActorCodeID, msig0.Actor{}, msig0.State{}) + inv.Register(builtin0.PaymentChannelActorCodeID, paych0.Actor{}, paych0.State{}) + inv.Register(builtin0.VerifiedRegistryActorCodeID, verifreg0.Actor{}, verifreg0.State{}) + inv.Register(builtin0.AccountActorCodeID, account0.Actor{}, account0.State{}) return inv } @@ -177,7 +177,7 @@ func DecodeParams(b []byte, out interface{}) error { } func DumpActorState(code cid.Cid, b []byte) (interface{}, error) { - if code == v0builtin.AccountActorCodeID { // Account code special case + if code == builtin0.AccountActorCodeID { // Account code special case return nil, nil } diff --git a/cli/multisig.go b/cli/multisig.go index ffbbd733b..23095bf06 100644 --- a/cli/multisig.go +++ b/cli/multisig.go @@ -17,7 +17,7 @@ import ( "github.com/filecoin-project/go-address" init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" - v0msig "github.com/filecoin-project/specs-actors/actors/builtin/multisig" + msig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig" cid "github.com/ipfs/go-cid" cbor "github.com/ipfs/go-ipld-cbor" "github.com/urfave/cli/v2" @@ -199,7 +199,7 @@ var msigInspectCmd = &cli.Command{ return err } - var mstate v0msig.State + var mstate msig0.State if err := mstate.UnmarshalCBOR(bytes.NewReader(obj)); err != nil { return err } @@ -251,7 +251,7 @@ var msigInspectCmd = &cli.Command{ }, } -func GetMultisigPending(ctx context.Context, lapi api.FullNode, hroot cid.Cid) (map[int64]*v0msig.Transaction, error) { +func GetMultisigPending(ctx context.Context, lapi api.FullNode, hroot cid.Cid) (map[int64]*msig0.Transaction, error) { bs := apibstore.NewAPIBlockstore(lapi) store := adt.WrapStore(ctx, cbor.NewCborStore(bs)) @@ -260,8 +260,8 @@ func GetMultisigPending(ctx context.Context, lapi api.FullNode, hroot cid.Cid) ( return nil, err } - txs := make(map[int64]*v0msig.Transaction) - var tx v0msig.Transaction + txs := make(map[int64]*msig0.Transaction) + var tx msig0.Transaction err = nd.ForEach(&tx, func(k string) error { txid, _ := binary.Varint([]byte(k)) @@ -276,7 +276,7 @@ func GetMultisigPending(ctx context.Context, lapi api.FullNode, hroot cid.Cid) ( return txs, nil } -func state(tx *v0msig.Transaction) string { +func state(tx *msig0.Transaction) string { /* // TODO(why): I strongly disagree with not having these... but i need to move forward if tx.Complete { return "done" @@ -385,7 +385,7 @@ var msigProposeCmd = &cli.Command{ return fmt.Errorf("proposal returned exit %d", wait.Receipt.ExitCode) } - var retval v0msig.ProposeReturn + var retval msig0.ProposeReturn if err := retval.UnmarshalCBOR(bytes.NewReader(wait.Receipt.Return)); err != nil { return fmt.Errorf("failed to unmarshal propose return value: %w", err) } diff --git a/cli/paych_test.go b/cli/paych_test.go index 598c178eb..49631f1fc 100644 --- a/cli/paych_test.go +++ b/cli/paych_test.go @@ -15,9 +15,9 @@ import ( "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/go-state-types/big" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" - v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" - v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" + power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" + verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/multiformats/go-multiaddr" @@ -40,11 +40,11 @@ import ( ) func init() { - v0power.ConsensusMinerMinPower = big.NewInt(2048) - v0miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ + power0.ConsensusMinerMinPower = big.NewInt(2048) + miner0.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } - v0verifreg.MinVerifiedDealSize = big.NewInt(256) + verifreg0.MinVerifiedDealSize = big.NewInt(256) } // TestPaymentChannels does a basic test to exercise the payment channel CLI diff --git a/cmd/lotus-pcr/main.go b/cmd/lotus-pcr/main.go index 53c8223ed..c8179d9b6 100644 --- a/cmd/lotus-pcr/main.go +++ b/cmd/lotus-pcr/main.go @@ -12,7 +12,7 @@ import ( "strconv" "time" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/go-state-types/network" "github.com/filecoin-project/lotus/chain/actors/builtin/miner" @@ -403,7 +403,7 @@ func (r *refunder) ProcessTipset(ctx context.Context, tipset *types.TipSet, refu } if nv < build.ActorUpgradeNetworkVersion { - var proveCommitSector v0miner.ProveCommitSectorParams + var proveCommitSector miner0.ProveCommitSectorParams if err := proveCommitSector.UnmarshalCBOR(bytes.NewBuffer(m.Params)); err != nil { log.Warnw("failed to decode provecommit params", "err", err, "method", messageMethod, "cid", msg.Cid, "miner", m.To) continue diff --git a/cmd/lotus-storage-miner/actor.go b/cmd/lotus-storage-miner/actor.go index 2493c5a1e..ea21aa90d 100644 --- a/cmd/lotus-storage-miner/actor.go +++ b/cmd/lotus-storage-miner/actor.go @@ -16,7 +16,7 @@ import ( "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/specs-actors/actors/builtin" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/actors" "github.com/filecoin-project/lotus/chain/types" @@ -88,7 +88,7 @@ var actorSetAddrsCmd = &cli.Command{ return err } - params, err := actors.SerializeParams(&v0miner.ChangeMultiaddrsParams{NewMultiaddrs: addrs}) + params, err := actors.SerializeParams(&miner0.ChangeMultiaddrsParams{NewMultiaddrs: addrs}) if err != nil { return err } @@ -153,7 +153,7 @@ var actorSetPeeridCmd = &cli.Command{ return err } - params, err := actors.SerializeParams(&v0miner.ChangePeerIDParams{NewID: abi.PeerID(pid)}) + params, err := actors.SerializeParams(&miner0.ChangePeerIDParams{NewID: abi.PeerID(pid)}) if err != nil { return err } @@ -226,7 +226,7 @@ var actorWithdrawCmd = &cli.Command{ } } - params, err := actors.SerializeParams(&v0miner.WithdrawBalanceParams{ + params, err := actors.SerializeParams(&miner0.WithdrawBalanceParams{ AmountRequested: amount, // Default to attempting to withdraw all the extra funds in the miner actor }) if err != nil { @@ -451,7 +451,7 @@ var actorControlSet = &cli.Command{ return nil } - cwp := &v0miner.ChangeWorkerAddressParams{ + cwp := &miner0.ChangeWorkerAddressParams{ NewWorker: mi.Worker, NewControlAddrs: toSet, } diff --git a/cmd/lotus-storage-miner/init.go b/cmd/lotus-storage-miner/init.go index 715daead8..4faf6a25b 100644 --- a/cmd/lotus-storage-miner/init.go +++ b/cmd/lotus-storage-miner/init.go @@ -32,10 +32,10 @@ import ( "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" "github.com/filecoin-project/lotus/extern/sector-storage/stores" - v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" - v0market "github.com/filecoin-project/specs-actors/actors/builtin/market" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" - v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" + market0 "github.com/filecoin-project/specs-actors/actors/builtin/market" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" + power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" lapi "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" @@ -373,7 +373,7 @@ func migratePreSealMeta(ctx context.Context, api lapi.FullNode, metadata string, return mds.Put(datastore.NewKey(modules.StorageCounterDSPrefix), buf[:size]) } -func findMarketDealID(ctx context.Context, api lapi.FullNode, deal v0market.DealProposal) (abi.DealID, error) { +func findMarketDealID(ctx context.Context, api lapi.FullNode, deal market0.DealProposal) (abi.DealID, error) { // TODO: find a better way // (this is only used by genesis miners) @@ -567,7 +567,7 @@ func configureStorageMiner(ctx context.Context, api lapi.FullNode, addr address. return xerrors.Errorf("getWorkerAddr returned bad address: %w", err) } - enc, err := actors.SerializeParams(&v0miner.ChangePeerIDParams{NewID: abi.PeerID(peerid)}) + enc, err := actors.SerializeParams(&miner0.ChangePeerIDParams{NewID: abi.PeerID(peerid)}) if err != nil { return err } @@ -575,7 +575,7 @@ func configureStorageMiner(ctx context.Context, api lapi.FullNode, addr address. msg := &types.Message{ To: addr, From: mi.Worker, - Method: v0builtin.MethodsMiner.ChangePeerID, + Method: builtin0.MethodsMiner.ChangePeerID, Params: enc, Value: types.NewInt(0), GasPremium: gasPrice, @@ -634,7 +634,7 @@ func createStorageMiner(ctx context.Context, api lapi.FullNode, peerid peer.ID, return address.Undef, err } - params, err := actors.SerializeParams(&v0power.CreateMinerParams{ + params, err := actors.SerializeParams(&power0.CreateMinerParams{ Owner: owner, Worker: worker, SealProofType: spt, @@ -654,11 +654,11 @@ func createStorageMiner(ctx context.Context, api lapi.FullNode, peerid peer.ID, } createStorageMinerMsg := &types.Message{ - To: v0builtin.StoragePowerActorAddr, + To: builtin0.StoragePowerActorAddr, From: sender, Value: big.Zero(), - Method: v0builtin.MethodsPower.CreateMiner, + Method: builtin0.MethodsPower.CreateMiner, Params: params, GasLimit: 0, @@ -682,7 +682,7 @@ func createStorageMiner(ctx context.Context, api lapi.FullNode, peerid peer.ID, return address.Undef, xerrors.Errorf("create miner failed: exit code %d", mw.Receipt.ExitCode) } - var retval v0power.CreateMinerReturn + var retval power0.CreateMinerReturn if err := retval.UnmarshalCBOR(bytes.NewReader(mw.Receipt.Return)); err != nil { return address.Undef, err } diff --git a/cmd/lotus-storage-miner/sectors.go b/cmd/lotus-storage-miner/sectors.go index 5659bed79..83550dbda 100644 --- a/cmd/lotus-storage-miner/sectors.go +++ b/cmd/lotus-storage-miner/sectors.go @@ -13,7 +13,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/chain/actors/builtin/miner" @@ -380,7 +380,7 @@ var sectorsCapacityCollateralCmd = &cli.Command{ Expiration: abi.ChainEpoch(cctx.Uint64("expiration")), } if pci.Expiration == 0 { - pci.Expiration = v0miner.MaxSectorExpirationExtension + pci.Expiration = miner0.MaxSectorExpirationExtension } pc, err := nApi.StateMinerInitialPledgeCollateral(ctx, maddr, pci, types.EmptyTSK) if err != nil { diff --git a/extern/storage-sealing/checks.go b/extern/storage-sealing/checks.go index 677cef1e9..27b62f49a 100644 --- a/extern/storage-sealing/checks.go +++ b/extern/storage-sealing/checks.go @@ -5,9 +5,9 @@ import ( "context" "github.com/filecoin-project/lotus/build" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" - v0proof "github.com/filecoin-project/specs-actors/actors/runtime/proof" + proof0 "github.com/filecoin-project/specs-actors/actors/runtime/proof" "golang.org/x/xerrors" @@ -102,7 +102,7 @@ func checkPrecommit(ctx context.Context, maddr address.Address, si SectorInfo, t var msd abi.ChainEpoch if nv < build.ActorUpgradeNetworkVersion { - msd = v0miner.MaxSealDuration[si.SectorType] + msd = miner0.MaxSealDuration[si.SectorType] } else { // TODO: ActorUpgrade msd = 0 @@ -190,7 +190,7 @@ func (m *Sealing) checkCommit(ctx context.Context, si SectorInfo, proof []byte, log.Warn("on-chain sealed CID doesn't match!") } - ok, err := m.verif.VerifySeal(v0proof.SealVerifyInfo{ + ok, err := m.verif.VerifySeal(proof0.SealVerifyInfo{ SectorID: m.minerSector(si.SectorNumber), SealedCID: pci.Info.SealedCID, SealProof: spt, diff --git a/extern/storage-sealing/constants.go b/extern/storage-sealing/constants.go index 06c48fa4c..8c7fa5abc 100644 --- a/extern/storage-sealing/constants.go +++ b/extern/storage-sealing/constants.go @@ -1,11 +1,11 @@ package sealing import ( - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" ) // Epochs -const SealRandomnessLookback = v0miner.ChainFinality +const SealRandomnessLookback = miner0.ChainFinality // Epochs const InteractivePoRepConfidence = 6 diff --git a/extern/storage-sealing/precommit_policy.go b/extern/storage-sealing/precommit_policy.go index 76d867144..2ee6c1afc 100644 --- a/extern/storage-sealing/precommit_policy.go +++ b/extern/storage-sealing/precommit_policy.go @@ -7,7 +7,7 @@ import ( "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/go-state-types/abi" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" ) type PreCommitPolicy interface { @@ -87,7 +87,7 @@ func (p *BasicPreCommitPolicy) Expiration(ctx context.Context, ps ...Piece) (abi var wpp abi.ChainEpoch if nv < build.ActorUpgradeNetworkVersion { - wpp = v0miner.WPoStProvingPeriod + wpp = miner0.WPoStProvingPeriod } else { // TODO: ActorUpgrade wpp = 0 diff --git a/extern/storage-sealing/sealing.go b/extern/storage-sealing/sealing.go index 01551e6d7..d5772e1d6 100644 --- a/extern/storage-sealing/sealing.go +++ b/extern/storage-sealing/sealing.go @@ -9,7 +9,7 @@ import ( "time" "github.com/filecoin-project/lotus/build" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/go-state-types/network" "github.com/ipfs/go-cid" @@ -430,7 +430,7 @@ func (m *Sealing) getPreCommitChallengeDelay(ctx context.Context, tok TipSetToke } if nv < build.ActorUpgradeNetworkVersion { - return v0miner.PreCommitChallengeDelay, nil + return miner0.PreCommitChallengeDelay, nil } // TODO: ActorUpgrade diff --git a/extern/storage-sealing/states_sealing.go b/extern/storage-sealing/states_sealing.go index 6ae42a91f..0109326fb 100644 --- a/extern/storage-sealing/states_sealing.go +++ b/extern/storage-sealing/states_sealing.go @@ -6,7 +6,7 @@ import ( "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/actors/builtin/miner" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" "golang.org/x/xerrors" @@ -191,8 +191,8 @@ func (m *Sealing) handlePreCommitting(ctx statemachine.Context, sector SectorInf var msd abi.ChainEpoch var mse abi.ChainEpoch if nv < build.ActorUpgradeNetworkVersion { - msd = v0miner.MaxSealDuration[sector.SectorType] - mse = v0miner.MinSectorExpiration + msd = miner0.MaxSealDuration[sector.SectorType] + mse = miner0.MinSectorExpiration } else { // TODO: ActorUpgrade msd = 0 @@ -387,7 +387,7 @@ func (m *Sealing) handleSubmitCommit(ctx statemachine.Context, sector SectorInfo enc := new(bytes.Buffer) if nv < build.ActorUpgradeNetworkVersion { - params := &v0miner.ProveCommitSectorParams{ + params := &miner0.ProveCommitSectorParams{ SectorNumber: sector.SectorNumber, Proof: sector.Proof, } diff --git a/node/impl/client/client.go b/node/impl/client/client.go index 6c60269ab..8b47144af 100644 --- a/node/impl/client/client.go +++ b/node/impl/client/client.go @@ -41,7 +41,7 @@ import ( "github.com/filecoin-project/go-multistore" "github.com/filecoin-project/go-padreader" "github.com/filecoin-project/go-state-types/abi" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" marketevents "github.com/filecoin-project/lotus/markets/loggers" @@ -87,7 +87,7 @@ func calcDealExpiration(minDuration uint64, md *dline.Info, startEpoch abi.Chain minExp := startEpoch + abi.ChainEpoch(minDuration) // Align on miners ProvingPeriodBoundary - return minExp + v0miner.WPoStProvingPeriod - (minExp % v0miner.WPoStProvingPeriod) + (md.PeriodStart % v0miner.WPoStProvingPeriod) - 1 + return minExp + miner0.WPoStProvingPeriod - (minExp % miner0.WPoStProvingPeriod) + (md.PeriodStart % miner0.WPoStProvingPeriod) - 1 } func (a *API) imgr() *importmgr.Mgr { diff --git a/node/impl/full/state.go b/node/impl/full/state.go index 3bed0dfbb..76bd3926b 100644 --- a/node/impl/full/state.go +++ b/node/impl/full/state.go @@ -5,7 +5,7 @@ import ( "context" "strconv" - v0market "github.com/filecoin-project/specs-actors/actors/builtin/market" + market0 "github.com/filecoin-project/specs-actors/actors/builtin/market" "github.com/filecoin-project/lotus/chain/actors/builtin/verifreg" @@ -24,7 +24,7 @@ import ( "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" "github.com/filecoin-project/specs-actors/actors/builtin" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/filecoin-project/specs-actors/actors/util/smoothing" @@ -921,7 +921,7 @@ func (a *StateAPI) StateMinerPreCommitDepositForPower(ctx context.Context, maddr duration := pci.Expiration - ts.Height() // TODO: ActorUpgrade - sectorWeight = v0miner.QAPowerForWeight(ssize, duration, w, vw) + sectorWeight = miner0.QAPowerForWeight(ssize, duration, w, vw) } var powerSmoothed smoothing.FilterEstimate @@ -947,7 +947,7 @@ func (a *StateAPI) StateMinerPreCommitDepositForPower(ctx context.Context, maddr } // TODO: ActorUpgrade - deposit := v0miner.PreCommitDepositForPower(&rewardSmoothed, &powerSmoothed, sectorWeight) + deposit := miner0.PreCommitDepositForPower(&rewardSmoothed, &powerSmoothed, sectorWeight) return types.BigDiv(types.BigMul(deposit, initialPledgeNum), initialPledgeDen), nil } @@ -983,7 +983,7 @@ func (a *StateAPI) StateMinerInitialPledgeCollateral(ctx context.Context, maddr duration := pci.Expiration - ts.Height() // TODO: handle changes to this function across actor upgrades. - sectorWeight = v0miner.QAPowerForWeight(ssize, duration, w, vw) + sectorWeight = miner0.QAPowerForWeight(ssize, duration, w, vw) } var ( @@ -1027,7 +1027,7 @@ func (a *StateAPI) StateMinerInitialPledgeCollateral(ctx context.Context, maddr // TODO: ActorUpgrade - initialPledge := v0miner.InitialPledgeForPower( + initialPledge := miner0.InitialPledgeForPower( sectorWeight, baselinePower, pledgeCollateral, @@ -1145,7 +1145,7 @@ func (a *StateAPI) StateDealProviderCollateralBounds(ctx context.Context, size a return api.DealCollateralBounds{}, xerrors.Errorf("getting reward baseline power: %w", err) } - min, max := v0market.DealProviderCollateralBounds(size, + min, max := market0.DealProviderCollateralBounds(size, verified, powClaim.RawBytePower, powClaim.QualityAdjPower, diff --git a/node/node_test.go b/node/node_test.go index 68ee178fc..0e404dc0b 100644 --- a/node/node_test.go +++ b/node/node_test.go @@ -10,9 +10,9 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/lotus/lib/lotuslog" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" - v0power "github.com/filecoin-project/specs-actors/actors/builtin/power" - v0verifreg "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" + power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" + verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" logging "github.com/ipfs/go-log/v2" "github.com/filecoin-project/lotus/api/test" @@ -21,11 +21,11 @@ import ( func init() { _ = logging.SetLogLevel("*", "INFO") - v0power.ConsensusMinerMinPower = big.NewInt(2048) - v0miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ + power0.ConsensusMinerMinPower = big.NewInt(2048) + miner0.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ abi.RegisteredSealProof_StackedDrg2KiBV1: {}, } - v0verifreg.MinVerifiedDealSize = big.NewInt(256) + verifreg0.MinVerifiedDealSize = big.NewInt(256) } func TestAPI(t *testing.T) { @@ -68,7 +68,7 @@ func TestAPIDealFlowReal(t *testing.T) { logging.SetLogLevel("sub", "ERROR") logging.SetLogLevel("storageminer", "ERROR") - v0miner.PreCommitChallengeDelay = 5 + miner0.PreCommitChallengeDelay = 5 t.Run("basic", func(t *testing.T) { test.TestDealFlow(t, builder.Builder, time.Second, false, false) diff --git a/node/test/builder.go b/node/test/builder.go index 2b26c13fc..c496b1e4c 100644 --- a/node/test/builder.go +++ b/node/test/builder.go @@ -37,7 +37,7 @@ import ( "github.com/filecoin-project/lotus/node/repo" "github.com/filecoin-project/lotus/storage/mockstorage" "github.com/filecoin-project/specs-actors/actors/builtin" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/ipfs/go-datastore" "github.com/libp2p/go-libp2p-core/crypto" "github.com/libp2p/go-libp2p-core/peer" @@ -83,7 +83,7 @@ func CreateTestStorageNode(ctx context.Context, t *testing.T, waddr address.Addr peerid, err := peer.IDFromPrivateKey(pk) require.NoError(t, err) - enc, err := actors.SerializeParams(&v0miner.ChangePeerIDParams{NewID: abi.PeerID(peerid)}) + enc, err := actors.SerializeParams(&miner0.ChangePeerIDParams{NewID: abi.PeerID(peerid)}) require.NoError(t, err) msg := &types.Message{ diff --git a/paychmgr/manager.go b/paychmgr/manager.go index 4556c37be..d9c568cbe 100644 --- a/paychmgr/manager.go +++ b/paychmgr/manager.go @@ -12,7 +12,7 @@ import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/crypto" - v0paych "github.com/filecoin-project/specs-actors/actors/builtin/paych" + paych0 "github.com/filecoin-project/specs-actors/actors/builtin/paych" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/chain/actors/adt" @@ -221,7 +221,7 @@ func (pm *Manager) GetChannelInfo(addr address.Address) (*ChannelInfo, error) { return ca.getChannelInfo(addr) } -func (pm *Manager) CreateVoucher(ctx context.Context, ch address.Address, voucher v0paych.SignedVoucher) (*api.VoucherCreateResult, error) { +func (pm *Manager) CreateVoucher(ctx context.Context, ch address.Address, voucher paych0.SignedVoucher) (*api.VoucherCreateResult, error) { ca, err := pm.accessorByAddress(ch) if err != nil { return nil, err @@ -233,7 +233,7 @@ func (pm *Manager) CreateVoucher(ctx context.Context, ch address.Address, vouche // CheckVoucherValid checks if the given voucher is valid (is or could become spendable at some point). // If the channel is not in the store, fetches the channel from state (and checks that // the channel To address is owned by the wallet). -func (pm *Manager) CheckVoucherValid(ctx context.Context, ch address.Address, sv *v0paych.SignedVoucher) error { +func (pm *Manager) CheckVoucherValid(ctx context.Context, ch address.Address, sv *paych0.SignedVoucher) error { // Get an accessor for the channel, creating it from state if necessary ca, err := pm.inboundChannelAccessor(ctx, ch) if err != nil { @@ -245,7 +245,7 @@ func (pm *Manager) CheckVoucherValid(ctx context.Context, ch address.Address, sv } // CheckVoucherSpendable checks if the given voucher is currently spendable -func (pm *Manager) CheckVoucherSpendable(ctx context.Context, ch address.Address, sv *v0paych.SignedVoucher, secret []byte, proof []byte) (bool, error) { +func (pm *Manager) CheckVoucherSpendable(ctx context.Context, ch address.Address, sv *paych0.SignedVoucher, secret []byte, proof []byte) (bool, error) { ca, err := pm.accessorByAddress(ch) if err != nil { return false, err @@ -256,7 +256,7 @@ func (pm *Manager) CheckVoucherSpendable(ctx context.Context, ch address.Address // AddVoucherOutbound adds a voucher for an outbound channel. // Returns an error if the channel is not already in the store. -func (pm *Manager) AddVoucherOutbound(ctx context.Context, ch address.Address, sv *v0paych.SignedVoucher, proof []byte, minDelta types.BigInt) (types.BigInt, error) { +func (pm *Manager) AddVoucherOutbound(ctx context.Context, ch address.Address, sv *paych0.SignedVoucher, proof []byte, minDelta types.BigInt) (types.BigInt, error) { ca, err := pm.accessorByAddress(ch) if err != nil { return types.NewInt(0), err @@ -267,7 +267,7 @@ func (pm *Manager) AddVoucherOutbound(ctx context.Context, ch address.Address, s // AddVoucherInbound adds a voucher for an inbound channel. // If the channel is not in the store, fetches the channel from state (and checks that // the channel To address is owned by the wallet). -func (pm *Manager) AddVoucherInbound(ctx context.Context, ch address.Address, sv *v0paych.SignedVoucher, proof []byte, minDelta types.BigInt) (types.BigInt, error) { +func (pm *Manager) AddVoucherInbound(ctx context.Context, ch address.Address, sv *paych0.SignedVoucher, proof []byte, minDelta types.BigInt) (types.BigInt, error) { // Get an accessor for the channel, creating it from state if necessary ca, err := pm.inboundChannelAccessor(ctx, ch) if err != nil { @@ -336,7 +336,7 @@ func (pm *Manager) trackInboundChannel(ctx context.Context, ch address.Address) return pm.store.TrackChannel(stateCi) } -func (pm *Manager) SubmitVoucher(ctx context.Context, ch address.Address, sv *v0paych.SignedVoucher, secret []byte, proof []byte) (cid.Cid, error) { +func (pm *Manager) SubmitVoucher(ctx context.Context, ch address.Address, sv *paych0.SignedVoucher, secret []byte, proof []byte) (cid.Cid, error) { ca, err := pm.accessorByAddress(ch) if err != nil { return cid.Undef, err diff --git a/paychmgr/paych.go b/paychmgr/paych.go index 53f16b4fc..11dfd2a1e 100644 --- a/paychmgr/paych.go +++ b/paychmgr/paych.go @@ -12,7 +12,7 @@ import ( cborutil "github.com/filecoin-project/go-cbor-util" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/specs-actors/actors/builtin" - v0paych "github.com/filecoin-project/specs-actors/actors/builtin/paych" + paych0 "github.com/filecoin-project/specs-actors/actors/builtin/paych" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/chain/actors" @@ -103,7 +103,7 @@ func (ca *channelAccessor) outboundActiveByFromTo(from, to address.Address) (*Ch // nonce, signing the voucher and storing it in the local datastore. // If there are not enough funds in the channel to create the voucher, returns // the shortfall in funds. -func (ca *channelAccessor) createVoucher(ctx context.Context, ch address.Address, voucher v0paych.SignedVoucher) (*api.VoucherCreateResult, error) { +func (ca *channelAccessor) createVoucher(ctx context.Context, ch address.Address, voucher paych0.SignedVoucher) (*api.VoucherCreateResult, error) { ca.lk.Lock() defer ca.lk.Unlock() @@ -162,14 +162,14 @@ func (ca *channelAccessor) nextNonceForLane(ci *ChannelInfo, lane uint64) uint64 return maxnonce + 1 } -func (ca *channelAccessor) checkVoucherValid(ctx context.Context, ch address.Address, sv *v0paych.SignedVoucher) (map[uint64]paych.LaneState, error) { +func (ca *channelAccessor) checkVoucherValid(ctx context.Context, ch address.Address, sv *paych0.SignedVoucher) (map[uint64]paych.LaneState, error) { ca.lk.Lock() defer ca.lk.Unlock() return ca.checkVoucherValidUnlocked(ctx, ch, sv) } -func (ca *channelAccessor) checkVoucherValidUnlocked(ctx context.Context, ch address.Address, sv *v0paych.SignedVoucher) (map[uint64]paych.LaneState, error) { +func (ca *channelAccessor) checkVoucherValidUnlocked(ctx context.Context, ch address.Address, sv *paych0.SignedVoucher) (map[uint64]paych.LaneState, error) { if sv.ChannelAddr != ch { return nil, xerrors.Errorf("voucher ChannelAddr doesn't match channel address, got %s, expected %s", sv.ChannelAddr, ch) } @@ -251,7 +251,7 @@ func (ca *channelAccessor) checkVoucherValidUnlocked(ctx context.Context, ch add return laneStates, nil } -func (ca *channelAccessor) checkVoucherSpendable(ctx context.Context, ch address.Address, sv *v0paych.SignedVoucher, secret []byte, proof []byte) (bool, error) { +func (ca *channelAccessor) checkVoucherSpendable(ctx context.Context, ch address.Address, sv *paych0.SignedVoucher, secret []byte, proof []byte) (bool, error) { ca.lk.Lock() defer ca.lk.Unlock() @@ -290,7 +290,7 @@ func (ca *channelAccessor) checkVoucherSpendable(ctx context.Context, ch address } } - enc, err := actors.SerializeParams(&v0paych.UpdateChannelStateParams{ + enc, err := actors.SerializeParams(&paych0.UpdateChannelStateParams{ Sv: *sv, Secret: secret, Proof: proof, @@ -325,14 +325,14 @@ func (ca *channelAccessor) getPaychRecipient(ctx context.Context, ch address.Add return state.To(), nil } -func (ca *channelAccessor) addVoucher(ctx context.Context, ch address.Address, sv *v0paych.SignedVoucher, proof []byte, minDelta types.BigInt) (types.BigInt, error) { +func (ca *channelAccessor) addVoucher(ctx context.Context, ch address.Address, sv *paych0.SignedVoucher, proof []byte, minDelta types.BigInt) (types.BigInt, error) { ca.lk.Lock() defer ca.lk.Unlock() return ca.addVoucherUnlocked(ctx, ch, sv, proof, minDelta) } -func (ca *channelAccessor) addVoucherUnlocked(ctx context.Context, ch address.Address, sv *v0paych.SignedVoucher, proof []byte, minDelta types.BigInt) (types.BigInt, error) { +func (ca *channelAccessor) addVoucherUnlocked(ctx context.Context, ch address.Address, sv *paych0.SignedVoucher, proof []byte, minDelta types.BigInt) (types.BigInt, error) { ci, err := ca.store.ByAddress(ch) if err != nil { return types.BigInt{}, err @@ -396,7 +396,7 @@ func (ca *channelAccessor) addVoucherUnlocked(ctx context.Context, ch address.Ad return delta, ca.store.putChannelInfo(ci) } -func (ca *channelAccessor) submitVoucher(ctx context.Context, ch address.Address, sv *v0paych.SignedVoucher, secret []byte, proof []byte) (cid.Cid, error) { +func (ca *channelAccessor) submitVoucher(ctx context.Context, ch address.Address, sv *paych0.SignedVoucher, secret []byte, proof []byte) (cid.Cid, error) { ca.lk.Lock() defer ca.lk.Unlock() @@ -437,7 +437,7 @@ func (ca *channelAccessor) submitVoucher(ctx context.Context, ch address.Address } } - enc, err := actors.SerializeParams(&v0paych.UpdateChannelStateParams{ + enc, err := actors.SerializeParams(&paych0.UpdateChannelStateParams{ Sv: *sv, Secret: secret, Proof: proof, @@ -543,7 +543,7 @@ func (ca *channelAccessor) laneState(ctx context.Context, state paych.State, ch } // Get the total redeemed amount across all lanes, after applying the voucher -func (ca *channelAccessor) totalRedeemedWithVoucher(laneStates map[uint64]paych.LaneState, sv *v0paych.SignedVoucher) (big.Int, error) { +func (ca *channelAccessor) totalRedeemedWithVoucher(laneStates map[uint64]paych.LaneState, sv *paych0.SignedVoucher) (big.Int, error) { // TODO: merges if len(sv.Merges) != 0 { return big.Int{}, xerrors.Errorf("dont currently support paych lane merges") diff --git a/paychmgr/paych_test.go b/paychmgr/paych_test.go index 434c83e9c..b27b1e540 100644 --- a/paychmgr/paych_test.go +++ b/paychmgr/paych_test.go @@ -15,7 +15,7 @@ import ( "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/specs-actors/actors/builtin" - v0paych "github.com/filecoin-project/specs-actors/actors/builtin/paych" + paych0 "github.com/filecoin-project/specs-actors/actors/builtin/paych" tutils "github.com/filecoin-project/specs-actors/support/testing" "github.com/filecoin-project/lotus/api" @@ -339,7 +339,7 @@ func TestCreateVoucher(t *testing.T) { // Create a voucher in lane 1 voucherLane1Amt := big.NewInt(5) - voucher := v0paych.SignedVoucher{ + voucher := paych0.SignedVoucher{ Lane: 1, Amount: voucherLane1Amt, } @@ -354,7 +354,7 @@ func TestCreateVoucher(t *testing.T) { // Create a voucher in lane 1 again, with a higher amount voucherLane1Amt = big.NewInt(8) - voucher = v0paych.SignedVoucher{ + voucher = paych0.SignedVoucher{ Lane: 1, Amount: voucherLane1Amt, } @@ -369,7 +369,7 @@ func TestCreateVoucher(t *testing.T) { // Create a voucher in lane 2 that covers all the remaining funds // in the channel voucherLane2Amt := big.Sub(s.amt, voucherLane1Amt) - voucher = v0paych.SignedVoucher{ + voucher = paych0.SignedVoucher{ Lane: 2, Amount: voucherLane2Amt, } @@ -383,7 +383,7 @@ func TestCreateVoucher(t *testing.T) { // Create a voucher in lane 2 that exceeds the remaining funds in the // channel voucherLane2Amt = big.Add(voucherLane2Amt, big.NewInt(1)) - voucher = v0paych.SignedVoucher{ + voucher = paych0.SignedVoucher{ Lane: 2, Amount: voucherLane2Amt, } @@ -772,7 +772,7 @@ func TestCheckSpendable(t *testing.T) { // Check that the secret and proof were passed through correctly lastCall := s.mock.getLastCall() - var p v0paych.UpdateChannelStateParams + var p paych0.UpdateChannelStateParams err = p.UnmarshalCBOR(bytes.NewReader(lastCall.Params)) require.NoError(t, err) require.Equal(t, otherProof, p.Proof) @@ -786,7 +786,7 @@ func TestCheckSpendable(t *testing.T) { require.True(t, spendable) lastCall = s.mock.getLastCall() - var p2 v0paych.UpdateChannelStateParams + var p2 paych0.UpdateChannelStateParams err = p2.UnmarshalCBOR(bytes.NewReader(lastCall.Params)) require.NoError(t, err) require.Equal(t, proof, p2.Proof) @@ -843,7 +843,7 @@ func TestSubmitVoucher(t *testing.T) { // Check that the secret and proof were passed through correctly msg := s.mock.pushedMessages(submitCid) - var p v0paych.UpdateChannelStateParams + var p paych0.UpdateChannelStateParams err = p.UnmarshalCBOR(bytes.NewReader(msg.Message.Params)) require.NoError(t, err) require.Equal(t, submitProof, p.Proof) @@ -863,7 +863,7 @@ func TestSubmitVoucher(t *testing.T) { require.NoError(t, err) msg = s.mock.pushedMessages(submitCid) - var p2 v0paych.UpdateChannelStateParams + var p2 paych0.UpdateChannelStateParams err = p2.UnmarshalCBOR(bytes.NewReader(msg.Message.Params)) require.NoError(t, err) require.Equal(t, addVoucherProof2, p2.Proof) @@ -879,7 +879,7 @@ func TestSubmitVoucher(t *testing.T) { require.NoError(t, err) msg = s.mock.pushedMessages(submitCid) - var p3 v0paych.UpdateChannelStateParams + var p3 paych0.UpdateChannelStateParams err = p3.UnmarshalCBOR(bytes.NewReader(msg.Message.Params)) require.NoError(t, err) require.Equal(t, proof3, p3.Proof) @@ -966,8 +966,8 @@ func testGenerateKeyPair(t *testing.T) ([]byte, []byte) { return priv, pub } -func createTestVoucher(t *testing.T, ch address.Address, voucherLane uint64, nonce uint64, voucherAmount big.Int, key []byte) *v0paych.SignedVoucher { - sv := &v0paych.SignedVoucher{ +func createTestVoucher(t *testing.T, ch address.Address, voucherLane uint64, nonce uint64, voucherAmount big.Int, key []byte) *paych0.SignedVoucher { + sv := &paych0.SignedVoucher{ ChannelAddr: ch, Lane: voucherLane, Nonce: nonce, @@ -982,13 +982,13 @@ func createTestVoucher(t *testing.T, ch address.Address, voucherLane uint64, non return sv } -func createTestVoucherWithExtra(t *testing.T, ch address.Address, voucherLane uint64, nonce uint64, voucherAmount big.Int, key []byte) *v0paych.SignedVoucher { - sv := &v0paych.SignedVoucher{ +func createTestVoucherWithExtra(t *testing.T, ch address.Address, voucherLane uint64, nonce uint64, voucherAmount big.Int, key []byte) *paych0.SignedVoucher { + sv := &paych0.SignedVoucher{ ChannelAddr: ch, Lane: voucherLane, Nonce: nonce, Amount: voucherAmount, - Extra: &v0paych.ModVerifyParams{ + Extra: &paych0.ModVerifyParams{ Actor: tutils.NewActorAddr(t, "act"), }, } @@ -1006,13 +1006,13 @@ type mockBestSpendableAPI struct { mgr *Manager } -func (m *mockBestSpendableAPI) PaychVoucherList(ctx context.Context, ch address.Address) ([]*v0paych.SignedVoucher, error) { +func (m *mockBestSpendableAPI) PaychVoucherList(ctx context.Context, ch address.Address) ([]*paych0.SignedVoucher, error) { vi, err := m.mgr.ListVouchers(ctx, ch) if err != nil { return nil, err } - out := make([]*v0paych.SignedVoucher, len(vi)) + out := make([]*paych0.SignedVoucher, len(vi)) for k, v := range vi { out[k] = v.Voucher } @@ -1020,7 +1020,7 @@ func (m *mockBestSpendableAPI) PaychVoucherList(ctx context.Context, ch address. return out, nil } -func (m *mockBestSpendableAPI) PaychVoucherCheckSpendable(ctx context.Context, ch address.Address, voucher *v0paych.SignedVoucher, secret []byte, proof []byte) (bool, error) { +func (m *mockBestSpendableAPI) PaychVoucherCheckSpendable(ctx context.Context, ch address.Address, voucher *paych0.SignedVoucher, secret []byte, proof []byte) (bool, error) { return m.mgr.CheckVoucherSpendable(ctx, ch, voucher, secret, proof) } diff --git a/paychmgr/simple.go b/paychmgr/simple.go index 2f6dc0593..46bbea62e 100644 --- a/paychmgr/simple.go +++ b/paychmgr/simple.go @@ -14,7 +14,7 @@ import ( "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/specs-actors/actors/builtin" init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" - v0paych "github.com/filecoin-project/specs-actors/actors/builtin/paych" + paych0 "github.com/filecoin-project/specs-actors/actors/builtin/paych" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" @@ -382,7 +382,7 @@ func (ca *channelAccessor) processTask(ctx context.Context, amt types.BigInt) *p // createPaych sends a message to create the channel and returns the message cid func (ca *channelAccessor) createPaych(ctx context.Context, amt types.BigInt) (cid.Cid, error) { - params, aerr := actors.SerializeParams(&v0paych.ConstructorParams{From: ca.from, To: ca.to}) + params, aerr := actors.SerializeParams(&paych0.ConstructorParams{From: ca.from, To: ca.to}) if aerr != nil { return cid.Undef, aerr } diff --git a/storage/adapter_storage_miner.go b/storage/adapter_storage_miner.go index efbd95817..db3ae63d9 100644 --- a/storage/adapter_storage_miner.go +++ b/storage/adapter_storage_miner.go @@ -15,7 +15,7 @@ import ( "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/specs-actors/actors/builtin" - v0market "github.com/filecoin-project/specs-actors/actors/builtin/market" + market0 "github.com/filecoin-project/specs-actors/actors/builtin/market" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/api/apibstore" @@ -137,7 +137,7 @@ func (s SealingAPIAdapter) StateComputeDataCommitment(ctx context.Context, maddr return cid.Undef, xerrors.Errorf("failed to unmarshal TipSetToken to TipSetKey: %w", err) } - ccparams, err := actors.SerializeParams(&v0market.ComputeDataCommitmentParams{ + ccparams, err := actors.SerializeParams(&market0.ComputeDataCommitmentParams{ DealIDs: deals, SectorType: sectorType, }) diff --git a/storage/miner.go b/storage/miner.go index d7780898d..6a5d4183b 100644 --- a/storage/miner.go +++ b/storage/miner.go @@ -5,7 +5,7 @@ import ( "errors" "time" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/go-state-types/network" @@ -146,7 +146,7 @@ func (m *Miner) Run(ctx context.Context) error { evts := events.NewEvents(ctx, m.api) adaptedAPI := NewSealingAPIAdapter(m.api) // TODO: Maybe we update this policy after actor upgrades? - pcp := sealing.NewBasicPreCommitPolicy(adaptedAPI, v0miner.MaxSectorExpirationExtension-(v0miner.WPoStProvingPeriod*2), md.PeriodStart%v0miner.WPoStProvingPeriod) + pcp := sealing.NewBasicPreCommitPolicy(adaptedAPI, miner0.MaxSectorExpirationExtension-(miner0.WPoStProvingPeriod*2), md.PeriodStart%miner0.WPoStProvingPeriod) m.sealing = sealing.New(adaptedAPI, fc, NewEventsAdapter(evts), m.maddr, m.ds, m.sealer, m.sc, m.verif, &pcp, sealing.GetSealingConfigFunc(m.getSealConfig), m.handleSealingNotifications) go m.sealing.Run(ctx) //nolint:errcheck // logged intside the function diff --git a/storage/wdpost_run_test.go b/storage/wdpost_run_test.go index 1a930b41a..58014d632 100644 --- a/storage/wdpost_run_test.go +++ b/storage/wdpost_run_test.go @@ -19,8 +19,8 @@ import ( "github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/go-state-types/network" "github.com/filecoin-project/specs-actors/actors/builtin" - v0builtin "github.com/filecoin-project/specs-actors/actors/builtin" - v0miner "github.com/filecoin-project/specs-actors/actors/builtin/miner" + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/specs-actors/actors/runtime/proof" tutils "github.com/filecoin-project/specs-actors/support/testing" @@ -134,7 +134,7 @@ func TestWDPostDoPost(t *testing.T) { // without exceeding the message sector limit require.NoError(t, err) - partitionsPerMsg := int(v0miner.AddressedSectorsMax / sectorsPerPartition) + partitionsPerMsg := int(miner0.AddressedSectorsMax / sectorsPerPartition) // Enough partitions to fill expectedMsgCount-1 messages partitionCount := (expectedMsgCount - 1) * partitionsPerMsg @@ -249,7 +249,7 @@ func (m *mockStorageMinerAPI) StateSearchMsg(ctx context.Context, cid cid.Cid) ( func (m *mockStorageMinerAPI) StateGetActor(ctx context.Context, actor address.Address, ts types.TipSetKey) (*types.Actor, error) { return &types.Actor{ - Code: v0builtin.StorageMinerActorCodeID, + Code: builtin0.StorageMinerActorCodeID, }, nil } From 35bce5a5c691c015abc6b5fc51e85e63bb4915e4 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Fri, 18 Sep 2020 15:40:49 -0700 Subject: [PATCH 108/303] revert post changes 1. Calling the specific partition/deadline APIs is faster. 2. It's _much_ easier to test this way. --- chain/actors/builtin/miner/miner.go | 2 - chain/actors/builtin/miner/v0.go | 5 -- storage/miner.go | 1 + storage/wdpost_run.go | 101 ++++++---------------------- 4 files changed, 22 insertions(+), 87 deletions(-) diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index b9cff99da..d25652d30 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -58,8 +58,6 @@ type State interface { DeadlineInfo(epoch abi.ChainEpoch) *dline.Info - MaxAddressedSectors() (uint64, error) - // Diff helpers. Used by Diff* functions internally. sectors() (adt.Array, error) decodeSectorOnChainInfo(*cbg.Deferred) (SectorOnChainInfo, error) diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index 26a91edd1..37df8c217 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -224,11 +224,6 @@ func (s *state0) NumDeadlines() (uint64, error) { return miner0.WPoStPeriodDeadlines, nil } -// Max sectors per PoSt -func (s *state0) MaxAddressedSectors() (uint64, error) { - return miner0.AddressedSectorsMax, nil -} - func (s *state0) DeadlinesChanged(other State) bool { other0, ok := other.(*state0) if !ok { diff --git a/storage/miner.go b/storage/miner.go index 6a5d4183b..61c4000f2 100644 --- a/storage/miner.go +++ b/storage/miner.go @@ -77,6 +77,7 @@ type storageMinerApi interface { StateSectorPartition(ctx context.Context, maddr address.Address, sectorNumber abi.SectorNumber, tok types.TipSetKey) (*miner.SectorLocation, error) StateMinerInfo(context.Context, address.Address, types.TipSetKey) (miner.MinerInfo, error) StateMinerDeadlines(context.Context, address.Address, types.TipSetKey) ([]api.Deadline, error) + StateMinerPartitions(context.Context, address.Address, uint64, types.TipSetKey) ([]api.Partition, error) StateMinerProvingDeadline(context.Context, address.Address, types.TipSetKey) (*dline.Info, error) StateMinerPreCommitDepositForPower(context.Context, address.Address, miner.SectorPreCommitInfo, types.TipSetKey) (types.BigInt, error) StateMinerInitialPledgeCollateral(context.Context, address.Address, miner.SectorPreCommitInfo, types.TipSetKey) (types.BigInt, error) diff --git a/storage/wdpost_run.go b/storage/wdpost_run.go index 2f5d97b76..06740b108 100644 --- a/storage/wdpost_run.go +++ b/storage/wdpost_run.go @@ -5,6 +5,8 @@ import ( "context" "time" + "github.com/filecoin-project/specs-actors/actors/runtime/proof" + "github.com/filecoin-project/go-bitfield" "github.com/filecoin-project/go-address" @@ -18,16 +20,14 @@ import ( "go.opencensus.io/trace" "golang.org/x/xerrors" - "github.com/filecoin-project/specs-actors/actors/runtime/proof" - "github.com/filecoin-project/lotus/api" - "github.com/filecoin-project/lotus/api/apibstore" "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/actors" "github.com/filecoin-project/lotus/chain/actors/builtin/miner" - "github.com/filecoin-project/lotus/chain/store" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/journal" + + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" ) func (s *WindowPoStScheduler) failPost(err error, deadline *dline.Info) { @@ -154,7 +154,7 @@ func (s *WindowPoStScheduler) checkSectors(ctx context.Context, check bitfield.B return sbf, nil } -func (s *WindowPoStScheduler) checkNextRecoveries(ctx context.Context, dlIdx uint64, partitions []miner.Partition) ([]miner.RecoveryDeclaration, *types.SignedMessage, error) { +func (s *WindowPoStScheduler) checkNextRecoveries(ctx context.Context, dlIdx uint64, partitions []api.Partition) ([]miner.RecoveryDeclaration, *types.SignedMessage, error) { ctx, span := trace.StartSpan(ctx, "storage.checkNextRecoveries") defer span.End() @@ -164,15 +164,7 @@ func (s *WindowPoStScheduler) checkNextRecoveries(ctx context.Context, dlIdx uin } for partIdx, partition := range partitions { - faults, err := partition.FaultySectors() - if err != nil { - return nil, nil, xerrors.Errorf("getting faults: %w", err) - } - recovering, err := partition.RecoveringSectors() - if err != nil { - return nil, nil, xerrors.Errorf("getting recovering: %w", err) - } - unrecovered, err := bitfield.SubtractBitField(faults, recovering) + unrecovered, err := bitfield.SubtractBitField(partition.FaultySectors, partition.RecoveringSectors) if err != nil { return nil, nil, xerrors.Errorf("subtracting recovered set from fault set: %w", err) } @@ -253,7 +245,7 @@ func (s *WindowPoStScheduler) checkNextRecoveries(ctx context.Context, dlIdx uin return recoveries, sm, nil } -func (s *WindowPoStScheduler) checkNextFaults(ctx context.Context, dlIdx uint64, partitions []miner.Partition) ([]miner.FaultDeclaration, *types.SignedMessage, error) { +func (s *WindowPoStScheduler) checkNextFaults(ctx context.Context, dlIdx uint64, partitions []api.Partition) ([]miner.FaultDeclaration, *types.SignedMessage, error) { ctx, span := trace.StartSpan(ctx, "storage.checkNextFaults") defer span.End() @@ -263,17 +255,12 @@ func (s *WindowPoStScheduler) checkNextFaults(ctx context.Context, dlIdx uint64, } for partIdx, partition := range partitions { - toCheck, err := partition.ActiveSectors() - if err != nil { - return nil, nil, xerrors.Errorf("getting active sectors: %w", err) - } - - good, err := s.checkSectors(ctx, toCheck) + good, err := s.checkSectors(ctx, partition.ActiveSectors) if err != nil { return nil, nil, xerrors.Errorf("checking sectors: %w", err) } - faulty, err := bitfield.SubtractBitField(toCheck, good) + faulty, err := bitfield.SubtractBitField(partition.ActiveSectors, good) if err != nil { return nil, nil, xerrors.Errorf("calculating faulty sector set: %w", err) } @@ -341,17 +328,6 @@ func (s *WindowPoStScheduler) runPost(ctx context.Context, di dline.Info, ts *ty ctx, span := trace.StartSpan(ctx, "storage.runPost") defer span.End() - stor := store.ActorStore(ctx, apibstore.NewAPIBlockstore(s.api)) - act, err := s.api.StateGetActor(context.TODO(), s.actor, ts.Key()) - if err != nil { - return nil, xerrors.Errorf("resolving actor: %w", err) - } - - mas, err := miner.Load(stor, act) - if err != nil { - return nil, xerrors.Errorf("getting miner state: %w", err) - } - go func() { // TODO: extract from runPost, run on fault cutoff boundaries @@ -359,18 +335,9 @@ func (s *WindowPoStScheduler) runPost(ctx context.Context, di dline.Info, ts *ty // late to declare them for this deadline declDeadline := (di.Index + 2) % di.WPoStPeriodDeadlines - dl, err := mas.LoadDeadline(declDeadline) + partitions, err := s.api.StateMinerPartitions(context.TODO(), s.actor, declDeadline, ts.Key()) if err != nil { - log.Errorf("loading deadline: %v", err) - return - } - var partitions []miner.Partition - err = dl.ForEachPartition(func(_ uint64, part miner.Partition) error { - partitions = append(partitions, part) - return nil - }) - if err != nil { - log.Errorf("loading partitions: %v", err) + log.Errorf("getting partitions: %v", err) return } @@ -429,24 +396,15 @@ func (s *WindowPoStScheduler) runPost(ctx context.Context, di dline.Info, ts *ty return nil, xerrors.Errorf("failed to get chain randomness for window post (ts=%d; deadline=%d): %w", ts.Height(), di, err) } - dl, err := mas.LoadDeadline(di.Index) - if err != nil { - return nil, xerrors.Errorf("loading deadline: %w", err) - } - // Get the partitions for the given deadline - var partitions []miner.Partition - err = dl.ForEachPartition(func(_ uint64, part miner.Partition) error { - partitions = append(partitions, part) - return nil - }) + partitions, err := s.api.StateMinerPartitions(ctx, s.actor, di.Index, ts.Key()) if err != nil { - return nil, xerrors.Errorf("loading partitions: %w", err) + return nil, xerrors.Errorf("getting partitions: %w", err) } // Split partitions into batches, so as not to exceed the number of sectors // allowed in a single message - partitionBatches, err := s.batchPartitions(partitions, mas) + partitionBatches, err := s.batchPartitions(partitions) if err != nil { return nil, err } @@ -475,16 +433,7 @@ func (s *WindowPoStScheduler) runPost(ctx context.Context, di dline.Info, ts *ty var sinfos []proof.SectorInfo for partIdx, partition := range batch { // TODO: Can do this in parallel - toProve, err := partition.ActiveSectors() - if err != nil { - return nil, xerrors.Errorf("getting active sectors: %w", err) - } - - recs, err := partition.RecoveringSectors() - if err != nil { - return nil, xerrors.Errorf("getting recovering sectors: %w", err) - } - toProve, err = bitfield.MergeBitFields(toProve, recs) + toProve, err := bitfield.MergeBitFields(partition.ActiveSectors, partition.RecoveringSectors) if err != nil { return nil, xerrors.Errorf("adding recoveries to set of sectors to prove: %w", err) } @@ -511,12 +460,7 @@ func (s *WindowPoStScheduler) runPost(ctx context.Context, di dline.Info, ts *ty skipCount += sc - partitionSectors, err := partition.AllSectors() - if err != nil { - return nil, xerrors.Errorf("getting partition sectors: %w", err) - } - - ssi, err := s.sectorsForProof(ctx, good, partitionSectors, ts) + ssi, err := s.sectorsForProof(ctx, good, partition.AllSectors, ts) if err != nil { return nil, xerrors.Errorf("getting sorted sector info: %w", err) } @@ -609,18 +553,13 @@ func (s *WindowPoStScheduler) runPost(ctx context.Context, di dline.Info, ts *ty return posts, nil } -func (s *WindowPoStScheduler) batchPartitions(partitions []miner.Partition, mas miner.State) ([][]miner.Partition, error) { +func (s *WindowPoStScheduler) batchPartitions(partitions []api.Partition) ([][]api.Partition, error) { // Get the number of sectors allowed in a partition, for this proof size sectorsPerPartition, err := builtin.PoStProofWindowPoStPartitionSectors(s.proofType) if err != nil { return nil, xerrors.Errorf("getting sectors per partition: %w", err) } - maxSectors, err := mas.MaxAddressedSectors() - if err != nil { - return nil, err - } - // We don't want to exceed the number of sectors allowed in a message. // So given the number of sectors in a partition, work out the number of // partitions that can be in a message without exceeding sectors per @@ -631,7 +570,9 @@ func (s *WindowPoStScheduler) batchPartitions(partitions []miner.Partition, mas // sectors per partition 3: ooo // partitions per message 2: oooOOO // <1><2> (3rd doesn't fit) - partitionsPerMsg := int(maxSectors / sectorsPerPartition) + // TODO(NETUPGRADE): we're going to need some form of policy abstraction + // where we can get policy from the future. Unfortunately, we can't just get this from the state. + partitionsPerMsg := int(miner0.AddressedSectorsMax / sectorsPerPartition) // The number of messages will be: // ceiling(number of partitions / partitions per message) @@ -641,7 +582,7 @@ func (s *WindowPoStScheduler) batchPartitions(partitions []miner.Partition, mas } // Split the partitions into batches - batches := make([][]miner.Partition, 0, batchCount) + batches := make([][]api.Partition, 0, batchCount) for i := 0; i < len(partitions); i += partitionsPerMsg { end := i + partitionsPerMsg if end > len(partitions) { From 26de0db75756b85f5135017fa43282b21b3255eb Mon Sep 17 00:00:00 2001 From: Travis Person Date: Wed, 9 Sep 2020 18:45:09 +0000 Subject: [PATCH 109/303] lotus-pcr: add recover-miners command --- cmd/lotus-pcr/main.go | 167 ++++++++++++++++++++++++++++++++++++++--- tools/stats/metrics.go | 22 ++++-- 2 files changed, 172 insertions(+), 17 deletions(-) diff --git a/cmd/lotus-pcr/main.go b/cmd/lotus-pcr/main.go index dc12693ca..473fc7ff1 100644 --- a/cmd/lotus-pcr/main.go +++ b/cmd/lotus-pcr/main.go @@ -38,6 +38,7 @@ var log = logging.Logger("main") func main() { local := []*cli.Command{ runCmd, + recoverMinersCmd, versionCmd, } @@ -101,6 +102,80 @@ var versionCmd = &cli.Command{ }, } +var recoverMinersCmd = &cli.Command{ + Name: "recover-miners", + Usage: "Ensure all miners with a negative available balance have a FIL surplus across accounts", + Flags: []cli.Flag{ + &cli.StringFlag{ + Name: "from", + EnvVars: []string{"LOTUS_PCR_FROM"}, + Usage: "wallet address to send refund from", + }, + &cli.BoolFlag{ + Name: "no-sync", + EnvVars: []string{"LOTUS_PCR_NO_SYNC"}, + Usage: "do not wait for chain sync to complete", + }, + &cli.BoolFlag{ + Name: "dry-run", + EnvVars: []string{"LOTUS_PCR_DRY_RUN"}, + Usage: "do not send any messages", + Value: false, + }, + &cli.IntFlag{ + Name: "miner-total-funds-threashold", + EnvVars: []string{"LOTUS_PCR_MINER_TOTAL_FUNDS_THREASHOLD"}, + Usage: "total filecoin across all accounts that should be met, if the miner balancer drops below zero", + Value: 0, + }, + }, + Action: func(cctx *cli.Context) error { + ctx := context.Background() + api, closer, err := stats.GetFullNodeAPI(cctx.Context, cctx.String("lotus-path")) + if err != nil { + log.Fatal(err) + } + defer closer() + + from, err := address.NewFromString(cctx.String("from")) + if err != nil { + return xerrors.Errorf("parsing source address (provide correct --from flag!): %w", err) + } + + if !cctx.Bool("no-sync") { + if err := stats.WaitForSyncComplete(ctx, api); err != nil { + log.Fatal(err) + } + } + + dryRun := cctx.Bool("dry-run") + minerTotalFundsThreashold := uint64(cctx.Int("miner-total-funds-threashold")) + + rf := &refunder{ + api: api, + wallet: from, + dryRun: dryRun, + minerTotalFundsThreashold: types.FromFil(minerTotalFundsThreashold), + } + + refundTipset, err := api.ChainHead(ctx) + if err != nil { + return err + } + + negativeBalancerRefund, err := rf.EnsureMinerMinimums(ctx, refundTipset, NewMinersRefund()) + if err != nil { + return err + } + + if err := rf.Refund(ctx, "refund negative balancer miner", refundTipset, negativeBalancerRefund, 0); err != nil { + return err + } + + return nil + }, +} + var runCmd = &cli.Command{ Name: "run", Usage: "Start message reimpursement", @@ -230,7 +305,7 @@ var runCmd = &cli.Command{ return err } - if err := rf.Refund(ctx, refundTipset, refunds, rounds); err != nil { + if err := rf.Refund(ctx, "refund stats", refundTipset, refunds, rounds); err != nil { return err } @@ -289,7 +364,6 @@ func (m *MinersRefund) Track(addr address.Address, value types.BigInt) { m.count = m.count + 1 m.totalRefunds = types.BigAdd(m.totalRefunds, value) - m.refunds[addr] = types.BigAdd(m.refunds[addr], value) } @@ -318,8 +392,12 @@ type refunderNodeApi interface { ChainGetParentMessages(ctx context.Context, blockCid cid.Cid) ([]api.Message, error) ChainGetParentReceipts(ctx context.Context, blockCid cid.Cid) ([]*types.MessageReceipt, error) ChainGetTipSetByHeight(ctx context.Context, epoch abi.ChainEpoch, tsk types.TipSetKey) (*types.TipSet, error) + ChainReadObj(context.Context, cid.Cid) ([]byte, error) StateMinerInitialPledgeCollateral(ctx context.Context, addr address.Address, precommitInfo miner.SectorPreCommitInfo, tsk types.TipSetKey) (types.BigInt, error) + StateMinerInfo(context.Context, address.Address, types.TipSetKey) (api.MinerInfo, error) StateSectorPreCommitInfo(ctx context.Context, addr address.Address, sector abi.SectorNumber, tsk types.TipSetKey) (miner.SectorPreCommitOnChainInfo, error) + StateMinerAvailableBalance(context.Context, address.Address, types.TipSetKey) (types.BigInt, error) + StateListMiners(context.Context, types.TipSetKey) ([]address.Address, error) StateGetActor(ctx context.Context, actor address.Address, tsk types.TipSetKey) (*types.Actor, error) MpoolPushMessage(ctx context.Context, msg *types.Message, spec *api.MessageSendSpec) (*types.SignedMessage, error) GasEstimateGasPremium(ctx context.Context, nblocksincl uint64, sender address.Address, gaslimit int64, tsk types.TipSetKey) (types.BigInt, error) @@ -327,12 +405,81 @@ type refunderNodeApi interface { } type refunder struct { - api refunderNodeApi - wallet address.Address - percentExtra int - dryRun bool - preCommitEnabled bool - proveCommitEnabled bool + api refunderNodeApi + wallet address.Address + percentExtra int + dryRun bool + preCommitEnabled bool + proveCommitEnabled bool + minerTotalFundsThreashold big.Int +} + +func (r *refunder) EnsureMinerMinimums(ctx context.Context, tipset *types.TipSet, refunds *MinersRefund) (*MinersRefund, error) { + miners, err := r.api.StateListMiners(ctx, tipset.Key()) + if err != nil { + return nil, err + } + + for _, maddr := range miners { + mact, err := r.api.StateGetActor(ctx, maddr, types.EmptyTSK) + if err != nil { + log.Errorw("failed", "err", err, "height", tipset.Height(), "key", tipset.Key(), "miner", maddr) + continue + } + + if !mact.Balance.GreaterThan(big.Zero()) { + continue + } + + minerAvailableBalance, err := r.api.StateMinerAvailableBalance(ctx, maddr, tipset.Key()) + if err != nil { + log.Errorw("failed", "err", err, "height", tipset.Height(), "key", tipset.Key(), "miner", maddr) + continue + } + + if minerAvailableBalance.GreaterThanEqual(big.Zero()) { + log.Debugw("skipping over miner with positive balance", "height", tipset.Height(), "key", tipset.Key(), "miner", maddr) + continue + } + + // Look up and find all addresses associated with the miner + minerInfo, err := r.api.StateMinerInfo(ctx, maddr, tipset.Key()) + + allAddresses := []address.Address{minerInfo.Worker, minerInfo.Owner} + allAddresses = append(allAddresses, minerInfo.ControlAddresses...) + + // Sum the balancer of all the addresses + addrSum := big.Zero() + addrCheck := make(map[address.Address]struct{}, len(allAddresses)) + for _, addr := range allAddresses { + if _, found := addrCheck[addr]; !found { + balance, err := r.api.WalletBalance(ctx, addr) + if err != nil { + log.Errorw("failed", "err", err, "height", tipset.Height(), "key", tipset.Key(), "miner", maddr) + continue + } + + addrSum = big.Add(addrSum, balance) + addrCheck[addr] = struct{}{} + } + } + + totalAvailableBalance := big.Add(addrSum, minerAvailableBalance) + + // If the miner has available balance they should use it + if totalAvailableBalance.GreaterThanEqual(r.minerTotalFundsThreashold) { + log.Debugw("skipping over miner with enough funds cross all accounts", "height", tipset.Height(), "key", tipset.Key(), "miner", maddr, "miner_available_balance", minerAvailableBalance, "wallet_total_balances", addrSum) + continue + } + + // Calculate the required FIL to bring the miner up to the minimum across all of their accounts + refundValue := big.Add(totalAvailableBalance.Abs(), r.minerTotalFundsThreashold) + refunds.Track(maddr, refundValue) + + log.Debugw("processing negative balance miner", "miner", maddr, "refund", refundValue) + } + + return refunds, nil } func (r *refunder) ProcessTipset(ctx context.Context, tipset *types.TipSet, refunds *MinersRefund) (*MinersRefund, error) { @@ -464,7 +611,7 @@ func (r *refunder) ProcessTipset(ctx context.Context, tipset *types.TipSet, refu return refunds, nil } -func (r *refunder) Refund(ctx context.Context, tipset *types.TipSet, refunds *MinersRefund, rounds int) error { +func (r *refunder) Refund(ctx context.Context, name string, tipset *types.TipSet, refunds *MinersRefund, rounds int) error { if refunds.Count() == 0 { log.Debugw("no messages to refund in tipset", "height", tipset.Height(), "key", tipset.Key()) return nil @@ -522,7 +669,7 @@ func (r *refunder) Refund(ctx context.Context, tipset *types.TipSet, refunds *Mi refundSum = types.BigAdd(refundSum, msg.Value) } - log.Infow("refund stats", "tipsets_processed", rounds, "height", tipset.Height(), "key", tipset.Key(), "messages_sent", len(messages)-failures, "refund_sum", refundSum, "messages_failures", failures, "messages_processed", refunds.Count()) + log.Infow(name, "tipsets_processed", rounds, "height", tipset.Height(), "key", tipset.Key(), "messages_sent", len(messages)-failures, "refund_sum", refundSum, "messages_failures", failures, "messages_processed", refunds.Count()) return nil } diff --git a/tools/stats/metrics.go b/tools/stats/metrics.go index e50ac953f..eeef72e8e 100644 --- a/tools/stats/metrics.go +++ b/tools/stats/metrics.go @@ -201,16 +201,24 @@ func RecordTipsetPoints(ctx context.Context, api api.FullNode, pl *PointList, ti return nil } -type apiIpldStore struct { +type ApiIpldStore struct { ctx context.Context - api api.FullNode + api apiIpldStoreApi } -func (ht *apiIpldStore) Context() context.Context { +type apiIpldStoreApi interface { + ChainReadObj(context.Context, cid.Cid) ([]byte, error) +} + +func NewApiIpldStore(ctx context.Context, api apiIpldStoreApi) *ApiIpldStore { + return &ApiIpldStore{ctx, api} +} + +func (ht *ApiIpldStore) Context() context.Context { return ht.ctx } -func (ht *apiIpldStore) Get(ctx context.Context, c cid.Cid, out interface{}) error { +func (ht *ApiIpldStore) Get(ctx context.Context, c cid.Cid, out interface{}) error { raw, err := ht.api.ChainReadObj(ctx, c) if err != nil { return err @@ -227,8 +235,8 @@ func (ht *apiIpldStore) Get(ctx context.Context, c cid.Cid, out interface{}) err return fmt.Errorf("Object does not implement CBORUnmarshaler") } -func (ht *apiIpldStore) Put(ctx context.Context, v interface{}) (cid.Cid, error) { - return cid.Undef, fmt.Errorf("Put is not implemented on apiIpldStore") +func (ht *ApiIpldStore) Put(ctx context.Context, v interface{}) (cid.Cid, error) { + return cid.Undef, fmt.Errorf("Put is not implemented on ApiIpldStore") } func RecordTipsetStatePoints(ctx context.Context, api api.FullNode, pl *PointList, tipset *types.TipSet) error { @@ -279,7 +287,7 @@ func RecordTipsetStatePoints(ctx context.Context, api api.FullNode, pl *PointLis return fmt.Errorf("failed to unmarshal power actor state: %w", err) } - s := &apiIpldStore{ctx, api} + s := NewApiIpldStore(ctx, api) mp, err := adt.AsMap(s, powerActorState.Claims) if err != nil { return err From e39036dd499ccc80697a2c38444953d77a1d7777 Mon Sep 17 00:00:00 2001 From: Travis Person Date: Thu, 10 Sep 2020 07:36:24 +0000 Subject: [PATCH 110/303] lotus-pcr: find miners command --- cmd/lotus-pcr/main.go | 258 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 228 insertions(+), 30 deletions(-) diff --git a/cmd/lotus-pcr/main.go b/cmd/lotus-pcr/main.go index 473fc7ff1..66279c29a 100644 --- a/cmd/lotus-pcr/main.go +++ b/cmd/lotus-pcr/main.go @@ -1,10 +1,13 @@ package main import ( + "bufio" "bytes" "context" + "encoding/csv" "fmt" "io/ioutil" + "math" "net/http" _ "net/http/pprof" "os" @@ -20,13 +23,14 @@ import ( "golang.org/x/xerrors" + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-bitfield" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/exitcode" "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/filecoin-project/go-address" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/types" @@ -39,6 +43,7 @@ func main() { local := []*cli.Command{ runCmd, recoverMinersCmd, + findMinersCmd, versionCmd, } @@ -102,6 +107,92 @@ var versionCmd = &cli.Command{ }, } +var findMinersCmd = &cli.Command{ + Name: "find-miners", + Usage: "find miners with a desired minimum balance", + Description: `Find miners returns a list of miners and their balances that are below a + threhold value. By default only the miner actor available balance is considered but other + account balances can be included by enabling them through the flags. + + Examples + Find all miners with an available balance below 100 FIL + + lotus-pcr find-miners --threshold 100 + + Find all miners with a balance below zero, which includes the owner and worker balances + + lotus-pcr find-miners --threshold 0 --owner --worker +`, + Flags: []cli.Flag{ + &cli.BoolFlag{ + Name: "no-sync", + EnvVars: []string{"LOTUS_PCR_NO_SYNC"}, + Usage: "do not wait for chain sync to complete", + }, + &cli.IntFlag{ + Name: "threshold", + EnvVars: []string{"LOTUS_PCR_THRESHOLD"}, + Usage: "balance below this limit will be printed", + Value: 0, + }, + &cli.BoolFlag{ + Name: "owner", + Usage: "include owner balance", + Value: false, + }, + &cli.BoolFlag{ + Name: "worker", + Usage: "include worker balance", + Value: false, + }, + &cli.BoolFlag{ + Name: "control", + Usage: "include control balance", + Value: false, + }, + }, + Action: func(cctx *cli.Context) error { + ctx := context.Background() + api, closer, err := stats.GetFullNodeAPI(cctx.Context, cctx.String("lotus-path")) + if err != nil { + log.Fatal(err) + } + defer closer() + + if !cctx.Bool("no-sync") { + if err := stats.WaitForSyncComplete(ctx, api); err != nil { + log.Fatal(err) + } + } + + owner := cctx.Bool("owner") + worker := cctx.Bool("worker") + control := cctx.Bool("control") + threshold := uint64(cctx.Int("threshold")) + + rf := &refunder{ + api: api, + threshold: types.FromFil(threshold), + } + + refundTipset, err := api.ChainHead(ctx) + if err != nil { + return err + } + + balanceRefund, err := rf.FindMiners(ctx, refundTipset, NewMinersRefund(), owner, worker, control) + if err != nil { + return err + } + + for _, maddr := range balanceRefund.Miners() { + fmt.Printf("%s\t%s\n", maddr, types.FIL(balanceRefund.GetRefund(maddr))) + } + + return nil + }, +} + var recoverMinersCmd = &cli.Command{ Name: "recover-miners", Usage: "Ensure all miners with a negative available balance have a FIL surplus across accounts", @@ -123,11 +214,15 @@ var recoverMinersCmd = &cli.Command{ Value: false, }, &cli.IntFlag{ - Name: "miner-total-funds-threashold", - EnvVars: []string{"LOTUS_PCR_MINER_TOTAL_FUNDS_THREASHOLD"}, - Usage: "total filecoin across all accounts that should be met, if the miner balancer drops below zero", + Name: "threshold", + EnvVars: []string{"LOTUS_PCR_THRESHOLD"}, + Usage: "total filecoin across all accounts that should be met, if the miner balance drops below zero", Value: 0, }, + &cli.StringFlag{ + Name: "output", + Usage: "dump data as a csv format to this file", + }, }, Action: func(cctx *cli.Context) error { ctx := context.Background() @@ -149,13 +244,13 @@ var recoverMinersCmd = &cli.Command{ } dryRun := cctx.Bool("dry-run") - minerTotalFundsThreashold := uint64(cctx.Int("miner-total-funds-threashold")) + threshold := uint64(cctx.Int("threshold")) rf := &refunder{ - api: api, - wallet: from, - dryRun: dryRun, - minerTotalFundsThreashold: types.FromFil(minerTotalFundsThreashold), + api: api, + wallet: from, + dryRun: dryRun, + threshold: types.FromFil(threshold), } refundTipset, err := api.ChainHead(ctx) @@ -163,12 +258,12 @@ var recoverMinersCmd = &cli.Command{ return err } - negativeBalancerRefund, err := rf.EnsureMinerMinimums(ctx, refundTipset, NewMinersRefund()) + balanceRefund, err := rf.EnsureMinerMinimums(ctx, refundTipset, NewMinersRefund(), cctx.String("output")) if err != nil { return err } - if err := rf.Refund(ctx, "refund negative balancer miner", refundTipset, negativeBalancerRefund, 0); err != nil { + if err := rf.Refund(ctx, "refund to recover miner", refundTipset, balanceRefund, 0); err != nil { return err } @@ -397,6 +492,8 @@ type refunderNodeApi interface { StateMinerInfo(context.Context, address.Address, types.TipSetKey) (api.MinerInfo, error) StateSectorPreCommitInfo(ctx context.Context, addr address.Address, sector abi.SectorNumber, tsk types.TipSetKey) (miner.SectorPreCommitOnChainInfo, error) StateMinerAvailableBalance(context.Context, address.Address, types.TipSetKey) (types.BigInt, error) + StateMinerSectors(ctx context.Context, addr address.Address, filter *bitfield.BitField, filterOut bool, tsk types.TipSetKey) ([]*api.ChainSectorInfo, error) + StateMinerFaults(ctx context.Context, addr address.Address, tsk types.TipSetKey) (bitfield.BitField, error) StateListMiners(context.Context, types.TipSetKey) ([]address.Address, error) StateGetActor(ctx context.Context, actor address.Address, tsk types.TipSetKey) (*types.Actor, error) MpoolPushMessage(ctx context.Context, msg *types.Message, spec *api.MessageSendSpec) (*types.SignedMessage, error) @@ -405,16 +502,16 @@ type refunderNodeApi interface { } type refunder struct { - api refunderNodeApi - wallet address.Address - percentExtra int - dryRun bool - preCommitEnabled bool - proveCommitEnabled bool - minerTotalFundsThreashold big.Int + api refunderNodeApi + wallet address.Address + percentExtra int + dryRun bool + preCommitEnabled bool + proveCommitEnabled bool + threshold big.Int } -func (r *refunder) EnsureMinerMinimums(ctx context.Context, tipset *types.TipSet, refunds *MinersRefund) (*MinersRefund, error) { +func (r *refunder) FindMiners(ctx context.Context, tipset *types.TipSet, refunds *MinersRefund, owner, worker, control bool) (*MinersRefund, error) { miners, err := r.api.StateListMiners(ctx, tipset.Key()) if err != nil { return nil, err @@ -437,8 +534,91 @@ func (r *refunder) EnsureMinerMinimums(ctx context.Context, tipset *types.TipSet continue } - if minerAvailableBalance.GreaterThanEqual(big.Zero()) { - log.Debugw("skipping over miner with positive balance", "height", tipset.Height(), "key", tipset.Key(), "miner", maddr) + // Look up and find all addresses associated with the miner + minerInfo, err := r.api.StateMinerInfo(ctx, maddr, tipset.Key()) + + allAddresses := []address.Address{} + + if worker { + allAddresses = append(allAddresses, minerInfo.Worker) + } + + if owner { + allAddresses = append(allAddresses, minerInfo.Owner) + } + + if control { + allAddresses = append(allAddresses, minerInfo.ControlAddresses...) + } + + // Sum the balancer of all the addresses + addrSum := big.Zero() + addrCheck := make(map[address.Address]struct{}, len(allAddresses)) + for _, addr := range allAddresses { + if _, found := addrCheck[addr]; !found { + balance, err := r.api.WalletBalance(ctx, addr) + if err != nil { + log.Errorw("failed", "err", err, "height", tipset.Height(), "key", tipset.Key(), "miner", maddr) + continue + } + + addrSum = big.Add(addrSum, balance) + addrCheck[addr] = struct{}{} + } + } + + totalAvailableBalance := big.Add(addrSum, minerAvailableBalance) + + if totalAvailableBalance.GreaterThanEqual(r.threshold) { + continue + } + + refunds.Track(maddr, totalAvailableBalance) + + log.Debugw("processing miner", "miner", maddr, "sectors", "available_balance", totalAvailableBalance) + } + + return refunds, nil +} + +func (r *refunder) EnsureMinerMinimums(ctx context.Context, tipset *types.TipSet, refunds *MinersRefund, output string) (*MinersRefund, error) { + miners, err := r.api.StateListMiners(ctx, tipset.Key()) + if err != nil { + return nil, err + } + + w := ioutil.Discard + if len(output) != 0 { + f, err := os.Create(output) + if err != nil { + return nil, err + } + + defer f.Close() + + w = bufio.NewWriter(f) + } + + csvOut := csv.NewWriter(w) + defer csvOut.Flush() + if err := csvOut.Write([]string{"MinerID", "Sectors", "CombinedBalance", "ProposedSend"}); err != nil { + return nil, err + } + + for _, maddr := range miners { + mact, err := r.api.StateGetActor(ctx, maddr, types.EmptyTSK) + if err != nil { + log.Errorw("failed", "err", err, "height", tipset.Height(), "key", tipset.Key(), "miner", maddr) + continue + } + + if !mact.Balance.GreaterThan(big.Zero()) { + continue + } + + minerAvailableBalance, err := r.api.StateMinerAvailableBalance(ctx, maddr, tipset.Key()) + if err != nil { + log.Errorw("failed", "err", err, "height", tipset.Height(), "key", tipset.Key(), "miner", maddr) continue } @@ -464,19 +644,37 @@ func (r *refunder) EnsureMinerMinimums(ctx context.Context, tipset *types.TipSet } } - totalAvailableBalance := big.Add(addrSum, minerAvailableBalance) - - // If the miner has available balance they should use it - if totalAvailableBalance.GreaterThanEqual(r.minerTotalFundsThreashold) { - log.Debugw("skipping over miner with enough funds cross all accounts", "height", tipset.Height(), "key", tipset.Key(), "miner", maddr, "miner_available_balance", minerAvailableBalance, "wallet_total_balances", addrSum) + sectorInfo, err := r.api.StateMinerSectors(ctx, maddr, nil, false, tipset.Key()) + if err != nil { + log.Errorw("failed to look up miner sectors", "err", err, "height", tipset.Height(), "key", tipset.Key(), "miner", maddr) continue } - // Calculate the required FIL to bring the miner up to the minimum across all of their accounts - refundValue := big.Add(totalAvailableBalance.Abs(), r.minerTotalFundsThreashold) - refunds.Track(maddr, refundValue) + if len(sectorInfo) == 0 { + log.Debugw("skipping miner with zero sectors", "height", tipset.Height(), "key", tipset.Key(), "miner", maddr) + continue + } - log.Debugw("processing negative balance miner", "miner", maddr, "refund", refundValue) + totalAvailableBalance := big.Add(addrSum, minerAvailableBalance) + + numSectorInfo := float64(len(sectorInfo)) + filAmount := uint64(math.Ceil(math.Max(math.Log(numSectorInfo)*math.Sqrt(numSectorInfo)/4, 20))) + attoFilAmount := big.Mul(big.NewIntUnsigned(filAmount), big.NewIntUnsigned(build.FilecoinPrecision)) + + if totalAvailableBalance.GreaterThanEqual(attoFilAmount) { + log.Debugw("skipping over miner with total available balance larger than refund", "height", tipset.Height(), "key", tipset.Key(), "miner", maddr, "available_balance", totalAvailableBalance, "possible_refund", attoFilAmount) + continue + } + + refundValue := big.Sub(attoFilAmount, totalAvailableBalance) + + refunds.Track(maddr, refundValue) + record := []string{maddr.String(), fmt.Sprintf("%d", len(sectorInfo)), totalAvailableBalance.String(), refundValue.String()} + if err := csvOut.Write(record); err != nil { + return nil, err + } + + log.Debugw("processing miner", "miner", maddr, "sectors", len(sectorInfo), "available_balance", totalAvailableBalance, "refund", refundValue) } return refunds, nil From e6bbc03ca8e4207907d8fb44df3818b074815c48 Mon Sep 17 00:00:00 2001 From: Travis Person Date: Sat, 19 Sep 2020 00:51:49 +0000 Subject: [PATCH 111/303] lotus-pcr: update miner recovery --- cmd/lotus-pcr/main.go | 343 +++++++++++++++++++++++++++++++++--------- 1 file changed, 269 insertions(+), 74 deletions(-) diff --git a/cmd/lotus-pcr/main.go b/cmd/lotus-pcr/main.go index 66279c29a..c80bbad48 100644 --- a/cmd/lotus-pcr/main.go +++ b/cmd/lotus-pcr/main.go @@ -7,7 +7,6 @@ import ( "encoding/csv" "fmt" "io/ioutil" - "math" "net/http" _ "net/http/pprof" "os" @@ -213,16 +212,28 @@ var recoverMinersCmd = &cli.Command{ Usage: "do not send any messages", Value: false, }, - &cli.IntFlag{ - Name: "threshold", - EnvVars: []string{"LOTUS_PCR_THRESHOLD"}, - Usage: "total filecoin across all accounts that should be met, if the miner balance drops below zero", - Value: 0, - }, &cli.StringFlag{ Name: "output", Usage: "dump data as a csv format to this file", }, + &cli.IntFlag{ + Name: "miner-recovery-cutoff", + EnvVars: []string{"LOTUS_PCR_MINER_RECOVERY_CUTOFF"}, + Usage: "maximum amount of FIL that can be sent to any one miner before refund percent is applied", + Value: 3000, + }, + &cli.IntFlag{ + Name: "miner-recovery-bonus", + EnvVars: []string{"LOTUS_PCR_MINER_RECOVERY_BONUS"}, + Usage: "additional FIL to send to each miner", + Value: 5, + }, + &cli.IntFlag{ + Name: "miner-recovery-refund-percent", + EnvVars: []string{"LOTUS_PCR_MINER_RECOVERY_REFUND_PERCENT"}, + Usage: "percent of refund to issue", + Value: 110, + }, }, Action: func(cctx *cli.Context) error { ctx := context.Background() @@ -244,13 +255,17 @@ var recoverMinersCmd = &cli.Command{ } dryRun := cctx.Bool("dry-run") - threshold := uint64(cctx.Int("threshold")) + minerRecoveryRefundPercent := cctx.Int("miner-recovery-refund-percent") + minerRecoveryCutoff := uint64(cctx.Int("miner-recovery-cutoff")) + minerRecoveryBonus := uint64(cctx.Int("miner-recovery-bonus")) rf := &refunder{ - api: api, - wallet: from, - dryRun: dryRun, - threshold: types.FromFil(threshold), + api: api, + wallet: from, + dryRun: dryRun, + minerRecoveryRefundPercent: minerRecoveryRefundPercent, + minerRecoveryCutoff: types.FromFil(minerRecoveryCutoff), + minerRecoveryBonus: types.FromFil(minerRecoveryBonus), } refundTipset, err := api.ChainHead(ctx) @@ -286,10 +301,10 @@ var runCmd = &cli.Command{ Usage: "do not wait for chain sync to complete", }, &cli.IntFlag{ - Name: "percent-extra", - EnvVars: []string{"LOTUS_PCR_PERCENT_EXTRA"}, - Usage: "extra funds to send above the refund", - Value: 3, + Name: "refund-percent", + EnvVars: []string{"LOTUS_PCR_REFUND_PERCENT"}, + Usage: "percent of refund to issue", + Value: 103, }, &cli.IntFlag{ Name: "max-message-queue", @@ -327,6 +342,36 @@ var runCmd = &cli.Command{ Usage: "the number of tipsets to delay message processing to smooth chain reorgs", Value: int(build.MessageConfidence), }, + &cli.BoolFlag{ + Name: "miner-recovery", + EnvVars: []string{"LOTUS_PCR_MINER_RECOVERY"}, + Usage: "run the miner recovery job", + Value: false, + }, + &cli.IntFlag{ + Name: "miner-recovery-period", + EnvVars: []string{"LOTUS_PCR_MINER_RECOVERY_PERIOD"}, + Usage: "interval between running miner recovery", + Value: 2880, + }, + &cli.IntFlag{ + Name: "miner-recovery-cutoff", + EnvVars: []string{"LOTUS_PCR_MINER_RECOVERY_CUTOFF"}, + Usage: "maximum amount of FIL that can be sent to any one miner before refund percent is applied", + Value: 3000, + }, + &cli.IntFlag{ + Name: "miner-recovery-bonus", + EnvVars: []string{"LOTUS_PCR_MINER_RECOVERY_BONUS"}, + Usage: "additional FIL to send to each miner", + Value: 5, + }, + &cli.IntFlag{ + Name: "miner-recovery-refund-percent", + EnvVars: []string{"LOTUS_PCR_MINER_RECOVERY_REFUND_PERCENT"}, + Usage: "percent of refund to issue", + Value: 110, + }, }, Action: func(cctx *cli.Context) error { go func() { @@ -365,24 +410,33 @@ var runCmd = &cli.Command{ log.Fatal(err) } - percentExtra := cctx.Int("percent-extra") + refundPercent := cctx.Int("refund-percent") maxMessageQueue := cctx.Int("max-message-queue") dryRun := cctx.Bool("dry-run") preCommitEnabled := cctx.Bool("pre-commit") proveCommitEnabled := cctx.Bool("prove-commit") aggregateTipsets := cctx.Int("aggregate-tipsets") + minerRecoveryEnabled := cctx.Bool("miner-recovery") + minerRecoveryPeriod := abi.ChainEpoch(int64(cctx.Int("miner-recovery-period"))) + minerRecoveryRefundPercent := cctx.Int("miner-recovery-refund-percent") + minerRecoveryCutoff := uint64(cctx.Int("miner-recovery-cutoff")) + minerRecoveryBonus := uint64(cctx.Int("miner-recovery-bonus")) rf := &refunder{ - api: api, - wallet: from, - percentExtra: percentExtra, - dryRun: dryRun, - preCommitEnabled: preCommitEnabled, - proveCommitEnabled: proveCommitEnabled, + api: api, + wallet: from, + refundPercent: refundPercent, + minerRecoveryRefundPercent: minerRecoveryRefundPercent, + minerRecoveryCutoff: types.FromFil(minerRecoveryCutoff), + minerRecoveryBonus: types.FromFil(minerRecoveryBonus), + dryRun: dryRun, + preCommitEnabled: preCommitEnabled, + proveCommitEnabled: proveCommitEnabled, } var refunds *MinersRefund = NewMinersRefund() var rounds int = 0 + nextMinerRecovery := r.MinerRecoveryHeight() + minerRecoveryPeriod for tipset := range tipsetsCh { refunds, err = rf.ProcessTipset(ctx, tipset, refunds) @@ -390,16 +444,33 @@ var runCmd = &cli.Command{ return err } - rounds = rounds + 1 - if rounds < aggregateTipsets { - continue - } - refundTipset, err := api.ChainHead(ctx) if err != nil { return err } + if minerRecoveryEnabled && refundTipset.Height() >= nextMinerRecovery { + recoveryRefund, err := rf.EnsureMinerMinimums(ctx, refundTipset, NewMinersRefund(), "") + if err != nil { + return err + } + + if err := rf.Refund(ctx, "refund to recover miners", refundTipset, recoveryRefund, 0); err != nil { + return err + } + + if err := r.SetMinerRecoveryHeight(tipset.Height()); err != nil { + return err + } + + nextMinerRecovery = r.MinerRecoveryHeight() + minerRecoveryPeriod + } + + rounds = rounds + 1 + if rounds < aggregateTipsets { + continue + } + if err := rf.Refund(ctx, "refund stats", refundTipset, refunds, rounds); err != nil { return err } @@ -502,13 +573,16 @@ type refunderNodeApi interface { } type refunder struct { - api refunderNodeApi - wallet address.Address - percentExtra int - dryRun bool - preCommitEnabled bool - proveCommitEnabled bool - threshold big.Int + api refunderNodeApi + wallet address.Address + refundPercent int + minerRecoveryRefundPercent int + minerRecoveryCutoff big.Int + minerRecoveryBonus big.Int + dryRun bool + preCommitEnabled bool + proveCommitEnabled bool + threshold big.Int } func (r *refunder) FindMiners(ctx context.Context, tipset *types.TipSet, refunds *MinersRefund, owner, worker, control bool) (*MinersRefund, error) { @@ -601,7 +675,7 @@ func (r *refunder) EnsureMinerMinimums(ctx context.Context, tipset *types.TipSet csvOut := csv.NewWriter(w) defer csvOut.Flush() - if err := csvOut.Write([]string{"MinerID", "Sectors", "CombinedBalance", "ProposedSend"}); err != nil { + if err := csvOut.Write([]string{"MinerID", "FaultedSectors", "AvailableBalance", "ProposedRefund"}); err != nil { return nil, err } @@ -644,37 +718,85 @@ func (r *refunder) EnsureMinerMinimums(ctx context.Context, tipset *types.TipSet } } - sectorInfo, err := r.api.StateMinerSectors(ctx, maddr, nil, false, tipset.Key()) + faults, err := r.api.StateMinerFaults(ctx, maddr, tipset.Key()) if err != nil { - log.Errorw("failed to look up miner sectors", "err", err, "height", tipset.Height(), "key", tipset.Key(), "miner", maddr) + log.Errorw("failed to look up miner faults", "err", err, "height", tipset.Height(), "key", tipset.Key(), "miner", maddr) continue } - if len(sectorInfo) == 0 { - log.Debugw("skipping miner with zero sectors", "height", tipset.Height(), "key", tipset.Key(), "miner", maddr) + faultsCount, err := faults.Count() + if err != nil { + log.Errorw("failed to get count of faults", "err", err, "height", tipset.Height(), "key", tipset.Key(), "miner", maddr) + continue + } + + if faultsCount == 0 { + log.Debugw("skipping miner with zero faults", "height", tipset.Height(), "key", tipset.Key(), "miner", maddr) continue } totalAvailableBalance := big.Add(addrSum, minerAvailableBalance) + balanceCutoff := big.Mul(big.Div(big.NewIntUnsigned(faultsCount), big.NewInt(10)), big.NewIntUnsigned(build.FilecoinPrecision)) - numSectorInfo := float64(len(sectorInfo)) - filAmount := uint64(math.Ceil(math.Max(math.Log(numSectorInfo)*math.Sqrt(numSectorInfo)/4, 20))) - attoFilAmount := big.Mul(big.NewIntUnsigned(filAmount), big.NewIntUnsigned(build.FilecoinPrecision)) - - if totalAvailableBalance.GreaterThanEqual(attoFilAmount) { - log.Debugw("skipping over miner with total available balance larger than refund", "height", tipset.Height(), "key", tipset.Key(), "miner", maddr, "available_balance", totalAvailableBalance, "possible_refund", attoFilAmount) + if totalAvailableBalance.GreaterThan(balanceCutoff) { + log.Debugw( + "skipping over miner with total available balance larger than refund", + "height", tipset.Height(), + "key", tipset.Key(), + "miner", maddr, + "available_balance", totalAvailableBalance, + "balance_cutoff", balanceCutoff, + "faults_count", faultsCount, + "available_balance_fil", big.Div(totalAvailableBalance, big.NewIntUnsigned(build.FilecoinPrecision)).Int64(), + "balance_cutoff_fil", big.Div(balanceCutoff, big.NewIntUnsigned(build.FilecoinPrecision)).Int64(), + ) continue } - refundValue := big.Sub(attoFilAmount, totalAvailableBalance) + refundValue := big.Sub(balanceCutoff, totalAvailableBalance) + if r.minerRecoveryRefundPercent > 0 { + refundValue = types.BigMul(types.BigDiv(refundValue, types.NewInt(100)), types.NewInt(uint64(r.minerRecoveryRefundPercent))) + } + + refundValue = big.Add(refundValue, r.minerRecoveryBonus) + + if refundValue.GreaterThan(r.minerRecoveryCutoff) { + log.Infow( + "skipping over miner with refund greater than refund cutoff", + "height", tipset.Height(), + "key", tipset.Key(), + "miner", maddr, + "available_balance", totalAvailableBalance, + "balance_cutoff", balanceCutoff, + "faults_count", faultsCount, + "refund", refundValue, + "available_balance_fil", big.Div(totalAvailableBalance, big.NewIntUnsigned(build.FilecoinPrecision)).Int64(), + "balance_cutoff_fil", big.Div(balanceCutoff, big.NewIntUnsigned(build.FilecoinPrecision)).Int64(), + "refund_fil", big.Div(refundValue, big.NewIntUnsigned(build.FilecoinPrecision)).Int64(), + ) + continue + } refunds.Track(maddr, refundValue) - record := []string{maddr.String(), fmt.Sprintf("%d", len(sectorInfo)), totalAvailableBalance.String(), refundValue.String()} + record := []string{ + maddr.String(), + fmt.Sprintf("%d", faultsCount), + big.Div(totalAvailableBalance, big.NewIntUnsigned(build.FilecoinPrecision)).String(), + big.Div(refundValue, big.NewIntUnsigned(build.FilecoinPrecision)).String(), + } if err := csvOut.Write(record); err != nil { return nil, err } - log.Debugw("processing miner", "miner", maddr, "sectors", len(sectorInfo), "available_balance", totalAvailableBalance, "refund", refundValue) + log.Debugw( + "processing miner", + "miner", maddr, + "faults_count", faultsCount, + "available_balance", totalAvailableBalance, + "refund", refundValue, + "available_balance_fil", big.Div(totalAvailableBalance, big.NewIntUnsigned(build.FilecoinPrecision)).Int64(), + "refund_fil", big.Div(refundValue, big.NewIntUnsigned(build.FilecoinPrecision)).Int64(), + ) } return refunds, nil @@ -794,17 +916,36 @@ func (r *refunder) ProcessTipset(ctx context.Context, tipset *types.TipSet, refu continue } - if r.percentExtra > 0 { - refundValue = types.BigAdd(refundValue, types.BigMul(types.BigDiv(refundValue, types.NewInt(100)), types.NewInt(uint64(r.percentExtra)))) + if r.refundPercent > 0 { + refundValue = types.BigMul(types.BigDiv(refundValue, types.NewInt(100)), types.NewInt(uint64(r.refundPercent))) } - log.Debugw("processing message", "method", messageMethod, "cid", msg.Cid, "from", m.From, "to", m.To, "value", m.Value, "gas_fee_cap", m.GasFeeCap, "gas_premium", m.GasPremium, "gas_used", recps[i].GasUsed, "refund", refundValue) + log.Debugw( + "processing message", + "method", messageMethod, + "cid", msg.Cid, + "from", m.From, + "to", m.To, + "value", m.Value, + "gas_fee_cap", m.GasFeeCap, + "gas_premium", m.GasPremium, + "gas_used", recps[i].GasUsed, + "refund", refundValue, + "refund_fil", big.Div(refundValue, big.NewIntUnsigned(build.FilecoinPrecision)).Int64(), + ) refunds.Track(m.From, refundValue) tipsetRefunds.Track(m.From, refundValue) } - log.Infow("tipset stats", "height", tipset.Height(), "key", tipset.Key(), "total_refunds", tipsetRefunds.TotalRefunds(), "messages_processed", tipsetRefunds.Count()) + log.Infow( + "tipset stats", + "height", tipset.Height(), + "key", tipset.Key(), + "total_refunds", tipsetRefunds.TotalRefunds(), + "total_refunds_fil", big.Div(tipsetRefunds.TotalRefunds(), big.NewIntUnsigned(build.FilecoinPrecision)).Int64(), + "messages_processed", tipsetRefunds.Count(), + ) return refunds, nil } @@ -867,13 +1008,24 @@ func (r *refunder) Refund(ctx context.Context, name string, tipset *types.TipSet refundSum = types.BigAdd(refundSum, msg.Value) } - log.Infow(name, "tipsets_processed", rounds, "height", tipset.Height(), "key", tipset.Key(), "messages_sent", len(messages)-failures, "refund_sum", refundSum, "messages_failures", failures, "messages_processed", refunds.Count()) + log.Infow( + name, + "tipsets_processed", rounds, + "height", tipset.Height(), + "key", tipset.Key(), + "messages_sent", len(messages)-failures, + "refund_sum", refundSum, + "refund_sum_fil", big.Div(refundSum, big.NewIntUnsigned(build.FilecoinPrecision)).Int64(), + "messages_failures", failures, + "messages_processed", refunds.Count(), + ) return nil } type Repo struct { - last abi.ChainEpoch - path string + lastHeight abi.ChainEpoch + lastMinerRecoveryHeight abi.ChainEpoch + path string } func NewRepo(path string) (*Repo, error) { @@ -883,8 +1035,9 @@ func NewRepo(path string) (*Repo, error) { } return &Repo{ - last: 0, - path: path, + lastHeight: 0, + lastMinerRecoveryHeight: 0, + path: path, }, nil } @@ -915,43 +1068,66 @@ func (r *Repo) init() error { return nil } -func (r *Repo) Open() (err error) { - if err = r.init(); err != nil { - return +func (r *Repo) Open() error { + if err := r.init(); err != nil { + return err } - var f *os.File + if err := r.loadHeight(); err != nil { + return err + } - f, err = os.OpenFile(filepath.Join(r.path, "height"), os.O_RDWR|os.O_CREATE, 0644) + if err := r.loadMinerRecoveryHeight(); err != nil { + return err + } + + return nil +} + +func loadChainEpoch(fn string) (abi.ChainEpoch, error) { + f, err := os.OpenFile(fn, os.O_RDWR|os.O_CREATE, 0644) if err != nil { - return + return 0, err } defer func() { err = f.Close() }() - var raw []byte - - raw, err = ioutil.ReadAll(f) + raw, err := ioutil.ReadAll(f) if err != nil { - return + return 0, err } height, err := strconv.Atoi(string(bytes.TrimSpace(raw))) if err != nil { - return + return 0, err } - r.last = abi.ChainEpoch(height) - return + return abi.ChainEpoch(height), nil +} + +func (r *Repo) loadHeight() error { + var err error + r.lastHeight, err = loadChainEpoch(filepath.Join(r.path, "height")) + return err +} + +func (r *Repo) loadMinerRecoveryHeight() error { + var err error + r.lastMinerRecoveryHeight, err = loadChainEpoch(filepath.Join(r.path, "miner_recovery_height")) + return err } func (r *Repo) Height() abi.ChainEpoch { - return r.last + return r.lastHeight +} + +func (r *Repo) MinerRecoveryHeight() abi.ChainEpoch { + return r.lastMinerRecoveryHeight } func (r *Repo) SetHeight(last abi.ChainEpoch) (err error) { - r.last = last + r.lastHeight = last var f *os.File f, err = os.OpenFile(filepath.Join(r.path, "height"), os.O_RDWR, 0644) if err != nil { @@ -962,7 +1138,26 @@ func (r *Repo) SetHeight(last abi.ChainEpoch) (err error) { err = f.Close() }() - if _, err = fmt.Fprintf(f, "%d", r.last); err != nil { + if _, err = fmt.Fprintf(f, "%d", r.lastHeight); err != nil { + return + } + + return +} + +func (r *Repo) SetMinerRecoveryHeight(last abi.ChainEpoch) (err error) { + r.lastMinerRecoveryHeight = last + var f *os.File + f, err = os.OpenFile(filepath.Join(r.path, "miner_recovery_height"), os.O_RDWR, 0644) + if err != nil { + return + } + + defer func() { + err = f.Close() + }() + + if _, err = fmt.Fprintf(f, "%d", r.lastMinerRecoveryHeight); err != nil { return } From 7c3f638f6853bd155b0b4becc59f395d735ea2ce Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Sat, 19 Sep 2020 00:30:24 -0400 Subject: [PATCH 112/303] Abstract FilterEstimate, PreCommitDepositForPower, and InitialPledgeForPower --- chain/actors/builtin/builtin.go | 11 +++-- chain/actors/builtin/power/v0.go | 5 ++- chain/actors/builtin/reward/reward.go | 3 ++ chain/actors/builtin/reward/v0.go | 29 +++++++++++++- node/impl/full/state.go | 58 ++++++++++++--------------- 5 files changed, 68 insertions(+), 38 deletions(-) diff --git a/chain/actors/builtin/builtin.go b/chain/actors/builtin/builtin.go index 4ce77804c..4906f0fa4 100644 --- a/chain/actors/builtin/builtin.go +++ b/chain/actors/builtin/builtin.go @@ -3,9 +3,9 @@ package builtin import ( "fmt" - "github.com/filecoin-project/go-state-types/network" + "github.com/filecoin-project/go-state-types/big" - smoothing0 "github.com/filecoin-project/specs-actors/actors/util/smoothing" + "github.com/filecoin-project/go-state-types/network" ) type Version int @@ -24,5 +24,8 @@ func VersionForNetwork(version network.Version) Version { } } -// TODO: find some way to abstract over this. -type FilterEstimate = smoothing0.FilterEstimate +// TODO: Why does actors have 2 different versions of this? +type FilterEstimate struct { + PositionEstimate big.Int + VelocityEstimate big.Int +} diff --git a/chain/actors/builtin/power/v0.go b/chain/actors/builtin/power/v0.go index 1d5a93d2b..94c8f749e 100644 --- a/chain/actors/builtin/power/v0.go +++ b/chain/actors/builtin/power/v0.go @@ -53,7 +53,10 @@ func (s *state0) MinerNominalPowerMeetsConsensusMinimum(a address.Address) (bool } func (s *state0) TotalPowerSmoothed() (builtin.FilterEstimate, error) { - return *s.State.ThisEpochQAPowerSmoothed, nil + return builtin.FilterEstimate{ + PositionEstimate: s.State.ThisEpochQAPowerSmoothed.PositionEstimate, + VelocityEstimate: s.State.ThisEpochQAPowerSmoothed.VelocityEstimate, + }, nil } func (s *state0) MinerCounts() (uint64, uint64, error) { diff --git a/chain/actors/builtin/reward/reward.go b/chain/actors/builtin/reward/reward.go index b56292fff..3f887914d 100644 --- a/chain/actors/builtin/reward/reward.go +++ b/chain/actors/builtin/reward/reward.go @@ -41,4 +41,7 @@ type State interface { CumsumBaseline() (abi.StoragePower, error) CumsumRealized() (abi.StoragePower, error) + + InitialPledgeForPower(abi.StoragePower, abi.TokenAmount, *builtin.FilterEstimate, abi.TokenAmount) (abi.TokenAmount, error) + PreCommitDepositForPower(builtin.FilterEstimate, abi.StoragePower) (abi.TokenAmount, error) } diff --git a/chain/actors/builtin/reward/v0.go b/chain/actors/builtin/reward/v0.go index 50ad49971..3efcaf93a 100644 --- a/chain/actors/builtin/reward/v0.go +++ b/chain/actors/builtin/reward/v0.go @@ -3,8 +3,10 @@ package reward import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/lotus/chain/actors/builtin" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/specs-actors/actors/builtin/reward" "github.com/filecoin-project/specs-actors/actors/util/adt" + "github.com/filecoin-project/specs-actors/actors/util/smoothing" ) type state0 struct { @@ -17,7 +19,10 @@ func (s *state0) ThisEpochReward() (abi.StoragePower, error) { } func (s *state0) ThisEpochRewardSmoothed() (builtin.FilterEstimate, error) { - return *s.State.ThisEpochRewardSmoothed, nil + return builtin.FilterEstimate{ + PositionEstimate: s.State.ThisEpochRewardSmoothed.PositionEstimate, + VelocityEstimate: s.State.ThisEpochRewardSmoothed.VelocityEstimate, + }, nil } func (s *state0) ThisEpochBaselinePower() (abi.StoragePower, error) { @@ -43,3 +48,25 @@ func (s *state0) CumsumBaseline() (abi.StoragePower, error) { func (s *state0) CumsumRealized() (abi.StoragePower, error) { return s.State.CumsumBaseline, nil } + +func (s *state0) InitialPledgeForPower(sectorWeight abi.StoragePower, networkTotalPledge abi.TokenAmount, networkQAPower *builtin.FilterEstimate, circSupply abi.TokenAmount) (abi.TokenAmount, error) { + return miner0.InitialPledgeForPower( + sectorWeight, + s.State.ThisEpochBaselinePower, + networkTotalPledge, + s.State.ThisEpochRewardSmoothed, + &smoothing.FilterEstimate{ + PositionEstimate: networkQAPower.PositionEstimate, + VelocityEstimate: networkQAPower.VelocityEstimate, + }, + circSupply), nil +} + +func (s *state0) PreCommitDepositForPower(networkQAPower builtin.FilterEstimate, sectorWeight abi.StoragePower) (abi.TokenAmount, error) { + return miner0.PreCommitDepositForPower(s.State.ThisEpochRewardSmoothed, + &smoothing.FilterEstimate{ + PositionEstimate: networkQAPower.PositionEstimate, + VelocityEstimate: networkQAPower.VelocityEstimate, + }, + sectorWeight), nil +} diff --git a/node/impl/full/state.go b/node/impl/full/state.go index 76bd3926b..e4400b073 100644 --- a/node/impl/full/state.go +++ b/node/impl/full/state.go @@ -5,6 +5,8 @@ import ( "context" "strconv" + builtin2 "github.com/filecoin-project/lotus/chain/actors/builtin" + market0 "github.com/filecoin-project/specs-actors/actors/builtin/market" "github.com/filecoin-project/lotus/chain/actors/builtin/verifreg" @@ -26,7 +28,6 @@ import ( "github.com/filecoin-project/specs-actors/actors/builtin" miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/specs-actors/actors/util/adt" - "github.com/filecoin-project/specs-actors/actors/util/smoothing" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/chain/actors/builtin/market" @@ -924,7 +925,7 @@ func (a *StateAPI) StateMinerPreCommitDepositForPower(ctx context.Context, maddr sectorWeight = miner0.QAPowerForWeight(ssize, duration, w, vw) } - var powerSmoothed smoothing.FilterEstimate + var powerSmoothed builtin2.FilterEstimate if act, err := state.GetActor(power.Address); err != nil { return types.EmptyInt, xerrors.Errorf("loading miner actor: %w", err) } else if s, err := power.Load(store, act); err != nil { @@ -935,19 +936,20 @@ func (a *StateAPI) StateMinerPreCommitDepositForPower(ctx context.Context, maddr powerSmoothed = p } - var rewardSmoothed smoothing.FilterEstimate - if act, err := state.GetActor(reward.Address); err != nil { + rewardActor, err := state.GetActor(reward.Address) + if err != nil { return types.EmptyInt, xerrors.Errorf("loading miner actor: %w", err) - } else if s, err := reward.Load(store, act); err != nil { - return types.EmptyInt, xerrors.Errorf("loading reward actor state: %w", err) - } else if r, err := s.ThisEpochRewardSmoothed(); err != nil { - return types.EmptyInt, xerrors.Errorf("failed to determine total reward: %w", err) - } else { - rewardSmoothed = r } - // TODO: ActorUpgrade - deposit := miner0.PreCommitDepositForPower(&rewardSmoothed, &powerSmoothed, sectorWeight) + rewardState, err := reward.Load(store, rewardActor) + if err != nil { + return types.EmptyInt, xerrors.Errorf("loading reward actor state: %w", err) + } + + deposit, err := rewardState.PreCommitDepositForPower(powerSmoothed, sectorWeight) + if err != nil { + return big.Zero(), xerrors.Errorf("calculating precommit deposit: %w", err) + } return types.BigDiv(types.BigMul(deposit, initialPledgeNum), initialPledgeDen), nil } @@ -982,12 +984,12 @@ func (a *StateAPI) StateMinerInitialPledgeCollateral(ctx context.Context, maddr // NB: not exactly accurate, but should always lead us to *over* estimate, not under duration := pci.Expiration - ts.Height() - // TODO: handle changes to this function across actor upgrades. + // TODO: ActorUpgrade sectorWeight = miner0.QAPowerForWeight(ssize, duration, w, vw) } var ( - powerSmoothed smoothing.FilterEstimate + powerSmoothed builtin2.FilterEstimate pledgeCollateral abi.TokenAmount ) if act, err := state.GetActor(power.Address); err != nil { @@ -1003,21 +1005,14 @@ func (a *StateAPI) StateMinerInitialPledgeCollateral(ctx context.Context, maddr pledgeCollateral = c } - var ( - rewardSmoothed smoothing.FilterEstimate - baselinePower abi.StoragePower - ) - if act, err := state.GetActor(reward.Address); err != nil { + rewardActor, err := state.GetActor(reward.Address) + if err != nil { return types.EmptyInt, xerrors.Errorf("loading miner actor: %w", err) - } else if s, err := reward.Load(store, act); err != nil { + } + + rewardState, err := reward.Load(store, rewardActor) + if err != nil { return types.EmptyInt, xerrors.Errorf("loading reward actor state: %w", err) - } else if r, err := s.ThisEpochRewardSmoothed(); err != nil { - return types.EmptyInt, xerrors.Errorf("failed to determine total reward: %w", err) - } else if p, err := s.ThisEpochBaselinePower(); err != nil { - return types.EmptyInt, xerrors.Errorf("failed to determine baseline power: %w", err) - } else { - rewardSmoothed = r - baselinePower = p } circSupply, err := a.StateCirculatingSupply(ctx, ts.Key()) @@ -1025,16 +1020,15 @@ func (a *StateAPI) StateMinerInitialPledgeCollateral(ctx context.Context, maddr return big.Zero(), xerrors.Errorf("getting circulating supply: %w", err) } - // TODO: ActorUpgrade - - initialPledge := miner0.InitialPledgeForPower( + initialPledge, err := rewardState.InitialPledgeForPower( sectorWeight, - baselinePower, pledgeCollateral, - &rewardSmoothed, &powerSmoothed, circSupply.FilCirculating, ) + if err != nil { + return big.Zero(), xerrors.Errorf("calculating initial pledge: %w", err) + } return types.BigDiv(types.BigMul(initialPledge, initialPledgeNum), initialPledgeDen), nil } From 6b40e1e30dabc87ddecfa84861b77aaf0046100e Mon Sep 17 00:00:00 2001 From: shepf Date: Sat, 19 Sep 2020 14:04:48 +0800 Subject: [PATCH 113/303] sync wait add heightDiff maybe useful! --- cli/sync.go | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/cli/sync.go b/cli/sync.go index bff34960e..3b4e2e9fb 100644 --- a/cli/sync.go +++ b/cli/sync.go @@ -249,14 +249,24 @@ func SyncWait(ctx context.Context, napi api.FullNode) error { ss := state.ActiveSyncs[working] + var baseHeight abi.ChainEpoch var target []cid.Cid var theight abi.ChainEpoch + var heightDiff int64 + + if ss.Base != nil { + baseHeight = ss.Base.Height() + heightDiff = int64(ss.Base.Height()) + } if ss.Target != nil { target = ss.Target.Cids() theight = ss.Target.Height() + heightDiff = int64(ss.Target.Height()) - heightDiff + } else { + heightDiff = 0 } - fmt.Printf("\r\x1b[2KWorker %d: Target Height: %d\tTarget: %s\tState: %s\tHeight: %d", working, theight, target, ss.Stage, ss.Height) + fmt.Printf("\r\x1b[2KWorker %d: Base Height: %d\tTarget Height: %d\t Height diff: %d\tTarget: %s\tState: %s\tHeight: %d", working, baseHeight, theight, heightDiff, target, ss.Stage, ss.Height) if time.Now().Unix()-int64(head.MinTimestamp()) < int64(build.BlockDelaySecs) { fmt.Println("\nDone!") From c401d2ec4ec58dd7ddf5e12598c04dcdcd8bf309 Mon Sep 17 00:00:00 2001 From: Jerry <1032246642@qq.com> Date: Sat, 19 Sep 2020 15:48:02 +0800 Subject: [PATCH 114/303] fix storage find error --- cmd/lotus-storage-miner/storage.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/lotus-storage-miner/storage.go b/cmd/lotus-storage-miner/storage.go index 71d88de6d..8a3687877 100644 --- a/cmd/lotus-storage-miner/storage.go +++ b/cmd/lotus-storage-miner/storage.go @@ -370,7 +370,7 @@ var storageFindCmd = &cli.Command{ } fmt.Printf("In %s (%s)\n", info.id, types[:len(types)-2]) - fmt.Printf("\tSealing: %t; Storage: %t\n", info.store.CanSeal, info.store.CanSeal) + fmt.Printf("\tSealing: %t; Storage: %t\n", info.store.CanSeal, info.store.CanStore) if localPath, ok := local[info.id]; ok { fmt.Printf("\tLocal (%s)\n", localPath) } else { From b3d0a5fb4a240500b8088dcbc068737fa27c3323 Mon Sep 17 00:00:00 2001 From: Travis Person Date: Sun, 20 Sep 2020 20:16:20 +0000 Subject: [PATCH 115/303] lotus-shed: add consensus check command --- cmd/lotus-shed/consensus.go | 286 ++++++++++++++++++++++++++++++++++++ cmd/lotus-shed/main.go | 8 + 2 files changed, 294 insertions(+) create mode 100644 cmd/lotus-shed/consensus.go diff --git a/cmd/lotus-shed/consensus.go b/cmd/lotus-shed/consensus.go new file mode 100644 index 000000000..59d9555df --- /dev/null +++ b/cmd/lotus-shed/consensus.go @@ -0,0 +1,286 @@ +package main + +import ( + "bufio" + "fmt" + "io" + "os" + "strconv" + "strings" + "time" + + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/lotus/api" + "github.com/filecoin-project/lotus/api/client" + "github.com/filecoin-project/lotus/build" + "github.com/filecoin-project/lotus/chain/types" + lcli "github.com/filecoin-project/lotus/cli" + "github.com/libp2p/go-libp2p-core/peer" + "github.com/multiformats/go-multiaddr" + "github.com/urfave/cli/v2" +) + +var consensusCmd = &cli.Command{ + Name: "consensus", + Usage: "tools for gathering information about consensus between nodes", + Flags: []cli.Flag{}, + Subcommands: []*cli.Command{ + consensusCheckCmd, + }, +} + +type consensusItem struct { + multiaddr multiaddr.Multiaddr + genesisTipset *types.TipSet + targetTipset *types.TipSet + headTipset *types.TipSet + peerID peer.ID + version api.Version + api api.FullNode +} + +var consensusCheckCmd = &cli.Command{ + Name: "check", + Usage: "verify if all nodes agree upon a common tipset for a given tipset height", + Description: `Consensus check verifies that all nodes share a common tipset for a given + height. + + The height flag specifies a chain height to start a comparison from. There are two special + arguments for this flag. All other expected values should be chain tipset heights. + + @common - Use the maximum common chain height between all nodes + @expected - Use the current time and the genesis timestamp to determine a height + + Examples + + Find the highest common tipset and look back 10 tipsets + lotus-shed consensus check --height @common --lookback 10 + + Calculate the expected tipset height and look back 10 tipsets + lotus-shed consensus check --height @expected --lookback 10 + + Check if nodes all share a common genesis + lotus-shed consensus check --height 0 + + Check that all nodes agree upon the tipset for 1day post genesis + lotus-shed consensus check --height 2880 --lookback 0 + `, + Flags: []cli.Flag{ + &cli.StringFlag{ + Name: "height", + Value: "@common", + Usage: "height of tipset to start check from", + }, + &cli.IntFlag{ + Name: "lookback", + Value: int(build.MessageConfidence * 2), + Usage: "number of tipsets behind to look back when comparing nodes", + }, + }, + Action: func(cctx *cli.Context) error { + filePath := cctx.Args().First() + + var input *bufio.Reader + if cctx.Args().Len() == 0 { + input = bufio.NewReader(os.Stdin) + } else { + var err error + inputFile, err := os.Open(filePath) + if err != nil { + return err + } + defer inputFile.Close() //nolint:errcheck + input = bufio.NewReader(inputFile) + } + + var nodes []*consensusItem + ctx := lcli.ReqContext(cctx) + + for { + strma, errR := input.ReadString('\n') + strma = strings.TrimSpace(strma) + + if len(strma) == 0 { + if errR == io.EOF { + break + } + continue + } + + apima, err := multiaddr.NewMultiaddr(strma) + if err != nil { + return err + } + ainfo := lcli.APIInfo{Addr: apima} + addr, err := ainfo.DialArgs() + if err != nil { + return err + } + + api, closer, err := client.NewFullNodeRPC(cctx.Context, addr, nil) + if err != nil { + return err + } + defer closer() + + peerID, err := api.ID(ctx) + if err != nil { + return err + } + + version, err := api.Version(ctx) + if err != nil { + return err + } + + genesisTipset, err := api.ChainGetGenesis(ctx) + if err != nil { + return err + } + + headTipset, err := api.ChainHead(ctx) + if err != nil { + return err + } + + nodes = append(nodes, &consensusItem{ + genesisTipset: genesisTipset, + headTipset: headTipset, + multiaddr: apima, + api: api, + peerID: peerID, + version: version, + }) + + if errR != nil && errR != io.EOF { + return err + } + + if errR == io.EOF { + break + } + } + + if len(nodes) == 0 { + return fmt.Errorf("no nodes") + } + + genesisBuckets := make(map[types.TipSetKey][]*consensusItem) + for _, node := range nodes { + genesisBuckets[node.genesisTipset.Key()] = append(genesisBuckets[node.genesisTipset.Key()], node) + + } + + if len(genesisBuckets) != 1 { + for _, nodes := range genesisBuckets { + for _, node := range nodes { + log.Errorw( + "genesis do not match", + "genesis_tipset", node.genesisTipset.Key(), + "peer_id", node.peerID, + "version", node.version, + ) + } + } + + return fmt.Errorf("genesis does not match between all nodes") + } + + target := abi.ChainEpoch(0) + + switch cctx.String("height") { + case "@common": + minTipset := nodes[0].headTipset + for _, node := range nodes { + if node.headTipset.Height() < minTipset.Height() { + minTipset = node.headTipset + } + } + + target = minTipset.Height() + case "@expected": + tnow := uint64(time.Now().Unix()) + tgen := nodes[0].genesisTipset.MinTimestamp() + + target = abi.ChainEpoch((tnow - tgen) / build.BlockDelaySecs) + default: + h, err := strconv.Atoi(strings.TrimSpace(cctx.String("height"))) + if err != nil { + return fmt.Errorf("failed to parse string: %s", cctx.String("height")) + } + + target = abi.ChainEpoch(h) + } + + lookback := abi.ChainEpoch(cctx.Int("lookback")) + if lookback > target { + target = abi.ChainEpoch(0) + } else { + target = target - lookback + } + + for _, node := range nodes { + targetTipset, err := node.api.ChainGetTipSetByHeight(ctx, target, types.EmptyTSK) + if err != nil { + log.Errorw("error checking target", "err", err) + node.targetTipset = nil + } else { + node.targetTipset = targetTipset + } + + } + for _, node := range nodes { + log.Debugw( + "node info", + "peer_id", node.peerID, + "version", node.version, + "genesis_tipset", node.genesisTipset.Key(), + "head_tipset", node.headTipset.Key(), + "target_tipset", node.targetTipset.Key(), + ) + } + + targetBuckets := make(map[types.TipSetKey][]*consensusItem) + for _, node := range nodes { + if node.targetTipset == nil { + targetBuckets[types.EmptyTSK] = append(targetBuckets[types.EmptyTSK], node) + continue + } + + targetBuckets[node.targetTipset.Key()] = append(targetBuckets[node.targetTipset.Key()], node) + } + + if nodes, ok := targetBuckets[types.EmptyTSK]; ok { + for _, node := range nodes { + log.Errorw( + "targeted tipset not found", + "peer_id", node.peerID, + "version", node.version, + "genesis_tipset", node.genesisTipset.Key(), + "head_tipset", node.headTipset.Key(), + "target_tipset", node.targetTipset.Key(), + ) + } + + return fmt.Errorf("targeted tipset not found") + } + + if len(targetBuckets) != 1 { + for _, nodes := range targetBuckets { + for _, node := range nodes { + log.Errorw( + "targeted tipset not found", + "peer_id", node.peerID, + "version", node.version, + "genesis_tipset", node.genesisTipset.Key(), + "head_tipset", node.headTipset.Key(), + "target_tipset", node.targetTipset.Key(), + ) + } + } + return fmt.Errorf("nodes not in consensus at tipset height %d", target) + } + + return nil + }, +} diff --git a/cmd/lotus-shed/main.go b/cmd/lotus-shed/main.go index cff3059b6..1a56756d1 100644 --- a/cmd/lotus-shed/main.go +++ b/cmd/lotus-shed/main.go @@ -35,6 +35,7 @@ func main() { mathCmd, mpoolStatsCmd, exportChainCmd, + consensusCmd, } app := &cli.App{ @@ -49,6 +50,13 @@ func main() { Hidden: true, Value: "~/.lotus", // TODO: Consider XDG_DATA_HOME }, + &cli.StringFlag{ + Name: "log-level", + Value: "info", + }, + }, + Before: func(cctx *cli.Context) error { + return logging.SetLogLevel("lotus-shed", cctx.String("log-level")) }, } From b25dd2a00d9c4d346087438d33a8d789a50aa8f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Sun, 20 Sep 2020 23:04:45 +0200 Subject: [PATCH 116/303] More correct / fasterer GetSectorsForWinningPoSt --- chain/actors/builtin/miner/v0.go | 12 ++++++------ chain/stmgr/utils.go | 20 +++++++++++++++----- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index 37df8c217..7985896f3 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -163,9 +163,9 @@ func (s *state0) LoadSectorsFromSet(filter *bitfield.BitField, filterOut bool) ( return nil, err } - var v cbg.Deferred - if err := a.ForEach(&v, func(i int64) error { - if filter != nil { + if filter != nil { + var v cbg.Deferred + if err := a.ForEach(&v, func(i int64) error { set, err := filter.IsSet(uint64(i)) if err != nil { return xerrors.Errorf("filter check error: %w", err) @@ -176,10 +176,10 @@ func (s *state0) LoadSectorsFromSet(filter *bitfield.BitField, filterOut bool) ( return xerrors.Errorf("filtering error: %w", err) } } + return nil + }); err != nil { + return nil, err } - return nil - }); err != nil { - return nil, err } return a, nil diff --git a/chain/stmgr/utils.go b/chain/stmgr/utils.go index 3684b9e77..203d49490 100644 --- a/chain/stmgr/utils.go +++ b/chain/stmgr/utils.go @@ -197,12 +197,21 @@ func GetSectorsForWinningPoSt(ctx context.Context, pv ffiwrapper.Verifier, sm *S return nil, xerrors.Errorf("failed to load miner actor state: %w", err) } - // TODO (!!): This was partition.Sectors-partition.Faults originally, which was likely very wrong, and will need to be an upgrade - // ^ THE CURRENT THING HERE WON'T SYNC v + // TODO (!!): Actor Update: Make this active sectors - provingSectors, err := miner.AllPartSectors(mas, miner.Partition.ActiveSectors) + allSectors, err := miner.AllPartSectors(mas, miner.Partition.AllSectors) if err != nil { - return nil, xerrors.Errorf("merge partition proving sets: %w", err) + return nil, xerrors.Errorf("get all sectors: %w", err) + } + + faultySectors, err := miner.AllPartSectors(mas, miner.Partition.FaultySectors) + if err != nil { + return nil, xerrors.Errorf("get faulty sectors: %w", err) + } + + provingSectors, err := bitfield.SubtractBitField(allSectors, faultySectors) // TODO: This is wrong, as it can contain faaults, change to just ActiveSectors in an upgrade + if err != nil { + return nil, xerrors.Errorf("calc proving sectors: %w", err) } numProvSect, err := provingSectors.Count() @@ -240,7 +249,8 @@ func GetSectorsForWinningPoSt(ctx context.Context, pv ffiwrapper.Verifier, sm *S return nil, xerrors.Errorf("generating winning post challenges: %w", err) } - sectors, err := mas.LoadSectorsFromSet(&provingSectors, false) + // we don't need to filter here (and it's **very** slow) + sectors, err := mas.LoadSectorsFromSet(nil, false) if err != nil { return nil, xerrors.Errorf("loading proving sectors: %w", err) } From ed285f1114ab1a9fd2a2d5b4f149077a8c3b851c Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Sun, 20 Sep 2020 17:53:46 -0400 Subject: [PATCH 117/303] Abstract SectorOnChainInfo and SectorPreCommitOnChainInfo --- chain/actors/builtin/builtin.go | 9 +++++---- chain/actors/builtin/market/v0.go | 6 +++--- chain/actors/builtin/miner/miner.go | 26 ++++++++++++++++++++++++-- chain/actors/builtin/miner/v0.go | 26 ++++++++++++++++++++++---- chain/actors/builtin/power/v0.go | 5 +---- chain/actors/builtin/reward/v0.go | 5 +---- 6 files changed, 56 insertions(+), 21 deletions(-) diff --git a/chain/actors/builtin/builtin.go b/chain/actors/builtin/builtin.go index 4906f0fa4..9ad976564 100644 --- a/chain/actors/builtin/builtin.go +++ b/chain/actors/builtin/builtin.go @@ -3,7 +3,7 @@ package builtin import ( "fmt" - "github.com/filecoin-project/go-state-types/big" + smoothing0 "github.com/filecoin-project/specs-actors/actors/util/smoothing" "github.com/filecoin-project/go-state-types/network" ) @@ -25,7 +25,8 @@ func VersionForNetwork(version network.Version) Version { } // TODO: Why does actors have 2 different versions of this? -type FilterEstimate struct { - PositionEstimate big.Int - VelocityEstimate big.Int +type FilterEstimate = smoothing0.FilterEstimate + +func FromV0FilterEstimate(v0 smoothing0.FilterEstimate) FilterEstimate { + return (FilterEstimate)(v0) } diff --git a/chain/actors/builtin/market/v0.go b/chain/actors/builtin/market/v0.go index 27eee4c50..e184b668d 100644 --- a/chain/actors/builtin/market/v0.go +++ b/chain/actors/builtin/market/v0.go @@ -26,7 +26,7 @@ func (s *state0) TotalLocked() (abi.TokenAmount, error) { func (s *state0) BalancesChanged(otherState State) bool { otherState0, ok := otherState.(*state0) if !ok { - // there's no way to compare differnt versions of the state, so let's + // there's no way to compare different versions of the state, so let's // just say that means the state of balances has changed return true } @@ -36,7 +36,7 @@ func (s *state0) BalancesChanged(otherState State) bool { func (s *state0) StatesChanged(otherState State) bool { otherState0, ok := otherState.(*state0) if !ok { - // there's no way to compare differnt versions of the state, so let's + // there's no way to compare different versions of the state, so let's // just say that means the state of balances has changed return true } @@ -54,7 +54,7 @@ func (s *state0) States() (DealStates, error) { func (s *state0) ProposalsChanged(otherState State) bool { otherState0, ok := otherState.(*state0) if !ok { - // there's no way to compare differnt versions of the state, so let's + // there's no way to compare different versions of the state, so let's // just say that means the state of balances has changed return true } diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index d25652d30..704ea1291 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -2,6 +2,7 @@ package miner import ( "github.com/filecoin-project/go-state-types/dline" + "github.com/ipfs/go-cid" "github.com/libp2p/go-libp2p-core/peer" cbg "github.com/whyrusleeping/cbor-gen" "golang.org/x/xerrors" @@ -81,9 +82,30 @@ type Partition interface { ActiveSectors() (bitfield.BitField, error) } -type SectorOnChainInfo = miner0.SectorOnChainInfo +type SectorOnChainInfo struct { + SectorNumber abi.SectorNumber + SealProof abi.RegisteredSealProof + SealedCID cid.Cid + DealIDs []abi.DealID + Activation abi.ChainEpoch + Expiration abi.ChainEpoch + DealWeight abi.DealWeight + VerifiedDealWeight abi.DealWeight + InitialPledge abi.TokenAmount + ExpectedDayReward abi.TokenAmount + ExpectedStoragePledge abi.TokenAmount +} + type SectorPreCommitInfo = miner0.SectorPreCommitInfo -type SectorPreCommitOnChainInfo = miner0.SectorPreCommitOnChainInfo + +type SectorPreCommitOnChainInfo struct { + Info SectorPreCommitInfo + PreCommitDeposit abi.TokenAmount + PreCommitEpoch abi.ChainEpoch + DealWeight abi.DealWeight + VerifiedDealWeight abi.DealWeight +} + type PoStPartition = miner0.PoStPartition type RecoveryDeclaration = miner0.RecoveryDeclaration type FaultDeclaration = miner0.FaultDeclaration diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index 7985896f3..71306fafd 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -62,7 +62,8 @@ func (s *state0) GetSector(num abi.SectorNumber) (*SectorOnChainInfo, error) { return nil, err } - return info, nil + ret := fromV0SectorOnChainInfo(*info) + return &ret, nil } func (s *state0) FindSector(num abi.SectorNumber) (*SectorLocation, error) { @@ -154,7 +155,8 @@ func (s *state0) GetPrecommittedSector(num abi.SectorNumber) (*SectorPreCommitOn return nil, err } - return info, nil + ret := fromV0SectorPreCommitOnChainInfo(*info) + return &ret, nil } func (s *state0) LoadSectorsFromSet(filter *bitfield.BitField, filterOut bool) (adt.Array, error) { @@ -279,7 +281,11 @@ func (s *state0) sectors() (adt.Array, error) { func (s *state0) decodeSectorOnChainInfo(val *cbg.Deferred) (SectorOnChainInfo, error) { var si miner0.SectorOnChainInfo err := si.UnmarshalCBOR(bytes.NewReader(val.Raw)) - return si, err + if err != nil { + return SectorOnChainInfo{}, err + } + + return fromV0SectorOnChainInfo(si), nil } func (s *state0) precommits() (adt.Map, error) { @@ -289,7 +295,11 @@ func (s *state0) precommits() (adt.Map, error) { func (s *state0) decodeSectorPreCommitOnChainInfo(val *cbg.Deferred) (SectorPreCommitOnChainInfo, error) { var sp miner0.SectorPreCommitOnChainInfo err := sp.UnmarshalCBOR(bytes.NewReader(val.Raw)) - return sp, err + if err != nil { + return SectorPreCommitOnChainInfo{}, err + } + + return fromV0SectorPreCommitOnChainInfo(sp), nil } func (d *deadline0) LoadPartition(idx uint64) (Partition, error) { @@ -336,3 +346,11 @@ func (p *partition0) FaultySectors() (bitfield.BitField, error) { func (p *partition0) RecoveringSectors() (bitfield.BitField, error) { return p.Partition.Recoveries, nil } + +func fromV0SectorOnChainInfo(v0 miner0.SectorOnChainInfo) SectorOnChainInfo { + return (SectorOnChainInfo)(v0) +} + +func fromV0SectorPreCommitOnChainInfo(v0 miner0.SectorPreCommitOnChainInfo) SectorPreCommitOnChainInfo { + return (SectorPreCommitOnChainInfo)(v0) +} diff --git a/chain/actors/builtin/power/v0.go b/chain/actors/builtin/power/v0.go index 94c8f749e..e19984f72 100644 --- a/chain/actors/builtin/power/v0.go +++ b/chain/actors/builtin/power/v0.go @@ -53,10 +53,7 @@ func (s *state0) MinerNominalPowerMeetsConsensusMinimum(a address.Address) (bool } func (s *state0) TotalPowerSmoothed() (builtin.FilterEstimate, error) { - return builtin.FilterEstimate{ - PositionEstimate: s.State.ThisEpochQAPowerSmoothed.PositionEstimate, - VelocityEstimate: s.State.ThisEpochQAPowerSmoothed.VelocityEstimate, - }, nil + return builtin.FromV0FilterEstimate(*s.State.ThisEpochQAPowerSmoothed), nil } func (s *state0) MinerCounts() (uint64, uint64, error) { diff --git a/chain/actors/builtin/reward/v0.go b/chain/actors/builtin/reward/v0.go index 3efcaf93a..981905ba5 100644 --- a/chain/actors/builtin/reward/v0.go +++ b/chain/actors/builtin/reward/v0.go @@ -19,10 +19,7 @@ func (s *state0) ThisEpochReward() (abi.StoragePower, error) { } func (s *state0) ThisEpochRewardSmoothed() (builtin.FilterEstimate, error) { - return builtin.FilterEstimate{ - PositionEstimate: s.State.ThisEpochRewardSmoothed.PositionEstimate, - VelocityEstimate: s.State.ThisEpochRewardSmoothed.VelocityEstimate, - }, nil + return builtin.FromV0FilterEstimate(*s.State.ThisEpochRewardSmoothed), nil } func (s *state0) ThisEpochBaselinePower() (abi.StoragePower, error) { From a95e34f742355deea28c2c1376d5ce7e4d1846b8 Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Mon, 21 Sep 2020 01:58:20 -0400 Subject: [PATCH 118/303] Fix build --- chain/actors/builtin/miner/cbor_gen.go | 313 +++++++++++++++++++++++++ chain/actors/builtin/miner/v0.go | 46 +++- chain/stmgr/utils.go | 2 +- gen/main.go | 9 + 4 files changed, 358 insertions(+), 12 deletions(-) create mode 100644 chain/actors/builtin/miner/cbor_gen.go diff --git a/chain/actors/builtin/miner/cbor_gen.go b/chain/actors/builtin/miner/cbor_gen.go new file mode 100644 index 000000000..16819d5c4 --- /dev/null +++ b/chain/actors/builtin/miner/cbor_gen.go @@ -0,0 +1,313 @@ +// Code generated by github.com/whyrusleeping/cbor-gen. DO NOT EDIT. + +package miner + +import ( + "fmt" + "io" + + abi "github.com/filecoin-project/go-state-types/abi" + cbg "github.com/whyrusleeping/cbor-gen" + xerrors "golang.org/x/xerrors" +) + +var _ = xerrors.Errorf + +var lengthBufSectorOnChainInfo = []byte{139} + +func (t *SectorOnChainInfo) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + if _, err := w.Write(lengthBufSectorOnChainInfo); err != nil { + return err + } + + scratch := make([]byte, 9) + + // t.SectorNumber (abi.SectorNumber) (uint64) + + if err := cbg.WriteMajorTypeHeaderBuf(scratch, w, cbg.MajUnsignedInt, uint64(t.SectorNumber)); err != nil { + return err + } + + // t.SealProof (abi.RegisteredSealProof) (int64) + if t.SealProof >= 0 { + if err := cbg.WriteMajorTypeHeaderBuf(scratch, w, cbg.MajUnsignedInt, uint64(t.SealProof)); err != nil { + return err + } + } else { + if err := cbg.WriteMajorTypeHeaderBuf(scratch, w, cbg.MajNegativeInt, uint64(-t.SealProof-1)); err != nil { + return err + } + } + + // t.SealedCID (cid.Cid) (struct) + + if err := cbg.WriteCidBuf(scratch, w, t.SealedCID); err != nil { + return xerrors.Errorf("failed to write cid field t.SealedCID: %w", err) + } + + // t.DealIDs ([]abi.DealID) (slice) + if len(t.DealIDs) > cbg.MaxLength { + return xerrors.Errorf("Slice value in field t.DealIDs was too long") + } + + if err := cbg.WriteMajorTypeHeaderBuf(scratch, w, cbg.MajArray, uint64(len(t.DealIDs))); err != nil { + return err + } + for _, v := range t.DealIDs { + if err := cbg.CborWriteHeader(w, cbg.MajUnsignedInt, uint64(v)); err != nil { + return err + } + } + + // t.Activation (abi.ChainEpoch) (int64) + if t.Activation >= 0 { + if err := cbg.WriteMajorTypeHeaderBuf(scratch, w, cbg.MajUnsignedInt, uint64(t.Activation)); err != nil { + return err + } + } else { + if err := cbg.WriteMajorTypeHeaderBuf(scratch, w, cbg.MajNegativeInt, uint64(-t.Activation-1)); err != nil { + return err + } + } + + // t.Expiration (abi.ChainEpoch) (int64) + if t.Expiration >= 0 { + if err := cbg.WriteMajorTypeHeaderBuf(scratch, w, cbg.MajUnsignedInt, uint64(t.Expiration)); err != nil { + return err + } + } else { + if err := cbg.WriteMajorTypeHeaderBuf(scratch, w, cbg.MajNegativeInt, uint64(-t.Expiration-1)); err != nil { + return err + } + } + + // t.DealWeight (big.Int) (struct) + if err := t.DealWeight.MarshalCBOR(w); err != nil { + return err + } + + // t.VerifiedDealWeight (big.Int) (struct) + if err := t.VerifiedDealWeight.MarshalCBOR(w); err != nil { + return err + } + + // t.InitialPledge (big.Int) (struct) + if err := t.InitialPledge.MarshalCBOR(w); err != nil { + return err + } + + // t.ExpectedDayReward (big.Int) (struct) + if err := t.ExpectedDayReward.MarshalCBOR(w); err != nil { + return err + } + + // t.ExpectedStoragePledge (big.Int) (struct) + if err := t.ExpectedStoragePledge.MarshalCBOR(w); err != nil { + return err + } + return nil +} + +func (t *SectorOnChainInfo) UnmarshalCBOR(r io.Reader) error { + *t = SectorOnChainInfo{} + + br := cbg.GetPeeker(r) + scratch := make([]byte, 8) + + maj, extra, err := cbg.CborReadHeaderBuf(br, scratch) + if err != nil { + return err + } + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 11 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.SectorNumber (abi.SectorNumber) (uint64) + + { + + maj, extra, err = cbg.CborReadHeaderBuf(br, scratch) + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.SectorNumber = abi.SectorNumber(extra) + + } + // t.SealProof (abi.RegisteredSealProof) (int64) + { + maj, extra, err := cbg.CborReadHeaderBuf(br, scratch) + var extraI int64 + if err != nil { + return err + } + switch maj { + case cbg.MajUnsignedInt: + extraI = int64(extra) + if extraI < 0 { + return fmt.Errorf("int64 positive overflow") + } + case cbg.MajNegativeInt: + extraI = int64(extra) + if extraI < 0 { + return fmt.Errorf("int64 negative oveflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.SealProof = abi.RegisteredSealProof(extraI) + } + // t.SealedCID (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(br) + if err != nil { + return xerrors.Errorf("failed to read cid field t.SealedCID: %w", err) + } + + t.SealedCID = c + + } + // t.DealIDs ([]abi.DealID) (slice) + + maj, extra, err = cbg.CborReadHeaderBuf(br, scratch) + if err != nil { + return err + } + + if extra > cbg.MaxLength { + return fmt.Errorf("t.DealIDs: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.DealIDs = make([]abi.DealID, extra) + } + + for i := 0; i < int(extra); i++ { + + maj, val, err := cbg.CborReadHeaderBuf(br, scratch) + if err != nil { + return xerrors.Errorf("failed to read uint64 for t.DealIDs slice: %w", err) + } + + if maj != cbg.MajUnsignedInt { + return xerrors.Errorf("value read for array t.DealIDs was not a uint, instead got %d", maj) + } + + t.DealIDs[i] = abi.DealID(val) + } + + // t.Activation (abi.ChainEpoch) (int64) + { + maj, extra, err := cbg.CborReadHeaderBuf(br, scratch) + var extraI int64 + if err != nil { + return err + } + switch maj { + case cbg.MajUnsignedInt: + extraI = int64(extra) + if extraI < 0 { + return fmt.Errorf("int64 positive overflow") + } + case cbg.MajNegativeInt: + extraI = int64(extra) + if extraI < 0 { + return fmt.Errorf("int64 negative oveflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.Activation = abi.ChainEpoch(extraI) + } + // t.Expiration (abi.ChainEpoch) (int64) + { + maj, extra, err := cbg.CborReadHeaderBuf(br, scratch) + var extraI int64 + if err != nil { + return err + } + switch maj { + case cbg.MajUnsignedInt: + extraI = int64(extra) + if extraI < 0 { + return fmt.Errorf("int64 positive overflow") + } + case cbg.MajNegativeInt: + extraI = int64(extra) + if extraI < 0 { + return fmt.Errorf("int64 negative oveflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.Expiration = abi.ChainEpoch(extraI) + } + // t.DealWeight (big.Int) (struct) + + { + + if err := t.DealWeight.UnmarshalCBOR(br); err != nil { + return xerrors.Errorf("unmarshaling t.DealWeight: %w", err) + } + + } + // t.VerifiedDealWeight (big.Int) (struct) + + { + + if err := t.VerifiedDealWeight.UnmarshalCBOR(br); err != nil { + return xerrors.Errorf("unmarshaling t.VerifiedDealWeight: %w", err) + } + + } + // t.InitialPledge (big.Int) (struct) + + { + + if err := t.InitialPledge.UnmarshalCBOR(br); err != nil { + return xerrors.Errorf("unmarshaling t.InitialPledge: %w", err) + } + + } + // t.ExpectedDayReward (big.Int) (struct) + + { + + if err := t.ExpectedDayReward.UnmarshalCBOR(br); err != nil { + return xerrors.Errorf("unmarshaling t.ExpectedDayReward: %w", err) + } + + } + // t.ExpectedStoragePledge (big.Int) (struct) + + { + + if err := t.ExpectedStoragePledge.UnmarshalCBOR(br); err != nil { + return xerrors.Errorf("unmarshaling t.ExpectedStoragePledge: %w", err) + } + + } + return nil +} diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index 71306fafd..6d4e7c589 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -165,26 +165,50 @@ func (s *state0) LoadSectorsFromSet(filter *bitfield.BitField, filterOut bool) ( return nil, err } - if filter != nil { - var v cbg.Deferred - if err := a.ForEach(&v, func(i int64) error { + ret := adt0.MakeEmptyArray(s.store) + var v cbg.Deferred + if err := a.ForEach(&v, func(i int64) error { + include := true + if filter != nil { set, err := filter.IsSet(uint64(i)) if err != nil { return xerrors.Errorf("filter check error: %w", err) } if set == filterOut { - err = a.Delete(uint64(i)) - if err != nil { - return xerrors.Errorf("filtering error: %w", err) - } + include = false } - return nil - }); err != nil { - return nil, err } + + if include { + var oci miner0.SectorOnChainInfo + if err := oci.UnmarshalCBOR(bytes.NewReader(v.Raw)); err != nil { + return err + } + + noci := SectorOnChainInfo{ + SectorNumber: oci.SectorNumber, + SealProof: oci.SealProof, + SealedCID: oci.SealedCID, + DealIDs: oci.DealIDs, + Activation: oci.Activation, + Expiration: oci.Expiration, + DealWeight: oci.DealWeight, + VerifiedDealWeight: oci.VerifiedDealWeight, + InitialPledge: oci.InitialPledge, + ExpectedDayReward: oci.ExpectedDayReward, + ExpectedStoragePledge: oci.ExpectedStoragePledge, + } + + if err := ret.Set(uint64(i), &noci); err != nil { + return err + } + } + return nil + }); err != nil { + return nil, err } - return a, nil + return ret, nil } func (s *state0) LoadPreCommittedSectors() (adt.Map, error) { diff --git a/chain/stmgr/utils.go b/chain/stmgr/utils.go index 203d49490..20d7bd54f 100644 --- a/chain/stmgr/utils.go +++ b/chain/stmgr/utils.go @@ -169,7 +169,7 @@ func GetMinerSectorSet(ctx context.Context, sm *StateManager, ts *types.TipSet, var sset []*miner.ChainSectorInfo var v cbg.Deferred if err := sectors.ForEach(&v, func(i int64) error { - var oci miner0.SectorOnChainInfo + var oci miner.SectorOnChainInfo if err := oci.UnmarshalCBOR(bytes.NewReader(v.Raw)); err != nil { return err } diff --git a/gen/main.go b/gen/main.go index be227663c..90b24e3a7 100644 --- a/gen/main.go +++ b/gen/main.go @@ -4,6 +4,8 @@ import ( "fmt" "os" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + gen "github.com/whyrusleeping/cbor-gen" "github.com/filecoin-project/lotus/api" @@ -76,4 +78,11 @@ func main() { os.Exit(1) } + err = gen.WriteTupleEncodersToFile("./chain/actors/builtin/miner/cbor_gen.go", "miner", + miner.SectorOnChainInfo{}, + ) + if err != nil { + fmt.Println(err) + os.Exit(1) + } } From b355eb75ebd99f4c4ea84b0c1288afdcdc91c0af Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Mon, 21 Sep 2020 02:19:32 -0400 Subject: [PATCH 119/303] Add compile-time checks that actors interfaces are correctly implemented --- chain/actors/builtin/account/v0.go | 2 ++ chain/actors/builtin/init/v0.go | 2 ++ chain/actors/builtin/market/v0.go | 2 ++ chain/actors/builtin/miner/v0.go | 2 ++ chain/actors/builtin/multisig/v0.go | 2 ++ chain/actors/builtin/paych/v0.go | 2 ++ chain/actors/builtin/power/v0.go | 2 ++ chain/actors/builtin/reward/v0.go | 2 ++ chain/actors/builtin/verifreg/v0.go | 2 ++ 9 files changed, 18 insertions(+) diff --git a/chain/actors/builtin/account/v0.go b/chain/actors/builtin/account/v0.go index 535255d0e..30bafbfd3 100644 --- a/chain/actors/builtin/account/v0.go +++ b/chain/actors/builtin/account/v0.go @@ -6,6 +6,8 @@ import ( "github.com/filecoin-project/specs-actors/actors/builtin/account" ) +var _ State = (*state0)(nil) + type state0 struct { account.State store adt.Store diff --git a/chain/actors/builtin/init/v0.go b/chain/actors/builtin/init/v0.go index 0e8395a08..717ed9669 100644 --- a/chain/actors/builtin/init/v0.go +++ b/chain/actors/builtin/init/v0.go @@ -13,6 +13,8 @@ import ( adt0 "github.com/filecoin-project/specs-actors/actors/util/adt" ) +var _ State = (*state0)(nil) + type state0 struct { init_.State store adt.Store diff --git a/chain/actors/builtin/market/v0.go b/chain/actors/builtin/market/v0.go index e184b668d..433445dab 100644 --- a/chain/actors/builtin/market/v0.go +++ b/chain/actors/builtin/market/v0.go @@ -12,6 +12,8 @@ import ( cbg "github.com/whyrusleeping/cbor-gen" ) +var _ State = (*state0)(nil) + type state0 struct { market.State store adt.Store diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index 6d4e7c589..010ae6699 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -17,6 +17,8 @@ import ( miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" ) +var _ State = (*state0)(nil) + type state0 struct { miner0.State store adt.Store diff --git a/chain/actors/builtin/multisig/v0.go b/chain/actors/builtin/multisig/v0.go index ded834d5f..5de5ca6ad 100644 --- a/chain/actors/builtin/multisig/v0.go +++ b/chain/actors/builtin/multisig/v0.go @@ -6,6 +6,8 @@ import ( "github.com/filecoin-project/specs-actors/actors/builtin/multisig" ) +var _ State = (*state0)(nil) + type state0 struct { multisig.State store adt.Store diff --git a/chain/actors/builtin/paych/v0.go b/chain/actors/builtin/paych/v0.go index 0c4b2f218..b69cf46ce 100644 --- a/chain/actors/builtin/paych/v0.go +++ b/chain/actors/builtin/paych/v0.go @@ -9,6 +9,8 @@ import ( adt0 "github.com/filecoin-project/specs-actors/actors/util/adt" ) +var _ State = (*state0)(nil) + type state0 struct { paych.State store adt.Store diff --git a/chain/actors/builtin/power/v0.go b/chain/actors/builtin/power/v0.go index e19984f72..f2fe96dad 100644 --- a/chain/actors/builtin/power/v0.go +++ b/chain/actors/builtin/power/v0.go @@ -8,6 +8,8 @@ import ( "github.com/filecoin-project/specs-actors/actors/util/adt" ) +var _ State = (*state0)(nil) + type state0 struct { power0.State store adt.Store diff --git a/chain/actors/builtin/reward/v0.go b/chain/actors/builtin/reward/v0.go index 981905ba5..df7117b67 100644 --- a/chain/actors/builtin/reward/v0.go +++ b/chain/actors/builtin/reward/v0.go @@ -9,6 +9,8 @@ import ( "github.com/filecoin-project/specs-actors/actors/util/smoothing" ) +var _ State = (*state0)(nil) + type state0 struct { reward.State store adt.Store diff --git a/chain/actors/builtin/verifreg/v0.go b/chain/actors/builtin/verifreg/v0.go index c397d6679..f64c27310 100644 --- a/chain/actors/builtin/verifreg/v0.go +++ b/chain/actors/builtin/verifreg/v0.go @@ -11,6 +11,8 @@ import ( "github.com/filecoin-project/lotus/chain/actors/adt" ) +var _ State = (*state0)(nil) + type state0 struct { verifreg0.State store adt.Store From f135ec84682f072626e90b9b43f65ad535ddaa33 Mon Sep 17 00:00:00 2001 From: vyzo Date: Mon, 21 Sep 2020 09:21:25 +0300 Subject: [PATCH 120/303] fix handling of end of sync --- chain/sync.go | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/chain/sync.go b/chain/sync.go index 03ae1cd4f..74dc5aa1a 100644 --- a/chain/sync.go +++ b/chain/sync.go @@ -1486,11 +1486,7 @@ func (syncer *Syncer) iterFullTipsets(ctx context.Context, headers []*types.TipS batchSize := concurrentSyncRequests * syncRequestBatchSize if i < batchSize { - if i == 0 { - batchSize = 1 - } else { - batchSize = i - } + batchSize = i + 1 } ss.SetStage(api.StageFetchingMessages) From 286fe042715cce1e11d2bcf67de8cdd28558190d Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Mon, 21 Sep 2020 02:52:45 -0400 Subject: [PATCH 121/303] Add some TODOs --- chain/stmgr/utils.go | 58 +++++++++++++++++++++++--------------------- 1 file changed, 31 insertions(+), 27 deletions(-) diff --git a/chain/stmgr/utils.go b/chain/stmgr/utils.go index 20d7bd54f..1056818a6 100644 --- a/chain/stmgr/utils.go +++ b/chain/stmgr/utils.go @@ -9,11 +9,7 @@ import ( "runtime" "strings" - init0 "github.com/filecoin-project/specs-actors/actors/builtin/init" - market0 "github.com/filecoin-project/specs-actors/actors/builtin/market" - power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" - - miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" + "github.com/filecoin-project/specs-actors/actors/builtin/cron" saruntime "github.com/filecoin-project/specs-actors/actors/runtime" "github.com/filecoin-project/specs-actors/actors/runtime/proof" @@ -28,11 +24,14 @@ import ( "github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/lotus/chain/actors/builtin/power" "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" - "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/account" - "github.com/filecoin-project/specs-actors/actors/builtin/cron" + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" + account0 "github.com/filecoin-project/specs-actors/actors/builtin/account" + init0 "github.com/filecoin-project/specs-actors/actors/builtin/init" + market0 "github.com/filecoin-project/specs-actors/actors/builtin/market" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" msig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig" - "github.com/filecoin-project/specs-actors/actors/builtin/paych" + paych0 "github.com/filecoin-project/specs-actors/actors/builtin/paych" + power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" reward0 "github.com/filecoin-project/specs-actors/actors/builtin/reward" verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" @@ -89,7 +88,8 @@ func GetPower(ctx context.Context, sm *StateManager, ts *types.TipSet, maddr add } func GetPowerRaw(ctx context.Context, sm *StateManager, st cid.Cid, maddr address.Address) (power.Claim, power.Claim, bool, error) { - act, err := sm.LoadActorRaw(ctx, builtin.StoragePowerActorAddr, st) + // TODO: ActorUpgrade + act, err := sm.LoadActorRaw(ctx, builtin0.StoragePowerActorAddr, st) if err != nil { return power.Claim{}, power.Claim{}, false, xerrors.Errorf("(get sset) failed to load power actor state: %w", err) } @@ -308,7 +308,8 @@ func StateMinerInfo(ctx context.Context, sm *StateManager, ts *types.TipSet, mad } func GetMinerSlashed(ctx context.Context, sm *StateManager, ts *types.TipSet, maddr address.Address) (bool, error) { - act, err := sm.LoadActor(ctx, builtin.StoragePowerActorAddr, ts) + // TODO: ActorUpgrade + act, err := sm.LoadActor(ctx, builtin0.StoragePowerActorAddr, ts) if err != nil { return false, xerrors.Errorf("failed to load power actor: %w", err) } @@ -331,7 +332,8 @@ func GetMinerSlashed(ctx context.Context, sm *StateManager, ts *types.TipSet, ma } func GetStorageDeal(ctx context.Context, sm *StateManager, dealID abi.DealID, ts *types.TipSet) (*api.MarketDeal, error) { - act, err := sm.LoadActor(ctx, builtin.StorageMarketActorAddr, ts) + // TODO: ActorUpgrade + act, err := sm.LoadActor(ctx, builtin0.StorageMarketActorAddr, ts) if err != nil { return nil, xerrors.Errorf("failed to load market actor: %w", err) } @@ -375,7 +377,8 @@ func GetStorageDeal(ctx context.Context, sm *StateManager, dealID abi.DealID, ts } func ListMinerActors(ctx context.Context, sm *StateManager, ts *types.TipSet) ([]address.Address, error) { - act, err := sm.LoadActor(ctx, builtin.StoragePowerActorAddr, ts) + // TODO: ActorUpgrade + act, err := sm.LoadActor(ctx, builtin0.StoragePowerActorAddr, ts) if err != nil { return nil, xerrors.Errorf("failed to load power actor: %w", err) } @@ -565,16 +568,16 @@ var MethodsMap = map[cid.Cid]map[abi.MethodNum]MethodMeta{} func init() { cidToMethods := map[cid.Cid][2]interface{}{ // builtin.SystemActorCodeID: {builtin.MethodsSystem, system.Actor{} }- apparently it doesn't have methods - builtin.InitActorCodeID: {builtin.MethodsInit, init0.Actor{}}, - builtin.CronActorCodeID: {builtin.MethodsCron, cron.Actor{}}, - builtin.AccountActorCodeID: {builtin.MethodsAccount, account.Actor{}}, - builtin.StoragePowerActorCodeID: {builtin.MethodsPower, power0.Actor{}}, - builtin.StorageMinerActorCodeID: {builtin.MethodsMiner, miner0.Actor{}}, - builtin.StorageMarketActorCodeID: {builtin.MethodsMarket, market0.Actor{}}, - builtin.PaymentChannelActorCodeID: {builtin.MethodsPaych, paych.Actor{}}, - builtin.MultisigActorCodeID: {builtin.MethodsMultisig, msig0.Actor{}}, - builtin.RewardActorCodeID: {builtin.MethodsReward, reward0.Actor{}}, - builtin.VerifiedRegistryActorCodeID: {builtin.MethodsVerifiedRegistry, verifreg0.Actor{}}, + builtin0.InitActorCodeID: {builtin0.MethodsInit, init0.Actor{}}, + builtin0.CronActorCodeID: {builtin0.MethodsCron, cron.Actor{}}, + builtin0.AccountActorCodeID: {builtin0.MethodsAccount, account0.Actor{}}, + builtin0.StoragePowerActorCodeID: {builtin0.MethodsPower, power0.Actor{}}, + builtin0.StorageMinerActorCodeID: {builtin0.MethodsMiner, miner0.Actor{}}, + builtin0.StorageMarketActorCodeID: {builtin0.MethodsMarket, market0.Actor{}}, + builtin0.PaymentChannelActorCodeID: {builtin0.MethodsPaych, paych0.Actor{}}, + builtin0.MultisigActorCodeID: {builtin0.MethodsMultisig, msig0.Actor{}}, + builtin0.RewardActorCodeID: {builtin0.MethodsReward, reward0.Actor{}}, + builtin0.VerifiedRegistryActorCodeID: {builtin0.MethodsVerifiedRegistry, verifreg0.Actor{}}, } for c, m := range cidToMethods { @@ -582,7 +585,7 @@ func init() { methods := make(map[abi.MethodNum]MethodMeta, len(exports)) // Explicitly add send, it's special. - methods[builtin.MethodSend] = MethodMeta{ + methods[builtin0.MethodSend] = MethodMeta{ Name: "Send", Params: reflect.TypeOf(new(abi.EmptyValue)), Ret: reflect.TypeOf(new(abi.EmptyValue)), @@ -622,9 +625,9 @@ func init() { } switch abi.MethodNum(number) { - case builtin.MethodSend: + case builtin0.MethodSend: panic("method 0 is reserved for Send") - case builtin.MethodConstructor: + case builtin0.MethodConstructor: if fnName != "Constructor" { panic("method 1 is reserved for Constructor") } @@ -654,7 +657,8 @@ func GetReturnType(ctx context.Context, sm *StateManager, to address.Address, me } func MinerHasMinPower(ctx context.Context, sm *StateManager, addr address.Address, ts *types.TipSet) (bool, error) { - pact, err := sm.LoadActor(ctx, builtin.StoragePowerActorAddr, ts) + // TODO: ActorUpgrade + pact, err := sm.LoadActor(ctx, builtin0.StoragePowerActorAddr, ts) if err != nil { return false, xerrors.Errorf("loading power actor state: %w", err) } From a307e4593a005888395db34e5af4691ee50d765d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Mon, 21 Sep 2020 09:52:57 +0200 Subject: [PATCH 122/303] wdpost: Fix TestWDPostDoPost --- storage/wdpost_run_test.go | 54 ++++++++++++++++++++++++++++---------- 1 file changed, 40 insertions(+), 14 deletions(-) diff --git a/storage/wdpost_run_test.go b/storage/wdpost_run_test.go index 58014d632..bd8e35d4f 100644 --- a/storage/wdpost_run_test.go +++ b/storage/wdpost_run_test.go @@ -5,18 +5,16 @@ import ( "context" "testing" - "github.com/filecoin-project/go-state-types/dline" - "github.com/stretchr/testify/require" + "github.com/ipfs/go-cid" + "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-bitfield" - "github.com/filecoin-project/lotus/api" - "github.com/filecoin-project/lotus/chain/types" - "github.com/ipfs/go-cid" - "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" + "github.com/filecoin-project/go-state-types/dline" "github.com/filecoin-project/go-state-types/network" "github.com/filecoin-project/specs-actors/actors/builtin" builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" @@ -24,7 +22,9 @@ import ( "github.com/filecoin-project/specs-actors/actors/runtime/proof" tutils "github.com/filecoin-project/specs-actors/support/testing" + "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + "github.com/filecoin-project/lotus/chain/types" ) type mockStorageMinerAPI struct { @@ -39,7 +39,10 @@ func newMockStorageMinerAPI() *mockStorageMinerAPI { } func (m *mockStorageMinerAPI) StateMinerInfo(ctx context.Context, a address.Address, key types.TipSetKey) (miner.MinerInfo, error) { - panic("implement me") + return miner.MinerInfo{ + Worker: tutils.NewIDAddr(nil, 101), + Owner: tutils.NewIDAddr(nil, 101), + }, nil } func (m *mockStorageMinerAPI) StateNetworkVersion(ctx context.Context, key types.TipSetKey) (network.Version, error) { @@ -167,7 +170,13 @@ func TestWDPostDoPost(t *testing.T) { worker: workerAct, } - di := &dline.Info{} + di := &dline.Info{ + WPoStPeriodDeadlines: miner0.WPoStPeriodDeadlines, + WPoStProvingPeriod: miner0.WPoStProvingPeriod, + WPoStChallengeWindow: miner0.WPoStChallengeWindow, + WPoStChallengeLookback: miner0.WPoStChallengeLookback, + FaultDeclarationCutoff: miner0.FaultDeclarationCutoff, + } ts := mockTipSet(t) scheduler.doPost(ctx, di, ts) @@ -232,7 +241,20 @@ func (m *mockStorageMinerAPI) StateSectorPartition(ctx context.Context, maddr ad } func (m *mockStorageMinerAPI) StateMinerProvingDeadline(ctx context.Context, address address.Address, key types.TipSetKey) (*dline.Info, error) { - panic("implement me") + return &dline.Info{ + CurrentEpoch: 0, + PeriodStart: 0, + Index: 0, + Open: 0, + Close: 0, + Challenge: 0, + FaultCutoff: 0, + WPoStPeriodDeadlines: miner0.WPoStPeriodDeadlines, + WPoStProvingPeriod: miner0.WPoStProvingPeriod, + WPoStChallengeWindow: miner0.WPoStChallengeWindow, + WPoStChallengeLookback: miner0.WPoStChallengeLookback, + FaultDeclarationCutoff: miner0.FaultDeclarationCutoff, + }, nil } func (m *mockStorageMinerAPI) StateMinerPreCommitDepositForPower(ctx context.Context, address address.Address, info miner.SectorPreCommitInfo, key types.TipSetKey) (types.BigInt, error) { @@ -270,11 +292,15 @@ func (m *mockStorageMinerAPI) StateMinerRecoveries(ctx context.Context, address } func (m *mockStorageMinerAPI) StateAccountKey(ctx context.Context, address address.Address, key types.TipSetKey) (address.Address, error) { - panic("implement me") + return address, nil } func (m *mockStorageMinerAPI) GasEstimateMessageGas(ctx context.Context, message *types.Message, spec *api.MessageSendSpec, key types.TipSetKey) (*types.Message, error) { - panic("implement me") + msg := *message + msg.GasFeeCap = big.NewInt(1) + msg.GasPremium = big.NewInt(1) + msg.GasLimit = 2 + return &msg, nil } func (m *mockStorageMinerAPI) ChainHead(ctx context.Context) (*types.TipSet, error) { @@ -306,15 +332,15 @@ func (m *mockStorageMinerAPI) ChainGetTipSet(ctx context.Context, key types.TipS } func (m *mockStorageMinerAPI) WalletSign(ctx context.Context, address address.Address, bytes []byte) (*crypto.Signature, error) { - panic("implement me") + return nil, nil } func (m *mockStorageMinerAPI) WalletBalance(ctx context.Context, address address.Address) (types.BigInt, error) { - panic("implement me") + return big.NewInt(333), nil } func (m *mockStorageMinerAPI) WalletHas(ctx context.Context, address address.Address) (bool, error) { - panic("implement me") + return true, nil } var _ storageMinerApi = &mockStorageMinerAPI{} From cfa041ca8ad7d54c1faf7e942ce70ef3e1313068 Mon Sep 17 00:00:00 2001 From: Alan Shaw Date: Mon, 14 Sep 2020 12:41:00 +0100 Subject: [PATCH 123/303] refactor: chaos caller validation --- conformance/chaos/actor.go | 34 +++++--- conformance/chaos/cbor_gen.go | 159 ++++++++++++++++++++++++++++++++++ conformance/chaos/gen/gen.go | 1 + 3 files changed, 181 insertions(+), 13 deletions(-) diff --git a/conformance/chaos/actor.go b/conformance/chaos/actor.go index 005a06f0d..bc68b086f 100644 --- a/conformance/chaos/actor.go +++ b/conformance/chaos/actor.go @@ -7,8 +7,6 @@ import ( "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/runtime" "github.com/ipfs/go-cid" - - typegen "github.com/whyrusleeping/cbor-gen" ) //go:generate go run ./gen @@ -31,10 +29,14 @@ type Actor struct{} type CallerValidationBranch int64 const ( + // CallerValidationBranchNone causes no caller validation to take place. CallerValidationBranchNone CallerValidationBranch = iota + // CallerValidationBranchTwice causes Runtime.ValidateImmediateCallerAcceptAny to be called twice. CallerValidationBranchTwice - CallerValidationBranchAddrNilSet - CallerValidationBranchTypeNilSet + // CallerValidationBranchIs causes caller validation against CallerValidationArgs.Addrs. + CallerValidationBranchIs + // CallerValidationBranchType causes caller validation against CallerValidationArgs.Types. + CallerValidationBranchType ) // MutateStateBranch is an enum used to select the type of state mutation to attempt. @@ -123,23 +125,29 @@ func (a Actor) Constructor(_ runtime.Runtime, _ *abi.EmptyValue) *abi.EmptyValue panic("constructor should not be called; the Chaos actor is a singleton actor") } +// CallerValidationArgs are the arguments to Actor.CallerValidation. +type CallerValidationArgs struct { + Branch CallerValidationBranch + Addrs []address.Address + Types []cid.Cid +} + // CallerValidation violates VM call validation constraints. // // CallerValidationBranchNone performs no validation. // CallerValidationBranchTwice validates twice. -// CallerValidationBranchAddrNilSet validates against an empty caller -// address set. -// CallerValidationBranchTypeNilSet validates against an empty caller type set. -func (a Actor) CallerValidation(rt runtime.Runtime, branch *typegen.CborInt) *abi.EmptyValue { - switch CallerValidationBranch(*branch) { +// CallerValidationBranchIs validates caller against CallerValidationArgs.Addrs. +// CallerValidationBranchType validates caller against CallerValidationArgs.Types. +func (a Actor) CallerValidation(rt runtime.Runtime, args *CallerValidationArgs) *abi.EmptyValue { + switch args.Branch { case CallerValidationBranchNone: case CallerValidationBranchTwice: rt.ValidateImmediateCallerAcceptAny() rt.ValidateImmediateCallerAcceptAny() - case CallerValidationBranchAddrNilSet: - rt.ValidateImmediateCallerIs() - case CallerValidationBranchTypeNilSet: - rt.ValidateImmediateCallerType() + case CallerValidationBranchIs: + rt.ValidateImmediateCallerIs(args.Addrs...) + case CallerValidationBranchType: + rt.ValidateImmediateCallerType(args.Types...) default: panic("invalid branch passed to CallerValidation") } diff --git a/conformance/chaos/cbor_gen.go b/conformance/chaos/cbor_gen.go index 61e36e661..882af7026 100644 --- a/conformance/chaos/cbor_gen.go +++ b/conformance/chaos/cbor_gen.go @@ -6,8 +6,10 @@ import ( "fmt" "io" + address "github.com/filecoin-project/go-address" abi "github.com/filecoin-project/go-state-types/abi" exitcode "github.com/filecoin-project/go-state-types/exitcode" + cid "github.com/ipfs/go-cid" cbg "github.com/whyrusleeping/cbor-gen" xerrors "golang.org/x/xerrors" ) @@ -115,6 +117,163 @@ func (t *State) UnmarshalCBOR(r io.Reader) error { return nil } +var lengthBufCallerValidationArgs = []byte{131} + +func (t *CallerValidationArgs) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + if _, err := w.Write(lengthBufCallerValidationArgs); err != nil { + return err + } + + scratch := make([]byte, 9) + + // t.Branch (chaos.CallerValidationBranch) (int64) + if t.Branch >= 0 { + if err := cbg.WriteMajorTypeHeaderBuf(scratch, w, cbg.MajUnsignedInt, uint64(t.Branch)); err != nil { + return err + } + } else { + if err := cbg.WriteMajorTypeHeaderBuf(scratch, w, cbg.MajNegativeInt, uint64(-t.Branch-1)); err != nil { + return err + } + } + + // t.Addrs ([]address.Address) (slice) + if len(t.Addrs) > cbg.MaxLength { + return xerrors.Errorf("Slice value in field t.Addrs was too long") + } + + if err := cbg.WriteMajorTypeHeaderBuf(scratch, w, cbg.MajArray, uint64(len(t.Addrs))); err != nil { + return err + } + for _, v := range t.Addrs { + if err := v.MarshalCBOR(w); err != nil { + return err + } + } + + // t.Types ([]cid.Cid) (slice) + if len(t.Types) > cbg.MaxLength { + return xerrors.Errorf("Slice value in field t.Types was too long") + } + + if err := cbg.WriteMajorTypeHeaderBuf(scratch, w, cbg.MajArray, uint64(len(t.Types))); err != nil { + return err + } + for _, v := range t.Types { + if err := cbg.WriteCidBuf(scratch, w, v); err != nil { + return xerrors.Errorf("failed writing cid field t.Types: %w", err) + } + } + return nil +} + +func (t *CallerValidationArgs) UnmarshalCBOR(r io.Reader) error { + *t = CallerValidationArgs{} + + br := cbg.GetPeeker(r) + scratch := make([]byte, 8) + + maj, extra, err := cbg.CborReadHeaderBuf(br, scratch) + if err != nil { + return err + } + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 3 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Branch (chaos.CallerValidationBranch) (int64) + { + maj, extra, err := cbg.CborReadHeaderBuf(br, scratch) + var extraI int64 + if err != nil { + return err + } + switch maj { + case cbg.MajUnsignedInt: + extraI = int64(extra) + if extraI < 0 { + return fmt.Errorf("int64 positive overflow") + } + case cbg.MajNegativeInt: + extraI = int64(extra) + if extraI < 0 { + return fmt.Errorf("int64 negative oveflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.Branch = CallerValidationBranch(extraI) + } + // t.Addrs ([]address.Address) (slice) + + maj, extra, err = cbg.CborReadHeaderBuf(br, scratch) + if err != nil { + return err + } + + if extra > cbg.MaxLength { + return fmt.Errorf("t.Addrs: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Addrs = make([]address.Address, extra) + } + + for i := 0; i < int(extra); i++ { + + var v address.Address + if err := v.UnmarshalCBOR(br); err != nil { + return err + } + + t.Addrs[i] = v + } + + // t.Types ([]cid.Cid) (slice) + + maj, extra, err = cbg.CborReadHeaderBuf(br, scratch) + if err != nil { + return err + } + + if extra > cbg.MaxLength { + return fmt.Errorf("t.Types: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Types = make([]cid.Cid, extra) + } + + for i := 0; i < int(extra); i++ { + + c, err := cbg.ReadCid(br) + if err != nil { + return xerrors.Errorf("reading cid field t.Types failed: %w", err) + } + t.Types[i] = c + } + + return nil +} + var lengthBufCreateActorArgs = []byte{132} func (t *CreateActorArgs) MarshalCBOR(w io.Writer) error { diff --git a/conformance/chaos/gen/gen.go b/conformance/chaos/gen/gen.go index ea04aee21..ac97da99e 100644 --- a/conformance/chaos/gen/gen.go +++ b/conformance/chaos/gen/gen.go @@ -9,6 +9,7 @@ import ( func main() { if err := gen.WriteTupleEncodersToFile("./cbor_gen.go", "chaos", chaos.State{}, + chaos.CallerValidationArgs{}, chaos.CreateActorArgs{}, chaos.ResolveAddressResponse{}, chaos.SendArgs{}, From ab53abf04eaee92973daade2d0f55a44b2ca972a Mon Sep 17 00:00:00 2001 From: Alan Shaw Date: Tue, 15 Sep 2020 14:00:33 +0100 Subject: [PATCH 124/303] feat: add CallerValidationBranchIsReceiver and tests --- conformance/chaos/actor.go | 4 ++ conformance/chaos/actor_test.go | 119 ++++++++++++++++++++++++++++++++ 2 files changed, 123 insertions(+) diff --git a/conformance/chaos/actor.go b/conformance/chaos/actor.go index bc68b086f..c56abcb8b 100644 --- a/conformance/chaos/actor.go +++ b/conformance/chaos/actor.go @@ -35,6 +35,8 @@ const ( CallerValidationBranchTwice // CallerValidationBranchIs causes caller validation against CallerValidationArgs.Addrs. CallerValidationBranchIs + // CallerValidationBranchIsReceiver causes validation that the caller was also the receiver. + CallerValidationBranchIsReceiver // CallerValidationBranchType causes caller validation against CallerValidationArgs.Types. CallerValidationBranchType ) @@ -146,6 +148,8 @@ func (a Actor) CallerValidation(rt runtime.Runtime, args *CallerValidationArgs) rt.ValidateImmediateCallerAcceptAny() case CallerValidationBranchIs: rt.ValidateImmediateCallerIs(args.Addrs...) + case CallerValidationBranchIsReceiver: + rt.ValidateImmediateCallerIs(rt.Message().Receiver()) case CallerValidationBranchType: rt.ValidateImmediateCallerType(args.Types...) default: diff --git a/conformance/chaos/actor_test.go b/conformance/chaos/actor_test.go index 2e899980d..c9d804309 100644 --- a/conformance/chaos/actor_test.go +++ b/conformance/chaos/actor_test.go @@ -2,6 +2,9 @@ package chaos import ( "context" + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/specs-actors/actors/builtin" + "github.com/ipfs/go-cid" "testing" "github.com/filecoin-project/go-state-types/abi" @@ -25,6 +28,108 @@ func TestSingleton(t *testing.T) { rt.Verify() } +func TestCallerValidationNone(t *testing.T) { + receiver := atesting.NewIDAddr(t, 100) + builder := mock.NewBuilder(context.Background(), receiver) + + rt := builder.Build(t) + var a Actor + + rt.Call(a.CallerValidation, &CallerValidationArgs{Branch: CallerValidationBranchNone}) + rt.Verify() +} + +func TestCallerValidationIs(t *testing.T) { + caller := atesting.NewIDAddr(t, 100) + receiver := atesting.NewIDAddr(t, 101) + builder := mock.NewBuilder(context.Background(), receiver) + + rt := builder.Build(t) + rt.SetCaller(caller, builtin.AccountActorCodeID) + var a Actor + + caddrs := []address.Address{atesting.NewIDAddr(t, 101)} + + rt.ExpectValidateCallerAddr(caddrs...) + // FIXME: https://github.com/filecoin-project/specs-actors/pull/1155 + rt.ExpectAbort(exitcode.ErrForbidden, func() { + rt.Call(a.CallerValidation, &CallerValidationArgs{ + Branch: CallerValidationBranchIs, + Addrs: caddrs, + }) + }) + rt.Verify() + + rt.ExpectValidateCallerAddr(caller) + rt.Call(a.CallerValidation, &CallerValidationArgs{ + Branch: CallerValidationBranchIs, + Addrs: []address.Address{caller}, + }) + rt.Verify() +} + +func TestCallerValidationIsReceiver(t *testing.T) { + caller := atesting.NewIDAddr(t, 100) + receiver := atesting.NewIDAddr(t, 101) + builder := mock.NewBuilder(context.Background(), receiver) + + rt := builder.Build(t) + var a Actor + + rt.SetCaller(caller, builtin.AccountActorCodeID) + rt.ExpectValidateCallerAddr(receiver) + // FIXME: https://github.com/filecoin-project/specs-actors/pull/1155 + rt.ExpectAbort(exitcode.ErrForbidden, func() { + rt.Call(a.CallerValidation, &CallerValidationArgs{Branch: CallerValidationBranchIsReceiver}) + }) + rt.Verify() + + rt.SetCaller(receiver, builtin.AccountActorCodeID) + rt.ExpectValidateCallerAddr(receiver) + rt.Call(a.CallerValidation, &CallerValidationArgs{Branch: CallerValidationBranchIsReceiver}) + rt.Verify() +} + +func TestCallerValidationType(t *testing.T) { + caller := atesting.NewIDAddr(t, 100) + receiver := atesting.NewIDAddr(t, 101) + builder := mock.NewBuilder(context.Background(), receiver) + + rt := builder.Build(t) + rt.SetCaller(caller, builtin.AccountActorCodeID) + var a Actor + + rt.ExpectValidateCallerType(builtin.CronActorCodeID) + // FIXME: https://github.com/filecoin-project/specs-actors/pull/1155 + rt.ExpectAbort(exitcode.ErrForbidden, func() { + rt.Call(a.CallerValidation, &CallerValidationArgs{ + Branch: CallerValidationBranchType, + Types: []cid.Cid{builtin.CronActorCodeID}, + }) + }) + rt.Verify() + + rt.ExpectValidateCallerType(builtin.AccountActorCodeID) + rt.Call(a.CallerValidation, &CallerValidationArgs{ + Branch: CallerValidationBranchType, + Types: []cid.Cid{builtin.AccountActorCodeID}, + }) + rt.Verify() +} + +func TestCallerValidationInvalidBranch(t *testing.T) { + receiver := atesting.NewIDAddr(t, 100) + builder := mock.NewBuilder(context.Background(), receiver) + + rt := builder.Build(t) + var a Actor + + rt.ExpectAssertionFailure("invalid branch passed to CallerValidation", func() { + rt.Call(a.CallerValidation, &CallerValidationArgs{Branch: -1}) + }) + rt.Verify() +} + func TestDeleteActor(t *testing.T) { receiver := atesting.NewIDAddr(t, 100) beneficiary := atesting.NewIDAddr(t, 101) @@ -118,6 +223,20 @@ func TestMutateStateReadonly(t *testing.T) { rt.Verify() } +func TestMutateStateInvalidBranch(t *testing.T) { + receiver := atesting.NewIDAddr(t, 100) + builder := mock.NewBuilder(context.Background(), receiver) + + rt := builder.Build(t) + var a Actor + + rt.ExpectValidateCallerAny() + rt.ExpectAssertionFailure("unknown mutation type", func() { + rt.Call(a.MutateState, &MutateStateArgs{Branch: -1}) + }) + rt.Verify() +} + func TestAbortWith(t *testing.T) { receiver := atesting.NewIDAddr(t, 100) builder := mock.NewBuilder(context.Background(), receiver) From 49a94b7cbab9b2acef1fa1765035f4c8a5ce9002 Mon Sep 17 00:00:00 2001 From: Alan Shaw Date: Tue, 15 Sep 2020 14:10:20 +0100 Subject: [PATCH 125/303] chore: appease linter --- conformance/chaos/actor_test.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/conformance/chaos/actor_test.go b/conformance/chaos/actor_test.go index c9d804309..675c617ab 100644 --- a/conformance/chaos/actor_test.go +++ b/conformance/chaos/actor_test.go @@ -2,16 +2,15 @@ package chaos import ( "context" - "github.com/filecoin-project/go-address" - "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/ipfs/go-cid" "testing" + "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/exitcode" "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/support/mock" atesting "github.com/filecoin-project/specs-actors/support/testing" + "github.com/ipfs/go-cid" ) func TestSingleton(t *testing.T) { From d607ca6118a9d859b99da43e1ba74251faf0d498 Mon Sep 17 00:00:00 2001 From: Alan Shaw Date: Tue, 15 Sep 2020 14:56:58 +0100 Subject: [PATCH 126/303] refactor: remove IsReceiver branch --- conformance/chaos/actor.go | 4 ---- conformance/chaos/actor_test.go | 22 ---------------------- 2 files changed, 26 deletions(-) diff --git a/conformance/chaos/actor.go b/conformance/chaos/actor.go index c56abcb8b..bc68b086f 100644 --- a/conformance/chaos/actor.go +++ b/conformance/chaos/actor.go @@ -35,8 +35,6 @@ const ( CallerValidationBranchTwice // CallerValidationBranchIs causes caller validation against CallerValidationArgs.Addrs. CallerValidationBranchIs - // CallerValidationBranchIsReceiver causes validation that the caller was also the receiver. - CallerValidationBranchIsReceiver // CallerValidationBranchType causes caller validation against CallerValidationArgs.Types. CallerValidationBranchType ) @@ -148,8 +146,6 @@ func (a Actor) CallerValidation(rt runtime.Runtime, args *CallerValidationArgs) rt.ValidateImmediateCallerAcceptAny() case CallerValidationBranchIs: rt.ValidateImmediateCallerIs(args.Addrs...) - case CallerValidationBranchIsReceiver: - rt.ValidateImmediateCallerIs(rt.Message().Receiver()) case CallerValidationBranchType: rt.ValidateImmediateCallerType(args.Types...) default: diff --git a/conformance/chaos/actor_test.go b/conformance/chaos/actor_test.go index 675c617ab..a6345da53 100644 --- a/conformance/chaos/actor_test.go +++ b/conformance/chaos/actor_test.go @@ -67,28 +67,6 @@ func TestCallerValidationIs(t *testing.T) { rt.Verify() } -func TestCallerValidationIsReceiver(t *testing.T) { - caller := atesting.NewIDAddr(t, 100) - receiver := atesting.NewIDAddr(t, 101) - builder := mock.NewBuilder(context.Background(), receiver) - - rt := builder.Build(t) - var a Actor - - rt.SetCaller(caller, builtin.AccountActorCodeID) - rt.ExpectValidateCallerAddr(receiver) - // FIXME: https://github.com/filecoin-project/specs-actors/pull/1155 - rt.ExpectAbort(exitcode.ErrForbidden, func() { - rt.Call(a.CallerValidation, &CallerValidationArgs{Branch: CallerValidationBranchIsReceiver}) - }) - rt.Verify() - - rt.SetCaller(receiver, builtin.AccountActorCodeID) - rt.ExpectValidateCallerAddr(receiver) - rt.Call(a.CallerValidation, &CallerValidationArgs{Branch: CallerValidationBranchIsReceiver}) - rt.Verify() -} - func TestCallerValidationType(t *testing.T) { caller := atesting.NewIDAddr(t, 100) receiver := atesting.NewIDAddr(t, 101) From dfaad08a8b57b08b3bbde9ef633dec97bb497ce7 Mon Sep 17 00:00:00 2001 From: Alan Shaw Date: Tue, 15 Sep 2020 15:03:57 +0100 Subject: [PATCH 127/303] fix: update cbor gen file --- conformance/chaos/cbor_gen.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/conformance/chaos/cbor_gen.go b/conformance/chaos/cbor_gen.go index 882af7026..0d34264ee 100644 --- a/conformance/chaos/cbor_gen.go +++ b/conformance/chaos/cbor_gen.go @@ -6,12 +6,12 @@ import ( "fmt" "io" - address "github.com/filecoin-project/go-address" - abi "github.com/filecoin-project/go-state-types/abi" - exitcode "github.com/filecoin-project/go-state-types/exitcode" - cid "github.com/ipfs/go-cid" + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/exitcode" + "github.com/ipfs/go-cid" cbg "github.com/whyrusleeping/cbor-gen" - xerrors "golang.org/x/xerrors" + "golang.org/x/xerrors" ) var _ = xerrors.Errorf From c1a9cf7edd9a8d089e97fccc70e97b73dffc93de Mon Sep 17 00:00:00 2001 From: Alan Shaw Date: Tue, 15 Sep 2020 15:47:11 +0100 Subject: [PATCH 128/303] refactor: renames --- conformance/chaos/actor.go | 16 ++++++++-------- conformance/chaos/actor_test.go | 8 ++++---- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/conformance/chaos/actor.go b/conformance/chaos/actor.go index bc68b086f..477204374 100644 --- a/conformance/chaos/actor.go +++ b/conformance/chaos/actor.go @@ -33,10 +33,10 @@ const ( CallerValidationBranchNone CallerValidationBranch = iota // CallerValidationBranchTwice causes Runtime.ValidateImmediateCallerAcceptAny to be called twice. CallerValidationBranchTwice - // CallerValidationBranchIs causes caller validation against CallerValidationArgs.Addrs. - CallerValidationBranchIs - // CallerValidationBranchType causes caller validation against CallerValidationArgs.Types. - CallerValidationBranchType + // CallerValidationBranchIsAddress causes caller validation against CallerValidationArgs.Addrs. + CallerValidationBranchIsAddress + // CallerValidationBranchIsType causes caller validation against CallerValidationArgs.Types. + CallerValidationBranchIsType ) // MutateStateBranch is an enum used to select the type of state mutation to attempt. @@ -136,17 +136,17 @@ type CallerValidationArgs struct { // // CallerValidationBranchNone performs no validation. // CallerValidationBranchTwice validates twice. -// CallerValidationBranchIs validates caller against CallerValidationArgs.Addrs. -// CallerValidationBranchType validates caller against CallerValidationArgs.Types. +// CallerValidationBranchIsAddress validates caller against CallerValidationArgs.Addrs. +// CallerValidationBranchIsType validates caller against CallerValidationArgs.Types. func (a Actor) CallerValidation(rt runtime.Runtime, args *CallerValidationArgs) *abi.EmptyValue { switch args.Branch { case CallerValidationBranchNone: case CallerValidationBranchTwice: rt.ValidateImmediateCallerAcceptAny() rt.ValidateImmediateCallerAcceptAny() - case CallerValidationBranchIs: + case CallerValidationBranchIsAddress: rt.ValidateImmediateCallerIs(args.Addrs...) - case CallerValidationBranchType: + case CallerValidationBranchIsType: rt.ValidateImmediateCallerType(args.Types...) default: panic("invalid branch passed to CallerValidation") diff --git a/conformance/chaos/actor_test.go b/conformance/chaos/actor_test.go index a6345da53..2061efb82 100644 --- a/conformance/chaos/actor_test.go +++ b/conformance/chaos/actor_test.go @@ -53,7 +53,7 @@ func TestCallerValidationIs(t *testing.T) { // FIXME: https://github.com/filecoin-project/specs-actors/pull/1155 rt.ExpectAbort(exitcode.ErrForbidden, func() { rt.Call(a.CallerValidation, &CallerValidationArgs{ - Branch: CallerValidationBranchIs, + Branch: CallerValidationBranchIsAddress, Addrs: caddrs, }) }) @@ -61,7 +61,7 @@ func TestCallerValidationIs(t *testing.T) { rt.ExpectValidateCallerAddr(caller) rt.Call(a.CallerValidation, &CallerValidationArgs{ - Branch: CallerValidationBranchIs, + Branch: CallerValidationBranchIsAddress, Addrs: []address.Address{caller}, }) rt.Verify() @@ -80,7 +80,7 @@ func TestCallerValidationType(t *testing.T) { // FIXME: https://github.com/filecoin-project/specs-actors/pull/1155 rt.ExpectAbort(exitcode.ErrForbidden, func() { rt.Call(a.CallerValidation, &CallerValidationArgs{ - Branch: CallerValidationBranchType, + Branch: CallerValidationBranchIsType, Types: []cid.Cid{builtin.CronActorCodeID}, }) }) @@ -88,7 +88,7 @@ func TestCallerValidationType(t *testing.T) { rt.ExpectValidateCallerType(builtin.AccountActorCodeID) rt.Call(a.CallerValidation, &CallerValidationArgs{ - Branch: CallerValidationBranchType, + Branch: CallerValidationBranchIsType, Types: []cid.Cid{builtin.AccountActorCodeID}, }) rt.Verify() From d9951cdff402b400015b5213097c8db67049f8b2 Mon Sep 17 00:00:00 2001 From: Alan Shaw Date: Mon, 21 Sep 2020 10:10:31 +0100 Subject: [PATCH 129/303] fix: regen --- conformance/chaos/cbor_gen.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/conformance/chaos/cbor_gen.go b/conformance/chaos/cbor_gen.go index 0d34264ee..882af7026 100644 --- a/conformance/chaos/cbor_gen.go +++ b/conformance/chaos/cbor_gen.go @@ -6,12 +6,12 @@ import ( "fmt" "io" - "github.com/filecoin-project/go-address" - "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/go-state-types/exitcode" - "github.com/ipfs/go-cid" + address "github.com/filecoin-project/go-address" + abi "github.com/filecoin-project/go-state-types/abi" + exitcode "github.com/filecoin-project/go-state-types/exitcode" + cid "github.com/ipfs/go-cid" cbg "github.com/whyrusleeping/cbor-gen" - "golang.org/x/xerrors" + xerrors "golang.org/x/xerrors" ) var _ = xerrors.Errorf From a79291070e216309e81aa929b0409bece4bf1820 Mon Sep 17 00:00:00 2001 From: Alan Shaw Date: Mon, 21 Sep 2020 11:53:38 +0100 Subject: [PATCH 130/303] chore: update test-vectors --- extern/test-vectors | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extern/test-vectors b/extern/test-vectors index 7d3becbeb..9db1dd8c9 160000 --- a/extern/test-vectors +++ b/extern/test-vectors @@ -1 +1 @@ -Subproject commit 7d3becbeb5b932baed419c43390595b5e5cece12 +Subproject commit 9db1dd8c9f85bd80eb624e77130a02a3aaf3a1f9 From d9f2b909ac5127589f7e385df5897d7bcd476da6 Mon Sep 17 00:00:00 2001 From: Alan Shaw Date: Mon, 21 Sep 2020 11:58:45 +0100 Subject: [PATCH 131/303] chore: update test-vectors --- extern/test-vectors | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extern/test-vectors b/extern/test-vectors index 9db1dd8c9..6bea015ed 160000 --- a/extern/test-vectors +++ b/extern/test-vectors @@ -1 +1 @@ -Subproject commit 9db1dd8c9f85bd80eb624e77130a02a3aaf3a1f9 +Subproject commit 6bea015edddde116001a4251dce3c4a9966c25d9 From 58a85f378cc00301014bf67b6445a8df5c54e295 Mon Sep 17 00:00:00 2001 From: vyzo Date: Mon, 21 Sep 2020 18:33:31 +0300 Subject: [PATCH 132/303] refactor response compressed index validation into its own function --- chain/exchange/client.go | 64 ++++++++++++++++++++++++---------------- 1 file changed, 39 insertions(+), 25 deletions(-) diff --git a/chain/exchange/client.go b/chain/exchange/client.go index 57563d5b2..20a130c1d 100644 --- a/chain/exchange/client.go +++ b/chain/exchange/client.go @@ -210,31 +210,9 @@ func (c *client) processResponse(req *Request, res *Response) (*validatedRespons // If the headers were also returned check that the compression // indexes are valid before `toFullTipSets()` is called by the // consumer. - for tipsetIdx := 0; tipsetIdx < resLength; tipsetIdx++ { - msgs := res.Chain[tipsetIdx].Messages - blocksNum := len(res.Chain[tipsetIdx].Blocks) - if len(msgs.BlsIncludes) != blocksNum { - return nil, xerrors.Errorf("BlsIncludes (%d) does not match number of blocks (%d)", - len(msgs.BlsIncludes), blocksNum) - } - if len(msgs.SecpkIncludes) != blocksNum { - return nil, xerrors.Errorf("SecpkIncludes (%d) does not match number of blocks (%d)", - len(msgs.SecpkIncludes), blocksNum) - } - for blockIdx := 0; blockIdx < blocksNum; blockIdx++ { - for _, mi := range msgs.BlsIncludes[blockIdx] { - if int(mi) >= len(msgs.Bls) { - return nil, xerrors.Errorf("index in BlsIncludes (%d) exceeds number of messages (%d)", - mi, len(msgs.Bls)) - } - } - for _, mi := range msgs.SecpkIncludes[blockIdx] { - if int(mi) >= len(msgs.Secpk) { - return nil, xerrors.Errorf("index in SecpkIncludes (%d) exceeds number of messages (%d)", - mi, len(msgs.Secpk)) - } - } - } + err := c.validateCompressedIndices(res.Chain) + if err != nil { + return nil, err } } } @@ -242,6 +220,42 @@ func (c *client) processResponse(req *Request, res *Response) (*validatedRespons return validRes, nil } +func (c *client) validateCompressedIndices(chain []*BSTipSet) error { + resLength := len(chain) + for tipsetIdx := 0; tipsetIdx < resLength; tipsetIdx++ { + msgs := chain[tipsetIdx].Messages + blocksNum := len(chain[tipsetIdx].Blocks) + + if len(msgs.BlsIncludes) != blocksNum { + return xerrors.Errorf("BlsIncludes (%d) does not match number of blocks (%d)", + len(msgs.BlsIncludes), blocksNum) + } + + if len(msgs.SecpkIncludes) != blocksNum { + return xerrors.Errorf("SecpkIncludes (%d) does not match number of blocks (%d)", + len(msgs.SecpkIncludes), blocksNum) + } + + for blockIdx := 0; blockIdx < blocksNum; blockIdx++ { + for _, mi := range msgs.BlsIncludes[blockIdx] { + if int(mi) >= len(msgs.Bls) { + return xerrors.Errorf("index in BlsIncludes (%d) exceeds number of messages (%d)", + mi, len(msgs.Bls)) + } + } + + for _, mi := range msgs.SecpkIncludes[blockIdx] { + if int(mi) >= len(msgs.Secpk) { + return xerrors.Errorf("index in SecpkIncludes (%d) exceeds number of messages (%d)", + mi, len(msgs.Secpk)) + } + } + } + } + + return nil +} + // GetBlocks implements Client.GetBlocks(). Refer to the godocs there. func (c *client) GetBlocks(ctx context.Context, tsk types.TipSetKey, count int) ([]*types.TipSet, error) { ctx, span := trace.StartSpan(ctx, "bsync.GetBlocks") From 44b52941f7a2af1c3cd69fd1324ce7454f48eb32 Mon Sep 17 00:00:00 2001 From: vyzo Date: Mon, 21 Sep 2020 18:50:41 +0300 Subject: [PATCH 133/303] add option to validate messages against expected tipset --- chain/exchange/client.go | 16 ++++++++++++++++ chain/exchange/protocol.go | 13 +++++++++---- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/chain/exchange/client.go b/chain/exchange/client.go index 20a130c1d..fcdcd544a 100644 --- a/chain/exchange/client.go +++ b/chain/exchange/client.go @@ -215,6 +215,22 @@ func (c *client) processResponse(req *Request, res *Response) (*validatedRespons return nil, err } } + + if options.ValidateMessages { + chain := make([]*BSTipSet, 0, resLength) + for i, resChain := range res.Chain { + next := &BSTipSet{ + Blocks: req.TipSets[i].Blocks(), + Messages: resChain.Messages, + } + chain = append(chain, next) + } + + err := c.validateCompressedIndices(chain) + if err != nil { + return nil, err + } + } } return validRes, nil diff --git a/chain/exchange/protocol.go b/chain/exchange/protocol.go index ac02cf60f..b1fe69bd2 100644 --- a/chain/exchange/protocol.go +++ b/chain/exchange/protocol.go @@ -57,6 +57,8 @@ type Request struct { // Request options, see `Options` type for more details. Compressed // in a single `uint64` to save space. Options uint64 + // Request tipsets for validation + TipSets []*types.TipSet } // `Request` processed and validated to query the tipsets needed. @@ -71,13 +73,15 @@ type validatedRequest struct { const ( Headers = 1 << iota Messages + Validate ) // Decompressed options into separate struct members for easy access // during internal processing.. type parsedOptions struct { - IncludeHeaders bool - IncludeMessages bool + IncludeHeaders bool + IncludeMessages bool + ValidateMessages bool } func (options *parsedOptions) noOptionsSet() bool { @@ -87,8 +91,9 @@ func (options *parsedOptions) noOptionsSet() bool { func parseOptions(optfield uint64) *parsedOptions { return &parsedOptions{ - IncludeHeaders: optfield&(uint64(Headers)) != 0, - IncludeMessages: optfield&(uint64(Messages)) != 0, + IncludeHeaders: optfield&(uint64(Headers)) != 0, + IncludeMessages: optfield&(uint64(Messages)) != 0, + ValidateMessages: optfield&(uint64(Validate)) != 0, } } From 5663b2d697c4bc809373f759e9a978b74b6846ab Mon Sep 17 00:00:00 2001 From: vyzo Date: Mon, 21 Sep 2020 18:58:52 +0300 Subject: [PATCH 134/303] change GetChainMessages api to include tipsets for validation --- chain/exchange/client.go | 9 +++++++-- chain/exchange/interfaces.go | 7 +++---- chain/sync.go | 4 ++-- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/chain/exchange/client.go b/chain/exchange/client.go index fcdcd544a..a99362745 100644 --- a/chain/exchange/client.go +++ b/chain/exchange/client.go @@ -217,6 +217,7 @@ func (c *client) processResponse(req *Request, res *Response) (*validatedRespons } if options.ValidateMessages { + // if the request includes target tipsets, validate against them chain := make([]*BSTipSet, 0, resLength) for i, resChain := range res.Chain { next := &BSTipSet{ @@ -318,7 +319,10 @@ func (c *client) GetFullTipSet(ctx context.Context, peer peer.ID, tsk types.TipS } // GetChainMessages implements Client.GetChainMessages(). Refer to the godocs there. -func (c *client) GetChainMessages(ctx context.Context, head *types.TipSet, length uint64) ([]*CompactedMessages, error) { +func (c *client) GetChainMessages(ctx context.Context, tipsets []*types.TipSet) ([]*CompactedMessages, error) { + head := tipsets[0] + length := uint64(len(tipsets)) + ctx, span := trace.StartSpan(ctx, "GetChainMessages") if span.IsRecordingEvents() { span.AddAttributes( @@ -331,7 +335,8 @@ func (c *client) GetChainMessages(ctx context.Context, head *types.TipSet, lengt req := &Request{ Head: head.Cids(), Length: length, - Options: Messages, + Options: Messages | Validate, + TipSets: tipsets, } validRes, err := c.doRequest(ctx, req, nil) diff --git a/chain/exchange/interfaces.go b/chain/exchange/interfaces.go index 79d8fd4b1..acc0854da 100644 --- a/chain/exchange/interfaces.go +++ b/chain/exchange/interfaces.go @@ -32,10 +32,9 @@ type Client interface { // or less. GetBlocks(ctx context.Context, tsk types.TipSetKey, count int) ([]*types.TipSet, error) - // GetChainMessages fetches messages from the network, from the provided - // tipset *backwards*, returning the messages from as many tipsets as the - // count parameter, or less. - GetChainMessages(ctx context.Context, head *types.TipSet, length uint64) ([]*CompactedMessages, error) + // GetChainMessages fetches messages from the network, starting from the first provided tipset + // and returning messages from as many tipsets as requested or less. + GetChainMessages(ctx context.Context, tipsets []*types.TipSet) ([]*CompactedMessages, error) // GetFullTipSet fetches a full tipset from a given peer. If successful, // the fetched object contains block headers and all messages in full form. diff --git a/chain/sync.go b/chain/sync.go index 74dc5aa1a..b47365b4b 100644 --- a/chain/sync.go +++ b/chain/sync.go @@ -1555,7 +1555,7 @@ func (syncer *Syncer) fetchMessages(ctx context.Context, headers []*types.TipSet failed := false for offset := 0; !failed && offset < nreq; { nextI := j + offset - nextHeader := headers[nextI] + lastI := j + nreq var requestErr error var requestResult []*exchange.CompactedMessages @@ -1566,7 +1566,7 @@ func (syncer *Syncer) fetchMessages(ctx context.Context, headers []*types.TipSet log.Infof("fetching messages at %d", startOffset+nextI) } - result, err := syncer.Exchange.GetChainMessages(ctx, nextHeader, uint64(nreq-offset)) + result, err := syncer.Exchange.GetChainMessages(ctx, headers[nextI:lastI]) if err != nil { requestErr = multierror.Append(requestErr, err) } else { From 0b5e4a961245f09634d9db750f928249b60ff3a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Mon, 21 Sep 2020 18:28:32 +0200 Subject: [PATCH 135/303] Make GetSectorsForWinningPoSt fast again --- chain/actors/adt/adt.go | 17 ++++++ chain/actors/builtin/miner/miner.go | 4 +- chain/actors/builtin/miner/v0.go | 83 +++++++++++++++-------------- 3 files changed, 61 insertions(+), 43 deletions(-) diff --git a/chain/actors/adt/adt.go b/chain/actors/adt/adt.go index fd5ee3f87..81c2e3a86 100644 --- a/chain/actors/adt/adt.go +++ b/chain/actors/adt/adt.go @@ -55,3 +55,20 @@ func AsArray(store Store, root cid.Cid, version network.Version) (Array, error) } return nil, xerrors.Errorf("unknown network version: %d", version) } + +type ROnlyArray interface { + Get(idx uint64, v cbor.Unmarshaler) (bool, error) + ForEach(v cbor.Unmarshaler, fn func(idx int64) error) error +} + +type ProxyArray struct { + GetFunc func(idx uint64, v cbor.Unmarshaler) (bool, error) + ForEachFunc func(v cbor.Unmarshaler, fn func(idx int64) error) error +} + +func (a *ProxyArray) Get(idx uint64, v cbor.Unmarshaler) (bool, error) { + return a.GetFunc(idx, v) +} +func (a *ProxyArray) ForEach(v cbor.Unmarshaler, fn func(idx int64) error) error { + return a.ForEachFunc(v, fn) +} diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index 704ea1291..b20539b8f 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -1,7 +1,6 @@ package miner import ( - "github.com/filecoin-project/go-state-types/dline" "github.com/ipfs/go-cid" "github.com/libp2p/go-libp2p-core/peer" cbg "github.com/whyrusleeping/cbor-gen" @@ -11,6 +10,7 @@ import ( "github.com/filecoin-project/go-bitfield" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/cbor" + "github.com/filecoin-project/go-state-types/dline" builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" @@ -47,7 +47,7 @@ type State interface { FindSector(abi.SectorNumber) (*SectorLocation, error) GetSectorExpiration(abi.SectorNumber) (*SectorExpiration, error) GetPrecommittedSector(abi.SectorNumber) (*SectorPreCommitOnChainInfo, error) - LoadSectorsFromSet(filter *bitfield.BitField, filterOut bool) (adt.Array, error) + LoadSectorsFromSet(filter *bitfield.BitField, filterOut bool) (adt.ROnlyArray, error) IsAllocated(abi.SectorNumber) (bool, error) LoadDeadline(idx uint64) (Deadline, error) diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index 010ae6699..ddc0b71a9 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -4,17 +4,19 @@ import ( "bytes" "errors" - "github.com/filecoin-project/go-address" - "github.com/filecoin-project/go-bitfield" - "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/go-state-types/dline" - "github.com/filecoin-project/lotus/chain/actors/adt" - adt0 "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/libp2p/go-libp2p-core/peer" cbg "github.com/whyrusleeping/cbor-gen" "golang.org/x/xerrors" + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-bitfield" + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/cbor" + "github.com/filecoin-project/go-state-types/dline" miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" + adt0 "github.com/filecoin-project/specs-actors/actors/util/adt" + + "github.com/filecoin-project/lotus/chain/actors/adt" ) var _ State = (*state0)(nil) @@ -161,56 +163,55 @@ func (s *state0) GetPrecommittedSector(num abi.SectorNumber) (*SectorPreCommitOn return &ret, nil } -func (s *state0) LoadSectorsFromSet(filter *bitfield.BitField, filterOut bool) (adt.Array, error) { +func (s *state0) LoadSectorsFromSet(filter *bitfield.BitField, filterOut bool) (adt.ROnlyArray, error) { a, err := adt0.AsArray(s.store, s.State.Sectors) if err != nil { return nil, err } - ret := adt0.MakeEmptyArray(s.store) - var v cbg.Deferred - if err := a.ForEach(&v, func(i int64) error { + incl := func(i uint64) (bool, error) { include := true if filter != nil { - set, err := filter.IsSet(uint64(i)) + set, err := filter.IsSet(i) if err != nil { - return xerrors.Errorf("filter check error: %w", err) + return false, xerrors.Errorf("filter check error: %w", err) } if set == filterOut { include = false } } - - if include { - var oci miner0.SectorOnChainInfo - if err := oci.UnmarshalCBOR(bytes.NewReader(v.Raw)); err != nil { - return err - } - - noci := SectorOnChainInfo{ - SectorNumber: oci.SectorNumber, - SealProof: oci.SealProof, - SealedCID: oci.SealedCID, - DealIDs: oci.DealIDs, - Activation: oci.Activation, - Expiration: oci.Expiration, - DealWeight: oci.DealWeight, - VerifiedDealWeight: oci.VerifiedDealWeight, - InitialPledge: oci.InitialPledge, - ExpectedDayReward: oci.ExpectedDayReward, - ExpectedStoragePledge: oci.ExpectedStoragePledge, - } - - if err := ret.Set(uint64(i), &noci); err != nil { - return err - } - } - return nil - }); err != nil { - return nil, err + return include, nil } - return ret, nil + return &adt.ProxyArray{ + GetFunc: func(idx uint64, v cbor.Unmarshaler) (bool, error) { + i, err := incl(idx) + if err != nil { + return false, err + } + if !i { + return false, nil + } + + // TODO: ActorUpgrade potentially convert + + return a.Get(idx, v) + }, + ForEachFunc: func(v cbor.Unmarshaler, fn func(int64) error) error { + // TODO: ActorUpgrade potentially convert the output + return a.ForEach(v, func(i int64) error { + include, err := incl(uint64(i)) + if err != nil { + return err + } + if !include { + return nil + } + + return fn(i) + }) + }, + }, nil } func (s *state0) LoadPreCommittedSectors() (adt.Map, error) { From a5e7fd8f5c0e8ed2c900bd23860e16d2336411f1 Mon Sep 17 00:00:00 2001 From: Hector Sanjuan Date: Mon, 21 Sep 2020 18:43:57 +0200 Subject: [PATCH 136/303] Re-add docs-check step to circle --- .circleci/config.yml | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.circleci/config.yml b/.circleci/config.yml index d8f149889..acd447f69 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -346,6 +346,15 @@ jobs: - run: git --no-pager diff - run: git --no-pager diff --quiet + docs-check: + executor: golang + steps: + - install-deps + - prepare + - run: make docsgen + - run: git --no-pager diff + - run: git --no-pager diff --quiet + lint: &lint description: | Run golangci-lint. @@ -415,6 +424,7 @@ workflows: - mod-tidy-check - gofmt - cbor-gen-check + - docs-check - test: codecov-upload: true test-suite-name: full From 1096f8acc6900dccc7db160cafe9284362f17db2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Mon, 21 Sep 2020 18:59:05 +0200 Subject: [PATCH 137/303] miner: Invert show-removed option in sectors list --- cmd/lotus-storage-miner/sectors.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cmd/lotus-storage-miner/sectors.go b/cmd/lotus-storage-miner/sectors.go index 0e6fe8435..f77c6b61c 100644 --- a/cmd/lotus-storage-miner/sectors.go +++ b/cmd/lotus-storage-miner/sectors.go @@ -2,7 +2,6 @@ package main import ( "fmt" - sealing "github.com/filecoin-project/lotus/extern/storage-sealing" "os" "sort" "strconv" @@ -19,6 +18,7 @@ import ( "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/chain/types" lcli "github.com/filecoin-project/lotus/cli" + sealing "github.com/filecoin-project/lotus/extern/storage-sealing" ) var sectorsCmd = &cli.Command{ @@ -139,8 +139,8 @@ var sectorsListCmd = &cli.Command{ Usage: "List sectors", Flags: []cli.Flag{ &cli.BoolFlag{ - Name: "hide-removed", - Usage: "to hide Removed sectors", + Name: "show-removed", + Usage: "show removed sectors", }, }, Action: func(cctx *cli.Context) error { @@ -199,11 +199,11 @@ var sectorsListCmd = &cli.Command{ continue } - if !cctx.Bool("hide-removed") || st.State != api.SectorState(sealing.Removed) { + if cctx.Bool("show-removed") || st.State != api.SectorState(sealing.Removed) { _, inSSet := commitedIDs[s] _, inASet := activeIDs[s] - fmt.Fprintf(w, "%d: %s\tsSet: %s\tactive: %s\ttktH: %d\tseedH: %d\tdeals: %v\t toUpgrade:%t\n", + _, _ = fmt.Fprintf(w, "%d: %s\tsSet: %s\tactive: %s\ttktH: %d\tseedH: %d\tdeals: %v\t toUpgrade:%t\n", s, st.State, yesno(inSSet), From ad3db0e83c5f6723573eec1464bc3bc48d29c001 Mon Sep 17 00:00:00 2001 From: Hector Sanjuan Date: Mon, 21 Sep 2020 19:05:39 +0200 Subject: [PATCH 138/303] Move unclassified docs back to the docs root --- .../en/{unclassified => }/WIP-arch-complementary-notes.md | 0 documentation/en/{unclassified => }/block-validation.md | 0 documentation/en/{unclassified => }/create-miner.md | 0 documentation/en/{unclassified => }/dev-tools-pond-ui.md | 0 documentation/en/{unclassified => }/sealing-procs.md | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename documentation/en/{unclassified => }/WIP-arch-complementary-notes.md (100%) rename documentation/en/{unclassified => }/block-validation.md (100%) rename documentation/en/{unclassified => }/create-miner.md (100%) rename documentation/en/{unclassified => }/dev-tools-pond-ui.md (100%) rename documentation/en/{unclassified => }/sealing-procs.md (100%) diff --git a/documentation/en/unclassified/WIP-arch-complementary-notes.md b/documentation/en/WIP-arch-complementary-notes.md similarity index 100% rename from documentation/en/unclassified/WIP-arch-complementary-notes.md rename to documentation/en/WIP-arch-complementary-notes.md diff --git a/documentation/en/unclassified/block-validation.md b/documentation/en/block-validation.md similarity index 100% rename from documentation/en/unclassified/block-validation.md rename to documentation/en/block-validation.md diff --git a/documentation/en/unclassified/create-miner.md b/documentation/en/create-miner.md similarity index 100% rename from documentation/en/unclassified/create-miner.md rename to documentation/en/create-miner.md diff --git a/documentation/en/unclassified/dev-tools-pond-ui.md b/documentation/en/dev-tools-pond-ui.md similarity index 100% rename from documentation/en/unclassified/dev-tools-pond-ui.md rename to documentation/en/dev-tools-pond-ui.md diff --git a/documentation/en/unclassified/sealing-procs.md b/documentation/en/sealing-procs.md similarity index 100% rename from documentation/en/unclassified/sealing-procs.md rename to documentation/en/sealing-procs.md From 025663118f65dc50d0dd13364fd57b7cddab70ed Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Mon, 21 Sep 2020 10:30:09 -0700 Subject: [PATCH 139/303] non-destructive diff --- chain/actors/adt/diff_adt.go | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/chain/actors/adt/diff_adt.go b/chain/actors/adt/diff_adt.go index 0784b77a2..160e12e19 100644 --- a/chain/actors/adt/diff_adt.go +++ b/chain/actors/adt/diff_adt.go @@ -27,6 +27,7 @@ type AdtArrayDiff interface { // - All values that exist in preArr and in curArr are passed to AdtArrayDiff.Modify() // - It is the responsibility of AdtArrayDiff.Modify() to determine if the values it was passed have been modified. func DiffAdtArray(preArr, curArr Array, out AdtArrayDiff) error { + notNew := make(map[int64]struct{}, curArr.Length()) prevVal := new(typegen.Deferred) if err := preArr.ForEach(prevVal, func(i int64) error { curVal := new(typegen.Deferred) @@ -47,14 +48,17 @@ func DiffAdtArray(preArr, curArr Array, out AdtArrayDiff) error { return err } } - - return curArr.Delete(uint64(i)) + notNew[i] = struct{}{} + return nil }); err != nil { return err } curVal := new(typegen.Deferred) return curArr.ForEach(curVal, func(i int64) error { + if _, ok := notNew[i]; ok { + return nil + } return out.Add(uint64(i), curVal) }) } @@ -76,6 +80,7 @@ type AdtMapDiff interface { } func DiffAdtMap(preMap, curMap Map, out AdtMapDiff) error { + notNew := make(map[string]struct{}) prevVal := new(typegen.Deferred) if err := preMap.ForEach(prevVal, func(key string) error { curVal := new(typegen.Deferred) @@ -101,14 +106,17 @@ func DiffAdtMap(preMap, curMap Map, out AdtMapDiff) error { return err } } - - return curMap.Delete(k) + notNew[key] = struct{}{} + return nil }); err != nil { return err } curVal := new(typegen.Deferred) return curMap.ForEach(curVal, func(key string) error { + if _, ok := notNew[key]; ok { + return nil + } return out.Add(key, curVal) }) } From 4cf0c105eb12685b384fad6fb3e249898687511f Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Mon, 21 Sep 2020 12:05:01 -0700 Subject: [PATCH 140/303] optimize sector loading And avoid exposing "arrays" via the miner abstraction. We may change these structures later. --- api/api_full.go | 6 +-- api/apistruct/struct.go | 10 ++-- chain/actors/adt/adt.go | 17 ------- chain/actors/builtin/miner/miner.go | 7 +-- chain/actors/builtin/miner/v0.go | 72 ++++++++++------------------- chain/stmgr/utils.go | 71 +++++++++------------------- cli/state.go | 6 +-- cmd/lotus-storage-miner/sectors.go | 6 +-- documentation/en/api-methods.md | 3 -- node/impl/full/state.go | 8 ++-- storage/miner.go | 2 +- storage/wdpost_run.go | 16 +++---- storage/wdpost_run_test.go | 16 +++---- 13 files changed, 81 insertions(+), 159 deletions(-) diff --git a/api/api_full.go b/api/api_full.go index 61bf1fd8d..f39d0e9bc 100644 --- a/api/api_full.go +++ b/api/api_full.go @@ -313,11 +313,9 @@ type FullNode interface { // StateNetworkName returns the name of the network the node is synced to StateNetworkName(context.Context) (dtypes.NetworkName, error) // StateMinerSectors returns info about the given miner's sectors. If the filter bitfield is nil, all sectors are included. - // If the filterOut boolean is set to true, any sectors in the filter are excluded. - // If false, only those sectors in the filter are included. - StateMinerSectors(context.Context, address.Address, *bitfield.BitField, bool, types.TipSetKey) ([]*miner.ChainSectorInfo, error) + StateMinerSectors(context.Context, address.Address, *bitfield.BitField, types.TipSetKey) ([]*miner.SectorOnChainInfo, error) // StateMinerActiveSectors returns info about sectors that a given miner is actively proving. - StateMinerActiveSectors(context.Context, address.Address, types.TipSetKey) ([]*miner.ChainSectorInfo, error) + StateMinerActiveSectors(context.Context, address.Address, types.TipSetKey) ([]*miner.SectorOnChainInfo, error) // StateMinerProvingDeadline calculates the deadline at some epoch for a proving period // and returns the deadline-related calculations. StateMinerProvingDeadline(context.Context, address.Address, types.TipSetKey) (*dline.Info, error) diff --git a/api/apistruct/struct.go b/api/apistruct/struct.go index cbe78c555..91a545479 100644 --- a/api/apistruct/struct.go +++ b/api/apistruct/struct.go @@ -162,8 +162,8 @@ type FullNodeStruct struct { ClientRetrieveTryRestartInsufficientFunds func(ctx context.Context, paymentChannel address.Address) error `perm:"write"` StateNetworkName func(context.Context) (dtypes.NetworkName, error) `perm:"read"` - StateMinerSectors func(context.Context, address.Address, *bitfield.BitField, bool, types.TipSetKey) ([]*miner.ChainSectorInfo, error) `perm:"read"` - StateMinerActiveSectors func(context.Context, address.Address, types.TipSetKey) ([]*miner.ChainSectorInfo, error) `perm:"read"` + StateMinerSectors func(context.Context, address.Address, *bitfield.BitField, types.TipSetKey) ([]*miner.SectorOnChainInfo, error) `perm:"read"` + StateMinerActiveSectors func(context.Context, address.Address, types.TipSetKey) ([]*miner.SectorOnChainInfo, error) `perm:"read"` StateMinerProvingDeadline func(context.Context, address.Address, types.TipSetKey) (*dline.Info, error) `perm:"read"` StateMinerPower func(context.Context, address.Address, types.TipSetKey) (*api.MinerPower, error) `perm:"read"` StateMinerInfo func(context.Context, address.Address, types.TipSetKey) (miner.MinerInfo, error) `perm:"read"` @@ -734,11 +734,11 @@ func (c *FullNodeStruct) StateNetworkName(ctx context.Context) (dtypes.NetworkNa return c.Internal.StateNetworkName(ctx) } -func (c *FullNodeStruct) StateMinerSectors(ctx context.Context, addr address.Address, filter *bitfield.BitField, filterOut bool, tsk types.TipSetKey) ([]*miner.ChainSectorInfo, error) { - return c.Internal.StateMinerSectors(ctx, addr, filter, filterOut, tsk) +func (c *FullNodeStruct) StateMinerSectors(ctx context.Context, addr address.Address, sectorNos *bitfield.BitField, tsk types.TipSetKey) ([]*miner.SectorOnChainInfo, error) { + return c.Internal.StateMinerSectors(ctx, addr, sectorNos, tsk) } -func (c *FullNodeStruct) StateMinerActiveSectors(ctx context.Context, addr address.Address, tsk types.TipSetKey) ([]*miner.ChainSectorInfo, error) { +func (c *FullNodeStruct) StateMinerActiveSectors(ctx context.Context, addr address.Address, tsk types.TipSetKey) ([]*miner.SectorOnChainInfo, error) { return c.Internal.StateMinerActiveSectors(ctx, addr, tsk) } diff --git a/chain/actors/adt/adt.go b/chain/actors/adt/adt.go index 81c2e3a86..fd5ee3f87 100644 --- a/chain/actors/adt/adt.go +++ b/chain/actors/adt/adt.go @@ -55,20 +55,3 @@ func AsArray(store Store, root cid.Cid, version network.Version) (Array, error) } return nil, xerrors.Errorf("unknown network version: %d", version) } - -type ROnlyArray interface { - Get(idx uint64, v cbor.Unmarshaler) (bool, error) - ForEach(v cbor.Unmarshaler, fn func(idx int64) error) error -} - -type ProxyArray struct { - GetFunc func(idx uint64, v cbor.Unmarshaler) (bool, error) - ForEachFunc func(v cbor.Unmarshaler, fn func(idx int64) error) error -} - -func (a *ProxyArray) Get(idx uint64, v cbor.Unmarshaler) (bool, error) { - return a.GetFunc(idx, v) -} -func (a *ProxyArray) ForEach(v cbor.Unmarshaler, fn func(idx int64) error) error { - return a.ForEachFunc(v, fn) -} diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index b20539b8f..cf5eea742 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -47,7 +47,7 @@ type State interface { FindSector(abi.SectorNumber) (*SectorLocation, error) GetSectorExpiration(abi.SectorNumber) (*SectorExpiration, error) GetPrecommittedSector(abi.SectorNumber) (*SectorPreCommitOnChainInfo, error) - LoadSectorsFromSet(filter *bitfield.BitField, filterOut bool) (adt.ROnlyArray, error) + LoadSectors(sectorNos *bitfield.BitField) ([]*SectorOnChainInfo, error) IsAllocated(abi.SectorNumber) (bool, error) LoadDeadline(idx uint64) (Deadline, error) @@ -129,11 +129,6 @@ type MinerInfo struct { WindowPoStPartitionSectors uint64 } -type ChainSectorInfo struct { - Info SectorOnChainInfo - ID abi.SectorNumber -} - type SectorExpiration struct { OnTime abi.ChainEpoch diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index ddc0b71a9..30ce7e73e 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -6,12 +6,10 @@ import ( "github.com/libp2p/go-libp2p-core/peer" cbg "github.com/whyrusleeping/cbor-gen" - "golang.org/x/xerrors" "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-bitfield" "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/go-state-types/cbor" "github.com/filecoin-project/go-state-types/dline" miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" adt0 "github.com/filecoin-project/specs-actors/actors/util/adt" @@ -163,59 +161,37 @@ func (s *state0) GetPrecommittedSector(num abi.SectorNumber) (*SectorPreCommitOn return &ret, nil } -func (s *state0) LoadSectorsFromSet(filter *bitfield.BitField, filterOut bool) (adt.ROnlyArray, error) { - a, err := adt0.AsArray(s.store, s.State.Sectors) +func (s *state0) LoadSectors(snos *bitfield.BitField) ([]*SectorOnChainInfo, error) { + sectors, err := miner0.LoadSectors(s.store, s.State.Sectors) if err != nil { return nil, err } - incl := func(i uint64) (bool, error) { - include := true - if filter != nil { - set, err := filter.IsSet(i) - if err != nil { - return false, xerrors.Errorf("filter check error: %w", err) - } - if set == filterOut { - include = false - } + // If no sector numbers are specified, load all. + if snos == nil { + infos := make([]*SectorOnChainInfo, 0, sectors.Length()) + var info0 miner0.SectorOnChainInfo + if err := sectors.ForEach(&info0, func(i int64) error { + info := fromV0SectorOnChainInfo(info0) + infos[i] = &info + return nil + }); err != nil { + return nil, err } - return include, nil + return infos, nil } - return &adt.ProxyArray{ - GetFunc: func(idx uint64, v cbor.Unmarshaler) (bool, error) { - i, err := incl(idx) - if err != nil { - return false, err - } - if !i { - return false, nil - } - - // TODO: ActorUpgrade potentially convert - - return a.Get(idx, v) - }, - ForEachFunc: func(v cbor.Unmarshaler, fn func(int64) error) error { - // TODO: ActorUpgrade potentially convert the output - return a.ForEach(v, func(i int64) error { - include, err := incl(uint64(i)) - if err != nil { - return err - } - if !include { - return nil - } - - return fn(i) - }) - }, - }, nil -} - -func (s *state0) LoadPreCommittedSectors() (adt.Map, error) { - return adt0.AsMap(s.store, s.State.PreCommittedSectors) + // Otherwise, load selected. + infos0, err := sectors.Load(*snos) + if err != nil { + return nil, err + } + infos := make([]*SectorOnChainInfo, len(infos0)) + for i, info0 := range infos0 { + info := fromV0SectorOnChainInfo(*info0) + infos[i] = &info + } + return infos, nil } func (s *state0) IsAllocated(num abi.SectorNumber) (bool, error) { diff --git a/chain/stmgr/utils.go b/chain/stmgr/utils.go index 1056818a6..1e670dace 100644 --- a/chain/stmgr/utils.go +++ b/chain/stmgr/utils.go @@ -150,7 +150,7 @@ func MinerSectorInfo(ctx context.Context, sm *StateManager, maddr address.Addres return mas.GetSector(sid) } -func GetMinerSectorSet(ctx context.Context, sm *StateManager, ts *types.TipSet, maddr address.Address, filter *bitfield.BitField, filterOut bool) ([]*miner.ChainSectorInfo, error) { +func GetMinerSectorSet(ctx context.Context, sm *StateManager, ts *types.TipSet, maddr address.Address, snos *bitfield.BitField) ([]*miner.SectorOnChainInfo, error) { act, err := sm.LoadActor(ctx, maddr, ts) if err != nil { return nil, xerrors.Errorf("(get sset) failed to load miner actor: %w", err) @@ -161,29 +161,7 @@ func GetMinerSectorSet(ctx context.Context, sm *StateManager, ts *types.TipSet, return nil, xerrors.Errorf("(get sset) failed to load miner actor state: %w", err) } - sectors, err := mas.LoadSectorsFromSet(filter, filterOut) - if err != nil { - return nil, xerrors.Errorf("(get sset) failed to load sectors: %w", err) - } - - var sset []*miner.ChainSectorInfo - var v cbg.Deferred - if err := sectors.ForEach(&v, func(i int64) error { - var oci miner.SectorOnChainInfo - if err := oci.UnmarshalCBOR(bytes.NewReader(v.Raw)); err != nil { - return err - } - sset = append(sset, &miner.ChainSectorInfo{ - Info: oci, - ID: abi.SectorNumber(i), - }) - - return nil - }); err != nil { - return nil, err - } - - return sset, nil + return mas.LoadSectors(snos) } func GetSectorsForWinningPoSt(ctx context.Context, pv ffiwrapper.Verifier, sm *StateManager, st cid.Cid, maddr address.Address, rand abi.PoStRandomness) ([]proof.SectorInfo, error) { @@ -249,35 +227,30 @@ func GetSectorsForWinningPoSt(ctx context.Context, pv ffiwrapper.Verifier, sm *S return nil, xerrors.Errorf("generating winning post challenges: %w", err) } - // we don't need to filter here (and it's **very** slow) - sectors, err := mas.LoadSectorsFromSet(nil, false) + iter, err := provingSectors.BitIterator() + if err != nil { + return nil, xerrors.Errorf("iterating over proving sectors: %w", err) + } + + // Select winning sectors by _index_ in the all-sectors bitfield. + selectedSectors := bitfield.New() + prev := uint64(0) + for _, n := range ids { + sno, err := iter.Nth(n - prev) + if err != nil { + return nil, xerrors.Errorf("iterating over proving sectors: %w", err) + } + selectedSectors.Set(sno) + prev = n + } + + sectors, err := mas.LoadSectors(&selectedSectors) if err != nil { return nil, xerrors.Errorf("loading proving sectors: %w", err) } - out := make([]proof.SectorInfo, len(ids)) - for i, n := range ids { - sb, err := provingSectors.Slice(n, 1) - if err != nil { - return nil, err - } - - sid, err := sb.First() - if err != nil { - return nil, err - } - - var sinfo miner.SectorOnChainInfo - found, err := sectors.Get(sid, &sinfo) - - if err != nil { - return nil, xerrors.Errorf("loading sector info: %w", err) - } - - if !found { - return nil, xerrors.Errorf("didn't find sector info for sector %d", n) - } - + out := make([]proof.SectorInfo, len(sectors)) + for i, sinfo := range sectors { out[i] = proof.SectorInfo{ SealProof: spt, SectorNumber: sinfo.SectorNumber, diff --git a/cli/state.go b/cli/state.go index 2476d7c59..d96c93c54 100644 --- a/cli/state.go +++ b/cli/state.go @@ -259,13 +259,13 @@ var stateSectorsCmd = &cli.Command{ return err } - sectors, err := api.StateMinerSectors(ctx, maddr, nil, true, ts.Key()) + sectors, err := api.StateMinerSectors(ctx, maddr, nil, ts.Key()) if err != nil { return err } for _, s := range sectors { - fmt.Printf("%d: %x\n", s.Info.SectorNumber, s.Info.SealedCID) + fmt.Printf("%d: %x\n", s.SectorNumber, s.SealedCID) } return nil @@ -305,7 +305,7 @@ var stateActiveSectorsCmd = &cli.Command{ } for _, s := range sectors { - fmt.Printf("%d: %x\n", s.Info.SectorNumber, s.Info.SealedCID) + fmt.Printf("%d: %x\n", s.SectorNumber, s.SealedCID) } return nil diff --git a/cmd/lotus-storage-miner/sectors.go b/cmd/lotus-storage-miner/sectors.go index e3512cfe4..27a5c31be 100644 --- a/cmd/lotus-storage-miner/sectors.go +++ b/cmd/lotus-storage-miner/sectors.go @@ -176,16 +176,16 @@ var sectorsListCmd = &cli.Command{ } activeIDs := make(map[abi.SectorNumber]struct{}, len(activeSet)) for _, info := range activeSet { - activeIDs[info.ID] = struct{}{} + activeIDs[info.SectorNumber] = struct{}{} } - sset, err := fullApi.StateMinerSectors(ctx, maddr, nil, true, types.EmptyTSK) + sset, err := fullApi.StateMinerSectors(ctx, maddr, nil, types.EmptyTSK) if err != nil { return err } commitedIDs := make(map[abi.SectorNumber]struct{}, len(activeSet)) for _, info := range sset { - commitedIDs[info.ID] = struct{}{} + commitedIDs[info.SectorNumber] = struct{}{} } sort.Slice(list, func(i, j int) bool { diff --git a/documentation/en/api-methods.md b/documentation/en/api-methods.md index 5616bbd26..fd201f18a 100644 --- a/documentation/en/api-methods.md +++ b/documentation/en/api-methods.md @@ -3714,8 +3714,6 @@ Response: ### StateMinerSectors StateMinerSectors returns info about the given miner's sectors. If the filter bitfield is nil, all sectors are included. -If the filterOut boolean is set to true, any sectors in the filter are excluded. -If false, only those sectors in the filter are included. Perms: read @@ -3727,7 +3725,6 @@ Inputs: [ 0 ], - true, [ { "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" diff --git a/node/impl/full/state.go b/node/impl/full/state.go index e4400b073..8d40da0ec 100644 --- a/node/impl/full/state.go +++ b/node/impl/full/state.go @@ -64,15 +64,15 @@ func (a *StateAPI) StateNetworkName(ctx context.Context) (dtypes.NetworkName, er return stmgr.GetNetworkName(ctx, a.StateManager, a.Chain.GetHeaviestTipSet().ParentState()) } -func (a *StateAPI) StateMinerSectors(ctx context.Context, addr address.Address, filter *bitfield.BitField, filterOut bool, tsk types.TipSetKey) ([]*miner.ChainSectorInfo, error) { +func (a *StateAPI) StateMinerSectors(ctx context.Context, addr address.Address, sectorNos *bitfield.BitField, tsk types.TipSetKey) ([]*miner.SectorOnChainInfo, error) { ts, err := a.Chain.GetTipSetFromKey(tsk) if err != nil { return nil, xerrors.Errorf("loading tipset %s: %w", tsk, err) } - return stmgr.GetMinerSectorSet(ctx, a.StateManager, ts, addr, filter, filterOut) + return stmgr.GetMinerSectorSet(ctx, a.StateManager, ts, addr, sectorNos) } -func (a *StateAPI) StateMinerActiveSectors(ctx context.Context, maddr address.Address, tsk types.TipSetKey) ([]*miner.ChainSectorInfo, error) { // TODO: only used in cli +func (a *StateAPI) StateMinerActiveSectors(ctx context.Context, maddr address.Address, tsk types.TipSetKey) ([]*miner.SectorOnChainInfo, error) { // TODO: only used in cli ts, err := a.Chain.GetTipSetFromKey(tsk) if err != nil { return nil, xerrors.Errorf("loading tipset %s: %w", tsk, err) @@ -93,7 +93,7 @@ func (a *StateAPI) StateMinerActiveSectors(ctx context.Context, maddr address.Ad return nil, xerrors.Errorf("merge partition active sets: %w", err) } - return stmgr.GetMinerSectorSet(ctx, a.StateManager, ts, maddr, &activeSectors, false) + return stmgr.GetMinerSectorSet(ctx, a.StateManager, ts, maddr, &activeSectors) } func (a *StateAPI) StateMinerInfo(ctx context.Context, actor address.Address, tsk types.TipSetKey) (miner.MinerInfo, error) { diff --git a/storage/miner.go b/storage/miner.go index 61c4000f2..a64ee977e 100644 --- a/storage/miner.go +++ b/storage/miner.go @@ -71,7 +71,7 @@ type SealingStateEvt struct { type storageMinerApi interface { // Call a read only method on actors (no interaction with the chain required) StateCall(context.Context, *types.Message, types.TipSetKey) (*api.InvocResult, error) - StateMinerSectors(context.Context, address.Address, *bitfield.BitField, bool, types.TipSetKey) ([]*miner.ChainSectorInfo, error) + StateMinerSectors(context.Context, address.Address, *bitfield.BitField, types.TipSetKey) ([]*miner.SectorOnChainInfo, error) StateSectorPreCommitInfo(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (miner.SectorPreCommitOnChainInfo, error) StateSectorGetInfo(context.Context, address.Address, abi.SectorNumber, types.TipSetKey) (*miner.SectorOnChainInfo, error) StateSectorPartition(ctx context.Context, maddr address.Address, sectorNumber abi.SectorNumber, tok types.TipSetKey) (*miner.SectorLocation, error) diff --git a/storage/wdpost_run.go b/storage/wdpost_run.go index 06740b108..254a2f0d3 100644 --- a/storage/wdpost_run.go +++ b/storage/wdpost_run.go @@ -594,7 +594,7 @@ func (s *WindowPoStScheduler) batchPartitions(partitions []api.Partition) ([][]a } func (s *WindowPoStScheduler) sectorsForProof(ctx context.Context, goodSectors, allSectors bitfield.BitField, ts *types.TipSet) ([]proof.SectorInfo, error) { - sset, err := s.api.StateMinerSectors(ctx, s.actor, &goodSectors, false, ts.Key()) + sset, err := s.api.StateMinerSectors(ctx, s.actor, &goodSectors, ts.Key()) if err != nil { return nil, err } @@ -604,17 +604,17 @@ func (s *WindowPoStScheduler) sectorsForProof(ctx context.Context, goodSectors, } substitute := proof.SectorInfo{ - SectorNumber: sset[0].ID, - SealedCID: sset[0].Info.SealedCID, - SealProof: sset[0].Info.SealProof, + SectorNumber: sset[0].SectorNumber, + SealedCID: sset[0].SealedCID, + SealProof: sset[0].SealProof, } sectorByID := make(map[uint64]proof.SectorInfo, len(sset)) for _, sector := range sset { - sectorByID[uint64(sector.ID)] = proof.SectorInfo{ - SectorNumber: sector.ID, - SealedCID: sector.Info.SealedCID, - SealProof: sector.Info.SealProof, + sectorByID[uint64(sector.SectorNumber)] = proof.SectorInfo{ + SectorNumber: sector.SectorNumber, + SealedCID: sector.SealedCID, + SealProof: sector.SealProof, } } diff --git a/storage/wdpost_run_test.go b/storage/wdpost_run_test.go index bd8e35d4f..1797cf35c 100644 --- a/storage/wdpost_run_test.go +++ b/storage/wdpost_run_test.go @@ -65,14 +65,14 @@ func (m *mockStorageMinerAPI) StateMinerPartitions(ctx context.Context, a addres return m.partitions, nil } -func (m *mockStorageMinerAPI) StateMinerSectors(ctx context.Context, address address.Address, field *bitfield.BitField, b bool, key types.TipSetKey) ([]*miner.ChainSectorInfo, error) { - var sis []*miner.ChainSectorInfo - _ = field.ForEach(func(i uint64) error { - sis = append(sis, &miner.ChainSectorInfo{ - Info: miner.SectorOnChainInfo{ - SectorNumber: abi.SectorNumber(i), - }, - ID: abi.SectorNumber(i), +func (m *mockStorageMinerAPI) StateMinerSectors(ctx context.Context, address address.Address, snos *bitfield.BitField, key types.TipSetKey) ([]*miner.SectorOnChainInfo, error) { + var sis []*miner.SectorOnChainInfo + if snos == nil { + panic("unsupported") + } + _ = snos.ForEach(func(i uint64) error { + sis = append(sis, &miner.SectorOnChainInfo{ + SectorNumber: abi.SectorNumber(i), }) return nil }) From 24ae9205fef921e1e15b59c291859c42ef5851ad Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Mon, 21 Sep 2020 12:50:12 -0700 Subject: [PATCH 141/303] cross-version state tree diff --- chain/state/statetree.go | 43 ++++++++++++++++++++++++++++++++ node/impl/full/state.go | 53 +++++----------------------------------- 2 files changed, 49 insertions(+), 47 deletions(-) diff --git a/chain/state/statetree.go b/chain/state/statetree.go index b3a3b7cee..fb6a14a9b 100644 --- a/chain/state/statetree.go +++ b/chain/state/statetree.go @@ -1,6 +1,7 @@ package state import ( + "bytes" "context" "fmt" @@ -14,6 +15,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/lotus/chain/actors/builtin" init_ "github.com/filecoin-project/lotus/chain/actors/builtin/init" + cbg "github.com/whyrusleeping/cbor-gen" "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/types" @@ -391,3 +393,44 @@ func (st *StateTree) ForEach(f func(address.Address, *types.Actor) error) error return f(addr, &act) }) } + +func Diff(oldTree, newTree *StateTree) (map[string]types.Actor, error) { + out := map[string]types.Actor{} + + var ( + ncval, ocval cbg.Deferred + buf = bytes.NewReader(nil) + ) + if err := newTree.root.ForEach(&ncval, func(k string) error { + var act types.Actor + + addr, err := address.NewFromBytes([]byte(k)) + if err != nil { + return xerrors.Errorf("address in state tree was not valid: %w", err) + } + + found, err := oldTree.root.Get(abi.AddrKey(addr), &ocval) + if err != nil { + return err + } + + if found && bytes.Equal(ocval.Raw, ncval.Raw) { + return nil // not changed + } + + buf.Reset(ncval.Raw) + err = act.UnmarshalCBOR(buf) + buf.Reset(nil) + + if err != nil { + return err + } + + out[addr.String()] = act + + return nil + }); err != nil { + return nil, err + } + return out, nil +} diff --git a/node/impl/full/state.go b/node/impl/full/state.go index 8d40da0ec..b64e60260 100644 --- a/node/impl/full/state.go +++ b/node/impl/full/state.go @@ -16,7 +16,6 @@ import ( cid "github.com/ipfs/go-cid" cbor "github.com/ipfs/go-ipld-cbor" - cbg "github.com/whyrusleeping/cbor-gen" "go.uber.org/fx" "golang.org/x/xerrors" @@ -27,7 +26,6 @@ import ( "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" "github.com/filecoin-project/specs-actors/actors/builtin" miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/chain/actors/builtin/market" @@ -618,58 +616,19 @@ func (a *StateAPI) StateMarketStorageDeal(ctx context.Context, dealId abi.DealID } func (a *StateAPI) StateChangedActors(ctx context.Context, old cid.Cid, new cid.Cid) (map[string]types.Actor, error) { - store := adt.WrapStore(ctx, cbor.NewCborStore(a.Chain.Blockstore())) + store := a.Chain.Store(ctx) - nh, err := adt.AsMap(store, new) + oldTree, err := state.LoadStateTree(store, old) if err != nil { - return nil, err + return nil, xerrors.Errorf("failed to load old state tree: %w", err) } - oh, err := adt.AsMap(store, old) + newTree, err := state.LoadStateTree(store, new) if err != nil { - return nil, err + return nil, xerrors.Errorf("failed to load new state tree: %w", err) } - out := map[string]types.Actor{} - - var ( - ncval, ocval cbg.Deferred - buf = bytes.NewReader(nil) - ) - err = nh.ForEach(&ncval, func(k string) error { - var act types.Actor - - addr, err := address.NewFromBytes([]byte(k)) - if err != nil { - return xerrors.Errorf("address in state tree was not valid: %w", err) - } - - found, err := oh.Get(abi.AddrKey(addr), &ocval) - if err != nil { - return err - } - - if found && bytes.Equal(ocval.Raw, ncval.Raw) { - return nil // not changed - } - - buf.Reset(ncval.Raw) - err = act.UnmarshalCBOR(buf) - buf.Reset(nil) - - if err != nil { - return err - } - - out[addr.String()] = act - - return nil - }) - if err != nil { - return nil, err - } - - return out, nil + state.Diff(oldTree, newTree) } func (a *StateAPI) StateMinerSectorCount(ctx context.Context, addr address.Address, tsk types.TipSetKey) (api.MinerSectors, error) { From f9a896f6f2f33e30f4cbd627613255488cbc2aec Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Mon, 21 Sep 2020 13:10:41 -0700 Subject: [PATCH 142/303] fix compile --- node/impl/full/state.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/node/impl/full/state.go b/node/impl/full/state.go index b64e60260..df747ba3f 100644 --- a/node/impl/full/state.go +++ b/node/impl/full/state.go @@ -628,7 +628,7 @@ func (a *StateAPI) StateChangedActors(ctx context.Context, old cid.Cid, new cid. return nil, xerrors.Errorf("failed to load new state tree: %w", err) } - state.Diff(oldTree, newTree) + return state.Diff(oldTree, newTree) } func (a *StateAPI) StateMinerSectorCount(ctx context.Context, addr address.Address, tsk types.TipSetKey) (api.MinerSectors, error) { From 0ab2459fcec5e85ea6496174b350b201e0b1518a Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Mon, 21 Sep 2020 13:13:38 -0700 Subject: [PATCH 143/303] convert multisig to new actor abstractions --- chain/actors/builtin/multisig/multisig.go | 9 ++ chain/actors/builtin/multisig/v0.go | 33 ++++++- cli/multisig.go | 103 +++++++--------------- 3 files changed, 74 insertions(+), 71 deletions(-) diff --git a/chain/actors/builtin/multisig/multisig.go b/chain/actors/builtin/multisig/multisig.go index 86a68c178..226eed75b 100644 --- a/chain/actors/builtin/multisig/multisig.go +++ b/chain/actors/builtin/multisig/multisig.go @@ -3,9 +3,12 @@ package multisig import ( "golang.org/x/xerrors" + "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/cbor" + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" + msig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig" "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/types" @@ -31,4 +34,10 @@ type State interface { StartEpoch() abi.ChainEpoch UnlockDuration() abi.ChainEpoch InitialBalance() abi.TokenAmount + Threshold() uint64 + Signers() []address.Address + + ForEachPendingTxn(func(id int64, txn Transaction) error) error } + +type Transaction = msig0.Transaction diff --git a/chain/actors/builtin/multisig/v0.go b/chain/actors/builtin/multisig/v0.go index 5de5ca6ad..e81a367cf 100644 --- a/chain/actors/builtin/multisig/v0.go +++ b/chain/actors/builtin/multisig/v0.go @@ -1,15 +1,21 @@ package multisig import ( + "encoding/binary" + + "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/lotus/chain/actors/adt" - "github.com/filecoin-project/specs-actors/actors/builtin/multisig" + "golang.org/x/xerrors" + + msig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig" + adt0 "github.com/filecoin-project/specs-actors/actors/util/adt" ) var _ State = (*state0)(nil) type state0 struct { - multisig.State + msig0.State store adt.Store } @@ -28,3 +34,26 @@ func (s *state0) UnlockDuration() abi.ChainEpoch { func (s *state0) InitialBalance() abi.TokenAmount { return s.State.InitialBalance } + +func (s *state0) Threshold() uint64 { + return s.State.NumApprovalsThreshold +} + +func (s *state0) Signers() []address.Address { + return s.State.Signers +} + +func (s *state0) ForEachPendingTxn(cb func(id int64, txn Transaction) error) error { + arr, err := adt0.AsMap(s.store, s.State.PendingTxns) + if err != nil { + return err + } + var out msig0.Transaction + return arr.ForEach(&out, func(key string) error { + txid, n := binary.Varint([]byte(key)) + if n <= 0 { + return xerrors.Errorf("invalid pending transaction key: %v", key) + } + return cb(txid, (Transaction)(out)) + }) +} diff --git a/cli/multisig.go b/cli/multisig.go index 23095bf06..2aabf5d7e 100644 --- a/cli/multisig.go +++ b/cli/multisig.go @@ -2,8 +2,6 @@ package cli import ( "bytes" - "context" - "encoding/binary" "encoding/hex" "fmt" "os" @@ -12,21 +10,21 @@ import ( "text/tabwriter" "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/filecoin-project/go-address" - init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" - msig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig" - cid "github.com/ipfs/go-cid" cbor "github.com/ipfs/go-ipld-cbor" "github.com/urfave/cli/v2" "golang.org/x/xerrors" - "github.com/filecoin-project/lotus/api" + "github.com/filecoin-project/specs-actors/actors/builtin" + init0 "github.com/filecoin-project/specs-actors/actors/builtin/init" + msig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig" + "github.com/filecoin-project/lotus/api/apibstore" "github.com/filecoin-project/lotus/build" - types "github.com/filecoin-project/lotus/chain/types" + "github.com/filecoin-project/lotus/chain/actors/adt" + "github.com/filecoin-project/lotus/chain/actors/builtin/multisig" + "github.com/filecoin-project/lotus/chain/types" ) var multisigCmd = &cli.Command{ @@ -146,7 +144,7 @@ var msigCreateCmd = &cli.Command{ // get address of newly created miner - var execreturn init_.ExecReturn + var execreturn init0.ExecReturn if err := execreturn.UnmarshalCBOR(bytes.NewReader(wait.Receipt.Return)); err != nil { return err } @@ -179,50 +177,54 @@ var msigInspectCmd = &cli.Command{ defer closer() ctx := ReqContext(cctx) + store := adt.WrapStore(ctx, cbor.NewCborStore(apibstore.NewAPIBlockstore(api))) + maddr, err := address.NewFromString(cctx.Args().First()) if err != nil { return err } - act, err := api.StateGetActor(ctx, maddr, types.EmptyTSK) - if err != nil { - return err - } - - obj, err := api.ChainReadObj(ctx, act.Head) - if err != nil { - return err - } - head, err := api.ChainHead(ctx) if err != nil { return err } - var mstate msig0.State - if err := mstate.UnmarshalCBOR(bytes.NewReader(obj)); err != nil { + act, err := api.StateGetActor(ctx, maddr, head.Key()) + if err != nil { + return err + } + + mstate, err := multisig.Load(store, act) + if err != nil { + return err + } + locked, err := mstate.LockedBalance(head.Height()) + if err != nil { return err } - locked := mstate.AmountLocked(head.Height() - mstate.StartEpoch) fmt.Printf("Balance: %s\n", types.FIL(act.Balance)) fmt.Printf("Spendable: %s\n", types.FIL(types.BigSub(act.Balance, locked))) if cctx.Bool("vesting") { - fmt.Printf("InitialBalance: %s\n", types.FIL(mstate.InitialBalance)) - fmt.Printf("StartEpoch: %d\n", mstate.StartEpoch) - fmt.Printf("UnlockDuration: %d\n", mstate.UnlockDuration) + fmt.Printf("InitialBalance: %s\n", types.FIL(mstate.InitialBalance())) + fmt.Printf("StartEpoch: %d\n", mstate.StartEpoch()) + fmt.Printf("UnlockDuration: %d\n", mstate.UnlockDuration()) } - fmt.Printf("Threshold: %d / %d\n", mstate.NumApprovalsThreshold, len(mstate.Signers)) + signers := mstate.Signers() + fmt.Printf("Threshold: %d / %d\n", mstate.Threshold(), len(signers)) fmt.Println("Signers:") - for _, s := range mstate.Signers { + for _, s := range signers { fmt.Printf("\t%s\n", s) } - pending, err := GetMultisigPending(ctx, api, mstate.PendingTxns) - if err != nil { - return fmt.Errorf("reading pending transactions: %w", err) + pending := make(map[int64]multisig.Transaction) + if err := mstate.ForEachPendingTxn(func(id int64, txn multisig.Transaction) error { + pending[id] = txn + return nil + }); err != nil { + return xerrors.Errorf("reading pending transactions: %w", err) } fmt.Println("Transactions: ", len(pending)) @@ -239,7 +241,7 @@ var msigInspectCmd = &cli.Command{ fmt.Fprintf(w, "ID\tState\tApprovals\tTo\tValue\tMethod\tParams\n") for _, txid := range txids { tx := pending[txid] - fmt.Fprintf(w, "%d\t%s\t%d\t%s\t%s\t%d\t%x\n", txid, state(tx), len(tx.Approved), tx.To, types.FIL(tx.Value), tx.Method, tx.Params) + fmt.Fprintf(w, "%d\t%s\t%d\t%s\t%s\t%d\t%x\n", txid, "pending", len(tx.Approved), tx.To, types.FIL(tx.Value), tx.Method, tx.Params) } if err := w.Flush(); err != nil { return xerrors.Errorf("flushing output: %+v", err) @@ -251,43 +253,6 @@ var msigInspectCmd = &cli.Command{ }, } -func GetMultisigPending(ctx context.Context, lapi api.FullNode, hroot cid.Cid) (map[int64]*msig0.Transaction, error) { - bs := apibstore.NewAPIBlockstore(lapi) - store := adt.WrapStore(ctx, cbor.NewCborStore(bs)) - - nd, err := adt.AsMap(store, hroot) - if err != nil { - return nil, err - } - - txs := make(map[int64]*msig0.Transaction) - var tx msig0.Transaction - err = nd.ForEach(&tx, func(k string) error { - txid, _ := binary.Varint([]byte(k)) - - cpy := tx // copy so we don't clobber on future iterations. - txs[txid] = &cpy - return nil - }) - if err != nil { - return nil, xerrors.Errorf("failed to iterate transactions hamt: %w", err) - } - - return txs, nil -} - -func state(tx *msig0.Transaction) string { - /* // TODO(why): I strongly disagree with not having these... but i need to move forward - if tx.Complete { - return "done" - } - if tx.Canceled { - return "canceled" - } - */ - return "pending" -} - var msigProposeCmd = &cli.Command{ Name: "propose", Usage: "Propose a multisig transaction", From a41bf74badf8586ebb20bcdba01d14cf006e5ff4 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Mon, 21 Sep 2020 13:25:03 -0700 Subject: [PATCH 144/303] fix: remove incorrect variable --- chain/actors/builtin/miner/miner.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index cf5eea742..ab2043954 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -18,8 +18,6 @@ import ( "github.com/filecoin-project/lotus/chain/types" ) -var Address = builtin0.InitActorAddr - func Load(store adt.Store, act *types.Actor) (st State, err error) { switch act.Code { case builtin0.StorageMinerActorCodeID: From 916421b247b8a075ca808c139df7dd52aa396f81 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Mon, 21 Sep 2020 13:43:47 -0700 Subject: [PATCH 145/303] convert lotus-shed balances --- chain/actors/builtin/miner/miner.go | 10 ++++++++ chain/actors/builtin/miner/v0.go | 15 ++++++++++++ cmd/lotus-shed/balances.go | 37 ++++++++++++++++------------- 3 files changed, 46 insertions(+), 16 deletions(-) diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index ab2043954..5f1c26013 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -18,6 +18,15 @@ import ( "github.com/filecoin-project/lotus/chain/types" ) +// Returns true if the specified actor code ID is a miner actor. +func Is(code cid.Cid) bool { + switch code { + case builtin0.StorageMinerActorCodeID: + return true + } + return false +} + func Load(store adt.Store, act *types.Actor) (st State, err error) { switch act.Code { case builtin0.StorageMinerActorCodeID: @@ -46,6 +55,7 @@ type State interface { GetSectorExpiration(abi.SectorNumber) (*SectorExpiration, error) GetPrecommittedSector(abi.SectorNumber) (*SectorPreCommitOnChainInfo, error) LoadSectors(sectorNos *bitfield.BitField) ([]*SectorOnChainInfo, error) + NumLiveSectors() (uint64, error) IsAllocated(abi.SectorNumber) (bool, error) LoadDeadline(idx uint64) (Deadline, error) diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index 30ce7e73e..a56778156 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -79,6 +79,21 @@ func (s *state0) FindSector(num abi.SectorNumber) (*SectorLocation, error) { }, nil } +func (s *state0) NumLiveSectors() (uint64, error) { + dls, err := s.State.LoadDeadlines(s.store) + if err != nil { + return 0, err + } + var total uint64 + if err := dls.ForEach(s.store, func(dlIdx uint64, dl *miner0.Deadline) error { + total += dl.LiveSectors + return nil + }); err != nil { + return 0, err + } + return total, nil +} + // GetSectorExpiration returns the effective expiration of the given sector. // // If the sector isn't found or has already been terminated, this method returns diff --git a/cmd/lotus-shed/balances.go b/cmd/lotus-shed/balances.go index 248f3b26e..413f86375 100644 --- a/cmd/lotus-shed/balances.go +++ b/cmd/lotus-shed/balances.go @@ -12,6 +12,8 @@ import ( "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/lotus/chain/actors/adt" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/stmgr" "github.com/filecoin-project/lotus/chain/store" @@ -21,9 +23,6 @@ import ( "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" "github.com/filecoin-project/lotus/lib/blockstore" "github.com/filecoin-project/lotus/node/repo" - "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/filecoin-project/specs-actors/actors/util/adt" ) type accountInfo struct { @@ -90,7 +89,7 @@ var chainBalanceCmd = &cli.Command{ Type: string(act.Code.Hash()[2:]), } - if act.Code == builtin.StorageMinerActorCodeID { + if miner.Is(act.Code) { pow, err := api.StateMinerPower(ctx, addr, tsk) if err != nil { return xerrors.Errorf("failed to get power: %w", err) @@ -167,6 +166,7 @@ var chainBalanceStateCmd = &cli.Command{ cs := store.NewChainStore(bs, mds, vm.Syscalls(ffiwrapper.ProofVerifier)) cst := cbor.NewCborStore(bs) + store := adt.WrapStore(ctx, cst) sm := stmgr.NewStateManager(cs) @@ -191,7 +191,7 @@ var chainBalanceStateCmd = &cli.Command{ PreCommits: types.FIL(big.NewInt(0)), } - if act.Code == builtin.StorageMinerActorCodeID && minerInfo { + if minerInfo && miner.Is(act.Code) { pow, _, _, err := stmgr.GetPowerRaw(ctx, sm, sroot, addr) if err != nil { return xerrors.Errorf("failed to get power: %w", err) @@ -199,24 +199,29 @@ var chainBalanceStateCmd = &cli.Command{ ai.Power = pow.RawBytePower - var st miner.State - if err := cst.Get(ctx, act.Head, &st); err != nil { + st, err := miner.Load(store, act) + if err != nil { return xerrors.Errorf("failed to read miner state: %w", err) } - sectors, err := adt.AsArray(cs.Store(ctx), st.Sectors) + liveSectorCount, err := st.NumLiveSectors() if err != nil { - return xerrors.Errorf("failed to load sector set: %w", err) + return xerrors.Errorf("failed to compute live sector count: %w", err) } - ai.InitialPledge = types.FIL(st.InitialPledgeRequirement) - ai.LockedFunds = types.FIL(st.LockedFunds) - ai.PreCommits = types.FIL(st.PreCommitDeposits) - ai.Sectors = sectors.Length() + lockedFunds, err := st.LockedFunds() + if err != nil { + return xerrors.Errorf("failed to compute locked funds: %w", err) + } - var minfo miner.MinerInfo - if err := cst.Get(ctx, st.Info, &minfo); err != nil { - return xerrors.Errorf("failed to read miner info: %w", err) + ai.InitialPledge = types.FIL(lockedFunds.InitialPledgeRequirement) + ai.LockedFunds = types.FIL(lockedFunds.VestingFunds) + ai.PreCommits = types.FIL(lockedFunds.PreCommitDeposits) + ai.Sectors = liveSectorCount + + minfo, err := st.Info() + if err != nil { + return xerrors.Errorf("failed to get miner info: %w", err) } ai.Worker = minfo.Worker From 4bab784e401bcaec79a30ac0a36b75cc98e73fdd Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Mon, 21 Sep 2020 15:04:39 -0700 Subject: [PATCH 146/303] migrate lotus-shed verifreg to specs-actors abstractions --- chain/actors/builtin/verifreg/v0.go | 40 ++++++++- chain/actors/builtin/verifreg/verifreg.go | 3 + cmd/lotus-shed/verifreg.go | 100 ++++++++-------------- 3 files changed, 76 insertions(+), 67 deletions(-) diff --git a/chain/actors/builtin/verifreg/v0.go b/chain/actors/builtin/verifreg/v0.go index f64c27310..c59a58811 100644 --- a/chain/actors/builtin/verifreg/v0.go +++ b/chain/actors/builtin/verifreg/v0.go @@ -6,6 +6,7 @@ import ( "github.com/filecoin-project/go-state-types/big" verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" adt0 "github.com/filecoin-project/specs-actors/actors/util/adt" + "github.com/ipfs/go-cid" "golang.org/x/xerrors" "github.com/filecoin-project/lotus/chain/actors/adt" @@ -18,22 +19,53 @@ type state0 struct { store adt.Store } -func (s *state0) VerifiedClientDataCap(addr address.Address) (bool, abi.StoragePower, error) { +func getDataCap(store adt.Store, root cid.Cid, addr address.Address) (bool, abi.StoragePower, error) { if addr.Protocol() != address.ID { return false, big.Zero(), xerrors.Errorf("can only look up ID addresses") } - vh, err := adt0.AsMap(s.store, s.VerifiedClients) + vh, err := adt0.AsMap(store, root) if err != nil { - return false, big.Zero(), xerrors.Errorf("loading verified clients: %w", err) + return false, big.Zero(), xerrors.Errorf("loading verifreg: %w", err) } var dcap abi.StoragePower if found, err := vh.Get(abi.AddrKey(addr), &dcap); err != nil { - return false, big.Zero(), xerrors.Errorf("looking up verified clients: %w", err) + return false, big.Zero(), xerrors.Errorf("looking up addr: %w", err) } else if !found { return false, big.Zero(), nil } return true, dcap, nil } + +func (s *state0) VerifiedClientDataCap(addr address.Address) (bool, abi.StoragePower, error) { + return getDataCap(s.store, s.State.VerifiedClients, addr) +} + +func (s *state0) VerifierDataCap(addr address.Address) (bool, abi.StoragePower, error) { + return getDataCap(s.store, s.State.Verifiers, addr) +} + +func forEachCap(store adt.Store, root cid.Cid, cb func(addr address.Address, dcap abi.StoragePower) error) error { + vh, err := adt0.AsMap(store, root) + if err != nil { + return xerrors.Errorf("loading verified clients: %w", err) + } + var dcap abi.StoragePower + return vh.ForEach(&dcap, func(key string) error { + a, err := address.NewFromBytes([]byte(key)) + if err != nil { + return err + } + return cb(a, dcap) + }) +} + +func (s *state0) ForEachVerifier(cb func(addr address.Address, dcap abi.StoragePower) error) error { + return forEachCap(s.store, s.State.Verifiers, cb) +} + +func (s *state0) ForEachClient(cb func(addr address.Address, dcap abi.StoragePower) error) error { + return forEachCap(s.store, s.State.VerifiedClients, cb) +} diff --git a/chain/actors/builtin/verifreg/verifreg.go b/chain/actors/builtin/verifreg/verifreg.go index 000a94349..c861f862f 100644 --- a/chain/actors/builtin/verifreg/verifreg.go +++ b/chain/actors/builtin/verifreg/verifreg.go @@ -31,4 +31,7 @@ type State interface { cbor.Marshaler VerifiedClientDataCap(address.Address) (bool, abi.StoragePower, error) + VerifierDataCap(address.Address) (bool, abi.StoragePower, error) + ForEachVerifier(func(addr address.Address, dcap abi.StoragePower) error) error + ForEachClient(func(addr address.Address, dcap abi.StoragePower) error) error } diff --git a/cmd/lotus-shed/verifreg.go b/cmd/lotus-shed/verifreg.go index 9f475261d..3e2f34f4b 100644 --- a/cmd/lotus-shed/verifreg.go +++ b/cmd/lotus-shed/verifreg.go @@ -8,13 +8,15 @@ import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" - "github.com/filecoin-project/specs-actors/actors/util/adt" + + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" + verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/lotus/api/apibstore" "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/actors" + "github.com/filecoin-project/lotus/chain/actors/adt" + "github.com/filecoin-project/lotus/chain/actors/builtin/verifreg" "github.com/filecoin-project/lotus/chain/types" lcli "github.com/filecoin-project/lotus/cli" cbor "github.com/ipfs/go-ipld-cbor" @@ -57,7 +59,7 @@ var verifRegAddVerifierCmd = &cli.Command{ return err } - params, err := actors.SerializeParams(&verifreg.AddVerifierParams{Address: target, Allowance: allowance}) + params, err := actors.SerializeParams(&verifreg0.AddVerifierParams{Address: target, Allowance: allowance}) if err != nil { return err } @@ -70,9 +72,9 @@ var verifRegAddVerifierCmd = &cli.Command{ ctx := lcli.ReqContext(cctx) msg := &types.Message{ - To: builtin.VerifiedRegistryActorAddr, + To: verifreg.Address, From: fromk, - Method: builtin.MethodsVerifiedRegistry.AddVerifier, + Method: builtin0.MethodsVerifiedRegistry.AddVerifier, Params: params, } @@ -131,7 +133,7 @@ var verifRegVerifyClientCmd = &cli.Command{ return err } - params, err := actors.SerializeParams(&verifreg.AddVerifiedClientParams{Address: target, Allowance: allowance}) + params, err := actors.SerializeParams(&verifreg0.AddVerifiedClientParams{Address: target, Allowance: allowance}) if err != nil { return err } @@ -144,9 +146,9 @@ var verifRegVerifyClientCmd = &cli.Command{ ctx := lcli.ReqContext(cctx) msg := &types.Message{ - To: builtin.VerifiedRegistryActorAddr, + To: verifreg.Address, From: fromk, - Method: builtin.MethodsVerifiedRegistry.AddVerifiedClient, + Method: builtin0.MethodsVerifiedRegistry.AddVerifiedClient, Params: params, } @@ -181,7 +183,7 @@ var verifRegListVerifiersCmd = &cli.Command{ defer closer() ctx := lcli.ReqContext(cctx) - act, err := api.StateGetActor(ctx, builtin.VerifiedRegistryActorAddr, types.EmptyTSK) + act, err := api.StateGetActor(ctx, verifreg.Address, types.EmptyTSK) if err != nil { return err } @@ -189,31 +191,14 @@ var verifRegListVerifiersCmd = &cli.Command{ apibs := apibstore.NewAPIBlockstore(api) store := adt.WrapStore(ctx, cbor.NewCborStore(apibs)) - var st verifreg.State - if err := store.Get(ctx, act.Head, &st); err != nil { - return err - } - - vh, err := adt.AsMap(store, st.Verifiers) + st, err := verifreg.Load(store, act) if err != nil { return err } - - var dcap verifreg.DataCap - if err := vh.ForEach(&dcap, func(k string) error { - addr, err := address.NewFromBytes([]byte(k)) - if err != nil { - return err - } - - fmt.Printf("%s: %s\n", addr, dcap) - - return nil - }); err != nil { + return st.ForEachVerifier(func(addr address.Address, dcap abi.StoragePower) error { + _, err := fmt.Printf("%s: %s\n", addr, dcap) return err - } - - return nil + }) }, } @@ -228,7 +213,7 @@ var verifRegListClientsCmd = &cli.Command{ defer closer() ctx := lcli.ReqContext(cctx) - act, err := api.StateGetActor(ctx, builtin.VerifiedRegistryActorAddr, types.EmptyTSK) + act, err := api.StateGetActor(ctx, verifreg.Address, types.EmptyTSK) if err != nil { return err } @@ -236,31 +221,14 @@ var verifRegListClientsCmd = &cli.Command{ apibs := apibstore.NewAPIBlockstore(api) store := adt.WrapStore(ctx, cbor.NewCborStore(apibs)) - var st verifreg.State - if err := store.Get(ctx, act.Head, &st); err != nil { - return err - } - - vh, err := adt.AsMap(store, st.VerifiedClients) + st, err := verifreg.Load(store, act) if err != nil { return err } - - var dcap verifreg.DataCap - if err := vh.ForEach(&dcap, func(k string) error { - addr, err := address.NewFromBytes([]byte(k)) - if err != nil { - return err - } - - fmt.Printf("%s: %s\n", addr, dcap) - - return nil - }); err != nil { + return st.ForEachClient(func(addr address.Address, dcap abi.StoragePower) error { + _, err := fmt.Printf("%s: %s\n", addr, dcap) return err - } - - return nil + }) }, } @@ -318,7 +286,17 @@ var verifRegCheckVerifierCmd = &cli.Command{ defer closer() ctx := lcli.ReqContext(cctx) - act, err := api.StateGetActor(ctx, builtin.VerifiedRegistryActorAddr, types.EmptyTSK) + head, err := api.ChainHead(ctx) + if err != nil { + return err + } + + vid, err := api.StateLookupID(ctx, vaddr, head.Key()) + if err != nil { + return err + } + + act, err := api.StateGetActor(ctx, verifreg.Address, head.Key()) if err != nil { return err } @@ -326,20 +304,16 @@ var verifRegCheckVerifierCmd = &cli.Command{ apibs := apibstore.NewAPIBlockstore(api) store := adt.WrapStore(ctx, cbor.NewCborStore(apibs)) - var st verifreg.State - if err := store.Get(ctx, act.Head, &st); err != nil { - return err - } - - vh, err := adt.AsMap(store, st.Verifiers) + st, err := verifreg.Load(store, act) if err != nil { return err } - var dcap verifreg.DataCap - if found, err := vh.Get(abi.AddrKey(vaddr), &dcap); err != nil { + found, dcap, err := st.VerifierDataCap(vid) + if err != nil { return err - } else if !found { + } + if !found { return fmt.Errorf("not found") } From 3f0106cfe5ba375b3e2ddad07dba8d5bef976a9b Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Mon, 21 Sep 2020 15:18:30 -0700 Subject: [PATCH 147/303] migrate lotus-shed/genesis-verify to actor abstraction --- chain/actors/builtin/miner/miner.go | 9 ------ chain/types/actor.go | 12 ++++++-- cmd/lotus-shed/balances.go | 4 +-- cmd/lotus-shed/genesis-verify.go | 48 ++++++++++++++++------------- cmd/lotus-shed/mempool-stats.go | 7 +++-- 5 files changed, 43 insertions(+), 37 deletions(-) diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index 5f1c26013..c2b2e3a0d 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -18,15 +18,6 @@ import ( "github.com/filecoin-project/lotus/chain/types" ) -// Returns true if the specified actor code ID is a miner actor. -func Is(code cid.Cid) bool { - switch code { - case builtin0.StorageMinerActorCodeID: - return true - } - return false -} - func Load(store adt.Store, act *types.Actor) (st State, err error) { switch act.Code { case builtin0.StorageMinerActorCodeID: diff --git a/chain/types/actor.go b/chain/types/actor.go index bb5635995..aa3ba2146 100644 --- a/chain/types/actor.go +++ b/chain/types/actor.go @@ -5,7 +5,7 @@ import ( "github.com/ipfs/go-cid" - "github.com/filecoin-project/specs-actors/actors/builtin" + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" ) var ErrActorNotFound = errors.New("actor not found") @@ -19,5 +19,13 @@ type Actor struct { } func (a *Actor) IsAccountActor() bool { - return a.Code == builtin.AccountActorCodeID + return a.Code == builtin0.AccountActorCodeID +} + +func (a *Actor) IsStorageMinerActor() bool { + return a.Code == builtin0.StorageMinerActorCodeID +} + +func (a *Actor) IsMultisigActor() bool { + return a.Code == builtin0.MultisigActorCodeID } diff --git a/cmd/lotus-shed/balances.go b/cmd/lotus-shed/balances.go index 413f86375..de92aa8b6 100644 --- a/cmd/lotus-shed/balances.go +++ b/cmd/lotus-shed/balances.go @@ -89,7 +89,7 @@ var chainBalanceCmd = &cli.Command{ Type: string(act.Code.Hash()[2:]), } - if miner.Is(act.Code) { + if act.IsStorageMinerActor() { pow, err := api.StateMinerPower(ctx, addr, tsk) if err != nil { return xerrors.Errorf("failed to get power: %w", err) @@ -191,7 +191,7 @@ var chainBalanceStateCmd = &cli.Command{ PreCommits: types.FIL(big.NewInt(0)), } - if minerInfo && miner.Is(act.Code) { + if minerInfo && act.IsStorageMinerActor() { pow, _, _, err := stmgr.GetPowerRaw(ctx, sm, sroot, addr) if err != nil { return xerrors.Errorf("failed to get power: %w", err) diff --git a/cmd/lotus-shed/genesis-verify.go b/cmd/lotus-shed/genesis-verify.go index 043cb72bb..1225d817a 100644 --- a/cmd/lotus-shed/genesis-verify.go +++ b/cmd/lotus-shed/genesis-verify.go @@ -14,16 +14,17 @@ import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/big" + "github.com/filecoin-project/lotus/build" + "github.com/filecoin-project/lotus/chain/actors/adt" + "github.com/filecoin-project/lotus/chain/actors/builtin/account" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + "github.com/filecoin-project/lotus/chain/actors/builtin/multisig" "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/stmgr" "github.com/filecoin-project/lotus/chain/store" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/lib/blockstore" - "github.com/filecoin-project/specs-actors/actors/builtin" - saacc "github.com/filecoin-project/specs-actors/actors/builtin/account" - saminer "github.com/filecoin-project/specs-actors/actors/builtin/miner" - samsig "github.com/filecoin-project/specs-actors/actors/builtin/multisig" ) type addrInfo struct { @@ -90,36 +91,41 @@ var genesisVerifyCmd = &cli.Command{ kminers := make(map[address.Address]minerInfo) ctx := context.TODO() + store := adt.WrapStore(ctx, cst) if err := stree.ForEach(func(addr address.Address, act *types.Actor) error { - switch act.Code { - case builtin.StorageMinerActorCodeID: - var st saminer.State - if err := cst.Get(ctx, act.Head, &st); err != nil { - return err + switch { + case act.IsStorageMinerActor(): + _, err := miner.Load(store, act) + if err != nil { + return xerrors.Errorf("miner actor: %w", err) } - + // TODO: actually verify something here? kminers[addr] = minerInfo{} - case builtin.MultisigActorCodeID: - var st samsig.State - if err := cst.Get(ctx, act.Head, &st); err != nil { + case act.IsMultisigActor(): + st, err := multisig.Load(store, act) + if err != nil { return xerrors.Errorf("multisig actor: %w", err) } kmultisigs[addr] = msigInfo{ Balance: types.FIL(act.Balance), - Signers: st.Signers, - Threshold: st.NumApprovalsThreshold, + Signers: st.Signers(), + Threshold: st.Threshold(), } msigAddrs = append(msigAddrs, addr) - case builtin.AccountActorCodeID: - var st saacc.State - if err := cst.Get(ctx, act.Head, &st); err != nil { - log.Warn(xerrors.Errorf("account actor %s: %w", addr, err)) + case act.IsAccountActor(): + st, err := account.Load(store, act) + if err != nil { + // TODO: magik6k: this _used_ to log instead of failing, why? + return xerrors.Errorf("account actor %s: %w", addr, err) + } + pkaddr, err := st.PubkeyAddress() + if err != nil { + return xerrors.Errorf("failed to get actor pk address %s: %w", addr, err) } - kaccounts[addr] = addrInfo{ - Key: st.Address, + Key: pkaddr, Balance: types.FIL(act.Balance.Copy()), } accAddrs = append(accAddrs, addr) diff --git a/cmd/lotus-shed/mempool-stats.go b/cmd/lotus-shed/mempool-stats.go index b81cf2704..165c01432 100644 --- a/cmd/lotus-shed/mempool-stats.go +++ b/cmd/lotus-shed/mempool-stats.go @@ -14,11 +14,12 @@ import ( "go.opencensus.io/stats/view" "go.opencensus.io/tag" + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" + "github.com/filecoin-project/go-address" lapi "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/chain/types" lcli "github.com/filecoin-project/lotus/cli" - "github.com/filecoin-project/specs-actors/actors/builtin" ) var ( @@ -121,7 +122,7 @@ var mpoolStatsCmd = &cli.Command{ return false, err } - ism := act.Code == builtin.StorageMinerActorCodeID + ism := act.IsStorageMinerActor() mcache[addr] = ism return ism, nil } @@ -143,7 +144,7 @@ var mpoolStatsCmd = &cli.Command{ seen: time.Now(), } - if u.Message.Message.Method == builtin.MethodsMiner.SubmitWindowedPoSt { + if u.Message.Message.Method == builtin0.MethodsMiner.SubmitWindowedPoSt { miner, err := isMiner(u.Message.Message.To) if err != nil { From 63f026f7c3fb52f894ed80d6fef7bdd1f7de8650 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Mon, 21 Sep 2020 15:24:45 -0700 Subject: [PATCH 148/303] migrate some more imports --- paychmgr/store.go | 15 ++++++++------- paychmgr/util.go | 11 ++++++----- storage/adapter_storage_miner.go | 7 ++++--- storage/miner.go | 6 +++--- storage/mockstorage/preseal.go | 5 +++-- storage/wdpost_run.go | 17 ++++++++--------- storage/wdpost_run_test.go | 13 ++++++------- 7 files changed, 38 insertions(+), 36 deletions(-) diff --git a/paychmgr/store.go b/paychmgr/store.go index 46249fa36..23916669e 100644 --- a/paychmgr/store.go +++ b/paychmgr/store.go @@ -12,12 +12,13 @@ import ( "github.com/filecoin-project/lotus/chain/types" cborutil "github.com/filecoin-project/go-cbor-util" - "github.com/filecoin-project/specs-actors/actors/builtin/paych" "github.com/ipfs/go-cid" "github.com/ipfs/go-datastore" "github.com/ipfs/go-datastore/namespace" dsq "github.com/ipfs/go-datastore/query" + paych0 "github.com/filecoin-project/specs-actors/actors/builtin/paych" + "github.com/filecoin-project/go-address" cborrpc "github.com/filecoin-project/go-cbor-util" @@ -48,7 +49,7 @@ const ( ) type VoucherInfo struct { - Voucher *paych.SignedVoucher + Voucher *paych0.SignedVoucher Proof []byte Submitted bool } @@ -102,7 +103,7 @@ func (ci *ChannelInfo) to() address.Address { // infoForVoucher gets the VoucherInfo for the given voucher. // returns nil if the channel doesn't have the voucher. -func (ci *ChannelInfo) infoForVoucher(sv *paych.SignedVoucher) (*VoucherInfo, error) { +func (ci *ChannelInfo) infoForVoucher(sv *paych0.SignedVoucher) (*VoucherInfo, error) { for _, v := range ci.Vouchers { eq, err := cborutil.Equals(sv, v.Voucher) if err != nil { @@ -115,7 +116,7 @@ func (ci *ChannelInfo) infoForVoucher(sv *paych.SignedVoucher) (*VoucherInfo, er return nil, nil } -func (ci *ChannelInfo) hasVoucher(sv *paych.SignedVoucher) (bool, error) { +func (ci *ChannelInfo) hasVoucher(sv *paych0.SignedVoucher) (bool, error) { vi, err := ci.infoForVoucher(sv) return vi != nil, err } @@ -123,7 +124,7 @@ func (ci *ChannelInfo) hasVoucher(sv *paych.SignedVoucher) (bool, error) { // markVoucherSubmitted marks the voucher, and any vouchers of lower nonce // in the same lane, as being submitted. // Note: This method doesn't write anything to the store. -func (ci *ChannelInfo) markVoucherSubmitted(sv *paych.SignedVoucher) error { +func (ci *ChannelInfo) markVoucherSubmitted(sv *paych0.SignedVoucher) error { vi, err := ci.infoForVoucher(sv) if err != nil { return err @@ -147,7 +148,7 @@ func (ci *ChannelInfo) markVoucherSubmitted(sv *paych.SignedVoucher) error { } // wasVoucherSubmitted returns true if the voucher has been submitted -func (ci *ChannelInfo) wasVoucherSubmitted(sv *paych.SignedVoucher) (bool, error) { +func (ci *ChannelInfo) wasVoucherSubmitted(sv *paych0.SignedVoucher) (bool, error) { vi, err := ci.infoForVoucher(sv) if err != nil { return false, err @@ -276,7 +277,7 @@ func (ps *Store) VouchersForPaych(ch address.Address) ([]*VoucherInfo, error) { return ci.Vouchers, nil } -func (ps *Store) MarkVoucherSubmitted(ci *ChannelInfo, sv *paych.SignedVoucher) error { +func (ps *Store) MarkVoucherSubmitted(ci *ChannelInfo, sv *paych0.SignedVoucher) error { err := ci.markVoucherSubmitted(sv) if err != nil { return err diff --git a/paychmgr/util.go b/paychmgr/util.go index 0509f8a24..2a8181c15 100644 --- a/paychmgr/util.go +++ b/paychmgr/util.go @@ -4,21 +4,22 @@ import ( "context" "github.com/filecoin-project/go-address" - "github.com/filecoin-project/specs-actors/actors/builtin/paych" + + paych0 "github.com/filecoin-project/specs-actors/actors/builtin/paych" ) type BestSpendableAPI interface { - PaychVoucherList(context.Context, address.Address) ([]*paych.SignedVoucher, error) - PaychVoucherCheckSpendable(context.Context, address.Address, *paych.SignedVoucher, []byte, []byte) (bool, error) + PaychVoucherList(context.Context, address.Address) ([]*paych0.SignedVoucher, error) + PaychVoucherCheckSpendable(context.Context, address.Address, *paych0.SignedVoucher, []byte, []byte) (bool, error) } -func BestSpendableByLane(ctx context.Context, api BestSpendableAPI, ch address.Address) (map[uint64]*paych.SignedVoucher, error) { +func BestSpendableByLane(ctx context.Context, api BestSpendableAPI, ch address.Address) (map[uint64]*paych0.SignedVoucher, error) { vouchers, err := api.PaychVoucherList(ctx, ch) if err != nil { return nil, err } - bestByLane := make(map[uint64]*paych.SignedVoucher) + bestByLane := make(map[uint64]*paych0.SignedVoucher) for _, voucher := range vouchers { spendable, err := api.PaychVoucherCheckSpendable(ctx, ch, voucher, nil, nil) if err != nil { diff --git a/storage/adapter_storage_miner.go b/storage/adapter_storage_miner.go index db3ae63d9..380fb4471 100644 --- a/storage/adapter_storage_miner.go +++ b/storage/adapter_storage_miner.go @@ -14,7 +14,8 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" - "github.com/filecoin-project/specs-actors/actors/builtin" + + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" market0 "github.com/filecoin-project/specs-actors/actors/builtin/market" "github.com/filecoin-project/lotus/api" @@ -146,10 +147,10 @@ func (s SealingAPIAdapter) StateComputeDataCommitment(ctx context.Context, maddr } ccmt := &types.Message{ - To: builtin.StorageMarketActorAddr, + To: market.Address, From: maddr, Value: types.NewInt(0), - Method: builtin.MethodsMarket.ComputeDataCommitment, + Method: builtin0.MethodsMarket.ComputeDataCommitment, Params: ccparams, } r, err := s.delegate.StateCall(ctx, ccmt, tsk) diff --git a/storage/miner.go b/storage/miner.go index a64ee977e..c1b50fe89 100644 --- a/storage/miner.go +++ b/storage/miner.go @@ -6,13 +6,13 @@ import ( "time" miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" + proof0 "github.com/filecoin-project/specs-actors/actors/runtime/proof" "github.com/filecoin-project/go-state-types/network" "github.com/filecoin-project/go-state-types/dline" "github.com/filecoin-project/go-bitfield" - "github.com/filecoin-project/specs-actors/actors/runtime/proof" "github.com/ipfs/go-cid" "github.com/ipfs/go-datastore" @@ -235,9 +235,9 @@ func (wpp *StorageWpp) GenerateCandidates(ctx context.Context, randomness abi.Po return cds, nil } -func (wpp *StorageWpp) ComputeProof(ctx context.Context, ssi []proof.SectorInfo, rand abi.PoStRandomness) ([]proof.PoStProof, error) { +func (wpp *StorageWpp) ComputeProof(ctx context.Context, ssi []proof0.SectorInfo, rand abi.PoStRandomness) ([]proof0.PoStProof, error) { if build.InsecurePoStValidation { - return []proof.PoStProof{{ProofBytes: []byte("valid proof")}}, nil + return []proof0.PoStProof{{ProofBytes: []byte("valid proof")}}, nil } log.Infof("Computing WinningPoSt ;%+v; %v", ssi, rand) diff --git a/storage/mockstorage/preseal.go b/storage/mockstorage/preseal.go index da063020d..8ca789ba6 100644 --- a/storage/mockstorage/preseal.go +++ b/storage/mockstorage/preseal.go @@ -9,7 +9,8 @@ import ( "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/lotus/extern/sector-storage/mock" - "github.com/filecoin-project/specs-actors/actors/builtin/market" + + market0 "github.com/filecoin-project/specs-actors/actors/builtin/market" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/wallet" @@ -48,7 +49,7 @@ func PreSeal(ssize abi.SectorSize, maddr address.Address, sectors int) (*genesis r := mock.CommDR(d) preseal.CommR, _ = commcid.ReplicaCommitmentV1ToCID(r[:]) preseal.SectorID = abi.SectorNumber(i + 1) - preseal.Deal = market.DealProposal{ + preseal.Deal = market0.DealProposal{ PieceCID: preseal.CommD, PieceSize: abi.PaddedPieceSize(ssize), Client: k.Address, diff --git a/storage/wdpost_run.go b/storage/wdpost_run.go index 254a2f0d3..9a497f879 100644 --- a/storage/wdpost_run.go +++ b/storage/wdpost_run.go @@ -5,8 +5,6 @@ import ( "context" "time" - "github.com/filecoin-project/specs-actors/actors/runtime/proof" - "github.com/filecoin-project/go-bitfield" "github.com/filecoin-project/go-address" @@ -14,20 +12,21 @@ import ( "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/go-state-types/dline" - "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/ipfs/go-cid" "go.opencensus.io/trace" "golang.org/x/xerrors" + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" + "github.com/filecoin-project/specs-actors/actors/runtime/proof" + "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/actors" "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/journal" - - miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" ) func (s *WindowPoStScheduler) failPost(err error, deadline *dline.Info) { @@ -219,7 +218,7 @@ func (s *WindowPoStScheduler) checkNextRecoveries(ctx context.Context, dlIdx uin msg := &types.Message{ To: s.actor, From: s.worker, - Method: builtin.MethodsMiner.DeclareFaultsRecovered, + Method: builtin0.MethodsMiner.DeclareFaultsRecovered, Params: enc, Value: types.NewInt(0), } @@ -298,7 +297,7 @@ func (s *WindowPoStScheduler) checkNextFaults(ctx context.Context, dlIdx uint64, msg := &types.Message{ To: s.actor, From: s.worker, - Method: builtin.MethodsMiner.DeclareFaults, + Method: builtin0.MethodsMiner.DeclareFaults, Params: enc, Value: types.NewInt(0), // TODO: Is there a fee? } @@ -555,7 +554,7 @@ func (s *WindowPoStScheduler) runPost(ctx context.Context, di dline.Info, ts *ty func (s *WindowPoStScheduler) batchPartitions(partitions []api.Partition) ([][]api.Partition, error) { // Get the number of sectors allowed in a partition, for this proof size - sectorsPerPartition, err := builtin.PoStProofWindowPoStPartitionSectors(s.proofType) + sectorsPerPartition, err := builtin0.PoStProofWindowPoStPartitionSectors(s.proofType) if err != nil { return nil, xerrors.Errorf("getting sectors per partition: %w", err) } @@ -647,7 +646,7 @@ func (s *WindowPoStScheduler) submitPost(ctx context.Context, proof *miner.Submi msg := &types.Message{ To: s.actor, From: s.worker, - Method: builtin.MethodsMiner.SubmitWindowedPoSt, + Method: builtin0.MethodsMiner.SubmitWindowedPoSt, Params: enc, Value: types.NewInt(0), } diff --git a/storage/wdpost_run_test.go b/storage/wdpost_run_test.go index 1797cf35c..10be2fbcd 100644 --- a/storage/wdpost_run_test.go +++ b/storage/wdpost_run_test.go @@ -16,10 +16,9 @@ import ( "github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/go-state-types/dline" "github.com/filecoin-project/go-state-types/network" - "github.com/filecoin-project/specs-actors/actors/builtin" builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/filecoin-project/specs-actors/actors/runtime/proof" + proof0 "github.com/filecoin-project/specs-actors/actors/runtime/proof" tutils "github.com/filecoin-project/specs-actors/support/testing" "github.com/filecoin-project/lotus/api" @@ -97,12 +96,12 @@ func (m *mockStorageMinerAPI) StateWaitMsg(ctx context.Context, cid cid.Cid, con type mockProver struct { } -func (m *mockProver) GenerateWinningPoSt(context.Context, abi.ActorID, []proof.SectorInfo, abi.PoStRandomness) ([]proof.PoStProof, error) { +func (m *mockProver) GenerateWinningPoSt(context.Context, abi.ActorID, []proof0.SectorInfo, abi.PoStRandomness) ([]proof0.PoStProof, error) { panic("implement me") } -func (m *mockProver) GenerateWindowPoSt(ctx context.Context, aid abi.ActorID, sis []proof.SectorInfo, pr abi.PoStRandomness) ([]proof.PoStProof, []abi.SectorID, error) { - return []proof.PoStProof{ +func (m *mockProver) GenerateWindowPoSt(ctx context.Context, aid abi.ActorID, sis []proof0.SectorInfo, pr abi.PoStRandomness) ([]proof0.PoStProof, []abi.SectorID, error) { + return []proof0.PoStProof{ { PoStProof: abi.RegisteredPoStProof_StackedDrgWindow2KiBV1, ProofBytes: []byte("post-proof"), @@ -131,7 +130,7 @@ func TestWDPostDoPost(t *testing.T) { mockStgMinerAPI := newMockStorageMinerAPI() // Get the number of sectors allowed in a partition for this proof type - sectorsPerPartition, err := builtin.PoStProofWindowPoStPartitionSectors(proofType) + sectorsPerPartition, err := builtin0.PoStProofWindowPoStPartitionSectors(proofType) require.NoError(t, err) // Work out the number of partitions that can be included in a message // without exceeding the message sector limit @@ -183,7 +182,7 @@ func TestWDPostDoPost(t *testing.T) { // Read the window PoST messages for i := 0; i < expectedMsgCount; i++ { msg := <-mockStgMinerAPI.pushedMessages - require.Equal(t, builtin.MethodsMiner.SubmitWindowedPoSt, msg.Method) + require.Equal(t, builtin0.MethodsMiner.SubmitWindowedPoSt, msg.Method) var params miner.SubmitWindowedPoStParams err := params.UnmarshalCBOR(bytes.NewReader(msg.Params)) require.NoError(t, err) From d33dd4f7bc9bc79b0c6e7957ab115c430d97bc79 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Mon, 21 Sep 2020 16:01:29 -0700 Subject: [PATCH 149/303] more renames --- chain/types/actor.go | 4 +++ markets/storageadapter/provider.go | 26 ++++++++-------- miner/miner.go | 4 +-- node/impl/full/gas.go | 7 +++-- node/impl/full/multisig.go | 49 ++++++++++++++++-------------- node/impl/full/state.go | 10 +++--- node/impl/paych/paych.go | 21 +++++++------ paychmgr/settler/settler.go | 15 ++++----- paychmgr/simple.go | 6 ++-- 9 files changed, 77 insertions(+), 65 deletions(-) diff --git a/chain/types/actor.go b/chain/types/actor.go index aa3ba2146..eb8e05c49 100644 --- a/chain/types/actor.go +++ b/chain/types/actor.go @@ -29,3 +29,7 @@ func (a *Actor) IsStorageMinerActor() bool { func (a *Actor) IsMultisigActor() bool { return a.Code == builtin0.MultisigActorCodeID } + +func (a *Actor) IsPaymentChannelActor() bool { + return a.Code == builtin0.PaymentChannelActorCodeID +} diff --git a/markets/storageadapter/provider.go b/markets/storageadapter/provider.go index 04c1055df..9f610d76a 100644 --- a/markets/storageadapter/provider.go +++ b/markets/storageadapter/provider.go @@ -8,25 +8,27 @@ import ( "io" "time" - "github.com/filecoin-project/lotus/chain/actors/builtin/miner" - "github.com/ipfs/go-cid" logging "github.com/ipfs/go-log/v2" "golang.org/x/xerrors" + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" + market0 "github.com/filecoin-project/specs-actors/actors/builtin/market" + "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-fil-markets/shared" "github.com/filecoin-project/go-fil-markets/storagemarket" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/go-state-types/exitcode" - "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/market" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/actors" "github.com/filecoin-project/lotus/chain/events" + + "github.com/filecoin-project/lotus/chain/actors/builtin/market" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/events/state" "github.com/filecoin-project/lotus/chain/types" sealing "github.com/filecoin-project/lotus/extern/storage-sealing" @@ -67,8 +69,8 @@ func (n *ProviderNodeAdapter) PublishDeals(ctx context.Context, deal storagemark return cid.Undef, err } - params, err := actors.SerializeParams(&market.PublishStorageDealsParams{ - Deals: []market.ClientDealProposal{deal.ClientDealProposal}, + params, err := actors.SerializeParams(&market0.PublishStorageDealsParams{ + Deals: []market0.ClientDealProposal{deal.ClientDealProposal}, }) if err != nil { @@ -77,10 +79,10 @@ func (n *ProviderNodeAdapter) PublishDeals(ctx context.Context, deal storagemark // TODO: We may want this to happen after fetching data smsg, err := n.MpoolPushMessage(ctx, &types.Message{ - To: builtin.StorageMarketActorAddr, + To: market.Address, From: mi.Worker, Value: types.NewInt(0), - Method: builtin.MethodsMarket.PublishStorageDeals, + Method: builtin0.MethodsMarket.PublishStorageDeals, Params: params, }, nil) if err != nil { @@ -177,10 +179,10 @@ func (n *ProviderNodeAdapter) EnsureFunds(ctx context.Context, addr, wallet addr func (n *ProviderNodeAdapter) AddFunds(ctx context.Context, addr address.Address, amount abi.TokenAmount) (cid.Cid, error) { // (Provider Node API) smsg, err := n.MpoolPushMessage(ctx, &types.Message{ - To: builtin.StorageMarketActorAddr, + To: market.Address, From: addr, Value: amount, - Method: builtin.MethodsMarket.AddBalance, + Method: builtin0.MethodsMarket.AddBalance, }, nil) if err != nil { return cid.Undef, err @@ -302,7 +304,7 @@ func (n *ProviderNodeAdapter) OnDealSectorCommitted(ctx context.Context, provide } switch msg.Method { - case builtin.MethodsMiner.PreCommitSector: + case builtin0.MethodsMiner.PreCommitSector: var params miner.SectorPreCommitInfo if err := params.UnmarshalCBOR(bytes.NewReader(msg.Params)); err != nil { return true, false, xerrors.Errorf("unmarshal pre commit: %w", err) @@ -317,7 +319,7 @@ func (n *ProviderNodeAdapter) OnDealSectorCommitted(ctx context.Context, provide } return true, false, nil - case builtin.MethodsMiner.ProveCommitSector: + case builtin0.MethodsMiner.ProveCommitSector: var params miner.ProveCommitSectorParams if err := params.UnmarshalCBOR(bytes.NewReader(msg.Params)); err != nil { return true, false, xerrors.Errorf("failed to unmarshal prove commit sector params: %w", err) diff --git a/miner/miner.go b/miner/miner.go index 2d8591992..5e8d8cf37 100644 --- a/miner/miner.go +++ b/miner/miner.go @@ -9,7 +9,7 @@ import ( "sync" "time" - "github.com/filecoin-project/specs-actors/actors/runtime/proof" + proof0 "github.com/filecoin-project/specs-actors/actors/runtime/proof" "github.com/filecoin-project/lotus/chain/gen/slashfilter" @@ -489,7 +489,7 @@ func (m *Miner) computeTicket(ctx context.Context, brand *types.BeaconEntry, bas } func (m *Miner) createBlock(base *MiningBase, addr address.Address, ticket *types.Ticket, - eproof *types.ElectionProof, bvals []types.BeaconEntry, wpostProof []proof.PoStProof, msgs []*types.SignedMessage) (*types.BlockMsg, error) { + eproof *types.ElectionProof, bvals []types.BeaconEntry, wpostProof []proof0.PoStProof, msgs []*types.SignedMessage) (*types.BlockMsg, error) { uts := base.TipSet.MinTimestamp() + build.BlockDelaySecs*(uint64(base.NullRounds)+1) nheight := base.TipSet.Height() + base.NullRounds + 1 diff --git a/node/impl/full/gas.go b/node/impl/full/gas.go index b207a1f6d..f03807c80 100644 --- a/node/impl/full/gas.go +++ b/node/impl/full/gas.go @@ -13,7 +13,8 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/exitcode" - "github.com/filecoin-project/specs-actors/actors/builtin" + + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" @@ -181,10 +182,10 @@ func (a *GasAPI) GasEstimateGasLimit(ctx context.Context, msgIn *types.Message, return res.MsgRct.GasUsed, nil } - if !act.Code.Equals(builtin.PaymentChannelActorCodeID) { + if !act.IsPaymentChannelActor() { return res.MsgRct.GasUsed, nil } - if msgIn.Method != builtin.MethodsPaych.Collect { + if msgIn.Method != builtin0.MethodsPaych.Collect { return res.MsgRct.GasUsed, nil } diff --git a/node/impl/full/multisig.go b/node/impl/full/multisig.go index 2322d5a1e..8c15a27be 100644 --- a/node/impl/full/multisig.go +++ b/node/impl/full/multisig.go @@ -9,10 +9,12 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/chain/actors" + init_ "github.com/filecoin-project/lotus/chain/actors/builtin/init" "github.com/filecoin-project/lotus/chain/types" - "github.com/filecoin-project/specs-actors/actors/builtin" - init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" - samsig "github.com/filecoin-project/specs-actors/actors/builtin/multisig" + + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" + init0 "github.com/filecoin-project/specs-actors/actors/builtin/init" + multisig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig" "github.com/ipfs/go-cid" "github.com/minio/blake2b-simd" @@ -46,7 +48,7 @@ func (a *MsigAPI) MsigCreate(ctx context.Context, req uint64, addrs []address.Ad } // Set up constructor parameters for multisig - msigParams := &samsig.ConstructorParams{ + msigParams := &multisig0.ConstructorParams{ Signers: addrs, NumApprovalsThreshold: req, UnlockDuration: duration, @@ -58,8 +60,9 @@ func (a *MsigAPI) MsigCreate(ctx context.Context, req uint64, addrs []address.Ad } // new actors are created by invoking 'exec' on the init actor with the constructor params - execParams := &init_.ExecParams{ - CodeCID: builtin.MultisigActorCodeID, + // TODO: network upgrade? + execParams := &init0.ExecParams{ + CodeCID: builtin0.MultisigActorCodeID, ConstructorParams: enc, } @@ -70,9 +73,9 @@ func (a *MsigAPI) MsigCreate(ctx context.Context, req uint64, addrs []address.Ad // now we create the message to send this with msg := types.Message{ - To: builtin.InitActorAddr, + To: init_.Address, From: src, - Method: builtin.MethodsInit.Exec, + Method: builtin0.MethodsInit.Exec, Params: enc, Value: val, } @@ -104,7 +107,7 @@ func (a *MsigAPI) MsigPropose(ctx context.Context, msig address.Address, to addr return cid.Undef, xerrors.Errorf("must provide source address") } - enc, actErr := actors.SerializeParams(&samsig.ProposeParams{ + enc, actErr := actors.SerializeParams(&multisig0.ProposeParams{ To: to, Value: amt, Method: abi.MethodNum(method), @@ -118,7 +121,7 @@ func (a *MsigAPI) MsigPropose(ctx context.Context, msig address.Address, to addr To: msig, From: src, Value: types.NewInt(0), - Method: builtin.MethodsMultisig.Propose, + Method: builtin0.MethodsMultisig.Propose, Params: enc, } @@ -136,7 +139,7 @@ func (a *MsigAPI) MsigAddPropose(ctx context.Context, msig address.Address, src return cid.Undef, actErr } - return a.MsigPropose(ctx, msig, msig, big.Zero(), src, uint64(builtin.MethodsMultisig.AddSigner), enc) + return a.MsigPropose(ctx, msig, msig, big.Zero(), src, uint64(builtin0.MethodsMultisig.AddSigner), enc) } func (a *MsigAPI) MsigAddApprove(ctx context.Context, msig address.Address, src address.Address, txID uint64, proposer address.Address, newAdd address.Address, inc bool) (cid.Cid, error) { @@ -145,7 +148,7 @@ func (a *MsigAPI) MsigAddApprove(ctx context.Context, msig address.Address, src return cid.Undef, actErr } - return a.MsigApprove(ctx, msig, txID, proposer, msig, big.Zero(), src, uint64(builtin.MethodsMultisig.AddSigner), enc) + return a.MsigApprove(ctx, msig, txID, proposer, msig, big.Zero(), src, uint64(builtin0.MethodsMultisig.AddSigner), enc) } func (a *MsigAPI) MsigAddCancel(ctx context.Context, msig address.Address, src address.Address, txID uint64, newAdd address.Address, inc bool) (cid.Cid, error) { @@ -154,7 +157,7 @@ func (a *MsigAPI) MsigAddCancel(ctx context.Context, msig address.Address, src a return cid.Undef, actErr } - return a.MsigCancel(ctx, msig, txID, msig, big.Zero(), src, uint64(builtin.MethodsMultisig.AddSigner), enc) + return a.MsigCancel(ctx, msig, txID, msig, big.Zero(), src, uint64(builtin0.MethodsMultisig.AddSigner), enc) } func (a *MsigAPI) MsigSwapPropose(ctx context.Context, msig address.Address, src address.Address, oldAdd address.Address, newAdd address.Address) (cid.Cid, error) { @@ -163,7 +166,7 @@ func (a *MsigAPI) MsigSwapPropose(ctx context.Context, msig address.Address, src return cid.Undef, actErr } - return a.MsigPropose(ctx, msig, msig, big.Zero(), src, uint64(builtin.MethodsMultisig.SwapSigner), enc) + return a.MsigPropose(ctx, msig, msig, big.Zero(), src, uint64(builtin0.MethodsMultisig.SwapSigner), enc) } func (a *MsigAPI) MsigSwapApprove(ctx context.Context, msig address.Address, src address.Address, txID uint64, proposer address.Address, oldAdd address.Address, newAdd address.Address) (cid.Cid, error) { @@ -172,7 +175,7 @@ func (a *MsigAPI) MsigSwapApprove(ctx context.Context, msig address.Address, src return cid.Undef, actErr } - return a.MsigApprove(ctx, msig, txID, proposer, msig, big.Zero(), src, uint64(builtin.MethodsMultisig.SwapSigner), enc) + return a.MsigApprove(ctx, msig, txID, proposer, msig, big.Zero(), src, uint64(builtin0.MethodsMultisig.SwapSigner), enc) } func (a *MsigAPI) MsigSwapCancel(ctx context.Context, msig address.Address, src address.Address, txID uint64, oldAdd address.Address, newAdd address.Address) (cid.Cid, error) { @@ -181,7 +184,7 @@ func (a *MsigAPI) MsigSwapCancel(ctx context.Context, msig address.Address, src return cid.Undef, actErr } - return a.MsigCancel(ctx, msig, txID, msig, big.Zero(), src, uint64(builtin.MethodsMultisig.SwapSigner), enc) + return a.MsigCancel(ctx, msig, txID, msig, big.Zero(), src, uint64(builtin0.MethodsMultisig.SwapSigner), enc) } func (a *MsigAPI) MsigApprove(ctx context.Context, msig address.Address, txID uint64, proposer address.Address, to address.Address, amt types.BigInt, src address.Address, method uint64, params []byte) (cid.Cid, error) { @@ -217,7 +220,7 @@ func (a *MsigAPI) msigApproveOrCancel(ctx context.Context, operation api.MsigPro proposer = proposerID } - p := samsig.ProposalHashData{ + p := multisig0.ProposalHashData{ Requester: proposer, To: to, Value: amt, @@ -231,8 +234,8 @@ func (a *MsigAPI) msigApproveOrCancel(ctx context.Context, operation api.MsigPro } phash := blake2b.Sum256(pser) - enc, err := actors.SerializeParams(&samsig.TxnIDParams{ - ID: samsig.TxnID(txID), + enc, err := actors.SerializeParams(&multisig0.TxnIDParams{ + ID: multisig0.TxnID(txID), ProposalHash: phash[:], }) @@ -248,9 +251,9 @@ func (a *MsigAPI) msigApproveOrCancel(ctx context.Context, operation api.MsigPro */ switch operation { case api.MsigApprove: - msigResponseMethod = builtin.MethodsMultisig.Approve + msigResponseMethod = builtin0.MethodsMultisig.Approve case api.MsigCancel: - msigResponseMethod = builtin.MethodsMultisig.Cancel + msigResponseMethod = builtin0.MethodsMultisig.Cancel default: return cid.Undef, xerrors.Errorf("Invalid operation for msigApproveOrCancel") } @@ -272,7 +275,7 @@ func (a *MsigAPI) msigApproveOrCancel(ctx context.Context, operation api.MsigPro } func serializeAddParams(new address.Address, inc bool) ([]byte, error) { - enc, actErr := actors.SerializeParams(&samsig.AddSignerParams{ + enc, actErr := actors.SerializeParams(&multisig0.AddSignerParams{ Signer: new, Increase: inc, }) @@ -284,7 +287,7 @@ func serializeAddParams(new address.Address, inc bool) ([]byte, error) { } func serializeSwapParams(old address.Address, new address.Address) ([]byte, error) { - enc, actErr := actors.SerializeParams(&samsig.SwapSignerParams{ + enc, actErr := actors.SerializeParams(&multisig0.SwapSignerParams{ From: old, To: new, }) diff --git a/node/impl/full/state.go b/node/impl/full/state.go index df747ba3f..0b2d86718 100644 --- a/node/impl/full/state.go +++ b/node/impl/full/state.go @@ -7,7 +7,9 @@ import ( builtin2 "github.com/filecoin-project/lotus/chain/actors/builtin" + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" market0 "github.com/filecoin-project/specs-actors/actors/builtin/market" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/actors/builtin/verifreg" @@ -24,8 +26,6 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" - "github.com/filecoin-project/specs-actors/actors/builtin" - miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/chain/actors/builtin/market" @@ -1025,7 +1025,7 @@ func (a *StateAPI) StateMinerAvailableBalance(ctx context.Context, maddr address // Returns zero if there is no entry in the data cap table for the // address. func (a *StateAPI) StateVerifiedClientStatus(ctx context.Context, addr address.Address, tsk types.TipSetKey) (*abi.StoragePower, error) { - act, err := a.StateGetActor(ctx, builtin.VerifiedRegistryActorAddr, tsk) + act, err := a.StateGetActor(ctx, builtin0.VerifiedRegistryActorAddr, tsk) if err != nil { return nil, err } @@ -1063,12 +1063,12 @@ func (a *StateAPI) StateDealProviderCollateralBounds(ctx context.Context, size a return api.DealCollateralBounds{}, xerrors.Errorf("loading tipset %s: %w", tsk, err) } - pact, err := a.StateGetActor(ctx, builtin.StoragePowerActorAddr, tsk) + pact, err := a.StateGetActor(ctx, builtin0.StoragePowerActorAddr, tsk) if err != nil { return api.DealCollateralBounds{}, xerrors.Errorf("failed to load power actor: %w", err) } - ract, err := a.StateGetActor(ctx, builtin.RewardActorAddr, tsk) + ract, err := a.StateGetActor(ctx, builtin0.RewardActorAddr, tsk) if err != nil { return api.DealCollateralBounds{}, xerrors.Errorf("failed to load reward actor: %w", err) } diff --git a/node/impl/paych/paych.go b/node/impl/paych/paych.go index 94fcc320d..b2e6be0ca 100644 --- a/node/impl/paych/paych.go +++ b/node/impl/paych/paych.go @@ -9,7 +9,8 @@ import ( "go.uber.org/fx" "github.com/filecoin-project/go-address" - "github.com/filecoin-project/specs-actors/actors/builtin/paych" + + paych0 "github.com/filecoin-project/specs-actors/actors/builtin/paych" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/chain/types" @@ -70,10 +71,10 @@ func (a *PaychAPI) PaychNewPayment(ctx context.Context, from, to address.Address return nil, err } - svs := make([]*paych.SignedVoucher, len(vouchers)) + svs := make([]*paych0.SignedVoucher, len(vouchers)) for i, v := range vouchers { - sv, err := a.PaychMgr.CreateVoucher(ctx, ch.Channel, paych.SignedVoucher{ + sv, err := a.PaychMgr.CreateVoucher(ctx, ch.Channel, paych0.SignedVoucher{ Amount: v.Amount, Lane: lane, @@ -122,15 +123,15 @@ func (a *PaychAPI) PaychCollect(ctx context.Context, addr address.Address) (cid. return a.PaychMgr.Collect(ctx, addr) } -func (a *PaychAPI) PaychVoucherCheckValid(ctx context.Context, ch address.Address, sv *paych.SignedVoucher) error { +func (a *PaychAPI) PaychVoucherCheckValid(ctx context.Context, ch address.Address, sv *paych0.SignedVoucher) error { return a.PaychMgr.CheckVoucherValid(ctx, ch, sv) } -func (a *PaychAPI) PaychVoucherCheckSpendable(ctx context.Context, ch address.Address, sv *paych.SignedVoucher, secret []byte, proof []byte) (bool, error) { +func (a *PaychAPI) PaychVoucherCheckSpendable(ctx context.Context, ch address.Address, sv *paych0.SignedVoucher, secret []byte, proof []byte) (bool, error) { return a.PaychMgr.CheckVoucherSpendable(ctx, ch, sv, secret, proof) } -func (a *PaychAPI) PaychVoucherAdd(ctx context.Context, ch address.Address, sv *paych.SignedVoucher, proof []byte, minDelta types.BigInt) (types.BigInt, error) { +func (a *PaychAPI) PaychVoucherAdd(ctx context.Context, ch address.Address, sv *paych0.SignedVoucher, proof []byte, minDelta types.BigInt) (types.BigInt, error) { return a.PaychMgr.AddVoucherInbound(ctx, ch, sv, proof, minDelta) } @@ -142,16 +143,16 @@ func (a *PaychAPI) PaychVoucherAdd(ctx context.Context, ch address.Address, sv * // If there are insufficient funds in the channel to create the voucher, // returns a nil voucher and the shortfall. func (a *PaychAPI) PaychVoucherCreate(ctx context.Context, pch address.Address, amt types.BigInt, lane uint64) (*api.VoucherCreateResult, error) { - return a.PaychMgr.CreateVoucher(ctx, pch, paych.SignedVoucher{Amount: amt, Lane: lane}) + return a.PaychMgr.CreateVoucher(ctx, pch, paych0.SignedVoucher{Amount: amt, Lane: lane}) } -func (a *PaychAPI) PaychVoucherList(ctx context.Context, pch address.Address) ([]*paych.SignedVoucher, error) { +func (a *PaychAPI) PaychVoucherList(ctx context.Context, pch address.Address) ([]*paych0.SignedVoucher, error) { vi, err := a.PaychMgr.ListVouchers(ctx, pch) if err != nil { return nil, err } - out := make([]*paych.SignedVoucher, len(vi)) + out := make([]*paych0.SignedVoucher, len(vi)) for k, v := range vi { out[k] = v.Voucher } @@ -159,6 +160,6 @@ func (a *PaychAPI) PaychVoucherList(ctx context.Context, pch address.Address) ([ return out, nil } -func (a *PaychAPI) PaychVoucherSubmit(ctx context.Context, ch address.Address, sv *paych.SignedVoucher, secret []byte, proof []byte) (cid.Cid, error) { +func (a *PaychAPI) PaychVoucherSubmit(ctx context.Context, ch address.Address, sv *paych0.SignedVoucher, secret []byte, proof []byte) (cid.Cid, error) { return a.PaychMgr.SubmitVoucher(ctx, ch, sv, secret, proof) } diff --git a/paychmgr/settler/settler.go b/paychmgr/settler/settler.go index 45f24cdd9..654ed66cc 100644 --- a/paychmgr/settler/settler.go +++ b/paychmgr/settler/settler.go @@ -13,8 +13,9 @@ import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/paych" + + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" + paych0 "github.com/filecoin-project/specs-actors/actors/builtin/paych" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" @@ -38,9 +39,9 @@ type API struct { type settlerAPI interface { PaychList(context.Context) ([]address.Address, error) PaychStatus(context.Context, address.Address) (*api.PaychStatus, error) - PaychVoucherCheckSpendable(context.Context, address.Address, *paych.SignedVoucher, []byte, []byte) (bool, error) - PaychVoucherList(context.Context, address.Address) ([]*paych.SignedVoucher, error) - PaychVoucherSubmit(context.Context, address.Address, *paych.SignedVoucher, []byte, []byte) (cid.Cid, error) + PaychVoucherCheckSpendable(context.Context, address.Address, *paych0.SignedVoucher, []byte, []byte) (bool, error) + PaychVoucherList(context.Context, address.Address) ([]*paych0.SignedVoucher, error) + PaychVoucherSubmit(context.Context, address.Address, *paych0.SignedVoucher, []byte, []byte) (cid.Cid, error) StateWaitMsg(ctx context.Context, cid cid.Cid, confidence uint64) (*api.MsgLookup, error) } @@ -85,7 +86,7 @@ func (pcs *paymentChannelSettler) messageHandler(msg *types.Message, rec *types. if err != nil { return true, err } - go func(voucher *paych.SignedVoucher, submitMessageCID cid.Cid) { + go func(voucher *paych0.SignedVoucher, submitMessageCID cid.Cid) { defer wg.Done() msgLookup, err := pcs.api.StateWaitMsg(pcs.ctx, submitMessageCID, build.MessageConfidence) if err != nil { @@ -106,7 +107,7 @@ func (pcs *paymentChannelSettler) revertHandler(ctx context.Context, ts *types.T func (pcs *paymentChannelSettler) matcher(msg *types.Message) (matchOnce bool, matched bool, err error) { // Check if this is a settle payment channel message - if msg.Method != builtin.MethodsPaych.Settle { + if msg.Method != builtin0.MethodsPaych.Settle { return false, false, nil } // Check if this payment channel is of concern to this node (i.e. tracked in payment channel store), diff --git a/paychmgr/simple.go b/paychmgr/simple.go index 46bbea62e..815b8acab 100644 --- a/paychmgr/simple.go +++ b/paychmgr/simple.go @@ -13,7 +13,7 @@ import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/specs-actors/actors/builtin" - init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" + init0 "github.com/filecoin-project/specs-actors/actors/builtin/init" paych0 "github.com/filecoin-project/specs-actors/actors/builtin/paych" "github.com/filecoin-project/lotus/api" @@ -387,7 +387,7 @@ func (ca *channelAccessor) createPaych(ctx context.Context, amt types.BigInt) (c return cid.Undef, aerr } - enc, aerr := actors.SerializeParams(&init_.ExecParams{ + enc, aerr := actors.SerializeParams(&init0.ExecParams{ CodeCID: builtin.PaymentChannelActorCodeID, ConstructorParams: params, }) @@ -452,7 +452,7 @@ func (ca *channelAccessor) waitPaychCreateMsg(channelID string, mcid cid.Cid) er return err } - var decodedReturn init_.ExecReturn + var decodedReturn init0.ExecReturn err = decodedReturn.UnmarshalCBOR(bytes.NewReader(mwait.Receipt.Return)) if err != nil { log.Error(err) From d56da1b014b24c6d163f60546c51462ab968f383 Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Tue, 22 Sep 2020 00:12:07 -0400 Subject: [PATCH 150/303] Refinements to stmgr and utils --- chain/actors/builtin/builtin.go | 8 +++ chain/actors/builtin/reward/reward.go | 3 ++ chain/stmgr/stmgr.go | 75 ++++++++++++--------------- chain/stmgr/utils.go | 15 ++---- node/impl/full/state.go | 19 +++---- 5 files changed, 56 insertions(+), 64 deletions(-) diff --git a/chain/actors/builtin/builtin.go b/chain/actors/builtin/builtin.go index 9ad976564..3230705dd 100644 --- a/chain/actors/builtin/builtin.go +++ b/chain/actors/builtin/builtin.go @@ -3,6 +3,9 @@ package builtin import ( "fmt" + "github.com/filecoin-project/go-state-types/abi" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" + smoothing0 "github.com/filecoin-project/specs-actors/actors/util/smoothing" "github.com/filecoin-project/go-state-types/network" @@ -30,3 +33,8 @@ type FilterEstimate = smoothing0.FilterEstimate func FromV0FilterEstimate(v0 smoothing0.FilterEstimate) FilterEstimate { return (FilterEstimate)(v0) } + +// Doesn't change between actors v0 and v1 +func QAPowerForWeight(size abi.SectorSize, duration abi.ChainEpoch, dealWeight, verifiedWeight abi.DealWeight) abi.StoragePower { + return miner0.QAPowerForWeight(size, duration, dealWeight, verifiedWeight) +} diff --git a/chain/actors/builtin/reward/reward.go b/chain/actors/builtin/reward/reward.go index 3f887914d..a4f936d9b 100644 --- a/chain/actors/builtin/reward/reward.go +++ b/chain/actors/builtin/reward/reward.go @@ -2,6 +2,7 @@ package reward import ( "github.com/filecoin-project/go-state-types/abi" + reward0 "github.com/filecoin-project/specs-actors/actors/builtin/reward" "golang.org/x/xerrors" "github.com/filecoin-project/go-state-types/cbor" @@ -45,3 +46,5 @@ type State interface { InitialPledgeForPower(abi.StoragePower, abi.TokenAmount, *builtin.FilterEstimate, abi.TokenAmount) (abi.TokenAmount, error) PreCommitDepositForPower(builtin.FilterEstimate, abi.StoragePower) (abi.TokenAmount, error) } + +type AwardBlockRewardParams = reward0.AwardBlockRewardParams diff --git a/chain/stmgr/stmgr.go b/chain/stmgr/stmgr.go index e6e557930..2f8d460aa 100644 --- a/chain/stmgr/stmgr.go +++ b/chain/stmgr/stmgr.go @@ -22,8 +22,7 @@ import ( "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/specs-actors/actors/builtin" - reward0 "github.com/filecoin-project/specs-actors/actors/builtin/reward" + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/filecoin-project/lotus/api" @@ -169,20 +168,20 @@ func (sm *StateManager) ApplyBlocks(ctx context.Context, parentEpoch abi.ChainEp runCron := func() error { // TODO: this nonce-getting is a tiny bit ugly - ca, err := vmi.StateTree().GetActor(builtin.SystemActorAddr) + ca, err := vmi.StateTree().GetActor(builtin0.SystemActorAddr) if err != nil { return err } cronMsg := &types.Message{ - To: builtin.CronActorAddr, - From: builtin.SystemActorAddr, + To: builtin0.CronActorAddr, + From: builtin0.SystemActorAddr, Nonce: ca.Nonce, Value: types.NewInt(0), GasFeeCap: types.NewInt(0), GasPremium: types.NewInt(0), GasLimit: build.BlockGasLimit * 10000, // Make super sure this is never too little - Method: builtin.MethodsCron.EpochTick, + Method: builtin0.MethodsCron.EpochTick, Params: nil, } ret, err := vmi.ApplyImplicitMessage(ctx, cronMsg) @@ -247,42 +246,34 @@ func (sm *StateManager) ApplyBlocks(ctx context.Context, parentEpoch abi.ChainEp processedMsgs[m.Cid()] = true } - var params []byte - - nv := sm.GetNtwkVersion(ctx, epoch) - if nv < build.ActorUpgradeNetworkVersion { - params, err = actors.SerializeParams(&reward0.AwardBlockRewardParams{ - Miner: b.Miner, - Penalty: penalty, - GasReward: gasReward, - WinCount: b.WinCount, - }) - if err != nil { - return cid.Undef, cid.Undef, xerrors.Errorf("failed to serialize award params: %w", err) - } - } else { - // TODO: ActorUpgrade - params = nil + params, err := actors.SerializeParams(&reward.AwardBlockRewardParams{ + Miner: b.Miner, + Penalty: penalty, + GasReward: gasReward, + WinCount: b.WinCount, + }) + if err != nil { + return cid.Undef, cid.Undef, xerrors.Errorf("failed to serialize award params: %w", err) } - sysAct, err := vmi.StateTree().GetActor(builtin.SystemActorAddr) - if err != nil { + sysAct, actErr := vmi.StateTree().GetActor(builtin0.SystemActorAddr) + if actErr != nil { return cid.Undef, cid.Undef, xerrors.Errorf("failed to get system actor: %w", err) } rwMsg := &types.Message{ - From: builtin.SystemActorAddr, - To: builtin.RewardActorAddr, + From: builtin0.SystemActorAddr, + To: reward.Address, Nonce: sysAct.Nonce, Value: types.NewInt(0), GasFeeCap: types.NewInt(0), GasPremium: types.NewInt(0), GasLimit: 1 << 30, - Method: builtin.MethodsReward.AwardBlockReward, + Method: builtin0.MethodsReward.AwardBlockReward, Params: params, } - ret, err := vmi.ApplyImplicitMessage(ctx, rwMsg) - if err != nil { + ret, actErr := vmi.ApplyImplicitMessage(ctx, rwMsg) + if actErr != nil { return cid.Undef, cid.Undef, xerrors.Errorf("failed to apply reward message for miner %s: %w", b.Miner, err) } if cb != nil { @@ -725,7 +716,7 @@ func (sm *StateManager) MarketBalance(ctx context.Context, addr address.Address, return api.MarketBalance{}, err } - act, err := st.GetActor(builtin.StorageMarketActorAddr) + act, err := st.GetActor(market.Address) if err != nil { return api.MarketBalance{}, err } @@ -853,7 +844,7 @@ func (sm *StateManager) setupGenesisActors(ctx context.Context) error { totalsByEpoch := make(map[abi.ChainEpoch]abi.TokenAmount) var act types.Actor err = r.ForEach(&act, func(k string) error { - if act.Code == builtin.MultisigActorCodeID { + if act.Code == builtin0.MultisigActorCodeID { var s multisig.State err := sm.cs.Store(ctx).Get(ctx, act.Head, &s) if err != nil { @@ -871,7 +862,7 @@ func (sm *StateManager) setupGenesisActors(ctx context.Context) error { totalsByEpoch[s.UnlockDuration()] = s.InitialBalance() } - } else if act.Code == builtin.AccountActorCodeID { + } else if act.Code == builtin0.AccountActorCodeID { // should exclude burnt funds actor and "remainder account actor" // should only ever be "faucet" accounts in testnets kaddr, err := address.NewFromBytes([]byte(k)) @@ -879,7 +870,7 @@ func (sm *StateManager) setupGenesisActors(ctx context.Context) error { return xerrors.Errorf("decoding address: %w", err) } - if kaddr != builtin.BurntFundsActorAddr { + if kaddr != builtin0.BurntFundsActorAddr { kid, err := sTree.LookupID(kaddr) if err != nil { return xerrors.Errorf("resolving address: %w", err) @@ -954,24 +945,24 @@ func (sm *StateManager) setupGenesisActorsTestnet(ctx context.Context) error { totalsByEpoch := make(map[abi.ChainEpoch]abi.TokenAmount) // 6 months - sixMonths := abi.ChainEpoch(183 * builtin.EpochsInDay) + sixMonths := abi.ChainEpoch(183 * builtin0.EpochsInDay) totalsByEpoch[sixMonths] = big.NewInt(49_929_341) totalsByEpoch[sixMonths] = big.Add(totalsByEpoch[sixMonths], big.NewInt(32_787_700)) // 1 year - oneYear := abi.ChainEpoch(365 * builtin.EpochsInDay) + oneYear := abi.ChainEpoch(365 * builtin0.EpochsInDay) totalsByEpoch[oneYear] = big.NewInt(22_421_712) // 2 years - twoYears := abi.ChainEpoch(2 * 365 * builtin.EpochsInDay) + twoYears := abi.ChainEpoch(2 * 365 * builtin0.EpochsInDay) totalsByEpoch[twoYears] = big.NewInt(7_223_364) // 3 years - threeYears := abi.ChainEpoch(3 * 365 * builtin.EpochsInDay) + threeYears := abi.ChainEpoch(3 * 365 * builtin0.EpochsInDay) totalsByEpoch[threeYears] = big.NewInt(87_637_883) // 6 years - sixYears := abi.ChainEpoch(6 * 365 * builtin.EpochsInDay) + sixYears := abi.ChainEpoch(6 * 365 * builtin0.EpochsInDay) totalsByEpoch[sixYears] = big.NewInt(100_000_000) totalsByEpoch[sixYears] = big.Add(totalsByEpoch[sixYears], big.NewInt(300_000_000)) @@ -1020,7 +1011,7 @@ func (sm *StateManager) GetFilVested(ctx context.Context, height abi.ChainEpoch, } func GetFilMined(ctx context.Context, st *state.StateTree) (abi.TokenAmount, error) { - ractor, err := st.GetActor(builtin.RewardActorAddr) + ractor, err := st.GetActor(reward.Address) if err != nil { return big.Zero(), xerrors.Errorf("failed to load reward actor state: %w", err) } @@ -1034,7 +1025,7 @@ func GetFilMined(ctx context.Context, st *state.StateTree) (abi.TokenAmount, err } func getFilMarketLocked(ctx context.Context, st *state.StateTree) (abi.TokenAmount, error) { - act, err := st.GetActor(builtin.StorageMarketActorAddr) + act, err := st.GetActor(market.Address) if err != nil { return big.Zero(), xerrors.Errorf("failed to load market actor: %w", err) } @@ -1048,7 +1039,7 @@ func getFilMarketLocked(ctx context.Context, st *state.StateTree) (abi.TokenAmou } func getFilPowerLocked(ctx context.Context, st *state.StateTree) (abi.TokenAmount, error) { - pactor, err := st.GetActor(builtin.StoragePowerActorAddr) + pactor, err := st.GetActor(power.Address) if err != nil { return big.Zero(), xerrors.Errorf("failed to load power actor: %w", err) } @@ -1077,7 +1068,7 @@ func (sm *StateManager) GetFilLocked(ctx context.Context, st *state.StateTree) ( } func GetFilBurnt(ctx context.Context, st *state.StateTree) (abi.TokenAmount, error) { - burnt, err := st.GetActor(builtin.BurntFundsActorAddr) + burnt, err := st.GetActor(builtin0.BurntFundsActorAddr) if err != nil { return big.Zero(), xerrors.Errorf("failed to load burnt actor: %w", err) } diff --git a/chain/stmgr/utils.go b/chain/stmgr/utils.go index 1e670dace..c9e8d32da 100644 --- a/chain/stmgr/utils.go +++ b/chain/stmgr/utils.go @@ -88,8 +88,7 @@ func GetPower(ctx context.Context, sm *StateManager, ts *types.TipSet, maddr add } func GetPowerRaw(ctx context.Context, sm *StateManager, st cid.Cid, maddr address.Address) (power.Claim, power.Claim, bool, error) { - // TODO: ActorUpgrade - act, err := sm.LoadActorRaw(ctx, builtin0.StoragePowerActorAddr, st) + act, err := sm.LoadActorRaw(ctx, power.Address, st) if err != nil { return power.Claim{}, power.Claim{}, false, xerrors.Errorf("(get sset) failed to load power actor state: %w", err) } @@ -281,8 +280,7 @@ func StateMinerInfo(ctx context.Context, sm *StateManager, ts *types.TipSet, mad } func GetMinerSlashed(ctx context.Context, sm *StateManager, ts *types.TipSet, maddr address.Address) (bool, error) { - // TODO: ActorUpgrade - act, err := sm.LoadActor(ctx, builtin0.StoragePowerActorAddr, ts) + act, err := sm.LoadActor(ctx, power.Address, ts) if err != nil { return false, xerrors.Errorf("failed to load power actor: %w", err) } @@ -305,8 +303,7 @@ func GetMinerSlashed(ctx context.Context, sm *StateManager, ts *types.TipSet, ma } func GetStorageDeal(ctx context.Context, sm *StateManager, dealID abi.DealID, ts *types.TipSet) (*api.MarketDeal, error) { - // TODO: ActorUpgrade - act, err := sm.LoadActor(ctx, builtin0.StorageMarketActorAddr, ts) + act, err := sm.LoadActor(ctx, market.Address, ts) if err != nil { return nil, xerrors.Errorf("failed to load market actor: %w", err) } @@ -350,8 +347,7 @@ func GetStorageDeal(ctx context.Context, sm *StateManager, dealID abi.DealID, ts } func ListMinerActors(ctx context.Context, sm *StateManager, ts *types.TipSet) ([]address.Address, error) { - // TODO: ActorUpgrade - act, err := sm.LoadActor(ctx, builtin0.StoragePowerActorAddr, ts) + act, err := sm.LoadActor(ctx, power.Address, ts) if err != nil { return nil, xerrors.Errorf("failed to load power actor: %w", err) } @@ -630,8 +626,7 @@ func GetReturnType(ctx context.Context, sm *StateManager, to address.Address, me } func MinerHasMinPower(ctx context.Context, sm *StateManager, addr address.Address, ts *types.TipSet) (bool, error) { - // TODO: ActorUpgrade - pact, err := sm.LoadActor(ctx, builtin0.StoragePowerActorAddr, ts) + pact, err := sm.LoadActor(ctx, power.Address, ts) if err != nil { return false, xerrors.Errorf("loading power actor state: %w", err) } diff --git a/node/impl/full/state.go b/node/impl/full/state.go index 0b2d86718..109a265ea 100644 --- a/node/impl/full/state.go +++ b/node/impl/full/state.go @@ -5,11 +5,10 @@ import ( "context" "strconv" - builtin2 "github.com/filecoin-project/lotus/chain/actors/builtin" + lotusbuiltin "github.com/filecoin-project/lotus/chain/actors/builtin" builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" market0 "github.com/filecoin-project/specs-actors/actors/builtin/market" - miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/actors/builtin/verifreg" @@ -871,7 +870,7 @@ func (a *StateAPI) StateMinerPreCommitDepositForPower(ctx context.Context, maddr var sectorWeight abi.StoragePower if act, err := state.GetActor(market.Address); err != nil { - return types.EmptyInt, xerrors.Errorf("loading miner actor %s: %w", maddr, err) + return types.EmptyInt, xerrors.Errorf("loading market actor %s: %w", maddr, err) } else if s, err := market.Load(store, act); err != nil { return types.EmptyInt, xerrors.Errorf("loading market actor state %s: %w", maddr, err) } else if w, vw, err := s.VerifyDealsForActivation(maddr, pci.DealIDs, ts.Height(), pci.Expiration); err != nil { @@ -879,14 +878,12 @@ func (a *StateAPI) StateMinerPreCommitDepositForPower(ctx context.Context, maddr } else { // NB: not exactly accurate, but should always lead us to *over* estimate, not under duration := pci.Expiration - ts.Height() - - // TODO: ActorUpgrade - sectorWeight = miner0.QAPowerForWeight(ssize, duration, w, vw) + sectorWeight = lotusbuiltin.QAPowerForWeight(ssize, duration, w, vw) } - var powerSmoothed builtin2.FilterEstimate + var powerSmoothed lotusbuiltin.FilterEstimate if act, err := state.GetActor(power.Address); err != nil { - return types.EmptyInt, xerrors.Errorf("loading miner actor: %w", err) + return types.EmptyInt, xerrors.Errorf("loading power actor: %w", err) } else if s, err := power.Load(store, act); err != nil { return types.EmptyInt, xerrors.Errorf("loading power actor state: %w", err) } else if p, err := s.TotalPowerSmoothed(); err != nil { @@ -942,13 +939,11 @@ func (a *StateAPI) StateMinerInitialPledgeCollateral(ctx context.Context, maddr } else { // NB: not exactly accurate, but should always lead us to *over* estimate, not under duration := pci.Expiration - ts.Height() - - // TODO: ActorUpgrade - sectorWeight = miner0.QAPowerForWeight(ssize, duration, w, vw) + sectorWeight = lotusbuiltin.QAPowerForWeight(ssize, duration, w, vw) } var ( - powerSmoothed builtin2.FilterEstimate + powerSmoothed lotusbuiltin.FilterEstimate pledgeCollateral abi.TokenAmount ) if act, err := state.GetActor(power.Address); err != nil { From 1dc69e397e66a0c622d5e2b0bc865c5e25241206 Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Tue, 22 Sep 2020 00:35:15 -0400 Subject: [PATCH 151/303] Resolve some unnecessary actor upgrade TODOs --- chain/actors/builtin/miner/miner.go | 6 ++++ cmd/lotus-pcr/main.go | 19 +++--------- extern/storage-sealing/checks.go | 13 +++----- extern/storage-sealing/precommit_policy.go | 21 +++---------- extern/storage-sealing/sealing.go | 17 ---------- extern/storage-sealing/states_sealing.go | 36 ++++++---------------- 6 files changed, 28 insertions(+), 84 deletions(-) diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index c2b2e3a0d..dbb4ddd73 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -18,6 +18,12 @@ import ( "github.com/filecoin-project/lotus/chain/types" ) +// Unchanged between v0 and v1 actors +var PreCommitChallengeDelay = miner0.PreCommitChallengeDelay +var WPoStProvingPeriod = miner0.WPoStProvingPeriod + +const MinSectorExpiration = miner0.MinSectorExpiration + func Load(store adt.Store, act *types.Actor) (st State, err error) { switch act.Code { case builtin0.StorageMinerActorCodeID: diff --git a/cmd/lotus-pcr/main.go b/cmd/lotus-pcr/main.go index c8179d9b6..fed42427c 100644 --- a/cmd/lotus-pcr/main.go +++ b/cmd/lotus-pcr/main.go @@ -396,24 +396,13 @@ func (r *refunder) ProcessTipset(ctx context.Context, tipset *types.TipSet, refu var sn abi.SectorNumber - nv, err := r.api.StateNetworkVersion(ctx, tipset.Key()) - if err != nil { - log.Warnw("failed to get network version") + var proveCommitSector miner0.ProveCommitSectorParams + if err := proveCommitSector.UnmarshalCBOR(bytes.NewBuffer(m.Params)); err != nil { + log.Warnw("failed to decode provecommit params", "err", err, "method", messageMethod, "cid", msg.Cid, "miner", m.To) continue } - if nv < build.ActorUpgradeNetworkVersion { - var proveCommitSector miner0.ProveCommitSectorParams - if err := proveCommitSector.UnmarshalCBOR(bytes.NewBuffer(m.Params)); err != nil { - log.Warnw("failed to decode provecommit params", "err", err, "method", messageMethod, "cid", msg.Cid, "miner", m.To) - continue - } - - sn = proveCommitSector.SectorNumber - } else { - // TODO: ActorUpgrade - sn = 0 - } + sn = proveCommitSector.SectorNumber // We use the parent tipset key because precommit information is removed when ProveCommitSector is executed precommitChainInfo, err := r.api.StateSectorPreCommitInfo(ctx, m.To, sn, tipset.Parents()) diff --git a/extern/storage-sealing/checks.go b/extern/storage-sealing/checks.go index 27b62f49a..3d9aedeb4 100644 --- a/extern/storage-sealing/checks.go +++ b/extern/storage-sealing/checks.go @@ -4,6 +4,8 @@ import ( "bytes" "context" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + "github.com/filecoin-project/lotus/build" miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" @@ -104,7 +106,7 @@ func checkPrecommit(ctx context.Context, maddr address.Address, si SectorInfo, t if nv < build.ActorUpgradeNetworkVersion { msd = miner0.MaxSealDuration[si.SectorType] } else { - // TODO: ActorUpgrade + // TODO: ActorUpgrade(use MaxProveCommitDuration) msd = 0 } @@ -154,13 +156,8 @@ func (m *Sealing) checkCommit(ctx context.Context, si SectorInfo, proof []byte, return &ErrNoPrecommit{xerrors.Errorf("precommit info not found on-chain")} } - pccd, err := m.getPreCommitChallengeDelay(ctx, tok) - if err != nil { - return xerrors.Errorf("failed to get precommit challenge delay: %w", err) - } - - if pci.PreCommitEpoch+pccd != si.SeedEpoch { - return &ErrBadSeed{xerrors.Errorf("seed epoch doesn't match on chain info: %d != %d", pci.PreCommitEpoch+pccd, si.SeedEpoch)} + if pci.PreCommitEpoch+miner.PreCommitChallengeDelay != si.SeedEpoch { + return &ErrBadSeed{xerrors.Errorf("seed epoch doesn't match on chain info: %d != %d", pci.PreCommitEpoch+miner.PreCommitChallengeDelay, si.SeedEpoch)} } buf := new(bytes.Buffer) diff --git a/extern/storage-sealing/precommit_policy.go b/extern/storage-sealing/precommit_policy.go index 2ee6c1afc..0b774b56f 100644 --- a/extern/storage-sealing/precommit_policy.go +++ b/extern/storage-sealing/precommit_policy.go @@ -3,11 +3,11 @@ package sealing import ( "context" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + "github.com/filecoin-project/go-state-types/network" - "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/go-state-types/abi" - miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" ) type PreCommitPolicy interface { @@ -52,7 +52,7 @@ func NewBasicPreCommitPolicy(api Chain, duration abi.ChainEpoch, provingBoundary // Expiration produces the pre-commit sector expiration epoch for an encoded // replica containing the provided enumeration of pieces and deals. func (p *BasicPreCommitPolicy) Expiration(ctx context.Context, ps ...Piece) (abi.ChainEpoch, error) { - tok, epoch, err := p.api.ChainHead(ctx) + _, epoch, err := p.api.ChainHead(ctx) if err != nil { return 0, err } @@ -80,20 +80,7 @@ func (p *BasicPreCommitPolicy) Expiration(ctx context.Context, ps ...Piece) (abi end = &tmp } - nv, err := p.api.StateNetworkVersion(ctx, tok) - if err != nil { - return 0, err - } - - var wpp abi.ChainEpoch - if nv < build.ActorUpgradeNetworkVersion { - wpp = miner0.WPoStProvingPeriod - } else { - // TODO: ActorUpgrade - wpp = 0 - } - - *end += wpp - (*end % wpp) + p.provingBoundary - 1 + *end += miner.WPoStProvingPeriod - (*end % miner.WPoStProvingPeriod) + p.provingBoundary - 1 return *end, nil } diff --git a/extern/storage-sealing/sealing.go b/extern/storage-sealing/sealing.go index d5772e1d6..1ba53661a 100644 --- a/extern/storage-sealing/sealing.go +++ b/extern/storage-sealing/sealing.go @@ -8,9 +8,6 @@ import ( "sync" "time" - "github.com/filecoin-project/lotus/build" - miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" - "github.com/filecoin-project/go-state-types/network" "github.com/ipfs/go-cid" "github.com/ipfs/go-datastore" @@ -422,17 +419,3 @@ func getDealPerSectorLimit(size abi.SectorSize) uint64 { } return 512 } - -func (m *Sealing) getPreCommitChallengeDelay(ctx context.Context, tok TipSetToken) (abi.ChainEpoch, error) { - nv, err := m.api.StateNetworkVersion(ctx, tok) - if err != nil { - return -1, xerrors.Errorf("failed to get network version: %w", err) - } - - if nv < build.ActorUpgradeNetworkVersion { - return miner0.PreCommitChallengeDelay, nil - } - - // TODO: ActorUpgrade - return -1, nil -} diff --git a/extern/storage-sealing/states_sealing.go b/extern/storage-sealing/states_sealing.go index 0109326fb..443365160 100644 --- a/extern/storage-sealing/states_sealing.go +++ b/extern/storage-sealing/states_sealing.go @@ -189,17 +189,14 @@ func (m *Sealing) handlePreCommitting(ctx statemachine.Context, sector SectorInf } var msd abi.ChainEpoch - var mse abi.ChainEpoch if nv < build.ActorUpgradeNetworkVersion { msd = miner0.MaxSealDuration[sector.SectorType] - mse = miner0.MinSectorExpiration } else { - // TODO: ActorUpgrade + // TODO: ActorUpgrade(use MaxProveCommitDuration) msd = 0 - mse = 0 } - if minExpiration := height + msd + mse + 10; expiration < minExpiration { + if minExpiration := height + msd + miner.MinSectorExpiration + 10; expiration < minExpiration { expiration = minExpiration } // TODO: enforce a reasonable _maximum_ sector lifetime? @@ -284,12 +281,7 @@ func (m *Sealing) handleWaitSeed(ctx statemachine.Context, sector SectorInfo) er return ctx.Send(SectorChainPreCommitFailed{error: xerrors.Errorf("precommit info not found on chain")}) } - pccd, err := m.getPreCommitChallengeDelay(ctx.Context(), tok) - if err != nil { - return ctx.Send(SectorChainPreCommitFailed{xerrors.Errorf("failed to get precommit challenge delay: %w", err)}) - } - - randHeight := pci.PreCommitEpoch + pccd + randHeight := pci.PreCommitEpoch + miner.PreCommitChallengeDelay err = m.events.ChainAt(func(ectx context.Context, _ TipSetToken, curH abi.ChainEpoch) error { // in case of null blocks the randomness can land after the tipset we @@ -380,24 +372,14 @@ func (m *Sealing) handleSubmitCommit(ctx statemachine.Context, sector SectorInfo return ctx.Send(SectorCommitFailed{xerrors.Errorf("commit check error: %w", err)}) } - nv, err := m.api.StateNetworkVersion(ctx.Context(), tok) - if err != nil { - return ctx.Send(SectorCommitFailed{xerrors.Errorf("failed to get network version: %w", err)}) + enc := new(bytes.Buffer) + params := &miner.ProveCommitSectorParams{ + SectorNumber: sector.SectorNumber, + Proof: sector.Proof, } - enc := new(bytes.Buffer) - if nv < build.ActorUpgradeNetworkVersion { - params := &miner0.ProveCommitSectorParams{ - SectorNumber: sector.SectorNumber, - Proof: sector.Proof, - } - - if err := params.MarshalCBOR(enc); err != nil { - return ctx.Send(SectorCommitFailed{xerrors.Errorf("could not serialize commit sector parameters: %w", err)}) - } - } else { - // TODO: ActorUpgrade - enc = nil + if err := params.MarshalCBOR(enc); err != nil { + return ctx.Send(SectorCommitFailed{xerrors.Errorf("could not serialize commit sector parameters: %w", err)}) } waddr, err := m.api.StateMinerWorkerAddress(ctx.Context(), m.maddr, tok) From 001ba17d37c4217e7e7a4737123132062f517772 Mon Sep 17 00:00:00 2001 From: zgfzgf <1901989065@qq.com> Date: Tue, 22 Sep 2020 15:21:35 +0800 Subject: [PATCH 152/303] break error --- miner/miner.go | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/miner/miner.go b/miner/miner.go index 2d8591992..144b2f413 100644 --- a/miner/miner.go +++ b/miner/miner.go @@ -151,6 +151,7 @@ func (m *Miner) mine(ctx context.Context) { var lastBase MiningBase for { + minerStop: select { case <-m.stop: stopping := m.stopping @@ -171,7 +172,7 @@ func (m *Miner) mine(ctx context.Context) { if err != nil { log.Errorf("failed to get best mining candidate: %s", err) if !m.niceSleep(time.Second * 5) { - break + goto minerStop } continue } @@ -203,7 +204,7 @@ func (m *Miner) mine(ctx context.Context) { if err != nil { log.Errorf("failed getting beacon entry: %s", err) if !m.niceSleep(time.Second) { - break + goto minerStop } continue } @@ -214,7 +215,7 @@ func (m *Miner) mine(ctx context.Context) { if base.TipSet.Equals(lastBase.TipSet) && lastBase.NullRounds == base.NullRounds { log.Warnf("BestMiningCandidate from the previous round: %s (nulls:%d)", lastBase.TipSet.Cids(), lastBase.NullRounds) if !m.niceSleep(time.Duration(build.BlockDelaySecs) * time.Second) { - break + goto minerStop } continue } @@ -225,7 +226,7 @@ func (m *Miner) mine(ctx context.Context) { if err != nil { log.Errorf("mining block failed: %+v", err) if !m.niceSleep(time.Second) { - break + goto minerStop } onDone(false, 0, err) continue From 9b91628d858a35f49de2f0f9ecc691a1cba3fbaf Mon Sep 17 00:00:00 2001 From: whyrusleeping Date: Tue, 22 Sep 2020 11:05:12 -0500 Subject: [PATCH 153/303] begin adding simple api server for deal stats --- cmd/lotus-shed/dealtracker.go | 78 +++++++++++++++++++++++++++++++++++ cmd/lotus-shed/main.go | 1 + 2 files changed, 79 insertions(+) create mode 100644 cmd/lotus-shed/dealtracker.go diff --git a/cmd/lotus-shed/dealtracker.go b/cmd/lotus-shed/dealtracker.go new file mode 100644 index 000000000..9f97337ee --- /dev/null +++ b/cmd/lotus-shed/dealtracker.go @@ -0,0 +1,78 @@ +package main + +import ( + "context" + "encoding/json" + "net/http" + + "github.com/filecoin-project/lotus/api" + lcli "github.com/filecoin-project/lotus/cli" + "github.com/urfave/cli/v2" +) + +type dealStatsServer struct { + api api.FullNode +} + +type dealCountResp struct { + Total int64 `json:"total"` + Epoch int64 `json:"epoch"` +} + +func (dss *dealStatsServer) handleStorageDealCount(w http.ResponseWriter, r *http.Request) { + ctx := context.Background() + + head, err := dss.api.ChainHead(ctx) + if err != nil { + log.Warnf("failed to get chain head: %s", err) + w.WriteHeader(500) + return + } + + deals, err := dss.api.StateMarketDeals(ctx, head.Key()) + if err != nil { + log.Warnf("failed to get market deals: %s", err) + w.WriteHeader(500) + return + } + + if err := json.NewEncoder(w).Encode(&dealCountResp{ + Total: int64(len(deals)), + Epoch: int64(head.Height()), + }); err != nil { + log.Warnf("failed to write back deal count response: %s", err) + return + } +} + +func (dss *dealStatsServer) handleStorageDealAverageSize(w http.ResponseWriter, r *http.Request) { + +} + +func (dss *dealStatsServer) handleStorageDealTotalReal(w http.ResponseWriter, r *http.Request) { + +} + +var serveDealStatsCmd = &cli.Command{ + Name: "serve-deal-stats", + Flags: []cli.Flag{}, + Action: func(cctx *cli.Context) error { + api, closer, err := lcli.GetFullNodeAPI(cctx) + if err != nil { + return err + } + + defer closer() + ctx := lcli.ReqContext(cctx) + + _ = ctx + + dss := &dealStatsServer{api} + + http.HandleFunc("/api/storagedeal/count", dss.handleStorageDealCount) + http.HandleFunc("/api/storagedeal/averagesize", dss.handleStorageDealAverageSize) + http.HandleFunc("/api/storagedeal/totalreal", dss.handleStorageDealTotalReal) + + panic(http.ListenAndServe(":7272", nil)) + }, +} diff --git a/cmd/lotus-shed/main.go b/cmd/lotus-shed/main.go index 1a56756d1..118b4ea72 100644 --- a/cmd/lotus-shed/main.go +++ b/cmd/lotus-shed/main.go @@ -36,6 +36,7 @@ func main() { mpoolStatsCmd, exportChainCmd, consensusCmd, + serveDealStatsCmd, } app := &cli.App{ From fc15888697effe357f177d00c35f07fc7666330f Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Tue, 22 Sep 2020 10:52:23 -0700 Subject: [PATCH 154/303] fixup some imports --- markets/storageadapter/client.go | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/markets/storageadapter/client.go b/markets/storageadapter/client.go index 781715903..fabc5b197 100644 --- a/markets/storageadapter/client.go +++ b/markets/storageadapter/client.go @@ -6,9 +6,9 @@ import ( "bytes" "context" - "github.com/filecoin-project/lotus/chain/actors/builtin/miner" - "github.com/filecoin-project/go-state-types/big" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin" + market0 "github.com/filecoin-project/specs-actors/actors/builtin/market" "golang.org/x/xerrors" @@ -20,6 +20,7 @@ import ( "github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/go-state-types/exitcode" "github.com/filecoin-project/lotus/build" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/events" "github.com/filecoin-project/lotus/chain/events/state" "github.com/filecoin-project/lotus/chain/market" @@ -29,8 +30,6 @@ import ( "github.com/filecoin-project/lotus/lib/sigs" "github.com/filecoin-project/lotus/markets/utils" "github.com/filecoin-project/lotus/node/impl/full" - "github.com/filecoin-project/specs-actors/actors/builtin" - samarket "github.com/filecoin-project/specs-actors/actors/builtin/market" "github.com/ipfs/go-cid" ) @@ -102,10 +101,10 @@ func (c *ClientNodeAdapter) VerifySignature(ctx context.Context, sig crypto.Sign func (c *ClientNodeAdapter) AddFunds(ctx context.Context, addr address.Address, amount abi.TokenAmount) (cid.Cid, error) { // (Provider Node API) smsg, err := c.MpoolPushMessage(ctx, &types.Message{ - To: builtin.StorageMarketActorAddr, + To: miner0.StorageMarketActorAddr, From: addr, Value: amount, - Method: builtin.MethodsMarket.AddBalance, + Method: miner0.MethodsMarket.AddBalance, }, nil) if err != nil { return cid.Undef, err @@ -156,15 +155,15 @@ func (c *ClientNodeAdapter) ValidatePublishedDeal(ctx context.Context, deal stor return 0, xerrors.Errorf("deal wasn't published by storage provider: from=%s, provider=%s", pubmsg.From, deal.Proposal.Provider) } - if pubmsg.To != builtin.StorageMarketActorAddr { + if pubmsg.To != miner0.StorageMarketActorAddr { return 0, xerrors.Errorf("deal publish message wasn't set to StorageMarket actor (to=%s)", pubmsg.To) } - if pubmsg.Method != builtin.MethodsMarket.PublishStorageDeals { + if pubmsg.Method != miner0.MethodsMarket.PublishStorageDeals { return 0, xerrors.Errorf("deal publish message called incorrect method (method=%s)", pubmsg.Method) } - var params samarket.PublishStorageDealsParams + var params market0.PublishStorageDealsParams if err := params.UnmarshalCBOR(bytes.NewReader(pubmsg.Params)); err != nil { return 0, err } @@ -196,7 +195,7 @@ func (c *ClientNodeAdapter) ValidatePublishedDeal(ctx context.Context, deal stor return 0, xerrors.Errorf("deal publish failed: exit=%d", ret.ExitCode) } - var res samarket.PublishStorageDealsReturn + var res market0.PublishStorageDealsReturn if err := res.UnmarshalCBOR(bytes.NewReader(ret.Return)); err != nil { return 0, err } @@ -274,7 +273,7 @@ func (c *ClientNodeAdapter) OnDealSectorCommitted(ctx context.Context, provider } switch msg.Method { - case builtin.MethodsMiner.PreCommitSector: + case miner0.MethodsMiner.PreCommitSector: var params miner.SectorPreCommitInfo if err := params.UnmarshalCBOR(bytes.NewReader(msg.Params)); err != nil { return true, false, xerrors.Errorf("unmarshal pre commit: %w", err) @@ -289,7 +288,7 @@ func (c *ClientNodeAdapter) OnDealSectorCommitted(ctx context.Context, provider } return true, false, nil - case builtin.MethodsMiner.ProveCommitSector: + case miner0.MethodsMiner.ProveCommitSector: var params miner.ProveCommitSectorParams if err := params.UnmarshalCBOR(bytes.NewReader(msg.Params)); err != nil { return true, false, xerrors.Errorf("failed to unmarshal prove commit sector params: %w", err) @@ -411,7 +410,7 @@ func (c *ClientNodeAdapter) OnDealExpiredOrSlashed(ctx context.Context, dealID a return nil } -func (c *ClientNodeAdapter) SignProposal(ctx context.Context, signer address.Address, proposal samarket.DealProposal) (*samarket.ClientDealProposal, error) { +func (c *ClientNodeAdapter) SignProposal(ctx context.Context, signer address.Address, proposal market0.DealProposal) (*market0.ClientDealProposal, error) { // TODO: output spec signed proposal buf, err := cborutil.Dump(&proposal) if err != nil { @@ -428,7 +427,7 @@ func (c *ClientNodeAdapter) SignProposal(ctx context.Context, signer address.Add return nil, err } - return &samarket.ClientDealProposal{ + return &market0.ClientDealProposal{ Proposal: proposal, ClientSignature: *sig, }, nil From f96698b54df95fcb44bbcf9cd62e9f710832196f Mon Sep 17 00:00:00 2001 From: whyrusleeping Date: Tue, 22 Sep 2020 12:54:39 -0500 Subject: [PATCH 155/303] finish up other endpoints --- cmd/lotus-shed/dealtracker.go | 136 +++++++++++++++++++++++++++++++++- 1 file changed, 134 insertions(+), 2 deletions(-) diff --git a/cmd/lotus-shed/dealtracker.go b/cmd/lotus-shed/dealtracker.go index 9f97337ee..1d3dad058 100644 --- a/cmd/lotus-shed/dealtracker.go +++ b/cmd/lotus-shed/dealtracker.go @@ -5,8 +5,10 @@ import ( "encoding/json" "net/http" + "github.com/filecoin-project/go-address" "github.com/filecoin-project/lotus/api" lcli "github.com/filecoin-project/lotus/cli" + "github.com/ipfs/go-cid" "github.com/urfave/cli/v2" ) @@ -14,11 +16,34 @@ type dealStatsServer struct { api api.FullNode } +var filteredClients map[address.Address]bool + +func init() { + filteredClients = make(map[address.Address]bool) + for _, a := range []string{"t0112", "t0113", "t0114", "t010089"} { + addr, err := address.NewFromString(a) + if err != nil { + panic(err) + } + filteredClients[addr] = true + } +} + type dealCountResp struct { Total int64 `json:"total"` Epoch int64 `json:"epoch"` } +func filterDeals(deals map[string]api.MarketDeal) []*api.MarketDeal { + out := make([]*api.MarketDeal, 0, len(deals)) + for _, d := range deals { + if !filteredClients[d.Proposal.Client] { + out = append(out, &d) + } + } + return out +} + func (dss *dealStatsServer) handleStorageDealCount(w http.ResponseWriter, r *http.Request) { ctx := context.Background() @@ -36,8 +61,15 @@ func (dss *dealStatsServer) handleStorageDealCount(w http.ResponseWriter, r *htt return } + var count int64 + for _, d := range deals { + if !filteredClients[d.Proposal.Client] { + count++ + } + } + if err := json.NewEncoder(w).Encode(&dealCountResp{ - Total: int64(len(deals)), + Total: count, Epoch: int64(head.Height()), }); err != nil { log.Warnf("failed to write back deal count response: %s", err) @@ -45,14 +77,113 @@ func (dss *dealStatsServer) handleStorageDealCount(w http.ResponseWriter, r *htt } } -func (dss *dealStatsServer) handleStorageDealAverageSize(w http.ResponseWriter, r *http.Request) { +type dealAverageResp struct { + AverageSize int64 `json:"averageSize"` + Epoch int64 `json:"epoch"` +} +func (dss *dealStatsServer) handleStorageDealAverageSize(w http.ResponseWriter, r *http.Request) { + ctx := context.Background() + + head, err := dss.api.ChainHead(ctx) + if err != nil { + log.Warnf("failed to get chain head: %s", err) + w.WriteHeader(500) + return + } + + deals, err := dss.api.StateMarketDeals(ctx, head.Key()) + if err != nil { + log.Warnf("failed to get market deals: %s", err) + w.WriteHeader(500) + return + } + + var count int64 + var totalBytes int64 + for _, d := range deals { + if !filteredClients[d.Proposal.Client] { + count++ + totalBytes += int64(d.Proposal.PieceSize.Unpadded()) + } + } + + if err := json.NewEncoder(w).Encode(&dealAverageResp{ + AverageSize: totalBytes / count, + Epoch: int64(head.Height()), + }); err != nil { + log.Warnf("failed to write back deal average response: %s", err) + return + } } func (dss *dealStatsServer) handleStorageDealTotalReal(w http.ResponseWriter, r *http.Request) { } +type clientStatsOutput struct { + Client address.Address `json:"client"` + DataSize int64 `json:"data_size"` + NumCids int `json:"num_cids"` + NumDeals int `json:"num_deals"` + NumMiners int `json:"num_miners"` + + cids map[cid.Cid]bool + providers map[address.Address]bool +} + +func (dss *dealStatsServer) handleStorageClientStats(w http.ResponseWriter, r *http.Request) { + ctx := context.Background() + + head, err := dss.api.ChainHead(ctx) + if err != nil { + log.Warnf("failed to get chain head: %s", err) + w.WriteHeader(500) + return + } + + deals, err := dss.api.StateMarketDeals(ctx, head.Key()) + if err != nil { + log.Warnf("failed to get market deals: %s", err) + w.WriteHeader(500) + return + } + + stats := make(map[address.Address]*clientStatsOutput) + + for _, d := range deals { + if filteredClients[d.Proposal.Client] { + continue + } + + st, ok := stats[d.Proposal.Client] + if !ok { + st = &clientStatsOutput{ + Client: d.Proposal.Client, + cids: make(map[cid.Cid]bool), + providers: make(map[address.Address]bool), + } + stats[d.Proposal.Client] = st + } + + st.DataSize += int64(d.Proposal.PieceSize.Unpadded()) + st.cids[d.Proposal.PieceCID] = true + st.providers[d.Proposal.Provider] = true + st.NumDeals++ + } + + out := make([]*clientStatsOutput, 0, len(stats)) + for _, cso := range stats { + cso.NumCids = len(cso.cids) + cso.NumMiners = len(cso.providers) + } + + if err := json.NewEncoder(w).Encode(out); err != nil { + log.Warnf("failed to write back client stats response: %s", err) + return + } +} + var serveDealStatsCmd = &cli.Command{ Name: "serve-deal-stats", Flags: []cli.Flag{}, @@ -72,6 +203,7 @@ var serveDealStatsCmd = &cli.Command{ http.HandleFunc("/api/storagedeal/count", dss.handleStorageDealCount) http.HandleFunc("/api/storagedeal/averagesize", dss.handleStorageDealAverageSize) http.HandleFunc("/api/storagedeal/totalreal", dss.handleStorageDealTotalReal) + http.HandleFunc("/api/storagedeal/clientstats", dss.handleStorageClientStats) panic(http.ListenAndServe(":7272", nil)) }, From 5314ba8c6d1008ae2ea10aa4017c9a88a4ab4144 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Tue, 22 Sep 2020 10:55:29 -0700 Subject: [PATCH 156/303] remove ptr indirection --- chain/events/state/predicates.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/chain/events/state/predicates.go b/chain/events/state/predicates.go index 56dfb981d..909533d15 100644 --- a/chain/events/state/predicates.go +++ b/chain/events/state/predicates.go @@ -303,7 +303,7 @@ func (sp *StatePredicates) OnInitActorChange(diffInitActorState DiffInitActorSta if err != nil { return false, nil, err } - return diffInitActorState(ctx, &oldState, &newState) + return diffInitActorState(ctx, oldState, newState) }) } @@ -405,7 +405,7 @@ type AddressChange struct { To AddressPair } -type DiffInitActorStateFunc func(ctx context.Context, oldState *init_.State, newState *init_.State) (changed bool, user UserData, err error) +type DiffInitActorStateFunc func(ctx context.Context, oldState init_.State, newState init_.State) (changed bool, user UserData, err error) func (i *InitActorAddressChanges) AsKey(key string) (abi.Keyer, error) { addr, err := address.NewFromBytes([]byte(key)) @@ -493,7 +493,7 @@ func (i *InitActorAddressChanges) Remove(key string, val *typegen.Deferred) erro } func (sp *StatePredicates) OnAddressMapChange() DiffInitActorStateFunc { - return func(ctx context.Context, oldState, newState *init_.State) (changed bool, user UserData, err error) { + return func(ctx context.Context, oldState, newState init_.State) (changed bool, user UserData, err error) { /*ctxStore := &contextStore{ ctx: ctx, cst: sp.cst, From ab070f2ebee287e6cddf9b43bc2abac77e9eeb9b Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Tue, 22 Sep 2020 11:09:41 -0700 Subject: [PATCH 157/303] copy actor object when iterating over actors This is a pretty big footgun. --- chain/state/statetree.go | 1 + 1 file changed, 1 insertion(+) diff --git a/chain/state/statetree.go b/chain/state/statetree.go index fb6a14a9b..a654d224b 100644 --- a/chain/state/statetree.go +++ b/chain/state/statetree.go @@ -385,6 +385,7 @@ func (st *StateTree) MutateActor(addr address.Address, f func(*types.Actor) erro func (st *StateTree) ForEach(f func(address.Address, *types.Actor) error) error { var act types.Actor return st.root.ForEach(&act, func(k string) error { + act := act // copy addr, err := address.NewFromBytes([]byte(k)) if err != nil { return xerrors.Errorf("invalid address (%x) found in state tree key: %w", []byte(k), err) From bc24fdbd14bde171f59f61d6f0061cbc1955b9d0 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Tue, 22 Sep 2020 11:09:56 -0700 Subject: [PATCH 158/303] finish migrating statemanager --- chain/actors/adt/adt.go | 8 ++++++ chain/stmgr/stmgr.go | 64 +++++++++++++++++------------------------ 2 files changed, 35 insertions(+), 37 deletions(-) diff --git a/chain/actors/adt/adt.go b/chain/actors/adt/adt.go index fd5ee3f87..39dd5cebc 100644 --- a/chain/actors/adt/adt.go +++ b/chain/actors/adt/adt.go @@ -55,3 +55,11 @@ func AsArray(store Store, root cid.Cid, version network.Version) (Array, error) } return nil, xerrors.Errorf("unknown network version: %d", version) } + +func NewArray(store Store, version builtin.Version) (Array, error) { + switch version { + case builtin.Version0: + return adt0.MakeEmptyArray(store), nil + } + return nil, xerrors.Errorf("unknown network version: %d", version) +} diff --git a/chain/stmgr/stmgr.go b/chain/stmgr/stmgr.go index 2f8d460aa..af729143c 100644 --- a/chain/stmgr/stmgr.go +++ b/chain/stmgr/stmgr.go @@ -5,12 +5,9 @@ import ( "fmt" "sync" + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" msig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig" - "github.com/filecoin-project/lotus/chain/actors/builtin/multisig" - - "github.com/filecoin-project/lotus/chain/actors/builtin/reward" - "github.com/ipfs/go-cid" cbor "github.com/ipfs/go-ipld-cbor" logging "github.com/ipfs/go-log/v2" @@ -22,15 +19,17 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/network" - builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/actors" + "github.com/filecoin-project/lotus/chain/actors/adt" + "github.com/filecoin-project/lotus/chain/actors/builtin" "github.com/filecoin-project/lotus/chain/actors/builtin/market" + "github.com/filecoin-project/lotus/chain/actors/builtin/multisig" "github.com/filecoin-project/lotus/chain/actors/builtin/paych" "github.com/filecoin-project/lotus/chain/actors/builtin/power" + "github.com/filecoin-project/lotus/chain/actors/builtin/reward" "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/store" "github.com/filecoin-project/lotus/chain/types" @@ -291,7 +290,11 @@ func (sm *StateManager) ApplyBlocks(ctx context.Context, parentEpoch abi.ChainEp return cid.Cid{}, cid.Cid{}, err } - rectarr := adt.MakeEmptyArray(sm.cs.Store(ctx)) + // XXX: Is the height correct? Or should it be epoch-1? + rectarr, err := adt.NewArray(sm.cs.Store(ctx), builtin.VersionForNetwork(sm.GetNtwkVersion(ctx, epoch))) + if err != nil { + return cid.Undef, cid.Undef, xerrors.Errorf("failed to create receipts amt: %w", err) + } for i, receipt := range receipts { if err := rectarr.Set(uint64(i), receipt); err != nil { return cid.Undef, cid.Undef, xerrors.Errorf("failed to build receipts amt: %w", err) @@ -689,17 +692,13 @@ func (sm *StateManager) ListAllActors(ctx context.Context, ts *types.TipSet) ([] return nil, err } - r, err := adt.AsMap(sm.cs.Store(ctx), st) + stateTree, err := sm.StateTree(st) if err != nil { return nil, err } var out []address.Address - err = r.ForEach(nil, func(k string) error { - addr, err := address.NewFromBytes([]byte(k)) - if err != nil { - return xerrors.Errorf("address in state tree was not valid: %w", err) - } + err = stateTree.ForEach(func(addr address.Address, act *types.Actor) error { out = append(out, addr) return nil }) @@ -836,17 +835,10 @@ func (sm *StateManager) setupGenesisActors(ctx context.Context) error { return xerrors.Errorf("setting up genesis pledge: %w", err) } - r, err := adt.AsMap(sm.cs.Store(ctx), st) - if err != nil { - return xerrors.Errorf("getting genesis actors: %w", err) - } - totalsByEpoch := make(map[abi.ChainEpoch]abi.TokenAmount) - var act types.Actor - err = r.ForEach(&act, func(k string) error { - if act.Code == builtin0.MultisigActorCodeID { - var s multisig.State - err := sm.cs.Store(ctx).Get(ctx, act.Head, &s) + err = sTree.ForEach(func(kaddr address.Address, act *types.Actor) error { + if act.IsMultisigActor() { + s, err := multisig.Load(sm.cs.Store(ctx), act) if err != nil { return err } @@ -862,25 +854,22 @@ func (sm *StateManager) setupGenesisActors(ctx context.Context) error { totalsByEpoch[s.UnlockDuration()] = s.InitialBalance() } - } else if act.Code == builtin0.AccountActorCodeID { + } else if act.IsAccountActor() { // should exclude burnt funds actor and "remainder account actor" // should only ever be "faucet" accounts in testnets - kaddr, err := address.NewFromBytes([]byte(k)) + if kaddr == builtin0.BurntFundsActorAddr { + return nil + } + + kid, err := sTree.LookupID(kaddr) if err != nil { - return xerrors.Errorf("decoding address: %w", err) + return xerrors.Errorf("resolving address: %w", err) } - if kaddr != builtin0.BurntFundsActorAddr { - kid, err := sTree.LookupID(kaddr) - if err != nil { - return xerrors.Errorf("resolving address: %w", err) - } - - gi.genesisActors = append(gi.genesisActors, genesisActor{ - addr: kid, - initBal: act.Balance, - }) - } + gi.genesisActors = append(gi.genesisActors, genesisActor{ + addr: kid, + initBal: act.Balance, + }) } return nil }) @@ -889,6 +878,7 @@ func (sm *StateManager) setupGenesisActors(ctx context.Context) error { return xerrors.Errorf("error setting up genesis infos: %w", err) } + // TODO: use network upgrade abstractions or always start at actors v0? gi.genesisMsigs = make([]msig0.State, 0, len(totalsByEpoch)) for k, v := range totalsByEpoch { ns := msig0.State{ From 441d7ff790fde269fa950d9106f591178b55648d Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Tue, 22 Sep 2020 11:14:55 -0700 Subject: [PATCH 159/303] cleanup imports some more --- chain/stmgr/forks.go | 12 +++++++----- chain/stmgr/utils.go | 22 ++++++++++------------ 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/chain/stmgr/forks.go b/chain/stmgr/forks.go index bb496849b..32e598065 100644 --- a/chain/stmgr/forks.go +++ b/chain/stmgr/forks.go @@ -6,12 +6,14 @@ import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" + + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" + power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" + adt0 "github.com/filecoin-project/specs-actors/actors/util/adt" + "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/specs-actors/actors/builtin" - miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" - power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" - "github.com/filecoin-project/specs-actors/actors/util/adt" cbor "github.com/ipfs/go-ipld-cbor" "golang.org/x/xerrors" ) @@ -221,7 +223,7 @@ func UpgradeFaucetBurnRecovery(ctx context.Context, sm *StateManager, tree types return xerrors.Errorf("failed to get miner info: %w", err) } - sectorsArr, err := adt.AsArray(sm.ChainStore().Store(ctx), st.Sectors) + sectorsArr, err := adt0.AsArray(sm.ChainStore().Store(ctx), st.Sectors) if err != nil { return xerrors.Errorf("failed to load sectors array: %w", err) } @@ -245,7 +247,7 @@ func UpgradeFaucetBurnRecovery(ctx context.Context, sm *StateManager, tree types return xerrors.Errorf("failed to load miner state: %w", err) } - lbsectors, err := adt.AsArray(sm.ChainStore().Store(ctx), lbst.Sectors) + lbsectors, err := adt0.AsArray(sm.ChainStore().Store(ctx), lbst.Sectors) if err != nil { return xerrors.Errorf("failed to load lb sectors array: %w", err) } diff --git a/chain/stmgr/utils.go b/chain/stmgr/utils.go index c9e8d32da..3493afca3 100644 --- a/chain/stmgr/utils.go +++ b/chain/stmgr/utils.go @@ -9,11 +9,6 @@ import ( "runtime" "strings" - "github.com/filecoin-project/specs-actors/actors/builtin/cron" - - saruntime "github.com/filecoin-project/specs-actors/actors/runtime" - "github.com/filecoin-project/specs-actors/actors/runtime/proof" - cid "github.com/ipfs/go-cid" cbg "github.com/whyrusleeping/cbor-gen" "golang.org/x/xerrors" @@ -22,10 +17,10 @@ import ( "github.com/filecoin-project/go-bitfield" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/crypto" - "github.com/filecoin-project/lotus/chain/actors/builtin/power" - "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" account0 "github.com/filecoin-project/specs-actors/actors/builtin/account" + cron0 "github.com/filecoin-project/specs-actors/actors/builtin/cron" init0 "github.com/filecoin-project/specs-actors/actors/builtin/init" market0 "github.com/filecoin-project/specs-actors/actors/builtin/market" miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" @@ -34,17 +29,20 @@ import ( power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" reward0 "github.com/filecoin-project/specs-actors/actors/builtin/reward" verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + proof0 "github.com/filecoin-project/specs-actors/actors/runtime/proof" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" init_ "github.com/filecoin-project/lotus/chain/actors/builtin/init" "github.com/filecoin-project/lotus/chain/actors/builtin/market" "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + "github.com/filecoin-project/lotus/chain/actors/builtin/power" "github.com/filecoin-project/lotus/chain/beacon" "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/store" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/vm" + "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" "github.com/filecoin-project/lotus/node/modules/dtypes" ) @@ -163,7 +161,7 @@ func GetMinerSectorSet(ctx context.Context, sm *StateManager, ts *types.TipSet, return mas.LoadSectors(snos) } -func GetSectorsForWinningPoSt(ctx context.Context, pv ffiwrapper.Verifier, sm *StateManager, st cid.Cid, maddr address.Address, rand abi.PoStRandomness) ([]proof.SectorInfo, error) { +func GetSectorsForWinningPoSt(ctx context.Context, pv ffiwrapper.Verifier, sm *StateManager, st cid.Cid, maddr address.Address, rand abi.PoStRandomness) ([]proof0.SectorInfo, error) { act, err := sm.LoadActorRaw(ctx, maddr, st) if err != nil { return nil, xerrors.Errorf("failed to load miner actor: %w", err) @@ -248,9 +246,9 @@ func GetSectorsForWinningPoSt(ctx context.Context, pv ffiwrapper.Verifier, sm *S return nil, xerrors.Errorf("loading proving sectors: %w", err) } - out := make([]proof.SectorInfo, len(sectors)) + out := make([]proof0.SectorInfo, len(sectors)) for i, sinfo := range sectors { - out[i] = proof.SectorInfo{ + out[i] = proof0.SectorInfo{ SealProof: spt, SectorNumber: sinfo.SectorNumber, SealedCID: sinfo.SealedCID, @@ -538,7 +536,7 @@ func init() { cidToMethods := map[cid.Cid][2]interface{}{ // builtin.SystemActorCodeID: {builtin.MethodsSystem, system.Actor{} }- apparently it doesn't have methods builtin0.InitActorCodeID: {builtin0.MethodsInit, init0.Actor{}}, - builtin0.CronActorCodeID: {builtin0.MethodsCron, cron.Actor{}}, + builtin0.CronActorCodeID: {builtin0.MethodsCron, cron0.Actor{}}, builtin0.AccountActorCodeID: {builtin0.MethodsAccount, account0.Actor{}}, builtin0.StoragePowerActorCodeID: {builtin0.MethodsPower, power0.Actor{}}, builtin0.StorageMinerActorCodeID: {builtin0.MethodsMiner, miner0.Actor{}}, @@ -550,7 +548,7 @@ func init() { } for c, m := range cidToMethods { - exports := m[1].(saruntime.Invokee).Exports() + exports := m[1].(vm.Invokee).Exports() methods := make(map[abi.MethodNum]MethodMeta, len(exports)) // Explicitly add send, it's special. From c91774be3bb8d8fcd98cdb5de96f1654de622ffe Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Tue, 22 Sep 2020 11:19:28 -0700 Subject: [PATCH 160/303] remove old comment --- cmd/lotus-shed/balances.go | 1 - 1 file changed, 1 deletion(-) diff --git a/cmd/lotus-shed/balances.go b/cmd/lotus-shed/balances.go index de92aa8b6..c156de931 100644 --- a/cmd/lotus-shed/balances.go +++ b/cmd/lotus-shed/balances.go @@ -170,7 +170,6 @@ var chainBalanceStateCmd = &cli.Command{ sm := stmgr.NewStateManager(cs) - // Options: (a) encode the version in the chain or (b) pass a flag. tree, err := state.LoadStateTree(cst, sroot) if err != nil { return err From 3153ab9ae3672a5a7b1aec1384364fdc50169e13 Mon Sep 17 00:00:00 2001 From: whyrusleeping Date: Tue, 22 Sep 2020 13:24:49 -0500 Subject: [PATCH 161/303] allow graceful shutdown --- cmd/lotus-shed/dealtracker.go | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/cmd/lotus-shed/dealtracker.go b/cmd/lotus-shed/dealtracker.go index 1d3dad058..cbe375803 100644 --- a/cmd/lotus-shed/dealtracker.go +++ b/cmd/lotus-shed/dealtracker.go @@ -3,6 +3,7 @@ package main import ( "context" "encoding/json" + "net" "net/http" "github.com/filecoin-project/go-address" @@ -200,11 +201,28 @@ var serveDealStatsCmd = &cli.Command{ dss := &dealStatsServer{api} - http.HandleFunc("/api/storagedeal/count", dss.handleStorageDealCount) - http.HandleFunc("/api/storagedeal/averagesize", dss.handleStorageDealAverageSize) - http.HandleFunc("/api/storagedeal/totalreal", dss.handleStorageDealTotalReal) - http.HandleFunc("/api/storagedeal/clientstats", dss.handleStorageClientStats) + mux := &http.ServeMux{} + mux.HandleFunc("/api/storagedeal/count", dss.handleStorageDealCount) + mux.HandleFunc("/api/storagedeal/averagesize", dss.handleStorageDealAverageSize) + mux.HandleFunc("/api/storagedeal/totalreal", dss.handleStorageDealTotalReal) + mux.HandleFunc("/api/storagedeal/clientstats", dss.handleStorageClientStats) - panic(http.ListenAndServe(":7272", nil)) + s := &http.Server{ + Addr: ":7272", + Handler: mux, + } + + go func() { + <-ctx.Done() + s.Shutdown(context.TODO()) + }() + + list, err := net.Listen("tcp", ":7272") + if err != nil { + panic(err) + } + + s.Serve(list) + return nil }, } From 3cf2fd595f7f74561a5856befa69afe6ee8d570f Mon Sep 17 00:00:00 2001 From: whyrusleeping Date: Tue, 22 Sep 2020 13:27:58 -0500 Subject: [PATCH 162/303] fix appending to array --- cmd/lotus-shed/dealtracker.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cmd/lotus-shed/dealtracker.go b/cmd/lotus-shed/dealtracker.go index cbe375803..57f42bc83 100644 --- a/cmd/lotus-shed/dealtracker.go +++ b/cmd/lotus-shed/dealtracker.go @@ -177,6 +177,8 @@ func (dss *dealStatsServer) handleStorageClientStats(w http.ResponseWriter, r *h for _, cso := range stats { cso.NumCids = len(cso.cids) cso.NumMiners = len(cso.providers) + + out = append(out, cso) } if err := json.NewEncoder(w).Encode(out); err != nil { From 88ada66280807b2000f78a5fca5f186bbf233df5 Mon Sep 17 00:00:00 2001 From: whyrusleeping Date: Tue, 22 Sep 2020 13:31:01 -0500 Subject: [PATCH 163/303] finish up the total bytes endpoint --- cmd/lotus-shed/dealtracker.go | 37 ++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/cmd/lotus-shed/dealtracker.go b/cmd/lotus-shed/dealtracker.go index 57f42bc83..18dc959f7 100644 --- a/cmd/lotus-shed/dealtracker.go +++ b/cmd/lotus-shed/dealtracker.go @@ -79,7 +79,7 @@ func (dss *dealStatsServer) handleStorageDealCount(w http.ResponseWriter, r *htt } type dealAverageResp struct { - AverageSize int64 `json:"averageSize"` + AverageSize int64 `json:"average_size"` Epoch int64 `json:"epoch"` } @@ -118,7 +118,42 @@ func (dss *dealStatsServer) handleStorageDealAverageSize(w http.ResponseWriter, } } +type dealTotalResp struct { + TotalBytes int64 `json:"total_size"` + Epoch int64 `json:"epoch"` +} + func (dss *dealStatsServer) handleStorageDealTotalReal(w http.ResponseWriter, r *http.Request) { + ctx := context.Background() + + head, err := dss.api.ChainHead(ctx) + if err != nil { + log.Warnf("failed to get chain head: %s", err) + w.WriteHeader(500) + return + } + + deals, err := dss.api.StateMarketDeals(ctx, head.Key()) + if err != nil { + log.Warnf("failed to get market deals: %s", err) + w.WriteHeader(500) + return + } + + var totalBytes int64 + for _, d := range deals { + if !filteredClients[d.Proposal.Client] { + totalBytes += int64(d.Proposal.PieceSize.Unpadded()) + } + } + + if err := json.NewEncoder(w).Encode(&dealTotalResp{ + TotalBytes: totalBytes, + Epoch: int64(head.Height()), + }); err != nil { + log.Warnf("failed to write back deal average response: %s", err) + return + } } From 2967c4ec109c2287b05b2732b9f04c1c101320b9 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Tue, 22 Sep 2020 12:02:29 -0700 Subject: [PATCH 164/303] use abstract actor type methods --- chain/stmgr/forks.go | 16 ++++++++-------- chain/vm/vm.go | 2 +- cli/multisig.go | 3 +-- cmd/lotus-pcr/main.go | 6 +++--- 4 files changed, 13 insertions(+), 14 deletions(-) diff --git a/chain/stmgr/forks.go b/chain/stmgr/forks.go index 32e598065..f9418c4d8 100644 --- a/chain/stmgr/forks.go +++ b/chain/stmgr/forks.go @@ -7,13 +7,13 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" adt0 "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/types" - "github.com/filecoin-project/specs-actors/actors/builtin" cbor "github.com/ipfs/go-ipld-cbor" "golang.org/x/xerrors" ) @@ -123,7 +123,7 @@ func UpgradeFaucetBurnRecovery(ctx context.Context, sm *StateManager, tree types // Take all excess funds away, put them into the reserve account err = fetree.ForEach(func(addr address.Address, act *types.Actor) error { switch act.Code { - case builtin.AccountActorCodeID, builtin.MultisigActorCodeID, builtin.PaymentChannelActorCodeID: + case builtin0.AccountActorCodeID, builtin0.MultisigActorCodeID, builtin0.PaymentChannelActorCodeID: sysAcc, err := isSystemAccount(addr) if err != nil { return xerrors.Errorf("checking system account: %w", err) @@ -136,7 +136,7 @@ func UpgradeFaucetBurnRecovery(ctx context.Context, sm *StateManager, tree types Amt: act.Balance, }) } - case builtin.StorageMinerActorCodeID: + case builtin0.StorageMinerActorCodeID: var st miner0.State if err := sm.ChainStore().Store(ctx).Get(ctx, act.Head, &st); err != nil { return xerrors.Errorf("failed to load miner state: %w", err) @@ -175,7 +175,7 @@ func UpgradeFaucetBurnRecovery(ctx context.Context, sm *StateManager, tree types // pull up power table to give miners back some funds proportional to their power var ps power0.State - powAct, err := tree.GetActor(builtin.StoragePowerActorAddr) + powAct, err := tree.GetActor(builtin0.StoragePowerActorAddr) if err != nil { return xerrors.Errorf("failed to load power actor: %w", err) } @@ -203,7 +203,7 @@ func UpgradeFaucetBurnRecovery(ctx context.Context, sm *StateManager, tree types } switch act.Code { - case builtin.AccountActorCodeID, builtin.MultisigActorCodeID, builtin.PaymentChannelActorCodeID: + case builtin0.AccountActorCodeID, builtin0.MultisigActorCodeID, builtin0.PaymentChannelActorCodeID: nbalance := big.Min(prevBalance, AccountCap) if nbalance.Sign() != 0 { transfersBack = append(transfersBack, transfer{ @@ -212,7 +212,7 @@ func UpgradeFaucetBurnRecovery(ctx context.Context, sm *StateManager, tree types Amt: nbalance, }) } - case builtin.StorageMinerActorCodeID: + case builtin0.StorageMinerActorCodeID: var st miner0.State if err := sm.ChainStore().Store(ctx).Get(ctx, act.Head, &st); err != nil { return xerrors.Errorf("failed to load miner state: %w", err) @@ -277,11 +277,11 @@ func UpgradeFaucetBurnRecovery(ctx context.Context, sm *StateManager, tree types } // transfer all burnt funds back to the reserve account - burntAct, err := tree.GetActor(builtin.BurntFundsActorAddr) + burntAct, err := tree.GetActor(builtin0.BurntFundsActorAddr) if err != nil { return xerrors.Errorf("failed to load burnt funds actor: %w", err) } - if err := doTransfer(tree, builtin.BurntFundsActorAddr, ReserveAddress, burntAct.Balance); err != nil { + if err := doTransfer(tree, builtin0.BurntFundsActorAddr, ReserveAddress, burntAct.Balance); err != nil { return xerrors.Errorf("failed to unburn funds: %w", err) } diff --git a/chain/vm/vm.go b/chain/vm/vm.go index 25c937ca3..049918fba 100644 --- a/chain/vm/vm.go +++ b/chain/vm/vm.go @@ -384,7 +384,7 @@ func (vm *VM) ApplyMessage(ctx context.Context, cmsg types.ChainMsg) (*ApplyRet, } // this should never happen, but is currently still exercised by some tests - if !fromActor.Code.Equals(builtin.AccountActorCodeID) { + if !fromActor.IsAccountActor() { gasOutputs := ZeroGasOutputs() gasOutputs.MinerPenalty = minerPenaltyAmount return &ApplyRet{ diff --git a/cli/multisig.go b/cli/multisig.go index 2aabf5d7e..81c6502d5 100644 --- a/cli/multisig.go +++ b/cli/multisig.go @@ -16,7 +16,6 @@ import ( "github.com/urfave/cli/v2" "golang.org/x/xerrors" - "github.com/filecoin-project/specs-actors/actors/builtin" init0 "github.com/filecoin-project/specs-actors/actors/builtin/init" msig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig" @@ -330,7 +329,7 @@ var msigProposeCmd = &cli.Command{ return fmt.Errorf("failed to look up multisig %s: %w", msig, err) } - if act.Code != builtin.MultisigActorCodeID { + if !act.IsMultisigActor() { return fmt.Errorf("actor %s is not a multisig actor", msig) } diff --git a/cmd/lotus-pcr/main.go b/cmd/lotus-pcr/main.go index fed42427c..36961a663 100644 --- a/cmd/lotus-pcr/main.go +++ b/cmd/lotus-pcr/main.go @@ -12,10 +12,10 @@ import ( "strconv" "time" + "github.com/filecoin-project/specs-actors/actors/builtin" miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/go-state-types/network" - "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/ipfs/go-cid" logging "github.com/ipfs/go-log/v2" @@ -28,11 +28,11 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/exitcode" - "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/go-address" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/tools/stats" ) @@ -375,7 +375,7 @@ func (r *refunder) ProcessTipset(ctx context.Context, tipset *types.TipSet, refu continue } - if a.Code != builtin.StorageMinerActorCodeID { + if !a.IsStorageMinerActor() { continue } From 46fb0e74cd3d23c5fd0c49c2022106839dbb6051 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Tue, 22 Sep 2020 14:09:33 -0700 Subject: [PATCH 165/303] add deal state iterator --- chain/actors/builtin/market/market.go | 1 + chain/actors/builtin/market/v0.go | 7 +++++++ 2 files changed, 8 insertions(+) diff --git a/chain/actors/builtin/market/market.go b/chain/actors/builtin/market/market.go index fa5f027b3..9cb0ffc13 100644 --- a/chain/actors/builtin/market/market.go +++ b/chain/actors/builtin/market/market.go @@ -50,6 +50,7 @@ type BalanceTable interface { } type DealStates interface { + ForEach(cb func(id abi.DealID, ds DealState) error) error Get(id abi.DealID) (*DealState, bool, error) array() adt.Array diff --git a/chain/actors/builtin/market/v0.go b/chain/actors/builtin/market/v0.go index 433445dab..14b8b7d93 100644 --- a/chain/actors/builtin/market/v0.go +++ b/chain/actors/builtin/market/v0.go @@ -126,6 +126,13 @@ func (s *dealStates0) Get(dealID abi.DealID) (*DealState, bool, error) { return &deal, true, nil } +func (s *dealStates0) ForEach(cb func(dealID abi.DealID, ds DealState) error) error { + var ds0 market.DealState + return s.Array.ForEach(&ds0, func(idx int64) error { + return cb(abi.DealID(idx), fromV0DealState(ds0)) + }) +} + func (s *dealStates0) decode(val *cbg.Deferred) (*DealState, error) { var ds0 market.DealState if err := ds0.UnmarshalCBOR(bytes.NewReader(val.Raw)); err != nil { From 77f81fc49be3d0fd67438795e41416bb5af18476 Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Tue, 22 Sep 2020 19:07:32 -0400 Subject: [PATCH 166/303] Test fix --- node/node_test.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/node/node_test.go b/node/node_test.go index 0e404dc0b..54498eec3 100644 --- a/node/node_test.go +++ b/node/node_test.go @@ -5,6 +5,8 @@ import ( "testing" "time" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + builder "github.com/filecoin-project/lotus/node/test" "github.com/filecoin-project/go-state-types/abi" @@ -68,6 +70,8 @@ func TestAPIDealFlowReal(t *testing.T) { logging.SetLogLevel("sub", "ERROR") logging.SetLogLevel("storageminer", "ERROR") + // TODO: Do this better. + miner.PreCommitChallengeDelay = 5 miner0.PreCommitChallengeDelay = 5 t.Run("basic", func(t *testing.T) { From dcf2735836ba5993f9a876139ff8476fc9c18a8e Mon Sep 17 00:00:00 2001 From: Lucas Molas Date: Tue, 22 Sep 2020 20:19:31 -0300 Subject: [PATCH 167/303] move validation from protocol to API --- chain/exchange/client.go | 45 +++++++++++++++++++++++++++----------- chain/exchange/protocol.go | 15 +++++-------- 2 files changed, 38 insertions(+), 22 deletions(-) diff --git a/chain/exchange/client.go b/chain/exchange/client.go index a99362745..371c50aed 100644 --- a/chain/exchange/client.go +++ b/chain/exchange/client.go @@ -65,7 +65,15 @@ func NewClient(lc fx.Lifecycle, host host.Host, pmgr peermgr.MaybePeerMgr) Clien // request options without disrupting external calls. In the future the // consumers should be forced to use a more standardized service and // adhere to a single API derived from this function. -func (c *client) doRequest(ctx context.Context, req *Request, singlePeer *peer.ID) (*validatedResponse, error) { +func (c *client) doRequest( + ctx context.Context, + req *Request, + singlePeer *peer.ID, + // In the `GetChainMessages` case, we won't request the headers but we still + // need them to check the integrity of the `CompactedMessages` in the response + // so the tipset blocks need to be provided by the caller. + tipsets []*types.TipSet, +) (*validatedResponse, error) { // Validate request. if req.Length == 0 { return nil, xerrors.Errorf("invalid request of length 0") @@ -116,7 +124,7 @@ func (c *client) doRequest(ctx context.Context, req *Request, singlePeer *peer.I } // Process and validate response. - validRes, err := c.processResponse(req, res) + validRes, err := c.processResponse(req, res, tipsets) if err != nil { log.Warnf("processing peer %s response failed: %s", peer.String(), err) @@ -144,7 +152,7 @@ func (c *client) doRequest(ctx context.Context, req *Request, singlePeer *peer.I // errors. Peer penalization should happen here then, before returning, so // we can apply the correct penalties depending on the cause of the error. // FIXME: Add the `peer` as argument once we implement penalties. -func (c *client) processResponse(req *Request, res *Response) (*validatedResponse, error) { +func (c *client) processResponse(req *Request, res *Response, tipsets []*types.TipSet) (*validatedResponse, error) { err := res.statusToError() if err != nil { return nil, xerrors.Errorf("status error: %s", err) @@ -176,6 +184,16 @@ func (c *client) processResponse(req *Request, res *Response) (*validatedRespons // Check for valid block sets and extract them into `TipSet`s. validRes.tipsets = make([]*types.TipSet, resLength) for i := 0; i < resLength; i++ { + if res.Chain[i] == nil { + return nil, xerrors.Errorf("response with nil tipset in pos %d", i) + } + for blockIdx, block := range res.Chain[i].Blocks { + if block == nil { + return nil, xerrors.Errorf("tipset with nil block in pos %d", blockIdx) + // FIXME: Maybe we should move this check to `NewTipSet`. + } + } + validRes.tipsets[i], err = types.NewTipSet(res.Chain[i].Blocks) if err != nil { return nil, xerrors.Errorf("invalid tipset blocks at height (head - %d): %w", i, err) @@ -214,14 +232,16 @@ func (c *client) processResponse(req *Request, res *Response) (*validatedRespons if err != nil { return nil, err } - } - - if options.ValidateMessages { - // if the request includes target tipsets, validate against them + } else { + // If we didn't request the headers they should have been provided + // by the caller. + if len(tipsets) < len(res.Chain) { + return nil, xerrors.Errorf("not enought tipsets provided for message response validation, needed %d, have %d", len(res.Chain), len(tipsets)) + } chain := make([]*BSTipSet, 0, resLength) for i, resChain := range res.Chain { next := &BSTipSet{ - Blocks: req.TipSets[i].Blocks(), + Blocks: tipsets[i].Blocks(), Messages: resChain.Messages, } chain = append(chain, next) @@ -290,7 +310,7 @@ func (c *client) GetBlocks(ctx context.Context, tsk types.TipSetKey, count int) Options: Headers, } - validRes, err := c.doRequest(ctx, req, nil) + validRes, err := c.doRequest(ctx, req, nil, nil) if err != nil { return nil, err } @@ -308,7 +328,7 @@ func (c *client) GetFullTipSet(ctx context.Context, peer peer.ID, tsk types.TipS Options: Headers | Messages, } - validRes, err := c.doRequest(ctx, req, &peer) + validRes, err := c.doRequest(ctx, req, &peer, nil) if err != nil { return nil, err } @@ -335,11 +355,10 @@ func (c *client) GetChainMessages(ctx context.Context, tipsets []*types.TipSet) req := &Request{ Head: head.Cids(), Length: length, - Options: Messages | Validate, - TipSets: tipsets, + Options: Messages, } - validRes, err := c.doRequest(ctx, req, nil) + validRes, err := c.doRequest(ctx, req, nil, tipsets) if err != nil { return nil, err } diff --git a/chain/exchange/protocol.go b/chain/exchange/protocol.go index b1fe69bd2..211479335 100644 --- a/chain/exchange/protocol.go +++ b/chain/exchange/protocol.go @@ -57,8 +57,6 @@ type Request struct { // Request options, see `Options` type for more details. Compressed // in a single `uint64` to save space. Options uint64 - // Request tipsets for validation - TipSets []*types.TipSet } // `Request` processed and validated to query the tipsets needed. @@ -73,15 +71,13 @@ type validatedRequest struct { const ( Headers = 1 << iota Messages - Validate ) // Decompressed options into separate struct members for easy access // during internal processing.. type parsedOptions struct { - IncludeHeaders bool - IncludeMessages bool - ValidateMessages bool + IncludeHeaders bool + IncludeMessages bool } func (options *parsedOptions) noOptionsSet() bool { @@ -91,9 +87,8 @@ func (options *parsedOptions) noOptionsSet() bool { func parseOptions(optfield uint64) *parsedOptions { return &parsedOptions{ - IncludeHeaders: optfield&(uint64(Headers)) != 0, - IncludeMessages: optfield&(uint64(Messages)) != 0, - ValidateMessages: optfield&(uint64(Validate)) != 0, + IncludeHeaders: optfield&(uint64(Headers)) != 0, + IncludeMessages: optfield&(uint64(Messages)) != 0, } } @@ -144,6 +139,8 @@ func (res *Response) statusToError() error { // FIXME: Rename. type BSTipSet struct { + // List of blocks belonging to a single tipset to which the + // `CompactedMessages` are linked. Blocks []*types.BlockHeader Messages *CompactedMessages } From 773714792f18a503ca1ad4d586734a7be7bc1223 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Tue, 22 Sep 2020 18:40:03 -0700 Subject: [PATCH 168/303] update oni --- extern/oni | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extern/oni b/extern/oni index 8b7e7d438..9a0d5cd73 160000 --- a/extern/oni +++ b/extern/oni @@ -1 +1 @@ -Subproject commit 8b7e7d438c4cc38a0d2d671876d4590ad20655b3 +Subproject commit 9a0d5cd739de77b357589ac1fc8b756ed27299be From ed4bf9b8fe26ce6fc98d0f3bdb1147523116b8ce Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Wed, 23 Sep 2020 00:48:35 -0400 Subject: [PATCH 169/303] API shouldn't depend on actors directly --- api/api_full.go | 8 ++++---- api/apistruct/struct.go | 2 +- chain/actors/builtin/builtin.go | 3 +++ chain/actors/builtin/paych/paych.go | 4 ++++ node/impl/paych/paych.go | 21 ++++++++++----------- 5 files changed, 22 insertions(+), 16 deletions(-) diff --git a/api/api_full.go b/api/api_full.go index f39d0e9bc..11060a9ea 100644 --- a/api/api_full.go +++ b/api/api_full.go @@ -21,9 +21,9 @@ import ( "github.com/filecoin-project/go-state-types/dline" "github.com/filecoin-project/lotus/chain/actors/builtin/market" "github.com/filecoin-project/lotus/chain/actors/builtin/miner" - "github.com/filecoin-project/specs-actors/actors/builtin/paych" - "github.com/filecoin-project/specs-actors/actors/runtime/proof" + "github.com/filecoin-project/lotus/chain/actors/builtin/paych" + "github.com/filecoin-project/lotus/chain/actors/builtin" "github.com/filecoin-project/lotus/chain/actors/builtin/power" "github.com/filecoin-project/lotus/chain/types" marketevents "github.com/filecoin-project/lotus/markets/loggers" @@ -788,7 +788,7 @@ type CirculatingSupply struct { type MiningBaseInfo struct { MinerPower types.BigInt NetworkPower types.BigInt - Sectors []proof.SectorInfo + Sectors []builtin.SectorInfo WorkerKey address.Address SectorSize abi.SectorSize PrevBeaconEntry types.BeaconEntry @@ -805,7 +805,7 @@ type BlockTemplate struct { Messages []*types.SignedMessage Epoch abi.ChainEpoch Timestamp uint64 - WinningPoStProof []proof.PoStProof + WinningPoStProof []builtin.PoStProof } type DataSize struct { diff --git a/api/apistruct/struct.go b/api/apistruct/struct.go index 91a545479..aea7aae8c 100644 --- a/api/apistruct/struct.go +++ b/api/apistruct/struct.go @@ -29,12 +29,12 @@ import ( "github.com/filecoin-project/lotus/extern/sector-storage/stores" "github.com/filecoin-project/lotus/extern/sector-storage/storiface" marketevents "github.com/filecoin-project/lotus/markets/loggers" - "github.com/filecoin-project/specs-actors/actors/builtin/paych" "github.com/filecoin-project/specs-storage/storage" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + "github.com/filecoin-project/lotus/chain/actors/builtin/paych" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/node/modules/dtypes" ) diff --git a/chain/actors/builtin/builtin.go b/chain/actors/builtin/builtin.go index 3230705dd..4079e694a 100644 --- a/chain/actors/builtin/builtin.go +++ b/chain/actors/builtin/builtin.go @@ -5,6 +5,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" + proof0 "github.com/filecoin-project/specs-actors/actors/runtime/proof" smoothing0 "github.com/filecoin-project/specs-actors/actors/util/smoothing" @@ -28,6 +29,8 @@ func VersionForNetwork(version network.Version) Version { } // TODO: Why does actors have 2 different versions of this? +type SectorInfo = proof0.SectorInfo +type PoStProof = proof0.PoStProof type FilterEstimate = smoothing0.FilterEstimate func FromV0FilterEstimate(v0 smoothing0.FilterEstimate) FilterEstimate { diff --git a/chain/actors/builtin/paych/paych.go b/chain/actors/builtin/paych/paych.go index 5eec5f08b..0413dcdd0 100644 --- a/chain/actors/builtin/paych/paych.go +++ b/chain/actors/builtin/paych/paych.go @@ -8,6 +8,7 @@ import ( big "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/cbor" builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" + paych0 "github.com/filecoin-project/specs-actors/actors/builtin/paych" "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/types" @@ -54,3 +55,6 @@ type LaneState interface { Redeemed() big.Int Nonce() uint64 } + +type SignedVoucher = paych0.SignedVoucher +type ModVerifyParams = paych0.ModVerifyParams diff --git a/node/impl/paych/paych.go b/node/impl/paych/paych.go index b2e6be0ca..af0a1db15 100644 --- a/node/impl/paych/paych.go +++ b/node/impl/paych/paych.go @@ -10,9 +10,8 @@ import ( "github.com/filecoin-project/go-address" - paych0 "github.com/filecoin-project/specs-actors/actors/builtin/paych" - "github.com/filecoin-project/lotus/api" + "github.com/filecoin-project/lotus/chain/actors/builtin/paych" "github.com/filecoin-project/lotus/chain/types" full "github.com/filecoin-project/lotus/node/impl/full" "github.com/filecoin-project/lotus/paychmgr" @@ -71,10 +70,10 @@ func (a *PaychAPI) PaychNewPayment(ctx context.Context, from, to address.Address return nil, err } - svs := make([]*paych0.SignedVoucher, len(vouchers)) + svs := make([]*paych.SignedVoucher, len(vouchers)) for i, v := range vouchers { - sv, err := a.PaychMgr.CreateVoucher(ctx, ch.Channel, paych0.SignedVoucher{ + sv, err := a.PaychMgr.CreateVoucher(ctx, ch.Channel, paych.SignedVoucher{ Amount: v.Amount, Lane: lane, @@ -123,15 +122,15 @@ func (a *PaychAPI) PaychCollect(ctx context.Context, addr address.Address) (cid. return a.PaychMgr.Collect(ctx, addr) } -func (a *PaychAPI) PaychVoucherCheckValid(ctx context.Context, ch address.Address, sv *paych0.SignedVoucher) error { +func (a *PaychAPI) PaychVoucherCheckValid(ctx context.Context, ch address.Address, sv *paych.SignedVoucher) error { return a.PaychMgr.CheckVoucherValid(ctx, ch, sv) } -func (a *PaychAPI) PaychVoucherCheckSpendable(ctx context.Context, ch address.Address, sv *paych0.SignedVoucher, secret []byte, proof []byte) (bool, error) { +func (a *PaychAPI) PaychVoucherCheckSpendable(ctx context.Context, ch address.Address, sv *paych.SignedVoucher, secret []byte, proof []byte) (bool, error) { return a.PaychMgr.CheckVoucherSpendable(ctx, ch, sv, secret, proof) } -func (a *PaychAPI) PaychVoucherAdd(ctx context.Context, ch address.Address, sv *paych0.SignedVoucher, proof []byte, minDelta types.BigInt) (types.BigInt, error) { +func (a *PaychAPI) PaychVoucherAdd(ctx context.Context, ch address.Address, sv *paych.SignedVoucher, proof []byte, minDelta types.BigInt) (types.BigInt, error) { return a.PaychMgr.AddVoucherInbound(ctx, ch, sv, proof, minDelta) } @@ -143,16 +142,16 @@ func (a *PaychAPI) PaychVoucherAdd(ctx context.Context, ch address.Address, sv * // If there are insufficient funds in the channel to create the voucher, // returns a nil voucher and the shortfall. func (a *PaychAPI) PaychVoucherCreate(ctx context.Context, pch address.Address, amt types.BigInt, lane uint64) (*api.VoucherCreateResult, error) { - return a.PaychMgr.CreateVoucher(ctx, pch, paych0.SignedVoucher{Amount: amt, Lane: lane}) + return a.PaychMgr.CreateVoucher(ctx, pch, paych.SignedVoucher{Amount: amt, Lane: lane}) } -func (a *PaychAPI) PaychVoucherList(ctx context.Context, pch address.Address) ([]*paych0.SignedVoucher, error) { +func (a *PaychAPI) PaychVoucherList(ctx context.Context, pch address.Address) ([]*paych.SignedVoucher, error) { vi, err := a.PaychMgr.ListVouchers(ctx, pch) if err != nil { return nil, err } - out := make([]*paych0.SignedVoucher, len(vi)) + out := make([]*paych.SignedVoucher, len(vi)) for k, v := range vi { out[k] = v.Voucher } @@ -160,6 +159,6 @@ func (a *PaychAPI) PaychVoucherList(ctx context.Context, pch address.Address) ([ return out, nil } -func (a *PaychAPI) PaychVoucherSubmit(ctx context.Context, ch address.Address, sv *paych0.SignedVoucher, secret []byte, proof []byte) (cid.Cid, error) { +func (a *PaychAPI) PaychVoucherSubmit(ctx context.Context, ch address.Address, sv *paych.SignedVoucher, secret []byte, proof []byte) (cid.Cid, error) { return a.PaychMgr.SubmitVoucher(ctx, ch, sv, secret, proof) } From e27fc03f5541288ef4a6c4080af9587ac706144a Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Wed, 23 Sep 2020 01:36:55 -0400 Subject: [PATCH 170/303] Reward state interface only needs cbor.Marshaler --- chain/actors/builtin/reward/reward.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chain/actors/builtin/reward/reward.go b/chain/actors/builtin/reward/reward.go index a4f936d9b..cfa82c774 100644 --- a/chain/actors/builtin/reward/reward.go +++ b/chain/actors/builtin/reward/reward.go @@ -29,7 +29,7 @@ func Load(store adt.Store, act *types.Actor) (st State, err error) { } type State interface { - cbor.Er + cbor.Marshaler ThisEpochBaselinePower() (abi.StoragePower, error) ThisEpochReward() (abi.StoragePower, error) From 476e7992e8e58de64c848081b03136a5e51c1644 Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Wed, 23 Sep 2020 01:19:43 -0400 Subject: [PATCH 171/303] Add an error return to all actor state interface methods --- chain/actors/builtin/market/market.go | 6 +- chain/actors/builtin/market/v0.go | 18 ++--- chain/actors/builtin/miner/miner.go | 6 +- chain/actors/builtin/miner/v0.go | 16 ++--- chain/actors/builtin/multisig/multisig.go | 10 +-- chain/actors/builtin/multisig/v0.go | 20 +++--- chain/actors/builtin/paych/mock/mock.go | 24 +++---- chain/actors/builtin/paych/paych.go | 12 ++-- chain/actors/builtin/paych/v0.go | 24 +++---- chain/events/state/predicates.go | 37 ++++++++-- chain/stmgr/stmgr.go | 23 +++++-- cli/multisig.go | 29 ++++++-- cli/paych_test.go | 4 +- cmd/lotus-chainwatch/processor/miner.go | 6 +- cmd/lotus-shed/genesis-verify.go | 13 +++- node/impl/full/state.go | 7 +- paychmgr/paych.go | 83 +++++++++++++++++------ paychmgr/simple.go | 6 +- paychmgr/state.go | 12 +++- 19 files changed, 245 insertions(+), 111 deletions(-) diff --git a/chain/actors/builtin/market/market.go b/chain/actors/builtin/market/market.go index 9cb0ffc13..84872b04b 100644 --- a/chain/actors/builtin/market/market.go +++ b/chain/actors/builtin/market/market.go @@ -31,13 +31,13 @@ func Load(store adt.Store, act *types.Actor) (st State, err error) { type State interface { cbor.Marshaler - BalancesChanged(State) bool + BalancesChanged(State) (bool, error) EscrowTable() (BalanceTable, error) LockedTable() (BalanceTable, error) TotalLocked() (abi.TokenAmount, error) - StatesChanged(State) bool + StatesChanged(State) (bool, error) States() (DealStates, error) - ProposalsChanged(State) bool + ProposalsChanged(State) (bool, error) Proposals() (DealProposals, error) VerifyDealsForActivation( minerAddr address.Address, deals []abi.DealID, currEpoch, sectorExpiry abi.ChainEpoch, diff --git a/chain/actors/builtin/market/v0.go b/chain/actors/builtin/market/v0.go index 14b8b7d93..2727f513d 100644 --- a/chain/actors/builtin/market/v0.go +++ b/chain/actors/builtin/market/v0.go @@ -25,24 +25,24 @@ func (s *state0) TotalLocked() (abi.TokenAmount, error) { return fml, nil } -func (s *state0) BalancesChanged(otherState State) bool { +func (s *state0) BalancesChanged(otherState State) (bool, error) { otherState0, ok := otherState.(*state0) if !ok { // there's no way to compare different versions of the state, so let's // just say that means the state of balances has changed - return true + return true, nil } - return !s.State.EscrowTable.Equals(otherState0.State.EscrowTable) || !s.State.LockedTable.Equals(otherState0.State.LockedTable) + return !s.State.EscrowTable.Equals(otherState0.State.EscrowTable) || !s.State.LockedTable.Equals(otherState0.State.LockedTable), nil } -func (s *state0) StatesChanged(otherState State) bool { +func (s *state0) StatesChanged(otherState State) (bool, error) { otherState0, ok := otherState.(*state0) if !ok { // there's no way to compare different versions of the state, so let's // just say that means the state of balances has changed - return true + return true, nil } - return !s.State.States.Equals(otherState0.State.States) + return !s.State.States.Equals(otherState0.State.States), nil } func (s *state0) States() (DealStates, error) { @@ -53,14 +53,14 @@ func (s *state0) States() (DealStates, error) { return &dealStates0{stateArray}, nil } -func (s *state0) ProposalsChanged(otherState State) bool { +func (s *state0) ProposalsChanged(otherState State) (bool, error) { otherState0, ok := otherState.(*state0) if !ok { // there's no way to compare different versions of the state, so let's // just say that means the state of balances has changed - return true + return true, nil } - return !s.State.Proposals.Equals(otherState0.State.Proposals) + return !s.State.Proposals.Equals(otherState0.State.Proposals), nil } func (s *state0) Proposals() (DealProposals, error) { diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index dbb4ddd73..50a0fc5ca 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -58,11 +58,11 @@ type State interface { LoadDeadline(idx uint64) (Deadline, error) ForEachDeadline(cb func(idx uint64, dl Deadline) error) error NumDeadlines() (uint64, error) - DeadlinesChanged(State) bool + DeadlinesChanged(State) (bool, error) Info() (MinerInfo, error) - DeadlineInfo(epoch abi.ChainEpoch) *dline.Info + DeadlineInfo(epoch abi.ChainEpoch) (*dline.Info, error) // Diff helpers. Used by Diff* functions internally. sectors() (adt.Array, error) @@ -76,7 +76,7 @@ type Deadline interface { ForEachPartition(cb func(idx uint64, part Partition) error) error PostSubmissions() (bitfield.BitField, error) - PartitionsChanged(Deadline) bool + PartitionsChanged(Deadline) (bool, error) } type Partition interface { diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index a56778156..e515b9ed6 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -244,14 +244,14 @@ func (s *state0) NumDeadlines() (uint64, error) { return miner0.WPoStPeriodDeadlines, nil } -func (s *state0) DeadlinesChanged(other State) bool { +func (s *state0) DeadlinesChanged(other State) (bool, error) { other0, ok := other.(*state0) if !ok { // treat an upgrade as a change, always - return true + return true, nil } - return s.State.Deadlines.Equals(other0.Deadlines) + return s.State.Deadlines.Equals(other0.Deadlines), nil } func (s *state0) Info() (MinerInfo, error) { @@ -288,8 +288,8 @@ func (s *state0) Info() (MinerInfo, error) { return mi, nil } -func (s *state0) DeadlineInfo(epoch abi.ChainEpoch) *dline.Info { - return s.State.DeadlineInfo(epoch) +func (s *state0) DeadlineInfo(epoch abi.ChainEpoch) (*dline.Info, error) { + return s.State.DeadlineInfo(epoch), nil } func (s *state0) sectors() (adt.Array, error) { @@ -339,14 +339,14 @@ func (d *deadline0) ForEachPartition(cb func(uint64, Partition) error) error { }) } -func (d *deadline0) PartitionsChanged(other Deadline) bool { +func (d *deadline0) PartitionsChanged(other Deadline) (bool, error) { other0, ok := other.(*deadline0) if !ok { // treat an upgrade as a change, always - return true + return true, nil } - return d.Deadline.Partitions.Equals(other0.Deadline.Partitions) + return d.Deadline.Partitions.Equals(other0.Deadline.Partitions), nil } func (d *deadline0) PostSubmissions() (bitfield.BitField, error) { diff --git a/chain/actors/builtin/multisig/multisig.go b/chain/actors/builtin/multisig/multisig.go index 226eed75b..884b6f493 100644 --- a/chain/actors/builtin/multisig/multisig.go +++ b/chain/actors/builtin/multisig/multisig.go @@ -31,11 +31,11 @@ type State interface { cbor.Marshaler LockedBalance(epoch abi.ChainEpoch) (abi.TokenAmount, error) - StartEpoch() abi.ChainEpoch - UnlockDuration() abi.ChainEpoch - InitialBalance() abi.TokenAmount - Threshold() uint64 - Signers() []address.Address + StartEpoch() (abi.ChainEpoch, error) + UnlockDuration() (abi.ChainEpoch, error) + InitialBalance() (abi.TokenAmount, error) + Threshold() (uint64, error) + Signers() ([]address.Address, error) ForEachPendingTxn(func(id int64, txn Transaction) error) error } diff --git a/chain/actors/builtin/multisig/v0.go b/chain/actors/builtin/multisig/v0.go index e81a367cf..ae0a7ac0e 100644 --- a/chain/actors/builtin/multisig/v0.go +++ b/chain/actors/builtin/multisig/v0.go @@ -23,24 +23,24 @@ func (s *state0) LockedBalance(currEpoch abi.ChainEpoch) (abi.TokenAmount, error return s.State.AmountLocked(currEpoch - s.State.StartEpoch), nil } -func (s *state0) StartEpoch() abi.ChainEpoch { - return s.State.StartEpoch +func (s *state0) StartEpoch() (abi.ChainEpoch, error) { + return s.State.StartEpoch, nil } -func (s *state0) UnlockDuration() abi.ChainEpoch { - return s.State.UnlockDuration +func (s *state0) UnlockDuration() (abi.ChainEpoch, error) { + return s.State.UnlockDuration, nil } -func (s *state0) InitialBalance() abi.TokenAmount { - return s.State.InitialBalance +func (s *state0) InitialBalance() (abi.TokenAmount, error) { + return s.State.InitialBalance, nil } -func (s *state0) Threshold() uint64 { - return s.State.NumApprovalsThreshold +func (s *state0) Threshold() (uint64, error) { + return s.State.NumApprovalsThreshold, nil } -func (s *state0) Signers() []address.Address { - return s.State.Signers +func (s *state0) Signers() ([]address.Address, error) { + return s.State.Signers, nil } func (s *state0) ForEachPendingTxn(cb func(id int64, txn Transaction) error) error { diff --git a/chain/actors/builtin/paych/mock/mock.go b/chain/actors/builtin/paych/mock/mock.go index 31f7fba93..c4903f3ac 100644 --- a/chain/actors/builtin/paych/mock/mock.go +++ b/chain/actors/builtin/paych/mock/mock.go @@ -45,23 +45,23 @@ func (ms *mockState) MarshalCBOR(io.Writer) error { } // Channel owner, who has funded the actor -func (ms *mockState) From() address.Address { - return ms.from +func (ms *mockState) From() (address.Address, error) { + return ms.from, nil } // Recipient of payouts from channel -func (ms *mockState) To() address.Address { - return ms.to +func (ms *mockState) To() (address.Address, error) { + return ms.to, nil } // Height at which the channel can be `Collected` -func (ms *mockState) SettlingAt() abi.ChainEpoch { - return ms.settlingAt +func (ms *mockState) SettlingAt() (abi.ChainEpoch, error) { + return ms.settlingAt, nil } // Amount successfully redeemed through the payment channel, paid out on `Collect()` -func (ms *mockState) ToSend() abi.TokenAmount { - return ms.toSend +func (ms *mockState) ToSend() (abi.TokenAmount, error) { + return ms.toSend, nil } // Get total number of lanes @@ -80,10 +80,10 @@ func (ms *mockState) ForEachLaneState(cb func(idx uint64, dl paych.LaneState) er return lastErr } -func (mls *mockLaneState) Redeemed() big.Int { - return mls.redeemed +func (mls *mockLaneState) Redeemed() (big.Int, error) { + return mls.redeemed, nil } -func (mls *mockLaneState) Nonce() uint64 { - return mls.nonce +func (mls *mockLaneState) Nonce() (uint64, error) { + return mls.nonce, nil } diff --git a/chain/actors/builtin/paych/paych.go b/chain/actors/builtin/paych/paych.go index 0413dcdd0..dad54163f 100644 --- a/chain/actors/builtin/paych/paych.go +++ b/chain/actors/builtin/paych/paych.go @@ -33,15 +33,15 @@ func Load(store adt.Store, act *types.Actor) (State, error) { type State interface { cbor.Marshaler // Channel owner, who has funded the actor - From() address.Address + From() (address.Address, error) // Recipient of payouts from channel - To() address.Address + To() (address.Address, error) // Height at which the channel can be `Collected` - SettlingAt() abi.ChainEpoch + SettlingAt() (abi.ChainEpoch, error) // Amount successfully redeemed through the payment channel, paid out on `Collect()` - ToSend() abi.TokenAmount + ToSend() (abi.TokenAmount, error) // Get total number of lanes LaneCount() (uint64, error) @@ -52,8 +52,8 @@ type State interface { // LaneState is an abstract copy of the state of a single lane type LaneState interface { - Redeemed() big.Int - Nonce() uint64 + Redeemed() (big.Int, error) + Nonce() (uint64, error) } type SignedVoucher = paych0.SignedVoucher diff --git a/chain/actors/builtin/paych/v0.go b/chain/actors/builtin/paych/v0.go index b69cf46ce..c0eea1000 100644 --- a/chain/actors/builtin/paych/v0.go +++ b/chain/actors/builtin/paych/v0.go @@ -18,23 +18,23 @@ type state0 struct { } // Channel owner, who has funded the actor -func (s *state0) From() address.Address { - return s.State.From +func (s *state0) From() (address.Address, error) { + return s.State.From, nil } // Recipient of payouts from channel -func (s *state0) To() address.Address { - return s.State.To +func (s *state0) To() (address.Address, error) { + return s.State.To, nil } // Height at which the channel can be `Collected` -func (s *state0) SettlingAt() abi.ChainEpoch { - return s.State.SettlingAt +func (s *state0) SettlingAt() (abi.ChainEpoch, error) { + return s.State.SettlingAt, nil } // Amount successfully redeemed through the payment channel, paid out on `Collect()` -func (s *state0) ToSend() abi.TokenAmount { - return s.State.ToSend +func (s *state0) ToSend() (abi.TokenAmount, error) { + return s.State.ToSend, nil } func (s *state0) getOrLoadLsAmt() (*adt0.Array, error) { @@ -82,10 +82,10 @@ type laneState0 struct { paych.LaneState } -func (ls *laneState0) Redeemed() big.Int { - return ls.LaneState.Redeemed +func (ls *laneState0) Redeemed() (big.Int, error) { + return ls.LaneState.Redeemed, nil } -func (ls *laneState0) Nonce() uint64 { - return ls.LaneState.Nonce +func (ls *laneState0) Nonce() (uint64, error) { + return ls.LaneState.Nonce, nil } diff --git a/chain/events/state/predicates.go b/chain/events/state/predicates.go index 909533d15..e6c2fa084 100644 --- a/chain/events/state/predicates.go +++ b/chain/events/state/predicates.go @@ -97,7 +97,12 @@ type DiffBalanceTablesFunc func(ctx context.Context, oldBalanceTable, newBalance // OnBalanceChanged runs when the escrow table for available balances changes func (sp *StatePredicates) OnBalanceChanged(diffBalances DiffBalanceTablesFunc) DiffStorageMarketStateFunc { return func(ctx context.Context, oldState market.State, newState market.State) (changed bool, user UserData, err error) { - if !oldState.BalancesChanged(newState) { + bc, err := oldState.BalancesChanged(newState) + if err != nil { + return false, nil, err + } + + if !bc { return false, nil, nil } @@ -132,7 +137,12 @@ type DiffAdtArraysFunc func(ctx context.Context, oldDealStateRoot, newDealStateR // OnDealStateChanged calls diffDealStates when the market deal state changes func (sp *StatePredicates) OnDealStateChanged(diffDealStates DiffDealStatesFunc) DiffStorageMarketStateFunc { return func(ctx context.Context, oldState market.State, newState market.State) (changed bool, user UserData, err error) { - if !oldState.StatesChanged(newState) { + sc, err := oldState.StatesChanged(newState) + if err != nil { + return false, nil, err + } + + if !sc { return false, nil, nil } @@ -152,7 +162,12 @@ func (sp *StatePredicates) OnDealStateChanged(diffDealStates DiffDealStatesFunc) // OnDealProposalChanged calls diffDealProps when the market proposal state changes func (sp *StatePredicates) OnDealProposalChanged(diffDealProps DiffDealProposalsFunc) DiffStorageMarketStateFunc { return func(ctx context.Context, oldState market.State, newState market.State) (changed bool, user UserData, err error) { - if !oldState.ProposalsChanged(newState) { + pc, err := oldState.ProposalsChanged(newState) + if err != nil { + return false, nil, err + } + + if !pc { return false, nil, nil } @@ -379,12 +394,22 @@ type PayChToSendChange struct { // OnToSendAmountChanges monitors changes on the total amount to send from one party to the other on a payment channel func (sp *StatePredicates) OnToSendAmountChanges() DiffPaymentChannelStateFunc { return func(ctx context.Context, oldState paych.State, newState paych.State) (changed bool, user UserData, err error) { - if oldState.ToSend().Equals(newState.ToSend()) { + ots, err := oldState.ToSend() + if err != nil { + return false, nil, err + } + + nts, err := newState.ToSend() + if err != nil { + return false, nil, err + } + + if ots.Equals(nts) { return false, nil, nil } return true, &PayChToSendChange{ - OldToSend: oldState.ToSend(), - NewToSend: newState.ToSend(), + OldToSend: ots, + NewToSend: nts, }, nil } } diff --git a/chain/stmgr/stmgr.go b/chain/stmgr/stmgr.go index af729143c..eaf9215db 100644 --- a/chain/stmgr/stmgr.go +++ b/chain/stmgr/stmgr.go @@ -843,15 +843,30 @@ func (sm *StateManager) setupGenesisActors(ctx context.Context) error { return err } - if s.StartEpoch() != 0 { + se, err := s.StartEpoch() + if err != nil { + return err + } + + if se != 0 { return xerrors.New("genesis multisig doesn't start vesting at epoch 0!") } - ot, f := totalsByEpoch[s.UnlockDuration()] + ud, err := s.UnlockDuration() + if err != nil { + return err + } + + ib, err := s.InitialBalance() + if err != nil { + return err + } + + ot, f := totalsByEpoch[ud] if f { - totalsByEpoch[s.UnlockDuration()] = big.Add(ot, s.InitialBalance()) + totalsByEpoch[ud] = big.Add(ot, ib) } else { - totalsByEpoch[s.UnlockDuration()] = s.InitialBalance() + totalsByEpoch[ud] = ib } } else if act.IsAccountActor() { diff --git a/cli/multisig.go b/cli/multisig.go index 81c6502d5..0cb4028a9 100644 --- a/cli/multisig.go +++ b/cli/multisig.go @@ -206,13 +206,32 @@ var msigInspectCmd = &cli.Command{ fmt.Printf("Spendable: %s\n", types.FIL(types.BigSub(act.Balance, locked))) if cctx.Bool("vesting") { - fmt.Printf("InitialBalance: %s\n", types.FIL(mstate.InitialBalance())) - fmt.Printf("StartEpoch: %d\n", mstate.StartEpoch()) - fmt.Printf("UnlockDuration: %d\n", mstate.UnlockDuration()) + ib, err := mstate.InitialBalance() + if err != nil { + return err + } + fmt.Printf("InitialBalance: %s\n", types.FIL(ib)) + se, err := mstate.StartEpoch() + if err != nil { + return err + } + fmt.Printf("StartEpoch: %d\n", se) + ud, err := mstate.UnlockDuration() + if err != nil { + return err + } + fmt.Printf("UnlockDuration: %d\n", ud) } - signers := mstate.Signers() - fmt.Printf("Threshold: %d / %d\n", mstate.Threshold(), len(signers)) + signers, err := mstate.Signers() + if err != nil { + return err + } + threshold, err := mstate.Threshold() + if err != nil { + return err + } + fmt.Printf("Threshold: %d / %d\n", threshold, len(signers)) fmt.Println("Signers:") for _, s := range signers { fmt.Printf("\t%s\n", s) diff --git a/cli/paych_test.go b/cli/paych_test.go index 49631f1fc..47a84fe5e 100644 --- a/cli/paych_test.go +++ b/cli/paych_test.go @@ -89,7 +89,9 @@ func TestPaymentChannels(t *testing.T) { // Wait for the chain to reach the settle height chState := getPaychState(ctx, t, paymentReceiver, chAddr) - waitForHeight(ctx, t, paymentReceiver, chState.SettlingAt()) + sa, err := chState.SettlingAt() + require.NoError(t, err) + waitForHeight(ctx, t, paymentReceiver, sa) // receiver: paych collect cmd = []string{chAddr.String()} diff --git a/cmd/lotus-chainwatch/processor/miner.go b/cmd/lotus-chainwatch/processor/miner.go index 17eef3afa..3a37a82f8 100644 --- a/cmd/lotus-chainwatch/processor/miner.go +++ b/cmd/lotus-chainwatch/processor/miner.go @@ -684,7 +684,11 @@ func (p *Processor) diffMinerPartitions(ctx context.Context, m minerActorInfo, e return err } curMiner := m.state - if !prevMiner.DeadlinesChanged(curMiner) { + dc, err := prevMiner.DeadlinesChanged(curMiner) + if err != nil { + return err + } + if !dc { return nil } panic("TODO") diff --git a/cmd/lotus-shed/genesis-verify.go b/cmd/lotus-shed/genesis-verify.go index 1225d817a..da2c82359 100644 --- a/cmd/lotus-shed/genesis-verify.go +++ b/cmd/lotus-shed/genesis-verify.go @@ -108,10 +108,19 @@ var genesisVerifyCmd = &cli.Command{ return xerrors.Errorf("multisig actor: %w", err) } + signers, err := st.Signers() + if err != nil { + return xerrors.Errorf("multisig actor: %w", err) + } + threshold, err := st.Threshold() + if err != nil { + return xerrors.Errorf("multisig actor: %w", err) + } + kmultisigs[addr] = msigInfo{ Balance: types.FIL(act.Balance), - Signers: st.Signers(), - Threshold: st.Threshold(), + Signers: signers, + Threshold: threshold, } msigAddrs = append(msigAddrs, addr) case act.IsAccountActor(): diff --git a/node/impl/full/state.go b/node/impl/full/state.go index 109a265ea..f8bf92a92 100644 --- a/node/impl/full/state.go +++ b/node/impl/full/state.go @@ -212,7 +212,12 @@ func (a *StateAPI) StateMinerProvingDeadline(ctx context.Context, addr address.A return nil, xerrors.Errorf("failed to load miner actor state: %w", err) } - return mas.DeadlineInfo(ts.Height()).NextNotElapsed(), nil + di, err := mas.DeadlineInfo(ts.Height()) + if err != nil { + return nil, xerrors.Errorf("failed to get deadline info: %w", err) + } + + return di.NextNotElapsed(), nil } func (a *StateAPI) StateMinerFaults(ctx context.Context, addr address.Address, tsk types.TipSetKey) (bitfield.BitField, error) { diff --git a/paychmgr/paych.go b/paychmgr/paych.go index 11dfd2a1e..f856b9890 100644 --- a/paychmgr/paych.go +++ b/paychmgr/paych.go @@ -48,12 +48,12 @@ type laneState struct { nonce uint64 } -func (ls laneState) Redeemed() big.Int { - return ls.redeemed +func (ls laneState) Redeemed() (big.Int, error) { + return ls.redeemed, nil } -func (ls laneState) Nonce() uint64 { - return ls.nonce +func (ls laneState) Nonce() (uint64, error) { + return ls.nonce, nil } // channelAccessor is used to simplify locking when accessing a channel @@ -181,7 +181,12 @@ func (ca *channelAccessor) checkVoucherValidUnlocked(ctx context.Context, ch add } // Load channel "From" account actor state - from, err := ca.api.ResolveToKeyAddress(ctx, pchState.From(), nil) + f, err := pchState.From() + if err != nil { + return nil, err + } + + from, err := ca.api.ResolveToKeyAddress(ctx, f, nil) if err != nil { return nil, err } @@ -208,13 +213,24 @@ func (ca *channelAccessor) checkVoucherValidUnlocked(ctx context.Context, ch add // If the new voucher nonce value is less than the highest known // nonce for the lane ls, lsExists := laneStates[sv.Lane] - if lsExists && sv.Nonce <= ls.Nonce() { - return nil, fmt.Errorf("nonce too low") - } + if lsExists { + n, err := ls.Nonce() + if err != nil { + return nil, err + } - // If the voucher amount is less than the highest known voucher amount - if lsExists && sv.Amount.LessThanEqual(ls.Redeemed()) { - return nil, fmt.Errorf("voucher amount is lower than amount for voucher with lower nonce") + if sv.Nonce <= n { + return nil, fmt.Errorf("nonce too low") + } + + // If the voucher amount is less than the highest known voucher amount + r, err := ls.Redeemed() + if err != nil { + return nil, err + } + if sv.Amount.LessThanEqual(r) { + return nil, fmt.Errorf("voucher amount is lower than amount for voucher with lower nonce") + } } // Total redeemed is the total redeemed amount for all lanes, including @@ -239,7 +255,12 @@ func (ca *channelAccessor) checkVoucherValidUnlocked(ctx context.Context, ch add // Total required balance = total redeemed + toSend // Must not exceed actor balance - newTotal := types.BigAdd(totalRedeemed, pchState.ToSend()) + ts, err := pchState.ToSend() + if err != nil { + return nil, err + } + + newTotal := types.BigAdd(totalRedeemed, ts) if act.Balance.LessThan(newTotal) { return nil, newErrInsufficientFunds(types.BigSub(newTotal, act.Balance)) } @@ -322,7 +343,7 @@ func (ca *channelAccessor) getPaychRecipient(ctx context.Context, ch address.Add return address.Address{}, err } - return state.To(), nil + return state.To() } func (ca *channelAccessor) addVoucher(ctx context.Context, ch address.Address, sv *paych0.SignedVoucher, proof []byte, minDelta types.BigInt) (types.BigInt, error) { @@ -376,7 +397,10 @@ func (ca *channelAccessor) addVoucherUnlocked(ctx context.Context, ch address.Ad laneState, exists := laneStates[sv.Lane] redeemed := big.NewInt(0) if exists { - redeemed = laneState.Redeemed() + redeemed, err = laneState.Redeemed() + if err != nil { + return types.NewInt(0), err + } } delta := types.BigSub(sv.Amount, redeemed) @@ -531,9 +555,14 @@ func (ca *channelAccessor) laneState(ctx context.Context, state paych.State, ch // If there's a voucher for a lane that isn't in chain state just // create it ls, ok := laneStates[v.Voucher.Lane] - - if ok && v.Voucher.Nonce < ls.Nonce() { - continue + if ok { + n, err := ls.Nonce() + if err != nil { + return nil, err + } + if v.Voucher.Nonce < n { + continue + } } laneStates[v.Voucher.Lane] = laneState{v.Voucher.Amount, v.Voucher.Nonce} @@ -551,17 +580,31 @@ func (ca *channelAccessor) totalRedeemedWithVoucher(laneStates map[uint64]paych. total := big.NewInt(0) for _, ls := range laneStates { - total = big.Add(total, ls.Redeemed()) + r, err := ls.Redeemed() + if err != nil { + return big.Int{}, err + } + total = big.Add(total, r) } lane, ok := laneStates[sv.Lane] if ok { // If the voucher is for an existing lane, and the voucher nonce // is higher than the lane nonce - if sv.Nonce > lane.Nonce() { + n, err := lane.Nonce() + if err != nil { + return big.Int{}, err + } + + if sv.Nonce > n { // Add the delta between the redeemed amount and the voucher // amount to the total - delta := big.Sub(sv.Amount, lane.Redeemed()) + r, err := lane.Redeemed() + if err != nil { + return big.Int{}, err + } + + delta := big.Sub(sv.Amount, r) total = big.Add(total, delta) } } else { diff --git a/paychmgr/simple.go b/paychmgr/simple.go index 815b8acab..d2a42a673 100644 --- a/paychmgr/simple.go +++ b/paychmgr/simple.go @@ -317,7 +317,11 @@ func (ca *channelAccessor) currentAvailableFunds(channelID string, queuedAmt typ } for _, ls := range laneStates { - totalRedeemed = types.BigAdd(totalRedeemed, ls.Redeemed()) + r, err := ls.Redeemed() + if err != nil { + return nil, err + } + totalRedeemed = types.BigAdd(totalRedeemed, r) } } diff --git a/paychmgr/state.go b/paychmgr/state.go index 2571ef73e..65963d2a0 100644 --- a/paychmgr/state.go +++ b/paychmgr/state.go @@ -24,11 +24,19 @@ func (ca *stateAccessor) loadStateChannelInfo(ctx context.Context, ch address.Ad } // Load channel "From" account actor state - from, err := ca.sm.ResolveToKeyAddress(ctx, st.From(), nil) + f, err := st.From() if err != nil { return nil, err } - to, err := ca.sm.ResolveToKeyAddress(ctx, st.To(), nil) + from, err := ca.sm.ResolveToKeyAddress(ctx, f, nil) + if err != nil { + return nil, err + } + t, err := st.To() + if err != nil { + return nil, err + } + to, err := ca.sm.ResolveToKeyAddress(ctx, t, nil) if err != nil { return nil, err } From 819180f739c7d6c15eb7d4c00ab5218c7d30096f Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Wed, 23 Sep 2020 02:14:28 -0400 Subject: [PATCH 172/303] Implement inefficient OnAddressMapChange predicate --- chain/events/state/predicates.go | 72 ++++++++++++++++++++++++-------- 1 file changed, 55 insertions(+), 17 deletions(-) diff --git a/chain/events/state/predicates.go b/chain/events/state/predicates.go index e6c2fa084..99b8480dc 100644 --- a/chain/events/state/predicates.go +++ b/chain/events/state/predicates.go @@ -519,32 +519,72 @@ func (i *InitActorAddressChanges) Remove(key string, val *typegen.Deferred) erro func (sp *StatePredicates) OnAddressMapChange() DiffInitActorStateFunc { return func(ctx context.Context, oldState, newState init_.State) (changed bool, user UserData, err error) { - /*ctxStore := &contextStore{ - ctx: ctx, - cst: sp.cst, - } - addressChanges := &InitActorAddressChanges{ Added: []AddressPair{}, Modified: []AddressChange{}, Removed: []AddressPair{}, } - if oldState.AddressMap.Equals(newState.AddressMap) { - return false, nil, nil - } + err = oldState.ForEachActor(func(oldId abi.ActorID, oldAddress address.Address) error { + oldIdAddress, err := address.NewIDAddress(uint64(oldId)) + if err != nil { + return err + } + + newIdAddress, found, err := newState.ResolveAddress(oldAddress) + if err != nil { + return err + } + + if !found { + addressChanges.Removed = append(addressChanges.Removed, AddressPair{ + ID: oldIdAddress, + PK: oldAddress, + }) + } + + if oldIdAddress != newIdAddress { + addressChanges.Modified = append(addressChanges.Modified, AddressChange{ + From: AddressPair{ + ID: oldIdAddress, + PK: oldAddress, + }, + To: AddressPair{ + ID: newIdAddress, + PK: oldAddress, + }, + }) + } + + return nil + }) - oldAddrs, err := adt0.AsMap(ctxStore, oldState.AddressMap) if err != nil { return false, nil, err } - newAddrs, err := adt0.AsMap(ctxStore, newState.AddressMap) - if err != nil { - return false, nil, err - } + err = newState.ForEachActor(func(newId abi.ActorID, newAddress address.Address) error { + newIdAddress, err := address.NewIDAddress(uint64(newId)) + if err != nil { + return err + } - if err := adt.DiffAdtMap(oldAddrs, newAddrs, addressChanges); err != nil { + _, found, err := newState.ResolveAddress(newAddress) + if err != nil { + return err + } + + if !found { + addressChanges.Added = append(addressChanges.Added, AddressPair{ + ID: newIdAddress, + PK: newAddress, + }) + } + + return nil + }) + + if err != nil { return false, nil, err } @@ -552,8 +592,6 @@ func (sp *StatePredicates) OnAddressMapChange() DiffInitActorStateFunc { return false, nil, nil } - return true, addressChanges, nil*/ - - panic("TODO") + return true, addressChanges, nil } } From a876a0ba443afee1477567b06679edf2f3ce21f2 Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Wed, 23 Sep 2020 02:18:52 -0400 Subject: [PATCH 173/303] Use actor state addresses --- chain/actors/builtin/market/market.go | 7 +++++ chain/gen/genesis/miners.go | 37 +++++++++++++++------------ chain/market/fundmgr.go | 3 ++- chain/market/fundmgr_test.go | 3 ++- chain/stmgr/forks_test.go | 3 ++- chain/store/weight.go | 3 +-- chain/sync.go | 3 +-- chain/vm/vm.go | 3 ++- paychmgr/paychget_test.go | 9 ++++--- paychmgr/simple.go | 3 ++- 10 files changed, 45 insertions(+), 29 deletions(-) diff --git a/chain/actors/builtin/market/market.go b/chain/actors/builtin/market/market.go index 84872b04b..fef0c03f9 100644 --- a/chain/actors/builtin/market/market.go +++ b/chain/actors/builtin/market/market.go @@ -7,6 +7,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/cbor" builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" + market0 "github.com/filecoin-project/specs-actors/actors/builtin/market" "github.com/ipfs/go-cid" cbg "github.com/whyrusleeping/cbor-gen" @@ -65,6 +66,12 @@ type DealProposals interface { decode(*cbg.Deferred) (*DealProposal, error) } +type PublishStorageDealsParams = market0.PublishStorageDealsParams +type PublishStorageDealsReturn = market0.PublishStorageDealsReturn +type VerifyDealsForActivationParams = market0.VerifyDealsForActivationParams + +type ClientDealProposal = market0.ClientDealProposal + type DealState struct { SectorStartEpoch abi.ChainEpoch // -1 if not yet included in proven sector LastUpdatedEpoch abi.ChainEpoch // -1 if deal state never updated diff --git a/chain/gen/genesis/miners.go b/chain/gen/genesis/miners.go index 853c9c4a0..1023e5efa 100644 --- a/chain/gen/genesis/miners.go +++ b/chain/gen/genesis/miners.go @@ -6,6 +6,12 @@ import ( "fmt" "math/rand" + market0 "github.com/filecoin-project/specs-actors/actors/builtin/market" + + "github.com/filecoin-project/lotus/chain/actors/builtin/power" + "github.com/filecoin-project/lotus/chain/actors/builtin/reward" + + "github.com/filecoin-project/lotus/chain/actors/builtin/market" "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/ipfs/go-cid" @@ -19,7 +25,6 @@ import ( "github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" "github.com/filecoin-project/specs-actors/actors/builtin" - "github.com/filecoin-project/specs-actors/actors/builtin/market" miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" reward0 "github.com/filecoin-project/specs-actors/actors/builtin/reward" @@ -109,7 +114,7 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid } params := mustEnc(constructorParams) - rval, err := doExecValue(ctx, vm, builtin.StoragePowerActorAddr, m.Owner, m.PowerBalance, builtin.MethodsPower.CreateMiner, params) + rval, err := doExecValue(ctx, vm, power.Address, m.Owner, m.PowerBalance, builtin.MethodsPower.CreateMiner, params) if err != nil { return cid.Undef, xerrors.Errorf("failed to create genesis miner: %w", err) } @@ -141,7 +146,7 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid if m.MarketBalance.GreaterThan(big.Zero()) { params := mustEnc(&minerInfos[i].maddr) - _, err := doExecValue(ctx, vm, builtin.StorageMarketActorAddr, m.Worker, m.MarketBalance, builtin.MethodsMarket.AddBalance, params) + _, err := doExecValue(ctx, vm, market.Address, m.Worker, m.MarketBalance, builtin.MethodsMarket.AddBalance, params) if err != nil { return cid.Undef, xerrors.Errorf("failed to create genesis miner (add balance): %w", err) } @@ -153,7 +158,7 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid publish := func(params *market.PublishStorageDealsParams) error { fmt.Printf("publishing %d storage deals on miner %s with worker %s\n", len(params.Deals), params.Deals[0].Proposal.Provider, m.Worker) - ret, err := doExecValue(ctx, vm, builtin.StorageMarketActorAddr, m.Worker, big.Zero(), builtin.MethodsMarket.PublishStorageDeals, mustEnc(params)) + ret, err := doExecValue(ctx, vm, market.Address, m.Worker, big.Zero(), builtin.MethodsMarket.PublishStorageDeals, mustEnc(params)) if err != nil { return xerrors.Errorf("failed to create genesis miner (publish deals): %w", err) } @@ -210,7 +215,7 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid } } - err = vm.MutateState(ctx, builtin.StoragePowerActorAddr, func(cst cbor.IpldStore, st *power0.State) error { + err = vm.MutateState(ctx, power.Address, func(cst cbor.IpldStore, st *power0.State) error { st.TotalQualityAdjPower = qaPow st.TotalRawBytePower = rawPow @@ -222,7 +227,7 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid return cid.Undef, xerrors.Errorf("mutating state: %w", err) } - err = vm.MutateState(ctx, builtin.RewardActorAddr, func(sct cbor.IpldStore, st *reward0.State) error { + err = vm.MutateState(ctx, reward.Address, func(sct cbor.IpldStore, st *reward0.State) error { *st = *reward0.ConstructState(qaPow) return nil }) @@ -252,7 +257,7 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid sectorWeight := miner0.QAPowerForWeight(m.SectorSize, minerInfos[i].presealExp, dweight.DealWeight, dweight.VerifiedDealWeight) // we've added fake power for this sector above, remove it now - err = vm.MutateState(ctx, builtin.StoragePowerActorAddr, func(cst cbor.IpldStore, st *power0.State) error { + err = vm.MutateState(ctx, power.Address, func(cst cbor.IpldStore, st *power0.State) error { st.TotalQualityAdjPower = types.BigSub(st.TotalQualityAdjPower, sectorWeight) //nolint:scopelint st.TotalRawBytePower = types.BigSub(st.TotalRawBytePower, types.NewInt(uint64(m.SectorSize))) return nil @@ -295,7 +300,7 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid Sectors: []abi.SectorNumber{preseal.SectorID}, } - _, err = doExecValue(ctx, vm, minerInfos[i].maddr, builtin.StoragePowerActorAddr, big.Zero(), builtin.MethodsMiner.ConfirmSectorProofsValid, mustEnc(confirmParams)) + _, err = doExecValue(ctx, vm, minerInfos[i].maddr, power.Address, big.Zero(), builtin.MethodsMiner.ConfirmSectorProofsValid, mustEnc(confirmParams)) if err != nil { return cid.Undef, xerrors.Errorf("failed to confirm presealed sectors: %w", err) } @@ -304,7 +309,7 @@ func SetupStorageMiners(ctx context.Context, cs *store.ChainStore, sroot cid.Cid } // Sanity-check total network power - err = vm.MutateState(ctx, builtin.StoragePowerActorAddr, func(cst cbor.IpldStore, st *power0.State) error { + err = vm.MutateState(ctx, power.Address, func(cst cbor.IpldStore, st *power0.State) error { if !st.TotalRawBytePower.Equals(rawPow) { return xerrors.Errorf("st.TotalRawBytePower doesn't match previously calculated rawPow") } @@ -344,7 +349,7 @@ func (fr *fakeRand) GetBeaconRandomness(ctx context.Context, personalization cry } func currentTotalPower(ctx context.Context, vm *vm.VM, maddr address.Address) (*power0.CurrentTotalPowerReturn, error) { - pwret, err := doExecValue(ctx, vm, builtin.StoragePowerActorAddr, maddr, big.Zero(), builtin.MethodsPower.CurrentTotalPower, nil) + pwret, err := doExecValue(ctx, vm, power.Address, maddr, big.Zero(), builtin.MethodsPower.CurrentTotalPower, nil) if err != nil { return nil, err } @@ -356,33 +361,33 @@ func currentTotalPower(ctx context.Context, vm *vm.VM, maddr address.Address) (* return &pwr, nil } -func dealWeight(ctx context.Context, vm *vm.VM, maddr address.Address, dealIDs []abi.DealID, sectorStart, sectorExpiry abi.ChainEpoch) (market.VerifyDealsForActivationReturn, error) { +func dealWeight(ctx context.Context, vm *vm.VM, maddr address.Address, dealIDs []abi.DealID, sectorStart, sectorExpiry abi.ChainEpoch) (market0.VerifyDealsForActivationReturn, error) { params := &market.VerifyDealsForActivationParams{ DealIDs: dealIDs, SectorStart: sectorStart, SectorExpiry: sectorExpiry, } - var dealWeights market.VerifyDealsForActivationReturn + var dealWeights market0.VerifyDealsForActivationReturn ret, err := doExecValue(ctx, vm, - builtin.StorageMarketActorAddr, + market.Address, maddr, abi.NewTokenAmount(0), builtin.MethodsMarket.VerifyDealsForActivation, mustEnc(params), ) if err != nil { - return market.VerifyDealsForActivationReturn{}, err + return market0.VerifyDealsForActivationReturn{}, err } if err := dealWeights.UnmarshalCBOR(bytes.NewReader(ret)); err != nil { - return market.VerifyDealsForActivationReturn{}, err + return market0.VerifyDealsForActivationReturn{}, err } return dealWeights, nil } func currentEpochBlockReward(ctx context.Context, vm *vm.VM, maddr address.Address) (*reward0.ThisEpochRewardReturn, error) { - rwret, err := doExecValue(ctx, vm, builtin.RewardActorAddr, maddr, big.Zero(), builtin.MethodsReward.ThisEpochReward, nil) + rwret, err := doExecValue(ctx, vm, reward.Address, maddr, big.Zero(), builtin.MethodsReward.ThisEpochReward, nil) if err != nil { return nil, err } diff --git a/chain/market/fundmgr.go b/chain/market/fundmgr.go index edf73d9bd..aef3b98eb 100644 --- a/chain/market/fundmgr.go +++ b/chain/market/fundmgr.go @@ -15,6 +15,7 @@ import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/chain/actors" + "github.com/filecoin-project/lotus/chain/actors/builtin/market" "github.com/filecoin-project/lotus/chain/events" "github.com/filecoin-project/lotus/chain/events/state" "github.com/filecoin-project/lotus/chain/types" @@ -151,7 +152,7 @@ func (fm *FundMgr) EnsureAvailable(ctx context.Context, addr, wallet address.Add } smsg, err := fm.api.MpoolPushMessage(ctx, &types.Message{ - To: builtin.StorageMarketActorAddr, + To: market.Address, From: wallet, Value: toAdd, Method: builtin.MethodsMarket.AddBalance, diff --git a/chain/market/fundmgr_test.go b/chain/market/fundmgr_test.go index c0e69c51c..b05db55d8 100644 --- a/chain/market/fundmgr_test.go +++ b/chain/market/fundmgr_test.go @@ -17,6 +17,7 @@ import ( "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/chain/actors" + "github.com/filecoin-project/lotus/chain/actors/builtin/market" "github.com/filecoin-project/lotus/chain/types" ) @@ -47,7 +48,7 @@ func (fapi *fakeAPI) MpoolPushMessage(ctx context.Context, msg *types.Message, s func addFundsMsg(toAdd abi.TokenAmount, addr address.Address, wallet address.Address) *types.Message { params, _ := actors.SerializeParams(&addr) return &types.Message{ - To: builtin.StorageMarketActorAddr, + To: market.Address, From: wallet, Value: toAdd, Method: builtin.MethodsMarket.AddBalance, diff --git a/chain/stmgr/forks_test.go b/chain/stmgr/forks_test.go index 87d328ce1..8c6d2ce40 100644 --- a/chain/stmgr/forks_test.go +++ b/chain/stmgr/forks_test.go @@ -19,6 +19,7 @@ import ( "github.com/filecoin-project/lotus/chain/actors" "github.com/filecoin-project/lotus/chain/actors/aerrors" + lotusinit "github.com/filecoin-project/lotus/chain/actors/builtin/init" "github.com/filecoin-project/lotus/chain/gen" "github.com/filecoin-project/lotus/chain/stmgr" . "github.com/filecoin-project/lotus/chain/stmgr" @@ -168,7 +169,7 @@ func TestForkHeightTriggers(t *testing.T) { m := &types.Message{ From: cg.Banker(), - To: builtin.InitActorAddr, + To: lotusinit.Address, Method: builtin.MethodsInit.Exec, Params: enc, GasLimit: types.TestGasLimit, diff --git a/chain/store/weight.go b/chain/store/weight.go index 2d83738c5..9100df315 100644 --- a/chain/store/weight.go +++ b/chain/store/weight.go @@ -10,7 +10,6 @@ import ( "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/types" - "github.com/filecoin-project/specs-actors/actors/builtin" cbor "github.com/ipfs/go-ipld-cbor" "golang.org/x/xerrors" ) @@ -35,7 +34,7 @@ func (cs *ChainStore) Weight(ctx context.Context, ts *types.TipSet) (types.BigIn return types.NewInt(0), xerrors.Errorf("load state tree: %w", err) } - act, err := state.GetActor(builtin.StoragePowerActorAddr) + act, err := state.GetActor(power.Address) if err != nil { return types.NewInt(0), xerrors.Errorf("get power actor: %w", err) } diff --git a/chain/sync.go b/chain/sync.go index 972321787..f641f078b 100644 --- a/chain/sync.go +++ b/chain/sync.go @@ -33,7 +33,6 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" - "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/util/adt" blst "github.com/supranational/blst/bindings/go" @@ -640,7 +639,7 @@ func (syncer *Syncer) ValidateTipSet(ctx context.Context, fts *store.FullTipSet) } func (syncer *Syncer) minerIsValid(ctx context.Context, maddr address.Address, baseTs *types.TipSet) error { - act, err := syncer.sm.LoadActor(ctx, builtin.StoragePowerActorAddr, baseTs) + act, err := syncer.sm.LoadActor(ctx, power.Address, baseTs) if err != nil { return xerrors.Errorf("failed to load power actor: %w", err) } diff --git a/chain/vm/vm.go b/chain/vm/vm.go index 049918fba..35ece7c57 100644 --- a/chain/vm/vm.go +++ b/chain/vm/vm.go @@ -28,6 +28,7 @@ import ( "github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/actors/aerrors" "github.com/filecoin-project/lotus/chain/actors/builtin/account" + "github.com/filecoin-project/lotus/chain/actors/builtin/reward" "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/lib/blockstore" @@ -493,7 +494,7 @@ func (vm *VM) ApplyMessage(ctx context.Context, cmsg types.ChainMsg) (*ApplyRet, return nil, xerrors.Errorf("failed to burn base fee: %w", err) } - if err := vm.transferFromGasHolder(builtin.RewardActorAddr, gasHolder, gasOutputs.MinerTip); err != nil { + if err := vm.transferFromGasHolder(reward.Address, gasHolder, gasOutputs.MinerTip); err != nil { return nil, xerrors.Errorf("failed to give miner gas reward: %w", err) } diff --git a/paychmgr/paychget_test.go b/paychmgr/paychget_test.go index 93233c54f..430e66c67 100644 --- a/paychmgr/paychget_test.go +++ b/paychmgr/paychget_test.go @@ -19,6 +19,7 @@ import ( init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" tutils "github.com/filecoin-project/specs-actors/support/testing" + lotusinit "github.com/filecoin-project/lotus/chain/actors/builtin/init" "github.com/filecoin-project/lotus/chain/actors/builtin/paych" paychmock "github.com/filecoin-project/lotus/chain/actors/builtin/paych/mock" "github.com/filecoin-project/lotus/chain/types" @@ -60,7 +61,7 @@ func TestPaychGetCreateChannelMsg(t *testing.T) { pushedMsg := mock.pushedMessages(mcid) require.Equal(t, from, pushedMsg.Message.From) - require.Equal(t, builtin.InitActorAddr, pushedMsg.Message.To) + require.Equal(t, lotusinit.Address, pushedMsg.Message.To) require.Equal(t, amt, pushedMsg.Message.Value) } @@ -712,7 +713,7 @@ func TestPaychGetMergeAddFunds(t *testing.T) { // Check create message amount is correct createMsg := mock.pushedMessages(createMsgCid) require.Equal(t, from, createMsg.Message.From) - require.Equal(t, builtin.InitActorAddr, createMsg.Message.To) + require.Equal(t, lotusinit.Address, createMsg.Message.To) require.Equal(t, createAmt, createMsg.Message.Value) // Check merged add funds amount is the sum of the individual @@ -808,7 +809,7 @@ func TestPaychGetMergeAddFundsCtxCancelOne(t *testing.T) { // Check create message amount is correct createMsg := mock.pushedMessages(createMsgCid) require.Equal(t, from, createMsg.Message.From) - require.Equal(t, builtin.InitActorAddr, createMsg.Message.To) + require.Equal(t, lotusinit.Address, createMsg.Message.To) require.Equal(t, createAmt, createMsg.Message.Value) // Check merged add funds amount only includes the second add funds amount @@ -890,7 +891,7 @@ func TestPaychGetMergeAddFundsCtxCancelAll(t *testing.T) { // Check create message amount is correct createMsg := mock.pushedMessages(createMsgCid) require.Equal(t, from, createMsg.Message.From) - require.Equal(t, builtin.InitActorAddr, createMsg.Message.To) + require.Equal(t, lotusinit.Address, createMsg.Message.To) require.Equal(t, createAmt, createMsg.Message.Value) } diff --git a/paychmgr/simple.go b/paychmgr/simple.go index d2a42a673..d49ccafe6 100644 --- a/paychmgr/simple.go +++ b/paychmgr/simple.go @@ -19,6 +19,7 @@ import ( "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/actors" + lotusinit "github.com/filecoin-project/lotus/chain/actors/builtin/init" "github.com/filecoin-project/lotus/chain/types" ) @@ -400,7 +401,7 @@ func (ca *channelAccessor) createPaych(ctx context.Context, amt types.BigInt) (c } msg := &types.Message{ - To: builtin.InitActorAddr, + To: lotusinit.Address, From: ca.from, Value: amt, Method: builtin.MethodsInit.Exec, From a4ade158f4e065b8729fa140fb1cc553391d7d03 Mon Sep 17 00:00:00 2001 From: zgfzgf <1901989065@qq.com> Date: Wed, 23 Sep 2020 20:24:19 +0800 Subject: [PATCH 174/303] change minerStop to minerLoop --- miner/miner.go | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/miner/miner.go b/miner/miner.go index 144b2f413..3b1e65a72 100644 --- a/miner/miner.go +++ b/miner/miner.go @@ -149,9 +149,8 @@ func (m *Miner) mine(ctx context.Context) { defer span.End() var lastBase MiningBase - +minerLoop: for { - minerStop: select { case <-m.stop: stopping := m.stopping @@ -172,7 +171,7 @@ func (m *Miner) mine(ctx context.Context) { if err != nil { log.Errorf("failed to get best mining candidate: %s", err) if !m.niceSleep(time.Second * 5) { - goto minerStop + goto minerLoop } continue } @@ -204,7 +203,7 @@ func (m *Miner) mine(ctx context.Context) { if err != nil { log.Errorf("failed getting beacon entry: %s", err) if !m.niceSleep(time.Second) { - goto minerStop + goto minerLoop } continue } @@ -215,7 +214,7 @@ func (m *Miner) mine(ctx context.Context) { if base.TipSet.Equals(lastBase.TipSet) && lastBase.NullRounds == base.NullRounds { log.Warnf("BestMiningCandidate from the previous round: %s (nulls:%d)", lastBase.TipSet.Cids(), lastBase.NullRounds) if !m.niceSleep(time.Duration(build.BlockDelaySecs) * time.Second) { - goto minerStop + goto minerLoop } continue } @@ -226,7 +225,7 @@ func (m *Miner) mine(ctx context.Context) { if err != nil { log.Errorf("mining block failed: %+v", err) if !m.niceSleep(time.Second) { - goto minerStop + goto minerLoop } onDone(false, 0, err) continue From 91a43c477c5ec8c8911ada49cbe5485b49273472 Mon Sep 17 00:00:00 2001 From: jennijuju Date: Mon, 21 Sep 2020 21:41:17 -0400 Subject: [PATCH 175/303] When doing `sectors update-state`, show a list of existing states if user inputs an invalid one. --- cmd/lotus-storage-miner/sectors.go | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/cmd/lotus-storage-miner/sectors.go b/cmd/lotus-storage-miner/sectors.go index 27a5c31be..370962bdc 100644 --- a/cmd/lotus-storage-miner/sectors.go +++ b/cmd/lotus-storage-miner/sectors.go @@ -404,8 +404,9 @@ var sectorsCapacityCollateralCmd = &cli.Command{ } var sectorsUpdateCmd = &cli.Command{ - Name: "update-state", - Usage: "ADVANCED: manually update the state of a sector, this may aid in error recovery", + Name: "update-state", + Usage: "ADVANCED: manually update the state of a sector, this may aid in error recovery", + ArgsUsage: " ", Flags: []cli.Flag{ &cli.BoolFlag{ Name: "really-do-it", @@ -431,8 +432,13 @@ var sectorsUpdateCmd = &cli.Command{ return xerrors.Errorf("could not parse sector number: %w", err) } - if _, ok := sealing.ExistSectorStateList[sealing.SectorState(cctx.Args().Get(1))]; !ok { - return xerrors.Errorf("Not existing sector state") + newState := cctx.Args().Get(1) + if _, ok := sealing.ExistSectorStateList[sealing.SectorState(newState)]; !ok { + fmt.Printf(" \"%s\" is not a valid state. Possible states for sectors are: \n", newState) + for state := range sealing.ExistSectorStateList { + fmt.Printf("%s\n", string(state)) + } + return nil } return nodeApi.SectorsUpdate(ctx, abi.SectorNumber(id), api.SectorState(cctx.Args().Get(1))) From f1ab1af6170e822803073f9ae74ad20d00fdda43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Kripalani?= Date: Wed, 23 Sep 2020 17:42:01 +0100 Subject: [PATCH 176/303] add init.State#Remove() for testing. --- chain/actors/builtin/init/init.go | 5 +++++ chain/actors/builtin/init/v0.go | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/chain/actors/builtin/init/init.go b/chain/actors/builtin/init/init.go index 1164891f8..f235450c2 100644 --- a/chain/actors/builtin/init/init.go +++ b/chain/actors/builtin/init/init.go @@ -36,4 +36,9 @@ type State interface { NetworkName() (dtypes.NetworkName, error) ForEachActor(func(id abi.ActorID, address address.Address) error) error + + // Remove exists to support tooling that manipulates state for testing. + // It should not be used in production code, as init actor entries are + // immutable. + Remove(addrs ...address.Address) error } diff --git a/chain/actors/builtin/init/v0.go b/chain/actors/builtin/init/v0.go index 717ed9669..425ba654c 100644 --- a/chain/actors/builtin/init/v0.go +++ b/chain/actors/builtin/init/v0.go @@ -4,6 +4,7 @@ import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" cbg "github.com/whyrusleeping/cbor-gen" + "golang.org/x/xerrors" init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" @@ -46,3 +47,21 @@ func (s *state0) ForEachActor(cb func(id abi.ActorID, address address.Address) e func (s *state0) NetworkName() (dtypes.NetworkName, error) { return dtypes.NetworkName(s.State.NetworkName), nil } + +func (s *state0) Remove(addrs ...address.Address) (err error) { + m, err := adt0.AsMap(s.store, s.State.AddressMap) + if err != nil { + return err + } + for _, addr := range addrs { + if err = m.Delete(abi.AddrKey(addr)); err != nil { + return xerrors.Errorf("failed to delete entry for address: %s; err: %w", addr, err) + } + } + amr, err := m.Root() + if err != nil { + return xerrors.Errorf("failed to get address map root: %w", err) + } + s.State.AddressMap = amr + return nil +} From 6c5ed3f07f287e375c171818f001f13e5f0dd7ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Wed, 23 Sep 2020 19:31:36 +0200 Subject: [PATCH 177/303] Some safeguards on chain delete-obj --- cli/chain.go | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/cli/chain.go b/cli/chain.go index 0f1e36518..bd72c2030 100644 --- a/cli/chain.go +++ b/cli/chain.go @@ -195,9 +195,15 @@ var chainReadObjCmd = &cli.Command{ } var chainDeleteObjCmd = &cli.Command{ - Name: "delete-obj", - Usage: "Delete an object", - ArgsUsage: "[objectCid]", + Name: "delete-obj", + Usage: "Delete an object from the chain blockstore", + Description: "WARNING: Removing wrong objects from the chain blockstore may lead to sync issues", + ArgsUsage: "[objectCid]", + Flags: []cli.Flag{ + &cli.BoolFlag{ + Name: "really-do-it", + }, + }, Action: func(cctx *cli.Context) error { api, closer, err := GetFullNodeAPI(cctx) if err != nil { @@ -211,6 +217,10 @@ var chainDeleteObjCmd = &cli.Command{ return fmt.Errorf("failed to parse cid input: %s", err) } + if !cctx.Bool("really-do-it") { + return xerrors.Errorf("pass the --really-do-it flag to proceed") + } + err = api.ChainDeleteObj(ctx, c) if err != nil { return err From 3fc791b0e8c1c12b2d729123e6cf3bb9386a1eca Mon Sep 17 00:00:00 2001 From: hannahhoward Date: Wed, 23 Sep 2020 12:16:26 -0700 Subject: [PATCH 178/303] feat(markets): update markets v0.6.2 --- go.mod | 10 +++++----- go.sum | 31 ++++++++++++++----------------- node/impl/client/client.go | 2 +- 3 files changed, 20 insertions(+), 23 deletions(-) diff --git a/go.mod b/go.mod index 6706a3eda..cfdf4cb1d 100644 --- a/go.mod +++ b/go.mod @@ -25,9 +25,9 @@ require ( github.com/filecoin-project/go-bitfield v0.2.0 github.com/filecoin-project/go-cbor-util v0.0.0-20191219014500-08c40a1e63a2 github.com/filecoin-project/go-crypto v0.0.0-20191218222705-effae4ea9f03 - github.com/filecoin-project/go-data-transfer v0.6.4 + github.com/filecoin-project/go-data-transfer v0.6.5 github.com/filecoin-project/go-fil-commcid v0.0.0-20200716160307-8f644712406f - github.com/filecoin-project/go-fil-markets v0.6.1-0.20200917052354-ee0af754c6e9 + github.com/filecoin-project/go-fil-markets v0.6.2 github.com/filecoin-project/go-jsonrpc v0.1.2-0.20200822201400-474f4fdccc52 github.com/filecoin-project/go-multistore v0.0.3 github.com/filecoin-project/go-padreader v0.0.0-20200903213702-ed5fae088b20 @@ -60,7 +60,7 @@ require ( github.com/ipfs/go-ds-measure v0.1.0 github.com/ipfs/go-filestore v1.0.0 github.com/ipfs/go-fs-lock v0.0.6 - github.com/ipfs/go-graphsync v0.1.2 + github.com/ipfs/go-graphsync v0.2.0 github.com/ipfs/go-ipfs-blockstore v1.0.1 github.com/ipfs/go-ipfs-chunker v0.0.5 github.com/ipfs/go-ipfs-ds-help v1.0.0 @@ -77,8 +77,8 @@ require ( github.com/ipfs/go-path v0.0.7 github.com/ipfs/go-unixfs v0.2.4 github.com/ipfs/interface-go-ipfs-core v0.2.3 - github.com/ipld/go-car v0.1.1-0.20200526133713-1c7508d55aae - github.com/ipld/go-ipld-prime v0.0.4-0.20200828224805-5ff8c8b0b6ef + github.com/ipld/go-car v0.1.1-0.20200923150018-8cdef32e2da4 + github.com/ipld/go-ipld-prime v0.5.1-0.20200828233916-988837377a7f github.com/kelseyhightower/envconfig v1.4.0 github.com/lib/pq v1.7.0 github.com/libp2p/go-eventbus v0.2.1 diff --git a/go.sum b/go.sum index e62cb92c9..3b31e6c3b 100644 --- a/go.sum +++ b/go.sum @@ -222,13 +222,12 @@ github.com/filecoin-project/go-cbor-util v0.0.0-20191219014500-08c40a1e63a2 h1:a github.com/filecoin-project/go-cbor-util v0.0.0-20191219014500-08c40a1e63a2/go.mod h1:pqTiPHobNkOVM5thSRsHYjyQfq7O5QSCMhvuu9JoDlg= github.com/filecoin-project/go-crypto v0.0.0-20191218222705-effae4ea9f03 h1:2pMXdBnCiXjfCYx/hLqFxccPoqsSveQFxVLvNxy9bus= github.com/filecoin-project/go-crypto v0.0.0-20191218222705-effae4ea9f03/go.mod h1:+viYnvGtUTgJRdy6oaeF4MTFKAfatX071MPDPBL11EQ= -github.com/filecoin-project/go-data-transfer v0.6.3/go.mod h1:PmBKVXkhh67/tnEdJXQwDHl5mT+7Tbcwe1NPninqhnM= -github.com/filecoin-project/go-data-transfer v0.6.4 h1:Q08ABa+cOTOLoAyHeA94fPLcwu53p6eeAaxMxQb0m0A= -github.com/filecoin-project/go-data-transfer v0.6.4/go.mod h1:PmBKVXkhh67/tnEdJXQwDHl5mT+7Tbcwe1NPninqhnM= +github.com/filecoin-project/go-data-transfer v0.6.5 h1:oP20la8Z0CLrw0uqvt6xVgw6rOevZeGJ9GNQeC0OCSU= +github.com/filecoin-project/go-data-transfer v0.6.5/go.mod h1:I9Ylb/UiZyqnI41wUoCXq/le0nDLhlwpFQCtNPxEPOA= github.com/filecoin-project/go-fil-commcid v0.0.0-20200716160307-8f644712406f h1:GxJzR3oRIMTPtpZ0b7QF8FKPK6/iPAc7trhlL5k/g+s= github.com/filecoin-project/go-fil-commcid v0.0.0-20200716160307-8f644712406f/go.mod h1:Eaox7Hvus1JgPrL5+M3+h7aSPHc0cVqpSxA+TxIEpZQ= -github.com/filecoin-project/go-fil-markets v0.6.1-0.20200917052354-ee0af754c6e9 h1:SnCUC9wHDId9TtV8PsQp8q1OOsi+NOLOwitIDnAgUa4= -github.com/filecoin-project/go-fil-markets v0.6.1-0.20200917052354-ee0af754c6e9/go.mod h1:PLr9svZxsnHkae1Ky7+66g7fP9AlneVxIVu+oSMq56A= +github.com/filecoin-project/go-fil-markets v0.6.2 h1:9Z57KeaQSa1liCmT1pH6SIjrn9mGTDFJXmR2WQVuaiY= +github.com/filecoin-project/go-fil-markets v0.6.2/go.mod h1:wtN4Hc/1hoVCpWhSWYxwUxH3PQtjSkWWuC1nQjiIWog= github.com/filecoin-project/go-hamt-ipld v0.1.5 h1:uoXrKbCQZ49OHpsTCkrThPNelC4W3LPEk0OrS/ytIBM= github.com/filecoin-project/go-hamt-ipld v0.1.5 h1:uoXrKbCQZ49OHpsTCkrThPNelC4W3LPEk0OrS/ytIBM= github.com/filecoin-project/go-hamt-ipld v0.1.5/go.mod h1:6Is+ONR5Cd5R6XZoCse1CWaXZc0Hdb/JeX+EQCQzX24= @@ -396,9 +395,8 @@ github.com/gxed/go-shellwords v1.0.3/go.mod h1:N7paucT91ByIjmVJHhvoarjoQnmsi3Jd3 github.com/gxed/hashland/keccakpg v0.0.1/go.mod h1:kRzw3HkwxFU1mpmPP8v1WyQzwdGfmKFJ6tItnhQ67kU= github.com/gxed/hashland/murmur3 v0.0.1/go.mod h1:KjXop02n4/ckmZSnY2+HKcLud/tcmvhST0bie/0lS48= github.com/gxed/pubsub v0.0.0-20180201040156-26ebdf44f824/go.mod h1:OiEWyHgK+CWrmOlVquHaIK1vhpUJydC9m0Je6mhaiNE= -github.com/hannahhoward/cbor-gen-for v0.0.0-20191218204337-9ab7b1bcc099/go.mod h1:WVPCl0HO/0RAL5+vBH2GMxBomlxBF70MAS78+Lu1//k= -github.com/hannahhoward/cbor-gen-for v0.0.0-20200723175505-5892b522820a h1:wfqh5oiHXvn3Rk54xy8Cwqh+HnYihGnjMNzdNb3/ld0= -github.com/hannahhoward/cbor-gen-for v0.0.0-20200723175505-5892b522820a/go.mod h1:jvfsLIxk0fY/2BKSQ1xf2406AKA5dwMmKKv0ADcOfN8= +github.com/hannahhoward/cbor-gen-for v0.0.0-20200817222906-ea96cece81f1 h1:F9k+7wv5OIk1zcq23QpdiL0hfDuXPjuOmMNaC6fgQ0Q= +github.com/hannahhoward/cbor-gen-for v0.0.0-20200817222906-ea96cece81f1/go.mod h1:jvfsLIxk0fY/2BKSQ1xf2406AKA5dwMmKKv0ADcOfN8= github.com/hannahhoward/go-pubsub v0.0.0-20200423002714-8d62886cc36e h1:3YKHER4nmd7b5qy5t0GWDTwSn4OyRgfAXSmo6VnryBY= github.com/hannahhoward/go-pubsub v0.0.0-20200423002714-8d62886cc36e/go.mod h1:I8h3MITA53gN9OnWGCgaMa0JWVRdXthWw4M3CPM54OY= github.com/hashicorp/consul/api v1.3.0/go.mod h1:MmDNSzIMUjNpY/mQ398R4bk2FnqQLoPndWW5VkKPlCE= @@ -504,8 +502,8 @@ github.com/ipfs/go-filestore v1.0.0/go.mod h1:/XOCuNtIe2f1YPbiXdYvD0BKLA0JR1MgPi github.com/ipfs/go-fs-lock v0.0.6 h1:sn3TWwNVQqSeNjlWy6zQ1uUGAZrV3hPOyEA6y1/N2a0= github.com/ipfs/go-fs-lock v0.0.6/go.mod h1:OTR+Rj9sHiRubJh3dRhD15Juhd/+w6VPOY28L7zESmM= github.com/ipfs/go-graphsync v0.1.0/go.mod h1:jMXfqIEDFukLPZHqDPp8tJMbHO9Rmeb9CEGevngQbmE= -github.com/ipfs/go-graphsync v0.1.2 h1:25Ll9kIXCE+DY0dicvfS3KMw+U5sd01b/FJbA7KAbhg= -github.com/ipfs/go-graphsync v0.1.2/go.mod h1:sLXVXm1OxtE2XYPw62MuXCdAuNwkAdsbnfrmos5odbA= +github.com/ipfs/go-graphsync v0.2.0 h1:x94MvHLNuRwBlZzVal7tR1RYK7T7H6bqQLPopxDbIF0= +github.com/ipfs/go-graphsync v0.2.0/go.mod h1:gEBvJUNelzMkaRPJTpg/jaKN4AQW/7wDWu0K92D8o10= github.com/ipfs/go-hamt-ipld v0.1.1/go.mod h1:1EZCr2v0jlCnhpa+aZ0JZYp8Tt2w16+JJOAVz17YcDk= github.com/ipfs/go-ipfs-blockstore v0.0.1/go.mod h1:d3WClOmRQKFnJ0Jz/jj/zmksX0ma1gROTlovZKBmN08= github.com/ipfs/go-ipfs-blockstore v0.1.0/go.mod h1:5aD0AvHPi7mZc6Ci1WCAhiBQu2IsfTduLl+422H6Rqw= @@ -609,14 +607,14 @@ github.com/ipfs/iptb v1.4.0 h1:YFYTrCkLMRwk/35IMyC6+yjoQSHTEcNcefBStLJzgvo= github.com/ipfs/iptb v1.4.0/go.mod h1:1rzHpCYtNp87/+hTxG5TfCVn/yMY3dKnLn8tBiMfdmg= github.com/ipfs/iptb-plugins v0.2.1 h1:au4HWn9/pRPbkxA08pDx2oRAs4cnbgQWgV0teYXuuGA= github.com/ipfs/iptb-plugins v0.2.1/go.mod h1:QXMbtIWZ+jRsW8a4h13qAKU7jcM7qaittO8wOsTP0Rs= -github.com/ipld/go-car v0.1.1-0.20200526133713-1c7508d55aae h1:OV9dxl8iPMCOD8Vi/hvFwRh3JWPXqmkYSVxWr9JnEzM= -github.com/ipld/go-car v0.1.1-0.20200526133713-1c7508d55aae/go.mod h1:2mvxpu4dKRnuH3mj5u6KW/tmRSCcXvy/KYiJ4nC6h4c= +github.com/ipld/go-car v0.1.1-0.20200923150018-8cdef32e2da4 h1:6phjU3kXvCEWOZpu+Ob0w6DzgPFZmDLgLPxJhD8RxEY= +github.com/ipld/go-car v0.1.1-0.20200923150018-8cdef32e2da4/go.mod h1:xrMEcuSq+D1vEwl+YAXsg/JfA98XGpXDwnkIL4Aimqw= github.com/ipld/go-ipld-prime v0.0.2-0.20200428162820-8b59dc292b8e/go.mod h1:uVIwe/u0H4VdKv3kaN1ck7uCb6yD9cFLS9/ELyXbsw8= -github.com/ipld/go-ipld-prime v0.0.4-0.20200828224805-5ff8c8b0b6ef h1:/yPelt/0CuzZsmRkYzBBnJ499JnAOGaIaAXHujx96ic= -github.com/ipld/go-ipld-prime v0.0.4-0.20200828224805-5ff8c8b0b6ef/go.mod h1:uVIwe/u0H4VdKv3kaN1ck7uCb6yD9cFLS9/ELyXbsw8= +github.com/ipld/go-ipld-prime v0.5.1-0.20200828233916-988837377a7f h1:XpOuNQ5GbXxUcSukbQcW9jkE7REpaFGJU2/T00fo9kA= +github.com/ipld/go-ipld-prime v0.5.1-0.20200828233916-988837377a7f/go.mod h1:0xEgdD6MKbZ1vF0GC+YcR/C4SQCAlRuOjIJ2i0HxqzM= github.com/ipld/go-ipld-prime-proto v0.0.0-20200428191222-c1ffdadc01e1/go.mod h1:OAV6xBmuTLsPZ+epzKkPB1e25FHk/vCtyatkdHcArLs= -github.com/ipld/go-ipld-prime-proto v0.0.0-20200828231332-ae0aea07222b h1:ZtlW6pubN17TDaStlxgrwEXXwwUfJaXu9RobwczXato= -github.com/ipld/go-ipld-prime-proto v0.0.0-20200828231332-ae0aea07222b/go.mod h1:OAV6xBmuTLsPZ+epzKkPB1e25FHk/vCtyatkdHcArLs= +github.com/ipld/go-ipld-prime-proto v0.0.0-20200922192210-9a2bfd4440a6 h1:6Mq+tZGSEMEoJJ1NbJRhddeelkXZcU8yfH/ZRYUo/Es= +github.com/ipld/go-ipld-prime-proto v0.0.0-20200922192210-9a2bfd4440a6/go.mod h1:3pHYooM9Ea65jewRwrb2u5uHZCNkNTe9ABsVB+SrkH0= github.com/ipsn/go-secp256k1 v0.0.0-20180726113642-9d62b9f0bc52 h1:QG4CGBqCeuBo6aZlGAamSkxWdgWfZGeE49eUOWJPA4c= github.com/ipsn/go-secp256k1 v0.0.0-20180726113642-9d62b9f0bc52/go.mod h1:fdg+/X9Gg4AsAIzWpEHwnqd+QY3b7lajxyjE1m4hkq4= github.com/jackpal/gateway v1.0.4/go.mod h1:lTpwd4ACLXmpyiCTRtfiNyVnUmqT9RivzCDQetPfnjA= @@ -1362,7 +1360,6 @@ github.com/weaveworks/promrus v1.2.0/go.mod h1:SaE82+OJ91yqjrE1rsvBWVzNZKcHYFtMU github.com/whyrusleeping/base32 v0.0.0-20170828182744-c30ac30633cc/go.mod h1:r45hJU7yEoA81k6MWNhpMj/kms0n14dkzkxYHoB96UM= github.com/whyrusleeping/bencher v0.0.0-20190829221104-bb6607aa8bba h1:X4n8JG2e2biEZZXdBKt9HX7DN3bYGFUqljqqy0DqgnY= github.com/whyrusleeping/bencher v0.0.0-20190829221104-bb6607aa8bba/go.mod h1:CHQnYnQUEPydYCwuy8lmTHfGmdw9TKrhWV0xLx8l0oM= -github.com/whyrusleeping/cbor-gen v0.0.0-20191212224538-d370462a7e8a/go.mod h1:xdlJQaiqipF0HW+Mzpg7XRM3fWbGvfgFlcppuvlkIvY= github.com/whyrusleeping/cbor-gen v0.0.0-20191216205031-b047b6acb3c0/go.mod h1:xdlJQaiqipF0HW+Mzpg7XRM3fWbGvfgFlcppuvlkIvY= github.com/whyrusleeping/cbor-gen v0.0.0-20200123233031-1cdf64d27158/go.mod h1:Xj/M2wWU+QdTdRbu/L/1dIZY8/Wb2K9pAhtroQuxJJI= github.com/whyrusleeping/cbor-gen v0.0.0-20200402171437-3d27c146c105/go.mod h1:Xj/M2wWU+QdTdRbu/L/1dIZY8/Wb2K9pAhtroQuxJJI= diff --git a/node/impl/client/client.go b/node/impl/client/client.go index 8b47144af..81978af16 100644 --- a/node/impl/client/client.go +++ b/node/impl/client/client.go @@ -711,7 +711,7 @@ func (a *API) ClientGenCar(ctx context.Context, ref api.FileRef, outputPath stri // TODO: does that defer mean to remove the whole blockstore? defer bufferedDS.Remove(ctx, c) //nolint:errcheck - ssb := builder.NewSelectorSpecBuilder(basicnode.Style.Any) + ssb := builder.NewSelectorSpecBuilder(basicnode.Prototype.Any) // entire DAG selector allSelector := ssb.ExploreRecursive(selector.RecursionLimitNone(), From 1c1d23d14273dbdca95b6a03537635799ad33c0e Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Wed, 23 Sep 2020 12:36:15 -0700 Subject: [PATCH 179/303] fix out-of-bounds when loading all sector infos fixes #3972 --- chain/actors/builtin/miner/v0.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index e515b9ed6..9cdfc25bc 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -186,9 +186,9 @@ func (s *state0) LoadSectors(snos *bitfield.BitField) ([]*SectorOnChainInfo, err if snos == nil { infos := make([]*SectorOnChainInfo, 0, sectors.Length()) var info0 miner0.SectorOnChainInfo - if err := sectors.ForEach(&info0, func(i int64) error { + if err := sectors.ForEach(&info0, func(_ int64) error { info := fromV0SectorOnChainInfo(info0) - infos[i] = &info + infos = append(infos, &info) return nil }); err != nil { return nil, err From a1281273bc20b7911ee7052936a8fda8f2eda776 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Wed, 23 Sep 2020 22:10:02 +0200 Subject: [PATCH 180/303] shed dealtracker: fix lint, env var filter --- cmd/lotus-shed/dealtracker.go | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/cmd/lotus-shed/dealtracker.go b/cmd/lotus-shed/dealtracker.go index 18dc959f7..d39f51bd1 100644 --- a/cmd/lotus-shed/dealtracker.go +++ b/cmd/lotus-shed/dealtracker.go @@ -5,6 +5,8 @@ import ( "encoding/json" "net" "net/http" + "os" + "strings" "github.com/filecoin-project/go-address" "github.com/filecoin-project/lotus/api" @@ -20,8 +22,15 @@ type dealStatsServer struct { var filteredClients map[address.Address]bool func init() { + fc := []string{"t0112", "t0113", "t0114", "t010089"} + + filtered, set := os.LookupEnv("FILTERED_CLIENTS") + if set { + fc = strings.Split(filtered, ":") + } + filteredClients = make(map[address.Address]bool) - for _, a := range []string{"t0112", "t0113", "t0114", "t010089"} { + for _, a := range fc { addr, err := address.NewFromString(a) if err != nil { panic(err) @@ -35,16 +44,6 @@ type dealCountResp struct { Epoch int64 `json:"epoch"` } -func filterDeals(deals map[string]api.MarketDeal) []*api.MarketDeal { - out := make([]*api.MarketDeal, 0, len(deals)) - for _, d := range deals { - if !filteredClients[d.Proposal.Client] { - out = append(out, &d) - } - } - return out -} - func (dss *dealStatsServer) handleStorageDealCount(w http.ResponseWriter, r *http.Request) { ctx := context.Background() @@ -251,15 +250,16 @@ var serveDealStatsCmd = &cli.Command{ go func() { <-ctx.Done() - s.Shutdown(context.TODO()) + if err := s.Shutdown(context.TODO()); err != nil { + log.Error(err) + } }() - list, err := net.Listen("tcp", ":7272") + list, err := net.Listen("tcp", ":7272") // nolint if err != nil { panic(err) } - s.Serve(list) - return nil + return s.Serve(list) }, } From 46f5b62a761b9e300b455a7da6776dbf0f2cf497 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Wed, 23 Sep 2020 12:47:41 -0700 Subject: [PATCH 181/303] Remove a misleading miner actor abstraction We shouldn't implement CBOR functions on the "abstract" miner info. Otherwise, we could end up trying to actually _use_ this "abstract" info when decoding state (which won't work across version). Also remove the use of these CBOR functions, and instead explicitly use miner0 types. We'll have to abstract over versions eventually, but we'll probably need some form of abstract miner builder (or maybe even adding some "add sector", etc. functions to the current miner abstraction? --- chain/actors/builtin/miner/cbor_gen.go | 313 ------------------------- chain/events/state/predicates_test.go | 6 +- gen/main.go | 10 - 3 files changed, 3 insertions(+), 326 deletions(-) delete mode 100644 chain/actors/builtin/miner/cbor_gen.go diff --git a/chain/actors/builtin/miner/cbor_gen.go b/chain/actors/builtin/miner/cbor_gen.go deleted file mode 100644 index 16819d5c4..000000000 --- a/chain/actors/builtin/miner/cbor_gen.go +++ /dev/null @@ -1,313 +0,0 @@ -// Code generated by github.com/whyrusleeping/cbor-gen. DO NOT EDIT. - -package miner - -import ( - "fmt" - "io" - - abi "github.com/filecoin-project/go-state-types/abi" - cbg "github.com/whyrusleeping/cbor-gen" - xerrors "golang.org/x/xerrors" -) - -var _ = xerrors.Errorf - -var lengthBufSectorOnChainInfo = []byte{139} - -func (t *SectorOnChainInfo) MarshalCBOR(w io.Writer) error { - if t == nil { - _, err := w.Write(cbg.CborNull) - return err - } - if _, err := w.Write(lengthBufSectorOnChainInfo); err != nil { - return err - } - - scratch := make([]byte, 9) - - // t.SectorNumber (abi.SectorNumber) (uint64) - - if err := cbg.WriteMajorTypeHeaderBuf(scratch, w, cbg.MajUnsignedInt, uint64(t.SectorNumber)); err != nil { - return err - } - - // t.SealProof (abi.RegisteredSealProof) (int64) - if t.SealProof >= 0 { - if err := cbg.WriteMajorTypeHeaderBuf(scratch, w, cbg.MajUnsignedInt, uint64(t.SealProof)); err != nil { - return err - } - } else { - if err := cbg.WriteMajorTypeHeaderBuf(scratch, w, cbg.MajNegativeInt, uint64(-t.SealProof-1)); err != nil { - return err - } - } - - // t.SealedCID (cid.Cid) (struct) - - if err := cbg.WriteCidBuf(scratch, w, t.SealedCID); err != nil { - return xerrors.Errorf("failed to write cid field t.SealedCID: %w", err) - } - - // t.DealIDs ([]abi.DealID) (slice) - if len(t.DealIDs) > cbg.MaxLength { - return xerrors.Errorf("Slice value in field t.DealIDs was too long") - } - - if err := cbg.WriteMajorTypeHeaderBuf(scratch, w, cbg.MajArray, uint64(len(t.DealIDs))); err != nil { - return err - } - for _, v := range t.DealIDs { - if err := cbg.CborWriteHeader(w, cbg.MajUnsignedInt, uint64(v)); err != nil { - return err - } - } - - // t.Activation (abi.ChainEpoch) (int64) - if t.Activation >= 0 { - if err := cbg.WriteMajorTypeHeaderBuf(scratch, w, cbg.MajUnsignedInt, uint64(t.Activation)); err != nil { - return err - } - } else { - if err := cbg.WriteMajorTypeHeaderBuf(scratch, w, cbg.MajNegativeInt, uint64(-t.Activation-1)); err != nil { - return err - } - } - - // t.Expiration (abi.ChainEpoch) (int64) - if t.Expiration >= 0 { - if err := cbg.WriteMajorTypeHeaderBuf(scratch, w, cbg.MajUnsignedInt, uint64(t.Expiration)); err != nil { - return err - } - } else { - if err := cbg.WriteMajorTypeHeaderBuf(scratch, w, cbg.MajNegativeInt, uint64(-t.Expiration-1)); err != nil { - return err - } - } - - // t.DealWeight (big.Int) (struct) - if err := t.DealWeight.MarshalCBOR(w); err != nil { - return err - } - - // t.VerifiedDealWeight (big.Int) (struct) - if err := t.VerifiedDealWeight.MarshalCBOR(w); err != nil { - return err - } - - // t.InitialPledge (big.Int) (struct) - if err := t.InitialPledge.MarshalCBOR(w); err != nil { - return err - } - - // t.ExpectedDayReward (big.Int) (struct) - if err := t.ExpectedDayReward.MarshalCBOR(w); err != nil { - return err - } - - // t.ExpectedStoragePledge (big.Int) (struct) - if err := t.ExpectedStoragePledge.MarshalCBOR(w); err != nil { - return err - } - return nil -} - -func (t *SectorOnChainInfo) UnmarshalCBOR(r io.Reader) error { - *t = SectorOnChainInfo{} - - br := cbg.GetPeeker(r) - scratch := make([]byte, 8) - - maj, extra, err := cbg.CborReadHeaderBuf(br, scratch) - if err != nil { - return err - } - if maj != cbg.MajArray { - return fmt.Errorf("cbor input should be of type array") - } - - if extra != 11 { - return fmt.Errorf("cbor input had wrong number of fields") - } - - // t.SectorNumber (abi.SectorNumber) (uint64) - - { - - maj, extra, err = cbg.CborReadHeaderBuf(br, scratch) - if err != nil { - return err - } - if maj != cbg.MajUnsignedInt { - return fmt.Errorf("wrong type for uint64 field") - } - t.SectorNumber = abi.SectorNumber(extra) - - } - // t.SealProof (abi.RegisteredSealProof) (int64) - { - maj, extra, err := cbg.CborReadHeaderBuf(br, scratch) - var extraI int64 - if err != nil { - return err - } - switch maj { - case cbg.MajUnsignedInt: - extraI = int64(extra) - if extraI < 0 { - return fmt.Errorf("int64 positive overflow") - } - case cbg.MajNegativeInt: - extraI = int64(extra) - if extraI < 0 { - return fmt.Errorf("int64 negative oveflow") - } - extraI = -1 - extraI - default: - return fmt.Errorf("wrong type for int64 field: %d", maj) - } - - t.SealProof = abi.RegisteredSealProof(extraI) - } - // t.SealedCID (cid.Cid) (struct) - - { - - c, err := cbg.ReadCid(br) - if err != nil { - return xerrors.Errorf("failed to read cid field t.SealedCID: %w", err) - } - - t.SealedCID = c - - } - // t.DealIDs ([]abi.DealID) (slice) - - maj, extra, err = cbg.CborReadHeaderBuf(br, scratch) - if err != nil { - return err - } - - if extra > cbg.MaxLength { - return fmt.Errorf("t.DealIDs: array too large (%d)", extra) - } - - if maj != cbg.MajArray { - return fmt.Errorf("expected cbor array") - } - - if extra > 0 { - t.DealIDs = make([]abi.DealID, extra) - } - - for i := 0; i < int(extra); i++ { - - maj, val, err := cbg.CborReadHeaderBuf(br, scratch) - if err != nil { - return xerrors.Errorf("failed to read uint64 for t.DealIDs slice: %w", err) - } - - if maj != cbg.MajUnsignedInt { - return xerrors.Errorf("value read for array t.DealIDs was not a uint, instead got %d", maj) - } - - t.DealIDs[i] = abi.DealID(val) - } - - // t.Activation (abi.ChainEpoch) (int64) - { - maj, extra, err := cbg.CborReadHeaderBuf(br, scratch) - var extraI int64 - if err != nil { - return err - } - switch maj { - case cbg.MajUnsignedInt: - extraI = int64(extra) - if extraI < 0 { - return fmt.Errorf("int64 positive overflow") - } - case cbg.MajNegativeInt: - extraI = int64(extra) - if extraI < 0 { - return fmt.Errorf("int64 negative oveflow") - } - extraI = -1 - extraI - default: - return fmt.Errorf("wrong type for int64 field: %d", maj) - } - - t.Activation = abi.ChainEpoch(extraI) - } - // t.Expiration (abi.ChainEpoch) (int64) - { - maj, extra, err := cbg.CborReadHeaderBuf(br, scratch) - var extraI int64 - if err != nil { - return err - } - switch maj { - case cbg.MajUnsignedInt: - extraI = int64(extra) - if extraI < 0 { - return fmt.Errorf("int64 positive overflow") - } - case cbg.MajNegativeInt: - extraI = int64(extra) - if extraI < 0 { - return fmt.Errorf("int64 negative oveflow") - } - extraI = -1 - extraI - default: - return fmt.Errorf("wrong type for int64 field: %d", maj) - } - - t.Expiration = abi.ChainEpoch(extraI) - } - // t.DealWeight (big.Int) (struct) - - { - - if err := t.DealWeight.UnmarshalCBOR(br); err != nil { - return xerrors.Errorf("unmarshaling t.DealWeight: %w", err) - } - - } - // t.VerifiedDealWeight (big.Int) (struct) - - { - - if err := t.VerifiedDealWeight.UnmarshalCBOR(br); err != nil { - return xerrors.Errorf("unmarshaling t.VerifiedDealWeight: %w", err) - } - - } - // t.InitialPledge (big.Int) (struct) - - { - - if err := t.InitialPledge.UnmarshalCBOR(br); err != nil { - return xerrors.Errorf("unmarshaling t.InitialPledge: %w", err) - } - - } - // t.ExpectedDayReward (big.Int) (struct) - - { - - if err := t.ExpectedDayReward.UnmarshalCBOR(br); err != nil { - return xerrors.Errorf("unmarshaling t.ExpectedDayReward: %w", err) - } - - } - // t.ExpectedStoragePledge (big.Int) (struct) - - { - - if err := t.ExpectedStoragePledge.UnmarshalCBOR(br); err != nil { - return xerrors.Errorf("unmarshaling t.ExpectedStoragePledge: %w", err) - } - - } - return nil -} diff --git a/chain/events/state/predicates_test.go b/chain/events/state/predicates_test.go index 832f6a0a7..461ac4997 100644 --- a/chain/events/state/predicates_test.go +++ b/chain/events/state/predicates_test.go @@ -581,7 +581,7 @@ func createEmptyMinerState(ctx context.Context, t *testing.T, store adt.Store, o func createSectorsAMT(ctx context.Context, t *testing.T, store adt.Store, sectors []miner.SectorOnChainInfo) cid.Cid { root := adt.MakeEmptyArray(store) for _, sector := range sectors { - sector := sector + sector := (miner0.SectorOnChainInfo)(sector) err := root.Set(uint64(sector.SectorNumber), §or) require.NoError(t, err) } @@ -614,8 +614,8 @@ const ( ) // returns a unique SectorPreCommitInfo with each invocation with SectorNumber set to `sectorNo`. -func newSectorPreCommitInfo(sectorNo abi.SectorNumber, sealed cid.Cid, expiration abi.ChainEpoch) *miner.SectorPreCommitInfo { - return &miner.SectorPreCommitInfo{ +func newSectorPreCommitInfo(sectorNo abi.SectorNumber, sealed cid.Cid, expiration abi.ChainEpoch) *miner0.SectorPreCommitInfo { + return &miner0.SectorPreCommitInfo{ SealProof: abi.RegisteredSealProof_StackedDrg32GiBV1, SectorNumber: sectorNo, SealedCID: sealed, diff --git a/gen/main.go b/gen/main.go index 90b24e3a7..bcb43a8f0 100644 --- a/gen/main.go +++ b/gen/main.go @@ -4,8 +4,6 @@ import ( "fmt" "os" - "github.com/filecoin-project/lotus/chain/actors/builtin/miner" - gen "github.com/whyrusleeping/cbor-gen" "github.com/filecoin-project/lotus/api" @@ -77,12 +75,4 @@ func main() { fmt.Println(err) os.Exit(1) } - - err = gen.WriteTupleEncodersToFile("./chain/actors/builtin/miner/cbor_gen.go", "miner", - miner.SectorOnChainInfo{}, - ) - if err != nil { - fmt.Println(err) - os.Exit(1) - } } From 32a699d6a35a50eb9fe38af98fa60617ec6d3e27 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Wed, 23 Sep 2020 12:24:51 -0700 Subject: [PATCH 182/303] Add some actors policy setters for testing Addresses: * https://github.com/filecoin-project/lotus/pull/3781/files/a307e4593a005888395db34e5af4691ee50d765d#r491966115 * https://github.com/filecoin-project/lotus/pull/3781/files/a307e4593a005888395db34e5af4691ee50d765d#r491966634 Note: This puts everything into a policy package to avoid a dependency cycle between the build package, the miner package, and the types package. This is also why I introduced a GetPreCommitChallengeDelay function and removed the variable. --- build/params_2k.go | 14 +++--- build/params_testnet.go | 19 ++++---- chain/actors/builtin/miner/miner.go | 1 - chain/actors/policy/policy.go | 56 ++++++++++++++++++++++++ chain/gen/gen.go | 7 ++- chain/gen/gen_test.go | 13 ++---- chain/stmgr/forks_test.go | 13 ++---- chain/store/store_test.go | 13 ++---- chain/sync_test.go | 13 ++---- cli/paych_test.go | 48 +++++++++----------- cmd/lotus-bench/main.go | 4 +- extern/storage-sealing/checks.go | 6 +-- extern/storage-sealing/states_sealing.go | 3 +- lotuspond/spawn.go | 6 +-- node/node_test.go | 24 +++++----- 15 files changed, 128 insertions(+), 112 deletions(-) create mode 100644 chain/actors/policy/policy.go diff --git a/build/params_2k.go b/build/params_2k.go index 4a49da22b..3edd0fb82 100644 --- a/build/params_2k.go +++ b/build/params_2k.go @@ -4,10 +4,8 @@ package build import ( "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/go-state-types/big" - miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" - power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" - verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + + "github.com/filecoin-project/lotus/chain/actors/policy" ) const UpgradeBreezeHeight = -1 @@ -20,11 +18,9 @@ var DrandSchedule = map[abi.ChainEpoch]DrandEnum{ } func init() { - power0.ConsensusMinerMinPower = big.NewInt(2048) - miner0.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ - abi.RegisteredSealProof_StackedDrg2KiBV1: {}, - } - verifreg0.MinVerifiedDealSize = big.NewInt(256) + policy.SetSupportedProofTypes(abi.RegisteredSealProof_StackedDrg2KiBV1) + policy.SetConsensusMinerMinPower(abi.NewStoragePower(2048)) + policy.SetMinVerifiedDealSize(abi.NewStoragePower(256)) BuildType |= Build2k } diff --git a/build/params_testnet.go b/build/params_testnet.go index 108aba20c..13d2ff62e 100644 --- a/build/params_testnet.go +++ b/build/params_testnet.go @@ -6,10 +6,9 @@ package build import ( "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/go-state-types/big" - "github.com/filecoin-project/specs-actors/actors/builtin" - miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" - power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" + "github.com/filecoin-project/lotus/chain/actors/policy" + + builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" ) var DrandSchedule = map[abi.ChainEpoch]DrandEnum{ @@ -23,13 +22,13 @@ const BreezeGasTampingDuration = 120 const UpgradeSmokeHeight = 51000 func init() { - power0.ConsensusMinerMinPower = big.NewInt(10 << 40) - miner0.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ - abi.RegisteredSealProof_StackedDrg32GiBV1: {}, - abi.RegisteredSealProof_StackedDrg64GiBV1: {}, - } + policy.SetConsensusMinerMinPower(abi.NewStoragePower(10 << 40)) + policy.SetSupportedProofTypes( + abi.RegisteredSealProof_StackedDrg32GiBV1, + abi.RegisteredSealProof_StackedDrg64GiBV1, + ) } -const BlockDelaySecs = uint64(builtin.EpochDurationSeconds) +const BlockDelaySecs = uint64(builtin0.EpochDurationSeconds) const PropagationDelaySecs = uint64(6) diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index 50a0fc5ca..1a4c466b9 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -19,7 +19,6 @@ import ( ) // Unchanged between v0 and v1 actors -var PreCommitChallengeDelay = miner0.PreCommitChallengeDelay var WPoStProvingPeriod = miner0.WPoStProvingPeriod const MinSectorExpiration = miner0.MinSectorExpiration diff --git a/chain/actors/policy/policy.go b/chain/actors/policy/policy.go new file mode 100644 index 000000000..eec52e855 --- /dev/null +++ b/chain/actors/policy/policy.go @@ -0,0 +1,56 @@ +package policy + +import ( + "github.com/filecoin-project/go-state-types/abi" + + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" + power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" + verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" +) + +// SetSupportedProofTypes sets supported proof types, across all actor versions. +// This should only be used for testing. +func SetSupportedProofTypes(types ...abi.RegisteredSealProof) { + newTypes := make(map[abi.RegisteredSealProof]struct{}, len(types)) + for _, t := range types { + newTypes[t] = struct{}{} + } + // Set for all miner versions. + miner0.SupportedProofTypes = newTypes +} + +// AddSupportedProofTypes sets supported proof types, across all actor versions. +// This should only be used for testing. +func AddSupportedProofTypes(types ...abi.RegisteredSealProof) { + newTypes := make(map[abi.RegisteredSealProof]struct{}, len(types)) + for _, t := range types { + newTypes[t] = struct{}{} + } + // Set for all miner versions. + miner0.SupportedProofTypes = newTypes +} + +// SetPreCommitChallengeDelay sets the pre-commit challenge delay across all +// actors versions. Use for testing. +func SetPreCommitChallengeDelay(delay abi.ChainEpoch) { + // Set for all miner versions. + miner0.PreCommitChallengeDelay = delay +} + +// TODO: this function shouldn't really exist. Instead, the API should expose the precommit delay. +func GetPreCommitChallengeDelay() abi.ChainEpoch { + return miner0.PreCommitChallengeDelay +} + +// SetConsensusMinerMinPower sets the minimum power of an individual miner must +// meet for leader election, across all actor versions. This should only be used +// for testing. +func SetConsensusMinerMinPower(p abi.StoragePower) { + power0.ConsensusMinerMinPower = p +} + +// SetMinVerifiedDealSize sets the minimum size of a verified deal. This should +// only be used for testing. +func SetMinVerifiedDealSize(size abi.StoragePower) { + verifreg0.MinVerifiedDealSize = size +} diff --git a/chain/gen/gen.go b/chain/gen/gen.go index c4ecf1d41..d05165ab1 100644 --- a/chain/gen/gen.go +++ b/chain/gen/gen.go @@ -14,7 +14,6 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" - miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" block "github.com/ipfs/go-block-format" "github.com/ipfs/go-blockservice" "github.com/ipfs/go-cid" @@ -28,6 +27,7 @@ import ( "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" + "github.com/filecoin-project/lotus/chain/actors/policy" "github.com/filecoin-project/lotus/chain/beacon" genesis2 "github.com/filecoin-project/lotus/chain/gen/genesis" "github.com/filecoin-project/lotus/chain/stmgr" @@ -121,9 +121,8 @@ var DefaultRemainderAccountActor = genesis.Actor{ } func NewGeneratorWithSectors(numSectors int) (*ChainGen, error) { - miner0.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ - abi.RegisteredSealProof_StackedDrg2KiBV1: {}, - } + // TODO: we really shouldn't modify a global variable here. + policy.SetSupportedProofTypes(abi.RegisteredSealProof_StackedDrg2KiBV1) mr := repo.NewMemory(nil) lr, err := mr.Lock(repo.StorageMiner) diff --git a/chain/gen/gen_test.go b/chain/gen/gen_test.go index be913f5f2..8c38328d0 100644 --- a/chain/gen/gen_test.go +++ b/chain/gen/gen_test.go @@ -4,21 +4,16 @@ import ( "testing" "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/go-state-types/big" - miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" - power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" - verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + "github.com/filecoin-project/lotus/chain/actors/policy" _ "github.com/filecoin-project/lotus/lib/sigs/bls" _ "github.com/filecoin-project/lotus/lib/sigs/secp" ) func init() { - miner0.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ - abi.RegisteredSealProof_StackedDrg2KiBV1: {}, - } - power0.ConsensusMinerMinPower = big.NewInt(2048) - verifreg0.MinVerifiedDealSize = big.NewInt(256) + policy.SetSupportedProofTypes(abi.RegisteredSealProof_StackedDrg2KiBV1) + policy.SetConsensusMinerMinPower(abi.NewStoragePower(2048)) + policy.SetMinVerifiedDealSize(abi.NewStoragePower(256)) } func testGeneration(t testing.TB, n int, msgs int, sectors int) { diff --git a/chain/stmgr/forks_test.go b/chain/stmgr/forks_test.go index 8c6d2ce40..516058a81 100644 --- a/chain/stmgr/forks_test.go +++ b/chain/stmgr/forks_test.go @@ -8,18 +8,15 @@ import ( "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/specs-actors/actors/builtin" init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" - miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" - power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" - verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/specs-actors/actors/runtime" "golang.org/x/xerrors" "github.com/filecoin-project/lotus/chain/actors" "github.com/filecoin-project/lotus/chain/actors/aerrors" lotusinit "github.com/filecoin-project/lotus/chain/actors/builtin/init" + "github.com/filecoin-project/lotus/chain/actors/policy" "github.com/filecoin-project/lotus/chain/gen" "github.com/filecoin-project/lotus/chain/stmgr" . "github.com/filecoin-project/lotus/chain/stmgr" @@ -34,11 +31,9 @@ import ( ) func init() { - miner0.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ - abi.RegisteredSealProof_StackedDrg2KiBV1: {}, - } - power0.ConsensusMinerMinPower = big.NewInt(2048) - verifreg0.MinVerifiedDealSize = big.NewInt(256) + policy.SetSupportedProofTypes(abi.RegisteredSealProof_StackedDrg2KiBV1) + policy.SetConsensusMinerMinPower(abi.NewStoragePower(2048)) + policy.SetMinVerifiedDealSize(abi.NewStoragePower(256)) } const testForkHeight = 40 diff --git a/chain/store/store_test.go b/chain/store/store_test.go index d5e092559..b7adfb595 100644 --- a/chain/store/store_test.go +++ b/chain/store/store_test.go @@ -8,12 +8,9 @@ import ( datastore "github.com/ipfs/go-datastore" "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" - miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" - power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" - verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" + "github.com/filecoin-project/lotus/chain/actors/policy" "github.com/filecoin-project/lotus/chain/gen" "github.com/filecoin-project/lotus/chain/store" "github.com/filecoin-project/lotus/chain/types" @@ -22,11 +19,9 @@ import ( ) func init() { - miner0.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ - abi.RegisteredSealProof_StackedDrg2KiBV1: {}, - } - power0.ConsensusMinerMinPower = big.NewInt(2048) - verifreg0.MinVerifiedDealSize = big.NewInt(256) + policy.SetSupportedProofTypes(abi.RegisteredSealProof_StackedDrg2KiBV1) + policy.SetConsensusMinerMinPower(abi.NewStoragePower(2048)) + policy.SetMinVerifiedDealSize(abi.NewStoragePower(256)) } func BenchmarkGetRandomness(b *testing.B) { diff --git a/chain/sync_test.go b/chain/sync_test.go index 53001caf8..7a839be2b 100644 --- a/chain/sync_test.go +++ b/chain/sync_test.go @@ -19,13 +19,10 @@ import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/go-state-types/big" - miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" - power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" - verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" + "github.com/filecoin-project/lotus/chain/actors/policy" "github.com/filecoin-project/lotus/chain/gen" "github.com/filecoin-project/lotus/chain/gen/slashfilter" "github.com/filecoin-project/lotus/chain/store" @@ -43,11 +40,9 @@ func init() { if err != nil { panic(err) } - miner0.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ - abi.RegisteredSealProof_StackedDrg2KiBV1: {}, - } - power0.ConsensusMinerMinPower = big.NewInt(2048) - verifreg0.MinVerifiedDealSize = big.NewInt(256) + policy.SetSupportedProofTypes(abi.RegisteredSealProof_StackedDrg2KiBV1) + policy.SetConsensusMinerMinPower(abi.NewStoragePower(2048)) + policy.SetMinVerifiedDealSize(abi.NewStoragePower(256)) } const source = 0 diff --git a/cli/paych_test.go b/cli/paych_test.go index 47a84fe5e..35f56d90e 100644 --- a/cli/paych_test.go +++ b/cli/paych_test.go @@ -12,39 +12,31 @@ import ( "testing" "time" - "github.com/filecoin-project/lotus/build" - - "github.com/filecoin-project/go-state-types/big" - miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" - power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" - verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" - - "github.com/multiformats/go-multiaddr" - - "github.com/filecoin-project/lotus/chain/events" - - "github.com/filecoin-project/lotus/api/apibstore" - "github.com/filecoin-project/lotus/chain/actors/adt" - "github.com/filecoin-project/lotus/chain/actors/builtin/paych" - cbor "github.com/ipfs/go-ipld-cbor" - - "github.com/filecoin-project/go-address" - "github.com/filecoin-project/lotus/chain/types" - - "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/lotus/api/test" - "github.com/filecoin-project/lotus/chain/wallet" - builder "github.com/filecoin-project/lotus/node/test" "github.com/stretchr/testify/require" "github.com/urfave/cli/v2" + + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + cbor "github.com/ipfs/go-ipld-cbor" + "github.com/multiformats/go-multiaddr" + + "github.com/filecoin-project/lotus/chain/actors/adt" + "github.com/filecoin-project/lotus/chain/actors/builtin/paych" + "github.com/filecoin-project/lotus/chain/actors/policy" + + "github.com/filecoin-project/lotus/api/apibstore" + "github.com/filecoin-project/lotus/api/test" + "github.com/filecoin-project/lotus/build" + "github.com/filecoin-project/lotus/chain/events" + "github.com/filecoin-project/lotus/chain/types" + "github.com/filecoin-project/lotus/chain/wallet" + builder "github.com/filecoin-project/lotus/node/test" ) func init() { - power0.ConsensusMinerMinPower = big.NewInt(2048) - miner0.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ - abi.RegisteredSealProof_StackedDrg2KiBV1: {}, - } - verifreg0.MinVerifiedDealSize = big.NewInt(256) + policy.SetSupportedProofTypes(abi.RegisteredSealProof_StackedDrg2KiBV1) + policy.SetConsensusMinerMinPower(abi.NewStoragePower(2048)) + policy.SetMinVerifiedDealSize(abi.NewStoragePower(256)) } // TestPaymentChannels does a basic test to exercise the payment channel CLI diff --git a/cmd/lotus-bench/main.go b/cmd/lotus-bench/main.go index 7da754415..2516bfd26 100644 --- a/cmd/lotus-bench/main.go +++ b/cmd/lotus-bench/main.go @@ -27,11 +27,11 @@ import ( "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper/basicfs" "github.com/filecoin-project/lotus/extern/sector-storage/stores" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/specs-storage/storage" lapi "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" + "github.com/filecoin-project/lotus/chain/actors/policy" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/genesis" ) @@ -76,7 +76,7 @@ func main() { log.Info("Starting lotus-bench") - miner.SupportedProofTypes[abi.RegisteredSealProof_StackedDrg2KiBV1] = struct{}{} + policy.AddSupportedProofTypes(abi.RegisteredSealProof_StackedDrg2KiBV1) app := &cli.App{ Name: "lotus-bench", diff --git a/extern/storage-sealing/checks.go b/extern/storage-sealing/checks.go index 3d9aedeb4..49994024f 100644 --- a/extern/storage-sealing/checks.go +++ b/extern/storage-sealing/checks.go @@ -4,7 +4,7 @@ import ( "bytes" "context" - "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + "github.com/filecoin-project/lotus/chain/actors/policy" "github.com/filecoin-project/lotus/build" miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" @@ -156,8 +156,8 @@ func (m *Sealing) checkCommit(ctx context.Context, si SectorInfo, proof []byte, return &ErrNoPrecommit{xerrors.Errorf("precommit info not found on-chain")} } - if pci.PreCommitEpoch+miner.PreCommitChallengeDelay != si.SeedEpoch { - return &ErrBadSeed{xerrors.Errorf("seed epoch doesn't match on chain info: %d != %d", pci.PreCommitEpoch+miner.PreCommitChallengeDelay, si.SeedEpoch)} + if pci.PreCommitEpoch+policy.GetPreCommitChallengeDelay() != si.SeedEpoch { + return &ErrBadSeed{xerrors.Errorf("seed epoch doesn't match on chain info: %d != %d", pci.PreCommitEpoch+policy.GetPreCommitChallengeDelay(), si.SeedEpoch)} } buf := new(bytes.Buffer) diff --git a/extern/storage-sealing/states_sealing.go b/extern/storage-sealing/states_sealing.go index 443365160..a4e852454 100644 --- a/extern/storage-sealing/states_sealing.go +++ b/extern/storage-sealing/states_sealing.go @@ -6,6 +6,7 @@ import ( "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/actors/builtin/miner" + "github.com/filecoin-project/lotus/chain/actors/policy" miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" "golang.org/x/xerrors" @@ -281,7 +282,7 @@ func (m *Sealing) handleWaitSeed(ctx statemachine.Context, sector SectorInfo) er return ctx.Send(SectorChainPreCommitFailed{error: xerrors.Errorf("precommit info not found on chain")}) } - randHeight := pci.PreCommitEpoch + miner.PreCommitChallengeDelay + randHeight := pci.PreCommitEpoch + policy.GetPreCommitChallengeDelay() err = m.events.ChainAt(func(ectx context.Context, _ TipSetToken, curH abi.ChainEpoch) error { // in case of null blocks the randomness can land after the tipset we diff --git a/lotuspond/spawn.go b/lotuspond/spawn.go index 5fa82a865..8b2e8661d 100644 --- a/lotuspond/spawn.go +++ b/lotuspond/spawn.go @@ -11,6 +11,7 @@ import ( "sync/atomic" "time" + "github.com/filecoin-project/lotus/chain/actors/policy" "github.com/filecoin-project/lotus/chain/types" "golang.org/x/xerrors" @@ -18,7 +19,6 @@ import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" genesis2 "github.com/filecoin-project/lotus/chain/gen/genesis" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/gen" "github.com/filecoin-project/lotus/cmd/lotus-seed/seed" @@ -26,9 +26,7 @@ import ( ) func init() { - miner.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ - abi.RegisteredSealProof_StackedDrg2KiBV1: {}, - } + policy.SetSupportedProofTypes(abi.RegisteredSealProof_StackedDrg2KiBV1) } func (api *api) Spawn() (nodeInfo, error) { diff --git a/node/node_test.go b/node/node_test.go index 54498eec3..001b99c04 100644 --- a/node/node_test.go +++ b/node/node_test.go @@ -5,29 +5,22 @@ import ( "testing" "time" - "github.com/filecoin-project/lotus/chain/actors/builtin/miner" - builder "github.com/filecoin-project/lotus/node/test" "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/lotus/lib/lotuslog" - miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" - power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" - verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" logging "github.com/ipfs/go-log/v2" "github.com/filecoin-project/lotus/api/test" + "github.com/filecoin-project/lotus/chain/actors/policy" ) func init() { _ = logging.SetLogLevel("*", "INFO") - power0.ConsensusMinerMinPower = big.NewInt(2048) - miner0.SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{ - abi.RegisteredSealProof_StackedDrg2KiBV1: {}, - } - verifreg0.MinVerifiedDealSize = big.NewInt(256) + policy.SetConsensusMinerMinPower(abi.NewStoragePower(2048)) + policy.SetSupportedProofTypes(abi.RegisteredSealProof_StackedDrg2KiBV1) + policy.SetMinVerifiedDealSize(abi.NewStoragePower(256)) } func TestAPI(t *testing.T) { @@ -70,9 +63,12 @@ func TestAPIDealFlowReal(t *testing.T) { logging.SetLogLevel("sub", "ERROR") logging.SetLogLevel("storageminer", "ERROR") - // TODO: Do this better. - miner.PreCommitChallengeDelay = 5 - miner0.PreCommitChallengeDelay = 5 + // TODO: just set this globally? + oldDelay := policy.GetPreCommitChallengeDelay() + policy.SetPreCommitChallengeDelay(5) + t.Cleanup(func() { + policy.SetPreCommitChallengeDelay(oldDelay) + }) t.Run("basic", func(t *testing.T) { test.TestDealFlow(t, builder.Builder, time.Second, false, false) From 22fafc7054c37c80e243139f783fea3c6ed28468 Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Wed, 23 Sep 2020 18:09:01 -0400 Subject: [PATCH 183/303] Lotus version 0.7.2 --- CHANGELOG.md | 36 ++++++++++++++++++++++++++++++++++++ build/version.go | 8 ++++---- 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 06c0959b7..7b9756da3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,41 @@ # Lotus changelog +# 0.7.2 / 2020-09-23 + +This optional release of Lotus introduces a major refactor around how a Lotus node interacts with code from the specs-actors repo. We now use interfaces to read the state of actors, which is required to be able to reason about different versions of actors code at the same time. + +Additionally, this release introduces various + +## Changes + +#### Core Lotus + +- Network upgrade support (https://github.com/filecoin-project/lotus/pull/3781) +- Upgrade markets to `v0.6.2` (https://github.com/filecoin-project/lotus/pull/3974) +- Validate chain sync response indices when fetching messages (https://github.com/filecoin-project/lotus/pull/3939) +- Add height diff to sync wait (https://github.com/filecoin-project/lotus/pull/3926) +- Replace Requires with Wants (https://github.com/filecoin-project/lotus/pull/3898) +- Update state diffing for market actor (https://github.com/filecoin-project/lotus/pull/3889) +- Parallel fetch for sync (https://github.com/filecoin-project/lotus/pull/3887) +- Fix SectorState (https://github.com/filecoin-project/lotus/pull/3881) + +#### User Experience + +- Fix out-of-bounds when loading all sector infos (https://github.com/filecoin-project/lotus/pull/3976 +- Add basic deal stats api server for spacerace slingshot (https://github.com/filecoin-project/lotus/pull/3963) +- When doing `sectors update-state`, show a list of existing states if user inputs an invalid one (https://github.com/filecoin-project/lotus/pull/3944) +- Fix `lotus-miner storage find` error (https://github.com/filecoin-project/lotus/pull/3927) +- Log shutdown method for lotus daemon and miner (https://github.com/filecoin-project/lotus/pull/3925) +- Update build and setup instruction link (https://github.com/filecoin-project/lotus/pull/3919) +- Add an option to hide sectors in Removed from `sectors list` (https://github.com/filecoin-project/lotus/pull/3903) + +#### Testing and validation + +- Add init.State#Remove() for testing (https://github.com/filecoin-project/lotus/pull/3971) +- lotus-shed: add consensus check command (https://github.com/filecoin-project/lotus/pull/3933) +- Add keyinfo verify and jwt token command to lotus-shed (https://github.com/filecoin-project/lotus/pull/3914) +- Fix conformance gen (https://github.com/filecoin-project/lotus/pull/3892) + # 0.7.1 / 2020-09-17 This optional release of Lotus introduces some critical fixes to the window PoSt process. It also upgrades some core dependencies, and introduces many improvements to the mining process, deal-making cycle, and overall User Experience. diff --git a/build/version.go b/build/version.go index 933cfca70..cfc8c3ab9 100644 --- a/build/version.go +++ b/build/version.go @@ -29,7 +29,7 @@ func buildType() string { } // BuildVersion is the local build version, set by build system -const BuildVersion = "0.7.1" +const BuildVersion = "0.7.2" func UserVersion() string { return BuildVersion + buildType() + CurrentCommit @@ -83,9 +83,9 @@ func VersionForType(nodeType NodeType) (Version, error) { // semver versions of the rpc api exposed var ( - FullAPIVersion = newVer(0, 15, 0) - MinerAPIVersion = newVer(0, 14, 0) - WorkerAPIVersion = newVer(0, 14, 0) + FullAPIVersion = newVer(0, 16, 0) + MinerAPIVersion = newVer(0, 15, 0) + WorkerAPIVersion = newVer(0, 15, 0) ) //nolint:varcheck,deadcode From f729c6b7f5920b2ffd46e23b60a8ad9e7b1ca566 Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Wed, 23 Sep 2020 18:25:45 -0400 Subject: [PATCH 184/303] Update docs --- documentation/en/api-methods.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/documentation/en/api-methods.md b/documentation/en/api-methods.md index 944751dae..22aa8e474 100644 --- a/documentation/en/api-methods.md +++ b/documentation/en/api-methods.md @@ -214,7 +214,7 @@ Response: ```json { "Version": "string value", - "APIVersion": 3840, + "APIVersion": 4096, "BlockDelay": 42 } ``` From 44748775ff7ae6924f315c69d0b0101eb8ddbb3b Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Wed, 23 Sep 2020 20:49:31 -0400 Subject: [PATCH 185/303] Fixup changelog: --- CHANGELOG.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b9756da3..16ced709b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ This optional release of Lotus introduces a major refactor around how a Lotus node interacts with code from the specs-actors repo. We now use interfaces to read the state of actors, which is required to be able to reason about different versions of actors code at the same time. -Additionally, this release introduces various +Additionally, this release introduces various improvements to the sync process, as well as changes to better the overall UX experience. ## Changes @@ -21,13 +21,12 @@ Additionally, this release introduces various #### User Experience -- Fix out-of-bounds when loading all sector infos (https://github.com/filecoin-project/lotus/pull/3976 - Add basic deal stats api server for spacerace slingshot (https://github.com/filecoin-project/lotus/pull/3963) - When doing `sectors update-state`, show a list of existing states if user inputs an invalid one (https://github.com/filecoin-project/lotus/pull/3944) - Fix `lotus-miner storage find` error (https://github.com/filecoin-project/lotus/pull/3927) - Log shutdown method for lotus daemon and miner (https://github.com/filecoin-project/lotus/pull/3925) - Update build and setup instruction link (https://github.com/filecoin-project/lotus/pull/3919) -- Add an option to hide sectors in Removed from `sectors list` (https://github.com/filecoin-project/lotus/pull/3903) +- Add an option to hide removed sectors from `sectors list` output (https://github.com/filecoin-project/lotus/pull/3903) #### Testing and validation From b4e03d1759813af0fdc154972948ba445a56af47 Mon Sep 17 00:00:00 2001 From: whyrusleeping Date: Wed, 23 Sep 2020 18:53:28 -0700 Subject: [PATCH 186/303] batch blockstore copies after block validation --- chain/sync.go | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/chain/sync.go b/chain/sync.go index be6c3595c..7562e233d 100644 --- a/chain/sync.go +++ b/chain/sync.go @@ -17,6 +17,7 @@ import ( "github.com/Gurpartap/async" "github.com/hashicorp/go-multierror" + blocks "github.com/ipfs/go-block-format" "github.com/ipfs/go-cid" cbor "github.com/ipfs/go-ipld-cbor" logging "github.com/ipfs/go-log/v2" @@ -374,21 +375,28 @@ func (syncer *Syncer) InformNewBlock(from peer.ID, blk *types.FullBlock) bool { return syncer.InformNewHead(from, fts) } -func copyBlockstore(from, to bstore.Blockstore) error { - cids, err := from.AllKeysChan(context.TODO()) +func copyBlockstore(ctx context.Context, from, to bstore.Blockstore) error { + ctx, span := trace.StartSpan(ctx, "copyBlockstore") + defer span.End() + + cids, err := from.AllKeysChan(ctx) if err != nil { return err } + // TODO: should probably expose better methods on the blockstore for this operation + var blks []blocks.Block for c := range cids { b, err := from.Get(c) if err != nil { return err } - if err := to.Put(b); err != nil { - return err - } + blks = append(blks, b) + } + + if err := to.PutMany(blks); err != nil { + return err } return nil @@ -1515,11 +1523,11 @@ func (syncer *Syncer) iterFullTipsets(ctx context.Context, headers []*types.TipS return err } - if err := persistMessages(bs, bstip); err != nil { + if err := persistMessages(ctx, bs, bstip); err != nil { return err } - if err := copyBlockstore(bs, syncer.store.Blockstore()); err != nil { + if err := copyBlockstore(ctx, bs, syncer.store.Blockstore()); err != nil { return xerrors.Errorf("message processing failed: %w", err) } } @@ -1596,7 +1604,10 @@ func (syncer *Syncer) fetchMessages(ctx context.Context, headers []*types.TipSet return batch, nil } -func persistMessages(bs bstore.Blockstore, bst *exchange.CompactedMessages) error { +func persistMessages(ctx context.Context, bs bstore.Blockstore, bst *exchange.CompactedMessages) error { + _, span := trace.StartSpan(ctx, "persistMessages") + defer span.End() + for _, m := range bst.Bls { //log.Infof("putting BLS message: %s", m.Cid()) if _, err := store.PutMessage(bs, m); err != nil { From 38e256cecefd3bf92ce79b9a815151a5165117cd Mon Sep 17 00:00:00 2001 From: whyrusleeping Date: Wed, 23 Sep 2020 20:19:20 -0700 Subject: [PATCH 187/303] add some tracing to the vm's blockstore copy --- chain/vm/vm.go | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/chain/vm/vm.go b/chain/vm/vm.go index 35ece7c57..beab8a5fb 100644 --- a/chain/vm/vm.go +++ b/chain/vm/vm.go @@ -546,7 +546,7 @@ func (vm *VM) Flush(ctx context.Context) (cid.Cid, error) { return cid.Undef, xerrors.Errorf("flushing vm: %w", err) } - if err := Copy(from, to, root); err != nil { + if err := Copy(ctx, from, to, root); err != nil { return cid.Undef, xerrors.Errorf("copying tree: %w", err) } @@ -600,9 +600,18 @@ func linksForObj(blk block.Block, cb func(cid.Cid)) error { } } -func Copy(from, to blockstore.Blockstore, root cid.Cid) error { +func Copy(ctx context.Context, from, to blockstore.Blockstore, root cid.Cid) error { + ctx, span := trace.StartSpan(ctx, "vm.Copy") + defer span.End() + + var numBlocks int + var totalCopySize int + var batch []block.Block batchCp := func(blk block.Block) error { + numBlocks++ + totalCopySize += len(blk.RawData()) + batch = append(batch, blk) if len(batch) > 100 { if err := to.PutMany(batch); err != nil { @@ -623,6 +632,11 @@ func Copy(from, to blockstore.Blockstore, root cid.Cid) error { } } + span.AddAttributes( + trace.Int64Attribute("numBlocks", int64(numBlocks)), + trace.Int64Attribute("copySize", int64(totalCopySize)), + ) + return nil } From ded3a30f55940b5e468045347716bc63e8cbfd87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Thu, 24 Sep 2020 11:56:54 +0200 Subject: [PATCH 188/303] fix lint --- chain/vm/vm.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chain/vm/vm.go b/chain/vm/vm.go index beab8a5fb..3bafbe090 100644 --- a/chain/vm/vm.go +++ b/chain/vm/vm.go @@ -601,7 +601,7 @@ func linksForObj(blk block.Block, cb func(cid.Cid)) error { } func Copy(ctx context.Context, from, to blockstore.Blockstore, root cid.Cid) error { - ctx, span := trace.StartSpan(ctx, "vm.Copy") + ctx, span := trace.StartSpan(ctx, "vm.Copy") // nolint defer span.End() var numBlocks int From 15eddf0c96313e53913e768bb7e20d27b401be25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Thu, 24 Sep 2020 13:35:45 +0200 Subject: [PATCH 189/303] Make sync wait nicer --- api/api_full.go | 2 ++ chain/vm/vm.go | 11 +++++++++++ cli/sync.go | 33 +++++++++++++++++++++++++++++++-- documentation/en/api-methods.md | 3 ++- node/impl/full/sync.go | 6 +++++- 5 files changed, 51 insertions(+), 4 deletions(-) diff --git a/api/api_full.go b/api/api_full.go index 772ce9250..6d2d0c7b5 100644 --- a/api/api_full.go +++ b/api/api_full.go @@ -725,6 +725,8 @@ type ActiveSync struct { type SyncState struct { ActiveSyncs []ActiveSync + + VMApplied uint64 } type SyncStateStage int diff --git a/chain/vm/vm.go b/chain/vm/vm.go index 3bafbe090..54ea47698 100644 --- a/chain/vm/vm.go +++ b/chain/vm/vm.go @@ -5,6 +5,7 @@ import ( "context" "fmt" "reflect" + "sync/atomic" "time" block "github.com/ipfs/go-block-format" @@ -40,6 +41,12 @@ var log = logging.Logger("vm") var actorLog = logging.Logger("actors") var gasOnActorExec = newGasCharge("OnActorExec", 0, 0) +// stat counters +var ( + StatSends uint64 + StatApplied uint64 +) + // ResolveToKeyAddr returns the public key type of address (`BLS`/`SECP256K1`) of an account actor identified by `addr`. func ResolveToKeyAddr(state types.StateTree, cst cbor.IpldStore, addr address.Address) (address.Address, error) { if addr.Protocol() == address.BLS || addr.Protocol() == address.SECP256K1 { @@ -204,6 +211,8 @@ type ApplyRet struct { func (vm *VM) send(ctx context.Context, msg *types.Message, parent *Runtime, gasCharge *GasCharge, start time.Time) ([]byte, aerrors.ActorError, *Runtime) { + defer atomic.AddUint64(&StatSends, 1) + st := vm.cstate origin := msg.From @@ -312,6 +321,7 @@ func checkMessage(msg *types.Message) error { func (vm *VM) ApplyImplicitMessage(ctx context.Context, msg *types.Message) (*ApplyRet, error) { start := build.Clock.Now() + defer atomic.AddUint64(&StatApplied, 1) ret, actorErr, rt := vm.send(ctx, msg, nil, nil, start) rt.finilizeGasTracing() return &ApplyRet{ @@ -331,6 +341,7 @@ func (vm *VM) ApplyMessage(ctx context.Context, cmsg types.ChainMsg) (*ApplyRet, start := build.Clock.Now() ctx, span := trace.StartSpan(ctx, "vm.ApplyMessage") defer span.End() + defer atomic.AddUint64(&StatApplied, 1) msg := cmsg.VMMessage() if span.IsRecordingEvents() { span.AddAttributes( diff --git a/cli/sync.go b/cli/sync.go index 3b4e2e9fb..bee87cf70 100644 --- a/cli/sync.go +++ b/cli/sync.go @@ -225,6 +225,16 @@ var syncCheckpointCmd = &cli.Command{ } func SyncWait(ctx context.Context, napi api.FullNode) error { + tick := time.Second / 4 + + lastLines := 0 + ticker := time.NewTicker(tick) + defer ticker.Stop() + + samples := 8 + i := 0 + var app, lastApp uint64 + for { state, err := napi.SyncState(ctx) if err != nil { @@ -266,7 +276,24 @@ func SyncWait(ctx context.Context, napi api.FullNode) error { heightDiff = 0 } - fmt.Printf("\r\x1b[2KWorker %d: Base Height: %d\tTarget Height: %d\t Height diff: %d\tTarget: %s\tState: %s\tHeight: %d", working, baseHeight, theight, heightDiff, target, ss.Stage, ss.Height) + for i := 0; i < lastLines; i++ { + fmt.Print("\r\x1b[2K\x1b[A") + } + + fmt.Printf("Worker: %d; Base: %d; Target: %d (diff: %d)\n", working, baseHeight, theight, heightDiff) + fmt.Printf("State: %s; Current Epoch: %d; Todo: %d\n", ss.Stage, ss.Height, theight-ss.Height) + lastLines = 2 + + if i%samples == 0 { + lastApp = app + app = state.VMApplied + } + if i > 0 { + fmt.Printf("Validated %d messages (%d per second)\n", state.VMApplied, (app-lastApp)*uint64(time.Second/tick)/uint64(samples)) + lastLines++ + } + + _ = target // todo: maybe print? (creates a bunch of line wrapping issues with most tipsets) if time.Now().Unix()-int64(head.MinTimestamp()) < int64(build.BlockDelaySecs) { fmt.Println("\nDone!") @@ -277,7 +304,9 @@ func SyncWait(ctx context.Context, napi api.FullNode) error { case <-ctx.Done(): fmt.Println("\nExit by user") return nil - case <-build.Clock.After(1 * time.Second): + case <-ticker.C: } + + i++ } } diff --git a/documentation/en/api-methods.md b/documentation/en/api-methods.md index 22aa8e474..e489fcb0f 100644 --- a/documentation/en/api-methods.md +++ b/documentation/en/api-methods.md @@ -4303,7 +4303,8 @@ Inputs: `null` Response: ```json { - "ActiveSyncs": null + "ActiveSyncs": null, + "VMApplied": 42 } ``` diff --git a/node/impl/full/sync.go b/node/impl/full/sync.go index 31a707b90..dc3bfe230 100644 --- a/node/impl/full/sync.go +++ b/node/impl/full/sync.go @@ -2,6 +2,7 @@ package full import ( "context" + "sync/atomic" cid "github.com/ipfs/go-cid" pubsub "github.com/libp2p/go-libp2p-pubsub" @@ -13,6 +14,7 @@ import ( "github.com/filecoin-project/lotus/chain" "github.com/filecoin-project/lotus/chain/gen/slashfilter" "github.com/filecoin-project/lotus/chain/types" + "github.com/filecoin-project/lotus/chain/vm" "github.com/filecoin-project/lotus/node/modules/dtypes" ) @@ -28,7 +30,9 @@ type SyncAPI struct { func (a *SyncAPI) SyncState(ctx context.Context) (*api.SyncState, error) { states := a.Syncer.State() - out := &api.SyncState{} + out := &api.SyncState{ + VMApplied: atomic.LoadUint64(&vm.StatApplied), + } for i := range states { ss := &states[i] From 3c524ac0e0d806468e1e3a28437e94115089d477 Mon Sep 17 00:00:00 2001 From: Dirk McCormick Date: Wed, 23 Sep 2020 18:28:11 +0200 Subject: [PATCH 190/303] refactor: move nonce generation from mpool to wallet --- chain/messagepool/messagepool.go | 94 ------------- chain/messagesigner/messagesigner.go | 116 ++++++++++++++++ chain/messagesigner/messagesigner_test.go | 159 ++++++++++++++++++++++ node/builder.go | 3 + node/impl/full/mpool.go | 66 +++++---- 5 files changed, 310 insertions(+), 128 deletions(-) create mode 100644 chain/messagesigner/messagesigner.go create mode 100644 chain/messagesigner/messagesigner_test.go diff --git a/chain/messagepool/messagepool.go b/chain/messagepool/messagepool.go index 96900925f..d54ea7164 100644 --- a/chain/messagepool/messagepool.go +++ b/chain/messagepool/messagepool.go @@ -75,8 +75,6 @@ var ( ErrRBFTooLowPremium = errors.New("replace by fee has too low GasPremium") ErrTooManyPendingMessages = errors.New("too many pending messages for actor") ErrNonceGap = errors.New("unfulfilled nonce gap") - - ErrTryAgain = errors.New("state inconsistency while pushing message; please try again") ) const ( @@ -795,98 +793,6 @@ func (mp *MessagePool) getStateBalance(addr address.Address, ts *types.TipSet) ( return act.Balance, nil } -func (mp *MessagePool) PushWithNonce(ctx context.Context, addr address.Address, cb func(address.Address, uint64) (*types.SignedMessage, error)) (*types.SignedMessage, error) { - // serialize push access to reduce lock contention - mp.addSema <- struct{}{} - defer func() { - <-mp.addSema - }() - - mp.curTsLk.Lock() - mp.lk.Lock() - - curTs := mp.curTs - - fromKey := addr - if fromKey.Protocol() == address.ID { - var err error - fromKey, err = mp.api.StateAccountKey(ctx, fromKey, mp.curTs) - if err != nil { - mp.lk.Unlock() - mp.curTsLk.Unlock() - return nil, xerrors.Errorf("resolving sender key: %w", err) - } - } - - nonce, err := mp.getNonceLocked(fromKey, mp.curTs) - if err != nil { - mp.lk.Unlock() - mp.curTsLk.Unlock() - return nil, xerrors.Errorf("get nonce locked failed: %w", err) - } - - // release the locks for signing - mp.lk.Unlock() - mp.curTsLk.Unlock() - - msg, err := cb(fromKey, nonce) - if err != nil { - return nil, err - } - - err = mp.checkMessage(msg) - if err != nil { - return nil, err - } - - msgb, err := msg.Serialize() - if err != nil { - return nil, err - } - - // reacquire the locks and check state for consistency - mp.curTsLk.Lock() - defer mp.curTsLk.Unlock() - - if mp.curTs != curTs { - return nil, ErrTryAgain - } - - mp.lk.Lock() - defer mp.lk.Unlock() - - nonce2, err := mp.getNonceLocked(fromKey, mp.curTs) - if err != nil { - return nil, xerrors.Errorf("get nonce locked failed: %w", err) - } - - if nonce2 != nonce { - return nil, ErrTryAgain - } - - publish, err := mp.verifyMsgBeforeAdd(msg, curTs, true) - if err != nil { - return nil, err - } - - if err := mp.checkBalance(msg, curTs); err != nil { - return nil, err - } - - if err := mp.addLocked(msg, false); err != nil { - return nil, xerrors.Errorf("add locked failed: %w", err) - } - if err := mp.addLocal(msg, msgb); err != nil { - log.Errorf("addLocal failed: %+v", err) - } - - if publish { - err = mp.api.PubSubPublish(build.MessagesTopic(mp.netName), msgb) - } - - return msg, err -} - func (mp *MessagePool) Remove(from address.Address, nonce uint64, applied bool) { mp.lk.Lock() defer mp.lk.Unlock() diff --git a/chain/messagesigner/messagesigner.go b/chain/messagesigner/messagesigner.go new file mode 100644 index 000000000..41b0edee9 --- /dev/null +++ b/chain/messagesigner/messagesigner.go @@ -0,0 +1,116 @@ +package messagesigner + +import ( + "bytes" + "context" + + "github.com/filecoin-project/lotus/chain/wallet" + + "github.com/filecoin-project/lotus/chain/messagepool" + + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/lotus/chain/types" + "github.com/filecoin-project/lotus/node/modules/dtypes" + "github.com/ipfs/go-datastore" + "github.com/ipfs/go-datastore/namespace" + cbg "github.com/whyrusleeping/cbor-gen" + "golang.org/x/xerrors" +) + +const dsKeyActorNonce = "ActorNonce" + +type mpoolAPI interface { + GetNonce(address.Address) (uint64, error) +} + +// MessageSigner keeps track of nonces per address, and increments the nonce +// when signing a message +type MessageSigner struct { + wallet *wallet.Wallet + mpool mpoolAPI + ds datastore.Batching +} + +func NewMessageSigner(wallet *wallet.Wallet, mpool *messagepool.MessagePool, ds dtypes.MetadataDS) *MessageSigner { + return newMessageSigner(wallet, mpool, ds) +} + +func newMessageSigner(wallet *wallet.Wallet, mpool mpoolAPI, ds dtypes.MetadataDS) *MessageSigner { + ds = namespace.Wrap(ds, datastore.NewKey("/message-signer/")) + return &MessageSigner{ + wallet: wallet, + mpool: mpool, + ds: ds, + } +} + +// SignMessage increments the nonce for the message From address, and signs +// the message +func (ms *MessageSigner) SignMessage(ctx context.Context, msg *types.Message) (*types.SignedMessage, error) { + nonce, err := ms.nextNonce(msg.From) + if err != nil { + return nil, xerrors.Errorf("failed to create nonce: %w", err) + } + + msg.Nonce = nonce + sig, err := ms.wallet.Sign(ctx, msg.From, msg.Cid().Bytes()) + if err != nil { + return nil, xerrors.Errorf("failed to sign message: %w", err) + } + + return &types.SignedMessage{ + Message: *msg, + Signature: *sig, + }, nil +} + +// nextNonce increments the nonce. +// If there is no nonce in the datastore, gets the nonce from the message pool. +func (ms *MessageSigner) nextNonce(addr address.Address) (uint64, error) { + addrNonceKey := datastore.KeyWithNamespaces([]string{dsKeyActorNonce, addr.String()}) + + // Get the nonce for this address from the datastore + nonceBytes, err := ms.ds.Get(addrNonceKey) + + var nonce uint64 + switch { + case xerrors.Is(err, datastore.ErrNotFound): + // If a nonce for this address hasn't yet been created in the + // datastore, check the mempool - nonces used to be created by + // the mempool so we need to support nodes that still have mempool + // nonces. Note that the mempool returns the actor state's nonce by + // default. + nonce, err = ms.mpool.GetNonce(addr) + if err != nil { + return 0, xerrors.Errorf("failed to get nonce from mempool: %w", err) + } + + case err != nil: + return 0, xerrors.Errorf("failed to get nonce from datastore: %w", err) + + default: + // There is a nonce in the mempool, so unmarshall and increment it + maj, val, err := cbg.CborReadHeader(bytes.NewReader(nonceBytes)) + if err != nil { + return 0, xerrors.Errorf("failed to parse nonce from datastore: %w", err) + } + if maj != cbg.MajUnsignedInt { + return 0, xerrors.Errorf("bad cbor type parsing nonce from datastore") + } + + nonce = val + 1 + } + + // Write the nonce for this address to the datastore + buf := bytes.Buffer{} + _, err = buf.Write(cbg.CborEncodeMajorType(cbg.MajUnsignedInt, nonce)) + if err != nil { + return 0, xerrors.Errorf("failed to marshall nonce: %w", err) + } + err = ms.ds.Put(addrNonceKey, buf.Bytes()) + if err != nil { + return 0, xerrors.Errorf("failed to write nonce to datastore: %w", err) + } + + return nonce, nil +} diff --git a/chain/messagesigner/messagesigner_test.go b/chain/messagesigner/messagesigner_test.go new file mode 100644 index 000000000..e52137892 --- /dev/null +++ b/chain/messagesigner/messagesigner_test.go @@ -0,0 +1,159 @@ +package messagesigner + +import ( + "context" + "sync" + "testing" + + "github.com/filecoin-project/lotus/chain/wallet" + + "github.com/filecoin-project/go-state-types/crypto" + "github.com/stretchr/testify/require" + + ds_sync "github.com/ipfs/go-datastore/sync" + + "github.com/filecoin-project/go-address" + + "github.com/filecoin-project/lotus/chain/types" + "github.com/ipfs/go-datastore" +) + +type mockMpool struct { + lk sync.RWMutex + nonces map[address.Address]uint64 +} + +func newMockMpool() *mockMpool { + return &mockMpool{nonces: make(map[address.Address]uint64)} +} + +func (mp *mockMpool) setNonce(addr address.Address, nonce uint64) { + mp.lk.Lock() + defer mp.lk.Unlock() + + mp.nonces[addr] = nonce +} + +func (mp *mockMpool) GetNonce(addr address.Address) (uint64, error) { + mp.lk.RLock() + defer mp.lk.RUnlock() + + return mp.nonces[addr], nil +} + +func TestMessageSignerSignMessage(t *testing.T) { + ctx := context.Background() + + w, _ := wallet.NewWallet(wallet.NewMemKeyStore()) + from1, err := w.GenerateKey(crypto.SigTypeSecp256k1) + require.NoError(t, err) + from2, err := w.GenerateKey(crypto.SigTypeSecp256k1) + require.NoError(t, err) + to1, err := w.GenerateKey(crypto.SigTypeSecp256k1) + require.NoError(t, err) + to2, err := w.GenerateKey(crypto.SigTypeSecp256k1) + require.NoError(t, err) + + type msgSpec struct { + msg *types.Message + mpoolNonce [1]uint64 + expNonce uint64 + } + tests := []struct { + name string + msgs []msgSpec + }{{ + // No nonce yet in datastore + name: "no nonce yet", + msgs: []msgSpec{{ + msg: &types.Message{ + To: to1, + From: from1, + }, + expNonce: 0, + }}, + }, { + // Get nonce value of zero from mpool + name: "mpool nonce zero", + msgs: []msgSpec{{ + msg: &types.Message{ + To: to1, + From: from1, + }, + mpoolNonce: [1]uint64{0}, + expNonce: 0, + }}, + }, { + // Get non-zero nonce value from mpool + name: "mpool nonce set", + msgs: []msgSpec{{ + msg: &types.Message{ + To: to1, + From: from1, + }, + mpoolNonce: [1]uint64{5}, + expNonce: 5, + }, { + msg: &types.Message{ + To: to1, + From: from1, + }, + // Should ignore mpool nonce because after the first message nonce + // will come from the datastore + mpoolNonce: [1]uint64{10}, + expNonce: 6, + }}, + }, { + // Nonce should increment independently for each address + name: "nonce increments per address", + msgs: []msgSpec{{ + msg: &types.Message{ + To: to1, + From: from1, + }, + expNonce: 0, + }, { + msg: &types.Message{ + To: to1, + From: from1, + }, + expNonce: 1, + }, { + msg: &types.Message{ + To: to2, + From: from2, + }, + mpoolNonce: [1]uint64{5}, + expNonce: 5, + }, { + msg: &types.Message{ + To: to2, + From: from2, + }, + expNonce: 6, + }, { + msg: &types.Message{ + To: to1, + From: from1, + }, + expNonce: 2, + }}, + }} + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + mpool := newMockMpool() + ds := ds_sync.MutexWrap(datastore.NewMapDatastore()) + ms := newMessageSigner(w, mpool, ds) + + for _, m := range tt.msgs { + if len(m.mpoolNonce) == 1 { + mpool.setNonce(m.msg.From, m.mpoolNonce[0]) + } + smsg, err := ms.SignMessage(ctx, m.msg) + require.NoError(t, err) + require.Equal(t, m.expNonce, smsg.Message.Nonce) + } + }) + } +} diff --git a/node/builder.go b/node/builder.go index c37a5db58..c49789a6a 100644 --- a/node/builder.go +++ b/node/builder.go @@ -6,6 +6,8 @@ import ( "os" "time" + "github.com/filecoin-project/lotus/chain/messagesigner" + logging "github.com/ipfs/go-log" ci "github.com/libp2p/go-libp2p-core/crypto" "github.com/libp2p/go-libp2p-core/host" @@ -259,6 +261,7 @@ func Online() Option { Override(new(*store.ChainStore), modules.ChainStore), Override(new(*stmgr.StateManager), stmgr.NewStateManager), Override(new(*wallet.Wallet), wallet.NewWallet), + Override(new(*messagesigner.MessageSigner), messagesigner.NewMessageSigner), Override(new(dtypes.ChainGCLocker), blockstore.NewGCLocker), Override(new(dtypes.ChainGCBlockstore), modules.ChainGCBlockstore), diff --git a/node/impl/full/mpool.go b/node/impl/full/mpool.go index 6acb17990..003260496 100644 --- a/node/impl/full/mpool.go +++ b/node/impl/full/mpool.go @@ -4,14 +4,14 @@ import ( "context" "encoding/json" + "github.com/filecoin-project/lotus/chain/messagesigner" + "github.com/filecoin-project/go-address" "github.com/ipfs/go-cid" "go.uber.org/fx" "golang.org/x/xerrors" "github.com/filecoin-project/lotus/api" - "github.com/filecoin-project/lotus/chain/messagepool" - "github.com/filecoin-project/lotus/chain/store" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/node/modules/dtypes" ) @@ -22,9 +22,7 @@ type MpoolAPI struct { WalletAPI GasAPI - Chain *store.ChainStore - - Mpool *messagepool.MessagePool + MessageSigner *messagesigner.MessageSigner PushLocks *dtypes.MpoolLocker } @@ -114,12 +112,14 @@ func (a *MpoolAPI) MpoolPush(ctx context.Context, smsg *types.SignedMessage) (ci } func (a *MpoolAPI) MpoolPushMessage(ctx context.Context, msg *types.Message, spec *api.MessageSendSpec) (*types.SignedMessage, error) { + cp := *msg + msg = &cp inMsg := *msg + fromA, err := a.Stmgr.ResolveToKeyAddress(ctx, msg.From, nil) + if err != nil { + return nil, xerrors.Errorf("getting key address: %w", err) + } { - fromA, err := a.Stmgr.ResolveToKeyAddress(ctx, msg.From, nil) - if err != nil { - return nil, xerrors.Errorf("getting key address: %w", err) - } done, err := a.PushLocks.TakeLock(ctx, fromA) if err != nil { return nil, xerrors.Errorf("taking lock: %w", err) @@ -131,7 +131,7 @@ func (a *MpoolAPI) MpoolPushMessage(ctx context.Context, msg *types.Message, spe return nil, xerrors.Errorf("MpoolPushMessage expects message nonce to be 0, was %d", msg.Nonce) } - msg, err := a.GasAPI.GasEstimateMessageGas(ctx, msg, spec, types.EmptyTSK) + msg, err = a.GasAPI.GasEstimateMessageGas(ctx, msg, spec, types.EmptyTSK) if err != nil { return nil, xerrors.Errorf("GasEstimateMessageGas error: %w", err) } @@ -143,33 +143,31 @@ func (a *MpoolAPI) MpoolPushMessage(ctx context.Context, msg *types.Message, spe inJson, outJson) } - sign := func(from address.Address, nonce uint64) (*types.SignedMessage, error) { - msg.Nonce = nonce - if msg.From.Protocol() == address.ID { - log.Warnf("Push from ID address (%s), adjusting to %s", msg.From, from) - msg.From = from - } - - b, err := a.WalletBalance(ctx, msg.From) - if err != nil { - return nil, xerrors.Errorf("mpool push: getting origin balance: %w", err) - } - - if b.LessThan(msg.Value) { - return nil, xerrors.Errorf("mpool push: not enough funds: %s < %s", b, msg.Value) - } - - return a.WalletSignMessage(ctx, from, msg) + if msg.From.Protocol() == address.ID { + log.Warnf("Push from ID address (%s), adjusting to %s", msg.From, fromA) + msg.From = fromA } - var m *types.SignedMessage -again: - m, err = a.Mpool.PushWithNonce(ctx, msg.From, sign) - if err == messagepool.ErrTryAgain { - log.Debugf("temporary failure while pushing message: %s; retrying", err) - goto again + b, err := a.WalletBalance(ctx, msg.From) + if err != nil { + return nil, xerrors.Errorf("mpool push: getting origin balance: %w", err) } - return m, err + + if b.LessThan(msg.Value) { + return nil, xerrors.Errorf("mpool push: not enough funds: %s < %s", b, msg.Value) + } + + smsg, err := a.MessageSigner.SignMessage(ctx, msg) + if err != nil { + return nil, xerrors.Errorf("mpool push: failed to sign message: %w", err) + } + + _, err = a.Mpool.Push(smsg) + if err != nil { + return nil, xerrors.Errorf("mpool push: failed to push message: %w", err) + } + + return smsg, err } func (a *MpoolAPI) MpoolGetNonce(ctx context.Context, addr address.Address) (uint64, error) { From 7eb9bec13f6d351e192b0e8319ccf1bf0c3c077e Mon Sep 17 00:00:00 2001 From: Dirk McCormick Date: Fri, 18 Sep 2020 18:03:59 +0200 Subject: [PATCH 191/303] feat: dont recompute post on submit redux --- storage/wdpost_changehandler.go | 533 ++++++++++++ storage/wdpost_changehandler_test.go | 1173 ++++++++++++++++++++++++++ storage/wdpost_nextdl_test.go | 38 + storage/wdpost_run.go | 193 +++-- storage/wdpost_run_test.go | 6 +- storage/wdpost_sched.go | 142 +--- 6 files changed, 1913 insertions(+), 172 deletions(-) create mode 100644 storage/wdpost_changehandler.go create mode 100644 storage/wdpost_changehandler_test.go create mode 100644 storage/wdpost_nextdl_test.go diff --git a/storage/wdpost_changehandler.go b/storage/wdpost_changehandler.go new file mode 100644 index 000000000..e65b7a7fc --- /dev/null +++ b/storage/wdpost_changehandler.go @@ -0,0 +1,533 @@ +package storage + +import ( + "context" + "sync" + + "github.com/filecoin-project/go-state-types/abi" + + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/specs-actors/actors/builtin/miner" + + "github.com/filecoin-project/go-state-types/dline" + "github.com/filecoin-project/lotus/chain/types" +) + +const SubmitConfidence = 4 + +type CompleteGeneratePoSTCb func(posts []miner.SubmitWindowedPoStParams, err error) +type CompleteSubmitPoSTCb func(err error) + +type changeHandlerAPI interface { + StateMinerProvingDeadline(context.Context, address.Address, types.TipSetKey) (*dline.Info, error) + startGeneratePoST(ctx context.Context, ts *types.TipSet, deadline *dline.Info, onComplete CompleteGeneratePoSTCb) context.CancelFunc + startSubmitPoST(ctx context.Context, ts *types.TipSet, deadline *dline.Info, posts []miner.SubmitWindowedPoStParams, onComplete CompleteSubmitPoSTCb) context.CancelFunc + onAbort(ts *types.TipSet, deadline *dline.Info) + failPost(err error, ts *types.TipSet, deadline *dline.Info) +} + +type changeHandler struct { + api changeHandlerAPI + actor address.Address + proveHdlr *proveHandler + submitHdlr *submitHandler +} + +func newChangeHandler(api changeHandlerAPI, actor address.Address) *changeHandler { + posts := newPostsCache() + p := newProver(api, posts) + s := newSubmitter(api, posts) + return &changeHandler{api: api, actor: actor, proveHdlr: p, submitHdlr: s} +} + +func (ch *changeHandler) start() { + go ch.proveHdlr.run() + go ch.submitHdlr.run() +} + +func (ch *changeHandler) update(ctx context.Context, revert *types.TipSet, advance *types.TipSet) error { + // Get the current deadline period + di, err := ch.api.StateMinerProvingDeadline(ctx, ch.actor, advance.Key()) + if err != nil { + return err + } + + if !di.PeriodStarted() { + return nil // not proving anything yet + } + + hc := &headChange{ + ctx: ctx, + revert: revert, + advance: advance, + di: di, + } + + select { + case ch.proveHdlr.hcs <- hc: + case <-ch.proveHdlr.shutdownCtx.Done(): + case <-ctx.Done(): + } + + select { + case ch.submitHdlr.hcs <- hc: + case <-ch.submitHdlr.shutdownCtx.Done(): + case <-ctx.Done(): + } + + return nil +} + +func (ch *changeHandler) shutdown() { + ch.proveHdlr.shutdown() + ch.submitHdlr.shutdown() +} + +func (ch *changeHandler) currentTSDI() (*types.TipSet, *dline.Info) { + return ch.submitHdlr.currentTSDI() +} + +// postsCache keeps a cache of PoSTs for each proving window +type postsCache struct { + added chan *postInfo + lk sync.RWMutex + cache map[abi.ChainEpoch][]miner.SubmitWindowedPoStParams +} + +func newPostsCache() *postsCache { + return &postsCache{ + added: make(chan *postInfo, 16), + cache: make(map[abi.ChainEpoch][]miner.SubmitWindowedPoStParams), + } +} + +func (c *postsCache) add(di *dline.Info, posts []miner.SubmitWindowedPoStParams) { + c.lk.Lock() + defer c.lk.Unlock() + + // TODO: clear cache entries older than chain finality + c.cache[di.Open] = posts + + c.added <- &postInfo{ + di: di, + posts: posts, + } +} + +func (c *postsCache) get(di *dline.Info) ([]miner.SubmitWindowedPoStParams, bool) { + c.lk.RLock() + defer c.lk.RUnlock() + + posts, ok := c.cache[di.Open] + return posts, ok +} + +type headChange struct { + ctx context.Context + revert *types.TipSet + advance *types.TipSet + di *dline.Info +} + +type currentPost struct { + di *dline.Info + abort context.CancelFunc +} + +type postResult struct { + ts *types.TipSet + currPost *currentPost + posts []miner.SubmitWindowedPoStParams + err error +} + +// proveHandler generates proofs +type proveHandler struct { + api changeHandlerAPI + posts *postsCache + + postResults chan *postResult + hcs chan *headChange + + current *currentPost + + shutdownCtx context.Context + shutdown context.CancelFunc + + // Used for testing + processedHeadChanges chan *headChange + processedPostResults chan *postResult +} + +func newProver( + api changeHandlerAPI, + posts *postsCache, +) *proveHandler { + ctx, cancel := context.WithCancel(context.Background()) + return &proveHandler{ + api: api, + posts: posts, + postResults: make(chan *postResult), + hcs: make(chan *headChange), + shutdownCtx: ctx, + shutdown: cancel, + } +} + +func (p *proveHandler) run() { + // Abort proving on shutdown + defer func() { + if p.current != nil { + p.current.abort() + } + }() + + for p.shutdownCtx.Err() == nil { + select { + case <-p.shutdownCtx.Done(): + return + + case hc := <-p.hcs: + // Head changed + p.processHeadChange(hc.ctx, hc.advance, hc.di) + if p.processedHeadChanges != nil { + p.processedHeadChanges <- hc + } + + case res := <-p.postResults: + // Proof generation complete + p.processPostResult(res) + if p.processedPostResults != nil { + p.processedPostResults <- res + } + } + } +} + +func (p *proveHandler) processHeadChange(ctx context.Context, newTS *types.TipSet, di *dline.Info) { + // If the post window has expired, abort the current proof + if p.current != nil && newTS.Height() >= p.current.di.Close { + // Cancel the context on the current proof + p.current.abort() + + // Clear out the reference to the proof so that we can immediately + // start generating a new proof, without having to worry about state + // getting clobbered when the abort completes + p.current = nil + } + + // Only generate one proof at a time + if p.current != nil { + return + } + + // If the proof for the current post window has been generated, check the + // next post window + _, complete := p.posts.get(di) + for complete { + di = nextDeadline(di) + _, complete = p.posts.get(di) + } + + // Check if the chain is above the Challenge height for the post window + if newTS.Height() < di.Challenge { + return + } + + p.current = ¤tPost{di: di} + curr := p.current + p.current.abort = p.api.startGeneratePoST(ctx, newTS, di, func(posts []miner.SubmitWindowedPoStParams, err error) { + p.postResults <- &postResult{ts: newTS, currPost: curr, posts: posts, err: err} + }) +} + +func (p *proveHandler) processPostResult(res *postResult) { + di := res.currPost.di + if res.err != nil { + // Proving failed so inform the API + p.api.failPost(res.err, res.ts, di) + log.Warnf("Aborted window post Proving (Deadline: %+v)", di) + p.api.onAbort(res.ts, di) + + // Check if the current post has already been aborted + if p.current == res.currPost { + // If the current post was not already aborted, setting it to nil + // marks it as complete so that a new post can be started + p.current = nil + } + return + } + + // Completed processing this proving window + p.current = nil + + // Add the proofs to the cache + p.posts.add(di, res.posts) +} + +type submitResult struct { + pw *postWindow + err error +} + +type SubmitState string + +const ( + SubmitStateStart SubmitState = "SubmitStateStart" + SubmitStateSubmitting SubmitState = "SubmitStateSubmitting" + SubmitStateComplete SubmitState = "SubmitStateComplete" +) + +type postWindow struct { + ts *types.TipSet + di *dline.Info + submitState SubmitState + abort context.CancelFunc +} + +type postInfo struct { + di *dline.Info + posts []miner.SubmitWindowedPoStParams +} + +// submitHandler submits proofs on-chain +type submitHandler struct { + api changeHandlerAPI + posts *postsCache + + submitResults chan *submitResult + hcs chan *headChange + + postWindows map[abi.ChainEpoch]*postWindow + getPostWindowReqs chan *getPWReq + + shutdownCtx context.Context + shutdown context.CancelFunc + + currentCtx context.Context + currentTS *types.TipSet + currentDI *dline.Info + getTSDIReq chan chan *tsdi + + // Used for testing + processedHeadChanges chan *headChange + processedSubmitResults chan *submitResult + processedPostReady chan *postInfo +} + +func newSubmitter( + api changeHandlerAPI, + posts *postsCache, +) *submitHandler { + ctx, cancel := context.WithCancel(context.Background()) + return &submitHandler{ + api: api, + posts: posts, + submitResults: make(chan *submitResult), + hcs: make(chan *headChange), + postWindows: make(map[abi.ChainEpoch]*postWindow), + getPostWindowReqs: make(chan *getPWReq), + getTSDIReq: make(chan chan *tsdi), + shutdownCtx: ctx, + shutdown: cancel, + } +} + +func (s *submitHandler) run() { + // On shutdown, abort in-progress submits + defer func() { + for _, pw := range s.postWindows { + if pw.abort != nil { + pw.abort() + } + } + }() + + for s.shutdownCtx.Err() == nil { + select { + case <-s.shutdownCtx.Done(): + return + + case hc := <-s.hcs: + // Head change + s.processHeadChange(hc.ctx, hc.revert, hc.advance, hc.di) + if s.processedHeadChanges != nil { + s.processedHeadChanges <- hc + } + + case pi := <-s.posts.added: + // Proof generated + s.processPostReady(pi) + if s.processedPostReady != nil { + s.processedPostReady <- pi + } + + case res := <-s.submitResults: + // Submit complete + s.processSubmitResult(res) + if s.processedSubmitResults != nil { + s.processedSubmitResults <- res + } + + case pwreq := <-s.getPostWindowReqs: + // used by getPostWindow() to sync with run loop + pwreq.out <- s.postWindows[pwreq.di.Open] + + case out := <-s.getTSDIReq: + // used by currentTSDI() to sync with run loop + out <- &tsdi{ts: s.currentTS, di: s.currentDI} + } + } +} + +// processHeadChange is called when the chain head changes +func (s *submitHandler) processHeadChange(ctx context.Context, revert *types.TipSet, advance *types.TipSet, di *dline.Info) { + s.currentCtx = ctx + s.currentTS = advance + s.currentDI = di + + // Start tracking the current post window if we're not already + // TODO: clear post windows older than chain finality + if _, ok := s.postWindows[di.Open]; !ok { + s.postWindows[di.Open] = &postWindow{ + di: di, + ts: advance, + submitState: SubmitStateStart, + } + } + + // Apply the change to all post windows + for _, pw := range s.postWindows { + s.processHeadChangeForPW(ctx, revert, advance, pw) + } +} + +func (s *submitHandler) processHeadChangeForPW(ctx context.Context, revert *types.TipSet, advance *types.TipSet, pw *postWindow) { + revertedToPrevDL := revert != nil && revert.Height() < pw.di.Open + expired := advance.Height() >= pw.di.Close + + // If the chain was reverted back to the previous deadline, or if the post + // window has expired, abort submit + if pw.submitState == SubmitStateSubmitting && (revertedToPrevDL || expired) { + // Replace the aborted postWindow with a new one so that we can + // submit again at any time without the state getting clobbered + // when the abort completes + abort := pw.abort + if abort != nil { + pw = &postWindow{ + di: pw.di, + ts: advance, + submitState: SubmitStateStart, + } + s.postWindows[pw.di.Open] = pw + + // Abort the current submit + abort() + } + } else if pw.submitState == SubmitStateComplete && revertedToPrevDL { + // If submit for this deadline has completed, but the chain was + // reverted back to the previous deadline, reset the submit state to the + // starting state, so that it can be resubmitted + pw.submitState = SubmitStateStart + } + + // Submit the proof to chain if the proof has been generated and the chain + // height is above confidence + s.submitIfReady(ctx, advance, pw) +} + +// processPostReady is called when a proof generation completes +func (s *submitHandler) processPostReady(pi *postInfo) { + pw, ok := s.postWindows[pi.di.Open] + if ok { + s.submitIfReady(s.currentCtx, s.currentTS, pw) + } +} + +// submitIfReady submits a proof if the chain is high enough and the proof +// has been generated for this deadline +func (s *submitHandler) submitIfReady(ctx context.Context, advance *types.TipSet, pw *postWindow) { + // If the window has expired, there's nothing more to do. + if advance.Height() >= pw.di.Close { + return + } + + // Check if we're already submitting, or already completed submit + if pw.submitState != SubmitStateStart { + return + } + + // Check if we've reached the confidence height to submit + if advance.Height() < pw.di.Open+SubmitConfidence { + return + } + + // Check if the proofs have been generated for this deadline + posts, ok := s.posts.get(pw.di) + if !ok { + return + } + + // If there was nothing to prove, move straight to the complete state + if len(posts) == 0 { + pw.submitState = SubmitStateComplete + return + } + + // Start submitting post + pw.submitState = SubmitStateSubmitting + pw.abort = s.api.startSubmitPoST(ctx, advance, pw.di, posts, func(err error) { + s.submitResults <- &submitResult{pw: pw, err: err} + }) +} + +// processSubmitResult is called with the response to a submit +func (s *submitHandler) processSubmitResult(res *submitResult) { + if res.err != nil { + // Submit failed so inform the API and go back to the start state + s.api.failPost(res.err, res.pw.ts, res.pw.di) + log.Warnf("Aborted window post Submitting (Deadline: %+v)", res.pw.di) + s.api.onAbort(res.pw.ts, res.pw.di) + + res.pw.submitState = SubmitStateStart + return + } + + // Submit succeeded so move to complete state + res.pw.submitState = SubmitStateComplete +} + +type tsdi struct { + ts *types.TipSet + di *dline.Info +} + +func (s *submitHandler) currentTSDI() (*types.TipSet, *dline.Info) { + out := make(chan *tsdi) + s.getTSDIReq <- out + res := <-out + return res.ts, res.di +} + +type getPWReq struct { + di *dline.Info + out chan *postWindow +} + +func (s *submitHandler) getPostWindow(di *dline.Info) *postWindow { + out := make(chan *postWindow) + s.getPostWindowReqs <- &getPWReq{di: di, out: out} + return <-out +} + +// nextDeadline gets deadline info for the subsequent deadline +func nextDeadline(currentDeadline *dline.Info) *dline.Info { + periodStart := currentDeadline.PeriodStart + newDeadline := currentDeadline.Index + 1 + if newDeadline == miner.WPoStPeriodDeadlines { + newDeadline = 0 + periodStart = periodStart + miner.WPoStProvingPeriod + } + + return miner.NewDeadlineInfo(periodStart, newDeadline, currentDeadline.CurrentEpoch) +} diff --git a/storage/wdpost_changehandler_test.go b/storage/wdpost_changehandler_test.go new file mode 100644 index 000000000..d2a4779e6 --- /dev/null +++ b/storage/wdpost_changehandler_test.go @@ -0,0 +1,1173 @@ +package storage + +import ( + "context" + "fmt" + "sync" + "testing" + "time" + + tutils "github.com/filecoin-project/specs-actors/support/testing" + + "github.com/filecoin-project/go-state-types/crypto" + + "github.com/ipfs/go-cid" + "github.com/stretchr/testify/require" + + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/dline" + "github.com/filecoin-project/lotus/chain/types" + "github.com/filecoin-project/specs-actors/actors/builtin/miner" +) + +var dummyCid cid.Cid + +func init() { + dummyCid, _ = cid.Parse("bafkqaaa") +} + +type proveRes struct { + posts []miner.SubmitWindowedPoStParams + err error +} + +type postStatus string + +const ( + postStatusStart postStatus = "postStatusStart" + postStatusProving postStatus = "postStatusProving" + postStatusComplete postStatus = "postStatusComplete" +) + +type mockAPI struct { + ch *changeHandler + deadline *dline.Info + proveResult chan *proveRes + submitResult chan error + onStateChange chan struct{} + + tsLock sync.RWMutex + ts map[types.TipSetKey]*types.TipSet + + abortCalledLock sync.RWMutex + abortCalled bool + + statesLk sync.RWMutex + postStates map[abi.ChainEpoch]postStatus +} + +func newMockAPI() *mockAPI { + return &mockAPI{ + proveResult: make(chan *proveRes), + onStateChange: make(chan struct{}), + submitResult: make(chan error), + postStates: make(map[abi.ChainEpoch]postStatus), + ts: make(map[types.TipSetKey]*types.TipSet), + } +} + +func (m *mockAPI) makeTs(t *testing.T, h abi.ChainEpoch) *types.TipSet { + m.tsLock.Lock() + defer m.tsLock.Unlock() + + ts := makeTs(t, h) + m.ts[ts.Key()] = ts + return ts +} + +func (m *mockAPI) setDeadline(di *dline.Info) { + m.tsLock.Lock() + defer m.tsLock.Unlock() + + m.deadline = di +} + +func (m *mockAPI) getDeadline(currentEpoch abi.ChainEpoch) *dline.Info { + close := miner.WPoStChallengeWindow - 1 + dlIdx := uint64(0) + for close < currentEpoch { + close += miner.WPoStChallengeWindow + dlIdx++ + } + return miner.NewDeadlineInfo(0, dlIdx, currentEpoch) +} + +func (m *mockAPI) StateMinerProvingDeadline(ctx context.Context, address address.Address, key types.TipSetKey) (*dline.Info, error) { + m.tsLock.RLock() + defer m.tsLock.RUnlock() + + ts, ok := m.ts[key] + if !ok { + panic(fmt.Sprintf("unexpected tipset key %s", key)) + } + + if m.deadline != nil { + m.deadline.CurrentEpoch = ts.Height() + return m.deadline, nil + } + + return m.getDeadline(ts.Height()), nil +} + +func (m *mockAPI) startGeneratePoST( + ctx context.Context, + ts *types.TipSet, + deadline *dline.Info, + completeGeneratePoST CompleteGeneratePoSTCb, +) context.CancelFunc { + ctx, cancel := context.WithCancel(ctx) + + m.statesLk.Lock() + defer m.statesLk.Unlock() + m.postStates[deadline.Open] = postStatusProving + + go func() { + defer cancel() + + select { + case psRes := <-m.proveResult: + m.statesLk.Lock() + { + if psRes.err == nil { + m.postStates[deadline.Open] = postStatusComplete + } else { + m.postStates[deadline.Open] = postStatusStart + } + } + m.statesLk.Unlock() + completeGeneratePoST(psRes.posts, psRes.err) + case <-ctx.Done(): + completeGeneratePoST(nil, ctx.Err()) + } + }() + + return cancel +} + +func (m *mockAPI) getPostStatus(di *dline.Info) postStatus { + m.statesLk.RLock() + defer m.statesLk.RUnlock() + + status, ok := m.postStates[di.Open] + if ok { + return status + } + return postStatusStart +} + +func (m *mockAPI) startSubmitPoST( + ctx context.Context, + ts *types.TipSet, + deadline *dline.Info, + posts []miner.SubmitWindowedPoStParams, + completeSubmitPoST CompleteSubmitPoSTCb, +) context.CancelFunc { + ctx, cancel := context.WithCancel(ctx) + + go func() { + defer cancel() + + select { + case err := <-m.submitResult: + completeSubmitPoST(err) + case <-ctx.Done(): + completeSubmitPoST(ctx.Err()) + } + }() + + return cancel +} + +func (m *mockAPI) onAbort(ts *types.TipSet, deadline *dline.Info) { + m.abortCalledLock.Lock() + defer m.abortCalledLock.Unlock() + m.abortCalled = true +} + +func (m *mockAPI) wasAbortCalled() bool { + m.abortCalledLock.RLock() + defer m.abortCalledLock.RUnlock() + return m.abortCalled +} + +func (m *mockAPI) failPost(err error, ts *types.TipSet, deadline *dline.Info) { +} + +func (m *mockAPI) setChangeHandler(ch *changeHandler) { + m.ch = ch +} + +// TestChangeHandlerBasic verifies we can generate a proof and submit it +func TestChangeHandlerBasic(t *testing.T) { + s := makeScaffolding(t) + mock := s.mock + + defer s.ch.shutdown() + s.ch.start() + + // Trigger a head change + currentEpoch := abi.ChainEpoch(1) + go triggerHeadAdvance(t, s, currentEpoch) + + // Should start proving + <-s.ch.proveHdlr.processedHeadChanges + di := mock.getDeadline(currentEpoch) + require.Equal(t, postStatusProving, s.mock.getPostStatus(di)) + + // Submitter doesn't have anything to do yet + <-s.ch.submitHdlr.processedHeadChanges + require.Equal(t, SubmitStateStart, s.submitState(di)) + + // Send a response to the call to generate proofs + posts := []miner.SubmitWindowedPoStParams{{Deadline: di.Index}} + mock.proveResult <- &proveRes{posts: posts} + + // Should move to proving complete + <-s.ch.proveHdlr.processedPostResults + require.Equal(t, postStatusComplete, s.mock.getPostStatus(di)) + + // Move to the correct height to submit the proof + currentEpoch = 1 + SubmitConfidence + go triggerHeadAdvance(t, s, currentEpoch) + + // Should move to submitting state + <-s.ch.submitHdlr.processedHeadChanges + di = mock.getDeadline(currentEpoch) + require.Equal(t, SubmitStateSubmitting, s.submitState(di)) + + // Send a response to the submit call + mock.submitResult <- nil + + // Should move to the complete state + <-s.ch.submitHdlr.processedSubmitResults + require.Equal(t, SubmitStateComplete, s.submitState(di)) +} + +// TestChangeHandlerFromProvingToSubmittingNoHeadChange tests that when the +// chain is already advanced past the confidence interval, we should move from +// proving to submitting without a head change in between. +func TestChangeHandlerFromProvingToSubmittingNoHeadChange(t *testing.T) { + s := makeScaffolding(t) + mock := s.mock + + // Monitor submit handler's processing of incoming postInfo + s.ch.submitHdlr.processedPostReady = make(chan *postInfo) + + defer s.ch.shutdown() + s.ch.start() + + // Trigger a head change + currentEpoch := abi.ChainEpoch(1) + go triggerHeadAdvance(t, s, currentEpoch) + + // Should start proving + <-s.ch.proveHdlr.processedHeadChanges + di := mock.getDeadline(currentEpoch) + require.Equal(t, postStatusProving, s.mock.getPostStatus(di)) + + // Submitter doesn't have anything to do yet + <-s.ch.submitHdlr.processedHeadChanges + require.Equal(t, SubmitStateStart, s.submitState(di)) + + // Trigger a head change that advances the chain beyond the submit + // confidence + currentEpoch = 1 + SubmitConfidence + go triggerHeadAdvance(t, s, currentEpoch) + + // Should be no change to state yet + <-s.ch.proveHdlr.processedHeadChanges + require.Equal(t, postStatusProving, s.mock.getPostStatus(di)) + <-s.ch.submitHdlr.processedHeadChanges + require.Equal(t, SubmitStateStart, s.submitState(di)) + + // Send a response to the call to generate proofs + posts := []miner.SubmitWindowedPoStParams{{Deadline: di.Index}} + mock.proveResult <- &proveRes{posts: posts} + + // Should move to proving complete + <-s.ch.proveHdlr.processedPostResults + di = mock.getDeadline(currentEpoch) + require.Equal(t, postStatusComplete, s.mock.getPostStatus(di)) + + // Should move directly to submitting state with no further head changes + <-s.ch.submitHdlr.processedPostReady + require.Equal(t, SubmitStateSubmitting, s.submitState(di)) +} + +// TestChangeHandlerFromProvingEmptyProofsToComplete tests that when there are no +// proofs generated we should not submit anything to chain but submit state +// should move to completed +func TestChangeHandlerFromProvingEmptyProofsToComplete(t *testing.T) { + s := makeScaffolding(t) + mock := s.mock + + // Monitor submit handler's processing of incoming postInfo + s.ch.submitHdlr.processedPostReady = make(chan *postInfo) + + defer s.ch.shutdown() + s.ch.start() + + // Trigger a head change + currentEpoch := abi.ChainEpoch(1) + go triggerHeadAdvance(t, s, currentEpoch) + + // Should start proving + <-s.ch.proveHdlr.processedHeadChanges + di := mock.getDeadline(currentEpoch) + require.Equal(t, postStatusProving, s.mock.getPostStatus(di)) + + // Submitter doesn't have anything to do yet + <-s.ch.submitHdlr.processedHeadChanges + require.Equal(t, SubmitStateStart, s.submitState(di)) + + // Trigger a head change that advances the chain beyond the submit + // confidence + currentEpoch = 1 + SubmitConfidence + go triggerHeadAdvance(t, s, currentEpoch) + + // Should be no change to state yet + <-s.ch.proveHdlr.processedHeadChanges + require.Equal(t, postStatusProving, s.mock.getPostStatus(di)) + <-s.ch.submitHdlr.processedHeadChanges + require.Equal(t, SubmitStateStart, s.submitState(di)) + + // Send a response to the call to generate proofs with an empty proofs array + posts := []miner.SubmitWindowedPoStParams{} + mock.proveResult <- &proveRes{posts: posts} + + // Should move to proving complete + <-s.ch.proveHdlr.processedPostResults + di = mock.getDeadline(currentEpoch) + require.Equal(t, postStatusComplete, s.mock.getPostStatus(di)) + + // Should move directly to submitting complete state + <-s.ch.submitHdlr.processedPostReady + require.Equal(t, SubmitStateComplete, s.submitState(di)) +} + +// TestChangeHandlerDontStartUntilProvingPeriod tests that the handler +// ignores updates until the proving period has been reached. +func TestChangeHandlerDontStartUntilProvingPeriod(t *testing.T) { + s := makeScaffolding(t) + mock := s.mock + + periodStart := miner.WPoStProvingPeriod + dlIdx := uint64(1) + currentEpoch := abi.ChainEpoch(10) + di := miner.NewDeadlineInfo(periodStart, dlIdx, currentEpoch) + mock.setDeadline(di) + + defer s.ch.shutdown() + s.ch.start() + + // Trigger a head change + go triggerHeadAdvance(t, s, currentEpoch) + + // Nothing should happen because the proving period has not started + select { + case <-s.ch.proveHdlr.processedHeadChanges: + require.Fail(t, "unexpected prove change") + case <-s.ch.submitHdlr.processedHeadChanges: + require.Fail(t, "unexpected submit change") + case <-time.After(10 * time.Millisecond): + } + + // Advance the head to the next proving period's first epoch + currentEpoch = periodStart + miner.WPoStChallengeWindow + di = miner.NewDeadlineInfo(periodStart, dlIdx, currentEpoch) + mock.setDeadline(di) + go triggerHeadAdvance(t, s, currentEpoch) + + // Should start proving + <-s.ch.proveHdlr.processedHeadChanges + require.Equal(t, postStatusProving, s.mock.getPostStatus(di)) +} + +// TestChangeHandlerStartProvingNextDeadline verifies that the proof handler +// starts proving the next deadline after the current one +func TestChangeHandlerStartProvingNextDeadline(t *testing.T) { + s := makeScaffolding(t) + mock := s.mock + + defer s.ch.shutdown() + s.ch.start() + + // Trigger a head change + currentEpoch := abi.ChainEpoch(1) + go triggerHeadAdvance(t, s, currentEpoch) + + // Should start proving + <-s.ch.proveHdlr.processedHeadChanges + di := mock.getDeadline(currentEpoch) + require.Equal(t, postStatusProving, s.mock.getPostStatus(di)) + + // Trigger a head change that advances the chain beyond the submit + // confidence + currentEpoch = 1 + SubmitConfidence + go triggerHeadAdvance(t, s, currentEpoch) + + // Should be no change to state yet + <-s.ch.proveHdlr.processedHeadChanges + require.Equal(t, postStatusProving, s.mock.getPostStatus(di)) + + // Send a response to the call to generate proofs + posts := []miner.SubmitWindowedPoStParams{{Deadline: di.Index}} + mock.proveResult <- &proveRes{posts: posts} + + // Should move to proving complete + <-s.ch.proveHdlr.processedPostResults + di = mock.getDeadline(currentEpoch) + require.Equal(t, postStatusComplete, s.mock.getPostStatus(di)) + + // Trigger head change that advances the chain to the Challenge epoch for + // the next deadline + go func() { + di = nextDeadline(di) + currentEpoch = di.Challenge + triggerHeadAdvance(t, s, currentEpoch) + }() + + // Should start generating next window's proof + <-s.ch.proveHdlr.processedHeadChanges + require.Equal(t, postStatusProving, s.mock.getPostStatus(di)) +} + +// TestChangeHandlerProvingRounds verifies we can generate several rounds of +// proofs as the chain head advances +func TestChangeHandlerProvingRounds(t *testing.T) { + s := makeScaffolding(t) + mock := s.mock + + defer s.ch.shutdown() + s.ch.start() + + completeProofIndex := abi.ChainEpoch(10) + for currentEpoch := abi.ChainEpoch(1); currentEpoch < miner.WPoStChallengeWindow*5; currentEpoch++ { + // Trigger a head change + di := mock.getDeadline(currentEpoch) + go triggerHeadAdvance(t, s, currentEpoch) + + // Wait for prover to process head change + <-s.ch.proveHdlr.processedHeadChanges + + completeProofEpoch := di.Open + completeProofIndex + next := nextDeadline(di) + //fmt.Println("epoch", currentEpoch, s.mock.getPostStatus(di), "next", s.mock.getPostStatus(next)) + if currentEpoch >= next.Challenge { + require.Equal(t, postStatusComplete, s.mock.getPostStatus(di)) + // At the next deadline's challenge epoch, should start proving + // for that epoch + require.Equal(t, postStatusProving, s.mock.getPostStatus(next)) + } else if currentEpoch > completeProofEpoch { + // After proving for the round is complete, should be in complete state + require.Equal(t, postStatusComplete, s.mock.getPostStatus(di)) + require.Equal(t, postStatusStart, s.mock.getPostStatus(next)) + } else { + // Until proving completes, should be in the proving state + require.Equal(t, postStatusProving, s.mock.getPostStatus(di)) + require.Equal(t, postStatusStart, s.mock.getPostStatus(next)) + } + + // Wait for submitter to process head change + <-s.ch.submitHdlr.processedHeadChanges + + completeSubmitEpoch := completeProofEpoch + 1 + //fmt.Println("epoch", currentEpoch, s.submitState(di)) + if currentEpoch > completeSubmitEpoch { + require.Equal(t, SubmitStateComplete, s.submitState(di)) + } else if currentEpoch > completeProofEpoch { + require.Equal(t, SubmitStateSubmitting, s.submitState(di)) + } else { + require.Equal(t, SubmitStateStart, s.submitState(di)) + } + + if currentEpoch == completeProofEpoch { + // Send a response to the call to generate proofs + posts := []miner.SubmitWindowedPoStParams{{Deadline: di.Index}} + mock.proveResult <- &proveRes{posts: posts} + + // Should move to proving complete + <-s.ch.proveHdlr.processedPostResults + require.Equal(t, postStatusComplete, s.mock.getPostStatus(di)) + } + + if currentEpoch == completeSubmitEpoch { + // Send a response to the submit call + mock.submitResult <- nil + + // Should move to the complete state + <-s.ch.submitHdlr.processedSubmitResults + require.Equal(t, SubmitStateComplete, s.submitState(di)) + } + } +} + +// TestChangeHandlerProvingErrorRecovery verifies that the proof handler +// recovers correctly from an error +func TestChangeHandlerProvingErrorRecovery(t *testing.T) { + s := makeScaffolding(t) + mock := s.mock + + defer s.ch.shutdown() + s.ch.start() + + // Trigger a head change + currentEpoch := abi.ChainEpoch(1) + go triggerHeadAdvance(t, s, currentEpoch) + + // Should start proving + <-s.ch.proveHdlr.processedHeadChanges + di := mock.getDeadline(currentEpoch) + require.Equal(t, postStatusProving, s.mock.getPostStatus(di)) + + // Send an error response to the call to generate proofs + mock.proveResult <- &proveRes{err: fmt.Errorf("err")} + + // Should abort and then move to start state + <-s.ch.proveHdlr.processedPostResults + require.Equal(t, postStatusStart, s.mock.getPostStatus(di)) + + // Trigger a head change + go triggerHeadAdvance(t, s, currentEpoch) + + // Should start proving + <-s.ch.proveHdlr.processedHeadChanges + require.Equal(t, postStatusProving, s.mock.getPostStatus(di)) + + // Send a success response to the call to generate proofs + posts := []miner.SubmitWindowedPoStParams{{Deadline: di.Index}} + mock.proveResult <- &proveRes{posts: posts} + + // Should move to proving complete + <-s.ch.proveHdlr.processedPostResults + require.Equal(t, postStatusComplete, s.mock.getPostStatus(di)) +} + +// TestChangeHandlerSubmitErrorRecovery verifies that the submit handler +// recovers correctly from an error +func TestChangeHandlerSubmitErrorRecovery(t *testing.T) { + s := makeScaffolding(t) + mock := s.mock + + defer s.ch.shutdown() + s.ch.start() + + // Trigger a head change + currentEpoch := abi.ChainEpoch(1) + go triggerHeadAdvance(t, s, currentEpoch) + + // Should start proving + <-s.ch.proveHdlr.processedHeadChanges + di := mock.getDeadline(currentEpoch) + require.Equal(t, postStatusProving, s.mock.getPostStatus(di)) + + // Submitter doesn't have anything to do yet + <-s.ch.submitHdlr.processedHeadChanges + require.Equal(t, SubmitStateStart, s.submitState(di)) + + // Send a response to the call to generate proofs + posts := []miner.SubmitWindowedPoStParams{{Deadline: di.Index}} + mock.proveResult <- &proveRes{posts: posts} + + // Should move to proving complete + <-s.ch.proveHdlr.processedPostResults + require.Equal(t, postStatusComplete, s.mock.getPostStatus(di)) + + // Move to the correct height to submit the proof + currentEpoch = 1 + SubmitConfidence + go triggerHeadAdvance(t, s, currentEpoch) + + // Read from prover incoming channel (so as not to block) + <-s.ch.proveHdlr.processedHeadChanges + + // Should move to submitting state + <-s.ch.submitHdlr.processedHeadChanges + di = mock.getDeadline(currentEpoch) + require.Equal(t, SubmitStateSubmitting, s.submitState(di)) + + // Send an error response to the call to submit + mock.submitResult <- fmt.Errorf("err") + + // Should abort and then move back to the start state + <-s.ch.submitHdlr.processedSubmitResults + require.Equal(t, SubmitStateStart, s.submitState(di)) + require.True(t, mock.wasAbortCalled()) + + // Trigger another head change + go triggerHeadAdvance(t, s, currentEpoch) + + // Read from prover incoming channel (so as not to block) + <-s.ch.proveHdlr.processedHeadChanges + + // Should move to submitting state + <-s.ch.submitHdlr.processedHeadChanges + di = mock.getDeadline(currentEpoch) + require.Equal(t, SubmitStateSubmitting, s.submitState(di)) + + // Send a response to the submit call + mock.submitResult <- nil + + // Should move to the complete state + <-s.ch.submitHdlr.processedSubmitResults + require.Equal(t, SubmitStateComplete, s.submitState(di)) +} + +// TestChangeHandlerProveExpiry verifies that the prove handler +// behaves correctly on expiry +func TestChangeHandlerProveExpiry(t *testing.T) { + s := makeScaffolding(t) + mock := s.mock + + defer s.ch.shutdown() + s.ch.start() + + // Trigger a head change + currentEpoch := abi.ChainEpoch(1) + go triggerHeadAdvance(t, s, currentEpoch) + + // Should start proving + <-s.ch.proveHdlr.processedHeadChanges + di := mock.getDeadline(currentEpoch) + require.Equal(t, postStatusProving, s.mock.getPostStatus(di)) + + // Move to a height that expires the current proof + currentEpoch = miner.WPoStChallengeWindow + di = mock.getDeadline(currentEpoch) + go triggerHeadAdvance(t, s, currentEpoch) + + // Should trigger an abort and start proving for the new deadline + <-s.ch.proveHdlr.processedHeadChanges + require.Equal(t, postStatusProving, s.mock.getPostStatus(di)) + <-s.ch.proveHdlr.processedPostResults + require.True(t, mock.wasAbortCalled()) + + // Send a response to the call to generate proofs + posts := []miner.SubmitWindowedPoStParams{{Deadline: di.Index}} + mock.proveResult <- &proveRes{posts: posts} + + // Should move to proving complete + <-s.ch.proveHdlr.processedPostResults + require.Equal(t, postStatusComplete, s.mock.getPostStatus(di)) +} + +// TestChangeHandlerSubmitExpiry verifies that the submit handler +// behaves correctly on expiry +func TestChangeHandlerSubmitExpiry(t *testing.T) { + s := makeScaffolding(t) + mock := s.mock + + // Ignore prove handler head change processing for this test + s.ch.proveHdlr.processedHeadChanges = nil + + defer s.ch.shutdown() + s.ch.start() + + // Trigger a head change + currentEpoch := abi.ChainEpoch(1) + go triggerHeadAdvance(t, s, currentEpoch) + + // Submitter doesn't have anything to do yet + <-s.ch.submitHdlr.processedHeadChanges + di := mock.getDeadline(currentEpoch) + require.Equal(t, SubmitStateStart, s.submitState(di)) + + // Send a response to the call to generate proofs + posts := []miner.SubmitWindowedPoStParams{{Deadline: di.Index}} + mock.proveResult <- &proveRes{posts: posts} + + // Should move to proving complete + <-s.ch.proveHdlr.processedPostResults + require.Equal(t, postStatusComplete, s.mock.getPostStatus(di)) + + // Move to the correct height to submit the proof + currentEpoch = 1 + SubmitConfidence + go triggerHeadAdvance(t, s, currentEpoch) + + // Should move to submitting state + <-s.ch.submitHdlr.processedHeadChanges + di = mock.getDeadline(currentEpoch) + require.Equal(t, SubmitStateSubmitting, s.submitState(di)) + + // Move to a height that expires the submit + currentEpoch = miner.WPoStChallengeWindow + di = mock.getDeadline(currentEpoch) + go triggerHeadAdvance(t, s, currentEpoch) + + // Should trigger an abort and move back to start state + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + + <-s.ch.submitHdlr.processedSubmitResults + require.True(t, mock.wasAbortCalled()) + }() + + go func() { + defer wg.Done() + + <-s.ch.submitHdlr.processedHeadChanges + require.Equal(t, SubmitStateStart, s.submitState(di)) + }() + + wg.Wait() +} + +// TestChangeHandlerProveRevert verifies that the prove handler +// behaves correctly on revert +func TestChangeHandlerProveRevert(t *testing.T) { + s := makeScaffolding(t) + mock := s.mock + + defer s.ch.shutdown() + s.ch.start() + + // Trigger a head change + currentEpoch := miner.WPoStChallengeWindow + go triggerHeadAdvance(t, s, currentEpoch) + + // Should start proving + <-s.ch.proveHdlr.processedHeadChanges + di := mock.getDeadline(currentEpoch) + require.Equal(t, postStatusProving, s.mock.getPostStatus(di)) + + // Trigger a revert to the previous epoch + revertEpoch := di.Open - 5 + go triggerHeadChange(t, s, revertEpoch, currentEpoch) + + // Should be no change + <-s.ch.proveHdlr.processedHeadChanges + require.Equal(t, postStatusProving, s.mock.getPostStatus(di)) + + // Send a response to the call to generate proofs + posts := []miner.SubmitWindowedPoStParams{{Deadline: di.Index}} + mock.proveResult <- &proveRes{posts: posts} + + // Should move to proving complete + <-s.ch.proveHdlr.processedPostResults + require.Equal(t, postStatusComplete, s.mock.getPostStatus(di)) + require.False(t, mock.wasAbortCalled()) +} + +// TestChangeHandlerSubmittingRevert verifies that the submit handler +// behaves correctly when there's a revert from the submitting state +func TestChangeHandlerSubmittingRevert(t *testing.T) { + s := makeScaffolding(t) + mock := s.mock + + // Ignore prove handler head change processing for this test + s.ch.proveHdlr.processedHeadChanges = nil + + defer s.ch.shutdown() + s.ch.start() + + // Trigger a head change + currentEpoch := miner.WPoStChallengeWindow + go triggerHeadAdvance(t, s, currentEpoch) + + // Submitter doesn't have anything to do yet + <-s.ch.submitHdlr.processedHeadChanges + di := mock.getDeadline(currentEpoch) + require.Equal(t, SubmitStateStart, s.submitState(di)) + + // Send a response to the call to generate proofs + posts := []miner.SubmitWindowedPoStParams{{Deadline: di.Index}} + mock.proveResult <- &proveRes{posts: posts} + + // Should move to proving complete + <-s.ch.proveHdlr.processedPostResults + require.Equal(t, postStatusComplete, s.mock.getPostStatus(di)) + + // Move to the correct height to submit the proof + currentEpoch = currentEpoch + 1 + SubmitConfidence + go triggerHeadAdvance(t, s, currentEpoch) + + // Should move to submitting state + <-s.ch.submitHdlr.processedHeadChanges + di = mock.getDeadline(currentEpoch) + require.Equal(t, SubmitStateSubmitting, s.submitState(di)) + + // Trigger a revert to the previous epoch + revertEpoch := di.Open - 5 + go triggerHeadChange(t, s, revertEpoch, currentEpoch) + + var wg sync.WaitGroup + wg.Add(2) + + // Should trigger an abort + go func() { + defer wg.Done() + + <-s.ch.submitHdlr.processedSubmitResults + require.True(t, mock.wasAbortCalled()) + }() + + // Should resubmit current epoch + go func() { + defer wg.Done() + + <-s.ch.submitHdlr.processedHeadChanges + require.Equal(t, SubmitStateSubmitting, s.submitState(di)) + }() + + wg.Wait() + + // Send a response to the resubmit call + mock.submitResult <- nil + + // Should move to the complete state + <-s.ch.submitHdlr.processedSubmitResults + require.Equal(t, SubmitStateComplete, s.submitState(di)) +} + +// TestChangeHandlerSubmitCompleteRevert verifies that the submit handler +// behaves correctly when there's a revert from the submit complete state +func TestChangeHandlerSubmitCompleteRevert(t *testing.T) { + s := makeScaffolding(t) + mock := s.mock + + // Ignore prove handler head change processing for this test + s.ch.proveHdlr.processedHeadChanges = nil + + defer s.ch.shutdown() + s.ch.start() + + // Trigger a head change + currentEpoch := miner.WPoStChallengeWindow + go triggerHeadAdvance(t, s, currentEpoch) + + // Submitter doesn't have anything to do yet + <-s.ch.submitHdlr.processedHeadChanges + di := mock.getDeadline(currentEpoch) + require.Equal(t, SubmitStateStart, s.submitState(di)) + + // Send a response to the call to generate proofs + posts := []miner.SubmitWindowedPoStParams{{Deadline: di.Index}} + mock.proveResult <- &proveRes{posts: posts} + + // Should move to proving complete + <-s.ch.proveHdlr.processedPostResults + require.Equal(t, postStatusComplete, s.mock.getPostStatus(di)) + + // Move to the correct height to submit the proof + currentEpoch = currentEpoch + 1 + SubmitConfidence + go triggerHeadAdvance(t, s, currentEpoch) + + // Should move to submitting state + <-s.ch.submitHdlr.processedHeadChanges + di = mock.getDeadline(currentEpoch) + require.Equal(t, SubmitStateSubmitting, s.submitState(di)) + + // Send a response to the resubmit call + mock.submitResult <- nil + + // Should move to the complete state + <-s.ch.submitHdlr.processedSubmitResults + require.Equal(t, SubmitStateComplete, s.submitState(di)) + + // Trigger a revert to the previous epoch + revertEpoch := di.Open - 5 + go triggerHeadChange(t, s, revertEpoch, currentEpoch) + + // Should resubmit current epoch + <-s.ch.submitHdlr.processedHeadChanges + require.Equal(t, SubmitStateSubmitting, s.submitState(di)) + + // Send a response to the resubmit call + mock.submitResult <- nil + + // Should move to the complete state + <-s.ch.submitHdlr.processedSubmitResults + require.Equal(t, SubmitStateComplete, s.submitState(di)) +} + +// TestChangeHandlerSubmitRevertTwoEpochs verifies that the submit handler +// behaves correctly when the revert is two epochs deep +func TestChangeHandlerSubmitRevertTwoEpochs(t *testing.T) { + s := makeScaffolding(t) + mock := s.mock + + // Ignore prove handler head change processing for this test + s.ch.proveHdlr.processedHeadChanges = nil + + defer s.ch.shutdown() + s.ch.start() + + // Trigger a head change + currentEpoch := miner.WPoStChallengeWindow + go triggerHeadAdvance(t, s, currentEpoch) + + // Submitter doesn't have anything to do yet + <-s.ch.submitHdlr.processedHeadChanges + diE1 := mock.getDeadline(currentEpoch) + require.Equal(t, SubmitStateStart, s.submitState(diE1)) + + // Send a response to the call to generate proofs + posts := []miner.SubmitWindowedPoStParams{{Deadline: diE1.Index}} + mock.proveResult <- &proveRes{posts: posts} + + // Should move to proving complete + <-s.ch.proveHdlr.processedPostResults + require.Equal(t, postStatusComplete, s.mock.getPostStatus(diE1)) + + // Move to the challenge epoch for the next deadline + diE2 := nextDeadline(diE1) + currentEpoch = diE2.Challenge + go triggerHeadAdvance(t, s, currentEpoch) + + // Should move to submitting state for epoch 1 + <-s.ch.submitHdlr.processedHeadChanges + diE1 = mock.getDeadline(currentEpoch) + require.Equal(t, SubmitStateSubmitting, s.submitState(diE1)) + + // Send a response to the submit call for epoch 1 + mock.submitResult <- nil + + // Should move to the complete state for epoch 1 + <-s.ch.submitHdlr.processedSubmitResults + require.Equal(t, SubmitStateComplete, s.submitState(diE1)) + + // Should start proving epoch 2 + // Send a response to the call to generate proofs + postsE2 := []miner.SubmitWindowedPoStParams{{Deadline: diE2.Index}} + mock.proveResult <- &proveRes{posts: postsE2} + + // Should move to proving complete for epoch 2 + <-s.ch.proveHdlr.processedPostResults + require.Equal(t, postStatusComplete, s.mock.getPostStatus(diE2)) + + // Move to the correct height to submit the proof for epoch 2 + currentEpoch = diE2.Open + 1 + SubmitConfidence + go triggerHeadAdvance(t, s, currentEpoch) + + // Should move to submitting state for epoch 2 + <-s.ch.submitHdlr.processedHeadChanges + diE2 = mock.getDeadline(currentEpoch) + require.Equal(t, SubmitStateSubmitting, s.submitState(diE2)) + + // Trigger a revert through two epochs (from epoch 2 to epoch 0) + revertEpoch := diE1.Open - 5 + go triggerHeadChange(t, s, revertEpoch, currentEpoch) + + var wg sync.WaitGroup + wg.Add(2) + + // Should trigger an abort + go func() { + defer wg.Done() + + <-s.ch.submitHdlr.processedSubmitResults + require.True(t, mock.wasAbortCalled()) + }() + + go func() { + defer wg.Done() + + <-s.ch.submitHdlr.processedHeadChanges + + // Should reset epoch 1 (that is expired) to start state + require.Equal(t, SubmitStateStart, s.submitState(diE1)) + // Should resubmit epoch 2 + require.Equal(t, SubmitStateSubmitting, s.submitState(diE2)) + }() + + wg.Wait() + + // Send a response to the resubmit call for epoch 2 + mock.submitResult <- nil + + // Should move to the complete state for epoch 2 + <-s.ch.submitHdlr.processedSubmitResults + require.Equal(t, SubmitStateComplete, s.submitState(diE2)) +} + +// TestChangeHandlerSubmitRevertAdvanceLess verifies that the submit handler +// behaves correctly when the revert is two epochs deep and the advance is +// to a lower height than before +func TestChangeHandlerSubmitRevertAdvanceLess(t *testing.T) { + s := makeScaffolding(t) + mock := s.mock + + // Ignore prove handler head change processing for this test + s.ch.proveHdlr.processedHeadChanges = nil + + defer s.ch.shutdown() + s.ch.start() + + // Trigger a head change + currentEpoch := miner.WPoStChallengeWindow + go triggerHeadAdvance(t, s, currentEpoch) + + // Submitter doesn't have anything to do yet + <-s.ch.submitHdlr.processedHeadChanges + diE1 := mock.getDeadline(currentEpoch) + require.Equal(t, SubmitStateStart, s.submitState(diE1)) + + // Send a response to the call to generate proofs + posts := []miner.SubmitWindowedPoStParams{{Deadline: diE1.Index}} + mock.proveResult <- &proveRes{posts: posts} + + // Should move to proving complete + <-s.ch.proveHdlr.processedPostResults + require.Equal(t, postStatusComplete, s.mock.getPostStatus(diE1)) + + // Move to the challenge epoch for the next deadline + diE2 := nextDeadline(diE1) + currentEpoch = diE2.Challenge + go triggerHeadAdvance(t, s, currentEpoch) + + // Should move to submitting state for epoch 1 + <-s.ch.submitHdlr.processedHeadChanges + diE1 = mock.getDeadline(currentEpoch) + require.Equal(t, SubmitStateSubmitting, s.submitState(diE1)) + + // Send a response to the submit call for epoch 1 + mock.submitResult <- nil + + // Should move to the complete state for epoch 1 + <-s.ch.submitHdlr.processedSubmitResults + require.Equal(t, SubmitStateComplete, s.submitState(diE1)) + + // Should start proving epoch 2 + // Send a response to the call to generate proofs + postsE2 := []miner.SubmitWindowedPoStParams{{Deadline: diE2.Index}} + mock.proveResult <- &proveRes{posts: postsE2} + + // Should move to proving complete for epoch 2 + <-s.ch.proveHdlr.processedPostResults + require.Equal(t, postStatusComplete, s.mock.getPostStatus(diE2)) + + // Move to the correct height to submit the proof for epoch 2 + currentEpoch = diE2.Open + 1 + SubmitConfidence + go triggerHeadAdvance(t, s, currentEpoch) + + // Should move to submitting state for epoch 2 + <-s.ch.submitHdlr.processedHeadChanges + diE2 = mock.getDeadline(currentEpoch) + require.Equal(t, SubmitStateSubmitting, s.submitState(diE2)) + + // Trigger a revert through two epochs (from epoch 2 to epoch 0) + // then advance to the previous epoch (to epoch 1) + revertEpoch := diE1.Open - 5 + currentEpoch = diE2.Open - 1 + go triggerHeadChange(t, s, revertEpoch, currentEpoch) + + var wg sync.WaitGroup + wg.Add(2) + + // Should trigger an abort + go func() { + defer wg.Done() + + <-s.ch.submitHdlr.processedSubmitResults + require.True(t, mock.wasAbortCalled()) + }() + + go func() { + defer wg.Done() + + <-s.ch.submitHdlr.processedHeadChanges + + // Should resubmit epoch 1 + require.Equal(t, SubmitStateSubmitting, s.submitState(diE1)) + // Should reset epoch 2 to start state + require.Equal(t, SubmitStateStart, s.submitState(diE2)) + }() + + wg.Wait() + + // Send a response to the resubmit call for epoch 1 + mock.submitResult <- nil + + // Should move to the complete state for epoch 1 + <-s.ch.submitHdlr.processedSubmitResults + require.Equal(t, SubmitStateComplete, s.submitState(diE1)) +} + +type smScaffolding struct { + ctx context.Context + mock *mockAPI + ch *changeHandler +} + +func makeScaffolding(t *testing.T) *smScaffolding { + ctx := context.Background() + actor := tutils.NewActorAddr(t, "actor") + mock := newMockAPI() + ch := newChangeHandler(mock, actor) + mock.setChangeHandler(ch) + + ch.proveHdlr.processedHeadChanges = make(chan *headChange) + ch.proveHdlr.processedPostResults = make(chan *postResult) + + ch.submitHdlr.processedHeadChanges = make(chan *headChange) + ch.submitHdlr.processedSubmitResults = make(chan *submitResult) + + return &smScaffolding{ + ctx: ctx, + mock: mock, + ch: ch, + } +} + +func triggerHeadAdvance(t *testing.T, s *smScaffolding, height abi.ChainEpoch) { + ts := s.mock.makeTs(t, height) + err := s.ch.update(s.ctx, nil, ts) + require.NoError(t, err) +} + +func triggerHeadChange(t *testing.T, s *smScaffolding, revertHeight, advanceHeight abi.ChainEpoch) { + tsRev := s.mock.makeTs(t, revertHeight) + tsAdv := s.mock.makeTs(t, advanceHeight) + err := s.ch.update(s.ctx, tsRev, tsAdv) + require.NoError(t, err) +} + +func (s *smScaffolding) submitState(di *dline.Info) SubmitState { + return s.ch.submitHdlr.getPostWindow(di).submitState +} + +func makeTs(t *testing.T, h abi.ChainEpoch) *types.TipSet { + var parents []cid.Cid + msgcid := dummyCid + + a, _ := address.NewFromString("t00") + b, _ := address.NewFromString("t02") + var ts, err = types.NewTipSet([]*types.BlockHeader{ + { + Height: h, + Miner: a, + + Parents: parents, + + Ticket: &types.Ticket{VRFProof: []byte{byte(h % 2)}}, + + ParentStateRoot: dummyCid, + Messages: msgcid, + ParentMessageReceipts: dummyCid, + + BlockSig: &crypto.Signature{Type: crypto.SigTypeBLS}, + BLSAggregate: &crypto.Signature{Type: crypto.SigTypeBLS}, + }, + { + Height: h, + Miner: b, + + Parents: parents, + + Ticket: &types.Ticket{VRFProof: []byte{byte((h + 1) % 2)}}, + + ParentStateRoot: dummyCid, + Messages: msgcid, + ParentMessageReceipts: dummyCid, + + BlockSig: &crypto.Signature{Type: crypto.SigTypeBLS}, + BLSAggregate: &crypto.Signature{Type: crypto.SigTypeBLS}, + }, + }) + + require.NoError(t, err) + + return ts +} diff --git a/storage/wdpost_nextdl_test.go b/storage/wdpost_nextdl_test.go new file mode 100644 index 000000000..ad4b1fdeb --- /dev/null +++ b/storage/wdpost_nextdl_test.go @@ -0,0 +1,38 @@ +package storage + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/specs-actors/actors/builtin/miner" +) + +func TestNextDeadline(t *testing.T) { + periodStart := abi.ChainEpoch(0) + deadlineIdx := 0 + currentEpoch := abi.ChainEpoch(10) + + di := miner.NewDeadlineInfo(periodStart, uint64(deadlineIdx), currentEpoch) + require.EqualValues(t, 0, di.Index) + require.EqualValues(t, 0, di.PeriodStart) + require.EqualValues(t, -20, di.Challenge) + require.EqualValues(t, 0, di.Open) + require.EqualValues(t, 60, di.Close) + + for i := 1; i < 1+int(miner.WPoStPeriodDeadlines)*2; i++ { + di = nextDeadline(di) + deadlineIdx = i % int(miner.WPoStPeriodDeadlines) + expPeriodStart := int(miner.WPoStProvingPeriod) * (i / int(miner.WPoStPeriodDeadlines)) + expOpen := expPeriodStart + deadlineIdx*int(miner.WPoStChallengeWindow) + expClose := expOpen + int(miner.WPoStChallengeWindow) + expChallenge := expOpen - int(miner.WPoStChallengeLookback) + //fmt.Printf("%d: %d@%d %d-%d (%d)\n", i, expPeriodStart, deadlineIdx, expOpen, expClose, expChallenge) + require.EqualValues(t, deadlineIdx, di.Index) + require.EqualValues(t, expPeriodStart, di.PeriodStart) + require.EqualValues(t, expOpen, di.Open) + require.EqualValues(t, expClose, di.Close) + require.EqualValues(t, expChallenge, di.Challenge) + } +} diff --git a/storage/wdpost_run.go b/storage/wdpost_run.go index 9a497f879..35fdfc6d1 100644 --- a/storage/wdpost_run.go +++ b/storage/wdpost_run.go @@ -29,15 +29,21 @@ import ( "github.com/filecoin-project/lotus/journal" ) -func (s *WindowPoStScheduler) failPost(err error, deadline *dline.Info) { +func (s *WindowPoStScheduler) failPost(err error, ts *types.TipSet, deadline *dline.Info) { journal.J.RecordEvent(s.evtTypes[evtTypeWdPoStScheduler], func() interface{} { + c := evtCommon{Error: err} + if ts != nil { + c.Deadline = deadline + c.Height = ts.Height() + c.TipSet = ts.Cids() + } return WdPoStSchedulerEvt{ - evtCommon: s.getEvtCommon(err), + evtCommon: c, State: SchedulerStateFaulted, } }) - log.Errorf("TODO") + log.Errorf("Got err %w - TODO handle errors", err) /*s.failLk.Lock() if eps > s.failed { s.failed = eps @@ -45,67 +51,134 @@ func (s *WindowPoStScheduler) failPost(err error, deadline *dline.Info) { s.failLk.Unlock()*/ } -func (s *WindowPoStScheduler) doPost(ctx context.Context, deadline *dline.Info, ts *types.TipSet) { - ctx, abort := context.WithCancel(ctx) - - s.abort = abort - s.activeDeadline = deadline - - journal.J.RecordEvent(s.evtTypes[evtTypeWdPoStScheduler], func() interface{} { - return WdPoStSchedulerEvt{ - evtCommon: s.getEvtCommon(nil), - State: SchedulerStateStarted, +// recordProofsEvent records a successful proofs_processed event in the +// journal, even if it was a noop (no partitions). +func (s *WindowPoStScheduler) recordProofsEvent(partitions []miner.PoStPartition, mcid cid.Cid) { + journal.J.RecordEvent(s.evtTypes[evtTypeWdPoStProofs], func() interface{} { + return &WdPoStProofsProcessedEvt{ + evtCommon: s.getEvtCommon(nil), + Partitions: partitions, + MessageCID: mcid, } }) +} +// startGeneratePoST kicks off the process of generating a PoST +func (s *WindowPoStScheduler) startGeneratePoST( + ctx context.Context, + ts *types.TipSet, + deadline *dline.Info, + completeGeneratePoST CompleteGeneratePoSTCb, +) context.CancelFunc { + ctx, abort := context.WithCancel(ctx) go func() { defer abort() - ctx, span := trace.StartSpan(ctx, "WindowPoStScheduler.doPost") - defer span.End() - - // recordProofsEvent records a successful proofs_processed event in the - // journal, even if it was a noop (no partitions). - recordProofsEvent := func(partitions []miner.PoStPartition, mcid cid.Cid) { - journal.J.RecordEvent(s.evtTypes[evtTypeWdPoStProofs], func() interface{} { - return &WdPoStProofsProcessedEvt{ - evtCommon: s.getEvtCommon(nil), - Partitions: partitions, - MessageCID: mcid, - } - }) - } - - posts, err := s.runPost(ctx, *deadline, ts) - if err != nil { - log.Errorf("run window post failed: %+v", err) - s.failPost(err, deadline) - return - } - - if len(posts) == 0 { - recordProofsEvent(nil, cid.Undef) - return - } - - for i := range posts { - post := &posts[i] - sm, err := s.submitPost(ctx, post) - if err != nil { - log.Errorf("submit window post failed: %+v", err) - s.failPost(err, deadline) - } else { - recordProofsEvent(post.Partitions, sm.Cid()) - } - } - journal.J.RecordEvent(s.evtTypes[evtTypeWdPoStScheduler], func() interface{} { return WdPoStSchedulerEvt{ evtCommon: s.getEvtCommon(nil), - State: SchedulerStateSucceeded, + State: SchedulerStateStarted, } }) + + posts, err := s.runGeneratePoST(ctx, ts, deadline) + completeGeneratePoST(posts, err) }() + + return abort +} + +// runGeneratePoST generates the PoST +func (s *WindowPoStScheduler) runGeneratePoST( + ctx context.Context, + ts *types.TipSet, + deadline *dline.Info, +) ([]miner.SubmitWindowedPoStParams, error) { + ctx, span := trace.StartSpan(ctx, "WindowPoStScheduler.generatePoST") + defer span.End() + + posts, err := s.runPost(ctx, *deadline, ts) + if err != nil { + log.Errorf("runPost failed: %+v", err) + return nil, err + } + + if len(posts) == 0 { + s.recordProofsEvent(nil, cid.Undef) + } + + return posts, nil +} + +// startSubmitPoST kicks of the process of submitting PoST +func (s *WindowPoStScheduler) startSubmitPoST( + ctx context.Context, + ts *types.TipSet, + deadline *dline.Info, + posts []miner.SubmitWindowedPoStParams, + completeSubmitPoST CompleteSubmitPoSTCb, +) context.CancelFunc { + + ctx, abort := context.WithCancel(ctx) + go func() { + defer abort() + + err := s.runSubmitPoST(ctx, ts, deadline, posts) + if err == nil { + journal.J.RecordEvent(s.evtTypes[evtTypeWdPoStScheduler], func() interface{} { + return WdPoStSchedulerEvt{ + evtCommon: s.getEvtCommon(nil), + State: SchedulerStateSucceeded, + } + }) + } + completeSubmitPoST(err) + }() + + return abort +} + +// runSubmitPoST submits PoST +func (s *WindowPoStScheduler) runSubmitPoST( + ctx context.Context, + ts *types.TipSet, + deadline *dline.Info, + posts []miner.SubmitWindowedPoStParams, +) error { + if len(posts) == 0 { + return nil + } + + ctx, span := trace.StartSpan(ctx, "WindowPoStScheduler.submitPoST") + defer span.End() + + // Get randomness from tickets + commEpoch := deadline.Open + commRand, err := s.api.ChainGetRandomnessFromTickets(ctx, ts.Key(), crypto.DomainSeparationTag_PoStChainCommit, commEpoch, nil) + if err != nil { + err = xerrors.Errorf("failed to get chain randomness from tickets for windowPost (ts=%d; deadline=%d): %w", ts.Height(), commEpoch, err) + log.Errorf("submitPost failed: %+v", err) + + return err + } + + var submitErr error + for i := range posts { + // Add randomness to PoST + post := &posts[i] + post.ChainCommitEpoch = commEpoch + post.ChainCommitRand = commRand + + // Submit PoST + sm, submitErr := s.submitPost(ctx, post) + if submitErr != nil { + log.Errorf("submit window post failed: %+v", submitErr) + } else { + s.recordProofsEvent(post.Partitions, sm.Cid()) + } + } + + return submitErr } func (s *WindowPoStScheduler) checkSectors(ctx context.Context, check bitfield.BitField) (bitfield.BitField, error) { @@ -392,7 +465,7 @@ func (s *WindowPoStScheduler) runPost(ctx context.Context, di dline.Info, ts *ty rand, err := s.api.ChainGetRandomnessFromBeacon(ctx, ts.Key(), crypto.DomainSeparationTag_WindowedPoStChallengeSeed, di.Challenge, buf.Bytes()) if err != nil { - return nil, xerrors.Errorf("failed to get chain randomness for window post (ts=%d; deadline=%d): %w", ts.Height(), di, err) + return nil, xerrors.Errorf("failed to get chain randomness from beacon for window post (ts=%d; deadline=%d): %w", ts.Height(), di, err) } // Get the partitions for the given deadline @@ -536,19 +609,6 @@ func (s *WindowPoStScheduler) runPost(ctx context.Context, di dline.Info, ts *ty posts = append(posts, params) } - // Compute randomness after generating proofs so as to reduce the impact - // of chain reorgs (which change randomness) - commEpoch := di.Open - commRand, err := s.api.ChainGetRandomnessFromTickets(ctx, ts.Key(), crypto.DomainSeparationTag_PoStChainCommit, commEpoch, nil) - if err != nil { - return nil, xerrors.Errorf("failed to get chain randomness for window post (ts=%d; deadline=%d): %w", ts.Height(), commEpoch, err) - } - - for i := range posts { - posts[i].ChainCommitEpoch = commEpoch - posts[i].ChainCommitRand = commRand - } - return posts, nil } @@ -589,6 +649,7 @@ func (s *WindowPoStScheduler) batchPartitions(partitions []api.Partition) ([][]a } batches = append(batches, partitions[i:end]) } + return batches, nil } diff --git a/storage/wdpost_run_test.go b/storage/wdpost_run_test.go index 10be2fbcd..09b9aee5c 100644 --- a/storage/wdpost_run_test.go +++ b/storage/wdpost_run_test.go @@ -11,6 +11,7 @@ import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-bitfield" + "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/crypto" @@ -177,7 +178,10 @@ func TestWDPostDoPost(t *testing.T) { FaultDeclarationCutoff: miner0.FaultDeclarationCutoff, } ts := mockTipSet(t) - scheduler.doPost(ctx, di, ts) + + scheduler.startGeneratePoST(ctx, ts, di, func(posts []miner.SubmitWindowedPoStParams, err error) { + scheduler.startSubmitPoST(ctx, ts, di, posts, func(err error) {}) + }) // Read the window PoST messages for i := 0; i < expectedMsgCount; i++ { diff --git a/storage/wdpost_sched.go b/storage/wdpost_sched.go index 7e60fd9ee..3a76a219f 100644 --- a/storage/wdpost_sched.go +++ b/storage/wdpost_sched.go @@ -22,8 +22,6 @@ import ( "go.opencensus.io/trace" ) -const StartConfidence = 4 // TODO: config - type WindowPoStScheduler struct { api storageMinerApi feeCfg config.MinerFeeConfig @@ -31,16 +29,11 @@ type WindowPoStScheduler struct { faultTracker sectorstorage.FaultTracker proofType abi.RegisteredPoStProof partitionSectors uint64 + ch *changeHandler actor address.Address worker address.Address - cur *types.TipSet - - // if a post is in progress, this indicates for which ElectionPeriodStart - activeDeadline *dline.Info - abort context.CancelFunc - evtTypes [4]journal.EventType // failed abi.ChainEpoch // eps @@ -77,16 +70,17 @@ func NewWindowedPoStScheduler(api storageMinerApi, fc config.MinerFeeConfig, sb }, nil } -func deadlineEquals(a, b *dline.Info) bool { - if a == nil || b == nil { - return b == a - } - - return a.PeriodStart == b.PeriodStart && a.Index == b.Index && a.Challenge == b.Challenge +type changeHandlerAPIImpl struct { + storageMinerApi + *WindowPoStScheduler } func (s *WindowPoStScheduler) Run(ctx context.Context) { - defer s.abortActivePoSt() + // Initialize change handler + chImpl := &changeHandlerAPIImpl{storageMinerApi: s.api, WindowPoStScheduler: s} + s.ch = newChangeHandler(chImpl, s.actor) + defer s.ch.shutdown() + s.ch.start() var notifs <-chan []*api.HeadChange var err error @@ -125,9 +119,7 @@ func (s *WindowPoStScheduler) Run(ctx context.Context) { continue } - if err := s.update(ctx, chg.Val); err != nil { - log.Errorf("%+v", err) - } + s.update(ctx, nil, chg.Val) gotCur = true continue @@ -135,7 +127,7 @@ func (s *WindowPoStScheduler) Run(ctx context.Context) { ctx, span := trace.StartSpan(ctx, "WindowPoStScheduler.headChange") - var lowest, highest *types.TipSet = s.cur, nil + var lowest, highest *types.TipSet = nil, nil for _, change := range changes { if change.Val == nil { @@ -149,12 +141,7 @@ func (s *WindowPoStScheduler) Run(ctx context.Context) { } } - if err := s.revert(ctx, lowest); err != nil { - log.Error("handling head reverts in window post sched: %+v", err) - } - if err := s.update(ctx, highest); err != nil { - log.Error("handling head updates in window post sched: %+v", err) - } + s.update(ctx, lowest, highest) span.End() case <-ctx.Done(): @@ -163,95 +150,40 @@ func (s *WindowPoStScheduler) Run(ctx context.Context) { } } -func (s *WindowPoStScheduler) revert(ctx context.Context, newLowest *types.TipSet) error { - if s.cur == newLowest { - return nil +func (s *WindowPoStScheduler) update(ctx context.Context, revert, apply *types.TipSet) { + if apply == nil { + log.Error("no new tipset in window post WindowPoStScheduler.update") + return } - s.cur = newLowest - - newDeadline, err := s.api.StateMinerProvingDeadline(ctx, s.actor, newLowest.Key()) + err := s.ch.update(ctx, revert, apply) if err != nil { - return err + log.Errorf("handling head updates in window post sched: %+v", err) } - - if !deadlineEquals(s.activeDeadline, newDeadline) { - s.abortActivePoSt() - } - - return nil } -func (s *WindowPoStScheduler) update(ctx context.Context, new *types.TipSet) error { - if new == nil { - return xerrors.Errorf("no new tipset in window post sched update") - } - - di, err := s.api.StateMinerProvingDeadline(ctx, s.actor, new.Key()) - if err != nil { - return err - } - - if deadlineEquals(s.activeDeadline, di) { - return nil // already working on this deadline - } - - if !di.PeriodStarted() { - return nil // not proving anything yet - } - - s.abortActivePoSt() - - // TODO: wait for di.Challenge here, will give us ~10min more to compute windowpost - // (Need to get correct deadline above, which is tricky) - - if di.Open+StartConfidence >= new.Height() { - log.Info("not starting window post yet, waiting for startconfidence", di.Open, di.Open+StartConfidence, new.Height()) - return nil - } - - /*s.failLk.Lock() - if s.failed > 0 { - s.failed = 0 - s.activeEPS = 0 - } - s.failLk.Unlock()*/ - log.Infof("at %d, do window post for P %d, dd %d", new.Height(), di.PeriodStart, di.Index) - - s.doPost(ctx, di, new) - - return nil +// onAbort is called when generating proofs or submitting proofs is aborted +func (s *WindowPoStScheduler) onAbort(ts *types.TipSet, deadline *dline.Info) { + journal.J.RecordEvent(s.evtTypes[evtTypeWdPoStScheduler], func() interface{} { + c := evtCommon{} + if ts != nil { + c.Deadline = deadline + c.Height = ts.Height() + c.TipSet = ts.Cids() + } + return WdPoStSchedulerEvt{ + evtCommon: c, + State: SchedulerStateAborted, + } + }) } -func (s *WindowPoStScheduler) abortActivePoSt() { - if s.activeDeadline == nil { - return // noop - } - - if s.abort != nil { - s.abort() - - journal.J.RecordEvent(s.evtTypes[evtTypeWdPoStScheduler], func() interface{} { - return WdPoStSchedulerEvt{ - evtCommon: s.getEvtCommon(nil), - State: SchedulerStateAborted, - } - }) - - log.Warnf("Aborting window post (Deadline: %+v)", s.activeDeadline) - } - - s.activeDeadline = nil - s.abort = nil -} - -// getEvtCommon populates and returns common attributes from state, for a -// WdPoSt journal event. func (s *WindowPoStScheduler) getEvtCommon(err error) evtCommon { c := evtCommon{Error: err} - if s.cur != nil { - c.Deadline = s.activeDeadline - c.Height = s.cur.Height() - c.TipSet = s.cur.Cids() + currentTS, currentDeadline := s.ch.currentTSDI() + if currentTS != nil { + c.Deadline = currentDeadline + c.Height = currentTS.Height() + c.TipSet = currentTS.Cids() } return c } From 43323b21887cb3a64a8d8680839d3f7679206dcd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Thu, 24 Sep 2020 16:03:24 +0200 Subject: [PATCH 192/303] Use continue instead of goto --- miner/miner.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/miner/miner.go b/miner/miner.go index 3b1e65a72..af566d142 100644 --- a/miner/miner.go +++ b/miner/miner.go @@ -171,7 +171,7 @@ minerLoop: if err != nil { log.Errorf("failed to get best mining candidate: %s", err) if !m.niceSleep(time.Second * 5) { - goto minerLoop + continue minerLoop } continue } @@ -203,7 +203,7 @@ minerLoop: if err != nil { log.Errorf("failed getting beacon entry: %s", err) if !m.niceSleep(time.Second) { - goto minerLoop + continue minerLoop } continue } @@ -214,7 +214,7 @@ minerLoop: if base.TipSet.Equals(lastBase.TipSet) && lastBase.NullRounds == base.NullRounds { log.Warnf("BestMiningCandidate from the previous round: %s (nulls:%d)", lastBase.TipSet.Cids(), lastBase.NullRounds) if !m.niceSleep(time.Duration(build.BlockDelaySecs) * time.Second) { - goto minerLoop + continue minerLoop } continue } @@ -225,7 +225,7 @@ minerLoop: if err != nil { log.Errorf("mining block failed: %+v", err) if !m.niceSleep(time.Second) { - goto minerLoop + continue minerLoop } onDone(false, 0, err) continue From f8f335df5562dcb22a46ffeb9f466667a058c3ed Mon Sep 17 00:00:00 2001 From: jennijuju Date: Wed, 23 Sep 2020 12:53:03 -0400 Subject: [PATCH 193/303] 3941: Added cmd `lotus-miner proving deadline " - To show the current proving period deadline information of given deadline index. - It outputs the following: - number of partitions in this deadline - partitions numbers has submitted PoSt since the current proving period started - if the deadline is the current proving deadline - for each patition, shows the amount of the sectors in this partition, and their numbers. Also, shows the number of fault sectors and corresponding sector numbers. --- cmd/lotus-storage-miner/proving.go | 92 ++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) diff --git a/cmd/lotus-storage-miner/proving.go b/cmd/lotus-storage-miner/proving.go index 4656c2263..377b81d32 100644 --- a/cmd/lotus-storage-miner/proving.go +++ b/cmd/lotus-storage-miner/proving.go @@ -3,6 +3,7 @@ package main import ( "fmt" "os" + "strconv" "text/tabwriter" "github.com/fatih/color" @@ -22,6 +23,7 @@ var provingCmd = &cli.Command{ Subcommands: []*cli.Command{ provingInfoCmd, provingDeadlinesCmd, + provingDeadlineInfoCmd, provingFaultsCmd, }, } @@ -279,3 +281,93 @@ var provingDeadlinesCmd = &cli.Command{ return tw.Flush() }, } + +var provingDeadlineInfoCmd = &cli.Command{ + Name: "deadline", + Usage: "View the current proving period deadline information by its index ", + ArgsUsage: "", + Action: func(cctx *cli.Context) error { + + if cctx.Args().Len() != 1 { + return xerrors.Errorf("must pass deadline index") + } + + dlIdx, err := strconv.ParseUint(cctx.Args().Get(0), 10, 64) + if err != nil { + return xerrors.Errorf("could not parse deadline index: %w", err) + } + + nodeApi, closer, err := lcli.GetStorageMinerAPI(cctx) + if err != nil { + return err + } + defer closer() + + api, acloser, err := lcli.GetFullNodeAPI(cctx) + if err != nil { + return err + } + defer acloser() + + ctx := lcli.ReqContext(cctx) + + maddr, err := getActorAddress(ctx, nodeApi, cctx.String("actor")) + if err != nil { + return err + } + + deadlines, err := api.StateMinerDeadlines(ctx, maddr, types.EmptyTSK) + if err != nil { + return xerrors.Errorf("getting deadlines: %w", err) + } + + di, err := api.StateMinerProvingDeadline(ctx, maddr, types.EmptyTSK) + if err != nil { + return xerrors.Errorf("getting deadlines: %w", err) + } + + partitions, err := api.StateMinerPartitions(ctx, maddr, dlIdx, types.EmptyTSK) + if err != nil { + return xerrors.Errorf("getting partitions for deadline %d: %w", dlIdx, err) + } + + provenPartitions, err := deadlines[dlIdx].PostSubmissions.Count() + if err != nil { + return err + } + + fmt.Printf("Deadline Index: %d\n", dlIdx) + fmt.Printf("Partitions: %d\n", len(partitions)) + fmt.Printf("Proven Partitions: %d\n", provenPartitions) + fmt.Printf("Current: %t\n\n", di.Index == dlIdx) + + for pIdx, partition := range partitions { + sectorCount, err := partition.AllSectors.Count() + if err != nil { + return err + } + + sectorNumbers, err := partition.AllSectors.All(sectorCount) + if err != nil { + return err + } + + faultsCount, err := partition.FaultySectors.Count() + if err != nil { + return err + } + + fn, err := partition.FaultySectors.All(faultsCount) + if err != nil { + return err + } + + fmt.Printf("Partition Index: %d\n", pIdx) + fmt.Printf("Sectors: %d\n", sectorCount) + fmt.Printf("Sector Numbers: %v\n", sectorNumbers) + fmt.Printf("Faults: %d\n", faultsCount) + fmt.Printf("Faulty Sectors: %d\n", fn) + } + return nil + }, +} From 4eaa05db5227f214fdd1188f480b4e7826bed596 Mon Sep 17 00:00:00 2001 From: whyrusleeping Date: Thu, 24 Sep 2020 09:40:49 -0700 Subject: [PATCH 194/303] add some more big pictures stats to stateroot stat --- cmd/lotus-shed/stateroot-stats.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/cmd/lotus-shed/stateroot-stats.go b/cmd/lotus-shed/stateroot-stats.go index c02e0202a..023f782bd 100644 --- a/cmd/lotus-shed/stateroot-stats.go +++ b/cmd/lotus-shed/stateroot-stats.go @@ -182,6 +182,11 @@ var staterootStatCmd = &cli.Command{ return infos[i].Stat.Size > infos[j].Stat.Size }) + var totalActorsSize uint64 + for _, info := range infos { + totalActorsSize += info.Stat.Size + } + outcap := 10 if cctx.Args().Len() > outcap { outcap = cctx.Args().Len() @@ -190,6 +195,15 @@ var staterootStatCmd = &cli.Command{ outcap = len(infos) } + totalStat, err := api.ChainStatObj(ctx, ts.ParentState(), cid.Undef) + if err != nil { + return err + } + + fmt.Println("Total state tree size: ", totalStat.Size) + fmt.Println("Sum of actor state size: ", totalActorsSize) + fmt.Println("State tree structure size: ", totalStat.Size-totalActorsSize) + fmt.Print("Addr\tType\tSize\n") for _, inf := range infos[:outcap] { cmh, err := multihash.Decode(inf.Actor.Code.Hash()) From 130ae3ccb34fad93454faa2061129915fd1b6192 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Thu, 24 Sep 2020 18:46:21 +0200 Subject: [PATCH 195/303] Multisig: Fix from flag descriptions --- cli/multisig.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cli/multisig.go b/cli/multisig.go index 944f67b2e..145f5ac41 100644 --- a/cli/multisig.go +++ b/cli/multisig.go @@ -968,7 +968,7 @@ var msigLockProposeCmd = &cli.Command{ Flags: []cli.Flag{ &cli.StringFlag{ Name: "from", - Usage: "account to send the approve message from", + Usage: "account to send the propose message from", }, }, Action: func(cctx *cli.Context) error { @@ -1152,7 +1152,7 @@ var msigLockCancelCmd = &cli.Command{ Flags: []cli.Flag{ &cli.StringFlag{ Name: "from", - Usage: "account to send the approve message from", + Usage: "account to send the cancel message from", }, }, Action: func(cctx *cli.Context) error { From 87b48c94a63437c54596942d3c121f6ff6caa3d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Kripalani?= Date: Thu, 24 Sep 2020 17:58:34 +0100 Subject: [PATCH 196/303] conformance: supply network version to driver. --- conformance/driver.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/conformance/driver.go b/conformance/driver.go index 66b6d0f8a..f43a8739d 100644 --- a/conformance/driver.go +++ b/conformance/driver.go @@ -122,6 +122,8 @@ func (d *Driver) ExecuteTipset(bs blockstore.Blockstore, ds ds.Batching, preroot // ExecuteMessage executes a conformance test vector message in a temporary VM. func (d *Driver) ExecuteMessage(bs blockstore.Blockstore, preroot cid.Cid, epoch abi.ChainEpoch, msg *types.Message) (*vm.ApplyRet, cid.Cid, error) { + // dummy state manager; only to reference the GetNetworkVersion method, which does not depend on state. + sm := new(stmgr.StateManager) vmOpts := &vm.VMOpts{ StateBase: preroot, Epoch: epoch, @@ -130,6 +132,7 @@ func (d *Driver) ExecuteMessage(bs blockstore.Blockstore, preroot cid.Cid, epoch Syscalls: mkFakedSigSyscalls(vm.Syscalls(ffiwrapper.ProofVerifier)), // TODO always succeeds; need more flexibility. CircSupplyCalc: nil, BaseFee: BaseFee, + NtwkVersion: sm.GetNtwkVersion, } lvm, err := vm.NewVM(context.TODO(), vmOpts) From 68663060dc19c67d09bc1544527b724b1accbe68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Kripalani?= Date: Thu, 24 Sep 2020 17:58:49 +0100 Subject: [PATCH 197/303] add state.StateTree#Version() accessor. --- chain/state/statetree.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/chain/state/statetree.go b/chain/state/statetree.go index a654d224b..fe932bfa1 100644 --- a/chain/state/statetree.go +++ b/chain/state/statetree.go @@ -395,6 +395,11 @@ func (st *StateTree) ForEach(f func(address.Address, *types.Actor) error) error }) } +// Version returns the version of the StateTree data structure in use. +func (st *StateTree) Version() builtin.Version { + return st.version +} + func Diff(oldTree, newTree *StateTree) (map[string]types.Actor, error) { out := map[string]types.Actor{} From cf9dfdb972f97251f604e9286f34450b2254085d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Thu, 24 Sep 2020 19:01:12 +0200 Subject: [PATCH 198/303] Multisig: fix build --- cli/multisig.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/cli/multisig.go b/cli/multisig.go index 145f5ac41..5b0977382 100644 --- a/cli/multisig.go +++ b/cli/multisig.go @@ -20,6 +20,7 @@ import ( "github.com/urfave/cli/v2" "golang.org/x/xerrors" + "github.com/filecoin-project/specs-actors/actors/builtin" init0 "github.com/filecoin-project/specs-actors/actors/builtin/init" msig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig" @@ -1018,7 +1019,7 @@ var msigLockProposeCmd = &cli.Command{ from = defaddr } - params, actErr := actors.SerializeParams(&samsig.LockBalanceParams{ + params, actErr := actors.SerializeParams(&msig0.LockBalanceParams{ StartEpoch: abi.ChainEpoch(start), UnlockDuration: abi.ChainEpoch(duration), Amount: abi.NewTokenAmount(amount.Int64()), @@ -1115,7 +1116,7 @@ var msigLockApproveCmd = &cli.Command{ from = defaddr } - params, actErr := actors.SerializeParams(&samsig.LockBalanceParams{ + params, actErr := actors.SerializeParams(&msig0.LockBalanceParams{ StartEpoch: abi.ChainEpoch(start), UnlockDuration: abi.ChainEpoch(duration), Amount: abi.NewTokenAmount(amount.Int64()), @@ -1207,7 +1208,7 @@ var msigLockCancelCmd = &cli.Command{ from = defaddr } - params, actErr := actors.SerializeParams(&samsig.LockBalanceParams{ + params, actErr := actors.SerializeParams(&msig0.LockBalanceParams{ StartEpoch: abi.ChainEpoch(start), UnlockDuration: abi.ChainEpoch(duration), Amount: abi.NewTokenAmount(amount.Int64()), From e48c525053ada752041c4917a5c22d9610e8746d Mon Sep 17 00:00:00 2001 From: Hector Sanjuan Date: Thu, 24 Sep 2020 19:41:14 +0200 Subject: [PATCH 199/303] Re-add jaeger-tracing --- documentation/en/jaeger-tracing.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 documentation/en/jaeger-tracing.md diff --git a/documentation/en/jaeger-tracing.md b/documentation/en/jaeger-tracing.md new file mode 100644 index 000000000..bbe4d3052 --- /dev/null +++ b/documentation/en/jaeger-tracing.md @@ -0,0 +1,26 @@ +# Jaeger Tracing + +Lotus has tracing built into many of its internals. To view the traces, first download [Jaeger](https://www.jaegertracing.io/download/) (Choose the 'all-in-one' binary). Then run it somewhere, start up the lotus daemon, and open up localhost:16686 in your browser. + +## Open Census + +Lotus uses [OpenCensus](https://opencensus.io/) for tracing application flow. This generates spans through the execution of annotated code paths. + +Currently it is set up to use Jaeger, though other tracing backends should be fairly easy to swap in. + +## Running Locally + +To easily run and view tracing locally, first, install jaeger. The easiest way to do this is to [download the binaries](https://www.jaegertracing.io/download/) and then run the `jaeger-all-in-one` binary. This will start up jaeger, listen for spans on `localhost:6831`, and expose a web UI for viewing traces on `http://localhost:16686/`. + +Now, to start sending traces from Lotus to Jaeger, set the environment variable `LOTUS_JAEGER` to `localhost:6831`, and start the `lotus daemon`. + +Now, to view any generated traces, open up `http://localhost:16686/` in your browser. + +## Adding Spans + +To annotate a new codepath with spans, add the following lines to the top of the function you wish to trace: + +```go +ctx, span := trace.StartSpan(ctx, "put function name here") +defer span.End() +``` From 6db37b72a85bf056630d757f591d11c92f8c65c9 Mon Sep 17 00:00:00 2001 From: whyrusleeping Date: Thu, 24 Sep 2020 11:05:21 -0700 Subject: [PATCH 200/303] update ffi to code with blst fixes --- extern/filecoin-ffi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extern/filecoin-ffi b/extern/filecoin-ffi index f640612a1..57e38efe4 160000 --- a/extern/filecoin-ffi +++ b/extern/filecoin-ffi @@ -1 +1 @@ -Subproject commit f640612a1a1f7a2dd8b3a49e1531db0aa0f63447 +Subproject commit 57e38efe4943f09d3127dcf6f0edd614e6acf68e From 306c098d304cb853351a9fe7d8ccf8ccb2bb1caa Mon Sep 17 00:00:00 2001 From: whyrusleeping Date: Thu, 24 Sep 2020 11:32:38 -0700 Subject: [PATCH 201/303] also update our vendored blst repo --- extern/fil-blst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extern/fil-blst b/extern/fil-blst index 5f93488fc..8609119cf 160000 --- a/extern/fil-blst +++ b/extern/fil-blst @@ -1 +1 @@ -Subproject commit 5f93488fc0dbfb450f2355269f18fc67010d59bb +Subproject commit 8609119cf4595d1741139c24378fcd8bc4f1c475 From 585b8cc51dee241dd0d340bd3df0502b10e324a6 Mon Sep 17 00:00:00 2001 From: Arsenii Petrovich Date: Fri, 25 Sep 2020 03:54:29 +0300 Subject: [PATCH 202/303] Add glif node to bootstrap peers --- build/bootstrap/bootstrappers.pi | 1 + 1 file changed, 1 insertion(+) diff --git a/build/bootstrap/bootstrappers.pi b/build/bootstrap/bootstrappers.pi index 465f3b5e9..481ede6ab 100644 --- a/build/bootstrap/bootstrappers.pi +++ b/build/bootstrap/bootstrappers.pi @@ -4,3 +4,4 @@ /dns4/bootstrap-4.testnet.fildev.network/tcp/1347/p2p/12D3KooWPkL9LrKRQgHtq7kn9ecNhGU9QaziG8R5tX8v9v7t3h34 /dns4/bootstrap-3.testnet.fildev.network/tcp/1347/p2p/12D3KooWKYSsbpgZ3HAjax5M1BXCwXLa6gVkUARciz7uN3FNtr7T /dns4/bootstrap-5.testnet.fildev.network/tcp/1347/p2p/12D3KooWQYzqnLASJAabyMpPb1GcWZvNSe7JDcRuhdRqonFoiK9W +/dns4/node.glif.io/tcp/1235/p2p/12D3KooWBF8cpp65hp2u9LK5mh19x67ftAam84z9LsfaquTDSBpt From 89bfe84f36bc8264a50cc6f9982774e06feac7e8 Mon Sep 17 00:00:00 2001 From: MaoBisheng-IPFSUNION Date: Fri, 25 Sep 2020 10:18:12 +0800 Subject: [PATCH 203/303] add new booststrappers we hope to add two booststrappers for the filecoin network to improve the network synchronization --- build/bootstrap/bootstrappers.pi | 3 +++ 1 file changed, 3 insertions(+) diff --git a/build/bootstrap/bootstrappers.pi b/build/bootstrap/bootstrappers.pi index 9c619b1bb..e64bd9dae 100644 --- a/build/bootstrap/bootstrappers.pi +++ b/build/bootstrap/bootstrappers.pi @@ -4,3 +4,6 @@ /dns4/lotus-bootstrap-1.fra.fil-test.net/tcp/1347/p2p/12D3KooWLLpNYoKdf9NgcWudBhXLdTcXncqAsTzozw1scMMu6nS5 /dns4/lotus-bootstrap-0.sin.fil-test.net/tcp/1347/p2p/12D3KooWCNL9vXaXwNs3Bu8uRAJK4pxpCyPeM7jZLSDpJma1wrV8 /dns4/lotus-bootstrap-1.sin.fil-test.net/tcp/1347/p2p/12D3KooWNGGxFda1eC5U2YKAgs4ypoFHn3Z3xHCsjmFdrCcytoxm + +/dns4/bootstrap-0.starpool.in/tcp/12757/p2p/12D3KooWGHpBMeZbestVEWkfdnC9u7p6uFHXL1n7m1ZBqsEmiUzz +/dns4/bootstrap-1.starpool.in/tcp/12757/p2p/12D3KooWQZrGH1PxSNZPum99M1zNvjNFM33d1AAu5DcvdHptuU7u From 8fbbebbaf14ce6726bfaea328a6899b63f6fcc0b Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Fri, 25 Sep 2020 00:11:10 -0400 Subject: [PATCH 204/303] Correct helptext around set ask --- cmd/lotus-storage-miner/market.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/lotus-storage-miner/market.go b/cmd/lotus-storage-miner/market.go index 1c9eac1b7..0e7be3dd3 100644 --- a/cmd/lotus-storage-miner/market.go +++ b/cmd/lotus-storage-miner/market.go @@ -156,12 +156,12 @@ var setAskCmd = &cli.Command{ Flags: []cli.Flag{ &cli.Uint64Flag{ Name: "price", - Usage: "Set the price of the ask for unverified deals (specified as FIL / GiB / Epoch) to `PRICE`", + Usage: "Set the price of the ask for unverified deals (specified as attoFIL / GiB / Epoch) to `PRICE`", Required: true, }, &cli.Uint64Flag{ Name: "verified-price", - Usage: "Set the price of the ask for verified deals (specified as FIL / GiB / Epoch) to `PRICE`", + Usage: "Set the price of the ask for verified deals (specified as attoFIL / GiB / Epoch) to `PRICE`", Required: true, }, &cli.StringFlag{ From 4ff38aa8564a3c86391bc6886e5e37d0c7ca286e Mon Sep 17 00:00:00 2001 From: hannahhoward Date: Fri, 25 Sep 2020 02:35:34 -0700 Subject: [PATCH 205/303] feat(markets): update to 0.6.3 --- go.mod | 6 +++--- go.sum | 12 ++++++------ 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/go.mod b/go.mod index cfdf4cb1d..ca7e0760d 100644 --- a/go.mod +++ b/go.mod @@ -25,9 +25,9 @@ require ( github.com/filecoin-project/go-bitfield v0.2.0 github.com/filecoin-project/go-cbor-util v0.0.0-20191219014500-08c40a1e63a2 github.com/filecoin-project/go-crypto v0.0.0-20191218222705-effae4ea9f03 - github.com/filecoin-project/go-data-transfer v0.6.5 + github.com/filecoin-project/go-data-transfer v0.6.6 github.com/filecoin-project/go-fil-commcid v0.0.0-20200716160307-8f644712406f - github.com/filecoin-project/go-fil-markets v0.6.2 + github.com/filecoin-project/go-fil-markets v0.6.3 github.com/filecoin-project/go-jsonrpc v0.1.2-0.20200822201400-474f4fdccc52 github.com/filecoin-project/go-multistore v0.0.3 github.com/filecoin-project/go-padreader v0.0.0-20200903213702-ed5fae088b20 @@ -60,7 +60,7 @@ require ( github.com/ipfs/go-ds-measure v0.1.0 github.com/ipfs/go-filestore v1.0.0 github.com/ipfs/go-fs-lock v0.0.6 - github.com/ipfs/go-graphsync v0.2.0 + github.com/ipfs/go-graphsync v0.2.1 github.com/ipfs/go-ipfs-blockstore v1.0.1 github.com/ipfs/go-ipfs-chunker v0.0.5 github.com/ipfs/go-ipfs-ds-help v1.0.0 diff --git a/go.sum b/go.sum index 3b31e6c3b..1ca615b59 100644 --- a/go.sum +++ b/go.sum @@ -222,12 +222,12 @@ github.com/filecoin-project/go-cbor-util v0.0.0-20191219014500-08c40a1e63a2 h1:a github.com/filecoin-project/go-cbor-util v0.0.0-20191219014500-08c40a1e63a2/go.mod h1:pqTiPHobNkOVM5thSRsHYjyQfq7O5QSCMhvuu9JoDlg= github.com/filecoin-project/go-crypto v0.0.0-20191218222705-effae4ea9f03 h1:2pMXdBnCiXjfCYx/hLqFxccPoqsSveQFxVLvNxy9bus= github.com/filecoin-project/go-crypto v0.0.0-20191218222705-effae4ea9f03/go.mod h1:+viYnvGtUTgJRdy6oaeF4MTFKAfatX071MPDPBL11EQ= -github.com/filecoin-project/go-data-transfer v0.6.5 h1:oP20la8Z0CLrw0uqvt6xVgw6rOevZeGJ9GNQeC0OCSU= -github.com/filecoin-project/go-data-transfer v0.6.5/go.mod h1:I9Ylb/UiZyqnI41wUoCXq/le0nDLhlwpFQCtNPxEPOA= +github.com/filecoin-project/go-data-transfer v0.6.6 h1:2TccLSxPYJENcYRdov2WvpTvQ1qUMrPkWe8sBrfj36g= +github.com/filecoin-project/go-data-transfer v0.6.6/go.mod h1:C++k1U6+jMQODOaen5OPDo9XQbth9Yq3ie94vNjBJbk= github.com/filecoin-project/go-fil-commcid v0.0.0-20200716160307-8f644712406f h1:GxJzR3oRIMTPtpZ0b7QF8FKPK6/iPAc7trhlL5k/g+s= github.com/filecoin-project/go-fil-commcid v0.0.0-20200716160307-8f644712406f/go.mod h1:Eaox7Hvus1JgPrL5+M3+h7aSPHc0cVqpSxA+TxIEpZQ= -github.com/filecoin-project/go-fil-markets v0.6.2 h1:9Z57KeaQSa1liCmT1pH6SIjrn9mGTDFJXmR2WQVuaiY= -github.com/filecoin-project/go-fil-markets v0.6.2/go.mod h1:wtN4Hc/1hoVCpWhSWYxwUxH3PQtjSkWWuC1nQjiIWog= +github.com/filecoin-project/go-fil-markets v0.6.3 h1:3kTxfquGvk3zQY+hJH1kEA28tRQ47phqSRqOI4+YcQM= +github.com/filecoin-project/go-fil-markets v0.6.3/go.mod h1:Ug1yhGhzTYC6qrpKsR2QpU8QRCeBpwkTA9RICVKuOMM= github.com/filecoin-project/go-hamt-ipld v0.1.5 h1:uoXrKbCQZ49OHpsTCkrThPNelC4W3LPEk0OrS/ytIBM= github.com/filecoin-project/go-hamt-ipld v0.1.5 h1:uoXrKbCQZ49OHpsTCkrThPNelC4W3LPEk0OrS/ytIBM= github.com/filecoin-project/go-hamt-ipld v0.1.5/go.mod h1:6Is+ONR5Cd5R6XZoCse1CWaXZc0Hdb/JeX+EQCQzX24= @@ -502,8 +502,8 @@ github.com/ipfs/go-filestore v1.0.0/go.mod h1:/XOCuNtIe2f1YPbiXdYvD0BKLA0JR1MgPi github.com/ipfs/go-fs-lock v0.0.6 h1:sn3TWwNVQqSeNjlWy6zQ1uUGAZrV3hPOyEA6y1/N2a0= github.com/ipfs/go-fs-lock v0.0.6/go.mod h1:OTR+Rj9sHiRubJh3dRhD15Juhd/+w6VPOY28L7zESmM= github.com/ipfs/go-graphsync v0.1.0/go.mod h1:jMXfqIEDFukLPZHqDPp8tJMbHO9Rmeb9CEGevngQbmE= -github.com/ipfs/go-graphsync v0.2.0 h1:x94MvHLNuRwBlZzVal7tR1RYK7T7H6bqQLPopxDbIF0= -github.com/ipfs/go-graphsync v0.2.0/go.mod h1:gEBvJUNelzMkaRPJTpg/jaKN4AQW/7wDWu0K92D8o10= +github.com/ipfs/go-graphsync v0.2.1 h1:MdehhqBSuTI2LARfKLkpYnt0mUrqHs/mtuDnESXHBfU= +github.com/ipfs/go-graphsync v0.2.1/go.mod h1:gEBvJUNelzMkaRPJTpg/jaKN4AQW/7wDWu0K92D8o10= github.com/ipfs/go-hamt-ipld v0.1.1/go.mod h1:1EZCr2v0jlCnhpa+aZ0JZYp8Tt2w16+JJOAVz17YcDk= github.com/ipfs/go-ipfs-blockstore v0.0.1/go.mod h1:d3WClOmRQKFnJ0Jz/jj/zmksX0ma1gROTlovZKBmN08= github.com/ipfs/go-ipfs-blockstore v0.1.0/go.mod h1:5aD0AvHPi7mZc6Ci1WCAhiBQu2IsfTduLl+422H6Rqw= From 9dfce400a7a5234ace883ae61648f94eb915516f Mon Sep 17 00:00:00 2001 From: MaoBisheng-IPFSUNION Date: Fri, 25 Sep 2020 17:36:57 +0800 Subject: [PATCH 206/303] delate --- build/bootstrap/bootstrappers.pi | 1 - 1 file changed, 1 deletion(-) diff --git a/build/bootstrap/bootstrappers.pi b/build/bootstrap/bootstrappers.pi index e64bd9dae..802f1471a 100644 --- a/build/bootstrap/bootstrappers.pi +++ b/build/bootstrap/bootstrappers.pi @@ -4,6 +4,5 @@ /dns4/lotus-bootstrap-1.fra.fil-test.net/tcp/1347/p2p/12D3KooWLLpNYoKdf9NgcWudBhXLdTcXncqAsTzozw1scMMu6nS5 /dns4/lotus-bootstrap-0.sin.fil-test.net/tcp/1347/p2p/12D3KooWCNL9vXaXwNs3Bu8uRAJK4pxpCyPeM7jZLSDpJma1wrV8 /dns4/lotus-bootstrap-1.sin.fil-test.net/tcp/1347/p2p/12D3KooWNGGxFda1eC5U2YKAgs4ypoFHn3Z3xHCsjmFdrCcytoxm - /dns4/bootstrap-0.starpool.in/tcp/12757/p2p/12D3KooWGHpBMeZbestVEWkfdnC9u7p6uFHXL1n7m1ZBqsEmiUzz /dns4/bootstrap-1.starpool.in/tcp/12757/p2p/12D3KooWQZrGH1PxSNZPum99M1zNvjNFM33d1AAu5DcvdHptuU7u From 13b38815c2e6df6d7d16cb024f3fedad1b2a4967 Mon Sep 17 00:00:00 2001 From: zgfzgf <1901989065@qq.com> Date: Fri, 25 Sep 2020 20:31:07 +0800 Subject: [PATCH 207/303] add trace wdpost --- storage/wdpost_sched.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/storage/wdpost_sched.go b/storage/wdpost_sched.go index 7e60fd9ee..9477e0306 100644 --- a/storage/wdpost_sched.go +++ b/storage/wdpost_sched.go @@ -125,10 +125,13 @@ func (s *WindowPoStScheduler) Run(ctx context.Context) { continue } + ctx, span := trace.StartSpan(ctx, "WindowPoStScheduler.headChange") + if err := s.update(ctx, chg.Val); err != nil { log.Errorf("%+v", err) } + span.End() gotCur = true continue } From 80a7ed811638853987a3124175606d7db5269bf2 Mon Sep 17 00:00:00 2001 From: Dirk McCormick Date: Fri, 25 Sep 2020 15:54:27 +0200 Subject: [PATCH 208/303] refactor: use abstract types instead of specs-actors --- chain/actors/builtin/miner/miner.go | 4 ++++ storage/wdpost_changehandler.go | 8 ++++++-- storage/wdpost_changehandler_test.go | 8 ++++---- storage/wdpost_nextdl_test.go | 4 ++-- 4 files changed, 16 insertions(+), 8 deletions(-) diff --git a/chain/actors/builtin/miner/miner.go b/chain/actors/builtin/miner/miner.go index 50a0fc5ca..e09cac587 100644 --- a/chain/actors/builtin/miner/miner.go +++ b/chain/actors/builtin/miner/miner.go @@ -21,6 +21,10 @@ import ( // Unchanged between v0 and v1 actors var PreCommitChallengeDelay = miner0.PreCommitChallengeDelay var WPoStProvingPeriod = miner0.WPoStProvingPeriod +var WPoStPeriodDeadlines = miner0.WPoStPeriodDeadlines +var WPoStChallengeWindow = miner0.WPoStChallengeWindow +var WPoStChallengeLookback = miner0.WPoStChallengeLookback +var FaultDeclarationCutoff = miner0.FaultDeclarationCutoff const MinSectorExpiration = miner0.MinSectorExpiration diff --git a/storage/wdpost_changehandler.go b/storage/wdpost_changehandler.go index e65b7a7fc..285995757 100644 --- a/storage/wdpost_changehandler.go +++ b/storage/wdpost_changehandler.go @@ -7,7 +7,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-address" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/go-state-types/dline" "github.com/filecoin-project/lotus/chain/types" @@ -529,5 +529,9 @@ func nextDeadline(currentDeadline *dline.Info) *dline.Info { periodStart = periodStart + miner.WPoStProvingPeriod } - return miner.NewDeadlineInfo(periodStart, newDeadline, currentDeadline.CurrentEpoch) + return NewDeadlineInfo(periodStart, newDeadline, currentDeadline.CurrentEpoch) +} + +func NewDeadlineInfo(periodStart abi.ChainEpoch, deadlineIdx uint64, currEpoch abi.ChainEpoch) *dline.Info { + return dline.NewInfo(periodStart, deadlineIdx, currEpoch, miner.WPoStPeriodDeadlines, miner.WPoStProvingPeriod, miner.WPoStChallengeWindow, miner.WPoStChallengeLookback, miner.FaultDeclarationCutoff) } diff --git a/storage/wdpost_changehandler_test.go b/storage/wdpost_changehandler_test.go index d2a4779e6..6479c0d7e 100644 --- a/storage/wdpost_changehandler_test.go +++ b/storage/wdpost_changehandler_test.go @@ -17,8 +17,8 @@ import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/dline" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/types" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" ) var dummyCid cid.Cid @@ -90,7 +90,7 @@ func (m *mockAPI) getDeadline(currentEpoch abi.ChainEpoch) *dline.Info { close += miner.WPoStChallengeWindow dlIdx++ } - return miner.NewDeadlineInfo(0, dlIdx, currentEpoch) + return NewDeadlineInfo(0, dlIdx, currentEpoch) } func (m *mockAPI) StateMinerProvingDeadline(ctx context.Context, address address.Address, key types.TipSetKey) (*dline.Info, error) { @@ -355,7 +355,7 @@ func TestChangeHandlerDontStartUntilProvingPeriod(t *testing.T) { periodStart := miner.WPoStProvingPeriod dlIdx := uint64(1) currentEpoch := abi.ChainEpoch(10) - di := miner.NewDeadlineInfo(periodStart, dlIdx, currentEpoch) + di := NewDeadlineInfo(periodStart, dlIdx, currentEpoch) mock.setDeadline(di) defer s.ch.shutdown() @@ -375,7 +375,7 @@ func TestChangeHandlerDontStartUntilProvingPeriod(t *testing.T) { // Advance the head to the next proving period's first epoch currentEpoch = periodStart + miner.WPoStChallengeWindow - di = miner.NewDeadlineInfo(periodStart, dlIdx, currentEpoch) + di = NewDeadlineInfo(periodStart, dlIdx, currentEpoch) mock.setDeadline(di) go triggerHeadAdvance(t, s, currentEpoch) diff --git a/storage/wdpost_nextdl_test.go b/storage/wdpost_nextdl_test.go index ad4b1fdeb..4a23bad65 100644 --- a/storage/wdpost_nextdl_test.go +++ b/storage/wdpost_nextdl_test.go @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/require" "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/specs-actors/actors/builtin/miner" + "github.com/filecoin-project/lotus/chain/actors/builtin/miner" ) func TestNextDeadline(t *testing.T) { @@ -14,7 +14,7 @@ func TestNextDeadline(t *testing.T) { deadlineIdx := 0 currentEpoch := abi.ChainEpoch(10) - di := miner.NewDeadlineInfo(periodStart, uint64(deadlineIdx), currentEpoch) + di := NewDeadlineInfo(periodStart, uint64(deadlineIdx), currentEpoch) require.EqualValues(t, 0, di.Index) require.EqualValues(t, 0, di.PeriodStart) require.EqualValues(t, -20, di.Challenge) From bdc782617f1547b1e9631ba34ba8fba917ce767e Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Fri, 25 Sep 2020 11:27:30 -0700 Subject: [PATCH 209/303] return an error when we fail to find a sector when checking sector expiration Returning nil, nil is a footgun. fix: https://github.com/filecoin-project/lotus/issues/3984 --- chain/actors/builtin/miner/v0.go | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/chain/actors/builtin/miner/v0.go b/chain/actors/builtin/miner/v0.go index 9cdfc25bc..f5aa7849d 100644 --- a/chain/actors/builtin/miner/v0.go +++ b/chain/actors/builtin/miner/v0.go @@ -6,6 +6,7 @@ import ( "github.com/libp2p/go-libp2p-core/peer" cbg "github.com/whyrusleeping/cbor-gen" + "golang.org/x/xerrors" "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-bitfield" @@ -96,9 +97,7 @@ func (s *state0) NumLiveSectors() (uint64, error) { // GetSectorExpiration returns the effective expiration of the given sector. // -// If the sector isn't found or has already been terminated, this method returns -// nil and no error. If the sector does not expire early, the Early expiration -// field is 0. +// If the sector does not expire early, the Early expiration field is 0. func (s *state0) GetSectorExpiration(num abi.SectorNumber) (*SectorExpiration, error) { dls, err := s.State.LoadDeadlines(s.store) if err != nil { @@ -161,7 +160,7 @@ func (s *state0) GetSectorExpiration(num abi.SectorNumber) (*SectorExpiration, e return nil, err } if out.Early == 0 && out.OnTime == 0 { - return nil, nil + return nil, xerrors.Errorf("failed to find sector %d", num) } return &out, nil } From ddcbcdea4809eb2e0c153207f9c8d1116d9cd1e8 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Fri, 25 Sep 2020 12:16:35 -0700 Subject: [PATCH 210/303] test sector status on expiring sectors --- api/test/ccupgrade.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/api/test/ccupgrade.go b/api/test/ccupgrade.go index b281f30a0..f58f1ff6e 100644 --- a/api/test/ccupgrade.go +++ b/api/test/ccupgrade.go @@ -94,6 +94,22 @@ func TestCCUpgrade(t *testing.T, b APIBuilder, blocktime time.Duration) { require.Less(t, 50000, int(exp.OnTime)) } + dlInfo, err := client.StateMinerProvingDeadline(ctx, maddr, types.EmptyTSK) + require.NoError(t, err) + + // Sector should expire. + for { + // Wait for the sector to expire. + status, err := miner.SectorsStatus(ctx, CC, true) + require.NoError(t, err) + if status.OnTime == 0 && status.Early == 0 { + break + } + t.Log("waiting for sector to expire") + // wait one deadline per loop. + time.Sleep(time.Duration(dlInfo.WPoStChallengeWindow) * blocktime) + } + fmt.Println("shutting down mining") atomic.AddInt64(&mine, -1) <-done From 60e43ccbb13a88473f91b80cf645758523658ad2 Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Fri, 25 Sep 2020 15:45:27 -0400 Subject: [PATCH 211/303] Add an envvar to set address network version --- build/params_shared_funcs.go | 6 ++++++ build/params_shared_vals.go | 12 +++++++++++ chain/types_test.go | 40 ++++++++++++++++++++++++++++++++++++ go.mod | 2 +- go.sum | 2 ++ 5 files changed, 61 insertions(+), 1 deletion(-) diff --git a/build/params_shared_funcs.go b/build/params_shared_funcs.go index 0e9739914..28567d3d1 100644 --- a/build/params_shared_funcs.go +++ b/build/params_shared_funcs.go @@ -3,6 +3,8 @@ package build import ( "sort" + "github.com/filecoin-project/go-address" + "github.com/libp2p/go-libp2p-core/protocol" "github.com/filecoin-project/go-state-types/abi" @@ -44,3 +46,7 @@ func UseNewestNetwork() bool { } return false } + +func SetAddressNetwork(n address.Network) { + address.CurrentNetwork = n +} diff --git a/build/params_shared_vals.go b/build/params_shared_vals.go index 3ee9f52ec..5dd23de44 100644 --- a/build/params_shared_vals.go +++ b/build/params_shared_vals.go @@ -4,6 +4,9 @@ package build import ( "math/big" + "os" + + "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/network" @@ -60,6 +63,11 @@ const TicketRandomnessLookback = abi.ChainEpoch(1) const WinningPoStSectorSetLookback = abi.ChainEpoch(10) +// ///// +// Address + +const AddressMainnetEnvVar = "_mainnet_" + // ///// // Devnet settings @@ -75,6 +83,10 @@ var InitialRewardBalance *big.Int func init() { InitialRewardBalance = big.NewInt(int64(FilAllocStorageMining)) InitialRewardBalance = InitialRewardBalance.Mul(InitialRewardBalance, big.NewInt(int64(FilecoinPrecision))) + + if os.Getenv("LOTUS_ADDRESS_TYPE") == AddressMainnetEnvVar { + SetAddressNetwork(address.Mainnet) + } } // Sync diff --git a/chain/types_test.go b/chain/types_test.go index 7d68da68d..b47471c9d 100644 --- a/chain/types_test.go +++ b/chain/types_test.go @@ -1,9 +1,12 @@ package chain import ( + "crypto/rand" "encoding/json" "testing" + "github.com/filecoin-project/lotus/build" + "github.com/filecoin-project/go-address" "github.com/filecoin-project/lotus/chain/types" ) @@ -35,3 +38,40 @@ func TestSignedMessageJsonRoundtrip(t *testing.T) { t.Fatal(err) } } + +func TestAddressType(t *testing.T) { + build.SetAddressNetwork(address.Testnet) + addr, err := makeRandomAddress() + if err != nil { + t.Fatal(err) + } + + if string(addr[0]) != address.TestnetPrefix { + t.Fatalf("address should start with %s", address.TestnetPrefix) + } + + build.SetAddressNetwork(address.Mainnet) + addr, err = makeRandomAddress() + if err != nil { + t.Fatal(err) + } + + if string(addr[0]) != address.MainnetPrefix { + t.Fatalf("address should start with %s", address.MainnetPrefix) + } +} + +func makeRandomAddress() (string, error) { + bytes := make([]byte, 32) + _, err := rand.Read(bytes) + if err != nil { + return "", err + } + + addr, err := address.NewActorAddress(bytes) + if err != nil { + return "", err + } + + return addr.String(), nil +} diff --git a/go.mod b/go.mod index ca7e0760d..cfa6bf47f 100644 --- a/go.mod +++ b/go.mod @@ -21,7 +21,7 @@ require ( github.com/elastic/go-sysinfo v1.3.0 github.com/fatih/color v1.8.0 github.com/filecoin-project/filecoin-ffi v0.30.4-0.20200716204036-cddc56607e1d - github.com/filecoin-project/go-address v0.0.3 + github.com/filecoin-project/go-address v0.0.4 github.com/filecoin-project/go-bitfield v0.2.0 github.com/filecoin-project/go-cbor-util v0.0.0-20191219014500-08c40a1e63a2 github.com/filecoin-project/go-crypto v0.0.0-20191218222705-effae4ea9f03 diff --git a/go.sum b/go.sum index 1ca615b59..7e50fc200 100644 --- a/go.sum +++ b/go.sum @@ -214,6 +214,8 @@ github.com/fatih/color v1.8.0/go.mod h1:3l45GVGkyrnYNl9HoIjnp2NnNWvh6hLAqD8yTfGj github.com/fd/go-nat v1.0.0/go.mod h1:BTBu/CKvMmOMUPkKVef1pngt2WFH/lg7E6yQnulfp6E= github.com/filecoin-project/go-address v0.0.3 h1:eVfbdjEbpbzIrbiSa+PiGUY+oDK9HnUn+M1R/ggoHf8= github.com/filecoin-project/go-address v0.0.3/go.mod h1:jr8JxKsYx+lQlQZmF5i2U0Z+cGQ59wMIps/8YW/lDj8= +github.com/filecoin-project/go-address v0.0.4 h1:gSNMv0qWwH16fGQs7ycOUrDjY6YCSsgLUl0I0KLjo8w= +github.com/filecoin-project/go-address v0.0.4/go.mod h1:jr8JxKsYx+lQlQZmF5i2U0Z+cGQ59wMIps/8YW/lDj8= github.com/filecoin-project/go-amt-ipld/v2 v2.1.0 h1:t6qDiuGYYngDqaLc2ZUvdtAg4UNxPeOYaXhBWSNsVaM= github.com/filecoin-project/go-amt-ipld/v2 v2.1.0/go.mod h1:nfFPoGyX0CU9SkXX8EoCcSuHN1XcbN0c6KBh7yvP5fs= github.com/filecoin-project/go-bitfield v0.2.0 h1:gCtLcjskIPtdg4NfN7gQZSQF9yrBQ7mkT0qCJxzGI2Q= From a13d10e42d70018652e9c4926bad9dd155514950 Mon Sep 17 00:00:00 2001 From: Travis Person Date: Fri, 25 Sep 2020 20:08:28 +0000 Subject: [PATCH 212/303] add logging to chain export --- chain/store/store.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/chain/store/store.go b/chain/store/store.go index fce8a650f..1dbf69547 100644 --- a/chain/store/store.go +++ b/chain/store/store.go @@ -15,9 +15,11 @@ import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/filecoin-project/lotus/api" + "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/vm" "github.com/filecoin-project/lotus/journal" bstore "github.com/filecoin-project/lotus/lib/blockstore" @@ -1183,6 +1185,7 @@ func (cs *ChainStore) Export(ctx context.Context, ts *types.TipSet, inclRecentRo } blocksToWalk := ts.Cids() + currentMinHeight := ts.Height() walkChain := func(blk cid.Cid) error { if !seen.Visit(blk) { @@ -1203,6 +1206,13 @@ func (cs *ChainStore) Export(ctx context.Context, ts *types.TipSet, inclRecentRo return xerrors.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 { mcids, err := recurseLinks(cs.bs, walked, b.Messages, []cid.Cid{b.Messages}) @@ -1251,6 +1261,9 @@ func (cs *ChainStore) Export(ctx context.Context, ts *types.TipSet, inclRecentRo return nil } + log.Infow("export started") + exportStart := build.Clock.Now() + for len(blocksToWalk) > 0 { next := blocksToWalk[0] blocksToWalk = blocksToWalk[1:] @@ -1259,6 +1272,8 @@ func (cs *ChainStore) Export(ctx context.Context, ts *types.TipSet, inclRecentRo } } + log.Infow("export finished", "duration", build.Clock.Now().Sub(exportStart).Seconds()) + return nil } From 4eec4a01410c19a5687fec620fca418551ce9803 Mon Sep 17 00:00:00 2001 From: Jakub Sztandera Date: Fri, 25 Sep 2020 23:28:12 +0200 Subject: [PATCH 213/303] Move policy change to seal bench Signed-off-by: Jakub Sztandera --- cmd/lotus-bench/main.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/lotus-bench/main.go b/cmd/lotus-bench/main.go index 2516bfd26..e409dfe5a 100644 --- a/cmd/lotus-bench/main.go +++ b/cmd/lotus-bench/main.go @@ -76,8 +76,6 @@ func main() { log.Info("Starting lotus-bench") - policy.AddSupportedProofTypes(abi.RegisteredSealProof_StackedDrg2KiBV1) - app := &cli.App{ Name: "lotus-bench", Usage: "Benchmark performance of lotus on your hardware", @@ -147,6 +145,8 @@ var sealBenchCmd = &cli.Command{ }, }, Action: func(c *cli.Context) error { + policy.AddSupportedProofTypes(abi.RegisteredSealProof_StackedDrg2KiBV1) + if c.Bool("no-gpu") { err := os.Setenv("BELLMAN_NO_GPU", "1") if err != nil { From d8431ff611be8ae5d47a4b05504e10ffd48c1673 Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Fri, 25 Sep 2020 17:33:25 -0400 Subject: [PATCH 214/303] Fix AddSupportedProofTypes --- chain/actors/policy/policy.go | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/chain/actors/policy/policy.go b/chain/actors/policy/policy.go index eec52e855..b8205177e 100644 --- a/chain/actors/policy/policy.go +++ b/chain/actors/policy/policy.go @@ -22,12 +22,10 @@ func SetSupportedProofTypes(types ...abi.RegisteredSealProof) { // AddSupportedProofTypes sets supported proof types, across all actor versions. // This should only be used for testing. func AddSupportedProofTypes(types ...abi.RegisteredSealProof) { - newTypes := make(map[abi.RegisteredSealProof]struct{}, len(types)) for _, t := range types { - newTypes[t] = struct{}{} + // Set for all miner versions. + miner0.SupportedProofTypes[t] = struct{}{} } - // Set for all miner versions. - miner0.SupportedProofTypes = newTypes } // SetPreCommitChallengeDelay sets the pre-commit challenge delay across all From a5f13a5b31cb555eca3d1e9a63fb69fb93ef5023 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Fri, 25 Sep 2020 14:36:36 -0700 Subject: [PATCH 215/303] Test supported proof types. --- chain/actors/policy/policy_test.go | 36 ++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 chain/actors/policy/policy_test.go diff --git a/chain/actors/policy/policy_test.go b/chain/actors/policy/policy_test.go new file mode 100644 index 000000000..be64362a2 --- /dev/null +++ b/chain/actors/policy/policy_test.go @@ -0,0 +1,36 @@ +package policy + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/filecoin-project/go-state-types/abi" + miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" +) + +func TestSupportedProofTypes(t *testing.T) { + var oldTypes []abi.RegisteredSealProof + for t := range miner0.SupportedProofTypes { + oldTypes = append(oldTypes, t) + } + t.Cleanup(func() { + SetSupportedProofTypes(oldTypes...) + }) + + SetSupportedProofTypes(abi.RegisteredSealProof_StackedDrg2KiBV1) + require.EqualValues(t, + miner0.SupportedProofTypes, + map[abi.RegisteredSealProof]struct{}{ + abi.RegisteredSealProof_StackedDrg2KiBV1: {}, + }, + ) + AddSupportedProofTypes(abi.RegisteredSealProof_StackedDrg8MiBV1) + require.EqualValues(t, + miner0.SupportedProofTypes, + map[abi.RegisteredSealProof]struct{}{ + abi.RegisteredSealProof_StackedDrg2KiBV1: {}, + abi.RegisteredSealProof_StackedDrg8MiBV1: {}, + }, + ) +} From 8545c08f30bdb25add71604f5f6b5f12ed862966 Mon Sep 17 00:00:00 2001 From: whyrusleeping Date: Fri, 25 Sep 2020 23:47:59 -0700 Subject: [PATCH 216/303] add json output to state compute --- cli/state.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/cli/state.go b/cli/state.go index d96c93c54..3d37e6fb7 100644 --- a/cli/state.go +++ b/cli/state.go @@ -818,6 +818,10 @@ var stateComputeStateCmd = &cli.Command{ Name: "html", Usage: "generate html report", }, + &cli.BoolFlag{ + Name: "json", + Usage: "generate json output", + }, }, Action: func(cctx *cli.Context) error { api, closer, err := GetFullNodeAPI(cctx) @@ -862,6 +866,15 @@ var stateComputeStateCmd = &cli.Command{ return err } + if cctx.Bool("json") { + out, err := json.Marshal(stout) + if err != nil { + return err + } + fmt.Println(string(out)) + return nil + } + if cctx.Bool("html") { codeCache := map[address.Address]cid.Cid{} getCode := func(addr address.Address) (cid.Cid, error) { From ef28ebb14a9e92833d6eb9cfab5f6f59279e516a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Thu, 24 Sep 2020 23:30:11 +0200 Subject: [PATCH 217/303] Ignition upgrades, much excite. --- build/params_2k.go | 2 + build/params_shared_vals.go | 6 +- build/params_testnet.go | 8 + chain/actors/builtin/builtin.go | 2 +- chain/stmgr/forks.go | 377 +++++++++++++++++++++++++++++--- chain/stmgr/forks_test.go | 18 +- chain/stmgr/stmgr.go | 194 +++++++++++++--- chain/stmgr/utils.go | 20 +- cli/state.go | 24 +- cmd/lotus-shed/balances.go | 138 ++++++++++++ go.mod | 2 +- go.sum | 4 +- node/modules/chain.go | 5 + node/modules/storageminer.go | 3 + storage/wdpost_run.go | 4 + 15 files changed, 708 insertions(+), 99 deletions(-) diff --git a/build/params_2k.go b/build/params_2k.go index 3edd0fb82..3682f7be1 100644 --- a/build/params_2k.go +++ b/build/params_2k.go @@ -12,6 +12,8 @@ const UpgradeBreezeHeight = -1 const BreezeGasTampingDuration = 0 const UpgradeSmokeHeight = -1 +const UpgradeIgnitionHeight = -2 +const UpgradeLiftoffHeight = -3 var DrandSchedule = map[abi.ChainEpoch]DrandEnum{ 0: DrandMainnet, diff --git a/build/params_shared_vals.go b/build/params_shared_vals.go index 3ee9f52ec..95c347281 100644 --- a/build/params_shared_vals.go +++ b/build/params_shared_vals.go @@ -22,8 +22,8 @@ const UnixfsLinksPerLevel = 1024 // Consensus / Network const AllowableClockDriftSecs = uint64(1) -const NewestNetworkVersion = network.Version2 -const ActorUpgradeNetworkVersion = network.Version3 +const NewestNetworkVersion = network.Version3 +const ActorUpgradeNetworkVersion = network.Version4 // Epochs const ForkLengthThreshold = Finality @@ -63,6 +63,8 @@ const WinningPoStSectorSetLookback = abi.ChainEpoch(10) // ///// // Devnet settings +var Devnet = true + const FilBase = uint64(2_000_000_000) const FilAllocStorageMining = uint64(1_100_000_000) diff --git a/build/params_testnet.go b/build/params_testnet.go index 13d2ff62e..960f3a9b6 100644 --- a/build/params_testnet.go +++ b/build/params_testnet.go @@ -21,12 +21,20 @@ const BreezeGasTampingDuration = 120 const UpgradeSmokeHeight = 51000 +const UpgradeIgnitionHeight = 94000 + +// This signals our tentative epoch for mainnet launch. Can make it later, but not earlier. +// Miners, clients, developers, custodians all need time to prepare. +// We still have upgrades and state changes to do, but can happen after signaling timing here. +const UpgradeLiftoffHeight = 148888 + func init() { policy.SetConsensusMinerMinPower(abi.NewStoragePower(10 << 40)) policy.SetSupportedProofTypes( abi.RegisteredSealProof_StackedDrg32GiBV1, abi.RegisteredSealProof_StackedDrg64GiBV1, ) + Devnet = false } const BlockDelaySecs = uint64(builtin0.EpochDurationSeconds) diff --git a/chain/actors/builtin/builtin.go b/chain/actors/builtin/builtin.go index 4079e694a..a85b4da65 100644 --- a/chain/actors/builtin/builtin.go +++ b/chain/actors/builtin/builtin.go @@ -21,7 +21,7 @@ const ( // Converts a network version into a specs-actors version. func VersionForNetwork(version network.Version) Version { switch version { - case network.Version0, network.Version1, network.Version2: + case network.Version0, network.Version1, network.Version2, network.Version3: return Version0 default: panic(fmt.Sprintf("unsupported network version %d", version)) diff --git a/chain/stmgr/forks.go b/chain/stmgr/forks.go index f9418c4d8..872c70b1e 100644 --- a/chain/stmgr/forks.go +++ b/chain/stmgr/forks.go @@ -1,44 +1,63 @@ package stmgr import ( + "bytes" "context" + "encoding/binary" + "math" + + multisig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig" + + "github.com/filecoin-project/lotus/chain/actors/builtin/multisig" + + "github.com/filecoin-project/lotus/chain/state" + + "github.com/filecoin-project/specs-actors/actors/migration/nv3" + + "github.com/ipfs/go-cid" "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" + init0 "github.com/filecoin-project/specs-actors/actors/builtin/init" miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" adt0 "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/types" + "github.com/filecoin-project/lotus/chain/vm" cbor "github.com/ipfs/go-ipld-cbor" "golang.org/x/xerrors" ) -var ForksAtHeight = map[abi.ChainEpoch]func(context.Context, *StateManager, types.StateTree, *types.TipSet) error{ - build.UpgradeBreezeHeight: UpgradeFaucetBurnRecovery, +var ForksAtHeight = map[abi.ChainEpoch]func(context.Context, *StateManager, ExecCallback, cid.Cid, *types.TipSet) (cid.Cid, error){ + build.UpgradeBreezeHeight: UpgradeFaucetBurnRecovery, + build.UpgradeIgnitionHeight: UpgradeIgnition, + build.UpgradeLiftoffHeight: UpgradeLiftoff, } -func (sm *StateManager) handleStateForks(ctx context.Context, st types.StateTree, height abi.ChainEpoch, ts *types.TipSet) (err error) { +func (sm *StateManager) handleStateForks(ctx context.Context, root cid.Cid, height abi.ChainEpoch, cb ExecCallback, ts *types.TipSet) (cid.Cid, error) { + retCid := root + var err error f, ok := ForksAtHeight[height] if ok { - err := f(ctx, sm, st, ts) + retCid, err = f(ctx, sm, cb, root, ts) if err != nil { - return err + return cid.Undef, err } } - return nil + return retCid, nil } type forEachTree interface { ForEach(func(address.Address, *types.Actor) error) error } -func doTransfer(tree types.StateTree, from, to address.Address, amt abi.TokenAmount) error { +func doTransfer(cb ExecCallback, tree types.StateTree, from, to address.Address, amt abi.TokenAmount) error { fromAct, err := tree.GetActor(from) if err != nil { return xerrors.Errorf("failed to get 'from' actor for transfer: %w", err) @@ -64,10 +83,43 @@ func doTransfer(tree types.StateTree, from, to address.Address, amt abi.TokenAmo return xerrors.Errorf("failed to persist to actor: %w", err) } + if cb != nil { + // record the transfer in execution traces + + fakeMsg := &types.Message{ + From: from, + To: to, + Value: amt, + Nonce: math.MaxUint64, + } + fakeRct := &types.MessageReceipt{ + ExitCode: 0, + Return: nil, + GasUsed: 0, + } + + if err := cb(fakeMsg.Cid(), fakeMsg, &vm.ApplyRet{ + MessageReceipt: *fakeRct, + ActorErr: nil, + ExecutionTrace: types.ExecutionTrace{ + Msg: fakeMsg, + MsgRct: fakeRct, + Error: "", + Duration: 0, + GasCharges: nil, + Subcalls: nil, + }, + Duration: 0, + GasCosts: vm.ZeroGasOutputs(), + }); err != nil { + return xerrors.Errorf("recording transfer: %w", err) + } + } + return nil } -func UpgradeFaucetBurnRecovery(ctx context.Context, sm *StateManager, tree types.StateTree, ts *types.TipSet) error { +func UpgradeFaucetBurnRecovery(ctx context.Context, sm *StateManager, cb ExecCallback, root cid.Cid, ts *types.TipSet) (cid.Cid, error) { // Some initial parameters FundsForMiners := types.FromFil(1_000_000) LookbackEpoch := abi.ChainEpoch(32000) @@ -94,22 +146,22 @@ func UpgradeFaucetBurnRecovery(ctx context.Context, sm *StateManager, tree types // Grab lookback state for account checks lbts, err := sm.ChainStore().GetTipsetByHeight(ctx, LookbackEpoch, ts, false) if err != nil { - return xerrors.Errorf("failed to get tipset at lookback height: %w", err) + return cid.Undef, xerrors.Errorf("failed to get tipset at lookback height: %w", err) } lbtree, err := sm.ParentState(lbts) if err != nil { - return xerrors.Errorf("loading state tree failed: %w", err) + return cid.Undef, xerrors.Errorf("loading state tree failed: %w", err) } ReserveAddress, err := address.NewFromString("t090") if err != nil { - return xerrors.Errorf("failed to parse reserve address: %w", err) + return cid.Undef, xerrors.Errorf("failed to parse reserve address: %w", err) } - fetree, ok := tree.(forEachTree) - if !ok { - return xerrors.Errorf("fork transition state tree doesnt support ForEach (%T)", tree) + tree, err := sm.StateTree(root) + if err != nil { + return cid.Undef, xerrors.Errorf("getting state tree: %w", err) } type transfer struct { @@ -121,7 +173,7 @@ func UpgradeFaucetBurnRecovery(ctx context.Context, sm *StateManager, tree types var transfers []transfer // Take all excess funds away, put them into the reserve account - err = fetree.ForEach(func(addr address.Address, act *types.Actor) error { + 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) @@ -163,13 +215,13 @@ func UpgradeFaucetBurnRecovery(ctx context.Context, sm *StateManager, tree types return nil }) if err != nil { - return xerrors.Errorf("foreach over state tree failed: %w", err) + return cid.Undef, xerrors.Errorf("foreach over state tree failed: %w", err) } // Execute transfers from previous step for _, t := range transfers { - if err := doTransfer(tree, t.From, t.To, t.Amt); err != nil { - return xerrors.Errorf("transfer %s %s->%s failed: %w", t.Amt, t.From, t.To, err) + if err := doTransfer(cb, tree, t.From, t.To, t.Amt); err != nil { + return cid.Undef, xerrors.Errorf("transfer %s %s->%s failed: %w", t.Amt, t.From, t.To, err) } } @@ -177,19 +229,19 @@ func UpgradeFaucetBurnRecovery(ctx context.Context, sm *StateManager, tree types var ps power0.State powAct, err := tree.GetActor(builtin0.StoragePowerActorAddr) if err != nil { - return xerrors.Errorf("failed to load power actor: %w", err) + return cid.Undef, xerrors.Errorf("failed to load power actor: %w", err) } cst := cbor.NewCborStore(sm.ChainStore().Blockstore()) if err := cst.Get(ctx, powAct.Head, &ps); err != nil { - return xerrors.Errorf("failed to get power actor state: %w", err) + return cid.Undef, xerrors.Errorf("failed to get power actor state: %w", err) } totalPower := ps.TotalBytesCommitted var transfersBack []transfer // Now, we return some funds to places where they are needed - err = fetree.ForEach(func(addr address.Address, act *types.Actor) error { + err = tree.ForEach(func(addr address.Address, act *types.Actor) error { lbact, err := lbtree.GetActor(addr) if err != nil { if !xerrors.Is(err, types.ErrActorNotFound) { @@ -267,53 +319,310 @@ func UpgradeFaucetBurnRecovery(ctx context.Context, sm *StateManager, tree types return nil }) if err != nil { - return xerrors.Errorf("foreach over state tree failed: %w", err) + return cid.Undef, xerrors.Errorf("foreach over state tree failed: %w", err) } for _, t := range transfersBack { - if err := doTransfer(tree, t.From, t.To, t.Amt); err != nil { - return xerrors.Errorf("transfer %s %s->%s failed: %w", t.Amt, t.From, t.To, err) + if err := doTransfer(cb, tree, t.From, t.To, t.Amt); err != nil { + return cid.Undef, xerrors.Errorf("transfer %s %s->%s failed: %w", t.Amt, t.From, t.To, err) } } // transfer all burnt funds back to the reserve account burntAct, err := tree.GetActor(builtin0.BurntFundsActorAddr) if err != nil { - return xerrors.Errorf("failed to load burnt funds actor: %w", err) + return cid.Undef, xerrors.Errorf("failed to load burnt funds actor: %w", err) } - if err := doTransfer(tree, builtin0.BurntFundsActorAddr, ReserveAddress, burntAct.Balance); err != nil { - return xerrors.Errorf("failed to unburn funds: %w", err) + if err := doTransfer(cb, tree, builtin0.BurntFundsActorAddr, ReserveAddress, burntAct.Balance); err != nil { + return cid.Undef, xerrors.Errorf("failed to unburn funds: %w", err) } // Top up the reimbursement service reimbAddr, err := address.NewFromString("t0111") if err != nil { - return xerrors.Errorf("failed to parse reimbursement service address") + return cid.Undef, xerrors.Errorf("failed to parse reimbursement service address") } reimb, err := tree.GetActor(reimbAddr) if err != nil { - return xerrors.Errorf("failed to load reimbursement account actor: %w", err) + return cid.Undef, xerrors.Errorf("failed to load reimbursement account actor: %w", err) } difference := types.BigSub(DesiredReimbursementBalance, reimb.Balance) - if err := doTransfer(tree, ReserveAddress, reimbAddr, difference); err != nil { - return xerrors.Errorf("failed to top up reimbursement account: %w", err) + if err := doTransfer(cb, tree, ReserveAddress, reimbAddr, difference); err != nil { + return cid.Undef, xerrors.Errorf("failed to top up reimbursement account: %w", err) } // Now, a final sanity check to make sure the balances all check out total := abi.NewTokenAmount(0) - err = fetree.ForEach(func(addr address.Address, act *types.Actor) error { + err = tree.ForEach(func(addr address.Address, act *types.Actor) error { total = types.BigAdd(total, act.Balance) return nil }) if err != nil { - return xerrors.Errorf("checking final state balance failed: %w", err) + return cid.Undef, xerrors.Errorf("checking final state balance failed: %w", err) } exp := types.FromFil(build.FilBase) if !exp.Equals(total) { - return xerrors.Errorf("resultant state tree account balance was not correct: %s", total) + return cid.Undef, xerrors.Errorf("resultant state tree account balance was not correct: %s", total) + } + + return tree.Flush(ctx) +} + +func UpgradeIgnition(ctx context.Context, sm *StateManager, cb ExecCallback, root cid.Cid, ts *types.TipSet) (cid.Cid, error) { + store := sm.cs.Store(ctx) + + nst, err := nv3.MigrateStateTree(ctx, store, root, build.UpgradeIgnitionHeight) + if err != nil { + return cid.Undef, xerrors.Errorf("migrating actors state: %w", err) + } + + tree, err := sm.StateTree(nst) + if err != nil { + return cid.Undef, xerrors.Errorf("getting state tree: %w", err) + } + + err = setNetworkName(ctx, store, tree, "ignition") + if err != nil { + return cid.Undef, xerrors.Errorf("setting network name: %w", err) + } + + split1, err := address.NewFromString("t0115") + if err != nil { + return cid.Undef, xerrors.Errorf("first split address: %w", err) + } + + split2, err := address.NewFromString("t0116") + if err != nil { + return cid.Undef, xerrors.Errorf("second split address: %w", err) + } + + err = resetGenesisMsigs(ctx, sm, store, tree) + if err != nil { + return cid.Undef, xerrors.Errorf("resetting genesis msig start epochs: %w", err) + } + + err = splitGenesisMultisig(ctx, cb, split1, store, tree, 50) + if err != nil { + return cid.Undef, xerrors.Errorf("splitting first msig: %w", err) + } + + err = splitGenesisMultisig(ctx, cb, split2, store, tree, 50) + if err != nil { + return cid.Undef, xerrors.Errorf("splitting second msig: %w", err) + } + + err = nv3.CheckStateTree(ctx, store, nst, build.UpgradeIgnitionHeight, builtin0.TotalFilecoin) + if err != nil { + return cid.Undef, xerrors.Errorf("sanity check after ignition upgrade failed: %w", err) + } + + return tree.Flush(ctx) +} + +func UpgradeLiftoff(ctx context.Context, sm *StateManager, cb ExecCallback, root cid.Cid, ts *types.TipSet) (cid.Cid, error) { + tree, err := sm.StateTree(root) + if err != nil { + return cid.Undef, xerrors.Errorf("getting state tree: %w", err) + } + + err = setNetworkName(ctx, sm.cs.Store(ctx), tree, "mainnet") + if err != nil { + return cid.Undef, xerrors.Errorf("setting network name: %w", err) + } + + return tree.Flush(ctx) +} + +func setNetworkName(ctx context.Context, store adt0.Store, tree *state.StateTree, name string) error { + ia, err := tree.GetActor(builtin0.InitActorAddr) + if err != nil { + return xerrors.Errorf("getting init actor: %w", err) + } + + var initState init0.State + if err := store.Get(ctx, ia.Head, &initState); err != nil { + return xerrors.Errorf("reading init state: %w", err) + } + + initState.NetworkName = name + + ia.Head, err = store.Put(ctx, &initState) + if err != nil { + return xerrors.Errorf("writing new init state: %w", err) + } + + if err := tree.SetActor(builtin0.InitActorAddr, ia); err != nil { + return xerrors.Errorf("setting init actor: %w", err) + } + + return nil +} + +func splitGenesisMultisig(ctx context.Context, cb ExecCallback, addr address.Address, store adt0.Store, tree *state.StateTree, portions uint64) error { + if portions < 1 { + return xerrors.Errorf("cannot split into 0 portions") + } + + mact, err := tree.GetActor(addr) + if err != nil { + return xerrors.Errorf("getting msig actor: %w", err) + } + + mst, err := multisig.Load(store, mact) + if err != nil { + return xerrors.Errorf("getting msig state: %w", err) + } + + signers, err := mst.Signers() + if err != nil { + return xerrors.Errorf("getting msig signers: %w", err) + } + + thresh, err := mst.Threshold() + if err != nil { + return xerrors.Errorf("getting msig threshold: %w", err) + } + + ibal, err := mst.InitialBalance() + if err != nil { + return xerrors.Errorf("getting msig initial balance: %w", err) + } + + se, err := mst.StartEpoch() + if err != nil { + return xerrors.Errorf("getting msig start epoch: %w", err) + } + + ud, err := mst.UnlockDuration() + if err != nil { + return xerrors.Errorf("getting msig unlock duration: %w", err) + } + + pending, err := adt0.MakeEmptyMap(store).Root() + if err != nil { + return xerrors.Errorf("failed to create empty map: %w", err) + } + + newIbal := big.Div(ibal, types.NewInt(portions)) + newState := &multisig0.State{ + Signers: signers, + NumApprovalsThreshold: thresh, + NextTxnID: 0, + InitialBalance: newIbal, + StartEpoch: se, + UnlockDuration: ud, + PendingTxns: pending, + } + + scid, err := store.Put(ctx, newState) + if err != nil { + return xerrors.Errorf("storing new state: %w", err) + } + + newActor := types.Actor{ + Code: builtin0.MultisigActorCodeID, + Head: scid, + Nonce: 0, + Balance: big.Zero(), + } + + i := uint64(0) + for i < portions { + keyAddr, err := makeKeyAddr(addr, i) + if err != nil { + return xerrors.Errorf("creating key address: %w", err) + } + + idAddr, err := tree.RegisterNewAddress(keyAddr) + if err != nil { + return xerrors.Errorf("registering new address: %w", err) + } + + err = tree.SetActor(idAddr, &newActor) + if err != nil { + return xerrors.Errorf("setting new msig actor state: %w", err) + } + + if err := doTransfer(cb, tree, addr, idAddr, newIbal); err != nil { + return xerrors.Errorf("transferring split msig balance: %w", err) + } + + i++ + } + + return nil +} + +func makeKeyAddr(splitAddr address.Address, count uint64) (address.Address, error) { + var b bytes.Buffer + if err := splitAddr.MarshalCBOR(&b); err != nil { + return address.Undef, xerrors.Errorf("marshalling split address: %w", err) + } + + if err := binary.Write(&b, binary.BigEndian, count); err != nil { + return address.Undef, xerrors.Errorf("writing count into a buffer: %w", err) + } + + if err := binary.Write(&b, binary.BigEndian, []byte("Ignition upgrade")); err != nil { + return address.Undef, xerrors.Errorf("writing fork name into a buffer: %w", err) + } + + addr, err := address.NewActorAddress(b.Bytes()) + if err != nil { + return address.Undef, xerrors.Errorf("create actor address: %w", err) + } + + return addr, nil +} + +func resetGenesisMsigs(ctx context.Context, sm *StateManager, store adt0.Store, tree *state.StateTree) error { + gb, err := sm.cs.GetGenesis() + if err != nil { + return xerrors.Errorf("getting genesis block: %w", err) + } + + gts, err := types.NewTipSet([]*types.BlockHeader{gb}) + if err != nil { + return xerrors.Errorf("getting genesis tipset: %w", err) + } + + cst := cbor.NewCborStore(sm.cs.Blockstore()) + genesisTree, err := state.LoadStateTree(cst, gts.ParentState()) + if err != nil { + return xerrors.Errorf("loading state tree: %w", err) + } + + err = genesisTree.ForEach(func(addr address.Address, genesisActor *types.Actor) error { + if genesisActor.Code == builtin0.MultisigActorCodeID { + currActor, err := tree.GetActor(addr) + if err != nil { + return xerrors.Errorf("loading actor: %w", err) + } + + var currState multisig0.State + if err := store.Get(ctx, currActor.Head, &currState); err != nil { + return xerrors.Errorf("reading multisig state: %w", err) + } + + currState.StartEpoch = build.UpgradeLiftoffHeight + + currActor.Head, err = store.Put(ctx, &currState) + if err != nil { + return xerrors.Errorf("writing new multisig state: %w", err) + } + + if err := tree.SetActor(addr, currActor); err != nil { + return xerrors.Errorf("setting multisig actor: %w", err) + } + } + return nil + }) + + if err != nil { + return xerrors.Errorf("iterating over genesis actors: %w", err) } return nil diff --git a/chain/stmgr/forks_test.go b/chain/stmgr/forks_test.go index 516058a81..a3423ccdd 100644 --- a/chain/stmgr/forks_test.go +++ b/chain/stmgr/forks_test.go @@ -25,6 +25,7 @@ import ( _ "github.com/filecoin-project/lotus/lib/sigs/bls" _ "github.com/filecoin-project/lotus/lib/sigs/secp" + "github.com/ipfs/go-cid" cbor "github.com/ipfs/go-ipld-cbor" logging "github.com/ipfs/go-log" cbg "github.com/whyrusleeping/cbor-gen" @@ -114,33 +115,38 @@ func TestForkHeightTriggers(t *testing.T) { t.Fatal(err) } - stmgr.ForksAtHeight[testForkHeight] = func(ctx context.Context, sm *StateManager, st types.StateTree, ts *types.TipSet) error { + stmgr.ForksAtHeight[testForkHeight] = func(ctx context.Context, sm *StateManager, cb ExecCallback, root cid.Cid, ts *types.TipSet) (cid.Cid, error) { cst := cbor.NewCborStore(sm.ChainStore().Blockstore()) + st, err := sm.StateTree(root) + if err != nil { + return cid.Undef, xerrors.Errorf("getting state tree: %w", err) + } + act, err := st.GetActor(taddr) if err != nil { - return err + return cid.Undef, err } var tas testActorState if err := cst.Get(ctx, act.Head, &tas); err != nil { - return xerrors.Errorf("in fork handler, failed to run get: %w", err) + return cid.Undef, xerrors.Errorf("in fork handler, failed to run get: %w", err) } tas.HasUpgraded = 55 ns, err := cst.Put(ctx, &tas) if err != nil { - return err + return cid.Undef, err } act.Head = ns if err := st.SetActor(taddr, act); err != nil { - return err + return cid.Undef, err } - return nil + return st.Flush(ctx) } inv.Register(builtin.PaymentChannelActorCodeID, &testActor{}, &testActorState{}) diff --git a/chain/stmgr/stmgr.go b/chain/stmgr/stmgr.go index eaf9215db..e800ce665 100644 --- a/chain/stmgr/stmgr.go +++ b/chain/stmgr/stmgr.go @@ -41,12 +41,13 @@ var log = logging.Logger("statemgr") type StateManager struct { cs *store.ChainStore - stCache map[string][]cid.Cid - compWait map[string]chan struct{} - stlk sync.Mutex - genesisMsigLk sync.Mutex - newVM func(context.Context, *vm.VMOpts) (*vm.VM, error) - genInfo *genesisInfo + stCache map[string][]cid.Cid + compWait map[string]chan struct{} + stlk sync.Mutex + genesisMsigLk sync.Mutex + newVM func(context.Context, *vm.VMOpts) (*vm.VM, error) + preIgnitionGenInfos *genesisInfo + postIgnitionGenInfos *genesisInfo } func NewStateManager(cs *store.ChainStore) *StateManager { @@ -123,9 +124,8 @@ func (sm *StateManager) TipSetState(ctx context.Context, ts *types.TipSet) (st c return st, rec, nil } -func (sm *StateManager) ExecutionTrace(ctx context.Context, ts *types.TipSet) (cid.Cid, []*api.InvocResult, error) { - var trace []*api.InvocResult - st, _, err := sm.computeTipSetState(ctx, ts, func(mcid cid.Cid, msg *types.Message, ret *vm.ApplyRet) error { +func traceFunc(trace *[]*api.InvocResult) func(mcid cid.Cid, msg *types.Message, ret *vm.ApplyRet) error { + return func(mcid cid.Cid, msg *types.Message, ret *vm.ApplyRet) error { ir := &api.InvocResult{ Msg: msg, MsgRct: &ret.MessageReceipt, @@ -135,9 +135,14 @@ func (sm *StateManager) ExecutionTrace(ctx context.Context, ts *types.TipSet) (c if ret.ActorErr != nil { ir.Error = ret.ActorErr.Error() } - trace = append(trace, ir) + *trace = append(*trace, ir) return nil - }) + } +} + +func (sm *StateManager) ExecutionTrace(ctx context.Context, ts *types.TipSet) (cid.Cid, []*api.InvocResult, error) { + var trace []*api.InvocResult + st, _, err := sm.computeTipSetState(ctx, ts, traceFunc(&trace)) if err != nil { return cid.Undef, nil, err } @@ -149,20 +154,24 @@ type ExecCallback func(cid.Cid, *types.Message, *vm.ApplyRet) error func (sm *StateManager) ApplyBlocks(ctx context.Context, parentEpoch abi.ChainEpoch, pstate cid.Cid, bms []store.BlockMessages, epoch abi.ChainEpoch, r vm.Rand, cb ExecCallback, baseFee abi.TokenAmount, ts *types.TipSet) (cid.Cid, cid.Cid, error) { - vmopt := &vm.VMOpts{ - StateBase: pstate, - Epoch: epoch, - Rand: r, - Bstore: sm.cs.Blockstore(), - Syscalls: sm.cs.VMSys(), - CircSupplyCalc: sm.GetCirculatingSupply, - NtwkVersion: sm.GetNtwkVersion, - BaseFee: baseFee, + makeVmWithBaseState := func(base cid.Cid) (*vm.VM, error) { + vmopt := &vm.VMOpts{ + StateBase: base, + Epoch: epoch, + Rand: r, + Bstore: sm.cs.Blockstore(), + Syscalls: sm.cs.VMSys(), + CircSupplyCalc: sm.GetCirculatingSupply, + NtwkVersion: sm.GetNtwkVersion, + BaseFee: baseFee, + } + + return sm.newVM(ctx, vmopt) } - vmi, err := sm.newVM(ctx, vmopt) + vmi, err := makeVmWithBaseState(pstate) if err != nil { - return cid.Undef, cid.Undef, xerrors.Errorf("instantiating VM failed: %w", err) + return cid.Undef, cid.Undef, xerrors.Errorf("making vm: %w", err) } runCron := func() error { @@ -202,19 +211,32 @@ func (sm *StateManager) ApplyBlocks(ctx context.Context, parentEpoch abi.ChainEp for i := parentEpoch; i < epoch; i++ { // handle state forks // XXX: The state tree - err = sm.handleStateForks(ctx, vmi.StateTree(), i, ts) + newState, err := sm.handleStateForks(ctx, pstate, i, cb, ts) if err != nil { return cid.Undef, cid.Undef, xerrors.Errorf("error handling state forks: %w", err) } + if pstate != newState { + vmi, err = makeVmWithBaseState(newState) + if err != nil { + return cid.Undef, cid.Undef, xerrors.Errorf("making vm: %w", err) + } + } + if i > parentEpoch { // run cron for null rounds if any if err := runCron(); err != nil { return cid.Cid{}, cid.Cid{}, err } + + newState, err = vmi.Flush(ctx) + if err != nil { + return cid.Undef, cid.Undef, xerrors.Errorf("flushing vm: %w", err) + } } vmi.SetBlockHeight(i + 1) + pstate = newState } var receipts []cbg.CBORMarshaler @@ -904,7 +926,7 @@ func (sm *StateManager) setupGenesisActors(ctx context.Context) error { gi.genesisMsigs = append(gi.genesisMsigs, ns) } - sm.genInfo = &gi + sm.preIgnitionGenInfos = &gi return nil } @@ -912,7 +934,7 @@ func (sm *StateManager) setupGenesisActors(ctx context.Context) error { // sets up information about the actors in the genesis state // For testnet we use a hardcoded set of multisig states, instead of what's actually in the genesis multisigs // We also do not consider ANY account actors (including the faucet) -func (sm *StateManager) setupGenesisActorsTestnet(ctx context.Context) error { +func (sm *StateManager) setupPreIgnitionGenesisActorsTestnet(ctx context.Context) error { gi := genesisInfo{} @@ -981,7 +1003,87 @@ func (sm *StateManager) setupGenesisActorsTestnet(ctx context.Context) error { gi.genesisMsigs = append(gi.genesisMsigs, ns) } - sm.genInfo = &gi + sm.preIgnitionGenInfos = &gi + + return nil +} + +// sets up information about the actors in the genesis state, post the ignition fork +func (sm *StateManager) setupPostIgnitionGenesisActors(ctx context.Context) error { + + gi := genesisInfo{} + + gb, err := sm.cs.GetGenesis() + if err != nil { + return xerrors.Errorf("getting genesis block: %w", err) + } + + gts, err := types.NewTipSet([]*types.BlockHeader{gb}) + if err != nil { + return xerrors.Errorf("getting genesis tipset: %w", err) + } + + st, _, err := sm.TipSetState(ctx, gts) + if err != nil { + return xerrors.Errorf("getting genesis tipset state: %w", err) + } + + cst := cbor.NewCborStore(sm.cs.Blockstore()) + sTree, err := state.LoadStateTree(cst, st) + if err != nil { + return xerrors.Errorf("loading state tree: %w", err) + } + + // Unnecessary, should be removed + gi.genesisMarketFunds, err = getFilMarketLocked(ctx, sTree) + if err != nil { + return xerrors.Errorf("setting up genesis market funds: %w", err) + } + + // Unnecessary, should be removed + gi.genesisPledge, err = getFilPowerLocked(ctx, sTree) + if err != nil { + return xerrors.Errorf("setting up genesis pledge: %w", err) + } + + totalsByEpoch := make(map[abi.ChainEpoch]abi.TokenAmount) + + // 6 months + sixMonths := abi.ChainEpoch(183 * builtin0.EpochsInDay) + totalsByEpoch[sixMonths] = big.NewInt(49_929_341) + totalsByEpoch[sixMonths] = big.Add(totalsByEpoch[sixMonths], big.NewInt(32_787_700)) + + // 1 year + oneYear := abi.ChainEpoch(365 * builtin0.EpochsInDay) + totalsByEpoch[oneYear] = big.NewInt(22_421_712) + + // 2 years + twoYears := abi.ChainEpoch(2 * 365 * builtin0.EpochsInDay) + totalsByEpoch[twoYears] = big.NewInt(7_223_364) + + // 3 years + threeYears := abi.ChainEpoch(3 * 365 * builtin0.EpochsInDay) + totalsByEpoch[threeYears] = big.NewInt(87_637_883) + + // 6 years + sixYears := abi.ChainEpoch(6 * 365 * builtin0.EpochsInDay) + totalsByEpoch[sixYears] = big.NewInt(100_000_000) + totalsByEpoch[sixYears] = big.Add(totalsByEpoch[sixYears], big.NewInt(300_000_000)) + + gi.genesisMsigs = make([]msig0.State, 0, len(totalsByEpoch)) + for k, v := range totalsByEpoch { + ns := msig0.State{ + // In the pre-ignition logic, we incorrectly set this value in Fil, not attoFil, an off-by-10^18 error + InitialBalance: big.Mul(v, big.NewInt(int64(build.FilecoinPrecision))), + UnlockDuration: k, + PendingTxns: cid.Undef, + // In the pre-ignition logic, the start epoch was 0. This changes in the fork logic of the Ignition upgrade itself. + StartEpoch: build.UpgradeLiftoffHeight, + } + gi.genesisMsigs = append(gi.genesisMsigs, ns) + } + + sm.postIgnitionGenInfos = &gi return nil } @@ -991,13 +1093,23 @@ func (sm *StateManager) setupGenesisActorsTestnet(ctx context.Context) error { // - For Accounts, it counts max(currentBalance - genesisBalance, 0). func (sm *StateManager) GetFilVested(ctx context.Context, height abi.ChainEpoch, st *state.StateTree) (abi.TokenAmount, error) { vf := big.Zero() - for _, v := range sm.genInfo.genesisMsigs { - au := big.Sub(v.InitialBalance, v.AmountLocked(height)) - vf = big.Add(vf, au) + if height <= build.UpgradeIgnitionHeight { + for _, v := range sm.preIgnitionGenInfos.genesisMsigs { + au := big.Sub(v.InitialBalance, v.AmountLocked(height)) + vf = big.Add(vf, au) + } + } else { + for _, v := range sm.postIgnitionGenInfos.genesisMsigs { + // In the pre-ignition logic, we simply called AmountLocked(height), assuming startEpoch was 0. + // The start epoch changed in the Ignition upgrade. + au := big.Sub(v.InitialBalance, v.AmountLocked(height-v.StartEpoch)) + vf = big.Add(vf, au) + } } // there should not be any such accounts in testnet (and also none in mainnet?) - for _, v := range sm.genInfo.genesisActors { + // continue to use preIgnitionGenInfos, nothing changed at the Ignition epoch + for _, v := range sm.preIgnitionGenInfos.genesisActors { act, err := st.GetActor(v.addr) if err != nil { return big.Zero(), xerrors.Errorf("failed to get actor: %w", err) @@ -1009,8 +1121,10 @@ func (sm *StateManager) GetFilVested(ctx context.Context, height abi.ChainEpoch, } } - vf = big.Add(vf, sm.genInfo.genesisPledge) - vf = big.Add(vf, sm.genInfo.genesisMarketFunds) + // continue to use preIgnitionGenInfos, nothing changed at the Ignition epoch + vf = big.Add(vf, sm.preIgnitionGenInfos.genesisPledge) + // continue to use preIgnitionGenInfos, nothing changed at the Ignition epoch + vf = big.Add(vf, sm.preIgnitionGenInfos.genesisMarketFunds) return vf, nil } @@ -1084,10 +1198,16 @@ func GetFilBurnt(ctx context.Context, st *state.StateTree) (abi.TokenAmount, err func (sm *StateManager) GetCirculatingSupplyDetailed(ctx context.Context, height abi.ChainEpoch, st *state.StateTree) (api.CirculatingSupply, error) { sm.genesisMsigLk.Lock() defer sm.genesisMsigLk.Unlock() - if sm.genInfo == nil { - err := sm.setupGenesisActorsTestnet(ctx) + if sm.preIgnitionGenInfos == nil { + err := sm.setupPreIgnitionGenesisActorsTestnet(ctx) if err != nil { - return api.CirculatingSupply{}, xerrors.Errorf("failed to setup genesis information: %w", err) + return api.CirculatingSupply{}, xerrors.Errorf("failed to setup pre-ignition genesis information: %w", err) + } + } + if sm.postIgnitionGenInfos == nil { + err := sm.setupPostIgnitionGenesisActors(ctx) + if err != nil { + return api.CirculatingSupply{}, xerrors.Errorf("failed to setup post-ignition genesis information: %w", err) } } @@ -1152,6 +1272,10 @@ func (sm *StateManager) GetNtwkVersion(ctx context.Context, height abi.ChainEpoc return network.Version1 } + if height <= build.UpgradeIgnitionHeight { + return network.Version2 + } + return build.NewestNetworkVersion } diff --git a/chain/stmgr/utils.go b/chain/stmgr/utils.go index 3493afca3..58e7f480f 100644 --- a/chain/stmgr/utils.go +++ b/chain/stmgr/utils.go @@ -368,6 +368,16 @@ func ComputeState(ctx context.Context, sm *StateManager, height abi.ChainEpoch, return cid.Undef, nil, err } + for i := ts.Height(); i < height; i++ { + // handle state forks + base, err = sm.handleStateForks(ctx, base, i, traceFunc(&trace), ts) + if err != nil { + return cid.Undef, nil, xerrors.Errorf("error handling state forks: %w", err) + } + + // TODO: should we also run cron here? + } + r := store.NewChainRand(sm.cs, ts.Cids()) vmopt := &vm.VMOpts{ StateBase: base, @@ -384,16 +394,6 @@ func ComputeState(ctx context.Context, sm *StateManager, height abi.ChainEpoch, return cid.Undef, nil, err } - for i := ts.Height(); i < height; i++ { - // handle state forks - err = sm.handleStateForks(ctx, vmi.StateTree(), i, ts) - if err != nil { - return cid.Undef, nil, xerrors.Errorf("error handling state forks: %w", err) - } - - // TODO: should we also run cron here? - } - for i, msg := range msgs { // TODO: Use the signed message length for secp messages ret, err := vmi.ApplyMessage(ctx, msg) diff --git a/cli/state.go b/cli/state.go index d96c93c54..b25a5e4a7 100644 --- a/cli/state.go +++ b/cli/state.go @@ -19,6 +19,7 @@ import ( "github.com/multiformats/go-multiaddr" "github.com/ipfs/go-cid" + cbor "github.com/ipfs/go-ipld-cbor" "github.com/libp2p/go-libp2p-core/peer" "github.com/multiformats/go-multihash" "github.com/urfave/cli/v2" @@ -33,7 +34,9 @@ import ( "github.com/filecoin-project/specs-actors/actors/builtin/exported" "github.com/filecoin-project/lotus/api" + "github.com/filecoin-project/lotus/api/apibstore" "github.com/filecoin-project/lotus/build" + "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/stmgr" "github.com/filecoin-project/lotus/chain/types" ) @@ -834,14 +837,14 @@ var stateComputeStateCmd = &cli.Command{ } h := abi.ChainEpoch(cctx.Uint64("vm-height")) - if h == 0 { - if ts == nil { - head, err := api.ChainHead(ctx) - if err != nil { - return err - } - ts = head + if ts == nil { + head, err := api.ChainHead(ctx) + if err != nil { + return err } + ts = head + } + if h == 0 { h = ts.Height() } @@ -863,13 +866,18 @@ var stateComputeStateCmd = &cli.Command{ } if cctx.Bool("html") { + st, err := state.LoadStateTree(cbor.NewCborStore(apibstore.NewAPIBlockstore(api)), stout.Root) + if err != nil { + return xerrors.Errorf("loading state tree: %w", err) + } + codeCache := map[address.Address]cid.Cid{} getCode := func(addr address.Address) (cid.Cid, error) { if c, found := codeCache[addr]; found { return c, nil } - c, err := api.StateGetActor(ctx, addr, ts.Key()) + c, err := st.GetActor(addr) if err != nil { return cid.Cid{}, err } diff --git a/cmd/lotus-shed/balances.go b/cmd/lotus-shed/balances.go index c156de931..1c89a00cf 100644 --- a/cmd/lotus-shed/balances.go +++ b/cmd/lotus-shed/balances.go @@ -3,9 +3,16 @@ package main import ( "context" "fmt" + "strconv" + + "github.com/docker/go-units" + lotusbuiltin "github.com/filecoin-project/lotus/chain/actors/builtin" + "github.com/filecoin-project/lotus/chain/actors/builtin/power" + "github.com/filecoin-project/lotus/chain/actors/builtin/reward" "github.com/ipfs/go-cid" cbor "github.com/ipfs/go-ipld-cbor" + logging "github.com/ipfs/go-log/v2" "github.com/urfave/cli/v2" "golang.org/x/xerrors" @@ -44,6 +51,7 @@ var auditsCmd = &cli.Command{ Subcommands: []*cli.Command{ chainBalanceCmd, chainBalanceStateCmd, + chainPledgeCmd, }, } @@ -248,3 +256,133 @@ var chainBalanceStateCmd = &cli.Command{ return nil }, } + +var chainPledgeCmd = &cli.Command{ + Name: "stateroot-pledge", + Description: "Calculate sector pledge numbers", + Flags: []cli.Flag{ + &cli.StringFlag{ + Name: "repo", + Value: "~/.lotus", + }, + }, + ArgsUsage: "[stateroot epoch]", + Action: func(cctx *cli.Context) error { + logging.SetLogLevel("badger", "ERROR") + ctx := context.TODO() + + if !cctx.Args().Present() { + return fmt.Errorf("must pass state root") + } + + sroot, err := cid.Decode(cctx.Args().First()) + if err != nil { + return fmt.Errorf("failed to parse input: %w", err) + } + + epoch, err := strconv.ParseInt(cctx.Args().Get(1), 10, 64) + if err != nil { + return xerrors.Errorf("parsing epoch arg: %w", err) + } + + fsrepo, err := repo.NewFS(cctx.String("repo")) + if err != nil { + return err + } + + lkrepo, err := fsrepo.Lock(repo.FullNode) + if err != nil { + return err + } + + defer lkrepo.Close() //nolint:errcheck + + ds, err := lkrepo.Datastore("/chain") + if err != nil { + return err + } + + mds, err := lkrepo.Datastore("/metadata") + if err != nil { + return err + } + + bs := blockstore.NewBlockstore(ds) + + cs := store.NewChainStore(bs, mds, vm.Syscalls(ffiwrapper.ProofVerifier)) + + cst := cbor.NewCborStore(bs) + store := adt.WrapStore(ctx, cst) + + sm := stmgr.NewStateManager(cs) + + state, err := state.LoadStateTree(cst, sroot) + if err != nil { + return err + } + + var ( + powerSmoothed lotusbuiltin.FilterEstimate + pledgeCollateral abi.TokenAmount + ) + if act, err := state.GetActor(power.Address); err != nil { + return xerrors.Errorf("loading miner actor: %w", err) + } else if s, err := power.Load(store, act); err != nil { + return xerrors.Errorf("loading power actor state: %w", err) + } else if p, err := s.TotalPowerSmoothed(); err != nil { + return xerrors.Errorf("failed to determine total power: %w", err) + } else if c, err := s.TotalLocked(); err != nil { + return xerrors.Errorf("failed to determine pledge collateral: %w", err) + } else { + powerSmoothed = p + pledgeCollateral = c + } + + circ, err := sm.GetCirculatingSupplyDetailed(ctx, abi.ChainEpoch(epoch), state) + if err != nil { + return err + } + + fmt.Println("(real) circulating supply: ", types.FIL(circ.FilCirculating)) + if circ.FilCirculating.LessThan(big.Zero()) { + circ.FilCirculating = big.Zero() + } + + rewardActor, err := state.GetActor(reward.Address) + if err != nil { + return xerrors.Errorf("loading miner actor: %w", err) + } + + rewardState, err := reward.Load(store, rewardActor) + if err != nil { + return xerrors.Errorf("loading reward actor state: %w", err) + } + + fmt.Println("FilVested", types.FIL(circ.FilVested)) + fmt.Println("FilMined", types.FIL(circ.FilMined)) + fmt.Println("FilBurnt", types.FIL(circ.FilBurnt)) + fmt.Println("FilLocked", types.FIL(circ.FilLocked)) + fmt.Println("FilCirculating", types.FIL(circ.FilCirculating)) + + for _, sectorWeight := range []abi.StoragePower{ + types.NewInt(32 << 30), + types.NewInt(64 << 30), + types.NewInt(32 << 30 * 10), + types.NewInt(64 << 30 * 10), + } { + initialPledge, err := rewardState.InitialPledgeForPower( + sectorWeight, + pledgeCollateral, + &powerSmoothed, + circ.FilCirculating, + ) + if err != nil { + return xerrors.Errorf("calculating initial pledge: %w", err) + } + + fmt.Println("IP ", units.HumanSize(float64(sectorWeight.Uint64())), types.FIL(initialPledge)) + } + + return nil + }, +} diff --git a/go.mod b/go.mod index ca7e0760d..b0de7dfd6 100644 --- a/go.mod +++ b/go.mod @@ -36,7 +36,7 @@ require ( github.com/filecoin-project/go-statemachine v0.0.0-20200813232949-df9b130df370 github.com/filecoin-project/go-statestore v0.1.0 github.com/filecoin-project/go-storedcounter v0.0.0-20200421200003-1c99c62e8a5b - github.com/filecoin-project/specs-actors v0.9.10 + github.com/filecoin-project/specs-actors v0.9.11 github.com/filecoin-project/specs-storage v0.1.1-0.20200907031224-ed2e5cd13796 github.com/filecoin-project/test-vectors/schema v0.0.1 github.com/gbrlsnchs/jwt/v3 v3.0.0-beta.1 diff --git a/go.sum b/go.sum index 1ca615b59..6412fe743 100644 --- a/go.sum +++ b/go.sum @@ -254,8 +254,8 @@ github.com/filecoin-project/go-storedcounter v0.0.0-20200421200003-1c99c62e8a5b github.com/filecoin-project/go-storedcounter v0.0.0-20200421200003-1c99c62e8a5b/go.mod h1:Q0GQOBtKf1oE10eSXSlhN45kDBdGvEcVOqMiffqX+N8= github.com/filecoin-project/specs-actors v0.9.4/go.mod h1:BStZQzx5x7TmCkLv0Bpa07U6cPKol6fd3w9KjMPZ6Z4= github.com/filecoin-project/specs-actors v0.9.7/go.mod h1:wM2z+kwqYgXn5Z7scV1YHLyd1Q1cy0R8HfTIWQ0BFGU= -github.com/filecoin-project/specs-actors v0.9.10 h1:gU0TrRhgkCsBEOP42sGDE7RQuR0Cov9hJhBqq+RJmjU= -github.com/filecoin-project/specs-actors v0.9.10/go.mod h1:czlvLQGEX0fjLLfdNHD7xLymy6L3n7aQzRWzsYGf+ys= +github.com/filecoin-project/specs-actors v0.9.11 h1:TnpG7HAeiUrfj0mJM7UaPW0P2137H62RGof7ftT5Mas= +github.com/filecoin-project/specs-actors v0.9.11/go.mod h1:czlvLQGEX0fjLLfdNHD7xLymy6L3n7aQzRWzsYGf+ys= github.com/filecoin-project/specs-storage v0.1.1-0.20200907031224-ed2e5cd13796 h1:dJsTPWpG2pcTeojO2pyn0c6l+x/3MZYCBgo/9d11JEk= github.com/filecoin-project/specs-storage v0.1.1-0.20200907031224-ed2e5cd13796/go.mod h1:nJRRM7Aa9XVvygr3W9k6xGF46RWzr2zxF/iGoAIfA/g= github.com/filecoin-project/test-vectors/schema v0.0.1 h1:5fNF76nl4qolEvcIsjc0kUADlTMVHO73tW4kXXPnsus= diff --git a/node/modules/chain.go b/node/modules/chain.go index 5eda51078..66f54a76a 100644 --- a/node/modules/chain.go +++ b/node/modules/chain.go @@ -18,6 +18,7 @@ import ( "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" + "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain" "github.com/filecoin-project/lotus/chain/beacon" "github.com/filecoin-project/lotus/chain/exchange" @@ -157,6 +158,10 @@ func SetGenesis(cs *store.ChainStore, g Genesis) (dtypes.AfterGenesisSet, error) } func NetworkName(mctx helpers.MetricsCtx, lc fx.Lifecycle, cs *store.ChainStore, _ dtypes.AfterGenesisSet) (dtypes.NetworkName, error) { + if !build.Devnet { + return "testnetnet", nil + } + ctx := helpers.LifecycleCtx(mctx, lc) netName, err := stmgr.GetNetworkName(ctx, stmgr.NewStateManager(cs), cs.GetHeaviestTipSet().ParentState()) diff --git a/node/modules/storageminer.go b/node/modules/storageminer.go index 9a94a56a5..de466b004 100644 --- a/node/modules/storageminer.go +++ b/node/modules/storageminer.go @@ -109,6 +109,9 @@ func MinerID(ma dtypes.MinerAddress) (dtypes.MinerID, error) { } func StorageNetworkName(ctx helpers.MetricsCtx, a lapi.FullNode) (dtypes.NetworkName, error) { + if !build.Devnet { + return "testnetnet", nil + } return a.StateNetworkName(ctx) } diff --git a/storage/wdpost_run.go b/storage/wdpost_run.go index 9a497f879..59ffcb74c 100644 --- a/storage/wdpost_run.go +++ b/storage/wdpost_run.go @@ -371,6 +371,10 @@ func (s *WindowPoStScheduler) runPost(ctx context.Context, di dline.Info, ts *ty return j }) + if ts.Height() > build.UpgradeIgnitionHeight { + return // FORK: declaring faults after ignition upgrade makes no sense + } + if faults, sigmsg, err = s.checkNextFaults(context.TODO(), declDeadline, partitions); err != nil { // TODO: This is also potentially really bad, but we try to post anyways log.Errorf("checking sector faults: %v", err) From 12e97dbea743c02031ffbcd4f9800cc2d414e2f1 Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Sat, 26 Sep 2020 02:59:24 -0400 Subject: [PATCH 218/303] Fix docs and linter --- chain/stmgr/forks.go | 4 ---- documentation/en/api-methods.md | 2 +- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/chain/stmgr/forks.go b/chain/stmgr/forks.go index 872c70b1e..252b731d7 100644 --- a/chain/stmgr/forks.go +++ b/chain/stmgr/forks.go @@ -53,10 +53,6 @@ func (sm *StateManager) handleStateForks(ctx context.Context, root cid.Cid, heig return retCid, nil } -type forEachTree interface { - ForEach(func(address.Address, *types.Actor) error) error -} - func doTransfer(cb ExecCallback, tree types.StateTree, from, to address.Address, amt abi.TokenAmount) error { fromAct, err := tree.GetActor(from) if err != nil { diff --git a/documentation/en/api-methods.md b/documentation/en/api-methods.md index e489fcb0f..ed082ccbf 100644 --- a/documentation/en/api-methods.md +++ b/documentation/en/api-methods.md @@ -3825,7 +3825,7 @@ Inputs: ] ``` -Response: `2` +Response: `3` ### StateReadState StateReadState returns the indicated actor's state. From 567261e2c7bc5b6cb764ab0ef3c9f1f30600448d Mon Sep 17 00:00:00 2001 From: whyrusleeping Date: Fri, 25 Sep 2020 23:59:59 -0700 Subject: [PATCH 219/303] set upgrade heights for testground builds --- build/params_testground.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/build/params_testground.go b/build/params_testground.go index 954b5ccfd..07cc88688 100644 --- a/build/params_testground.go +++ b/build/params_testground.go @@ -74,7 +74,9 @@ var ( UpgradeBreezeHeight abi.ChainEpoch = -1 BreezeGasTampingDuration abi.ChainEpoch = 0 - UpgradeSmokeHeight abi.ChainEpoch = -1 + UpgradeSmokeHeight abi.ChainEpoch = -1 + UpgradeIgnitionHeight abi.ChainEpoch = -2 + UpgradeLiftoffHeight abi.ChainEpoch = -3 DrandSchedule = map[abi.ChainEpoch]DrandEnum{ 0: DrandMainnet, @@ -82,4 +84,6 @@ var ( NewestNetworkVersion = network.Version2 ActorUpgradeNetworkVersion = network.Version3 + + Devnet = true ) From 45eadc1b3aeddf794b8f29186863e43e6e25034b Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Sat, 26 Sep 2020 01:45:22 -0400 Subject: [PATCH 220/303] Lotus version 0.8.0 --- CHANGELOG.md | 57 ++++++++++++++++++++++++++++++++++++++++++++++++ build/version.go | 2 +- 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 16ced709b..ac687675e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,62 @@ # Lotus changelog +# 0.8.0 / 2020-09-26 + +This consensus-breaking release of Lotus introduces an upgrade to the network. The changes that break consensus are: + +- Upgrading to specs-actors v0.9.11, which reduces WindowPoSt faults per [FIP 0002](https://github.com/filecoin-project/FIPs/blob/master/FIPS/fip-0002.md) to reduce cost for honest miners with occasional faults (see https://github.com/filecoin-project/specs-actors/pull/1181) +- Revisions to some cryptoeconomics and network params + +This release also updates go-fil-markets to fix an incompatibility issue between v0.7.2 and earlier versions. + +## Changes + +#### Dependencies + +- Update spec actors to 0.9.11 (https://github.com/filecoin-project/lotus/pull/4039) +- Update markets to 0.6.3 (https://github.com/filecoin-project/lotus/pull/4013) + +#### Core Lotus + +- Network upgrade (https://github.com/filecoin-project/lotus/pull/4039) +- Fix AddSupportedProofTypes (https://github.com/filecoin-project/lotus/pull/4033) +- Return an error when we fail to find a sector when checking sector expiration (https://github.com/filecoin-project/lotus/pull/4026) +- Batch blockstore copies after block validation (https://github.com/filecoin-project/lotus/pull/3980) +- Remove a misleading miner actor abstraction (https://github.com/filecoin-project/lotus/pull/3977) +- Fix out-of-bounds when loading all sector infos (https://github.com/filecoin-project/lotus/pull/3976) +- Fix break condition in the miner (https://github.com/filecoin-project/lotus/pull/3953) + +#### UX + +- Correct helptext around miners setting ask (https://github.com/filecoin-project/lotus/pull/4009) +- Make sync wait nicer (https://github.com/filecoin-project/lotus/pull/3991) + +#### Tooling and validation + +- Small adjustments following network upgradability changes (https://github.com/filecoin-project/lotus/pull/3996) +- Add some more big pictures stats to stateroot stat (https://github.com/filecoin-project/lotus/pull/3995) +- Add some actors policy setters for testing (https://github.com/filecoin-project/lotus/pull/3975) + +## Contributors + +The following contributors had 5 or more commits go into this release. +We are grateful for every contribution! + +| Contributor | Commits | Lines ± | +|--------------------|---------|---------------| +| arajasek | 66 | +3140/-1261 | +| Stebalien | 64 | +3797/-3434 | +| magik6k | 48 | +1892/-976 | +| raulk | 40 | +2412/-1549 | +| vyzo | 22 | +287/-196 | +| alanshaw | 15 | +761/-146 | +| whyrusleeping | 15 | +736/-52 | +| hannahhoward | 14 | +1237/837- | +| anton | 6 | +32/-8 | +| travisperson | 5 | +502/-6 | +| Frank | 5 | +78/-39 | +| Jennifer | 5 | +148/-41 | + # 0.7.2 / 2020-09-23 This optional release of Lotus introduces a major refactor around how a Lotus node interacts with code from the specs-actors repo. We now use interfaces to read the state of actors, which is required to be able to reason about different versions of actors code at the same time. diff --git a/build/version.go b/build/version.go index cfc8c3ab9..77b98f008 100644 --- a/build/version.go +++ b/build/version.go @@ -29,7 +29,7 @@ func buildType() string { } // BuildVersion is the local build version, set by build system -const BuildVersion = "0.7.2" +const BuildVersion = "0.8.0" func UserVersion() string { return BuildVersion + buildType() + CurrentCommit From 81a30cbf062fb0e031dfdfc0826f61faeacc6b22 Mon Sep 17 00:00:00 2001 From: Steven Li Date: Sat, 26 Sep 2020 16:01:10 +0800 Subject: [PATCH 221/303] Add one more node located in China --- build/bootstrap/bootstrappers.pi | 1 + 1 file changed, 1 insertion(+) diff --git a/build/bootstrap/bootstrappers.pi b/build/bootstrap/bootstrappers.pi index 465f3b5e9..1c8b77709 100644 --- a/build/bootstrap/bootstrappers.pi +++ b/build/bootstrap/bootstrappers.pi @@ -4,3 +4,4 @@ /dns4/bootstrap-4.testnet.fildev.network/tcp/1347/p2p/12D3KooWPkL9LrKRQgHtq7kn9ecNhGU9QaziG8R5tX8v9v7t3h34 /dns4/bootstrap-3.testnet.fildev.network/tcp/1347/p2p/12D3KooWKYSsbpgZ3HAjax5M1BXCwXLa6gVkUARciz7uN3FNtr7T /dns4/bootstrap-5.testnet.fildev.network/tcp/1347/p2p/12D3KooWQYzqnLASJAabyMpPb1GcWZvNSe7JDcRuhdRqonFoiK9W +/dns4/lotus-bootstrap.forceup.cn/tcp/41778/p2p/12D3KooWFQsv3nRMUevZNWWsY1Wu6NUzUbawnWU5NcRhgKuJA37C From 650725d71e909089e5087169d8d694e3f4076e4c Mon Sep 17 00:00:00 2001 From: zgfzgf <1901989065@qq.com> Date: Sat, 26 Sep 2020 17:30:58 +0800 Subject: [PATCH 222/303] add printf --- api/test/window_post.go | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/api/test/window_post.go b/api/test/window_post.go index 683489a91..958c91816 100644 --- a/api/test/window_post.go +++ b/api/test/window_post.go @@ -153,18 +153,16 @@ func TestWindowPost(t *testing.T, b APIBuilder, blocktime time.Duration, nSector require.NoError(t, err) fmt.Printf("Running one proving period\n") + fmt.Printf("End for head.Height > %d\n", di.PeriodStart+di.WPoStProvingPeriod+2) for { head, err := client.ChainHead(ctx) require.NoError(t, err) if head.Height() > di.PeriodStart+(di.WPoStProvingPeriod)+2 { + fmt.Printf("Now head.Height = %d\n", head.Height()) break } - - if head.Height()%100 == 0 { - fmt.Printf("@%d\n", head.Height()) - } build.Clock.Sleep(blocktime) } @@ -186,7 +184,6 @@ func TestWindowPost(t *testing.T, b APIBuilder, blocktime time.Duration, nSector require.Greater(t, len(parts), 0) secs := parts[0].AllSectors - require.NoError(t, err) n, err := secs.Count() require.NoError(t, err) require.Equal(t, uint64(2), n) @@ -210,7 +207,6 @@ func TestWindowPost(t *testing.T, b APIBuilder, blocktime time.Duration, nSector require.Greater(t, len(parts), 0) secs := parts[0].AllSectors - require.NoError(t, err) n, err := secs.Count() require.NoError(t, err) require.Equal(t, uint64(2), n) @@ -236,18 +232,17 @@ func TestWindowPost(t *testing.T, b APIBuilder, blocktime time.Duration, nSector require.NoError(t, err) fmt.Printf("Go through another PP, wait for sectors to become faulty\n") + fmt.Printf("End for head.Height > %d\n", di.PeriodStart+di.WPoStProvingPeriod+2) for { head, err := client.ChainHead(ctx) require.NoError(t, err) if head.Height() > di.PeriodStart+(di.WPoStProvingPeriod)+2 { + fmt.Printf("Now head.Height = %d\n", head.Height()) break } - if head.Height()%100 == 0 { - fmt.Printf("@%d\n", head.Height()) - } build.Clock.Sleep(blocktime) } @@ -267,17 +262,17 @@ func TestWindowPost(t *testing.T, b APIBuilder, blocktime time.Duration, nSector di, err = client.StateMinerProvingDeadline(ctx, maddr, types.EmptyTSK) require.NoError(t, err) + fmt.Printf("End for head.Height > %d\n", di.PeriodStart+di.WPoStProvingPeriod+2) + for { head, err := client.ChainHead(ctx) require.NoError(t, err) if head.Height() > di.PeriodStart+di.WPoStProvingPeriod+2 { + fmt.Printf("Now head.Height = %d\n", head.Height()) break } - if head.Height()%100 == 0 { - fmt.Printf("@%d\n", head.Height()) - } build.Clock.Sleep(blocktime) } @@ -300,12 +295,14 @@ func TestWindowPost(t *testing.T, b APIBuilder, blocktime time.Duration, nSector require.NoError(t, err) waitUntil := head.Height() + 10 + fmt.Printf("End for head.Height > %d\n", waitUntil) for { head, err := client.ChainHead(ctx) require.NoError(t, err) if head.Height() > waitUntil { + fmt.Printf("Now head.Height = %d\n", head.Height()) break } } From bddd6dd8a8aaa89d38a5ccebc3b066224ca6b510 Mon Sep 17 00:00:00 2001 From: whyrusleeping Date: Sat, 26 Sep 2020 11:06:16 -0500 Subject: [PATCH 223/303] fix GetPower with no miner address --- chain/stmgr/utils.go | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/chain/stmgr/utils.go b/chain/stmgr/utils.go index 58e7f480f..bac5a31f5 100644 --- a/chain/stmgr/utils.go +++ b/chain/stmgr/utils.go @@ -102,6 +102,7 @@ func GetPowerRaw(ctx context.Context, sm *StateManager, st cid.Cid, maddr addres } var mpow power.Claim + var minpow bool if maddr != address.Undef { var found bool mpow, found, err = pas.MinerPower(maddr) @@ -109,11 +110,11 @@ func GetPowerRaw(ctx context.Context, sm *StateManager, st cid.Cid, maddr addres // TODO: return an error when not found? return power.Claim{}, power.Claim{}, false, err } - } - minpow, err := pas.MinerNominalPowerMeetsConsensusMinimum(maddr) - if err != nil { - return power.Claim{}, power.Claim{}, false, err + minpow, err = pas.MinerNominalPowerMeetsConsensusMinimum(maddr) + if err != nil { + return power.Claim{}, power.Claim{}, false, err + } } return mpow, tpow, minpow, nil From 1c5cb50da340b19f287b211a40238e8782378cad Mon Sep 17 00:00:00 2001 From: Travis Person Date: Sat, 26 Sep 2020 17:09:16 +0000 Subject: [PATCH 224/303] Add back network power to stats --- tools/stats/metrics.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tools/stats/metrics.go b/tools/stats/metrics.go index 22069c3d0..dd51ee69f 100644 --- a/tools/stats/metrics.go +++ b/tools/stats/metrics.go @@ -10,6 +10,7 @@ import ( "strings" "time" + "github.com/filecoin-project/go-address" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/actors/builtin/reward" @@ -252,6 +253,14 @@ func RecordTipsetStatePoints(ctx context.Context, api api.FullNode, pl *PointLis p := NewPoint("network.balance", netBalFilFloat) pl.AddPoint(p) + totalPower, err := api.StateMinerPower(ctx, address.Address{}, tipset.Key()) + if err != nil { + return err + } + + p = NewPoint("chain.power", totalPower.TotalPower.QualityAdjPower.Int64()) + pl.AddPoint(p) + miners, err := api.StateListMiners(ctx, tipset.Key()) if err != nil { return err From 8955b8d8a7ae3110acd82f072e9d739be7f73ac1 Mon Sep 17 00:00:00 2001 From: Peter Rabbitson Date: Sat, 26 Sep 2020 21:16:28 +0200 Subject: [PATCH 225/303] Centralize filtering, output wallet addresses --- cmd/lotus-shed/dealtracker.go | 186 ++++++++++++++++++---------------- 1 file changed, 97 insertions(+), 89 deletions(-) diff --git a/cmd/lotus-shed/dealtracker.go b/cmd/lotus-shed/dealtracker.go index d39f51bd1..a21923009 100644 --- a/cmd/lotus-shed/dealtracker.go +++ b/cmd/lotus-shed/dealtracker.go @@ -5,8 +5,7 @@ import ( "encoding/json" "net" "net/http" - "os" - "strings" + "sync" "github.com/filecoin-project/go-address" "github.com/filecoin-project/lotus/api" @@ -19,23 +18,27 @@ type dealStatsServer struct { api api.FullNode } -var filteredClients map[address.Address]bool +// these lists grow continuously with the network +// TODO: need to switch this to an LRU of sorts, to ensure refreshes +var knownFiltered = new(sync.Map) +var resolvedWallets = new(sync.Map) func init() { - fc := []string{"t0112", "t0113", "t0114", "t010089"} - - filtered, set := os.LookupEnv("FILTERED_CLIENTS") - if set { - fc = strings.Split(filtered, ":") - } - - filteredClients = make(map[address.Address]bool) - for _, a := range fc { - addr, err := address.NewFromString(a) + for _, a := range []string{ + "t0100", // client for genesis miner + "t0112", // client for genesis miner + "t0113", // client for genesis miner + "t0114", // client for genesis miner + "t1nslxql4pck5pq7hddlzym3orxlx35wkepzjkm3i", // SR1 dealbot wallet + "t1stghxhdp2w53dym2nz2jtbpk6ccd4l2lxgmezlq", // SR1 dealbot wallet + "t1mcr5xkgv4jdl3rnz77outn6xbmygb55vdejgbfi", // SR1 dealbot wallet + "t1qiqdbbmrdalbntnuapriirduvxu5ltsc5mhy7si", // SR1 dealbot wallet + } { + a, err := address.NewFromString(a) if err != nil { panic(err) } - filteredClients[addr] = true + knownFiltered.Store(a, true) } } @@ -45,32 +48,16 @@ type dealCountResp struct { } func (dss *dealStatsServer) handleStorageDealCount(w http.ResponseWriter, r *http.Request) { - ctx := context.Background() - head, err := dss.api.ChainHead(ctx) - if err != nil { - log.Warnf("failed to get chain head: %s", err) + epoch, deals := dss.filteredDealList() + if epoch == 0 { w.WriteHeader(500) return } - deals, err := dss.api.StateMarketDeals(ctx, head.Key()) - if err != nil { - log.Warnf("failed to get market deals: %s", err) - w.WriteHeader(500) - return - } - - var count int64 - for _, d := range deals { - if !filteredClients[d.Proposal.Client] { - count++ - } - } - if err := json.NewEncoder(w).Encode(&dealCountResp{ - Total: count, - Epoch: int64(head.Height()), + Total: int64(len(deals)), + Epoch: epoch, }); err != nil { log.Warnf("failed to write back deal count response: %s", err) return @@ -83,34 +70,21 @@ type dealAverageResp struct { } func (dss *dealStatsServer) handleStorageDealAverageSize(w http.ResponseWriter, r *http.Request) { - ctx := context.Background() - head, err := dss.api.ChainHead(ctx) - if err != nil { - log.Warnf("failed to get chain head: %s", err) + epoch, deals := dss.filteredDealList() + if epoch == 0 { w.WriteHeader(500) return } - deals, err := dss.api.StateMarketDeals(ctx, head.Key()) - if err != nil { - log.Warnf("failed to get market deals: %s", err) - w.WriteHeader(500) - return - } - - var count int64 var totalBytes int64 for _, d := range deals { - if !filteredClients[d.Proposal.Client] { - count++ - totalBytes += int64(d.Proposal.PieceSize.Unpadded()) - } + totalBytes += int64(d.deal.Proposal.PieceSize.Unpadded()) } if err := json.NewEncoder(w).Encode(&dealAverageResp{ - AverageSize: totalBytes / count, - Epoch: int64(head.Height()), + AverageSize: totalBytes / int64(len(deals)), + Epoch: epoch, }); err != nil { log.Warnf("failed to write back deal average response: %s", err) return @@ -123,32 +97,20 @@ type dealTotalResp struct { } func (dss *dealStatsServer) handleStorageDealTotalReal(w http.ResponseWriter, r *http.Request) { - ctx := context.Background() - - head, err := dss.api.ChainHead(ctx) - if err != nil { - log.Warnf("failed to get chain head: %s", err) - w.WriteHeader(500) - return - } - - deals, err := dss.api.StateMarketDeals(ctx, head.Key()) - if err != nil { - log.Warnf("failed to get market deals: %s", err) + epoch, deals := dss.filteredDealList() + if epoch == 0 { w.WriteHeader(500) return } var totalBytes int64 for _, d := range deals { - if !filteredClients[d.Proposal.Client] { - totalBytes += int64(d.Proposal.PieceSize.Unpadded()) - } + totalBytes += int64(d.deal.Proposal.PieceSize.Unpadded()) } if err := json.NewEncoder(w).Encode(&dealTotalResp{ TotalBytes: totalBytes, - Epoch: int64(head.Height()), + Epoch: epoch, }); err != nil { log.Warnf("failed to write back deal average response: %s", err) return @@ -168,18 +130,8 @@ type clientStatsOutput struct { } func (dss *dealStatsServer) handleStorageClientStats(w http.ResponseWriter, r *http.Request) { - ctx := context.Background() - - head, err := dss.api.ChainHead(ctx) - if err != nil { - log.Warnf("failed to get chain head: %s", err) - w.WriteHeader(500) - return - } - - deals, err := dss.api.StateMarketDeals(ctx, head.Key()) - if err != nil { - log.Warnf("failed to get market deals: %s", err) + epoch, deals := dss.filteredDealList() + if epoch == 0 { w.WriteHeader(500) return } @@ -187,23 +139,20 @@ func (dss *dealStatsServer) handleStorageClientStats(w http.ResponseWriter, r *h stats := make(map[address.Address]*clientStatsOutput) for _, d := range deals { - if filteredClients[d.Proposal.Client] { - continue - } - st, ok := stats[d.Proposal.Client] + st, ok := stats[d.deal.Proposal.Client] if !ok { st = &clientStatsOutput{ - Client: d.Proposal.Client, + Client: d.resolvedWallet, cids: make(map[cid.Cid]bool), providers: make(map[address.Address]bool), } - stats[d.Proposal.Client] = st + stats[d.deal.Proposal.Client] = st } - st.DataSize += int64(d.Proposal.PieceSize.Unpadded()) - st.cids[d.Proposal.PieceCID] = true - st.providers[d.Proposal.Provider] = true + st.DataSize += int64(d.deal.Proposal.PieceSize.Unpadded()) + st.cids[d.deal.Proposal.PieceCID] = true + st.providers[d.deal.Proposal.Provider] = true st.NumDeals++ } @@ -221,6 +170,65 @@ func (dss *dealStatsServer) handleStorageClientStats(w http.ResponseWriter, r *h } } +type dealInfo struct { + deal api.MarketDeal + resolvedWallet address.Address +} + +// filteredDealList returns the current epoch and a list of filtered deals +// on error returns an epoch of 0 +func (dss *dealStatsServer) filteredDealList() (int64, map[string]dealInfo) { + ctx := context.Background() + + head, err := dss.api.ChainHead(ctx) + if err != nil { + log.Warnf("failed to get chain head: %s", err) + return 0, nil + } + + deals, err := dss.api.StateMarketDeals(ctx, head.Key()) + if err != nil { + log.Warnf("failed to get market deals: %s", err) + return 0, nil + } + + ret := make(map[string]dealInfo, len(deals)) + for dealKey, d := range deals { + + // Counting no-longer-active deals as per Pooja's request + // // https://github.com/filecoin-project/specs-actors/blob/v0.9.9/actors/builtin/market/deal.go#L81-L85 + // if d.State.SectorStartEpoch < 0 { + // continue + // } + + if _, isFiltered := knownFiltered.Load(d.Proposal.Client); isFiltered { + continue + } + + if _, wasSeen := resolvedWallets.Load(d.Proposal.Client); !wasSeen { + w, err := dss.api.StateAccountKey(ctx, d.Proposal.Client, head.Key()) + if err != nil { + log.Warnf("failed to resolve id '%s' to wallet address: %s", d.Proposal.Client, err) + continue + } else { + resolvedWallets.Store(d.Proposal.Client, w) + } + } + + w, _ := resolvedWallets.Load(d.Proposal.Client) + if _, isFiltered := knownFiltered.Load(w); isFiltered { + continue + } + + ret[dealKey] = dealInfo{ + deal: d, + resolvedWallet: w.(address.Address), + } + } + + return int64(head.Height()), ret +} + var serveDealStatsCmd = &cli.Command{ Name: "serve-deal-stats", Flags: []cli.Flag{}, From 10cdbadd82158cc36959877733ad008188b6aa14 Mon Sep 17 00:00:00 2001 From: Peter Rabbitson Date: Sat, 26 Sep 2020 21:29:11 +0200 Subject: [PATCH 226/303] Arrange json as the frontend expects it --- cmd/lotus-shed/dealtracker.go | 55 ++++++++++++++++++++++------------- 1 file changed, 35 insertions(+), 20 deletions(-) diff --git a/cmd/lotus-shed/dealtracker.go b/cmd/lotus-shed/dealtracker.go index a21923009..1340dc9c6 100644 --- a/cmd/lotus-shed/dealtracker.go +++ b/cmd/lotus-shed/dealtracker.go @@ -43,8 +43,9 @@ func init() { } type dealCountResp struct { - Total int64 `json:"total"` - Epoch int64 `json:"epoch"` + Epoch int64 `json:"epoch"` + Endpoint string `json:"endpoint"` + Payload int64 `json:"payload"` } func (dss *dealStatsServer) handleStorageDealCount(w http.ResponseWriter, r *http.Request) { @@ -56,8 +57,9 @@ func (dss *dealStatsServer) handleStorageDealCount(w http.ResponseWriter, r *htt } if err := json.NewEncoder(w).Encode(&dealCountResp{ - Total: int64(len(deals)), - Epoch: epoch, + Endpoint: "COUNT_DEALS", + Payload: int64(len(deals)), + Epoch: epoch, }); err != nil { log.Warnf("failed to write back deal count response: %s", err) return @@ -65,8 +67,9 @@ func (dss *dealStatsServer) handleStorageDealCount(w http.ResponseWriter, r *htt } type dealAverageResp struct { - AverageSize int64 `json:"average_size"` - Epoch int64 `json:"epoch"` + Epoch int64 `json:"epoch"` + Endpoint string `json:"endpoint"` + Payload int64 `json:"payload"` } func (dss *dealStatsServer) handleStorageDealAverageSize(w http.ResponseWriter, r *http.Request) { @@ -83,8 +86,9 @@ func (dss *dealStatsServer) handleStorageDealAverageSize(w http.ResponseWriter, } if err := json.NewEncoder(w).Encode(&dealAverageResp{ - AverageSize: totalBytes / int64(len(deals)), - Epoch: epoch, + Endpoint: "AVERAGE_DEAL_SIZE", + Payload: totalBytes / int64(len(deals)), + Epoch: epoch, }); err != nil { log.Warnf("failed to write back deal average response: %s", err) return @@ -92,8 +96,9 @@ func (dss *dealStatsServer) handleStorageDealAverageSize(w http.ResponseWriter, } type dealTotalResp struct { - TotalBytes int64 `json:"total_size"` - Epoch int64 `json:"epoch"` + Epoch int64 `json:"epoch"` + Endpoint string `json:"endpoint"` + Payload int64 `json:"payload"` } func (dss *dealStatsServer) handleStorageDealTotalReal(w http.ResponseWriter, r *http.Request) { @@ -109,8 +114,9 @@ func (dss *dealStatsServer) handleStorageDealTotalReal(w http.ResponseWriter, r } if err := json.NewEncoder(w).Encode(&dealTotalResp{ - TotalBytes: totalBytes, - Epoch: epoch, + Endpoint: "DEAL_BYTES", + Payload: totalBytes, + Epoch: epoch, }); err != nil { log.Warnf("failed to write back deal average response: %s", err) return @@ -119,6 +125,12 @@ func (dss *dealStatsServer) handleStorageDealTotalReal(w http.ResponseWriter, r } type clientStatsOutput struct { + Epoch int64 `json:"epoch"` + Endpoint string `json:"endpoint"` + Payload []*clientStats `json:"payload"` +} + +type clientStats struct { Client address.Address `json:"client"` DataSize int64 `json:"data_size"` NumCids int `json:"num_cids"` @@ -136,13 +148,13 @@ func (dss *dealStatsServer) handleStorageClientStats(w http.ResponseWriter, r *h return } - stats := make(map[address.Address]*clientStatsOutput) + stats := make(map[address.Address]*clientStats) for _, d := range deals { st, ok := stats[d.deal.Proposal.Client] if !ok { - st = &clientStatsOutput{ + st = &clientStats{ Client: d.resolvedWallet, cids: make(map[cid.Cid]bool), providers: make(map[address.Address]bool), @@ -156,12 +168,15 @@ func (dss *dealStatsServer) handleStorageClientStats(w http.ResponseWriter, r *h st.NumDeals++ } - out := make([]*clientStatsOutput, 0, len(stats)) - for _, cso := range stats { - cso.NumCids = len(cso.cids) - cso.NumMiners = len(cso.providers) - - out = append(out, cso) + out := clientStatsOutput{ + Epoch: epoch, + Endpoint: "CLIENT_DEAL_STATS", + Payload: make([]*clientStats, 0, len(stats)), + } + for _, cs := range stats { + cs.NumCids = len(cs.cids) + cs.NumMiners = len(cs.providers) + out.Payload = append(out.Payload, cs) } if err := json.NewEncoder(w).Encode(out); err != nil { From 1483f1e59adcbd91ab90ca01a3b8591e8f37c1fc Mon Sep 17 00:00:00 2001 From: Peter Rabbitson Date: Sat, 26 Sep 2020 21:43:49 +0200 Subject: [PATCH 227/303] Add filtering of addresses associated with miners --- cmd/lotus-shed/dealtracker.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/cmd/lotus-shed/dealtracker.go b/cmd/lotus-shed/dealtracker.go index 1340dc9c6..719e821a5 100644 --- a/cmd/lotus-shed/dealtracker.go +++ b/cmd/lotus-shed/dealtracker.go @@ -201,6 +201,26 @@ func (dss *dealStatsServer) filteredDealList() (int64, map[string]dealInfo) { return 0, nil } + // Exclude any address associated with a miner + miners, err := dss.api.StateListMiners(ctx, head.Key()) + if err != nil { + log.Warnf("failed to get miner list: %s", err) + return 0, nil + } + for _, m := range miners { + info, err := dss.api.StateMinerInfo(ctx, m, head.Key()) + if err != nil { + log.Warnf("failed to get info for known miner '%s': %s", m, err) + continue + } + + knownFiltered.Store(info.Owner, true) + knownFiltered.Store(info.Worker, true) + for _, a := range info.ControlAddresses { + knownFiltered.Store(a, true) + } + } + deals, err := dss.api.StateMarketDeals(ctx, head.Key()) if err != nil { log.Warnf("failed to get market deals: %s", err) From fb3bcc4ce527961fa172898a180d1fbb865fc133 Mon Sep 17 00:00:00 2001 From: Peter Rabbitson Date: Sat, 26 Sep 2020 21:49:05 +0200 Subject: [PATCH 228/303] Add startup warning --- cmd/lotus-shed/dealtracker.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cmd/lotus-shed/dealtracker.go b/cmd/lotus-shed/dealtracker.go index 719e821a5..8a9d0d6f3 100644 --- a/cmd/lotus-shed/dealtracker.go +++ b/cmd/lotus-shed/dealtracker.go @@ -303,6 +303,8 @@ var serveDealStatsCmd = &cli.Command{ panic(err) } + log.Warnf("deal-stat server listening on %s\n== NOTE: QUERIES ARE EXPENSIVE - YOU MUST FRONT-CACHE THIS SERVICE\n", list.Addr().String()) + return s.Serve(list) }, } From 70071e273d10f07010e70673f0d878fbb46f2262 Mon Sep 17 00:00:00 2001 From: zgfzgf <1901989065@qq.com> Date: Sun, 27 Sep 2020 09:58:37 +0800 Subject: [PATCH 229/303] optimize tipset Equals func --- chain/types/tipset.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/chain/types/tipset.go b/chain/types/tipset.go index 44d41c29d..5d34ec89d 100644 --- a/chain/types/tipset.go +++ b/chain/types/tipset.go @@ -167,6 +167,10 @@ func (ts *TipSet) Equals(ots *TipSet) bool { return false } + if ts.height != ots.height { + return false + } + if len(ts.blks) != len(ots.blks) { return false } From 04876c663e16eb381adb6695f32db1c7f99493ab Mon Sep 17 00:00:00 2001 From: zgfzgf <1901989065@qq.com> Date: Sun, 27 Sep 2020 10:17:06 +0800 Subject: [PATCH 230/303] modify tipset Equals --- chain/types/tipset.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/chain/types/tipset.go b/chain/types/tipset.go index 5d34ec89d..07eff3734 100644 --- a/chain/types/tipset.go +++ b/chain/types/tipset.go @@ -171,12 +171,12 @@ func (ts *TipSet) Equals(ots *TipSet) bool { return false } - if len(ts.blks) != len(ots.blks) { + if len(ts.cids) != len(ots.cids) { return false } - for i, b := range ts.blks { - if b.Cid() != ots.blks[i].Cid() { + for i, cid := range ts.cids { + if cid != ots.cids[i] { return false } } From 7a14455ac8253e0a9fd23fd358baf541efe3ca8e Mon Sep 17 00:00:00 2001 From: zgfzgf <1901989065@qq.com> Date: Sun, 27 Sep 2020 15:01:42 +0800 Subject: [PATCH 231/303] miner debug where injectNulls != 0 --- miner/miner.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/miner/miner.go b/miner/miner.go index 1b79f5245..d4e7b2317 100644 --- a/miner/miner.go +++ b/miner/miner.go @@ -211,6 +211,8 @@ minerLoop: base = prebase } + base.NullRounds += injectNulls // testing + if base.TipSet.Equals(lastBase.TipSet) && lastBase.NullRounds == base.NullRounds { log.Warnf("BestMiningCandidate from the previous round: %s (nulls:%d)", lastBase.TipSet.Cids(), lastBase.NullRounds) if !m.niceSleep(time.Duration(build.BlockDelaySecs) * time.Second) { @@ -219,8 +221,6 @@ minerLoop: continue } - base.NullRounds += injectNulls // testing - b, err := m.mineOne(ctx, base) if err != nil { log.Errorf("mining block failed: %+v", err) From e4c1f090af73cc0e9f997b3de5e9a9443b493ad5 Mon Sep 17 00:00:00 2001 From: Peter Rabbitson Date: Sun, 27 Sep 2020 20:44:50 +0200 Subject: [PATCH 232/303] Disable exclusion of miner-associated addresses --- cmd/lotus-shed/dealtracker.go | 40 +++++++++++++++++++---------------- 1 file changed, 22 insertions(+), 18 deletions(-) diff --git a/cmd/lotus-shed/dealtracker.go b/cmd/lotus-shed/dealtracker.go index 8a9d0d6f3..083db8ecb 100644 --- a/cmd/lotus-shed/dealtracker.go +++ b/cmd/lotus-shed/dealtracker.go @@ -26,6 +26,8 @@ var resolvedWallets = new(sync.Map) func init() { for _, a := range []string{ "t0100", // client for genesis miner + "t0101", // client for genesis miner + "t0102", // client for genesis miner "t0112", // client for genesis miner "t0113", // client for genesis miner "t0114", // client for genesis miner @@ -201,25 +203,27 @@ func (dss *dealStatsServer) filteredDealList() (int64, map[string]dealInfo) { return 0, nil } - // Exclude any address associated with a miner - miners, err := dss.api.StateListMiners(ctx, head.Key()) - if err != nil { - log.Warnf("failed to get miner list: %s", err) - return 0, nil - } - for _, m := range miners { - info, err := dss.api.StateMinerInfo(ctx, m, head.Key()) - if err != nil { - log.Warnf("failed to get info for known miner '%s': %s", m, err) - continue - } + // Disabled as per @pooja's request + // + // // Exclude any address associated with a miner + // miners, err := dss.api.StateListMiners(ctx, head.Key()) + // if err != nil { + // log.Warnf("failed to get miner list: %s", err) + // return 0, nil + // } + // for _, m := range miners { + // info, err := dss.api.StateMinerInfo(ctx, m, head.Key()) + // if err != nil { + // log.Warnf("failed to get info for known miner '%s': %s", m, err) + // continue + // } - knownFiltered.Store(info.Owner, true) - knownFiltered.Store(info.Worker, true) - for _, a := range info.ControlAddresses { - knownFiltered.Store(a, true) - } - } + // knownFiltered.Store(info.Owner, true) + // knownFiltered.Store(info.Worker, true) + // for _, a := range info.ControlAddresses { + // knownFiltered.Store(a, true) + // } + // } deals, err := dss.api.StateMarketDeals(ctx, head.Key()) if err != nil { From be5dc2c57fb8dfde934ddaa63b22d25dd5ca0356 Mon Sep 17 00:00:00 2001 From: Peter Rabbitson Date: Sun, 27 Sep 2020 20:45:45 +0200 Subject: [PATCH 233/303] Walk back 10 epochs for stat generation --- cmd/lotus-shed/dealtracker.go | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/cmd/lotus-shed/dealtracker.go b/cmd/lotus-shed/dealtracker.go index 083db8ecb..8ded6bf4a 100644 --- a/cmd/lotus-shed/dealtracker.go +++ b/cmd/lotus-shed/dealtracker.go @@ -8,6 +8,7 @@ import ( "sync" "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/lotus/api" lcli "github.com/filecoin-project/lotus/cli" "github.com/ipfs/go-cid" @@ -18,6 +19,10 @@ type dealStatsServer struct { api api.FullNode } +// Requested by @jbenet +// How many epochs back to look at for dealstats +var epochLookback = abi.ChainEpoch(10) + // these lists grow continuously with the network // TODO: need to switch this to an LRU of sorts, to ensure refreshes var knownFiltered = new(sync.Map) @@ -203,6 +208,12 @@ func (dss *dealStatsServer) filteredDealList() (int64, map[string]dealInfo) { return 0, nil } + head, err = dss.api.ChainGetTipSetByHeight(ctx, head.Height()-epochLookback, head.Key()) + if err != nil { + log.Warnf("failed to walk back %s epochs: %s", epochLookback, err) + return 0, nil + } + // Disabled as per @pooja's request // // // Exclude any address associated with a miner From e5c56da3217217362cffef257b1433034882c228 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Kripalani?= Date: Sun, 27 Sep 2020 20:10:05 +0100 Subject: [PATCH 234/303] move conformance tvx tool to lotus. --- .github/CODEOWNERS | 1 + cmd/tvx/exec.go | 92 +++++++++ cmd/tvx/extract.go | 380 +++++++++++++++++++++++++++++++++++++ cmd/tvx/main.go | 92 +++++++++ cmd/tvx/state.go | 293 ++++++++++++++++++++++++++++ cmd/tvx/stores.go | 143 ++++++++++++++ conformance/corpus_test.go | 133 +++++++++++++ conformance/driver.go | 8 +- conformance/reporter.go | 62 ++++++ conformance/runner.go | 253 ++++++++++++++++++++++++ conformance/runner_test.go | 376 ------------------------------------ go.sum | 1 + 12 files changed, 1457 insertions(+), 377 deletions(-) create mode 100644 cmd/tvx/exec.go create mode 100644 cmd/tvx/extract.go create mode 100644 cmd/tvx/main.go create mode 100644 cmd/tvx/state.go create mode 100644 cmd/tvx/stores.go create mode 100644 conformance/corpus_test.go create mode 100644 conformance/reporter.go create mode 100644 conformance/runner.go delete mode 100644 conformance/runner_test.go diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 49e461d00..6d717b44d 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -13,3 +13,4 @@ ### Conformance testing. conformance/ @raulk extern/test-vectors @raulk +cmd/tvx @raulk \ No newline at end of file diff --git a/cmd/tvx/exec.go b/cmd/tvx/exec.go new file mode 100644 index 000000000..9ec6f9e2b --- /dev/null +++ b/cmd/tvx/exec.go @@ -0,0 +1,92 @@ +package main + +import ( + "encoding/json" + "fmt" + "io" + "log" + "os" + + "github.com/fatih/color" + "github.com/urfave/cli/v2" + + "github.com/filecoin-project/lotus/conformance" + + "github.com/filecoin-project/test-vectors/schema" +) + +var execFlags struct { + file string +} + +var execCmd = &cli.Command{ + Name: "exec", + Description: "execute one or many test vectors against Lotus; supplied as a single JSON file, or a ndjson stdin stream", + Action: runExecLotus, + Flags: []cli.Flag{ + &cli.StringFlag{ + Name: "file", + Usage: "input file; if not supplied, the vector will be read from stdin", + TakesFile: true, + Destination: &execFlags.file, + }, + }, +} + +func runExecLotus(_ *cli.Context) error { + if file := execFlags.file; file != "" { + // we have a single test vector supplied as a file. + file, err := os.Open(file) + if err != nil { + return fmt.Errorf("failed to open test vector: %w", err) + } + + var ( + dec = json.NewDecoder(file) + tv schema.TestVector + ) + + if err = dec.Decode(&tv); err != nil { + return fmt.Errorf("failed to decode test vector: %w", err) + } + + return executeTestVector(tv) + } + + for dec := json.NewDecoder(os.Stdin); ; { + var tv schema.TestVector + switch err := dec.Decode(&tv); err { + case nil: + if err = executeTestVector(tv); err != nil { + return err + } + case io.EOF: + // we're done. + return nil + default: + // something bad happened. + return err + } + } +} + +func executeTestVector(tv schema.TestVector) error { + log.Println("executing test vector:", tv.Meta.ID) + r := new(conformance.LogReporter) + switch class := tv.Class; class { + case "message": + conformance.ExecuteMessageVector(r, &tv) + case "tipset": + conformance.ExecuteTipsetVector(r, &tv) + default: + return fmt.Errorf("test vector class %s not supported", class) + } + + if r.Failed() { + log.Println(color.HiRedString("❌ test vector failed")) + } else { + log.Println(color.GreenString("✅ test vector succeeded")) + } + + return nil +} diff --git a/cmd/tvx/extract.go b/cmd/tvx/extract.go new file mode 100644 index 000000000..81fd3efbf --- /dev/null +++ b/cmd/tvx/extract.go @@ -0,0 +1,380 @@ +package main + +import ( + "bytes" + "compress/gzip" + "context" + "encoding/json" + "fmt" + "io" + "log" + "os" + + "github.com/filecoin-project/lotus/api" + init_ "github.com/filecoin-project/lotus/chain/actors/builtin/init" + "github.com/filecoin-project/lotus/chain/actors/builtin/reward" + "github.com/filecoin-project/lotus/chain/types" + "github.com/filecoin-project/lotus/chain/vm" + "github.com/filecoin-project/lotus/conformance" + + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/specs-actors/actors/builtin" + "github.com/filecoin-project/test-vectors/schema" + + "github.com/ipfs/go-cid" + "github.com/urfave/cli/v2" +) + +var extractFlags struct { + id string + class string + cid string + file string + retain string +} + +var extractCmd = &cli.Command{ + Name: "extract", + Description: "generate a message-class test vector by extracting it from a live chain", + Action: runExtract, + Flags: []cli.Flag{ + &apiFlag, + &cli.StringFlag{ + Name: "class", + Usage: "class of vector to extract; other required flags depend on the; values: 'message'", + Value: "message", + Destination: &extractFlags.class, + }, + &cli.StringFlag{ + Name: "id", + Usage: "identifier to name this test vector with", + Value: "", + Destination: &extractFlags.id, + }, + &cli.StringFlag{ + Name: "cid", + Usage: "message CID to generate test vector from", + Required: true, + Destination: &extractFlags.cid, + }, + &cli.StringFlag{ + Name: "out", + Aliases: []string{"o"}, + Usage: "file to write test vector to", + Destination: &extractFlags.file, + }, + &cli.StringFlag{ + Name: "state-retain", + Usage: "state retention policy; values: 'accessed-cids', 'accessed-actors'", + Value: "accessed-cids", + Destination: &extractFlags.retain, + }, + }, +} + +func runExtract(_ *cli.Context) error { + // LOTUS_DISABLE_VM_BUF disables what's called "VM state tree buffering", + // which stashes write operations in a BufferedBlockstore + // (https://github.com/filecoin-project/lotus/blob/b7a4dbb07fd8332b4492313a617e3458f8003b2a/lib/bufbstore/buf_bstore.go#L21) + // such that they're not written until the VM is actually flushed. + // + // For some reason, the standard behaviour was not working for me (raulk), + // and disabling it (such that the state transformations are written immediately + // to the blockstore) worked. + _ = os.Setenv("LOTUS_DISABLE_VM_BUF", "iknowitsabadidea") + + ctx := context.Background() + + mcid, err := cid.Decode(extractFlags.cid) + if err != nil { + return err + } + + // Make the API client. + api, closer, err := makeAPIClient() + if err != nil { + return err + } + defer closer() + + log.Printf("locating message with CID: %s", mcid) + + // Locate the message. + msgInfo, err := api.StateSearchMsg(ctx, mcid) + if err != nil { + return fmt.Errorf("failed to locate message: %w", err) + } + + log.Printf("located message at tipset %s (height: %d) with exit code: %s", msgInfo.TipSet, msgInfo.Height, msgInfo.Receipt.ExitCode) + + // Extract the full message. + msg, err := api.ChainGetMessage(ctx, mcid) + if err != nil { + return err + } + + log.Printf("full message: %+v", msg) + + execTs, incTs, err := fetchThisAndPrevTipset(ctx, api, msgInfo.TipSet) + if err != nil { + return err + } + + log.Printf("message was executed in tipset: %s", execTs.Key()) + log.Printf("message was included in tipset: %s", incTs.Key()) + log.Printf("finding precursor messages") + + // Iterate through blocks, finding the one that contains the message and its + // precursors, if any. + var allmsgs []*types.Message + for _, b := range incTs.Blocks() { + messages, err := api.ChainGetBlockMessages(ctx, b.Cid()) + if err != nil { + return err + } + + related, found, err := findMsgAndPrecursors(messages, msg) + if err != nil { + return fmt.Errorf("invariant failed while scanning messages in block %s: %w", b.Cid(), err) + } + + if found { + var mcids []cid.Cid + for _, m := range related { + mcids = append(mcids, m.Cid()) + } + log.Printf("found message in block %s; precursors: %v", b.Cid(), mcids[:len(mcids)-1]) + allmsgs = related + break + } + + log.Printf("message not found in block %s; precursors found: %v; ignoring block", b.Cid(), related) + } + + if allmsgs == nil { + // Message was not found; abort. + return fmt.Errorf("did not find a block containing the message") + } + + precursors := allmsgs[:len(allmsgs)-1] + + var ( + // create a read-through store that uses ChainGetObject to fetch unknown CIDs. + pst = NewProxyingStores(ctx, api) + g = NewSurgeon(ctx, api, pst) + ) + + driver := conformance.NewDriver(ctx, schema.Selector{}) + + // this is the root of the state tree we start with. + root := incTs.ParentState() + log.Printf("base state tree root CID: %s", root) + + // on top of that state tree, we apply all precursors. + log.Printf("number of precursors to apply: %d", len(precursors)) + for i, m := range precursors { + log.Printf("applying precursor %d, cid: %s", i, m.Cid()) + _, root, err = driver.ExecuteMessage(pst.Blockstore, root, execTs.Height(), m) + if err != nil { + return fmt.Errorf("failed to execute precursor message: %w", err) + } + } + + var ( + preroot cid.Cid + postroot cid.Cid + applyret *vm.ApplyRet + carWriter func(w io.Writer) error + retention = extractFlags.retain + ) + + log.Printf("using state retention strategy: %s", retention) + switch retention { + case "accessed-cids": + tbs, ok := pst.Blockstore.(TracingBlockstore) + if !ok { + return fmt.Errorf("requested 'accessed-cids' state retention, but no tracing blockstore was present") + } + + tbs.StartTracing() + + preroot = root + applyret, postroot, err = driver.ExecuteMessage(pst.Blockstore, preroot, execTs.Height(), msg) + if err != nil { + return fmt.Errorf("failed to execute message: %w", err) + } + accessed := tbs.FinishTracing() + carWriter = func(w io.Writer) error { + return g.WriteCARIncluding(w, accessed, preroot, postroot) + } + + case "accessed-actors": + log.Printf("calculating accessed actors") + // get actors accessed by message. + retain, err := g.GetAccessedActors(ctx, api, mcid) + if err != nil { + return fmt.Errorf("failed to calculate accessed actors: %w", err) + } + // also append the reward actor and the burnt funds actor. + retain = append(retain, reward.Address, builtin.BurntFundsActorAddr, init_.Address) + log.Printf("calculated accessed actors: %v", retain) + + // get the masked state tree from the root, + preroot, err = g.GetMaskedStateTree(root, retain) + if err != nil { + return err + } + applyret, postroot, err = driver.ExecuteMessage(pst.Blockstore, preroot, execTs.Height(), msg) + if err != nil { + return fmt.Errorf("failed to execute message: %w", err) + } + carWriter = func(w io.Writer) error { + return g.WriteCAR(w, preroot, postroot) + } + + default: + return fmt.Errorf("unknown state retention option: %s", retention) + } + + msgBytes, err := msg.Serialize() + if err != nil { + return err + } + + var ( + out = new(bytes.Buffer) + gw = gzip.NewWriter(out) + ) + if err := carWriter(gw); err != nil { + return err + } + if err = gw.Flush(); err != nil { + return err + } + if err = gw.Close(); err != nil { + return err + } + + version, err := api.Version(ctx) + if err != nil { + return err + } + + ntwkName, err := api.StateNetworkName(ctx) + if err != nil { + return err + } + + // Write out the test vector. + vector := schema.TestVector{ + Class: schema.ClassMessage, + Meta: &schema.Metadata{ + ID: extractFlags.id, + Gen: []schema.GenerationData{ + {Source: fmt.Sprintf("message:%s:%s", ntwkName, msg.Cid().String())}, + {Source: "github.com/filecoin-project/lotus", Version: version.String()}}, + }, + CAR: out.Bytes(), + Pre: &schema.Preconditions{ + Epoch: int64(execTs.Height()), + StateTree: &schema.StateTree{ + RootCID: preroot, + }, + }, + ApplyMessages: []schema.Message{{Bytes: msgBytes}}, + Post: &schema.Postconditions{ + StateTree: &schema.StateTree{ + RootCID: postroot, + }, + Receipts: []*schema.Receipt{ + { + ExitCode: int64(applyret.ExitCode), + ReturnValue: applyret.Return, + GasUsed: applyret.GasUsed, + }, + }, + }, + } + + output := io.WriteCloser(os.Stdout) + if extractFlags.file != "" { + output, err = os.Create(extractFlags.file) + if err != nil { + return err + } + defer output.Close() + } + + enc := json.NewEncoder(output) + enc.SetIndent("", " ") + if err := enc.Encode(&vector); err != nil { + return err + } + + return nil +} + +// fetchThisAndPrevTipset returns the full tipset identified by the key, as well +// as the previous tipset. In the context of vector generation, the target +// tipset is the one where a message was executed, and the previous tipset is +// the one where the message was included. +func fetchThisAndPrevTipset(ctx context.Context, api api.FullNode, target types.TipSetKey) (targetTs *types.TipSet, prevTs *types.TipSet, err error) { + // get the tipset on which this message was "executed" on. + // https://github.com/filecoin-project/lotus/issues/2847 + targetTs, err = api.ChainGetTipSet(ctx, target) + if err != nil { + return nil, nil, err + } + // get the previous tipset, on which this message was mined, + // i.e. included on-chain. + prevTs, err = api.ChainGetTipSet(ctx, targetTs.Parents()) + if err != nil { + return nil, nil, err + } + return targetTs, prevTs, nil +} + +// findMsgAndPrecursors scans the messages in a block to locate the supplied +// message, looking into the BLS or SECP section depending on the sender's +// address type. +// +// It returns any precursors (if they exist), and the found message (if found), +// in a slice. +// +// It also returns a boolean indicating whether the message was actually found. +// +// This function also asserts invariants, and if those fail, it returns an error. +func findMsgAndPrecursors(messages *api.BlockMessages, target *types.Message) (related []*types.Message, found bool, err error) { + // Decide which block of messages to process, depending on whether the + // sender is a BLS or a SECP account. + input := messages.BlsMessages + if senderKind := target.From.Protocol(); senderKind == address.SECP256K1 { + input = make([]*types.Message, 0, len(messages.SecpkMessages)) + for _, sm := range messages.SecpkMessages { + input = append(input, &sm.Message) + } + } + + for _, other := range input { + if other.From != target.From { + continue + } + + // this message is from the same sender, so it's related. + related = append(related, other) + + if other.Nonce > target.Nonce { + return nil, false, fmt.Errorf("a message with nonce higher than the target was found before the target; offending mcid: %s", other.Cid()) + } + + // this message is the target; we're done. + if other.Cid() == target.Cid() { + return related, true, nil + } + } + + // this could happen because a block contained related messages, but not + // the target (that is, messages with a lower nonce, but ultimately not the + // target). + return related, false, nil +} diff --git a/cmd/tvx/main.go b/cmd/tvx/main.go new file mode 100644 index 000000000..183c2fbe1 --- /dev/null +++ b/cmd/tvx/main.go @@ -0,0 +1,92 @@ +package main + +import ( + "context" + "fmt" + "log" + "net/http" + "os" + "sort" + "strings" + + "github.com/filecoin-project/go-jsonrpc" + "github.com/multiformats/go-multiaddr" + manet "github.com/multiformats/go-multiaddr/net" + + "github.com/urfave/cli/v2" + + "github.com/filecoin-project/lotus/api" + "github.com/filecoin-project/lotus/api/client" +) + +var apiEndpoint string + +var apiFlag = cli.StringFlag{ + Name: "api", + Usage: "json-rpc api endpoint, formatted as token:multiaddr", + EnvVars: []string{"FULLNODE_API_INFO"}, + DefaultText: "", + Destination: &apiEndpoint, +} + +func main() { + app := &cli.App{ + Name: "tvx", + Description: `tvx is a tool for extracting and executing test vectors. It has two subcommands. + + tvx extract extracts a test vector from a live network. It requires access to + a Filecoin client that exposes the standard JSON-RPC API endpoint. Set the API + endpoint on the FULLNODE_API_INFO env variable, or through the --api flag. The + format is token:multiaddr. Only message class test vectors are supported + for now. + + tvx exec executes test vectors against Lotus. Either you can supply one in a + file, or many as an ndjson stdin stream.`, + Usage: "tvx is a tool for extracting and executing test vectors", + Commands: []*cli.Command{ + extractCmd, + execCmd, + }, + } + + sort.Sort(cli.CommandsByName(app.Commands)) + for _, c := range app.Commands { + sort.Sort(cli.FlagsByName(c.Flags)) + } + + if err := app.Run(os.Args); err != nil { + log.Fatal(err) + } +} + +func makeAPIClient() (api.FullNode, jsonrpc.ClientCloser, error) { + sp := strings.SplitN(apiEndpoint, ":", 2) + if len(sp) != 2 { + return nil, nil, fmt.Errorf("invalid api value, missing token or address: %s", apiEndpoint) + } + + token := sp[0] + ma, err := multiaddr.NewMultiaddr(sp[1]) + if err != nil { + return nil, nil, fmt.Errorf("could not parse provided multiaddr: %w", err) + } + + _, dialAddr, err := manet.DialArgs(ma) + if err != nil { + return nil, nil, fmt.Errorf("invalid api multiAddr: %w", err) + } + + var ( + addr = "ws://" + dialAddr + "/rpc/v0" + headers = make(http.Header, 1) + ) + if len(token) != 0 { + headers.Add("Authorization", "Bearer "+token) + } + + node, closer, err := client.NewFullNodeRPC(context.Background(), addr, headers) + if err != nil { + return nil, nil, fmt.Errorf("could not connect to api: %w", err) + } + return node, closer, nil +} diff --git a/cmd/tvx/state.go b/cmd/tvx/state.go new file mode 100644 index 000000000..cef5c5494 --- /dev/null +++ b/cmd/tvx/state.go @@ -0,0 +1,293 @@ +package main + +import ( + "context" + "fmt" + "io" + "log" + + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + "github.com/ipfs/go-cid" + "github.com/ipfs/go-ipld-format" + "github.com/ipld/go-car" + cbg "github.com/whyrusleeping/cbor-gen" + + "github.com/filecoin-project/lotus/api" + init_ "github.com/filecoin-project/lotus/chain/actors/builtin/init" + "github.com/filecoin-project/lotus/chain/state" + "github.com/filecoin-project/lotus/chain/types" + "github.com/filecoin-project/lotus/chain/vm" +) + +// StateSurgeon is an object used to fetch and manipulate state. +type StateSurgeon struct { + ctx context.Context + api api.FullNode + stores *Stores +} + +// NewSurgeon returns a state surgeon, an object used to fetch and manipulate +// state. +func NewSurgeon(ctx context.Context, api api.FullNode, stores *Stores) *StateSurgeon { + return &StateSurgeon{ + ctx: ctx, + api: api, + stores: stores, + } +} + +// GetMaskedStateTree trims the state tree at the supplied tipset to contain +// only the state of the actors in the retain set. It also "dives" into some +// singleton system actors, like the init actor, to trim the state so as to +// compute a minimal state tree. In the future, thid method will dive into +// other system actors like the power actor and the market actor. +func (sg *StateSurgeon) GetMaskedStateTree(previousRoot cid.Cid, retain []address.Address) (cid.Cid, error) { + // TODO: this will need to be parameterized on network version. + st, err := state.LoadStateTree(sg.stores.CBORStore, previousRoot) + if err != nil { + return cid.Undef, err + } + + initActor, initState, err := sg.loadInitActor(st) + if err != nil { + return cid.Undef, err + } + + err = sg.retainInitEntries(initState, retain) + if err != nil { + return cid.Undef, err + } + + err = sg.saveInitActor(initActor, initState, st) + if err != nil { + return cid.Undef, err + } + + // resolve all addresses to ID addresses. + resolved, err := sg.resolveAddresses(retain, initState) + if err != nil { + return cid.Undef, err + } + + st, err = sg.transplantActors(st, resolved) + if err != nil { + return cid.Undef, err + } + + root, err := st.Flush(sg.ctx) + if err != nil { + return cid.Undef, err + } + + return root, nil +} + +// GetAccessedActors identifies the actors that were accessed during the +// execution of a message. +func (sg *StateSurgeon) GetAccessedActors(ctx context.Context, a api.FullNode, mid cid.Cid) ([]address.Address, error) { + log.Printf("calculating accessed actors during execution of message: %s", mid) + msgInfo, err := a.StateSearchMsg(ctx, mid) + if err != nil { + return nil, err + } + if msgInfo == nil { + return nil, fmt.Errorf("message info is nil") + } + + msgObj, err := a.ChainGetMessage(ctx, mid) + if err != nil { + return nil, err + } + + ts, err := a.ChainGetTipSet(ctx, msgInfo.TipSet) + if err != nil { + return nil, err + } + + trace, err := a.StateCall(ctx, msgObj, ts.Parents()) + if err != nil { + return nil, fmt.Errorf("could not replay msg: %w", err) + } + + accessed := make(map[address.Address]struct{}) + + var recur func(trace *types.ExecutionTrace) + recur = func(trace *types.ExecutionTrace) { + accessed[trace.Msg.To] = struct{}{} + accessed[trace.Msg.From] = struct{}{} + for _, s := range trace.Subcalls { + recur(&s) + } + } + recur(&trace.ExecutionTrace) + + ret := make([]address.Address, 0, len(accessed)) + for k := range accessed { + ret = append(ret, k) + } + + return ret, nil +} + +// WriteCAR recursively writes the tree referenced by the root as a CAR into the +// supplied io.Writer. +func (sg *StateSurgeon) WriteCAR(w io.Writer, roots ...cid.Cid) error { + carWalkFn := func(nd format.Node) (out []*format.Link, err error) { + for _, link := range nd.Links() { + if link.Cid.Prefix().Codec == cid.FilCommitmentSealed || link.Cid.Prefix().Codec == cid.FilCommitmentUnsealed { + continue + } + out = append(out, link) + } + return out, nil + } + return car.WriteCarWithWalker(sg.ctx, sg.stores.DAGService, roots, w, carWalkFn) +} + +// WriteCARIncluding writes a CAR including only the CIDs that are listed in +// the include set. This leads to an intentially sparse tree with dangling links. +func (sg *StateSurgeon) WriteCARIncluding(w io.Writer, include map[cid.Cid]struct{}, roots ...cid.Cid) error { + carWalkFn := func(nd format.Node) (out []*format.Link, err error) { + for _, link := range nd.Links() { + if _, ok := include[link.Cid]; !ok { + continue + } + if link.Cid.Prefix().Codec == cid.FilCommitmentSealed || link.Cid.Prefix().Codec == cid.FilCommitmentUnsealed { + continue + } + out = append(out, link) + } + return out, nil + } + return car.WriteCarWithWalker(sg.ctx, sg.stores.DAGService, roots, w, carWalkFn) +} + +// transplantActors plucks the state from the supplied actors at the given +// tipset, and places it into the supplied state map. +func (sg *StateSurgeon) transplantActors(src *state.StateTree, pluck []address.Address) (*state.StateTree, error) { + log.Printf("transplanting actor states: %v", pluck) + + dst, err := state.NewStateTree(sg.stores.CBORStore, src.Version()) + if err != nil { + return nil, err + } + + for _, a := range pluck { + actor, err := src.GetActor(a) + if err != nil { + return nil, fmt.Errorf("get actor %s failed: %w", a, err) + } + + err = dst.SetActor(a, actor) + if err != nil { + return nil, err + } + + // recursive copy of the actor state. + err = vm.Copy(context.TODO(), sg.stores.Blockstore, sg.stores.Blockstore, actor.Head) + if err != nil { + return nil, err + } + + actorState, err := sg.api.ChainReadObj(sg.ctx, actor.Head) + if err != nil { + return nil, err + } + + cid, err := sg.stores.CBORStore.Put(sg.ctx, &cbg.Deferred{Raw: actorState}) + if err != nil { + return nil, err + } + + if cid != actor.Head { + panic("mismatched cids") + } + } + + return dst, nil +} + +// saveInitActor saves the state of the init actor to the provided state map. +func (sg *StateSurgeon) saveInitActor(initActor *types.Actor, initState init_.State, st *state.StateTree) error { + log.Printf("saving init actor into state tree") + + // Store the state of the init actor. + cid, err := sg.stores.CBORStore.Put(sg.ctx, initState) + if err != nil { + return err + } + actor := *initActor + actor.Head = cid + + err = st.SetActor(init_.Address, &actor) + if err != nil { + return err + } + + cid, _ = st.Flush(sg.ctx) + log.Printf("saved init actor into state tree; new root: %s", cid) + return nil +} + +// retainInitEntries takes an old init actor state, and retains only the +// entries in the retain set, returning a new init actor state. +func (sg *StateSurgeon) retainInitEntries(state init_.State, retain []address.Address) error { + log.Printf("retaining init actor entries for addresses: %v", retain) + + m := make(map[address.Address]struct{}, len(retain)) + for _, a := range retain { + m[a] = struct{}{} + } + + var remove []address.Address + _ = state.ForEachActor(func(id abi.ActorID, address address.Address) error { + if _, ok := m[address]; !ok { + remove = append(remove, address) + } + return nil + }) + + err := state.Remove(remove...) + log.Printf("new init actor state: %+v", state) + return err +} + +// resolveAddresses resolved the requested addresses from the provided +// InitActor state, returning a slice of length len(orig), where each index +// contains the resolved address. +func (sg *StateSurgeon) resolveAddresses(orig []address.Address, ist init_.State) (ret []address.Address, err error) { + log.Printf("resolving addresses: %v", orig) + + ret = make([]address.Address, len(orig)) + for i, addr := range orig { + resolved, found, err := ist.ResolveAddress(addr) + if err != nil { + return nil, err + } + if !found { + return nil, fmt.Errorf("address not found: %s", addr) + } + ret[i] = resolved + } + + log.Printf("resolved addresses: %v", ret) + return ret, nil +} + +// loadInitActor loads the init actor state from a given tipset. +func (sg *StateSurgeon) loadInitActor(st *state.StateTree) (*types.Actor, init_.State, error) { + actor, err := st.GetActor(init_.Address) + if err != nil { + return nil, nil, err + } + + initState, err := init_.Load(sg.stores.ADTStore, actor) + if err != nil { + return nil, nil, err + } + + log.Printf("loaded init actor state: %+v", initState) + + return actor, initState, nil +} diff --git a/cmd/tvx/stores.go b/cmd/tvx/stores.go new file mode 100644 index 000000000..7d3fd5e3a --- /dev/null +++ b/cmd/tvx/stores.go @@ -0,0 +1,143 @@ +package main + +import ( + "context" + "log" + "sync" + + "github.com/fatih/color" + + "github.com/filecoin-project/lotus/api" + "github.com/filecoin-project/lotus/lib/blockstore" + + "github.com/filecoin-project/specs-actors/actors/util/adt" + + blocks "github.com/ipfs/go-block-format" + "github.com/ipfs/go-blockservice" + "github.com/ipfs/go-cid" + ds "github.com/ipfs/go-datastore" + exchange "github.com/ipfs/go-ipfs-exchange-interface" + offline "github.com/ipfs/go-ipfs-exchange-offline" + cbor "github.com/ipfs/go-ipld-cbor" + format "github.com/ipfs/go-ipld-format" + "github.com/ipfs/go-merkledag" +) + +// Stores is a collection of the different stores and services that are needed +// to deal with the data layer of Filecoin, conveniently interlinked with one +// another. +type Stores struct { + CBORStore cbor.IpldStore + ADTStore adt.Store + Datastore ds.Batching + Blockstore blockstore.Blockstore + BlockService blockservice.BlockService + Exchange exchange.Interface + DAGService format.DAGService +} + +// NewProxyingStores is a set of Stores backed by a proxying Blockstore that +// proxies Get requests for unknown CIDs to a Filecoin node, via the +// ChainReadObj RPC. +func NewProxyingStores(ctx context.Context, api api.FullNode) *Stores { + ds := ds.NewMapDatastore() + + bs := &proxyingBlockstore{ + ctx: ctx, + api: api, + Blockstore: blockstore.NewBlockstore(ds), + } + + return NewStores(ctx, ds, bs) +} + +// NewStores creates a non-proxying set of Stores. +func NewStores(ctx context.Context, ds ds.Batching, bs blockstore.Blockstore) *Stores { + var ( + cborstore = cbor.NewCborStore(bs) + offl = offline.Exchange(bs) + blkserv = blockservice.New(bs, offl) + dserv = merkledag.NewDAGService(blkserv) + ) + + return &Stores{ + CBORStore: cborstore, + ADTStore: adt.WrapStore(ctx, cborstore), + Datastore: ds, + Blockstore: bs, + Exchange: offl, + BlockService: blkserv, + DAGService: dserv, + } +} + +// TracingBlockstore is a Blockstore trait that records CIDs that were accessed +// through Get. +type TracingBlockstore interface { + // StartTracing starts tracing CIDs accessed through the this Blockstore. + StartTracing() + + // FinishTracing finishes tracing accessed CIDs, and returns a map of the + // CIDs that were traced. + FinishTracing() map[cid.Cid]struct{} +} + +// proxyingBlockstore is a Blockstore wrapper that fetches unknown CIDs from +// a Filecoin node via JSON-RPC. +type proxyingBlockstore struct { + ctx context.Context + api api.FullNode + + lk sync.RWMutex + tracing bool + traced map[cid.Cid]struct{} + + blockstore.Blockstore +} + +var _ TracingBlockstore = (*proxyingBlockstore)(nil) + +func (pb *proxyingBlockstore) StartTracing() { + pb.lk.Lock() + pb.tracing = true + pb.traced = map[cid.Cid]struct{}{} + pb.lk.Unlock() +} + +func (pb *proxyingBlockstore) FinishTracing() map[cid.Cid]struct{} { + pb.lk.Lock() + ret := pb.traced + pb.tracing = false + pb.traced = map[cid.Cid]struct{}{} + pb.lk.Unlock() + return ret +} + +func (pb *proxyingBlockstore) Get(cid cid.Cid) (blocks.Block, error) { + pb.lk.RLock() + if pb.tracing { + pb.traced[cid] = struct{}{} + } + pb.lk.RUnlock() + + if block, err := pb.Blockstore.Get(cid); err == nil { + return block, err + } + + log.Println(color.CyanString("fetching cid via rpc: %v", cid)) + item, err := pb.api.ChainReadObj(pb.ctx, cid) + if err != nil { + return nil, err + } + block, err := blocks.NewBlockWithCid(item, cid) + if err != nil { + return nil, err + } + + err = pb.Blockstore.Put(block) + if err != nil { + return nil, err + } + + return block, nil +} diff --git a/conformance/corpus_test.go b/conformance/corpus_test.go new file mode 100644 index 000000000..3d447570d --- /dev/null +++ b/conformance/corpus_test.go @@ -0,0 +1,133 @@ +package conformance + +import ( + "encoding/json" + "io/ioutil" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/filecoin-project/test-vectors/schema" +) + +const ( + // EnvSkipConformance, if 1, skips the conformance test suite. + EnvSkipConformance = "SKIP_CONFORMANCE" + + // EnvCorpusRootDir is the name of the environment variable where the path + // to an alternative corpus location can be provided. + // + // The default is defaultCorpusRoot. + EnvCorpusRootDir = "CORPUS_DIR" + + // defaultCorpusRoot is the directory where the test vector corpus is hosted. + // It is mounted on the Lotus repo as a git submodule. + // + // When running this test, the corpus root can be overridden through the + // -conformance.corpus CLI flag to run an alternate corpus. + defaultCorpusRoot = "../extern/test-vectors/corpus" +) + +// ignore is a set of paths relative to root to skip. +var ignore = map[string]struct{}{ + ".git": {}, + "schema.json": {}, +} + +// TestConformance is the entrypoint test that runs all test vectors found +// in the corpus root directory. +// +// It locates all json files via a recursive walk, skipping over the ignore set, +// as well as files beginning with _. It parses each file as a test vector, and +// runs it via the Driver. +func TestConformance(t *testing.T) { + if skip := strings.TrimSpace(os.Getenv(EnvSkipConformance)); skip == "1" { + t.SkipNow() + } + // corpusRoot is the effective corpus root path, taken from the `-conformance.corpus` CLI flag, + // falling back to defaultCorpusRoot if not provided. + corpusRoot := defaultCorpusRoot + if dir := strings.TrimSpace(os.Getenv(EnvCorpusRootDir)); dir != "" { + corpusRoot = dir + } + + var vectors []string + err := filepath.Walk(corpusRoot+"/", func(path string, info os.FileInfo, err error) error { + if err != nil { + t.Fatal(err) + } + + filename := filepath.Base(path) + rel, err := filepath.Rel(corpusRoot, path) + if err != nil { + t.Fatal(err) + } + + if _, ok := ignore[rel]; ok { + // skip over using the right error. + if info.IsDir() { + return filepath.SkipDir + } + return nil + } + if info.IsDir() { + // dive into directories. + return nil + } + if filepath.Ext(path) != ".json" { + // skip if not .json. + return nil + } + if ignored := strings.HasPrefix(filename, "_"); ignored { + // ignore files starting with _. + t.Logf("ignoring: %s", rel) + return nil + } + vectors = append(vectors, rel) + return nil + }) + + if err != nil { + t.Fatal(err) + } + + if len(vectors) == 0 { + t.Fatalf("no test vectors found") + } + + // Run a test for each vector. + for _, v := range vectors { + path := filepath.Join(corpusRoot, v) + raw, err := ioutil.ReadFile(path) + if err != nil { + t.Fatalf("failed to read test raw file: %s", path) + } + + var vector schema.TestVector + err = json.Unmarshal(raw, &vector) + if err != nil { + t.Errorf("failed to parse test vector %s: %s; skipping", path, err) + continue + } + + t.Run(v, func(t *testing.T) { + for _, h := range vector.Hints { + if h == schema.HintIncorrect { + t.Logf("skipping vector marked as incorrect: %s", vector.Meta.ID) + t.SkipNow() + } + } + + // dispatch the execution depending on the vector class. + switch vector.Class { + case "message": + ExecuteMessageVector(t, &vector) + case "tipset": + ExecuteTipsetVector(t, &vector) + default: + t.Fatalf("test vector class not supported: %s", vector.Class) + } + }) + } +} diff --git a/conformance/driver.go b/conformance/driver.go index f43a8739d..ee9727cae 100644 --- a/conformance/driver.go +++ b/conformance/driver.go @@ -5,6 +5,7 @@ import ( "github.com/filecoin-project/go-state-types/crypto" + "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/stmgr" "github.com/filecoin-project/lotus/chain/store" "github.com/filecoin-project/lotus/chain/types" @@ -154,7 +155,12 @@ func (d *Driver) ExecuteMessage(bs blockstore.Blockstore, preroot cid.Cid, epoch return nil, cid.Undef, err } - root, err := lvm.Flush(d.ctx) + // do not flush the VM, as this forces a recursive copy to the blockstore, + // walking the full state tree, which we don't require. + // root, err := lvm.Flush(d.ctx) + // + // instead, flush the pending writes on the state tree. + root, err := lvm.StateTree().(*state.StateTree).Flush(d.ctx) return ret, root, err } diff --git a/conformance/reporter.go b/conformance/reporter.go new file mode 100644 index 000000000..747caae32 --- /dev/null +++ b/conformance/reporter.go @@ -0,0 +1,62 @@ +package conformance + +import ( + "log" + "os" + "sync/atomic" + "testing" + + "github.com/fatih/color" +) + +// Reporter is a contains a subset of the testing.T methods, so that the +// Execute* functions in this package can be used inside or outside of +// go test runs. +type Reporter interface { + Helper() + + Log(args ...interface{}) + Errorf(format string, args ...interface{}) + Fatalf(format string, args ...interface{}) + Logf(format string, args ...interface{}) + FailNow() + Failed() bool +} + +var _ Reporter = (*testing.T)(nil) + +// LogReporter wires the Reporter methods to the log package. It is appropriate +// to use when calling the Execute* functions from a standalone CLI program. +type LogReporter struct { + failed int32 +} + +var _ Reporter = (*LogReporter)(nil) + +func (_ *LogReporter) Helper() {} + +func (_ *LogReporter) Log(args ...interface{}) { + log.Println(args...) +} + +func (_ *LogReporter) Logf(format string, args ...interface{}) { + log.Printf(format, args...) +} + +func (_ *LogReporter) FailNow() { + os.Exit(1) +} + +func (l *LogReporter) Failed() bool { + return atomic.LoadInt32(&l.failed) == 1 +} + +func (l *LogReporter) Errorf(format string, args ...interface{}) { + atomic.StoreInt32(&l.failed, 1) + log.Println(color.HiRedString("❌ "+format, args...)) +} + +func (l *LogReporter) Fatalf(format string, args ...interface{}) { + atomic.StoreInt32(&l.failed, 1) + log.Fatal(color.HiRedString("❌ "+format, args...)) +} diff --git a/conformance/runner.go b/conformance/runner.go new file mode 100644 index 000000000..1fc1c1425 --- /dev/null +++ b/conformance/runner.go @@ -0,0 +1,253 @@ +package conformance + +import ( + "bytes" + "compress/gzip" + "context" + "encoding/base64" + "fmt" + "io/ioutil" + "os" + "os/exec" + "strconv" + + "github.com/fatih/color" + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/exitcode" + "github.com/filecoin-project/test-vectors/schema" + "github.com/ipfs/go-blockservice" + "github.com/ipfs/go-cid" + ds "github.com/ipfs/go-datastore" + offline "github.com/ipfs/go-ipfs-exchange-offline" + format "github.com/ipfs/go-ipld-format" + "github.com/ipfs/go-merkledag" + "github.com/ipld/go-car" + + "github.com/filecoin-project/lotus/chain/types" + "github.com/filecoin-project/lotus/chain/vm" + "github.com/filecoin-project/lotus/lib/blockstore" +) + +// ExecuteMessageVector executes a message-class test vector. +func ExecuteMessageVector(r Reporter, vector *schema.TestVector) { + var ( + ctx = context.Background() + epoch = vector.Pre.Epoch + root = vector.Pre.StateTree.RootCID + ) + + // Load the CAR into a new temporary Blockstore. + bs, err := LoadVectorCAR(vector.CAR) + if err != nil { + r.Fatalf("failed to load the vector CAR: %w", err) + } + + // Create a new Driver. + driver := NewDriver(ctx, vector.Selector) + + // Apply every message. + for i, m := range vector.ApplyMessages { + msg, err := types.DecodeMessage(m.Bytes) + if err != nil { + r.Fatalf("failed to deserialize message: %s", err) + } + + // add an epoch if one's set. + if m.Epoch != nil { + epoch = *m.Epoch + } + + // Execute the message. + var ret *vm.ApplyRet + ret, root, err = driver.ExecuteMessage(bs, root, abi.ChainEpoch(epoch), msg) + if err != nil { + r.Fatalf("fatal failure when executing message: %s", err) + } + + // Assert that the receipt matches what the test vector expects. + assertMsgResult(r, vector.Post.Receipts[i], ret, strconv.Itoa(i)) + } + + // Once all messages are applied, assert that the final state root matches + // the expected postcondition root. + if expected, actual := vector.Post.StateTree.RootCID, root; expected != actual { + r.Errorf("wrong post root cid; expected %v, but got %v", expected, actual) + dumpThreeWayStateDiff(r, vector, bs, root) + r.FailNow() + } +} + +// ExecuteTipsetVector executes a tipset-class test vector. +func ExecuteTipsetVector(r Reporter, vector *schema.TestVector) { + var ( + ctx = context.Background() + prevEpoch = vector.Pre.Epoch + root = vector.Pre.StateTree.RootCID + tmpds = ds.NewMapDatastore() + ) + + // Load the vector CAR into a new temporary Blockstore. + bs, err := LoadVectorCAR(vector.CAR) + if err != nil { + r.Fatalf("failed to load the vector CAR: %w", err) + } + + // Create a new Driver. + driver := NewDriver(ctx, vector.Selector) + + // Apply every tipset. + var receiptsIdx int + for i, ts := range vector.ApplyTipsets { + ts := ts // capture + ret, err := driver.ExecuteTipset(bs, tmpds, root, abi.ChainEpoch(prevEpoch), &ts) + if err != nil { + r.Fatalf("failed to apply tipset %d message: %s", i, err) + } + + for j, v := range ret.AppliedResults { + assertMsgResult(r, vector.Post.Receipts[receiptsIdx], v, fmt.Sprintf("%d of tipset %d", j, i)) + receiptsIdx++ + } + + // Compare the receipts root. + if expected, actual := vector.Post.ReceiptsRoots[i], ret.ReceiptsRoot; expected != actual { + r.Errorf("post receipts root doesn't match; expected: %s, was: %s", expected, actual) + } + + prevEpoch = ts.Epoch + root = ret.PostStateRoot + } + + // Once all messages are applied, assert that the final state root matches + // the expected postcondition root. + if expected, actual := vector.Post.StateTree.RootCID, root; expected != actual { + r.Errorf("wrong post root cid; expected %v, but got %v", expected, actual) + dumpThreeWayStateDiff(r, vector, bs, root) + r.FailNow() + } +} + +// assertMsgResult compares a message result. It takes the expected receipt +// encoded in the vector, the actual receipt returned by Lotus, and a message +// label to log in the assertion failure message to facilitate debugging. +func assertMsgResult(r Reporter, expected *schema.Receipt, actual *vm.ApplyRet, label string) { + r.Helper() + + if expected, actual := exitcode.ExitCode(expected.ExitCode), actual.ExitCode; expected != actual { + r.Errorf("exit code of msg %s did not match; expected: %s, got: %s", label, expected, actual) + } + if expected, actual := expected.GasUsed, actual.GasUsed; expected != actual { + r.Errorf("gas used of msg %s did not match; expected: %d, got: %d", label, expected, actual) + } + if expected, actual := []byte(expected.ReturnValue), actual.Return; !bytes.Equal(expected, actual) { + r.Errorf("return value of msg %s did not match; expected: %s, got: %s", label, base64.StdEncoding.EncodeToString(expected), base64.StdEncoding.EncodeToString(actual)) + } +} + +func dumpThreeWayStateDiff(r Reporter, vector *schema.TestVector, bs blockstore.Blockstore, actual cid.Cid) { + // check if statediff exists; if not, skip. + if err := exec.Command("statediff", "--help").Run(); err != nil { + r.Log("could not dump 3-way state tree diff upon test failure: statediff command not found") + r.Log("install statediff with:") + r.Log("$ git clone https://github.com/filecoin-project/statediff.git") + r.Log("$ cd statediff") + r.Log("$ go generate ./...") + r.Log("$ go install ./cmd/statediff") + return + } + + tmpCar, err := writeStateToTempCAR(bs, + vector.Pre.StateTree.RootCID, + vector.Post.StateTree.RootCID, + actual, + ) + if err != nil { + r.Fatalf("failed to write temporary state CAR: %s", err) + } + defer os.RemoveAll(tmpCar) + + color.NoColor = false // enable colouring. + + var ( + a = color.New(color.FgMagenta, color.Bold).Sprint("(A) expected final state") + b = color.New(color.FgYellow, color.Bold).Sprint("(B) actual final state") + c = color.New(color.FgCyan, color.Bold).Sprint("(C) initial state") + d1 = color.New(color.FgGreen, color.Bold).Sprint("[Δ1]") + d2 = color.New(color.FgGreen, color.Bold).Sprint("[Δ2]") + d3 = color.New(color.FgGreen, color.Bold).Sprint("[Δ3]") + ) + + printDiff := func(left, right cid.Cid) { + cmd := exec.Command("statediff", "car", "--file", tmpCar, left.String(), right.String()) + b, err := cmd.CombinedOutput() + if err != nil { + r.Fatalf("statediff failed: %s", err) + } + r.Log(string(b)) + } + + bold := color.New(color.Bold).SprintfFunc() + + // run state diffs. + r.Log(bold("=== dumping 3-way diffs between %s, %s, %s ===", a, b, c)) + + r.Log(bold("--- %s left: %s; right: %s ---", d1, a, b)) + printDiff(vector.Post.StateTree.RootCID, actual) + + r.Log(bold("--- %s left: %s; right: %s ---", d2, c, b)) + printDiff(vector.Pre.StateTree.RootCID, actual) + + r.Log(bold("--- %s left: %s; right: %s ---", d3, c, a)) + printDiff(vector.Pre.StateTree.RootCID, vector.Post.StateTree.RootCID) +} + +// writeStateToTempCAR writes the provided roots to a temporary CAR that'll be +// cleaned up via t.Cleanup(). It returns the full path of the temp file. +func writeStateToTempCAR(bs blockstore.Blockstore, roots ...cid.Cid) (string, error) { + tmp, err := ioutil.TempFile("", "lotus-tests-*.car") + if err != nil { + return "", fmt.Errorf("failed to create temp file to dump CAR for diffing: %w", err) + } + + carWalkFn := func(nd format.Node) (out []*format.Link, err error) { + for _, link := range nd.Links() { + if link.Cid.Prefix().Codec == cid.FilCommitmentSealed || link.Cid.Prefix().Codec == cid.FilCommitmentUnsealed { + continue + } + out = append(out, link) + } + return out, nil + } + + var ( + offl = offline.Exchange(bs) + blkserv = blockservice.New(bs, offl) + dserv = merkledag.NewDAGService(blkserv) + ) + + err = car.WriteCarWithWalker(context.Background(), dserv, roots, tmp, carWalkFn) + if err != nil { + return "", fmt.Errorf("failed to dump CAR for diffing: %w", err) + } + _ = tmp.Close() + return tmp.Name(), nil +} + +func LoadVectorCAR(vectorCAR schema.Base64EncodedBytes) (blockstore.Blockstore, error) { + bs := blockstore.NewTemporary() + + // Read the base64-encoded CAR from the vector, and inflate the gzip. + buf := bytes.NewReader(vectorCAR) + r, err := gzip.NewReader(buf) + if err != nil { + return nil, fmt.Errorf("failed to inflate gzipped CAR: %s", err) + } + defer r.Close() // nolint + + // Load the CAR embedded in the test vector into the Blockstore. + _, err = car.LoadCar(bs, r) + if err != nil { + return nil, fmt.Errorf("failed to load state tree car from test vector: %s", err) + } + return bs, nil +} diff --git a/conformance/runner_test.go b/conformance/runner_test.go deleted file mode 100644 index cc7ef6b3d..000000000 --- a/conformance/runner_test.go +++ /dev/null @@ -1,376 +0,0 @@ -package conformance - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "encoding/json" - "fmt" - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "strconv" - "strings" - "testing" - - "github.com/filecoin-project/go-state-types/abi" - "github.com/filecoin-project/go-state-types/exitcode" - "github.com/ipfs/go-blockservice" - "github.com/ipfs/go-cid" - ds "github.com/ipfs/go-datastore" - offline "github.com/ipfs/go-ipfs-exchange-offline" - format "github.com/ipfs/go-ipld-format" - "github.com/ipfs/go-merkledag" - - "github.com/filecoin-project/lotus/chain/types" - "github.com/filecoin-project/lotus/chain/vm" - "github.com/filecoin-project/lotus/lib/blockstore" - - "github.com/filecoin-project/test-vectors/schema" - - "github.com/fatih/color" - "github.com/ipld/go-car" -) - -const ( - // EnvSkipConformance, if 1, skips the conformance test suite. - EnvSkipConformance = "SKIP_CONFORMANCE" - - // EnvCorpusRootDir is the name of the environment variable where the path - // to an alternative corpus location can be provided. - // - // The default is defaultCorpusRoot. - EnvCorpusRootDir = "CORPUS_DIR" - - // defaultCorpusRoot is the directory where the test vector corpus is hosted. - // It is mounted on the Lotus repo as a git submodule. - // - // When running this test, the corpus root can be overridden through the - // -conformance.corpus CLI flag to run an alternate corpus. - defaultCorpusRoot = "../extern/test-vectors/corpus" -) - -// ignore is a set of paths relative to root to skip. -var ignore = map[string]struct{}{ - ".git": {}, - "schema.json": {}, -} - -// TestConformance is the entrypoint test that runs all test vectors found -// in the corpus root directory. -// -// It locates all json files via a recursive walk, skipping over the ignore set, -// as well as files beginning with _. It parses each file as a test vector, and -// runs it via the Driver. -func TestConformance(t *testing.T) { - if skip := strings.TrimSpace(os.Getenv(EnvSkipConformance)); skip == "1" { - t.SkipNow() - } - // corpusRoot is the effective corpus root path, taken from the `-conformance.corpus` CLI flag, - // falling back to defaultCorpusRoot if not provided. - corpusRoot := defaultCorpusRoot - if dir := strings.TrimSpace(os.Getenv(EnvCorpusRootDir)); dir != "" { - corpusRoot = dir - } - - var vectors []string - err := filepath.Walk(corpusRoot+"/", func(path string, info os.FileInfo, err error) error { - if err != nil { - t.Fatal(err) - } - - filename := filepath.Base(path) - rel, err := filepath.Rel(corpusRoot, path) - if err != nil { - t.Fatal(err) - } - - if _, ok := ignore[rel]; ok { - // skip over using the right error. - if info.IsDir() { - return filepath.SkipDir - } - return nil - } - if info.IsDir() { - // dive into directories. - return nil - } - if filepath.Ext(path) != ".json" { - // skip if not .json. - return nil - } - if ignored := strings.HasPrefix(filename, "_"); ignored { - // ignore files starting with _. - t.Logf("ignoring: %s", rel) - return nil - } - vectors = append(vectors, rel) - return nil - }) - - if err != nil { - t.Fatal(err) - } - - if len(vectors) == 0 { - t.Fatalf("no test vectors found") - } - - // Run a test for each vector. - for _, v := range vectors { - path := filepath.Join(corpusRoot, v) - raw, err := ioutil.ReadFile(path) - if err != nil { - t.Fatalf("failed to read test raw file: %s", path) - } - - var vector schema.TestVector - err = json.Unmarshal(raw, &vector) - if err != nil { - t.Errorf("failed to parse test vector %s: %s; skipping", path, err) - continue - } - - t.Run(v, func(t *testing.T) { - for _, h := range vector.Hints { - if h == schema.HintIncorrect { - t.Logf("skipping vector marked as incorrect: %s", vector.Meta.ID) - t.SkipNow() - } - } - - // dispatch the execution depending on the vector class. - switch vector.Class { - case "message": - executeMessageVector(t, &vector) - case "tipset": - executeTipsetVector(t, &vector) - default: - t.Fatalf("test vector class not supported: %s", vector.Class) - } - }) - } -} - -// executeMessageVector executes a message-class test vector. -func executeMessageVector(t *testing.T, vector *schema.TestVector) { - var ( - ctx = context.Background() - epoch = vector.Pre.Epoch - root = vector.Pre.StateTree.RootCID - ) - - // Load the CAR into a new temporary Blockstore. - bs := loadCAR(t, vector.CAR) - - // Create a new Driver. - driver := NewDriver(ctx, vector.Selector) - - // Apply every message. - for i, m := range vector.ApplyMessages { - msg, err := types.DecodeMessage(m.Bytes) - if err != nil { - t.Fatalf("failed to deserialize message: %s", err) - } - - // add an epoch if one's set. - if m.Epoch != nil { - epoch = *m.Epoch - } - - // Execute the message. - var ret *vm.ApplyRet - ret, root, err = driver.ExecuteMessage(bs, root, abi.ChainEpoch(epoch), msg) - if err != nil { - t.Fatalf("fatal failure when executing message: %s", err) - } - - // Assert that the receipt matches what the test vector expects. - assertMsgResult(t, vector.Post.Receipts[i], ret, strconv.Itoa(i)) - } - - // Once all messages are applied, assert that the final state root matches - // the expected postcondition root. - if expected, actual := vector.Post.StateTree.RootCID, root; expected != actual { - t.Logf("actual state root CID doesn't match expected one; expected: %s, actual: %s", expected, actual) - dumpThreeWayStateDiff(t, vector, bs, root) - t.FailNow() - } -} - -// executeTipsetVector executes a tipset-class test vector. -func executeTipsetVector(t *testing.T, vector *schema.TestVector) { - var ( - ctx = context.Background() - prevEpoch = vector.Pre.Epoch - root = vector.Pre.StateTree.RootCID - tmpds = ds.NewMapDatastore() - ) - - // Load the CAR into a new temporary Blockstore. - bs := loadCAR(t, vector.CAR) - - // Create a new Driver. - driver := NewDriver(ctx, vector.Selector) - - // Apply every tipset. - var receiptsIdx int - for i, ts := range vector.ApplyTipsets { - ts := ts // capture - ret, err := driver.ExecuteTipset(bs, tmpds, root, abi.ChainEpoch(prevEpoch), &ts) - if err != nil { - t.Fatalf("failed to apply tipset %d message: %s", i, err) - } - - for j, v := range ret.AppliedResults { - assertMsgResult(t, vector.Post.Receipts[receiptsIdx], v, fmt.Sprintf("%d of tipset %d", j, i)) - receiptsIdx++ - } - - // Compare the receipts root. - if expected, actual := vector.Post.ReceiptsRoots[i], ret.ReceiptsRoot; expected != actual { - t.Errorf("post receipts root doesn't match; expected: %s, was: %s", expected, actual) - } - - prevEpoch = ts.Epoch - root = ret.PostStateRoot - } - - // Once all messages are applied, assert that the final state root matches - // the expected postcondition root. - if expected, actual := vector.Post.StateTree.RootCID, root; expected != actual { - t.Logf("actual state root CID doesn't match expected one; expected: %s, actual: %s", expected, actual) - dumpThreeWayStateDiff(t, vector, bs, root) - t.FailNow() - } -} - -// assertMsgResult compares a message result. It takes the expected receipt -// encoded in the vector, the actual receipt returned by Lotus, and a message -// label to log in the assertion failure message to facilitate debugging. -func assertMsgResult(t *testing.T, expected *schema.Receipt, actual *vm.ApplyRet, label string) { - t.Helper() - - if expected, actual := exitcode.ExitCode(expected.ExitCode), actual.ExitCode; expected != actual { - t.Errorf("exit code of msg %s did not match; expected: %s, got: %s", label, expected, actual) - } - if expected, actual := expected.GasUsed, actual.GasUsed; expected != actual { - t.Errorf("gas used of msg %s did not match; expected: %d, got: %d", label, expected, actual) - } - if expected, actual := []byte(expected.ReturnValue), actual.Return; !bytes.Equal(expected, actual) { - t.Errorf("return value of msg %s did not match; expected: %s, got: %s", label, base64.StdEncoding.EncodeToString(expected), base64.StdEncoding.EncodeToString(actual)) - } -} - -func dumpThreeWayStateDiff(t *testing.T, vector *schema.TestVector, bs blockstore.Blockstore, actual cid.Cid) { - // check if statediff exists; if not, skip. - if err := exec.Command("statediff", "--help").Run(); err != nil { - t.Log("could not dump 3-way state tree diff upon test failure: statediff command not found") - t.Log("install statediff with:") - t.Log("$ git clone https://github.com/filecoin-project/statediff.git") - t.Log("$ cd statediff") - t.Log("$ go generate ./...") - t.Log("$ go install ./cmd/statediff") - return - } - - tmpCar := writeStateToTempCAR(t, bs, - vector.Pre.StateTree.RootCID, - vector.Post.StateTree.RootCID, - actual, - ) - - color.NoColor = false // enable colouring. - - t.Errorf("wrong post root cid; expected %v, but got %v", vector.Post.StateTree.RootCID, actual) - - var ( - a = color.New(color.FgMagenta, color.Bold).Sprint("(A) expected final state") - b = color.New(color.FgYellow, color.Bold).Sprint("(B) actual final state") - c = color.New(color.FgCyan, color.Bold).Sprint("(C) initial state") - d1 = color.New(color.FgGreen, color.Bold).Sprint("[Δ1]") - d2 = color.New(color.FgGreen, color.Bold).Sprint("[Δ2]") - d3 = color.New(color.FgGreen, color.Bold).Sprint("[Δ3]") - ) - - printDiff := func(left, right cid.Cid) { - cmd := exec.Command("statediff", "car", "--file", tmpCar, left.String(), right.String()) - b, err := cmd.CombinedOutput() - if err != nil { - t.Fatalf("statediff failed: %s", err) - } - t.Log(string(b)) - } - - bold := color.New(color.Bold).SprintfFunc() - - // run state diffs. - t.Log(bold("=== dumping 3-way diffs between %s, %s, %s ===", a, b, c)) - - t.Log(bold("--- %s left: %s; right: %s ---", d1, a, b)) - printDiff(vector.Post.StateTree.RootCID, actual) - - t.Log(bold("--- %s left: %s; right: %s ---", d2, c, b)) - printDiff(vector.Pre.StateTree.RootCID, actual) - - t.Log(bold("--- %s left: %s; right: %s ---", d3, c, a)) - printDiff(vector.Pre.StateTree.RootCID, vector.Post.StateTree.RootCID) -} - -// writeStateToTempCAR writes the provided roots to a temporary CAR that'll be -// cleaned up via t.Cleanup(). It returns the full path of the temp file. -func writeStateToTempCAR(t *testing.T, bs blockstore.Blockstore, roots ...cid.Cid) string { - tmp, err := ioutil.TempFile("", "lotus-tests-*.car") - if err != nil { - t.Fatalf("failed to create temp file to dump CAR for diffing: %s", err) - } - // register a cleanup function to delete the CAR. - t.Cleanup(func() { - _ = os.Remove(tmp.Name()) - }) - - carWalkFn := func(nd format.Node) (out []*format.Link, err error) { - for _, link := range nd.Links() { - if link.Cid.Prefix().Codec == cid.FilCommitmentSealed || link.Cid.Prefix().Codec == cid.FilCommitmentUnsealed { - continue - } - out = append(out, link) - } - return out, nil - } - - var ( - offl = offline.Exchange(bs) - blkserv = blockservice.New(bs, offl) - dserv = merkledag.NewDAGService(blkserv) - ) - - err = car.WriteCarWithWalker(context.Background(), dserv, roots, tmp, carWalkFn) - if err != nil { - t.Fatalf("failed to dump CAR for diffing: %s", err) - } - _ = tmp.Close() - return tmp.Name() -} - -func loadCAR(t *testing.T, vectorCAR schema.Base64EncodedBytes) blockstore.Blockstore { - bs := blockstore.NewTemporary() - - // Read the base64-encoded CAR from the vector, and inflate the gzip. - buf := bytes.NewReader(vectorCAR) - r, err := gzip.NewReader(buf) - if err != nil { - t.Fatalf("failed to inflate gzipped CAR: %s", err) - } - defer r.Close() // nolint - - // Load the CAR embedded in the test vector into the Blockstore. - _, err = car.LoadCar(bs, r) - if err != nil { - t.Fatalf("failed to load state tree car from test vector: %s", err) - } - return bs -} diff --git a/go.sum b/go.sum index 6412fe743..bdb80aa83 100644 --- a/go.sum +++ b/go.sum @@ -504,6 +504,7 @@ github.com/ipfs/go-fs-lock v0.0.6/go.mod h1:OTR+Rj9sHiRubJh3dRhD15Juhd/+w6VPOY28 github.com/ipfs/go-graphsync v0.1.0/go.mod h1:jMXfqIEDFukLPZHqDPp8tJMbHO9Rmeb9CEGevngQbmE= github.com/ipfs/go-graphsync v0.2.1 h1:MdehhqBSuTI2LARfKLkpYnt0mUrqHs/mtuDnESXHBfU= github.com/ipfs/go-graphsync v0.2.1/go.mod h1:gEBvJUNelzMkaRPJTpg/jaKN4AQW/7wDWu0K92D8o10= +github.com/ipfs/go-hamt-ipld v0.1.1 h1:0IQdvwnAAUKmDE+PMJa5y1QiwOPHpI9+eAbQEEEYthk= github.com/ipfs/go-hamt-ipld v0.1.1/go.mod h1:1EZCr2v0jlCnhpa+aZ0JZYp8Tt2w16+JJOAVz17YcDk= github.com/ipfs/go-ipfs-blockstore v0.0.1/go.mod h1:d3WClOmRQKFnJ0Jz/jj/zmksX0ma1gROTlovZKBmN08= github.com/ipfs/go-ipfs-blockstore v0.1.0/go.mod h1:5aD0AvHPi7mZc6Ci1WCAhiBQu2IsfTduLl+422H6Rqw= From a712c109d804c09988d69a741a10b17fd2312f2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Kripalani?= Date: Sun, 27 Sep 2020 20:30:32 +0100 Subject: [PATCH 235/303] tvx/extract: print confirmation. --- cmd/tvx/extract.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/cmd/tvx/extract.go b/cmd/tvx/extract.go index 81fd3efbf..62314c6f6 100644 --- a/cmd/tvx/extract.go +++ b/cmd/tvx/extract.go @@ -48,7 +48,7 @@ var extractCmd = &cli.Command{ &cli.StringFlag{ Name: "id", Usage: "identifier to name this test vector with", - Value: "", + Value: "(undefined)", Destination: &extractFlags.id, }, &cli.StringFlag{ @@ -297,12 +297,13 @@ func runExtract(_ *cli.Context) error { } output := io.WriteCloser(os.Stdout) - if extractFlags.file != "" { - output, err = os.Create(extractFlags.file) + if file := extractFlags.file; file != "" { + output, err = os.Create(file) if err != nil { return err } defer output.Close() + defer log.Printf("wrote test vector to file: %s", file) } enc := json.NewEncoder(output) From f5f23f7291ab83c021e86164d775c896d261ea52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Kripalani?= Date: Sun, 27 Sep 2020 20:55:09 +0100 Subject: [PATCH 236/303] driver: option for VM flushing. --- cmd/tvx/extract.go | 4 +++- conformance/driver.go | 35 +++++++++++++++++++++++++++-------- conformance/runner.go | 4 ++-- 3 files changed, 32 insertions(+), 11 deletions(-) diff --git a/cmd/tvx/extract.go b/cmd/tvx/extract.go index 62314c6f6..06b3d6fe8 100644 --- a/cmd/tvx/extract.go +++ b/cmd/tvx/extract.go @@ -164,7 +164,9 @@ func runExtract(_ *cli.Context) error { g = NewSurgeon(ctx, api, pst) ) - driver := conformance.NewDriver(ctx, schema.Selector{}) + driver := conformance.NewDriver(ctx, schema.Selector{}, conformance.DriverOpts{ + DisableVMFlush: true, + }) // this is the root of the state tree we start with. root := incTs.ParentState() diff --git a/conformance/driver.go b/conformance/driver.go index ee9727cae..fdd4fe3a9 100644 --- a/conformance/driver.go +++ b/conformance/driver.go @@ -33,10 +33,24 @@ var ( type Driver struct { ctx context.Context selector schema.Selector + vmFlush bool } -func NewDriver(ctx context.Context, selector schema.Selector) *Driver { - return &Driver{ctx: ctx, selector: selector} +type DriverOpts struct { + // DisableVMFlush, when true, avoids calling VM.Flush(), forces a blockstore + // recursive copy, from the temporary buffer blockstore, to the real + // system's blockstore. Disabling VM flushing is useful when extracting test + // vectors and trimming state, as we don't want to force an accidental + // deep copy of the state tree. + // + // Disabling VM flushing almost always should go hand-in-hand with + // LOTUS_DISABLE_VM_BUF=iknowitsabadidea. That way, state tree writes are + // immediately committed to the blockstore. + DisableVMFlush bool +} + +func NewDriver(ctx context.Context, selector schema.Selector, opts DriverOpts) *Driver { + return &Driver{ctx: ctx, selector: selector, vmFlush: !opts.DisableVMFlush} } type ExecuteTipsetResult struct { @@ -155,12 +169,17 @@ func (d *Driver) ExecuteMessage(bs blockstore.Blockstore, preroot cid.Cid, epoch return nil, cid.Undef, err } - // do not flush the VM, as this forces a recursive copy to the blockstore, - // walking the full state tree, which we don't require. - // root, err := lvm.Flush(d.ctx) - // - // instead, flush the pending writes on the state tree. - root, err := lvm.StateTree().(*state.StateTree).Flush(d.ctx) + var root cid.Cid + if d.vmFlush { + // flush the VM, committing the state tree changes and forcing a + // recursive copoy from the temporary blcokstore to the real blockstore. + root, err = lvm.Flush(d.ctx) + } else { + // do not flush the VM, just the state tree; this should be used with + // LOTUS_DISABLE_VM_BUF enabled, so writes will anyway be visible. + root, err = lvm.StateTree().(*state.StateTree).Flush(d.ctx) + } + return ret, root, err } diff --git a/conformance/runner.go b/conformance/runner.go index 1fc1c1425..6ffdcd2eb 100644 --- a/conformance/runner.go +++ b/conformance/runner.go @@ -43,7 +43,7 @@ func ExecuteMessageVector(r Reporter, vector *schema.TestVector) { } // Create a new Driver. - driver := NewDriver(ctx, vector.Selector) + driver := NewDriver(ctx, vector.Selector, DriverOpts{}) // Apply every message. for i, m := range vector.ApplyMessages { @@ -93,7 +93,7 @@ func ExecuteTipsetVector(r Reporter, vector *schema.TestVector) { } // Create a new Driver. - driver := NewDriver(ctx, vector.Selector) + driver := NewDriver(ctx, vector.Selector, DriverOpts{}) // Apply every tipset. var receiptsIdx int From fe869c9c223e148b44efddca794a570145c1c3fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Kripalani?= Date: Sun, 27 Sep 2020 21:06:07 +0100 Subject: [PATCH 237/303] address review comments; lint. --- cmd/tvx/extract.go | 2 +- cmd/tvx/main.go | 4 +++- cmd/tvx/state.go | 2 +- cmd/tvx/stores.go | 4 +++- conformance/driver.go | 2 +- conformance/reporter.go | 8 ++++---- conformance/runner.go | 2 +- 7 files changed, 14 insertions(+), 10 deletions(-) diff --git a/cmd/tvx/extract.go b/cmd/tvx/extract.go index 06b3d6fe8..d3faa6d6d 100644 --- a/cmd/tvx/extract.go +++ b/cmd/tvx/extract.go @@ -304,7 +304,7 @@ func runExtract(_ *cli.Context) error { if err != nil { return err } - defer output.Close() + defer output.Close() //nolint:errcheck defer log.Printf("wrote test vector to file: %s", file) } diff --git a/cmd/tvx/main.go b/cmd/tvx/main.go index 183c2fbe1..2ab217953 100644 --- a/cmd/tvx/main.go +++ b/cmd/tvx/main.go @@ -23,7 +23,9 @@ var apiEndpoint string var apiFlag = cli.StringFlag{ Name: "api", - Usage: "json-rpc api endpoint, formatted as token:multiaddr", + Usage: "json-rpc api endpoint, formatted as [token]:multiaddr;" + + "tvx uses unpriviliged operations, so the token may be omitted," + + "but permissions may change in the future", EnvVars: []string{"FULLNODE_API_INFO"}, DefaultText: "", Destination: &apiEndpoint, diff --git a/cmd/tvx/state.go b/cmd/tvx/state.go index cef5c5494..5bf1cf153 100644 --- a/cmd/tvx/state.go +++ b/cmd/tvx/state.go @@ -9,7 +9,7 @@ import ( "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" "github.com/ipfs/go-cid" - "github.com/ipfs/go-ipld-format" + format "github.com/ipfs/go-ipld-format" "github.com/ipld/go-car" cbg "github.com/whyrusleeping/cbor-gen" diff --git a/cmd/tvx/stores.go b/cmd/tvx/stores.go index 7d3fd5e3a..c389f8c88 100644 --- a/cmd/tvx/stores.go +++ b/cmd/tvx/stores.go @@ -6,6 +6,7 @@ import ( "sync" "github.com/fatih/color" + dssync "github.com/ipfs/go-datastore/sync" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/lib/blockstore" @@ -40,7 +41,8 @@ type Stores struct { // proxies Get requests for unknown CIDs to a Filecoin node, via the // ChainReadObj RPC. func NewProxyingStores(ctx context.Context, api api.FullNode) *Stores { - ds := ds.NewMapDatastore() + ds := dssync.MutexWrap(ds.NewMapDatastore()) + ds = dssync.MutexWrap(ds) bs := &proxyingBlockstore{ ctx: ctx, diff --git a/conformance/driver.go b/conformance/driver.go index fdd4fe3a9..90d05ae88 100644 --- a/conformance/driver.go +++ b/conformance/driver.go @@ -33,7 +33,7 @@ var ( type Driver struct { ctx context.Context selector schema.Selector - vmFlush bool + vmFlush bool } type DriverOpts struct { diff --git a/conformance/reporter.go b/conformance/reporter.go index 747caae32..1cd2d389d 100644 --- a/conformance/reporter.go +++ b/conformance/reporter.go @@ -33,17 +33,17 @@ type LogReporter struct { var _ Reporter = (*LogReporter)(nil) -func (_ *LogReporter) Helper() {} +func (*LogReporter) Helper() {} -func (_ *LogReporter) Log(args ...interface{}) { +func (*LogReporter) Log(args ...interface{}) { log.Println(args...) } -func (_ *LogReporter) Logf(format string, args ...interface{}) { +func (*LogReporter) Logf(format string, args ...interface{}) { log.Printf(format, args...) } -func (_ *LogReporter) FailNow() { +func (*LogReporter) FailNow() { os.Exit(1) } diff --git a/conformance/runner.go b/conformance/runner.go index 6ffdcd2eb..456955b25 100644 --- a/conformance/runner.go +++ b/conformance/runner.go @@ -164,7 +164,7 @@ func dumpThreeWayStateDiff(r Reporter, vector *schema.TestVector, bs blockstore. if err != nil { r.Fatalf("failed to write temporary state CAR: %s", err) } - defer os.RemoveAll(tmpCar) + defer os.RemoveAll(tmpCar) //nolint:errcheck color.NoColor = false // enable colouring. From 9a355c4bc5b10bd24c55f819e2a32ae882312dcd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Kripalani?= Date: Sun, 27 Sep 2020 21:11:32 +0100 Subject: [PATCH 238/303] fix lint errors. --- cmd/tvx/main.go | 4 ++-- cmd/tvx/state.go | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/cmd/tvx/main.go b/cmd/tvx/main.go index 2ab217953..6d5c64101 100644 --- a/cmd/tvx/main.go +++ b/cmd/tvx/main.go @@ -22,8 +22,8 @@ import ( var apiEndpoint string var apiFlag = cli.StringFlag{ - Name: "api", - Usage: "json-rpc api endpoint, formatted as [token]:multiaddr;" + + Name: "api", + Usage: "json-rpc api endpoint, formatted as [token]:multiaddr;" + "tvx uses unpriviliged operations, so the token may be omitted," + "but permissions may change in the future", EnvVars: []string{"FULLNODE_API_INFO"}, diff --git a/cmd/tvx/state.go b/cmd/tvx/state.go index 5bf1cf153..bff5cbd6e 100644 --- a/cmd/tvx/state.go +++ b/cmd/tvx/state.go @@ -116,8 +116,8 @@ func (sg *StateSurgeon) GetAccessedActors(ctx context.Context, a api.FullNode, m recur = func(trace *types.ExecutionTrace) { accessed[trace.Msg.To] = struct{}{} accessed[trace.Msg.From] = struct{}{} - for _, s := range trace.Subcalls { - recur(&s) + for i := range trace.Subcalls { + recur(&trace.Subcalls[i]) } } recur(&trace.ExecutionTrace) From a2d24b5b33a18418edc63bea9518e9dbed72bfef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E6=9E=97=E6=AC=A3?= Date: Mon, 28 Sep 2020 13:53:29 +0800 Subject: [PATCH 239/303] add ipfsmain bootstrapper --- build/bootstrap/bootstrappers.pi | 3 +++ 1 file changed, 3 insertions(+) diff --git a/build/bootstrap/bootstrappers.pi b/build/bootstrap/bootstrappers.pi index 465f3b5e9..51adb3cc7 100644 --- a/build/bootstrap/bootstrappers.pi +++ b/build/bootstrap/bootstrappers.pi @@ -4,3 +4,6 @@ /dns4/bootstrap-4.testnet.fildev.network/tcp/1347/p2p/12D3KooWPkL9LrKRQgHtq7kn9ecNhGU9QaziG8R5tX8v9v7t3h34 /dns4/bootstrap-3.testnet.fildev.network/tcp/1347/p2p/12D3KooWKYSsbpgZ3HAjax5M1BXCwXLa6gVkUARciz7uN3FNtr7T /dns4/bootstrap-5.testnet.fildev.network/tcp/1347/p2p/12D3KooWQYzqnLASJAabyMpPb1GcWZvNSe7JDcRuhdRqonFoiK9W + +/dns4/bootstrap-0.ipfsmain.cn/tcp/34721/p2p/12D3KooWQnwEGNqcM2nAcPtRR9rAX8Hrg4k9kJLCHoTR5chJfz6d +/dns4/bootstrap-1.ipfsmain.cn/tcp/34723/p2p/12D3KooWMKxMkD5DMpSWsW7dBddKxKT7L2GgbNuckz9otxvkvByP \ No newline at end of file From a3145bae07f3658183d95d9a6e56d2f3ae38ce76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Mon, 28 Sep 2020 12:17:54 +0200 Subject: [PATCH 240/303] daemon cmd: Add progress bar to chain import --- cmd/lotus/daemon.go | 18 +++++++++++++++++- go.mod | 1 + 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/cmd/lotus/daemon.go b/cmd/lotus/daemon.go index e0fee6564..93f6e4b8c 100644 --- a/cmd/lotus/daemon.go +++ b/cmd/lotus/daemon.go @@ -23,6 +23,7 @@ import ( "go.opencensus.io/stats/view" "go.opencensus.io/tag" "golang.org/x/xerrors" + "gopkg.in/cheggaaa/pb.v1" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/build" @@ -333,6 +334,11 @@ func ImportChain(r repo.Repo, fname string, snapshot bool) error { } defer fi.Close() //nolint:errcheck + st, err := os.Stat(fname) + if err != nil { + return err + } + lr, err := r.Lock(repo.FullNode) if err != nil { return err @@ -354,7 +360,17 @@ func ImportChain(r repo.Repo, fname string, snapshot bool) error { cst := store.NewChainStore(bs, mds, vm.Syscalls(ffiwrapper.ProofVerifier)) log.Info("importing chain from file...") - ts, err := cst.Import(fi) + + bar := pb.New64(st.Size()) + br := bar.NewProxyReader(fi) + bar.ShowTimeLeft = true + bar.ShowPercent = true + bar.Units = pb.U_BYTES + + bar.Start() + ts, err := cst.Import(br) + bar.Finish() + if err != nil { return xerrors.Errorf("importing chain failed: %w", err) } diff --git a/go.mod b/go.mod index 67d87347f..2c0322ecc 100644 --- a/go.mod +++ b/go.mod @@ -125,6 +125,7 @@ require ( golang.org/x/sys v0.0.0-20200602225109-6fdc65e7d980 golang.org/x/time v0.0.0-20191024005414-555d28b269f0 golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 + gopkg.in/cheggaaa/pb.v1 v1.0.28 gotest.tools v2.2.0+incompatible launchpad.net/gocheck v0.0.0-20140225173054-000000000087 // indirect ) From f8095296997f6d5d8ba05d66acf291cfa048ae50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Mon, 28 Sep 2020 12:28:12 +0200 Subject: [PATCH 241/303] daemon cmd: Support imports straight from http --- cmd/lotus/daemon.go | 64 +++++++++++++++++++++++++++++++-------------- 1 file changed, 45 insertions(+), 19 deletions(-) diff --git a/cmd/lotus/daemon.go b/cmd/lotus/daemon.go index 93f6e4b8c..b976fde79 100644 --- a/cmd/lotus/daemon.go +++ b/cmd/lotus/daemon.go @@ -3,11 +3,14 @@ package main import ( + "bufio" "context" "encoding/hex" "encoding/json" "fmt" + "io" "io/ioutil" + "net/http" "os" "runtime/pprof" "strings" @@ -101,11 +104,11 @@ var DaemonCmd = &cli.Command{ }, &cli.StringFlag{ Name: "import-chain", - Usage: "on first run, load chain from given file and validate", + Usage: "on first run, load chain from given file or url and validate", }, &cli.StringFlag{ Name: "import-snapshot", - Usage: "import chain state from a given chain export file", + Usage: "import chain state from a given chain export file or url", }, &cli.BoolFlag{ Name: "halt-after-import", @@ -207,11 +210,6 @@ var DaemonCmd = &cli.Command{ issnapshot = true } - chainfile, err := homedir.Expand(chainfile) - if err != nil { - return err - } - if err := ImportChain(r, chainfile, issnapshot); err != nil { return err } @@ -327,16 +325,41 @@ func importKey(ctx context.Context, api api.FullNode, f string) error { return nil } -func ImportChain(r repo.Repo, fname string, snapshot bool) error { - fi, err := os.Open(fname) - if err != nil { - return err - } - defer fi.Close() //nolint:errcheck +func ImportChain(r repo.Repo, fname string, snapshot bool) (err error) { + var rd io.Reader + var l int64 + if strings.HasPrefix(fname, "http://") || strings.HasPrefix(fname, "https://") { + resp, err := http.Get(fname) //nolint:gosec + if err != nil { + return err + } + defer resp.Body.Close() //nolint:errcheck - st, err := os.Stat(fname) - if err != nil { - return err + if resp.StatusCode != http.StatusOK { + return xerrors.Errorf("non-200 response: %d", resp.StatusCode) + } + + rd = resp.Body + l = resp.ContentLength + } else { + fname, err = homedir.Expand(fname) + if err != nil { + return err + } + + fi, err := os.Open(fname) + if err != nil { + return err + } + defer fi.Close() //nolint:errcheck + + st, err := os.Stat(fname) + if err != nil { + return err + } + + rd = fi + l = st.Size() } lr, err := r.Lock(repo.FullNode) @@ -359,12 +382,15 @@ func ImportChain(r repo.Repo, fname string, snapshot bool) error { cst := store.NewChainStore(bs, mds, vm.Syscalls(ffiwrapper.ProofVerifier)) - log.Info("importing chain from file...") + log.Infof("importing chain from %s...", fname) - bar := pb.New64(st.Size()) - br := bar.NewProxyReader(fi) + bufr := bufio.NewReaderSize(rd, 1<<20) + + bar := pb.New64(l) + br := bar.NewProxyReader(bufr) bar.ShowTimeLeft = true bar.ShowPercent = true + bar.ShowSpeed = true bar.Units = pb.U_BYTES bar.Start() From f05a40feed0ebd475ad5845ad751c449a01fb199 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Kripalani?= Date: Mon, 28 Sep 2020 12:27:42 +0100 Subject: [PATCH 242/303] use lotus CLI package; document API endpoint setting in usage. --- cmd/tvx/extract.go | 6 ++-- cmd/tvx/main.go | 80 ++++++++++++---------------------------------- 2 files changed, 23 insertions(+), 63 deletions(-) diff --git a/cmd/tvx/extract.go b/cmd/tvx/extract.go index d3faa6d6d..d8053e5c2 100644 --- a/cmd/tvx/extract.go +++ b/cmd/tvx/extract.go @@ -15,6 +15,7 @@ import ( "github.com/filecoin-project/lotus/chain/actors/builtin/reward" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/vm" + lcli "github.com/filecoin-project/lotus/cli" "github.com/filecoin-project/lotus/conformance" "github.com/filecoin-project/go-address" @@ -38,7 +39,6 @@ var extractCmd = &cli.Command{ Description: "generate a message-class test vector by extracting it from a live chain", Action: runExtract, Flags: []cli.Flag{ - &apiFlag, &cli.StringFlag{ Name: "class", Usage: "class of vector to extract; other required flags depend on the; values: 'message'", @@ -72,7 +72,7 @@ var extractCmd = &cli.Command{ }, } -func runExtract(_ *cli.Context) error { +func runExtract(c *cli.Context) error { // LOTUS_DISABLE_VM_BUF disables what's called "VM state tree buffering", // which stashes write operations in a BufferedBlockstore // (https://github.com/filecoin-project/lotus/blob/b7a4dbb07fd8332b4492313a617e3458f8003b2a/lib/bufbstore/buf_bstore.go#L21) @@ -91,7 +91,7 @@ func runExtract(_ *cli.Context) error { } // Make the API client. - api, closer, err := makeAPIClient() + api, closer, err := lcli.GetFullNodeAPI(c) if err != nil { return err } diff --git a/cmd/tvx/main.go b/cmd/tvx/main.go index 6d5c64101..a74a029ce 100644 --- a/cmd/tvx/main.go +++ b/cmd/tvx/main.go @@ -1,49 +1,41 @@ package main import ( - "context" - "fmt" "log" - "net/http" "os" "sort" - "strings" - - "github.com/filecoin-project/go-jsonrpc" - "github.com/multiformats/go-multiaddr" - manet "github.com/multiformats/go-multiaddr/net" "github.com/urfave/cli/v2" - - "github.com/filecoin-project/lotus/api" - "github.com/filecoin-project/lotus/api/client" ) -var apiEndpoint string - -var apiFlag = cli.StringFlag{ - Name: "api", - Usage: "json-rpc api endpoint, formatted as [token]:multiaddr;" + - "tvx uses unpriviliged operations, so the token may be omitted," + - "but permissions may change in the future", - EnvVars: []string{"FULLNODE_API_INFO"}, - DefaultText: "", - Destination: &apiEndpoint, -} - func main() { app := &cli.App{ Name: "tvx", Description: `tvx is a tool for extracting and executing test vectors. It has two subcommands. tvx extract extracts a test vector from a live network. It requires access to - a Filecoin client that exposes the standard JSON-RPC API endpoint. Set the API - endpoint on the FULLNODE_API_INFO env variable, or through the --api flag. The - format is token:multiaddr. Only message class test vectors are supported - for now. + a Filecoin client that exposes the standard JSON-RPC API endpoint. Only + message class test vectors are supported at this time. tvx exec executes test vectors against Lotus. Either you can supply one in a - file, or many as an ndjson stdin stream.`, + file, or many as an ndjson stdin stream. + + SETTING THE JSON-RPC API ENDPOINT + + You can set the JSON-RPC API endpoint through one of the following approaches. + + 1. Directly set the API endpoint on the FULLNODE_API_INFO env variable. + The format is [token]:multiaddr, where token is optional for commands not + accessing privileged operations. + + 2. If you're running tvx against a local Lotus client, you can set the REPO + env variable to have the API endpoint and token extracted from the repo. + + 3. Rely on the default fallback, which inspects ~/.lotus and extracts the + API endpoint string if the location is a Lotus repo. + + tvx will apply these approaches in the same order of precedence they're listed. +`, Usage: "tvx is a tool for extracting and executing test vectors", Commands: []*cli.Command{ extractCmd, @@ -60,35 +52,3 @@ func main() { log.Fatal(err) } } - -func makeAPIClient() (api.FullNode, jsonrpc.ClientCloser, error) { - sp := strings.SplitN(apiEndpoint, ":", 2) - if len(sp) != 2 { - return nil, nil, fmt.Errorf("invalid api value, missing token or address: %s", apiEndpoint) - } - - token := sp[0] - ma, err := multiaddr.NewMultiaddr(sp[1]) - if err != nil { - return nil, nil, fmt.Errorf("could not parse provided multiaddr: %w", err) - } - - _, dialAddr, err := manet.DialArgs(ma) - if err != nil { - return nil, nil, fmt.Errorf("invalid api multiAddr: %w", err) - } - - var ( - addr = "ws://" + dialAddr + "/rpc/v0" - headers = make(http.Header, 1) - ) - if len(token) != 0 { - headers.Add("Authorization", "Bearer "+token) - } - - node, closer, err := client.NewFullNodeRPC(context.Background(), addr, headers) - if err != nil { - return nil, nil, fmt.Errorf("could not connect to api: %w", err) - } - return node, closer, nil -} From dfdcbd184d7679cb32dfefe7be4ce2ffd6159d6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Kripalani?= Date: Mon, 28 Sep 2020 12:35:01 +0100 Subject: [PATCH 243/303] add --repo flag. --- cmd/tvx/extract.go | 3 ++- cmd/tvx/main.go | 17 +++++++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/cmd/tvx/extract.go b/cmd/tvx/extract.go index d8053e5c2..3408cea12 100644 --- a/cmd/tvx/extract.go +++ b/cmd/tvx/extract.go @@ -36,9 +36,10 @@ var extractFlags struct { var extractCmd = &cli.Command{ Name: "extract", - Description: "generate a message-class test vector by extracting it from a live chain", + Description: "generate a test vector by extracting it from a live chain", Action: runExtract, Flags: []cli.Flag{ + &repoFlag, &cli.StringFlag{ Name: "class", Usage: "class of vector to extract; other required flags depend on the; values: 'message'", diff --git a/cmd/tvx/main.go b/cmd/tvx/main.go index a74a029ce..361ba41c3 100644 --- a/cmd/tvx/main.go +++ b/cmd/tvx/main.go @@ -8,6 +8,18 @@ import ( "github.com/urfave/cli/v2" ) +// DefaultLotusRepoPath is where the fallback path where to look for a Lotus +// client repo. It is expanded with mitchellh/go-homedir, so it'll work with all +// OSes despite the Unix twiddle notation. +const DefaultLotusRepoPath = "~/.lotus" + +var repoFlag = cli.StringFlag{ + Name: "repo", + EnvVars: []string{"LOTUS_PATH"}, + Value: DefaultLotusRepoPath, + TakesFile: true, +} + func main() { app := &cli.App{ Name: "tvx", @@ -22,7 +34,7 @@ func main() { SETTING THE JSON-RPC API ENDPOINT - You can set the JSON-RPC API endpoint through one of the following approaches. + You can set the JSON-RPC API endpoint through one of the following methods. 1. Directly set the API endpoint on the FULLNODE_API_INFO env variable. The format is [token]:multiaddr, where token is optional for commands not @@ -30,11 +42,12 @@ func main() { 2. If you're running tvx against a local Lotus client, you can set the REPO env variable to have the API endpoint and token extracted from the repo. + Alternatively, you can pass the --repo CLI flag. 3. Rely on the default fallback, which inspects ~/.lotus and extracts the API endpoint string if the location is a Lotus repo. - tvx will apply these approaches in the same order of precedence they're listed. + tvx will apply these methods in the same order of precedence they're listed. `, Usage: "tvx is a tool for extracting and executing test vectors", Commands: []*cli.Command{ From 8f3be7866765ce5054dd2ffe20c55dee82a4fe2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Kripalani?= Date: Mon, 28 Sep 2020 13:00:07 +0100 Subject: [PATCH 244/303] tvx/extract: allow passing in block to speed things up. --- cmd/tvx/extract.go | 71 ++++++++++++++++++++++++++++++++++++---------- 1 file changed, 56 insertions(+), 15 deletions(-) diff --git a/cmd/tvx/extract.go b/cmd/tvx/extract.go index 3408cea12..09465d356 100644 --- a/cmd/tvx/extract.go +++ b/cmd/tvx/extract.go @@ -28,6 +28,7 @@ import ( var extractFlags struct { id string + block string class string cid string file string @@ -52,6 +53,11 @@ var extractCmd = &cli.Command{ Value: "(undefined)", Destination: &extractFlags.id, }, + &cli.StringFlag{ + Name: "block", + Usage: "optionally, the block CID the message was included in, to avoid expensive chain scanning", + Destination: &extractFlags.block, + }, &cli.StringFlag{ Name: "cid", Usage: "message CID to generate test vector from", @@ -98,27 +104,59 @@ func runExtract(c *cli.Context) error { } defer closer() - log.Printf("locating message with CID: %s", mcid) - - // Locate the message. - msgInfo, err := api.StateSearchMsg(ctx, mcid) - if err != nil { - return fmt.Errorf("failed to locate message: %w", err) - } - - log.Printf("located message at tipset %s (height: %d) with exit code: %s", msgInfo.TipSet, msgInfo.Height, msgInfo.Receipt.ExitCode) + var ( + msg *types.Message + incTs *types.TipSet + execTs *types.TipSet + ) // Extract the full message. - msg, err := api.ChainGetMessage(ctx, mcid) + msg, err = api.ChainGetMessage(ctx, mcid) if err != nil { return err } - log.Printf("full message: %+v", msg) + log.Printf("found message with CID %s: %+v", mcid, msg) - execTs, incTs, err := fetchThisAndPrevTipset(ctx, api, msgInfo.TipSet) - if err != nil { - return err + if block := extractFlags.block; block == "" { + log.Printf("locating message in blockchain") + + // Locate the message. + msgInfo, err := api.StateSearchMsg(ctx, mcid) + if err != nil { + return fmt.Errorf("failed to locate message: %w", err) + } + + log.Printf("located message at tipset %s (height: %d) with exit code: %s", msgInfo.TipSet, msgInfo.Height, msgInfo.Receipt.ExitCode) + + execTs, incTs, err = fetchThisAndPrevTipset(ctx, api, msgInfo.TipSet) + if err != nil { + return err + } + } else { + bcid, err := cid.Decode(block) + if err != nil { + return err + } + + log.Printf("message inclusion block CID was provided; scanning around it: %s", bcid) + + blk, err := api.ChainGetBlock(ctx, bcid) + if err != nil { + return fmt.Errorf("failed to get block: %w", err) + } + + // types.EmptyTSK hints to use the HEAD. + execTs, err = api.ChainGetTipSetByHeight(ctx, blk.Height+1, types.EmptyTSK) + if err != nil { + return fmt.Errorf("failed to get message execution tipset: %w", err) + } + + // walk back from the execTs instead of HEAD, to save time. + incTs, err = api.ChainGetTipSetByHeight(ctx, blk.Height, execTs.Key()) + if err != nil { + return fmt.Errorf("failed to get message inclusion tipset: %w", err) + } } log.Printf("message was executed in tipset: %s", execTs.Key()) @@ -274,7 +312,10 @@ func runExtract(c *cli.Context) error { Meta: &schema.Metadata{ ID: extractFlags.id, Gen: []schema.GenerationData{ - {Source: fmt.Sprintf("message:%s:%s", ntwkName, msg.Cid().String())}, + {Source: fmt.Sprintf("network:%s", ntwkName)}, + {Source: fmt.Sprintf("msg:%s", msg.Cid().String())}, + {Source: fmt.Sprintf("inc_ts:%s", incTs.Key().String())}, + {Source: fmt.Sprintf("exec_ts:%s", execTs.Key().String())}, {Source: "github.com/filecoin-project/lotus", Version: version.String()}}, }, CAR: out.Bytes(), From a0dffb44d31595a51857516a58439fd3964f044e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Kripalani?= Date: Mon, 28 Sep 2020 13:11:34 +0100 Subject: [PATCH 245/303] tvx/extract: perform sanity check on receipt. --- cmd/tvx/extract.go | 31 ++++++++++++++++++++++++++++--- conformance/runner.go | 8 ++++---- 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/cmd/tvx/extract.go b/cmd/tvx/extract.go index 09465d356..8dbaf45d5 100644 --- a/cmd/tvx/extract.go +++ b/cmd/tvx/extract.go @@ -10,6 +10,8 @@ import ( "log" "os" + "github.com/fatih/color" + "github.com/filecoin-project/lotus/api" init_ "github.com/filecoin-project/lotus/chain/actors/builtin/init" "github.com/filecoin-project/lotus/chain/actors/builtin/reward" @@ -277,6 +279,25 @@ func runExtract(c *cli.Context) error { return fmt.Errorf("unknown state retention option: %s", retention) } + log.Printf("message applied; preroot: %s, postroot: %s", preroot, postroot) + log.Printf("performing sanity check on receipt") + + receipt := &schema.Receipt{ + ExitCode: int64(applyret.ExitCode), + ReturnValue: applyret.Return, + GasUsed: applyret.GasUsed, + } + + reporter := new(conformance.LogReporter) + conformance.AssertMsgResult(reporter, receipt, applyret, "as locally executed") + if reporter.Failed() { + log.Printf(color.RedString("receipt sanity check failed; aborting")) + return fmt.Errorf("vector generation aborted") + } else { + log.Printf(color.GreenString("receipt sanity check succeeded")) + } + + log.Printf("generating vector") msgBytes, err := msg.Serialize() if err != nil { return err @@ -311,11 +332,15 @@ func runExtract(c *cli.Context) error { Class: schema.ClassMessage, Meta: &schema.Metadata{ ID: extractFlags.id, + // TODO need to replace schema.GenerationData with a more flexible + // data structure that makes no assumption about the traceability + // data that's being recorded; a flexible map[string]string + // would do. Gen: []schema.GenerationData{ {Source: fmt.Sprintf("network:%s", ntwkName)}, - {Source: fmt.Sprintf("msg:%s", msg.Cid().String())}, - {Source: fmt.Sprintf("inc_ts:%s", incTs.Key().String())}, - {Source: fmt.Sprintf("exec_ts:%s", execTs.Key().String())}, + {Source: fmt.Sprintf("message:%s", msg.Cid().String())}, + {Source: fmt.Sprintf("inclusion_tipset:%s", incTs.Key().String())}, + {Source: fmt.Sprintf("execution_tipset:%s", execTs.Key().String())}, {Source: "github.com/filecoin-project/lotus", Version: version.String()}}, }, CAR: out.Bytes(), diff --git a/conformance/runner.go b/conformance/runner.go index 456955b25..0fc4b13fc 100644 --- a/conformance/runner.go +++ b/conformance/runner.go @@ -65,7 +65,7 @@ func ExecuteMessageVector(r Reporter, vector *schema.TestVector) { } // Assert that the receipt matches what the test vector expects. - assertMsgResult(r, vector.Post.Receipts[i], ret, strconv.Itoa(i)) + AssertMsgResult(r, vector.Post.Receipts[i], ret, strconv.Itoa(i)) } // Once all messages are applied, assert that the final state root matches @@ -105,7 +105,7 @@ func ExecuteTipsetVector(r Reporter, vector *schema.TestVector) { } for j, v := range ret.AppliedResults { - assertMsgResult(r, vector.Post.Receipts[receiptsIdx], v, fmt.Sprintf("%d of tipset %d", j, i)) + AssertMsgResult(r, vector.Post.Receipts[receiptsIdx], v, fmt.Sprintf("%d of tipset %d", j, i)) receiptsIdx++ } @@ -127,10 +127,10 @@ func ExecuteTipsetVector(r Reporter, vector *schema.TestVector) { } } -// assertMsgResult compares a message result. It takes the expected receipt +// AssertMsgResult compares a message result. It takes the expected receipt // encoded in the vector, the actual receipt returned by Lotus, and a message // label to log in the assertion failure message to facilitate debugging. -func assertMsgResult(r Reporter, expected *schema.Receipt, actual *vm.ApplyRet, label string) { +func AssertMsgResult(r Reporter, expected *schema.Receipt, actual *vm.ApplyRet, label string) { r.Helper() if expected, actual := exitcode.ExitCode(expected.ExitCode), actual.ExitCode; expected != actual { From 4c9717187f8995dd5b9cf647ac003815dd645a80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Kripalani?= Date: Mon, 28 Sep 2020 13:19:45 +0100 Subject: [PATCH 246/303] tvx/extract: small refactor. --- cmd/tvx/extract.go | 108 +++++++++++++++++++++++---------------------- 1 file changed, 56 insertions(+), 52 deletions(-) diff --git a/cmd/tvx/extract.go b/cmd/tvx/extract.go index 8dbaf45d5..29330daaa 100644 --- a/cmd/tvx/extract.go +++ b/cmd/tvx/extract.go @@ -106,59 +106,9 @@ func runExtract(c *cli.Context) error { } defer closer() - var ( - msg *types.Message - incTs *types.TipSet - execTs *types.TipSet - ) - - // Extract the full message. - msg, err = api.ChainGetMessage(ctx, mcid) + msg, execTs, incTs, err := resolveFromChain(ctx, api, mcid) if err != nil { - return err - } - - log.Printf("found message with CID %s: %+v", mcid, msg) - - if block := extractFlags.block; block == "" { - log.Printf("locating message in blockchain") - - // Locate the message. - msgInfo, err := api.StateSearchMsg(ctx, mcid) - if err != nil { - return fmt.Errorf("failed to locate message: %w", err) - } - - log.Printf("located message at tipset %s (height: %d) with exit code: %s", msgInfo.TipSet, msgInfo.Height, msgInfo.Receipt.ExitCode) - - execTs, incTs, err = fetchThisAndPrevTipset(ctx, api, msgInfo.TipSet) - if err != nil { - return err - } - } else { - bcid, err := cid.Decode(block) - if err != nil { - return err - } - - log.Printf("message inclusion block CID was provided; scanning around it: %s", bcid) - - blk, err := api.ChainGetBlock(ctx, bcid) - if err != nil { - return fmt.Errorf("failed to get block: %w", err) - } - - // types.EmptyTSK hints to use the HEAD. - execTs, err = api.ChainGetTipSetByHeight(ctx, blk.Height+1, types.EmptyTSK) - if err != nil { - return fmt.Errorf("failed to get message execution tipset: %w", err) - } - - // walk back from the execTs instead of HEAD, to save time. - incTs, err = api.ChainGetTipSetByHeight(ctx, blk.Height, execTs.Key()) - if err != nil { - return fmt.Errorf("failed to get message inclusion tipset: %w", err) - } + return fmt.Errorf("failed to resolve message and tipsets from chain: %w", err) } log.Printf("message was executed in tipset: %s", execTs.Key()) @@ -384,6 +334,60 @@ func runExtract(c *cli.Context) error { return nil } +// resolveFromChain queries the chain for the provided message, using the block CID to +// speed up the query, if provided +func resolveFromChain(ctx context.Context, api api.FullNode, mcid cid.Cid) (msg *types.Message, execTs *types.TipSet, incTs *types.TipSet, err error) { + // Extract the full message. + msg, err = api.ChainGetMessage(ctx, mcid) + if err != nil { + return nil, nil, nil, err + } + + log.Printf("found message with CID %s: %+v", mcid, msg) + + block := extractFlags.block + if block == "" { + log.Printf("locating message in blockchain") + + // Locate the message. + msgInfo, err := api.StateSearchMsg(ctx, mcid) + if err != nil { + return nil, nil, nil, fmt.Errorf("failed to locate message: %w", err) + } + + log.Printf("located message at tipset %s (height: %d) with exit code: %s", msgInfo.TipSet, msgInfo.Height, msgInfo.Receipt.ExitCode) + + execTs, incTs, err = fetchThisAndPrevTipset(ctx, api, msgInfo.TipSet) + return msg, execTs, incTs, err + } + + bcid, err := cid.Decode(block) + if err != nil { + return nil, nil, nil, err + } + + log.Printf("message inclusion block CID was provided; scanning around it: %s", bcid) + + blk, err := api.ChainGetBlock(ctx, bcid) + if err != nil { + return nil, nil, nil, fmt.Errorf("failed to get block: %w", err) + } + + // types.EmptyTSK hints to use the HEAD. + execTs, err = api.ChainGetTipSetByHeight(ctx, blk.Height+1, types.EmptyTSK) + if err != nil { + return nil, nil, nil, fmt.Errorf("failed to get message execution tipset: %w", err) + } + + // walk back from the execTs instead of HEAD, to save time. + incTs, err = api.ChainGetTipSetByHeight(ctx, blk.Height, execTs.Key()) + if err != nil { + return nil, nil, nil, fmt.Errorf("failed to get message inclusion tipset: %w", err) + } + + return msg, execTs, incTs, nil +} + // fetchThisAndPrevTipset returns the full tipset identified by the key, as well // as the previous tipset. In the context of vector generation, the target // tipset is the one where a message was executed, and the previous tipset is From 9f6862a456e391552b6c17cd1a0c82d5a6e70965 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Kripalani?= Date: Mon, 28 Sep 2020 13:22:56 +0100 Subject: [PATCH 247/303] fix lint. --- cmd/tvx/extract.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cmd/tvx/extract.go b/cmd/tvx/extract.go index 29330daaa..07c6ca7ef 100644 --- a/cmd/tvx/extract.go +++ b/cmd/tvx/extract.go @@ -230,7 +230,7 @@ func runExtract(c *cli.Context) error { } log.Printf("message applied; preroot: %s, postroot: %s", preroot, postroot) - log.Printf("performing sanity check on receipt") + log.Println("performing sanity check on receipt") receipt := &schema.Receipt{ ExitCode: int64(applyret.ExitCode), @@ -241,13 +241,13 @@ func runExtract(c *cli.Context) error { reporter := new(conformance.LogReporter) conformance.AssertMsgResult(reporter, receipt, applyret, "as locally executed") if reporter.Failed() { - log.Printf(color.RedString("receipt sanity check failed; aborting")) + log.Println(color.RedString("receipt sanity check failed; aborting")) return fmt.Errorf("vector generation aborted") - } else { - log.Printf(color.GreenString("receipt sanity check succeeded")) } - log.Printf("generating vector") + log.Println(color.GreenString("receipt sanity check succeeded")) + + log.Println("generating vector") msgBytes, err := msg.Serialize() if err != nil { return err From 6b16d48bad56544d547449e3df8972cf5feb72ee Mon Sep 17 00:00:00 2001 From: Dirk McCormick Date: Mon, 28 Sep 2020 15:56:44 +0200 Subject: [PATCH 248/303] refactor: fetch tipset blocks in parallel --- chain/store/store.go | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/chain/store/store.go b/chain/store/store.go index 1dbf69547..e68857e0b 100644 --- a/chain/store/store.go +++ b/chain/store/store.go @@ -10,6 +10,8 @@ import ( "strconv" "sync" + "golang.org/x/sync/errgroup" + "github.com/filecoin-project/go-state-types/crypto" "github.com/minio/blake2b-simd" @@ -467,14 +469,25 @@ func (cs *ChainStore) LoadTipSet(tsk types.TipSetKey) (*types.TipSet, error) { return v.(*types.TipSet), nil } - var blks []*types.BlockHeader - for _, c := range tsk.Cids() { - b, err := cs.GetBlock(c) - if err != nil { - return nil, xerrors.Errorf("get block %s: %w", c, err) - } + // Fetch tipset block headers from blockstore in parallel + var eg errgroup.Group + cids := tsk.Cids() + blks := make([]*types.BlockHeader, 0, len(cids)) + for _, c := range cids { + c := c + eg.Go(func() error { + b, err := cs.GetBlock(c) + if err != nil { + return xerrors.Errorf("get block %s: %w", c, err) + } - blks = append(blks, b) + blks = append(blks, b) + return nil + }) + } + err := eg.Wait() + if err != nil { + return nil, err } ts, err := types.NewTipSet(blks) From cfe6f595b036c332843697413fce5b78104159af Mon Sep 17 00:00:00 2001 From: Dirk McCormick Date: Mon, 28 Sep 2020 16:35:37 +0200 Subject: [PATCH 249/303] fix: unsafe append in LoadTipSet --- chain/store/store.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/chain/store/store.go b/chain/store/store.go index e68857e0b..6c93db7a0 100644 --- a/chain/store/store.go +++ b/chain/store/store.go @@ -472,16 +472,16 @@ func (cs *ChainStore) LoadTipSet(tsk types.TipSetKey) (*types.TipSet, error) { // Fetch tipset block headers from blockstore in parallel var eg errgroup.Group cids := tsk.Cids() - blks := make([]*types.BlockHeader, 0, len(cids)) - for _, c := range cids { - c := c + blks := make([]*types.BlockHeader, len(cids)) + for i, c := range cids { + i, c := i, c eg.Go(func() error { b, err := cs.GetBlock(c) if err != nil { return xerrors.Errorf("get block %s: %w", c, err) } - blks = append(blks, b) + blks[i] = b return nil }) } From 96f882860fdc2a9edeb92f07964d7fb5a73b0c1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Kripalani?= Date: Mon, 28 Sep 2020 17:02:56 +0100 Subject: [PATCH 250/303] add extract-many command. --- cmd/tvx/actor_mapping.go | 44 +++++++++ cmd/tvx/extract.go | 50 ++++++---- cmd/tvx/extract_many.go | 204 +++++++++++++++++++++++++++++++++++++++ cmd/tvx/main.go | 6 +- 4 files changed, 283 insertions(+), 21 deletions(-) create mode 100644 cmd/tvx/actor_mapping.go create mode 100644 cmd/tvx/extract_many.go diff --git a/cmd/tvx/actor_mapping.go b/cmd/tvx/actor_mapping.go new file mode 100644 index 000000000..8c306aca0 --- /dev/null +++ b/cmd/tvx/actor_mapping.go @@ -0,0 +1,44 @@ +package main + +import ( + "reflect" + + "github.com/filecoin-project/specs-actors/actors/builtin" + "github.com/ipfs/go-cid" + "github.com/multiformats/go-multihash" +) + +var ActorMethodTable = make(map[string][]string, 64) + +var Actors = map[cid.Cid]interface{}{ + builtin.InitActorCodeID: builtin.MethodsInit, + builtin.CronActorCodeID: builtin.MethodsCron, + builtin.AccountActorCodeID: builtin.MethodsAccount, + builtin.StoragePowerActorCodeID: builtin.MethodsPower, + builtin.StorageMinerActorCodeID: builtin.MethodsMiner, + builtin.StorageMarketActorCodeID: builtin.MethodsMarket, + builtin.PaymentChannelActorCodeID: builtin.MethodsPaych, + builtin.MultisigActorCodeID: builtin.MethodsMultisig, + builtin.RewardActorCodeID: builtin.MethodsReward, + builtin.VerifiedRegistryActorCodeID: builtin.MethodsVerifiedRegistry, +} + +func init() { + for code, methods := range Actors { + cmh, err := multihash.Decode(code.Hash()) // identity hash. + if err != nil { + panic(err) + } + + var ( + aname = string(cmh.Digest) + rt = reflect.TypeOf(methods) + nf = rt.NumField() + ) + + ActorMethodTable[aname] = append(ActorMethodTable[aname], "Send") + for i := 0; i < nf; i++ { + ActorMethodTable[aname] = append(ActorMethodTable[aname], rt.Field(i).Name) + } + } +} diff --git a/cmd/tvx/extract.go b/cmd/tvx/extract.go index 07c6ca7ef..e10fbad09 100644 --- a/cmd/tvx/extract.go +++ b/cmd/tvx/extract.go @@ -9,6 +9,7 @@ import ( "io" "log" "os" + "path/filepath" "github.com/fatih/color" @@ -28,7 +29,7 @@ import ( "github.com/urfave/cli/v2" ) -var extractFlags struct { +type extractOpts struct { id string block string class string @@ -37,6 +38,8 @@ var extractFlags struct { retain string } +var extractFlags extractOpts + var extractCmd = &cli.Command{ Name: "extract", Description: "generate a test vector by extracting it from a live chain", @@ -94,19 +97,23 @@ func runExtract(c *cli.Context) error { ctx := context.Background() - mcid, err := cid.Decode(extractFlags.cid) - if err != nil { - return err - } - // Make the API client. - api, closer, err := lcli.GetFullNodeAPI(c) + fapi, closer, err := lcli.GetFullNodeAPI(c) if err != nil { return err } defer closer() - msg, execTs, incTs, err := resolveFromChain(ctx, api, mcid) + return doExtract(ctx, fapi, extractFlags) +} + +func doExtract(ctx context.Context, fapi api.FullNode, opts extractOpts) error { + mcid, err := cid.Decode(opts.cid) + if err != nil { + return err + } + + msg, execTs, incTs, err := resolveFromChain(ctx, fapi, mcid, opts.block) if err != nil { return fmt.Errorf("failed to resolve message and tipsets from chain: %w", err) } @@ -119,7 +126,7 @@ func runExtract(c *cli.Context) error { // precursors, if any. var allmsgs []*types.Message for _, b := range incTs.Blocks() { - messages, err := api.ChainGetBlockMessages(ctx, b.Cid()) + messages, err := fapi.ChainGetBlockMessages(ctx, b.Cid()) if err != nil { return err } @@ -139,7 +146,7 @@ func runExtract(c *cli.Context) error { break } - log.Printf("message not found in block %s; precursors found: %v; ignoring block", b.Cid(), related) + log.Printf("message not found in block %s; number of precursors found: %d; ignoring block", b.Cid(), len(related)) } if allmsgs == nil { @@ -151,8 +158,8 @@ func runExtract(c *cli.Context) error { var ( // create a read-through store that uses ChainGetObject to fetch unknown CIDs. - pst = NewProxyingStores(ctx, api) - g = NewSurgeon(ctx, api, pst) + pst = NewProxyingStores(ctx, fapi) + g = NewSurgeon(ctx, fapi, pst) ) driver := conformance.NewDriver(ctx, schema.Selector{}, conformance.DriverOpts{ @@ -178,7 +185,7 @@ func runExtract(c *cli.Context) error { postroot cid.Cid applyret *vm.ApplyRet carWriter func(w io.Writer) error - retention = extractFlags.retain + retention = opts.retain ) log.Printf("using state retention strategy: %s", retention) @@ -204,7 +211,7 @@ func runExtract(c *cli.Context) error { case "accessed-actors": log.Printf("calculating accessed actors") // get actors accessed by message. - retain, err := g.GetAccessedActors(ctx, api, mcid) + retain, err := g.GetAccessedActors(ctx, fapi, mcid) if err != nil { return fmt.Errorf("failed to calculate accessed actors: %w", err) } @@ -267,12 +274,12 @@ func runExtract(c *cli.Context) error { return err } - version, err := api.Version(ctx) + version, err := fapi.Version(ctx) if err != nil { return err } - ntwkName, err := api.StateNetworkName(ctx) + ntwkName, err := fapi.StateNetworkName(ctx) if err != nil { return err } @@ -281,7 +288,7 @@ func runExtract(c *cli.Context) error { vector := schema.TestVector{ Class: schema.ClassMessage, Meta: &schema.Metadata{ - ID: extractFlags.id, + ID: opts.id, // TODO need to replace schema.GenerationData with a more flexible // data structure that makes no assumption about the traceability // data that's being recorded; a flexible map[string]string @@ -316,7 +323,11 @@ func runExtract(c *cli.Context) error { } output := io.WriteCloser(os.Stdout) - if file := extractFlags.file; file != "" { + if file := opts.file; file != "" { + dir := filepath.Dir(file) + if err := os.MkdirAll(dir, 0755); err != nil { + return fmt.Errorf("unable to create directory %s: %w", dir, err) + } output, err = os.Create(file) if err != nil { return err @@ -336,7 +347,7 @@ func runExtract(c *cli.Context) error { // resolveFromChain queries the chain for the provided message, using the block CID to // speed up the query, if provided -func resolveFromChain(ctx context.Context, api api.FullNode, mcid cid.Cid) (msg *types.Message, execTs *types.TipSet, incTs *types.TipSet, err error) { +func resolveFromChain(ctx context.Context, api api.FullNode, mcid cid.Cid, block string) (msg *types.Message, execTs *types.TipSet, incTs *types.TipSet, err error) { // Extract the full message. msg, err = api.ChainGetMessage(ctx, mcid) if err != nil { @@ -345,7 +356,6 @@ func resolveFromChain(ctx context.Context, api api.FullNode, mcid cid.Cid) (msg log.Printf("found message with CID %s: %+v", mcid, msg) - block := extractFlags.block if block == "" { log.Printf("locating message in blockchain") diff --git a/cmd/tvx/extract_many.go b/cmd/tvx/extract_many.go new file mode 100644 index 000000000..8fea8df4c --- /dev/null +++ b/cmd/tvx/extract_many.go @@ -0,0 +1,204 @@ +package main + +import ( + "context" + "encoding/csv" + "fmt" + "io" + "log" + "os" + "path/filepath" + "strconv" + "strings" + + "github.com/fatih/color" + "github.com/filecoin-project/go-state-types/exitcode" + "github.com/hashicorp/go-multierror" + "github.com/urfave/cli/v2" + + lcli "github.com/filecoin-project/lotus/cli" +) + +var extractManyFlags struct { + in string + outdir string +} + +var extractManyCmd = &cli.Command{ + Name: "extract-many", + Description: `generate many test vectors by repeateadly calling tvx extract, using a csv file as input. + + The CSV file must have a format just like the following: + + message_cid,receiver_code,method_num,exit_code,height,block_cid,seq + bafy2bzacedvuvgpsnwq7i7kltfap6hnp7fdmzf6lr4w34zycjrthb3v7k6zi6,fil/1/account,0,0,67972,bafy2bzacebthpxzlk7zhlkz3jfzl4qw7mdoswcxlf3rkof3b4mbxfj3qzfk7w,1 + bafy2bzacedwicofymn4imgny2hhbmcm4o5bikwnv3qqgohyx73fbtopiqlro6,fil/1/account,0,0,67860,bafy2bzacebj7beoxyzll522o6o76mt7von4psn3tlvunokhv4zhpwmfpipgti,2 + ... + + The first row MUST be a header row. At the bare minimum, those seven fields + must appear, in the order specified. Extra fields are accepted, but always + after these compulsory six. +`, + Action: runExtractMany, + Flags: []cli.Flag{ + &repoFlag, + &cli.StringFlag{ + Name: "in", + Usage: "path to input file (csv)", + Destination: &extractManyFlags.in, + }, + &cli.StringFlag{ + Name: "out-dir", + Usage: "output directory", + Destination: &extractManyFlags.outdir, + }, + }, +} + +func runExtractMany(c *cli.Context) error { + // LOTUS_DISABLE_VM_BUF disables what's called "VM state tree buffering", + // which stashes write operations in a BufferedBlockstore + // (https://github.com/filecoin-project/lotus/blob/b7a4dbb07fd8332b4492313a617e3458f8003b2a/lib/bufbstore/buf_bstore.go#L21) + // such that they're not written until the VM is actually flushed. + // + // For some reason, the standard behaviour was not working for me (raulk), + // and disabling it (such that the state transformations are written immediately + // to the blockstore) worked. + _ = os.Setenv("LOTUS_DISABLE_VM_BUF", "iknowitsabadidea") + + ctx := context.Background() + + // Make the API client. + fapi, closer, err := lcli.GetFullNodeAPI(c) + if err != nil { + return err + } + defer closer() + + var ( + in = extractManyFlags.in + outdir = extractManyFlags.outdir + ) + + if in == "" { + return fmt.Errorf("input file not provided") + } + + if outdir == "" { + return fmt.Errorf("output dir not provided") + } + + // Open the CSV file for reading. + f, err := os.Open(in) + if err != nil { + return fmt.Errorf("could not open file %s: %w", in, err) + } + + // Ensure the output directory exists. + if err := os.MkdirAll(outdir, 0755); err != nil { + return fmt.Errorf("could not create output dir %s: %w", outdir, err) + } + + // Create a CSV reader and validate the header row. + reader := csv.NewReader(f) + if header, err := reader.Read(); err != nil { + return fmt.Errorf("failed to read header from csv: %w", err) + } else if l := len(header); l < 7 { + return fmt.Errorf("insufficient number of fields: %d", l) + } else if f := header[0]; f != "message_cid" { + return fmt.Errorf("csv sanity check failed: expected first field in header to be 'message_cid'; was: %s", f) + } else { + log.Println(color.GreenString("csv sanity check succeeded; header contains fields: %v", header)) + } + + var generated []string + merr := new(multierror.Error) + // Read each row and extract the requested message. + for { + row, err := reader.Read() + if err == io.EOF { + break + } else if err != nil { + return fmt.Errorf("failed to read row: %w", err) + } + var ( + cid = row[0] + actorcode = row[1] + methodnumstr = row[2] + exitcodestr = row[3] + _ = row[4] + block = row[5] + seq = row[6] + + exit int + methodnum int + methodname string + ) + + // Parse the exit code. + if exit, err = strconv.Atoi(exitcodestr); err != nil { + return fmt.Errorf("invalid exitcode number: %d", exit) + } + // Parse the method number. + if methodnum, err = strconv.Atoi(methodnumstr); err != nil { + return fmt.Errorf("invalid method number: %s", methodnumstr) + } + + // Lookup the method in actor method table. + if m, ok := ActorMethodTable[actorcode]; !ok { + return fmt.Errorf("unrecognized actor: %s", actorcode) + } else if methodnum >= len(m) { + return fmt.Errorf("unrecognized method number for actor %s: %d", actorcode, methodnum) + } else { + methodname = m[methodnum] + } + + // exitcode string representations are of kind ErrType(0); strip out + // the number portion. + exitcodename := strings.Split(exitcode.ExitCode(exit).String(), "(")[0] + // replace the slashes in the actor code name with underscores. + actorcodename := strings.ReplaceAll(actorcode, "/", "_") + + // Compute the ID of the vector. + id := fmt.Sprintf("extracted-msg-%s-%s-%s-%s", actorcodename, methodname, exitcodename, seq) + // Vector filename, using a base of outdir. + file := filepath.Join(outdir, actorcodename, methodname, exitcodename, id) + ".json" + + log.Println(color.YellowString("processing message id: %s", id)) + + opts := extractOpts{ + id: id, + block: block, + class: "message", + cid: cid, + file: file, + retain: "accessed-cids", + } + + if err := doExtract(ctx, fapi, opts); err != nil { + merr = multierror.Append(err, fmt.Errorf("failed to extract vector for message %s: %w", cid, err)) + continue + } + + log.Println(color.MagentaString("generated file: %s", file)) + + generated = append(generated, file) + } + + if len(generated) == 0 { + log.Println("no files generated") + } else { + log.Println("files generated:") + for _, g := range generated { + log.Println(g) + } + } + + if merr.ErrorOrNil() != nil { + log.Println(color.YellowString("done processing with errors: %s")) + } else { + log.Println(color.GreenString("done processing with no errors")) + } + + return merr.ErrorOrNil() +} diff --git a/cmd/tvx/main.go b/cmd/tvx/main.go index 361ba41c3..6c887d163 100644 --- a/cmd/tvx/main.go +++ b/cmd/tvx/main.go @@ -23,7 +23,7 @@ var repoFlag = cli.StringFlag{ func main() { app := &cli.App{ Name: "tvx", - Description: `tvx is a tool for extracting and executing test vectors. It has two subcommands. + Description: `tvx is a tool for extracting and executing test vectors. It has three subcommands. tvx extract extracts a test vector from a live network. It requires access to a Filecoin client that exposes the standard JSON-RPC API endpoint. Only @@ -32,6 +32,9 @@ func main() { tvx exec executes test vectors against Lotus. Either you can supply one in a file, or many as an ndjson stdin stream. + tvx extract-many performs a batch extraction of many messages, supplied in a + CSV file. Refer to the help of that subcommand for more info. + SETTING THE JSON-RPC API ENDPOINT You can set the JSON-RPC API endpoint through one of the following methods. @@ -53,6 +56,7 @@ func main() { Commands: []*cli.Command{ extractCmd, execCmd, + extractManyCmd, }, } From 64f24fd276d0f964b78ece61fd2be6cdbb674b1f Mon Sep 17 00:00:00 2001 From: jennijuju Date: Mon, 28 Sep 2020 15:34:06 -0400 Subject: [PATCH 251/303] Added an option to hide sector info for `lotus-miner info` --- cmd/lotus-storage-miner/info.go | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/cmd/lotus-storage-miner/info.go b/cmd/lotus-storage-miner/info.go index 3ccfd67da..213d62e6e 100644 --- a/cmd/lotus-storage-miner/info.go +++ b/cmd/lotus-storage-miner/info.go @@ -33,6 +33,12 @@ var infoCmd = &cli.Command{ Subcommands: []*cli.Command{ infoAllCmd, }, + Flags: []cli.Flag{ + &cli.BoolFlag{ + Name: "hide-sectors-info", + Usage: "hide sectors info", + }, + }, Action: infoCmdAct, } @@ -199,10 +205,12 @@ func infoCmdAct(cctx *cli.Context) error { fmt.Printf("Expected Seal Duration: %s\n\n", sealdur) - fmt.Println("Sectors:") - err = sectorsInfo(ctx, nodeApi) - if err != nil { - return err + if !cctx.Bool("hide-sectors-info") { + fmt.Println("Sectors:") + err = sectorsInfo(ctx, nodeApi) + if err != nil { + return err + } } // TODO: grab actr state / info From 4b3b35c9defec5d2bfab6b527e4eeebe25109bd1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Kripalani?= Date: Mon, 28 Sep 2020 23:04:52 +0100 Subject: [PATCH 252/303] conformance: record and feed circulating supply. --- cmd/tvx/extract.go | 18 ++++++++++++++---- conformance/driver.go | 34 ++++++++++++++++++++++------------ conformance/runner.go | 8 +++++++- go.mod | 2 +- go.sum | 4 ++-- 5 files changed, 46 insertions(+), 20 deletions(-) diff --git a/cmd/tvx/extract.go b/cmd/tvx/extract.go index e10fbad09..0dc7f6aa0 100644 --- a/cmd/tvx/extract.go +++ b/cmd/tvx/extract.go @@ -118,8 +118,17 @@ func doExtract(ctx context.Context, fapi api.FullNode, opts extractOpts) error { return fmt.Errorf("failed to resolve message and tipsets from chain: %w", err) } + // get the circulating supply before the message was executed. + circSupplyDetail, err := fapi.StateCirculatingSupply(ctx, incTs.Key()) + if err != nil { + return fmt.Errorf("failed while fetching circulating supply: %w", err) + } + + circSupply := circSupplyDetail.FilCirculating.Int64() + log.Printf("message was executed in tipset: %s", execTs.Key()) log.Printf("message was included in tipset: %s", incTs.Key()) + log.Printf("circulating supply at inclusion tipset: %d", circSupply) log.Printf("finding precursor messages") // Iterate through blocks, finding the one that contains the message and its @@ -174,7 +183,7 @@ func doExtract(ctx context.Context, fapi api.FullNode, opts extractOpts) error { log.Printf("number of precursors to apply: %d", len(precursors)) for i, m := range precursors { log.Printf("applying precursor %d, cid: %s", i, m.Cid()) - _, root, err = driver.ExecuteMessage(pst.Blockstore, root, execTs.Height(), m) + _, root, err = driver.ExecuteMessage(pst.Blockstore, root, execTs.Height(), m, &circSupplyDetail.FilCirculating) if err != nil { return fmt.Errorf("failed to execute precursor message: %w", err) } @@ -199,7 +208,7 @@ func doExtract(ctx context.Context, fapi api.FullNode, opts extractOpts) error { tbs.StartTracing() preroot = root - applyret, postroot, err = driver.ExecuteMessage(pst.Blockstore, preroot, execTs.Height(), msg) + applyret, postroot, err = driver.ExecuteMessage(pst.Blockstore, preroot, execTs.Height(), msg, &circSupplyDetail.FilCirculating) if err != nil { return fmt.Errorf("failed to execute message: %w", err) } @@ -224,7 +233,7 @@ func doExtract(ctx context.Context, fapi api.FullNode, opts extractOpts) error { if err != nil { return err } - applyret, postroot, err = driver.ExecuteMessage(pst.Blockstore, preroot, execTs.Height(), msg) + applyret, postroot, err = driver.ExecuteMessage(pst.Blockstore, preroot, execTs.Height(), msg, &circSupplyDetail.FilCirculating) if err != nil { return fmt.Errorf("failed to execute message: %w", err) } @@ -302,7 +311,8 @@ func doExtract(ctx context.Context, fapi api.FullNode, opts extractOpts) error { }, CAR: out.Bytes(), Pre: &schema.Preconditions{ - Epoch: int64(execTs.Height()), + Epoch: int64(execTs.Height()), + CircSupply: &circSupply, StateTree: &schema.StateTree{ RootCID: preroot, }, diff --git a/conformance/driver.go b/conformance/driver.go index 90d05ae88..3f50b67a9 100644 --- a/conformance/driver.go +++ b/conformance/driver.go @@ -3,8 +3,6 @@ package conformance import ( "context" - "github.com/filecoin-project/go-state-types/crypto" - "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/stmgr" "github.com/filecoin-project/lotus/chain/store" @@ -15,6 +13,7 @@ import ( "github.com/filecoin-project/lotus/lib/blockstore" "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/test-vectors/schema" @@ -24,6 +23,11 @@ import ( ds "github.com/ipfs/go-datastore" ) +// DefaultCirculatingSupply is the fallback circulating supply returned by +// the driver's CircSupplyCalculator function, used if the vector specifies +// no circulating supply. +var DefaultCirculatingSupply = types.TotalFilecoinInt + var ( // BaseFee to use in the VM. // TODO make parametrisable through vector. @@ -136,18 +140,24 @@ func (d *Driver) ExecuteTipset(bs blockstore.Blockstore, ds ds.Batching, preroot } // ExecuteMessage executes a conformance test vector message in a temporary VM. -func (d *Driver) ExecuteMessage(bs blockstore.Blockstore, preroot cid.Cid, epoch abi.ChainEpoch, msg *types.Message) (*vm.ApplyRet, cid.Cid, error) { - // dummy state manager; only to reference the GetNetworkVersion method, which does not depend on state. +func (d *Driver) ExecuteMessage(bs blockstore.Blockstore, preroot cid.Cid, epoch abi.ChainEpoch, msg *types.Message, circSupply *abi.TokenAmount) (*vm.ApplyRet, cid.Cid, error) { + // dummy state manager; only to reference the GetNetworkVersion method, + // which does not depend on state. sm := new(stmgr.StateManager) vmOpts := &vm.VMOpts{ - StateBase: preroot, - Epoch: epoch, - Rand: &testRand{}, // TODO always succeeds; need more flexibility. - Bstore: bs, - Syscalls: mkFakedSigSyscalls(vm.Syscalls(ffiwrapper.ProofVerifier)), // TODO always succeeds; need more flexibility. - CircSupplyCalc: nil, - BaseFee: BaseFee, - NtwkVersion: sm.GetNtwkVersion, + StateBase: preroot, + Epoch: epoch, + Rand: &testRand{}, // TODO always succeeds; need more flexibility. + Bstore: bs, + Syscalls: mkFakedSigSyscalls(vm.Syscalls(ffiwrapper.ProofVerifier)), // TODO always succeeds; need more flexibility. + CircSupplyCalc: func(_ context.Context, _ abi.ChainEpoch, _ *state.StateTree) (abi.TokenAmount, error) { + if circSupply != nil { + return *circSupply, nil + } + return DefaultCirculatingSupply, nil + }, + BaseFee: BaseFee, + NtwkVersion: sm.GetNtwkVersion, } lvm, err := vm.NewVM(context.TODO(), vmOpts) diff --git a/conformance/runner.go b/conformance/runner.go index 0fc4b13fc..812f3cc08 100644 --- a/conformance/runner.go +++ b/conformance/runner.go @@ -45,6 +45,12 @@ func ExecuteMessageVector(r Reporter, vector *schema.TestVector) { // Create a new Driver. driver := NewDriver(ctx, vector.Selector, DriverOpts{}) + var circSupply *abi.TokenAmount + if cs := vector.Pre.CircSupply; cs != nil { + ta := abi.NewTokenAmount(*cs) + circSupply = &ta + } + // Apply every message. for i, m := range vector.ApplyMessages { msg, err := types.DecodeMessage(m.Bytes) @@ -59,7 +65,7 @@ func ExecuteMessageVector(r Reporter, vector *schema.TestVector) { // Execute the message. var ret *vm.ApplyRet - ret, root, err = driver.ExecuteMessage(bs, root, abi.ChainEpoch(epoch), msg) + ret, root, err = driver.ExecuteMessage(bs, root, abi.ChainEpoch(epoch), msg, circSupply) if err != nil { r.Fatalf("fatal failure when executing message: %s", err) } diff --git a/go.mod b/go.mod index b0de7dfd6..bf3748749 100644 --- a/go.mod +++ b/go.mod @@ -38,7 +38,7 @@ require ( github.com/filecoin-project/go-storedcounter v0.0.0-20200421200003-1c99c62e8a5b github.com/filecoin-project/specs-actors v0.9.11 github.com/filecoin-project/specs-storage v0.1.1-0.20200907031224-ed2e5cd13796 - github.com/filecoin-project/test-vectors/schema v0.0.1 + github.com/filecoin-project/test-vectors/schema v0.0.2 github.com/gbrlsnchs/jwt/v3 v3.0.0-beta.1 github.com/go-kit/kit v0.10.0 github.com/go-ole/go-ole v1.2.4 // indirect diff --git a/go.sum b/go.sum index bdb80aa83..6a310ed3d 100644 --- a/go.sum +++ b/go.sum @@ -258,8 +258,8 @@ github.com/filecoin-project/specs-actors v0.9.11 h1:TnpG7HAeiUrfj0mJM7UaPW0P2137 github.com/filecoin-project/specs-actors v0.9.11/go.mod h1:czlvLQGEX0fjLLfdNHD7xLymy6L3n7aQzRWzsYGf+ys= github.com/filecoin-project/specs-storage v0.1.1-0.20200907031224-ed2e5cd13796 h1:dJsTPWpG2pcTeojO2pyn0c6l+x/3MZYCBgo/9d11JEk= github.com/filecoin-project/specs-storage v0.1.1-0.20200907031224-ed2e5cd13796/go.mod h1:nJRRM7Aa9XVvygr3W9k6xGF46RWzr2zxF/iGoAIfA/g= -github.com/filecoin-project/test-vectors/schema v0.0.1 h1:5fNF76nl4qolEvcIsjc0kUADlTMVHO73tW4kXXPnsus= -github.com/filecoin-project/test-vectors/schema v0.0.1/go.mod h1:iQ9QXLpYWL3m7warwvK1JC/pTri8mnfEmKygNDqqY6E= +github.com/filecoin-project/test-vectors/schema v0.0.2 h1:/Pp//88WBXe0h+ksntdL2HpEgAmbwXrftAfeVG39zdY= +github.com/filecoin-project/test-vectors/schema v0.0.2/go.mod h1:iQ9QXLpYWL3m7warwvK1JC/pTri8mnfEmKygNDqqY6E= github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= github.com/flynn/noise v0.0.0-20180327030543-2492fe189ae6 h1:u/UEqS66A5ckRmS4yNpjmVH56sVtS/RfclBAYocb4as= github.com/flynn/noise v0.0.0-20180327030543-2492fe189ae6/go.mod h1:1i71OnUq3iUe1ma7Lr6yG6/rjvM3emb6yoL7xLFzcVQ= From 9b403e26e5d6c279383469cc86e1ac554b50ec75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Kripalani?= Date: Mon, 28 Sep 2020 23:07:45 +0100 Subject: [PATCH 253/303] fix lint. --- cmd/tvx/extract_many.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/tvx/extract_many.go b/cmd/tvx/extract_many.go index 8fea8df4c..83ec72b21 100644 --- a/cmd/tvx/extract_many.go +++ b/cmd/tvx/extract_many.go @@ -26,7 +26,7 @@ var extractManyFlags struct { var extractManyCmd = &cli.Command{ Name: "extract-many", - Description: `generate many test vectors by repeateadly calling tvx extract, using a csv file as input. + Description: `generate many test vectors by repeatedly calling tvx extract, using a csv file as input. The CSV file must have a format just like the following: From 044674487e56c6355354191ab546a5410aee789e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Kripalani?= Date: Mon, 28 Sep 2020 23:14:20 +0100 Subject: [PATCH 254/303] fix double mutex. --- cmd/tvx/stores.go | 3 --- 1 file changed, 3 deletions(-) diff --git a/cmd/tvx/stores.go b/cmd/tvx/stores.go index c389f8c88..6e50e0839 100644 --- a/cmd/tvx/stores.go +++ b/cmd/tvx/stores.go @@ -42,14 +42,11 @@ type Stores struct { // ChainReadObj RPC. func NewProxyingStores(ctx context.Context, api api.FullNode) *Stores { ds := dssync.MutexWrap(ds.NewMapDatastore()) - ds = dssync.MutexWrap(ds) - bs := &proxyingBlockstore{ ctx: ctx, api: api, Blockstore: blockstore.NewBlockstore(ds), } - return NewStores(ctx, ds, bs) } From eaece306b6c16efe642160f52d5e73a6a687d976 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Tue, 29 Sep 2020 11:17:23 +0200 Subject: [PATCH 255/303] wallet list cli: Print balances/nonces --- cli/wallet.go | 69 +++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 62 insertions(+), 7 deletions(-) diff --git a/cli/wallet.go b/cli/wallet.go index 27993a1ba..0d69673f9 100644 --- a/cli/wallet.go +++ b/cli/wallet.go @@ -9,13 +9,16 @@ import ( "os" "strings" - "github.com/filecoin-project/go-address" - "github.com/filecoin-project/go-state-types/crypto" - types "github.com/filecoin-project/lotus/chain/types" - "github.com/filecoin-project/lotus/chain/wallet" + "github.com/urfave/cli/v2" "golang.org/x/xerrors" - "github.com/urfave/cli/v2" + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/big" + "github.com/filecoin-project/go-state-types/crypto" + + types "github.com/filecoin-project/lotus/chain/types" + "github.com/filecoin-project/lotus/chain/wallet" + "github.com/filecoin-project/lotus/lib/tablewriter" ) var walletCmd = &cli.Command{ @@ -66,6 +69,13 @@ var walletNew = &cli.Command{ var walletList = &cli.Command{ Name: "list", Usage: "List wallet address", + Flags: []cli.Flag{ + &cli.BoolFlag{ + Name: "addr-only", + Usage: "Only print addresses", + Aliases: []string{"a"}, + }, + }, Action: func(cctx *cli.Context) error { api, closer, err := GetFullNodeAPI(cctx) if err != nil { @@ -79,9 +89,54 @@ var walletList = &cli.Command{ return err } - for _, addr := range addrs { - fmt.Println(addr.String()) + def, err := api.WalletDefaultAddress(ctx) + if err != nil { + return err } + + tw := tablewriter.New( + tablewriter.Col("Address"), + tablewriter.Col("Balance"), + tablewriter.Col("Nonce"), + tablewriter.Col("Default"), + tablewriter.NewLineCol("Error")) + + for _, addr := range addrs { + if cctx.Bool("addr-only") { + fmt.Println(addr.String()) + } else { + a, err := api.StateGetActor(ctx, addr, types.EmptyTSK) + if err != nil { + if !strings.Contains(err.Error(), "actor not found") { + tw.Write(map[string]interface{}{ + "Address": addr, + "Error": err, + }) + continue + } + + a = &types.Actor{ + Balance: big.Zero(), + } + } + + row := map[string]interface{}{ + "Address": addr, + "Balance": types.FIL(a.Balance), + "Nonce": a.Nonce, + } + if addr == def { + row["Default"] = "X" + } + + tw.Write(row) + } + } + + if !cctx.Bool("addr-only") { + return tw.Flush(os.Stdout) + } + return nil }, } From d1c10a61dd61a38a90c7d49dcd1cfeb74318eba4 Mon Sep 17 00:00:00 2001 From: Dirk McCormick Date: Tue, 29 Sep 2020 12:19:04 +0200 Subject: [PATCH 256/303] fix: message signer - always compare with mpool nonce --- chain/messagesigner/messagesigner.go | 44 +++++++++++++---------- chain/messagesigner/messagesigner_test.go | 5 ++- node/builder.go | 3 +- node/impl/full/mpool.go | 3 +- 4 files changed, 30 insertions(+), 25 deletions(-) diff --git a/chain/messagesigner/messagesigner.go b/chain/messagesigner/messagesigner.go index 41b0edee9..1ad83543b 100644 --- a/chain/messagesigner/messagesigner.go +++ b/chain/messagesigner/messagesigner.go @@ -4,21 +4,22 @@ import ( "bytes" "context" - "github.com/filecoin-project/lotus/chain/wallet" - - "github.com/filecoin-project/lotus/chain/messagepool" - "github.com/filecoin-project/go-address" + "github.com/filecoin-project/lotus/chain/messagepool" "github.com/filecoin-project/lotus/chain/types" + "github.com/filecoin-project/lotus/chain/wallet" "github.com/filecoin-project/lotus/node/modules/dtypes" "github.com/ipfs/go-datastore" "github.com/ipfs/go-datastore/namespace" + logging "github.com/ipfs/go-log/v2" cbg "github.com/whyrusleeping/cbor-gen" "golang.org/x/xerrors" ) const dsKeyActorNonce = "ActorNonce" +var log = logging.Logger("messagesigner") + type mpoolAPI interface { GetNonce(address.Address) (uint64, error) } @@ -67,30 +68,30 @@ func (ms *MessageSigner) SignMessage(ctx context.Context, msg *types.Message) (* // nextNonce increments the nonce. // If there is no nonce in the datastore, gets the nonce from the message pool. func (ms *MessageSigner) nextNonce(addr address.Address) (uint64, error) { - addrNonceKey := datastore.KeyWithNamespaces([]string{dsKeyActorNonce, addr.String()}) + // Nonces used to be created by the mempool and we need to support nodes + // that have mempool nonces, so first check the mempool for a nonce for + // this address. Note that the mempool returns the actor state's nonce + // by default. + nonce, err := ms.mpool.GetNonce(addr) + if err != nil { + return 0, xerrors.Errorf("failed to get nonce from mempool: %w", err) + } // Get the nonce for this address from the datastore - nonceBytes, err := ms.ds.Get(addrNonceKey) + addrNonceKey := datastore.KeyWithNamespaces([]string{dsKeyActorNonce, addr.String()}) + dsNonceBytes, err := ms.ds.Get(addrNonceKey) - var nonce uint64 switch { case xerrors.Is(err, datastore.ErrNotFound): // If a nonce for this address hasn't yet been created in the - // datastore, check the mempool - nonces used to be created by - // the mempool so we need to support nodes that still have mempool - // nonces. Note that the mempool returns the actor state's nonce by - // default. - nonce, err = ms.mpool.GetNonce(addr) - if err != nil { - return 0, xerrors.Errorf("failed to get nonce from mempool: %w", err) - } + // datastore, just use the nonce from the mempool case err != nil: return 0, xerrors.Errorf("failed to get nonce from datastore: %w", err) default: - // There is a nonce in the mempool, so unmarshall and increment it - maj, val, err := cbg.CborReadHeader(bytes.NewReader(nonceBytes)) + // There is a nonce in the datastore, so unmarshall and increment it + maj, val, err := cbg.CborReadHeader(bytes.NewReader(dsNonceBytes)) if err != nil { return 0, xerrors.Errorf("failed to parse nonce from datastore: %w", err) } @@ -98,7 +99,14 @@ func (ms *MessageSigner) nextNonce(addr address.Address) (uint64, error) { return 0, xerrors.Errorf("bad cbor type parsing nonce from datastore") } - nonce = val + 1 + dsNonce := val + 1 + + // The message pool nonce should be <= than the datastore nonce + if nonce <= dsNonce { + nonce = dsNonce + } else { + log.Warnf("mempool nonce was larger than datastore nonce (%d > %d)", nonce, dsNonce) + } } // Write the nonce for this address to the datastore diff --git a/chain/messagesigner/messagesigner_test.go b/chain/messagesigner/messagesigner_test.go index e52137892..55676b258 100644 --- a/chain/messagesigner/messagesigner_test.go +++ b/chain/messagesigner/messagesigner_test.go @@ -98,10 +98,9 @@ func TestMessageSignerSignMessage(t *testing.T) { To: to1, From: from1, }, - // Should ignore mpool nonce because after the first message nonce - // will come from the datastore + // Should adjust datastore nonce because mpool nonce is higher mpoolNonce: [1]uint64{10}, - expNonce: 6, + expNonce: 10, }}, }, { // Nonce should increment independently for each address diff --git a/node/builder.go b/node/builder.go index c49789a6a..da2924338 100644 --- a/node/builder.go +++ b/node/builder.go @@ -6,8 +6,6 @@ import ( "os" "time" - "github.com/filecoin-project/lotus/chain/messagesigner" - logging "github.com/ipfs/go-log" ci "github.com/libp2p/go-libp2p-core/crypto" "github.com/libp2p/go-libp2p-core/host" @@ -37,6 +35,7 @@ import ( "github.com/filecoin-project/lotus/chain/gen/slashfilter" "github.com/filecoin-project/lotus/chain/market" "github.com/filecoin-project/lotus/chain/messagepool" + "github.com/filecoin-project/lotus/chain/messagesigner" "github.com/filecoin-project/lotus/chain/metrics" "github.com/filecoin-project/lotus/chain/stmgr" "github.com/filecoin-project/lotus/chain/store" diff --git a/node/impl/full/mpool.go b/node/impl/full/mpool.go index 003260496..066aafdc5 100644 --- a/node/impl/full/mpool.go +++ b/node/impl/full/mpool.go @@ -4,14 +4,13 @@ import ( "context" "encoding/json" - "github.com/filecoin-project/lotus/chain/messagesigner" - "github.com/filecoin-project/go-address" "github.com/ipfs/go-cid" "go.uber.org/fx" "golang.org/x/xerrors" "github.com/filecoin-project/lotus/api" + "github.com/filecoin-project/lotus/chain/messagesigner" "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/node/modules/dtypes" ) From 09e5cc90a40791b3139e5eac8912532246ca8058 Mon Sep 17 00:00:00 2001 From: Hector Sanjuan Date: Tue, 29 Sep 2020 14:45:55 +0200 Subject: [PATCH 257/303] Add README to documentation/en with explanations --- documentation/en/README.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 documentation/en/README.md diff --git a/documentation/en/README.md b/documentation/en/README.md new file mode 100644 index 000000000..76f11ed90 --- /dev/null +++ b/documentation/en/README.md @@ -0,0 +1,16 @@ +# Lotus documentation + +This folder contains some Lotus documentation mostly intended for Lotus developers. + +User documentation (including documentation for miners) has been moved to specific Lotus sections in https://docs.filecoin.io: + +- https://docs.filecoin.io/get-started/lotus +- https://docs.filecoin.io/store/lotus +- https://docs.filecoin.io/mine/lotus +- https://docs.filecoin.io/build/lotus + +## The Lotu.sh site + +The https://lotu.sh and https://docs.lotu.sh sites are generated from this folder based on the index provided by [.library.json](.library.json). This is done at the [lotus-docs repository](https://github.com/filecoin-project/lotus-docs), which contains Lotus as a git submodule. + +To update the site, the lotus-docs repository should be updated with the desired version for the lotus git submodule. Once pushed to master, it will be auto-deployed. From 96193c20448a530e3f0c542700fb78fa928bc880 Mon Sep 17 00:00:00 2001 From: Jakub Sztandera Date: Wed, 16 Sep 2020 16:34:54 +0200 Subject: [PATCH 258/303] Implement bench-cache Signed-off-by: Jakub Sztandera --- cmd/lotus-bench/caching_verifier.go | 33 +++++++++++++++ cmd/lotus-bench/import.go | 63 +++++++++++++++++++++-------- 2 files changed, 80 insertions(+), 16 deletions(-) create mode 100644 cmd/lotus-bench/caching_verifier.go diff --git a/cmd/lotus-bench/caching_verifier.go b/cmd/lotus-bench/caching_verifier.go new file mode 100644 index 000000000..cd794e647 --- /dev/null +++ b/cmd/lotus-bench/caching_verifier.go @@ -0,0 +1,33 @@ +package main + +import ( + "context" + + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" + "github.com/filecoin-project/specs-actors/actors/runtime/proof" + "github.com/ipfs/go-datastore" +) + +type cachingVerifier struct { + ds datastore.Datastore + backend ffiwrapper.Verifier +} + +func (cv *cachingVerifier) VerifySeal(svi proof.SealVerifyInfo) (bool, error) { + svi.MarshalCBOR(nil) + return cv.backend.VerifySeal(svi) +} +func (cv *cachingVerifier) VerifyWinningPoSt(ctx context.Context, info proof.WinningPoStVerifyInfo) (bool, error) { + info.MarshalCBOR(nil) + return cv.backend.VerifyWinningPoSt(ctx, info) +} +func (cv *cachingVerifier) VerifyWindowPoSt(ctx context.Context, info proof.WindowPoStVerifyInfo) (bool, error) { + info.MarshalCBOR(nil) + return cv.backend.VerifyWindowPoSt(ctx, info) +} +func (cv *cachingVerifier) GenerateWinningPoStSectorChallenge(ctx context.Context, proofType abi.RegisteredPoStProof, a abi.ActorID, rnd abi.PoStRandomness, u uint64) ([]uint64, error) { + return cv.backend.GenerateWinningPoStSectorChallenge(ctx, proofType, a, rnd, u) +} + +var _ ffiwrapper.Verifier = (*cachingVerifier)(nil) diff --git a/cmd/lotus-bench/import.go b/cmd/lotus-bench/import.go index f2845ba20..fc81c600e 100644 --- a/cmd/lotus-bench/import.go +++ b/cmd/lotus-bench/import.go @@ -60,6 +60,15 @@ var importBenchCmd = &cli.Command{ Name: "repodir", Usage: "set the repo directory for the lotus bench run (defaults to /tmp)", }, + &cli.StringFlag{ + Name: "syscall-cache", + Usage: "read and write syscall results from datastore", + }, + &cli.BoolFlag{ + Name: "export-traces", + Usage: "should we export execution traces", + Value: true, + }, }, Action: func(cctx *cli.Context) error { vm.BatchSealVerifyParallelism = cctx.Int("batch-seal-verify-threads") @@ -85,7 +94,10 @@ var importBenchCmd = &cli.Command{ tdir = tmp } - bds, err := badger.NewDatastore(tdir, nil) + bdgOpt := badger.DefaultOptions + bdgOpt.GcInterval = 0 + + bds, err := badger.NewDatastore(tdir, &bdgOpt) if err != nil { return err } @@ -96,7 +108,21 @@ var importBenchCmd = &cli.Command{ } bs = cbs ds := datastore.NewMapDatastore() - cs := store.NewChainStore(bs, ds, vm.Syscalls(ffiwrapper.ProofVerifier)) + + var verifier ffiwrapper.Verifier = ffiwrapper.ProofVerifier + if cctx.IsSet("syscall-cache") { + + scds, err := badger.NewDatastore(cctx.String("syscall-cache"), &bdgOpt) + if err != nil { + return xerrors.Errorf("opening syscall-cache datastore: %w", err) + } + verifier = &cachingVerifier{ + ds: scds, + backend: verifier, + } + } + + cs := store.NewChainStore(bs, ds, vm.Syscalls(verifier)) stm := stmgr.NewStateManager(cs) prof, err := os.Create("import-bench.prof") @@ -144,13 +170,16 @@ var importBenchCmd = &cli.Command{ ts = next } - ibj, err := os.Create("import-bench.json") - if err != nil { - return err - } - defer ibj.Close() //nolint:errcheck + var enc *json.Encoder + if cctx.Bool("export-traces") { + ibj, err := os.Create("import-bench.json") + if err != nil { + return err + } + defer ibj.Close() //nolint:errcheck - enc := json.NewEncoder(ibj) + enc = json.NewEncoder(ibj) + } var lastTse *TipSetExec @@ -173,17 +202,19 @@ var importBenchCmd = &cli.Command{ if err != nil { return err } - stripCallers(trace) + if enc != nil { + stripCallers(trace) - lastTse = &TipSetExec{ - TipSet: cur.Key(), - Trace: trace, - Duration: time.Since(start), + lastTse = &TipSetExec{ + TipSet: cur.Key(), + Trace: trace, + Duration: time.Since(start), + } + if err := enc.Encode(lastTse); err != nil { + return xerrors.Errorf("failed to write out tipsetexec: %w", err) + } } lastState = st - if err := enc.Encode(lastTse); err != nil { - return xerrors.Errorf("failed to write out tipsetexec: %w", err) - } } pprof.StopCPUProfile() From 79ba4598d6f85bdc3e95faeb0e394af61e5e0666 Mon Sep 17 00:00:00 2001 From: Jakub Sztandera Date: Wed, 16 Sep 2020 17:54:22 +0200 Subject: [PATCH 259/303] Implement cache Signed-off-by: Jakub Sztandera --- cmd/lotus-bench/caching_verifier.go | 75 +++++++++++++++++++++++++++-- 1 file changed, 70 insertions(+), 5 deletions(-) diff --git a/cmd/lotus-bench/caching_verifier.go b/cmd/lotus-bench/caching_verifier.go index cd794e647..28897071a 100644 --- a/cmd/lotus-bench/caching_verifier.go +++ b/cmd/lotus-bench/caching_verifier.go @@ -1,12 +1,16 @@ package main import ( + "bufio" "context" + "errors" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" "github.com/filecoin-project/specs-actors/actors/runtime/proof" "github.com/ipfs/go-datastore" + "github.com/minio/blake2b-simd" + cbg "github.com/whyrusleeping/cbor-gen" ) type cachingVerifier struct { @@ -14,17 +18,78 @@ type cachingVerifier struct { backend ffiwrapper.Verifier } +const bufsize = 128 + +func (cv cachingVerifier) withCache(execute func() (bool, error), param cbg.CBORMarshaler) (bool, error) { + hasher := blake2b.New256() + wr := bufio.NewWriterSize(hasher, bufsize) + err := param.MarshalCBOR(wr) + if err != nil { + log.Errorf("could not marshal call info: %+v", err) + return execute() + } + err = wr.Flush() + if err != nil { + log.Errorf("could not flush: %+v", err) + return execute() + } + hash := hasher.Sum(nil) + key := datastore.NewKey(string(hash)) + fromDs, err := cv.ds.Get(key) + if err == nil { + switch fromDs[0] { + case 's': + return true, nil + case 'f': + return false, nil + case 'e': + return false, errors.New(string(fromDs[1:])) + default: + log.Errorf("bad cached result in cache %s(%x)", fromDs[0], fromDs[0]) + return execute() + } + } else if errors.Is(err, datastore.ErrNotFound) { + // recalc + ok, err := execute() + var save []byte + if err != nil { + if ok { + log.Errorf("sucess with an error: %+v", err) + } else { + save = append([]byte{'e'}, []byte(err.Error())...) + } + } else if ok { + save = []byte{'s'} + } else { + save = []byte{'f'} + } + + if len(save) != 0 { + errSave := cv.ds.Put(key, save) + if errSave != nil { + log.Errorf("error saving result: %+v", errSave) + } + } + + return ok, err + } else { + log.Errorf("could not get data from cache: %+v", err) + return execute() + } +} + func (cv *cachingVerifier) VerifySeal(svi proof.SealVerifyInfo) (bool, error) { - svi.MarshalCBOR(nil) - return cv.backend.VerifySeal(svi) + return cv.withCache(func() (bool, error) { + return cv.backend.VerifySeal(svi) + }, &svi) } func (cv *cachingVerifier) VerifyWinningPoSt(ctx context.Context, info proof.WinningPoStVerifyInfo) (bool, error) { - info.MarshalCBOR(nil) return cv.backend.VerifyWinningPoSt(ctx, info) } func (cv *cachingVerifier) VerifyWindowPoSt(ctx context.Context, info proof.WindowPoStVerifyInfo) (bool, error) { - info.MarshalCBOR(nil) - return cv.backend.VerifyWindowPoSt(ctx, info) + return cv.withCache(func() (bool, error) { + return cv.backend.VerifyWindowPoSt(ctx, info) + }, &info) } func (cv *cachingVerifier) GenerateWinningPoStSectorChallenge(ctx context.Context, proofType abi.RegisteredPoStProof, a abi.ActorID, rnd abi.PoStRandomness, u uint64) ([]uint64, error) { return cv.backend.GenerateWinningPoStSectorChallenge(ctx, proofType, a, rnd, u) From 53ab17cf50f5d7a69b81a6945bbe317a747bd10d Mon Sep 17 00:00:00 2001 From: Jakub Sztandera Date: Wed, 16 Sep 2020 20:10:00 +0200 Subject: [PATCH 260/303] Add no import to import-bench Signed-off-by: Jakub Sztandera --- cmd/lotus-bench/import.go | 37 +++++++++++++++++++++++++++---------- 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/cmd/lotus-bench/import.go b/cmd/lotus-bench/import.go index fc81c600e..c16796a13 100644 --- a/cmd/lotus-bench/import.go +++ b/cmd/lotus-bench/import.go @@ -24,6 +24,7 @@ import ( "github.com/filecoin-project/lotus/lib/blockstore" _ "github.com/filecoin-project/lotus/lib/sigs/bls" _ "github.com/filecoin-project/lotus/lib/sigs/secp" + "github.com/ipld/go-car" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" @@ -69,6 +70,10 @@ var importBenchCmd = &cli.Command{ Usage: "should we export execution traces", Value: true, }, + &cli.BoolFlag{ + Name: "no-import", + Usage: "should we import the chain? if set to true chain has to be previously imported", + }, }, Action: func(cctx *cli.Context) error { vm.BatchSealVerifyParallelism = cctx.Int("batch-seal-verify-threads") @@ -111,7 +116,6 @@ var importBenchCmd = &cli.Command{ var verifier ffiwrapper.Verifier = ffiwrapper.ProofVerifier if cctx.IsSet("syscall-cache") { - scds, err := badger.NewDatastore(cctx.String("syscall-cache"), &bdgOpt) if err != nil { return xerrors.Errorf("opening syscall-cache datastore: %w", err) @@ -135,9 +139,21 @@ var importBenchCmd = &cli.Command{ return err } - head, err := cs.Import(cfi) - if err != nil { - return err + var head *types.TipSet + if !cctx.Bool("no-import") { + head, err = cs.Import(cfi) + if err != nil { + return err + } + } else { + cr, err := car.NewCarReader(cfi) + if err != nil { + return err + } + head, err = cs.LoadTipSet(types.NewTipSetKey(cr.Header.Roots...)) + if err != nil { + return err + } } gb, err := cs.GetTipsetByHeight(context.TODO(), 0, head, true) @@ -188,6 +204,7 @@ var importBenchCmd = &cli.Command{ cur := tschain[i] log.Infof("computing state (height: %d, ts=%s)", cur.Height(), cur.Cids()) if cur.ParentState() != lastState { + stripCallers(lastTse.Trace) lastTrace := lastTse.Trace d, err := json.MarshalIndent(lastTrace, "", " ") if err != nil { @@ -202,14 +219,14 @@ var importBenchCmd = &cli.Command{ if err != nil { return err } + lastTse = &TipSetExec{ + TipSet: cur.Key(), + Trace: trace, + Duration: time.Since(start), + } if enc != nil { - stripCallers(trace) + stripCallers(lastTse.Trace) - lastTse = &TipSetExec{ - TipSet: cur.Key(), - Trace: trace, - Duration: time.Since(start), - } if err := enc.Encode(lastTse); err != nil { return xerrors.Errorf("failed to write out tipsetexec: %w", err) } From 1f4d1dcc58fc2da3574c479159775e4b19b1a720 Mon Sep 17 00:00:00 2001 From: Jakub Sztandera Date: Wed, 16 Sep 2020 20:38:28 +0200 Subject: [PATCH 261/303] Do not sync Signed-off-by: Jakub Sztandera --- cmd/lotus-bench/import.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cmd/lotus-bench/import.go b/cmd/lotus-bench/import.go index c16796a13..443e67950 100644 --- a/cmd/lotus-bench/import.go +++ b/cmd/lotus-bench/import.go @@ -101,6 +101,8 @@ var importBenchCmd = &cli.Command{ bdgOpt := badger.DefaultOptions bdgOpt.GcInterval = 0 + bdgOpt.Options.SyncWrites = false + bdgOpt.Options.Truncate = true bds, err := badger.NewDatastore(tdir, &bdgOpt) if err != nil { From 12a0dd3d0a0a6b80c1e11c2e05d39b5024d55139 Mon Sep 17 00:00:00 2001 From: Jakub Sztandera Date: Thu, 17 Sep 2020 00:06:20 +0200 Subject: [PATCH 262/303] <3 to linter Signed-off-by: Jakub Sztandera --- cmd/lotus-bench/caching_verifier.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/lotus-bench/caching_verifier.go b/cmd/lotus-bench/caching_verifier.go index 28897071a..51ab696f7 100644 --- a/cmd/lotus-bench/caching_verifier.go +++ b/cmd/lotus-bench/caching_verifier.go @@ -54,7 +54,7 @@ func (cv cachingVerifier) withCache(execute func() (bool, error), param cbg.CBOR var save []byte if err != nil { if ok { - log.Errorf("sucess with an error: %+v", err) + log.Errorf("success with an error: %+v", err) } else { save = append([]byte{'e'}, []byte(err.Error())...) } From 108fe7823c9dadf3d7e3812d79a66f4e6769ef5e Mon Sep 17 00:00:00 2001 From: Jakub Sztandera Date: Fri, 18 Sep 2020 13:39:38 +0200 Subject: [PATCH 263/303] Add command to trigger gc Signed-off-by: Jakub Sztandera --- cmd/lotus-bench/import.go | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/cmd/lotus-bench/import.go b/cmd/lotus-bench/import.go index 443e67950..72ac5d60b 100644 --- a/cmd/lotus-bench/import.go +++ b/cmd/lotus-bench/import.go @@ -74,6 +74,9 @@ var importBenchCmd = &cli.Command{ Name: "no-import", Usage: "should we import the chain? if set to true chain has to be previously imported", }, + &cli.BoolFlag{ + Name: "only-gc", + }, }, Action: func(cctx *cli.Context) error { vm.BatchSealVerifyParallelism = cctx.Int("batch-seal-verify-threads") @@ -103,11 +106,15 @@ var importBenchCmd = &cli.Command{ bdgOpt.GcInterval = 0 bdgOpt.Options.SyncWrites = false bdgOpt.Options.Truncate = true + bdgOpt.Options.DetectConflicts = false + bdgOpt.Options.MaxTableSize = 64 << 20 bds, err := badger.NewDatastore(tdir, &bdgOpt) if err != nil { return err } + + bds.CollectGarbage() bs := blockstore.NewBlockstore(bds) cbs, err := blockstore.CachedBlockstore(context.TODO(), bs, blockstore.DefaultCacheOpts()) if err != nil { @@ -122,11 +129,15 @@ var importBenchCmd = &cli.Command{ if err != nil { return xerrors.Errorf("opening syscall-cache datastore: %w", err) } + scds.CollectGarbage() verifier = &cachingVerifier{ ds: scds, backend: verifier, } } + if cctx.Bool("only-gc") { + return nil + } cs := store.NewChainStore(bs, ds, vm.Syscalls(verifier)) stm := stmgr.NewStateManager(cs) From 782717948ae9926e4afa7a42f758e8c70abe13d8 Mon Sep 17 00:00:00 2001 From: Jakub Sztandera Date: Fri, 18 Sep 2020 13:54:20 +0200 Subject: [PATCH 264/303] Add logs Signed-off-by: Jakub Sztandera --- cmd/lotus-bench/import.go | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/cmd/lotus-bench/import.go b/cmd/lotus-bench/import.go index 72ac5d60b..c6d49a78c 100644 --- a/cmd/lotus-bench/import.go +++ b/cmd/lotus-bench/import.go @@ -114,7 +114,11 @@ var importBenchCmd = &cli.Command{ return err } - bds.CollectGarbage() + if cctx.Bool("only-gc") { + log.Info("calling CollectGarbage on main ds") + bds.CollectGarbage() + log.Info("done calling CollectGarbage on main ds") + } bs := blockstore.NewBlockstore(bds) cbs, err := blockstore.CachedBlockstore(context.TODO(), bs, blockstore.DefaultCacheOpts()) if err != nil { @@ -129,7 +133,12 @@ var importBenchCmd = &cli.Command{ if err != nil { return xerrors.Errorf("opening syscall-cache datastore: %w", err) } - scds.CollectGarbage() + + if cctx.Bool("only-gc") { + log.Info("calling CollectGarbage on syscall ds") + scds.CollectGarbage() + log.Info("done calling CollectGarbage on syscall ds") + } verifier = &cachingVerifier{ ds: scds, backend: verifier, From 3858309368bfa069f86f71b3558ef4532d6f422f Mon Sep 17 00:00:00 2001 From: Jakub Sztandera Date: Fri, 18 Sep 2020 13:55:37 +0200 Subject: [PATCH 265/303] Add http to import bench Signed-off-by: Jakub Sztandera --- cmd/lotus-bench/import.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/cmd/lotus-bench/import.go b/cmd/lotus-bench/import.go index c6d49a78c..8c874206f 100644 --- a/cmd/lotus-bench/import.go +++ b/cmd/lotus-bench/import.go @@ -91,6 +91,10 @@ var importBenchCmd = &cli.Command{ } defer cfi.Close() //nolint:errcheck // read only file + go func() { + http.ListenAndServe("localhost:6060", nil) //nolint:errcheck + }() + var tdir string if rdir := cctx.String("repodir"); rdir != "" { tdir = rdir From 01386a206c0c8c9d9007d35a80307cae93b0781b Mon Sep 17 00:00:00 2001 From: Jakub Sztandera Date: Fri, 18 Sep 2020 15:17:13 +0200 Subject: [PATCH 266/303] Update options Signed-off-by: Jakub Sztandera --- cmd/lotus-bench/import.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cmd/lotus-bench/import.go b/cmd/lotus-bench/import.go index 8c874206f..db87ebeb6 100644 --- a/cmd/lotus-bench/import.go +++ b/cmd/lotus-bench/import.go @@ -29,8 +29,10 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" + bdg "github.com/dgraph-io/badger/v2" "github.com/ipfs/go-datastore" badger "github.com/ipfs/go-ds-badger2" + "github.com/urfave/cli/v2" "golang.org/x/xerrors" ) @@ -108,10 +110,10 @@ var importBenchCmd = &cli.Command{ bdgOpt := badger.DefaultOptions bdgOpt.GcInterval = 0 + bdgOpt.Options = bdg.DefaultOptions("") bdgOpt.Options.SyncWrites = false bdgOpt.Options.Truncate = true bdgOpt.Options.DetectConflicts = false - bdgOpt.Options.MaxTableSize = 64 << 20 bds, err := badger.NewDatastore(tdir, &bdgOpt) if err != nil { From f21c5cbbe28fe382c1670298e11819cf4949e7af Mon Sep 17 00:00:00 2001 From: Jakub Sztandera Date: Sat, 19 Sep 2020 19:11:37 +0200 Subject: [PATCH 267/303] Add start-at Signed-off-by: Jakub Sztandera --- cmd/lotus-bench/import.go | 69 ++++++++++++++++++++++++--------------- go.mod | 9 ++--- go.sum | 31 ++++++++++++++++++ 3 files changed, 78 insertions(+), 31 deletions(-) diff --git a/cmd/lotus-bench/import.go b/cmd/lotus-bench/import.go index db87ebeb6..3c5bd0cda 100644 --- a/cmd/lotus-bench/import.go +++ b/cmd/lotus-bench/import.go @@ -28,6 +28,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" + "github.com/filecoin-project/statediff" bdg "github.com/dgraph-io/badger/v2" "github.com/ipfs/go-datastore" @@ -79,6 +80,9 @@ var importBenchCmd = &cli.Command{ &cli.BoolFlag{ Name: "only-gc", }, + &cli.Int64Flag{ + Name: "start-at", + }, }, Action: func(cctx *cli.Context) error { vm.BatchSealVerifyParallelism = cctx.Int("batch-seal-verify-threads") @@ -194,6 +198,20 @@ var importBenchCmd = &cli.Command{ return err } + startEpoch := abi.ChainEpoch(1) + if cctx.IsSet("start-at") { + startEpoch = abi.ChainEpoch(cctx.Int64("start-at")) + start, err := cs.GetTipsetByHeight(context.TODO(), abi.ChainEpoch(cctx.Int64("start-at")), head, true) + if err != nil { + return err + } + + err = cs.SetHead(start) + if err != nil { + return err + } + } + if h := cctx.Int64("height"); h != 0 { tsh, err := cs.GetTipsetByHeight(context.TODO(), abi.ChainEpoch(h), head, true) if err != nil { @@ -204,7 +222,7 @@ var importBenchCmd = &cli.Command{ ts := head tschain := []*types.TipSet{ts} - for ts.Height() != 0 { + for ts.Height() > startEpoch { next, err := cs.LoadTipSet(ts.Parents()) if err != nil { return err @@ -225,41 +243,38 @@ var importBenchCmd = &cli.Command{ enc = json.NewEncoder(ibj) } - var lastTse *TipSetExec - - lastState := tschain[len(tschain)-1].ParentState() - for i := len(tschain) - 2; i >= 0; i-- { + for i := len(tschain) - 1; i >= 1; i-- { cur := tschain[i] + start := time.Now() log.Infof("computing state (height: %d, ts=%s)", cur.Height(), cur.Cids()) - if cur.ParentState() != lastState { - stripCallers(lastTse.Trace) - lastTrace := lastTse.Trace + st, trace, err := stm.ExecutionTrace(context.TODO(), cur) + if err != nil { + return err + } + tse := &TipSetExec{ + TipSet: cur.Key(), + Trace: trace, + Duration: time.Since(start), + } + if enc != nil { + stripCallers(tse.Trace) + + if err := enc.Encode(tse); err != nil { + return xerrors.Errorf("failed to write out tipsetexec: %w", err) + } + } + if tschain[i-1].ParentState() != st { + stripCallers(tse.Trace) + lastTrace := tse.Trace d, err := json.MarshalIndent(lastTrace, "", " ") if err != nil { panic(err) } fmt.Println("TRACE") fmt.Println(string(d)) - return xerrors.Errorf("tipset chain had state mismatch at height %d (%s != %s)", cur.Height(), cur.ParentState(), lastState) + fmt.Println(statediff.Diff(context.Background(), bs, tschain[i-1].ParentState(), st, statediff.ExpandActors)) + return xerrors.Errorf("tipset chain had state mismatch at height %d (%s != %s)", cur.Height(), cur.ParentState(), st) } - start := time.Now() - st, trace, err := stm.ExecutionTrace(context.TODO(), cur) - if err != nil { - return err - } - lastTse = &TipSetExec{ - TipSet: cur.Key(), - Trace: trace, - Duration: time.Since(start), - } - if enc != nil { - stripCallers(lastTse.Trace) - - if err := enc.Encode(lastTse); err != nil { - return xerrors.Errorf("failed to write out tipsetexec: %w", err) - } - } - lastState = st } pprof.StopCPUProfile() diff --git a/go.mod b/go.mod index 2c0322ecc..83137d7c8 100644 --- a/go.mod +++ b/go.mod @@ -8,7 +8,6 @@ require ( github.com/BurntSushi/toml v0.3.1 github.com/GeertJohan/go.rice v1.0.0 github.com/Gurpartap/async v0.0.0-20180927173644-4f7f499dd9ee - github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d // indirect github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d github.com/buger/goterm v0.0.0-20200322175922-2f3e71b85129 github.com/coreos/go-systemd/v22 v22.0.0 @@ -38,10 +37,10 @@ require ( github.com/filecoin-project/go-storedcounter v0.0.0-20200421200003-1c99c62e8a5b github.com/filecoin-project/specs-actors v0.9.11 github.com/filecoin-project/specs-storage v0.1.1-0.20200907031224-ed2e5cd13796 + github.com/filecoin-project/statediff v0.0.6-0.20200918150628-da86dd0d264c github.com/filecoin-project/test-vectors/schema v0.0.1 github.com/gbrlsnchs/jwt/v3 v3.0.0-beta.1 github.com/go-kit/kit v0.10.0 - github.com/go-ole/go-ole v1.2.4 // indirect github.com/google/uuid v1.1.1 github.com/gorilla/mux v1.7.4 github.com/gorilla/websocket v1.4.2 @@ -117,7 +116,6 @@ require ( github.com/whyrusleeping/pubsub v0.0.0-20131020042734-02de8aa2db3d github.com/xorcare/golden v0.6.1-0.20191112154924-b87f686d7542 go.opencensus.io v0.22.4 - go.uber.org/dig v1.10.0 // indirect go.uber.org/fx v1.9.0 go.uber.org/multierr v1.5.0 go.uber.org/zap v1.15.0 @@ -127,9 +125,12 @@ require ( golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 gopkg.in/cheggaaa/pb.v1 v1.0.28 gotest.tools v2.2.0+incompatible - launchpad.net/gocheck v0.0.0-20140225173054-000000000087 // indirect ) +replace github.com/filecoin-project/lotus => ./ + +replace github.com/filecoin-project/statediff => ./../statediff + replace github.com/golangci/golangci-lint => github.com/golangci/golangci-lint v1.18.0 replace github.com/filecoin-project/filecoin-ffi => ./extern/filecoin-ffi diff --git a/go.sum b/go.sum index 05e643708..2455766b1 100644 --- a/go.sum +++ b/go.sum @@ -159,6 +159,8 @@ github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/davidlazar/go-crypto v0.0.0-20170701192655-dcfb0a7ac018/go.mod h1:rQYf4tfk5sSwFsnDg3qYaBxSjsD9S8+59vW0dKUgme4= github.com/davidlazar/go-crypto v0.0.0-20190912175916-7055855a373f h1:BOaYiTvg8p9vBUXpklC22XSK/mifLF7lG9jtmYYi3Tc= github.com/davidlazar/go-crypto v0.0.0-20190912175916-7055855a373f/go.mod h1:rQYf4tfk5sSwFsnDg3qYaBxSjsD9S8+59vW0dKUgme4= +github.com/davidlazar/go-crypto v0.0.0-20200604182044-b73af7476f6c h1:pFUpOrbxDR6AkioZ1ySsx5yxlDQZ8stG2b88gTPxgJU= +github.com/davidlazar/go-crypto v0.0.0-20200604182044-b73af7476f6c/go.mod h1:6UhI8N9EjYm1c2odKpFpAYeR8dsBeM7PtzQhRgxRr9U= github.com/detailyang/go-fallocate v0.0.0-20180908115635-432fa640bd2e h1:lj77EKYUpYXTd8CD/+QMIf8b6OIOTsfEBSXiAzuEHTU= github.com/detailyang/go-fallocate v0.0.0-20180908115635-432fa640bd2e/go.mod h1:3ZQK6DMPSz/QZ73jlWxBtUhNA8xZx7LzUFSq/OfP8vk= github.com/dgraph-io/badger v1.5.5-0.20190226225317-8115aed38f8f/go.mod h1:VZxzAIRPHRVNRKRo6AXrX9BJegn6il06VMTZVJYCIjQ= @@ -206,6 +208,7 @@ github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymF github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/evanw/esbuild v0.6.28/go.mod h1:mptxmSXIzBIKKCe4jo9A5SToEd1G+AKZ9JmY85dYRJ0= github.com/facebookgo/atomicfile v0.0.0-20151019160806-2de1f203e7d5 h1:BBso6MBKW8ncyZLv37o+KNyy0HrrHgfnOaGQC2qvN+A= github.com/facebookgo/atomicfile v0.0.0-20151019160806-2de1f203e7d5/go.mod h1:JpoxHjuQauoxiFMl1ie8Xc/7TfLuMZ5eOCONd1sUBHg= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= @@ -218,6 +221,8 @@ github.com/filecoin-project/go-address v0.0.4 h1:gSNMv0qWwH16fGQs7ycOUrDjY6YCSsg github.com/filecoin-project/go-address v0.0.4/go.mod h1:jr8JxKsYx+lQlQZmF5i2U0Z+cGQ59wMIps/8YW/lDj8= github.com/filecoin-project/go-amt-ipld/v2 v2.1.0 h1:t6qDiuGYYngDqaLc2ZUvdtAg4UNxPeOYaXhBWSNsVaM= github.com/filecoin-project/go-amt-ipld/v2 v2.1.0/go.mod h1:nfFPoGyX0CU9SkXX8EoCcSuHN1XcbN0c6KBh7yvP5fs= +github.com/filecoin-project/go-amt-ipld/v2 v2.1.1-0.20200731171407-e559a0579161 h1:K6t4Hrs+rwUxBz2xg88Bdqeh4k5/rycQFdPseZhRyfE= +github.com/filecoin-project/go-amt-ipld/v2 v2.1.1-0.20200731171407-e559a0579161/go.mod h1:vgmwKBkx+ca5OIeEvstiQgzAZnb7R6QaqE1oEDSqa6g= github.com/filecoin-project/go-bitfield v0.2.0 h1:gCtLcjskIPtdg4NfN7gQZSQF9yrBQ7mkT0qCJxzGI2Q= github.com/filecoin-project/go-bitfield v0.2.0/go.mod h1:CNl9WG8hgR5mttCnUErjcQjGvuiZjRqK9rHVBsQF4oM= github.com/filecoin-project/go-cbor-util v0.0.0-20191219014500-08c40a1e63a2 h1:av5fw6wmm58FYMgJeoB/lK9XXrgdugYiTqkdxjTy9k8= @@ -280,6 +285,7 @@ github.com/go-check/check v0.0.0-20180628173108-788fd7840127/go.mod h1:9ES+weclK github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/kit v0.10.0 h1:dXFJfIHVvUcpSgDOV+Ne6t7jXri8Tfv2uOLHUZ2XNuo= @@ -506,6 +512,11 @@ github.com/ipfs/go-fs-lock v0.0.6/go.mod h1:OTR+Rj9sHiRubJh3dRhD15Juhd/+w6VPOY28 github.com/ipfs/go-graphsync v0.1.0/go.mod h1:jMXfqIEDFukLPZHqDPp8tJMbHO9Rmeb9CEGevngQbmE= github.com/ipfs/go-graphsync v0.2.1 h1:MdehhqBSuTI2LARfKLkpYnt0mUrqHs/mtuDnESXHBfU= github.com/ipfs/go-graphsync v0.2.1/go.mod h1:gEBvJUNelzMkaRPJTpg/jaKN4AQW/7wDWu0K92D8o10= +github.com/ipfs/go-graphsync v0.2.0 h1:x94MvHLNuRwBlZzVal7tR1RYK7T7H6bqQLPopxDbIF0= +github.com/ipfs/go-graphsync v0.2.0/go.mod h1:gEBvJUNelzMkaRPJTpg/jaKN4AQW/7wDWu0K92D8o10= +github.com/ipfs/go-graphsync v0.1.2 h1:25Ll9kIXCE+DY0dicvfS3KMw+U5sd01b/FJbA7KAbhg= +github.com/ipfs/go-graphsync v0.1.2/go.mod h1:sLXVXm1OxtE2XYPw62MuXCdAuNwkAdsbnfrmos5odbA= +github.com/ipfs/go-hamt-ipld v0.1.1 h1:0IQdvwnAAUKmDE+PMJa5y1QiwOPHpI9+eAbQEEEYthk= github.com/ipfs/go-hamt-ipld v0.1.1/go.mod h1:1EZCr2v0jlCnhpa+aZ0JZYp8Tt2w16+JJOAVz17YcDk= github.com/ipfs/go-ipfs-blockstore v0.0.1/go.mod h1:d3WClOmRQKFnJ0Jz/jj/zmksX0ma1gROTlovZKBmN08= github.com/ipfs/go-ipfs-blockstore v0.1.0/go.mod h1:5aD0AvHPi7mZc6Ci1WCAhiBQu2IsfTduLl+422H6Rqw= @@ -688,6 +699,7 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/pty v1.1.3/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/lib/pq v1.7.0 h1:h93mCPfUSkaul3Ka/VG8uZdmW1uMHDGxzu0NWHuJmHY= github.com/lib/pq v1.7.0/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/libp2p/go-addr-util v0.0.1/go.mod h1:4ac6O7n9rIAKB1dnd+s8IbbMXkt+oBpzX4/+RACcnlQ= @@ -1015,6 +1027,8 @@ github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNx github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.8 h1:HLtExJ+uU2HOZ+wI0Tt5DtUDrx8yhUqDcp7fYERX4CE= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/mattn/go-runewidth v0.0.7 h1:Ei8KR0497xHyKJPAv59M1dkC+rOZCMBJ+t3fZ+twI54= github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= @@ -1317,6 +1331,8 @@ github.com/streadway/handy v0.0.0-20190108123426-d5acb3125c2a/go.mod h1:qNTQ5P5J github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.2.0 h1:Hbg2NidpLE8veEBkEZTL3CvlkUIVzuU9jDplZO54c48= +github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= @@ -1369,6 +1385,7 @@ github.com/whyrusleeping/cbor-gen v0.0.0-20200414195334-429a0b5e922e/go.mod h1:X github.com/whyrusleeping/cbor-gen v0.0.0-20200504204219-64967432584d/go.mod h1:W5MvapuoHRP8rz4vxjwCK1pDqF1aQcWsV5PZ+AHbqdg= github.com/whyrusleeping/cbor-gen v0.0.0-20200710004633-5379fc63235d/go.mod h1:fgkXqYy7bV2cFeIEOkVTZS/WjXARfBqSH6Q2qHL33hQ= github.com/whyrusleeping/cbor-gen v0.0.0-20200715143311-227fab5a2377/go.mod h1:fgkXqYy7bV2cFeIEOkVTZS/WjXARfBqSH6Q2qHL33hQ= +github.com/whyrusleeping/cbor-gen v0.0.0-20200723185710-6a3894a6352b/go.mod h1:fgkXqYy7bV2cFeIEOkVTZS/WjXARfBqSH6Q2qHL33hQ= github.com/whyrusleeping/cbor-gen v0.0.0-20200810223238-211df3b9e24c/go.mod h1:fgkXqYy7bV2cFeIEOkVTZS/WjXARfBqSH6Q2qHL33hQ= github.com/whyrusleeping/cbor-gen v0.0.0-20200812213548-958ddffe352c/go.mod h1:fgkXqYy7bV2cFeIEOkVTZS/WjXARfBqSH6Q2qHL33hQ= github.com/whyrusleeping/cbor-gen v0.0.0-20200814224545-656e08ce49ee h1:U7zWWvvAjT76EiuWPSOiZlQDnaQYPxPoxugTtTAcJK0= @@ -1395,6 +1412,8 @@ github.com/whyrusleeping/pubsub v0.0.0-20131020042734-02de8aa2db3d/go.mod h1:g7c github.com/whyrusleeping/timecache v0.0.0-20160911033111-cfcb2f1abfee h1:lYbXeSvJi5zk5GLKVuid9TVjS9a0OmLIDKTfoZBL6Ow= github.com/whyrusleeping/timecache v0.0.0-20160911033111-cfcb2f1abfee/go.mod h1:m2aV4LZI4Aez7dP5PMyVKEHhUyEJ/RjmPEDOpDvudHg= github.com/whyrusleeping/yamux v1.1.5/go.mod h1:E8LnQQ8HKx5KD29HZFUwM1PxCOdPRzGwur1mcYhXcD8= +github.com/willscott/go-cmp v0.5.2-0.20200812183318-8affb9542345 h1:IJVAwIctqDFOrO0C2qzksXmANviyHJzrklU27e1ltzE= +github.com/willscott/go-cmp v0.5.2-0.20200812183318-8affb9542345/go.mod h1:D7hA8H5pyQx7Y5Em7IWx1R4vNJzfon3gpG9nxjkITjQ= github.com/x-cray/logrus-prefixed-formatter v0.5.2/go.mod h1:2duySbKsL6M18s5GU7VPsoEPHyzalCE06qoARUCeBBE= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/xlab/c-for-go v0.0.0-20200718154222-87b0065af829 h1:wb7xrDzfkLgPHsSEBm+VSx6aDdi64VtV0xvP0E6j8bk= @@ -1483,6 +1502,7 @@ golang.org/x/crypto v0.0.0-20200128174031-69ecbb4d6d5d/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20200221231518-2aa609cf4a9d/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200423211502-4bdfaf469ed5/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200602180216-279210d13fed/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= @@ -1495,6 +1515,8 @@ golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u0 golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= golang.org/x/exp v0.0.0-20200207192155-f17229e696bd h1:zkO/Lhoka23X63N9OSzpSeROEUQ5ODw47tM3YWjygbs= golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= +golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6 h1:QE6XYQK6naiK1EPAe1g/ILLxN5RBoH5xkJk3CqlMI/Y= +golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= @@ -1508,11 +1530,14 @@ golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHl golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= golang.org/x/lint v0.0.0-20200130185559-910be7a94367 h1:0IiAsCRByjO2QjX7ZPkw5oU9x+n1YqRL802rjC0c3Aw= golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20200302205851-738671d3881b h1:Wh+f8QHJXR411sJR8/vRBTZ7YapZaRvUcLFFJhusH0k= +golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= @@ -1614,6 +1639,7 @@ golang.org/x/sys v0.0.0-20190902133755-9109b7679e13/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190922100055-0a153f010e69/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190924154521-2837fb4f24fe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191025021431-6c3a3bfe00ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -1623,6 +1649,7 @@ golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20191220142924-d4481acd189f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -1631,6 +1658,7 @@ golang.org/x/sys v0.0.0-20200217220822-9197077df867/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200420163511-1957bb5e6d1f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200501145240-bc7a7d42d5c3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200509044756-6aff5f38e54f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200602225109-6fdc65e7d980 h1:OjiUf46hAmXblsZdnoSXsEUSKU8r1UEzcL5RVZ4gO9Y= @@ -1674,6 +1702,7 @@ golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191216052735-49a3e744a425/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= @@ -1802,6 +1831,8 @@ honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWh honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.1-2019.2.3 h1:3JgtbtFHMiCmsznwGVTUWbgGov+pVqnlf1dEJTNAXeM= honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +honnef.co/go/tools v0.0.1-2020.1.3 h1:sXmLre5bzIR6ypkjXCDI3jHPssRhc8KD/Ome589sc3U= +honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= howett.net/plist v0.0.0-20181124034731-591f970eefbb h1:jhnBjNi9UFpfpl8YZhA9CrOqpnJdvzuiHsl/dnxl11M= howett.net/plist v0.0.0-20181124034731-591f970eefbb/go.mod h1:vMygbs4qMhSZSc4lCUl2OEE+rDiIIJAIdR4m7MiMcm0= launchpad.net/gocheck v0.0.0-20140225173054-000000000087 h1:Izowp2XBH6Ya6rv+hqbceQyw/gSGoXfH/UPoTGduL54= From ebc8489ff183859cc0d567bd95b5904183b25152 Mon Sep 17 00:00:00 2001 From: Jakub Sztandera Date: Sat, 19 Sep 2020 20:27:24 +0200 Subject: [PATCH 268/303] Add global-profile option Signed-off-by: Jakub Sztandera --- cmd/lotus-bench/import.go | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/cmd/lotus-bench/import.go b/cmd/lotus-bench/import.go index 3c5bd0cda..e201baa85 100644 --- a/cmd/lotus-bench/import.go +++ b/cmd/lotus-bench/import.go @@ -80,6 +80,10 @@ var importBenchCmd = &cli.Command{ &cli.BoolFlag{ Name: "only-gc", }, + &cli.BoolFlag{ + Name: "global-profile", + Value: true, + }, &cli.Int64Flag{ Name: "start-at", }, @@ -161,14 +165,16 @@ var importBenchCmd = &cli.Command{ cs := store.NewChainStore(bs, ds, vm.Syscalls(verifier)) stm := stmgr.NewStateManager(cs) - prof, err := os.Create("import-bench.prof") - if err != nil { - return err - } - defer prof.Close() //nolint:errcheck + if cctx.Bool("global-profile") { + prof, err := os.Create("import-bench.prof") + if err != nil { + return err + } + defer prof.Close() //nolint:errcheck - if err := pprof.StartCPUProfile(prof); err != nil { - return err + if err := pprof.StartCPUProfile(prof); err != nil { + return err + } } var head *types.TipSet From 35cf69ae646574557acfaaa8bd65a4693560b352 Mon Sep 17 00:00:00 2001 From: Jakub Sztandera Date: Sat, 19 Sep 2020 20:49:40 +0200 Subject: [PATCH 269/303] Disable bloomcache Signed-off-by: Jakub Sztandera --- cmd/lotus-bench/import.go | 3 +++ go.mod | 1 + 2 files changed, 4 insertions(+) diff --git a/cmd/lotus-bench/import.go b/cmd/lotus-bench/import.go index e201baa85..5da4f2d3d 100644 --- a/cmd/lotus-bench/import.go +++ b/cmd/lotus-bench/import.go @@ -134,6 +134,9 @@ var importBenchCmd = &cli.Command{ log.Info("done calling CollectGarbage on main ds") } bs := blockstore.NewBlockstore(bds) + cacheOpts := blockstore.DefaultCacheOpts() + cacheOpts.HasBloomFilterSize = 0 + cbs, err := blockstore.CachedBlockstore(context.TODO(), bs, blockstore.DefaultCacheOpts()) if err != nil { return err diff --git a/go.mod b/go.mod index 83137d7c8..d2e552ffc 100644 --- a/go.mod +++ b/go.mod @@ -116,6 +116,7 @@ require ( github.com/whyrusleeping/pubsub v0.0.0-20131020042734-02de8aa2db3d github.com/xorcare/golden v0.6.1-0.20191112154924-b87f686d7542 go.opencensus.io v0.22.4 + go.uber.org/dig v1.10.0 // indirect go.uber.org/fx v1.9.0 go.uber.org/multierr v1.5.0 go.uber.org/zap v1.15.0 From 242a77b391c001ddf3fad53c3f5c8160e157c4c3 Mon Sep 17 00:00:00 2001 From: Jakub Sztandera Date: Sat, 19 Sep 2020 20:50:06 +0200 Subject: [PATCH 270/303] go mod tidy Signed-off-by: Jakub Sztandera --- cmd/lotus-bench/import.go | 2 +- go.mod | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/cmd/lotus-bench/import.go b/cmd/lotus-bench/import.go index 5da4f2d3d..428fd4212 100644 --- a/cmd/lotus-bench/import.go +++ b/cmd/lotus-bench/import.go @@ -137,7 +137,7 @@ var importBenchCmd = &cli.Command{ cacheOpts := blockstore.DefaultCacheOpts() cacheOpts.HasBloomFilterSize = 0 - cbs, err := blockstore.CachedBlockstore(context.TODO(), bs, blockstore.DefaultCacheOpts()) + cbs, err := blockstore.CachedBlockstore(context.TODO(), bs, cacheOpts) if err != nil { return err } diff --git a/go.mod b/go.mod index d2e552ffc..83137d7c8 100644 --- a/go.mod +++ b/go.mod @@ -116,7 +116,6 @@ require ( github.com/whyrusleeping/pubsub v0.0.0-20131020042734-02de8aa2db3d github.com/xorcare/golden v0.6.1-0.20191112154924-b87f686d7542 go.opencensus.io v0.22.4 - go.uber.org/dig v1.10.0 // indirect go.uber.org/fx v1.9.0 go.uber.org/multierr v1.5.0 go.uber.org/zap v1.15.0 From b7f18b460147f43d59203f43f5845164d9f81066 Mon Sep 17 00:00:00 2001 From: Jakub Sztandera Date: Sat, 19 Sep 2020 21:00:38 +0200 Subject: [PATCH 271/303] Disable callers Signed-off-by: Jakub Sztandera --- chain/vm/runtime.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chain/vm/runtime.go b/chain/vm/runtime.go index 156d57282..eb4476718 100644 --- a/chain/vm/runtime.go +++ b/chain/vm/runtime.go @@ -5,7 +5,6 @@ import ( "context" "encoding/binary" "fmt" - gruntime "runtime" "time" "github.com/filecoin-project/go-address" @@ -493,7 +492,8 @@ func (rt *Runtime) chargeGasFunc(skip int) func(GasCharge) { func (rt *Runtime) chargeGasInternal(gas GasCharge, skip int) aerrors.ActorError { toUse := gas.Total() var callers [10]uintptr - cout := gruntime.Callers(2+skip, callers[:]) + + cout := 0 //gruntime.Callers(2+skip, callers[:]) now := build.Clock.Now() if rt.lastGasCharge != nil { From 1c6214b76d1cb1022afeb8ac66e475c046ec4a4f Mon Sep 17 00:00:00 2001 From: Jakub Sztandera Date: Sun, 20 Sep 2020 03:22:41 +0200 Subject: [PATCH 272/303] Usage go-bitfield with buffer pool Signed-off-by: Jakub Sztandera --- go.mod | 2 +- go.sum | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/go.mod b/go.mod index 83137d7c8..afa317614 100644 --- a/go.mod +++ b/go.mod @@ -21,7 +21,7 @@ require ( github.com/fatih/color v1.8.0 github.com/filecoin-project/filecoin-ffi v0.30.4-0.20200716204036-cddc56607e1d github.com/filecoin-project/go-address v0.0.4 - github.com/filecoin-project/go-bitfield v0.2.0 + github.com/filecoin-project/go-bitfield v0.2.1-0.20200920172649-837cbe6a1ed3 github.com/filecoin-project/go-cbor-util v0.0.0-20191219014500-08c40a1e63a2 github.com/filecoin-project/go-crypto v0.0.0-20191218222705-effae4ea9f03 github.com/filecoin-project/go-data-transfer v0.6.6 diff --git a/go.sum b/go.sum index 2455766b1..28606d17a 100644 --- a/go.sum +++ b/go.sum @@ -225,6 +225,10 @@ github.com/filecoin-project/go-amt-ipld/v2 v2.1.1-0.20200731171407-e559a0579161 github.com/filecoin-project/go-amt-ipld/v2 v2.1.1-0.20200731171407-e559a0579161/go.mod h1:vgmwKBkx+ca5OIeEvstiQgzAZnb7R6QaqE1oEDSqa6g= github.com/filecoin-project/go-bitfield v0.2.0 h1:gCtLcjskIPtdg4NfN7gQZSQF9yrBQ7mkT0qCJxzGI2Q= github.com/filecoin-project/go-bitfield v0.2.0/go.mod h1:CNl9WG8hgR5mttCnUErjcQjGvuiZjRqK9rHVBsQF4oM= +github.com/filecoin-project/go-bitfield v0.2.1-0.20200920171219-7c2059195a8c h1:eEmdVMWo7AngX9fGZSSAm/V6+7tqiBawFfHRjW35JwU= +github.com/filecoin-project/go-bitfield v0.2.1-0.20200920171219-7c2059195a8c/go.mod h1:CNl9WG8hgR5mttCnUErjcQjGvuiZjRqK9rHVBsQF4oM= +github.com/filecoin-project/go-bitfield v0.2.1-0.20200920172649-837cbe6a1ed3 h1:HQa4+yCYsLq1TLM0kopeAhSCLbtZ541cWEi5N5rO+9g= +github.com/filecoin-project/go-bitfield v0.2.1-0.20200920172649-837cbe6a1ed3/go.mod h1:CNl9WG8hgR5mttCnUErjcQjGvuiZjRqK9rHVBsQF4oM= github.com/filecoin-project/go-cbor-util v0.0.0-20191219014500-08c40a1e63a2 h1:av5fw6wmm58FYMgJeoB/lK9XXrgdugYiTqkdxjTy9k8= github.com/filecoin-project/go-cbor-util v0.0.0-20191219014500-08c40a1e63a2/go.mod h1:pqTiPHobNkOVM5thSRsHYjyQfq7O5QSCMhvuu9JoDlg= github.com/filecoin-project/go-crypto v0.0.0-20191218222705-effae4ea9f03 h1:2pMXdBnCiXjfCYx/hLqFxccPoqsSveQFxVLvNxy9bus= From 0771c23fb02d2c6cb456f81c297cdb441345e7a6 Mon Sep 17 00:00:00 2001 From: Jakub Sztandera Date: Mon, 21 Sep 2020 22:47:03 +0200 Subject: [PATCH 273/303] Use pebble Signed-off-by: Jakub Sztandera --- cmd/lotus-bench/import.go | 26 ++++++++++++++++++++++++-- go.mod | 4 +++- go.sum | 23 +++++++++++++++++++++-- 3 files changed, 48 insertions(+), 5 deletions(-) diff --git a/cmd/lotus-bench/import.go b/cmd/lotus-bench/import.go index 428fd4212..b535ed96c 100644 --- a/cmd/lotus-bench/import.go +++ b/cmd/lotus-bench/import.go @@ -16,6 +16,8 @@ import ( "sort" "time" + "github.com/cockroachdb/pebble" + "github.com/cockroachdb/pebble/bloom" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/chain/stmgr" "github.com/filecoin-project/lotus/chain/store" @@ -33,6 +35,7 @@ import ( bdg "github.com/dgraph-io/badger/v2" "github.com/ipfs/go-datastore" badger "github.com/ipfs/go-ds-badger2" + pebbleds "github.com/ipfs/go-ds-pebble" "github.com/urfave/cli/v2" "golang.org/x/xerrors" @@ -123,14 +126,33 @@ var importBenchCmd = &cli.Command{ bdgOpt.Options.Truncate = true bdgOpt.Options.DetectConflicts = false - bds, err := badger.NewDatastore(tdir, &bdgOpt) + cache := 512 + bds, err := pebbleds.NewDatastore(tdir, &pebble.Options{ + // Pebble has a single combined cache area and the write + // buffers are taken from this too. Assign all available + // memory allowance for cache. + Cache: pebble.NewCache(int64(cache * 1024 * 1024)), + // The size of memory table(as well as the write buffer). + // Note, there may have more than two memory tables in the system. + // MemTableStopWritesThreshold can be configured to avoid the memory abuse. + MemTableSize: cache * 1024 * 1024 / 4, + // The default compaction concurrency(1 thread), + // Here use all available CPUs for faster compaction. + MaxConcurrentCompactions: runtime.NumCPU(), + // Per-level options. Options for at least one level must be specified. The + // options for the last level are used for all subsequent levels. + Levels: []pebble.LevelOptions{ + {TargetFileSize: 2 * 1024 * 1024, FilterPolicy: bloom.FilterPolicy(10)}, + }, + Logger: log, + }) if err != nil { return err } if cctx.Bool("only-gc") { log.Info("calling CollectGarbage on main ds") - bds.CollectGarbage() + //bds.CollectGarbage() log.Info("done calling CollectGarbage on main ds") } bs := blockstore.NewBlockstore(bds) diff --git a/go.mod b/go.mod index afa317614..3b3b4fed7 100644 --- a/go.mod +++ b/go.mod @@ -10,6 +10,7 @@ require ( github.com/Gurpartap/async v0.0.0-20180927173644-4f7f499dd9ee github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d github.com/buger/goterm v0.0.0-20200322175922-2f3e71b85129 + github.com/cockroachdb/pebble v0.0.0-20200916222308-4e219a90ba5b github.com/coreos/go-systemd/v22 v22.0.0 github.com/detailyang/go-fallocate v0.0.0-20180908115635-432fa640bd2e github.com/dgraph-io/badger/v2 v2.2007.2 @@ -53,10 +54,11 @@ require ( github.com/ipfs/go-blockservice v0.1.4-0.20200624145336-a978cec6e834 github.com/ipfs/go-cid v0.0.7 github.com/ipfs/go-cidutil v0.0.2 - github.com/ipfs/go-datastore v0.4.4 + github.com/ipfs/go-datastore v0.4.5 github.com/ipfs/go-ds-badger2 v0.1.1-0.20200708190120-187fc06f714e github.com/ipfs/go-ds-leveldb v0.4.2 github.com/ipfs/go-ds-measure v0.1.0 + github.com/ipfs/go-ds-pebble v0.0.2-0.20200921211847-f1ffb3128b61 github.com/ipfs/go-filestore v1.0.0 github.com/ipfs/go-fs-lock v0.0.6 github.com/ipfs/go-graphsync v0.2.1 diff --git a/go.sum b/go.sum index 28606d17a..19e33d294 100644 --- a/go.sum +++ b/go.sum @@ -112,6 +112,8 @@ github.com/buger/jsonparser v0.0.0-20181115193947-bf1c66bbce23/go.mod h1:bbYlZJ7 github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ= github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/certifi/gocertifi v0.0.0-20200211180108-c7c1fbc02894 h1:JLaf/iINcLyjwbtTsCJjc6rtlASgHeIJPrB6QmwURnA= +github.com/certifi/gocertifi v0.0.0-20200211180108-c7c1fbc02894/go.mod h1:sGbDF6GwGcLpkNXPUTkMRoywsNa/ol15pxFe6ERfguA= github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= @@ -125,6 +127,14 @@ github.com/clbanning/x2j v0.0.0-20191024224557-825249438eec/go.mod h1:jMjuTZXRI4 github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= +github.com/cockroachdb/errors v1.2.4 h1:Lap807SXTH5tri2TivECb/4abUkMZC9zRoLarvcKDqs= +github.com/cockroachdb/errors v1.2.4/go.mod h1:rQD95gz6FARkaKkQXUksEje/d9a6wBJoCr5oaCLELYA= +github.com/cockroachdb/logtags v0.0.0-20190617123548-eb05cc24525f h1:o/kfcElHqOiXqcou5a3rIlMc7oJbMQkeLk0VQJ7zgqY= +github.com/cockroachdb/logtags v0.0.0-20190617123548-eb05cc24525f/go.mod h1:i/u985jwjWRlyHXQbwatDASoW0RMlZ/3i9yJHE2xLkI= +github.com/cockroachdb/pebble v0.0.0-20200916222308-4e219a90ba5b h1:OKALTB609+19AM7wsO0k8yMwAqjEIppcnYvyIhA+ZlQ= +github.com/cockroachdb/pebble v0.0.0-20200916222308-4e219a90ba5b/go.mod h1:hU7vhtrqonEphNF+xt8/lHdaBprxmV1h8BOGrd9XwmQ= +github.com/cockroachdb/redact v0.0.0-20200622112456-cd282804bbd3 h1:2+dpIJzYMSbLi0587YXpi8tOJT52qCOI/1I0UNThc/I= +github.com/cockroachdb/redact v0.0.0-20200622112456-cd282804bbd3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd h1:qMd81Ts1T2OTKmB4acZcyKaMtRnY5Y44NuXGX2GFJ1w= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= @@ -225,8 +235,6 @@ github.com/filecoin-project/go-amt-ipld/v2 v2.1.1-0.20200731171407-e559a0579161 github.com/filecoin-project/go-amt-ipld/v2 v2.1.1-0.20200731171407-e559a0579161/go.mod h1:vgmwKBkx+ca5OIeEvstiQgzAZnb7R6QaqE1oEDSqa6g= github.com/filecoin-project/go-bitfield v0.2.0 h1:gCtLcjskIPtdg4NfN7gQZSQF9yrBQ7mkT0qCJxzGI2Q= github.com/filecoin-project/go-bitfield v0.2.0/go.mod h1:CNl9WG8hgR5mttCnUErjcQjGvuiZjRqK9rHVBsQF4oM= -github.com/filecoin-project/go-bitfield v0.2.1-0.20200920171219-7c2059195a8c h1:eEmdVMWo7AngX9fGZSSAm/V6+7tqiBawFfHRjW35JwU= -github.com/filecoin-project/go-bitfield v0.2.1-0.20200920171219-7c2059195a8c/go.mod h1:CNl9WG8hgR5mttCnUErjcQjGvuiZjRqK9rHVBsQF4oM= github.com/filecoin-project/go-bitfield v0.2.1-0.20200920172649-837cbe6a1ed3 h1:HQa4+yCYsLq1TLM0kopeAhSCLbtZ541cWEi5N5rO+9g= github.com/filecoin-project/go-bitfield v0.2.1-0.20200920172649-837cbe6a1ed3/go.mod h1:CNl9WG8hgR5mttCnUErjcQjGvuiZjRqK9rHVBsQF4oM= github.com/filecoin-project/go-cbor-util v0.0.0-20191219014500-08c40a1e63a2 h1:av5fw6wmm58FYMgJeoB/lK9XXrgdugYiTqkdxjTy9k8= @@ -283,6 +291,9 @@ github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWo github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/gbrlsnchs/jwt/v3 v3.0.0-beta.1 h1:EzDjxMg43q1tA2c0MV3tNbaontnHLplHyFF6M5KiVP0= github.com/gbrlsnchs/jwt/v3 v3.0.0-beta.1/go.mod h1:0eHX/BVySxPc6SE2mZRoppGq7qcEagxdmQnA3dzork8= +github.com/getsentry/raven-go v0.2.0 h1:no+xWJRb5ZI7eE8TWgIq1jLulQiIoLG0IfYxv5JYMGs= +github.com/getsentry/raven-go v0.2.0/go.mod h1:KungGk8q33+aIAZUIVWZDr2OfAEBsO49PX4NzFV5kcQ= +github.com/ghemawat/stream v0.0.0-20171120220530-696b145b53b9/go.mod h1:106OIgooyS7OzLDOpUGgm9fA3bQENb/cFSyyBmMoJDs= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gliderlabs/ssh v0.1.1/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0= github.com/go-check/check v0.0.0-20180628173108-788fd7840127/go.mod h1:9ES+weclKsC9YodN5RgxqK/VD9HM9JsCSh7rNhMZE98= @@ -351,6 +362,8 @@ github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4= github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.2-0.20190904063534-ff6b7dc882cf h1:gFVkHXmVAhEbxZVDln5V9GKrLaluNoFHDbrZwAWZgws= +github.com/golang/snappy v0.0.2-0.20190904063534-ff6b7dc882cf/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= @@ -491,6 +504,8 @@ github.com/ipfs/go-datastore v0.4.1/go.mod h1:SX/xMIKoCszPqp+z9JhPYCmoOoXTvaa13X github.com/ipfs/go-datastore v0.4.2/go.mod h1:SX/xMIKoCszPqp+z9JhPYCmoOoXTvaa13XEbGtsFUhA= github.com/ipfs/go-datastore v0.4.4 h1:rjvQ9+muFaJ+QZ7dN5B1MSDNQ0JVZKkkES/rMZmA8X8= github.com/ipfs/go-datastore v0.4.4/go.mod h1:SX/xMIKoCszPqp+z9JhPYCmoOoXTvaa13XEbGtsFUhA= +github.com/ipfs/go-datastore v0.4.5 h1:cwOUcGMLdLPWgu3SlrCckCMznaGADbPqE0r8h768/Dg= +github.com/ipfs/go-datastore v0.4.5/go.mod h1:eXTcaaiN6uOlVCLS9GjJUJtlvJfM3xk23w3fyfrmmJs= github.com/ipfs/go-detect-race v0.0.1 h1:qX/xay2W3E4Q1U7d9lNs1sU9nvguX0a7319XbyQ6cOk= github.com/ipfs/go-detect-race v0.0.1/go.mod h1:8BNT7shDZPo99Q74BpGMK+4D8Mn4j46UU0LZ723meps= github.com/ipfs/go-ds-badger v0.0.2/go.mod h1:Y3QpeSFWQf6MopLTiZD+VT6IC1yZqaGmjvRcKeSGij8= @@ -509,6 +524,8 @@ github.com/ipfs/go-ds-leveldb v0.4.2 h1:QmQoAJ9WkPMUfBLnu1sBVy0xWWlJPg0m4kRAiJL9 github.com/ipfs/go-ds-leveldb v0.4.2/go.mod h1:jpbku/YqBSsBc1qgME8BkWS4AxzF2cEu1Ii2r79Hh9s= github.com/ipfs/go-ds-measure v0.1.0 h1:vE4TyY4aeLeVgnnPBC5QzKIjKrqzha0NCujTfgvVbVQ= github.com/ipfs/go-ds-measure v0.1.0/go.mod h1:1nDiFrhLlwArTME1Ees2XaBOl49OoCgd2A3f8EchMSY= +github.com/ipfs/go-ds-pebble v0.0.2-0.20200921211847-f1ffb3128b61 h1:2wNNdpETSZgnsgy7wx7O6ueu+LCSZRedWrAsIPiOeFE= +github.com/ipfs/go-ds-pebble v0.0.2-0.20200921211847-f1ffb3128b61/go.mod h1:oh4liWHulKcDKVhCska5NLelE3MatWl+1FwSz3tY91g= github.com/ipfs/go-filestore v1.0.0 h1:QR7ekKH+q2AGiWDc7W2Q0qHuYSRZGUJqUn0GsegEPb0= github.com/ipfs/go-filestore v1.0.0/go.mod h1:/XOCuNtIe2f1YPbiXdYvD0BKLA0JR1MgPiFOdcuu9SM= github.com/ipfs/go-fs-lock v0.0.6 h1:sn3TWwNVQqSeNjlWy6zQ1uUGAZrV3hPOyEA6y1/N2a0= @@ -1521,6 +1538,8 @@ golang.org/x/exp v0.0.0-20200207192155-f17229e696bd h1:zkO/Lhoka23X63N9OSzpSeROE golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6 h1:QE6XYQK6naiK1EPAe1g/ILLxN5RBoH5xkJk3CqlMI/Y= golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= +golang.org/x/exp v0.0.0-20200513190911-00229845015e h1:rMqLP+9XLy+LdbCXHjJHAmTfXCr93W7oruWA6Hq1Alc= +golang.org/x/exp v0.0.0-20200513190911-00229845015e/go.mod h1:4M0jN8W1tt0AVLNr8HDosyJCDCDuyL9N9+3m7wDWgKw= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= From 55c6b88537dd9f7b5db9aa601127634b9d13c96b Mon Sep 17 00:00:00 2001 From: Jakub Sztandera Date: Tue, 22 Sep 2020 00:46:31 +0200 Subject: [PATCH 274/303] Add toggle for badger, flag out gas tracing Signed-off-by: Jakub Sztandera --- chain/vm/runtime.go | 56 ++++++++++++++++++++----------------- chain/vm/vm.go | 19 +++++++++---- cmd/lotus-bench/import.go | 58 +++++++++++++++++++++------------------ 3 files changed, 75 insertions(+), 58 deletions(-) diff --git a/chain/vm/runtime.go b/chain/vm/runtime.go index eb4476718..72dd413ed 100644 --- a/chain/vm/runtime.go +++ b/chain/vm/runtime.go @@ -459,8 +459,10 @@ func (rt *Runtime) stateCommit(oldh, newh cid.Cid) aerrors.ActorError { } func (rt *Runtime) finilizeGasTracing() { - if rt.lastGasCharge != nil { - rt.lastGasCharge.TimeTaken = time.Since(rt.lastGasChargeTime) + if enableTracing { + if rt.lastGasCharge != nil { + rt.lastGasCharge.TimeTaken = time.Since(rt.lastGasChargeTime) + } } } @@ -489,35 +491,39 @@ func (rt *Runtime) chargeGasFunc(skip int) func(GasCharge) { } +var enableTracing = false + func (rt *Runtime) chargeGasInternal(gas GasCharge, skip int) aerrors.ActorError { toUse := gas.Total() - var callers [10]uintptr + if enableTracing { + var callers [10]uintptr - cout := 0 //gruntime.Callers(2+skip, callers[:]) + cout := 0 //gruntime.Callers(2+skip, callers[:]) - now := build.Clock.Now() - if rt.lastGasCharge != nil { - rt.lastGasCharge.TimeTaken = now.Sub(rt.lastGasChargeTime) + now := build.Clock.Now() + if rt.lastGasCharge != nil { + rt.lastGasCharge.TimeTaken = now.Sub(rt.lastGasChargeTime) + } + + gasTrace := types.GasTrace{ + Name: gas.Name, + Extra: gas.Extra, + + TotalGas: toUse, + ComputeGas: gas.ComputeGas, + StorageGas: gas.StorageGas, + + TotalVirtualGas: gas.VirtualCompute*GasComputeMulti + gas.VirtualStorage*GasStorageMulti, + VirtualComputeGas: gas.VirtualCompute, + VirtualStorageGas: gas.VirtualStorage, + + Callers: callers[:cout], + } + rt.executionTrace.GasCharges = append(rt.executionTrace.GasCharges, &gasTrace) + rt.lastGasChargeTime = now + rt.lastGasCharge = &gasTrace } - gasTrace := types.GasTrace{ - Name: gas.Name, - Extra: gas.Extra, - - TotalGas: toUse, - ComputeGas: gas.ComputeGas, - StorageGas: gas.StorageGas, - - TotalVirtualGas: gas.VirtualCompute*GasComputeMulti + gas.VirtualStorage*GasStorageMulti, - VirtualComputeGas: gas.VirtualCompute, - VirtualStorageGas: gas.VirtualStorage, - - Callers: callers[:cout], - } - rt.executionTrace.GasCharges = append(rt.executionTrace.GasCharges, &gasTrace) - rt.lastGasChargeTime = now - rt.lastGasCharge = &gasTrace - // overflow safe if rt.gasUsed > rt.gasAvailable-toUse { rt.gasUsed = rt.gasAvailable diff --git a/chain/vm/vm.go b/chain/vm/vm.go index 54ea47698..c566ec1eb 100644 --- a/chain/vm/vm.go +++ b/chain/vm/vm.go @@ -227,14 +227,21 @@ func (vm *VM) send(ctx context.Context, msg *types.Message, parent *Runtime, } rt := vm.makeRuntime(ctx, msg, origin, on, gasUsed, nac) - rt.lastGasChargeTime = start + if enableTracing { + rt.lastGasChargeTime = start + if parent != nil { + rt.lastGasChargeTime = parent.lastGasChargeTime + rt.lastGasCharge = parent.lastGasCharge + defer func() { + parent.lastGasChargeTime = rt.lastGasChargeTime + parent.lastGasCharge = rt.lastGasCharge + }() + } + } + if parent != nil { - rt.lastGasChargeTime = parent.lastGasChargeTime - rt.lastGasCharge = parent.lastGasCharge defer func() { - parent.gasUsed = rt.gasUsed - parent.lastGasChargeTime = rt.lastGasChargeTime - parent.lastGasCharge = rt.lastGasCharge + parent.gasUsed += rt.gasUsed }() } if gasCharge != nil { diff --git a/cmd/lotus-bench/import.go b/cmd/lotus-bench/import.go index b535ed96c..c3554f939 100644 --- a/cmd/lotus-bench/import.go +++ b/cmd/lotus-bench/import.go @@ -119,33 +119,37 @@ var importBenchCmd = &cli.Command{ tdir = tmp } - bdgOpt := badger.DefaultOptions - bdgOpt.GcInterval = 0 - bdgOpt.Options = bdg.DefaultOptions("") - bdgOpt.Options.SyncWrites = false - bdgOpt.Options.Truncate = true - bdgOpt.Options.DetectConflicts = false - - cache := 512 - bds, err := pebbleds.NewDatastore(tdir, &pebble.Options{ - // Pebble has a single combined cache area and the write - // buffers are taken from this too. Assign all available - // memory allowance for cache. - Cache: pebble.NewCache(int64(cache * 1024 * 1024)), - // The size of memory table(as well as the write buffer). - // Note, there may have more than two memory tables in the system. - // MemTableStopWritesThreshold can be configured to avoid the memory abuse. - MemTableSize: cache * 1024 * 1024 / 4, - // The default compaction concurrency(1 thread), - // Here use all available CPUs for faster compaction. - MaxConcurrentCompactions: runtime.NumCPU(), - // Per-level options. Options for at least one level must be specified. The - // options for the last level are used for all subsequent levels. - Levels: []pebble.LevelOptions{ - {TargetFileSize: 2 * 1024 * 1024, FilterPolicy: bloom.FilterPolicy(10)}, - }, - Logger: log, - }) + var bds datastore.Batching + if false { + cache := 512 + bds, err = pebbleds.NewDatastore(tdir, &pebble.Options{ + // Pebble has a single combined cache area and the write + // buffers are taken from this too. Assign all available + // memory allowance for cache. + Cache: pebble.NewCache(int64(cache * 1024 * 1024)), + // The size of memory table(as well as the write buffer). + // Note, there may have more than two memory tables in the system. + // MemTableStopWritesThreshold can be configured to avoid the memory abuse. + MemTableSize: cache * 1024 * 1024 / 4, + // The default compaction concurrency(1 thread), + // Here use all available CPUs for faster compaction. + MaxConcurrentCompactions: runtime.NumCPU(), + // Per-level options. Options for at least one level must be specified. The + // options for the last level are used for all subsequent levels. + Levels: []pebble.LevelOptions{ + {TargetFileSize: 2 * 1024 * 1024, FilterPolicy: bloom.FilterPolicy(10)}, + }, + Logger: log, + }) + } else { + bdgOpt := badger.DefaultOptions + bdgOpt.GcInterval = 0 + bdgOpt.Options = bdg.DefaultOptions("") + bdgOpt.Options.SyncWrites = false + bdgOpt.Options.Truncate = true + bdgOpt.Options.DetectConflicts = false + bds, err = badger.NewDatastore(tdir, &bdgOpt) + } if err != nil { return err } From ff8c0af8c82c022b86fd7f1043460711c31a6c43 Mon Sep 17 00:00:00 2001 From: Jakub Sztandera Date: Tue, 22 Sep 2020 00:54:11 +0200 Subject: [PATCH 275/303] Add only-import option Signed-off-by: Jakub Sztandera --- cmd/lotus-bench/import.go | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/cmd/lotus-bench/import.go b/cmd/lotus-bench/import.go index c3554f939..6af1bfc02 100644 --- a/cmd/lotus-bench/import.go +++ b/cmd/lotus-bench/import.go @@ -90,6 +90,9 @@ var importBenchCmd = &cli.Command{ &cli.Int64Flag{ Name: "start-at", }, + &cli.BoolFlag{ + Name: "only-import", + }, }, Action: func(cctx *cli.Context) error { vm.BatchSealVerifyParallelism = cctx.Int("batch-seal-verify-threads") @@ -119,6 +122,13 @@ var importBenchCmd = &cli.Command{ tdir = tmp } + bdgOpt := badger.DefaultOptions + bdgOpt.GcInterval = 0 + bdgOpt.Options = bdg.DefaultOptions("") + bdgOpt.Options.SyncWrites = false + bdgOpt.Options.Truncate = true + bdgOpt.Options.DetectConflicts = false + var bds datastore.Batching if false { cache := 512 @@ -142,17 +152,12 @@ var importBenchCmd = &cli.Command{ Logger: log, }) } else { - bdgOpt := badger.DefaultOptions - bdgOpt.GcInterval = 0 - bdgOpt.Options = bdg.DefaultOptions("") - bdgOpt.Options.SyncWrites = false - bdgOpt.Options.Truncate = true - bdgOpt.Options.DetectConflicts = false bds, err = badger.NewDatastore(tdir, &bdgOpt) } if err != nil { return err } + defer bds.Close() if cctx.Bool("only-gc") { log.Info("calling CollectGarbage on main ds") @@ -176,6 +181,7 @@ var importBenchCmd = &cli.Command{ if err != nil { return xerrors.Errorf("opening syscall-cache datastore: %w", err) } + defer scds.Close() if cctx.Bool("only-gc") { log.Info("calling CollectGarbage on syscall ds") @@ -223,6 +229,10 @@ var importBenchCmd = &cli.Command{ } } + if cctx.Bool("only-import") { + return nil + } + gb, err := cs.GetTipsetByHeight(context.TODO(), 0, head, true) if err != nil { return err From 76db65b1afcfa3f752ff51afcdc9021bacd38415 Mon Sep 17 00:00:00 2001 From: Jakub Sztandera Date: Tue, 22 Sep 2020 00:57:37 +0200 Subject: [PATCH 276/303] Update pebble Signed-off-by: Jakub Sztandera --- chain/vm/vm.go | 2 +- cmd/lotus-bench/import.go | 4 ++-- go.mod | 2 +- go.sum | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/chain/vm/vm.go b/chain/vm/vm.go index c566ec1eb..44979454f 100644 --- a/chain/vm/vm.go +++ b/chain/vm/vm.go @@ -241,7 +241,7 @@ func (vm *VM) send(ctx context.Context, msg *types.Message, parent *Runtime, if parent != nil { defer func() { - parent.gasUsed += rt.gasUsed + parent.gasUsed = rt.gasUsed }() } if gasCharge != nil { diff --git a/cmd/lotus-bench/import.go b/cmd/lotus-bench/import.go index 6af1bfc02..94dae0d98 100644 --- a/cmd/lotus-bench/import.go +++ b/cmd/lotus-bench/import.go @@ -130,7 +130,7 @@ var importBenchCmd = &cli.Command{ bdgOpt.Options.DetectConflicts = false var bds datastore.Batching - if false { + if true { cache := 512 bds, err = pebbleds.NewDatastore(tdir, &pebble.Options{ // Pebble has a single combined cache area and the write @@ -147,7 +147,7 @@ var importBenchCmd = &cli.Command{ // Per-level options. Options for at least one level must be specified. The // options for the last level are used for all subsequent levels. Levels: []pebble.LevelOptions{ - {TargetFileSize: 2 * 1024 * 1024, FilterPolicy: bloom.FilterPolicy(10)}, + {TargetFileSize: 16 * 1024 * 1024, FilterPolicy: bloom.FilterPolicy(10), Compression: pebble.NoCompression}, }, Logger: log, }) diff --git a/go.mod b/go.mod index 3b3b4fed7..17cb2fd36 100644 --- a/go.mod +++ b/go.mod @@ -58,7 +58,7 @@ require ( github.com/ipfs/go-ds-badger2 v0.1.1-0.20200708190120-187fc06f714e github.com/ipfs/go-ds-leveldb v0.4.2 github.com/ipfs/go-ds-measure v0.1.0 - github.com/ipfs/go-ds-pebble v0.0.2-0.20200921211847-f1ffb3128b61 + github.com/ipfs/go-ds-pebble v0.0.2-0.20200921225637-ce220f8ac459 github.com/ipfs/go-filestore v1.0.0 github.com/ipfs/go-fs-lock v0.0.6 github.com/ipfs/go-graphsync v0.2.1 diff --git a/go.sum b/go.sum index 19e33d294..6929c9a23 100644 --- a/go.sum +++ b/go.sum @@ -524,8 +524,8 @@ github.com/ipfs/go-ds-leveldb v0.4.2 h1:QmQoAJ9WkPMUfBLnu1sBVy0xWWlJPg0m4kRAiJL9 github.com/ipfs/go-ds-leveldb v0.4.2/go.mod h1:jpbku/YqBSsBc1qgME8BkWS4AxzF2cEu1Ii2r79Hh9s= github.com/ipfs/go-ds-measure v0.1.0 h1:vE4TyY4aeLeVgnnPBC5QzKIjKrqzha0NCujTfgvVbVQ= github.com/ipfs/go-ds-measure v0.1.0/go.mod h1:1nDiFrhLlwArTME1Ees2XaBOl49OoCgd2A3f8EchMSY= -github.com/ipfs/go-ds-pebble v0.0.2-0.20200921211847-f1ffb3128b61 h1:2wNNdpETSZgnsgy7wx7O6ueu+LCSZRedWrAsIPiOeFE= -github.com/ipfs/go-ds-pebble v0.0.2-0.20200921211847-f1ffb3128b61/go.mod h1:oh4liWHulKcDKVhCska5NLelE3MatWl+1FwSz3tY91g= +github.com/ipfs/go-ds-pebble v0.0.2-0.20200921225637-ce220f8ac459 h1:W3YMLEvOXqdW+sYMiguhWP6txJwQvIQqhvpU8yAMGQs= +github.com/ipfs/go-ds-pebble v0.0.2-0.20200921225637-ce220f8ac459/go.mod h1:oh4liWHulKcDKVhCska5NLelE3MatWl+1FwSz3tY91g= github.com/ipfs/go-filestore v1.0.0 h1:QR7ekKH+q2AGiWDc7W2Q0qHuYSRZGUJqUn0GsegEPb0= github.com/ipfs/go-filestore v1.0.0/go.mod h1:/XOCuNtIe2f1YPbiXdYvD0BKLA0JR1MgPiFOdcuu9SM= github.com/ipfs/go-fs-lock v0.0.6 h1:sn3TWwNVQqSeNjlWy6zQ1uUGAZrV3hPOyEA6y1/N2a0= From 0d914ac1d4c4d0e8955c7074e9dd03eb49f44900 Mon Sep 17 00:00:00 2001 From: Jakub Sztandera Date: Tue, 22 Sep 2020 22:01:41 +0200 Subject: [PATCH 277/303] Switch to badger Signed-off-by: Jakub Sztandera --- cmd/lotus-bench/import.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/lotus-bench/import.go b/cmd/lotus-bench/import.go index 94dae0d98..c8328684e 100644 --- a/cmd/lotus-bench/import.go +++ b/cmd/lotus-bench/import.go @@ -130,7 +130,7 @@ var importBenchCmd = &cli.Command{ bdgOpt.Options.DetectConflicts = false var bds datastore.Batching - if true { + if false { cache := 512 bds, err = pebbleds.NewDatastore(tdir, &pebble.Options{ // Pebble has a single combined cache area and the write From 7e8c6e507055f1f75607facbc0d0220608540343 Mon Sep 17 00:00:00 2001 From: Jakub Sztandera Date: Wed, 23 Sep 2020 18:44:41 +0200 Subject: [PATCH 278/303] Remove statediff, fix lint, go mod tidy Signed-off-by: Jakub Sztandera --- cmd/lotus-bench/import.go | 20 +++----------------- go.mod | 7 ++++--- go.sum | 23 ----------------------- 3 files changed, 7 insertions(+), 43 deletions(-) diff --git a/cmd/lotus-bench/import.go b/cmd/lotus-bench/import.go index c8328684e..3d93b0e5e 100644 --- a/cmd/lotus-bench/import.go +++ b/cmd/lotus-bench/import.go @@ -30,7 +30,6 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" - "github.com/filecoin-project/statediff" bdg "github.com/dgraph-io/badger/v2" "github.com/ipfs/go-datastore" @@ -80,9 +79,6 @@ var importBenchCmd = &cli.Command{ Name: "no-import", Usage: "should we import the chain? if set to true chain has to be previously imported", }, - &cli.BoolFlag{ - Name: "only-gc", - }, &cli.BoolFlag{ Name: "global-profile", Value: true, @@ -157,13 +153,8 @@ var importBenchCmd = &cli.Command{ if err != nil { return err } - defer bds.Close() + defer bds.Close() //nolint:errcheck - if cctx.Bool("only-gc") { - log.Info("calling CollectGarbage on main ds") - //bds.CollectGarbage() - log.Info("done calling CollectGarbage on main ds") - } bs := blockstore.NewBlockstore(bds) cacheOpts := blockstore.DefaultCacheOpts() cacheOpts.HasBloomFilterSize = 0 @@ -181,13 +172,8 @@ var importBenchCmd = &cli.Command{ if err != nil { return xerrors.Errorf("opening syscall-cache datastore: %w", err) } - defer scds.Close() + defer scds.Close() //nolint:errcheck - if cctx.Bool("only-gc") { - log.Info("calling CollectGarbage on syscall ds") - scds.CollectGarbage() - log.Info("done calling CollectGarbage on syscall ds") - } verifier = &cachingVerifier{ ds: scds, backend: verifier, @@ -317,7 +303,7 @@ var importBenchCmd = &cli.Command{ } fmt.Println("TRACE") fmt.Println(string(d)) - fmt.Println(statediff.Diff(context.Background(), bs, tschain[i-1].ParentState(), st, statediff.ExpandActors)) + //fmt.Println(statediff.Diff(context.Background(), bs, tschain[i-1].ParentState(), st, statediff.ExpandActors)) return xerrors.Errorf("tipset chain had state mismatch at height %d (%s != %s)", cur.Height(), cur.ParentState(), st) } } diff --git a/go.mod b/go.mod index 17cb2fd36..b8896d78f 100644 --- a/go.mod +++ b/go.mod @@ -8,6 +8,7 @@ require ( github.com/BurntSushi/toml v0.3.1 github.com/GeertJohan/go.rice v1.0.0 github.com/Gurpartap/async v0.0.0-20180927173644-4f7f499dd9ee + github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d // indirect github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d github.com/buger/goterm v0.0.0-20200322175922-2f3e71b85129 github.com/cockroachdb/pebble v0.0.0-20200916222308-4e219a90ba5b @@ -38,10 +39,10 @@ require ( github.com/filecoin-project/go-storedcounter v0.0.0-20200421200003-1c99c62e8a5b github.com/filecoin-project/specs-actors v0.9.11 github.com/filecoin-project/specs-storage v0.1.1-0.20200907031224-ed2e5cd13796 - github.com/filecoin-project/statediff v0.0.6-0.20200918150628-da86dd0d264c github.com/filecoin-project/test-vectors/schema v0.0.1 github.com/gbrlsnchs/jwt/v3 v3.0.0-beta.1 github.com/go-kit/kit v0.10.0 + github.com/go-ole/go-ole v1.2.4 // indirect github.com/google/uuid v1.1.1 github.com/gorilla/mux v1.7.4 github.com/gorilla/websocket v1.4.2 @@ -118,6 +119,7 @@ require ( github.com/whyrusleeping/pubsub v0.0.0-20131020042734-02de8aa2db3d github.com/xorcare/golden v0.6.1-0.20191112154924-b87f686d7542 go.opencensus.io v0.22.4 + go.uber.org/dig v1.10.0 // indirect go.uber.org/fx v1.9.0 go.uber.org/multierr v1.5.0 go.uber.org/zap v1.15.0 @@ -127,12 +129,11 @@ require ( golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 gopkg.in/cheggaaa/pb.v1 v1.0.28 gotest.tools v2.2.0+incompatible + launchpad.net/gocheck v0.0.0-20140225173054-000000000087 // indirect ) replace github.com/filecoin-project/lotus => ./ -replace github.com/filecoin-project/statediff => ./../statediff - replace github.com/golangci/golangci-lint => github.com/golangci/golangci-lint v1.18.0 replace github.com/filecoin-project/filecoin-ffi => ./extern/filecoin-ffi diff --git a/go.sum b/go.sum index 6929c9a23..cbceb52c6 100644 --- a/go.sum +++ b/go.sum @@ -169,8 +169,6 @@ github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/davidlazar/go-crypto v0.0.0-20170701192655-dcfb0a7ac018/go.mod h1:rQYf4tfk5sSwFsnDg3qYaBxSjsD9S8+59vW0dKUgme4= github.com/davidlazar/go-crypto v0.0.0-20190912175916-7055855a373f h1:BOaYiTvg8p9vBUXpklC22XSK/mifLF7lG9jtmYYi3Tc= github.com/davidlazar/go-crypto v0.0.0-20190912175916-7055855a373f/go.mod h1:rQYf4tfk5sSwFsnDg3qYaBxSjsD9S8+59vW0dKUgme4= -github.com/davidlazar/go-crypto v0.0.0-20200604182044-b73af7476f6c h1:pFUpOrbxDR6AkioZ1ySsx5yxlDQZ8stG2b88gTPxgJU= -github.com/davidlazar/go-crypto v0.0.0-20200604182044-b73af7476f6c/go.mod h1:6UhI8N9EjYm1c2odKpFpAYeR8dsBeM7PtzQhRgxRr9U= github.com/detailyang/go-fallocate v0.0.0-20180908115635-432fa640bd2e h1:lj77EKYUpYXTd8CD/+QMIf8b6OIOTsfEBSXiAzuEHTU= github.com/detailyang/go-fallocate v0.0.0-20180908115635-432fa640bd2e/go.mod h1:3ZQK6DMPSz/QZ73jlWxBtUhNA8xZx7LzUFSq/OfP8vk= github.com/dgraph-io/badger v1.5.5-0.20190226225317-8115aed38f8f/go.mod h1:VZxzAIRPHRVNRKRo6AXrX9BJegn6il06VMTZVJYCIjQ= @@ -218,7 +216,6 @@ github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymF github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/evanw/esbuild v0.6.28/go.mod h1:mptxmSXIzBIKKCe4jo9A5SToEd1G+AKZ9JmY85dYRJ0= github.com/facebookgo/atomicfile v0.0.0-20151019160806-2de1f203e7d5 h1:BBso6MBKW8ncyZLv37o+KNyy0HrrHgfnOaGQC2qvN+A= github.com/facebookgo/atomicfile v0.0.0-20151019160806-2de1f203e7d5/go.mod h1:JpoxHjuQauoxiFMl1ie8Xc/7TfLuMZ5eOCONd1sUBHg= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= @@ -231,8 +228,6 @@ github.com/filecoin-project/go-address v0.0.4 h1:gSNMv0qWwH16fGQs7ycOUrDjY6YCSsg github.com/filecoin-project/go-address v0.0.4/go.mod h1:jr8JxKsYx+lQlQZmF5i2U0Z+cGQ59wMIps/8YW/lDj8= github.com/filecoin-project/go-amt-ipld/v2 v2.1.0 h1:t6qDiuGYYngDqaLc2ZUvdtAg4UNxPeOYaXhBWSNsVaM= github.com/filecoin-project/go-amt-ipld/v2 v2.1.0/go.mod h1:nfFPoGyX0CU9SkXX8EoCcSuHN1XcbN0c6KBh7yvP5fs= -github.com/filecoin-project/go-amt-ipld/v2 v2.1.1-0.20200731171407-e559a0579161 h1:K6t4Hrs+rwUxBz2xg88Bdqeh4k5/rycQFdPseZhRyfE= -github.com/filecoin-project/go-amt-ipld/v2 v2.1.1-0.20200731171407-e559a0579161/go.mod h1:vgmwKBkx+ca5OIeEvstiQgzAZnb7R6QaqE1oEDSqa6g= github.com/filecoin-project/go-bitfield v0.2.0 h1:gCtLcjskIPtdg4NfN7gQZSQF9yrBQ7mkT0qCJxzGI2Q= github.com/filecoin-project/go-bitfield v0.2.0/go.mod h1:CNl9WG8hgR5mttCnUErjcQjGvuiZjRqK9rHVBsQF4oM= github.com/filecoin-project/go-bitfield v0.2.1-0.20200920172649-837cbe6a1ed3 h1:HQa4+yCYsLq1TLM0kopeAhSCLbtZ541cWEi5N5rO+9g= @@ -720,7 +715,6 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/pty v1.1.3/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/lib/pq v1.7.0 h1:h93mCPfUSkaul3Ka/VG8uZdmW1uMHDGxzu0NWHuJmHY= github.com/lib/pq v1.7.0/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/libp2p/go-addr-util v0.0.1/go.mod h1:4ac6O7n9rIAKB1dnd+s8IbbMXkt+oBpzX4/+RACcnlQ= @@ -1048,8 +1042,6 @@ github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNx github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.8 h1:HLtExJ+uU2HOZ+wI0Tt5DtUDrx8yhUqDcp7fYERX4CE= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= -github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/mattn/go-runewidth v0.0.7 h1:Ei8KR0497xHyKJPAv59M1dkC+rOZCMBJ+t3fZ+twI54= github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= @@ -1352,8 +1344,6 @@ github.com/streadway/handy v0.0.0-20190108123426-d5acb3125c2a/go.mod h1:qNTQ5P5J github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.2.0 h1:Hbg2NidpLE8veEBkEZTL3CvlkUIVzuU9jDplZO54c48= -github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= @@ -1406,7 +1396,6 @@ github.com/whyrusleeping/cbor-gen v0.0.0-20200414195334-429a0b5e922e/go.mod h1:X github.com/whyrusleeping/cbor-gen v0.0.0-20200504204219-64967432584d/go.mod h1:W5MvapuoHRP8rz4vxjwCK1pDqF1aQcWsV5PZ+AHbqdg= github.com/whyrusleeping/cbor-gen v0.0.0-20200710004633-5379fc63235d/go.mod h1:fgkXqYy7bV2cFeIEOkVTZS/WjXARfBqSH6Q2qHL33hQ= github.com/whyrusleeping/cbor-gen v0.0.0-20200715143311-227fab5a2377/go.mod h1:fgkXqYy7bV2cFeIEOkVTZS/WjXARfBqSH6Q2qHL33hQ= -github.com/whyrusleeping/cbor-gen v0.0.0-20200723185710-6a3894a6352b/go.mod h1:fgkXqYy7bV2cFeIEOkVTZS/WjXARfBqSH6Q2qHL33hQ= github.com/whyrusleeping/cbor-gen v0.0.0-20200810223238-211df3b9e24c/go.mod h1:fgkXqYy7bV2cFeIEOkVTZS/WjXARfBqSH6Q2qHL33hQ= github.com/whyrusleeping/cbor-gen v0.0.0-20200812213548-958ddffe352c/go.mod h1:fgkXqYy7bV2cFeIEOkVTZS/WjXARfBqSH6Q2qHL33hQ= github.com/whyrusleeping/cbor-gen v0.0.0-20200814224545-656e08ce49ee h1:U7zWWvvAjT76EiuWPSOiZlQDnaQYPxPoxugTtTAcJK0= @@ -1433,8 +1422,6 @@ github.com/whyrusleeping/pubsub v0.0.0-20131020042734-02de8aa2db3d/go.mod h1:g7c github.com/whyrusleeping/timecache v0.0.0-20160911033111-cfcb2f1abfee h1:lYbXeSvJi5zk5GLKVuid9TVjS9a0OmLIDKTfoZBL6Ow= github.com/whyrusleeping/timecache v0.0.0-20160911033111-cfcb2f1abfee/go.mod h1:m2aV4LZI4Aez7dP5PMyVKEHhUyEJ/RjmPEDOpDvudHg= github.com/whyrusleeping/yamux v1.1.5/go.mod h1:E8LnQQ8HKx5KD29HZFUwM1PxCOdPRzGwur1mcYhXcD8= -github.com/willscott/go-cmp v0.5.2-0.20200812183318-8affb9542345 h1:IJVAwIctqDFOrO0C2qzksXmANviyHJzrklU27e1ltzE= -github.com/willscott/go-cmp v0.5.2-0.20200812183318-8affb9542345/go.mod h1:D7hA8H5pyQx7Y5Em7IWx1R4vNJzfon3gpG9nxjkITjQ= github.com/x-cray/logrus-prefixed-formatter v0.5.2/go.mod h1:2duySbKsL6M18s5GU7VPsoEPHyzalCE06qoARUCeBBE= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/xlab/c-for-go v0.0.0-20200718154222-87b0065af829 h1:wb7xrDzfkLgPHsSEBm+VSx6aDdi64VtV0xvP0E6j8bk= @@ -1523,7 +1510,6 @@ golang.org/x/crypto v0.0.0-20200128174031-69ecbb4d6d5d/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20200221231518-2aa609cf4a9d/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200423211502-4bdfaf469ed5/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20200602180216-279210d13fed/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= @@ -1536,8 +1522,6 @@ golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u0 golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= golang.org/x/exp v0.0.0-20200207192155-f17229e696bd h1:zkO/Lhoka23X63N9OSzpSeROEUQ5ODw47tM3YWjygbs= golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= -golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6 h1:QE6XYQK6naiK1EPAe1g/ILLxN5RBoH5xkJk3CqlMI/Y= -golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= golang.org/x/exp v0.0.0-20200513190911-00229845015e h1:rMqLP+9XLy+LdbCXHjJHAmTfXCr93W7oruWA6Hq1Alc= golang.org/x/exp v0.0.0-20200513190911-00229845015e/go.mod h1:4M0jN8W1tt0AVLNr8HDosyJCDCDuyL9N9+3m7wDWgKw= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= @@ -1553,8 +1537,6 @@ golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHl golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= golang.org/x/lint v0.0.0-20200130185559-910be7a94367 h1:0IiAsCRByjO2QjX7ZPkw5oU9x+n1YqRL802rjC0c3Aw= golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20200302205851-738671d3881b h1:Wh+f8QHJXR411sJR8/vRBTZ7YapZaRvUcLFFJhusH0k= -golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= @@ -1672,7 +1654,6 @@ golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20191220142924-d4481acd189f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -1681,7 +1662,6 @@ golang.org/x/sys v0.0.0-20200217220822-9197077df867/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200420163511-1957bb5e6d1f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200501145240-bc7a7d42d5c3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200509044756-6aff5f38e54f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200602225109-6fdc65e7d980 h1:OjiUf46hAmXblsZdnoSXsEUSKU8r1UEzcL5RVZ4gO9Y= @@ -1725,7 +1705,6 @@ golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191216052735-49a3e744a425/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= @@ -1854,8 +1833,6 @@ honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWh honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.1-2019.2.3 h1:3JgtbtFHMiCmsznwGVTUWbgGov+pVqnlf1dEJTNAXeM= honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= -honnef.co/go/tools v0.0.1-2020.1.3 h1:sXmLre5bzIR6ypkjXCDI3jHPssRhc8KD/Ome589sc3U= -honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= howett.net/plist v0.0.0-20181124034731-591f970eefbb h1:jhnBjNi9UFpfpl8YZhA9CrOqpnJdvzuiHsl/dnxl11M= howett.net/plist v0.0.0-20181124034731-591f970eefbb/go.mod h1:vMygbs4qMhSZSc4lCUl2OEE+rDiIIJAIdR4m7MiMcm0= launchpad.net/gocheck v0.0.0-20140225173054-000000000087 h1:Izowp2XBH6Ya6rv+hqbceQyw/gSGoXfH/UPoTGduL54= From 247a5e2c496eaae153cab85d88335db922e36ed0 Mon Sep 17 00:00:00 2001 From: Jakub Sztandera Date: Thu, 24 Sep 2020 17:49:58 +0200 Subject: [PATCH 279/303] Go mod tidy Signed-off-by: Jakub Sztandera --- go.sum | 4 ---- 1 file changed, 4 deletions(-) diff --git a/go.sum b/go.sum index cbceb52c6..0f309ce1a 100644 --- a/go.sum +++ b/go.sum @@ -528,10 +528,6 @@ github.com/ipfs/go-fs-lock v0.0.6/go.mod h1:OTR+Rj9sHiRubJh3dRhD15Juhd/+w6VPOY28 github.com/ipfs/go-graphsync v0.1.0/go.mod h1:jMXfqIEDFukLPZHqDPp8tJMbHO9Rmeb9CEGevngQbmE= github.com/ipfs/go-graphsync v0.2.1 h1:MdehhqBSuTI2LARfKLkpYnt0mUrqHs/mtuDnESXHBfU= github.com/ipfs/go-graphsync v0.2.1/go.mod h1:gEBvJUNelzMkaRPJTpg/jaKN4AQW/7wDWu0K92D8o10= -github.com/ipfs/go-graphsync v0.2.0 h1:x94MvHLNuRwBlZzVal7tR1RYK7T7H6bqQLPopxDbIF0= -github.com/ipfs/go-graphsync v0.2.0/go.mod h1:gEBvJUNelzMkaRPJTpg/jaKN4AQW/7wDWu0K92D8o10= -github.com/ipfs/go-graphsync v0.1.2 h1:25Ll9kIXCE+DY0dicvfS3KMw+U5sd01b/FJbA7KAbhg= -github.com/ipfs/go-graphsync v0.1.2/go.mod h1:sLXVXm1OxtE2XYPw62MuXCdAuNwkAdsbnfrmos5odbA= github.com/ipfs/go-hamt-ipld v0.1.1 h1:0IQdvwnAAUKmDE+PMJa5y1QiwOPHpI9+eAbQEEEYthk= github.com/ipfs/go-hamt-ipld v0.1.1/go.mod h1:1EZCr2v0jlCnhpa+aZ0JZYp8Tt2w16+JJOAVz17YcDk= github.com/ipfs/go-ipfs-blockstore v0.0.1/go.mod h1:d3WClOmRQKFnJ0Jz/jj/zmksX0ma1gROTlovZKBmN08= From baef3c8dd26318fb435c894bfd030e7daf68834a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Tue, 29 Sep 2020 15:22:46 +0200 Subject: [PATCH 280/303] sectorstorage: Fix potential panic in FinalizeSector --- .../sector-storage/ffiwrapper/sealer_cgo.go | 47 ++++++++++--------- 1 file changed, 25 insertions(+), 22 deletions(-) diff --git a/extern/sector-storage/ffiwrapper/sealer_cgo.go b/extern/sector-storage/ffiwrapper/sealer_cgo.go index 9bc2680ed..d75501838 100644 --- a/extern/sector-storage/ffiwrapper/sealer_cgo.go +++ b/extern/sector-storage/ffiwrapper/sealer_cgo.go @@ -546,34 +546,37 @@ func (sb *Sealer) FinalizeSector(ctx context.Context, sector abi.SectorID, keepU defer done() pf, err := openPartialFile(maxPieceSize, paths.Unsealed) - if xerrors.Is(err, os.ErrNotExist) { - return xerrors.Errorf("opening partial file: %w", err) - } + if err == nil { + var at uint64 + for sr.HasNext() { + r, err := sr.NextRun() + if err != nil { + _ = pf.Close() + return err + } - var at uint64 - for sr.HasNext() { - r, err := sr.NextRun() - if err != nil { - _ = pf.Close() + offset := at + at += r.Len + if !r.Val { + continue + } + + err = pf.Free(storiface.PaddedByteIndex(abi.UnpaddedPieceSize(offset).Padded()), abi.UnpaddedPieceSize(r.Len).Padded()) + if err != nil { + _ = pf.Close() + return xerrors.Errorf("free partial file range: %w", err) + } + } + + if err := pf.Close(); err != nil { return err } - - offset := at - at += r.Len - if !r.Val { - continue - } - - err = pf.Free(storiface.PaddedByteIndex(abi.UnpaddedPieceSize(offset).Padded()), abi.UnpaddedPieceSize(r.Len).Padded()) - if err != nil { - _ = pf.Close() - return xerrors.Errorf("free partial file range: %w", err) + } else { + if !xerrors.Is(err, os.ErrNotExist) { + return xerrors.Errorf("opening partial file: %w", err) } } - if err := pf.Close(); err != nil { - return err - } } paths, done, err := sb.sectors.AcquireSector(ctx, sector, stores.FTCache, 0, stores.PathStorage) From 9fe32b7777af8037e1572ccb84feb639970b049c Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Wed, 30 Sep 2020 01:10:03 -0400 Subject: [PATCH 281/303] Fix wallet list --- cli/wallet.go | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/cli/wallet.go b/cli/wallet.go index 0d69673f9..aa5b9bed3 100644 --- a/cli/wallet.go +++ b/cli/wallet.go @@ -89,10 +89,8 @@ var walletList = &cli.Command{ return err } - def, err := api.WalletDefaultAddress(ctx) - if err != nil { - return err - } + // Assume an error means no default key is set + def, _ := api.WalletDefaultAddress(ctx) tw := tablewriter.New( tablewriter.Col("Address"), From a4e71174297138fdb4d25240fafe4b90abfc656d Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Sun, 27 Sep 2020 17:52:26 -0400 Subject: [PATCH 282/303] Add lotus shed util to validate a tipset --- api/api_full.go | 3 ++ api/apistruct/struct.go | 5 ++++ chain/store/store.go | 10 +++++++ cmd/lotus-shed/main.go | 1 + cmd/lotus-shed/sync.go | 64 +++++++++++++++++++++++++++++++++++++++++ node/impl/full/sync.go | 26 +++++++++++++++++ 6 files changed, 109 insertions(+) create mode 100644 cmd/lotus-shed/sync.go diff --git a/api/api_full.go b/api/api_full.go index 6d2d0c7b5..0e5622f4c 100644 --- a/api/api_full.go +++ b/api/api_full.go @@ -176,6 +176,9 @@ type FullNode interface { // the reason. SyncCheckBad(ctx context.Context, bcid cid.Cid) (string, error) + // SyncValidateTipset indicates whether the provided tipset is valid or not + SyncValidateTipset(ctx context.Context, tsk types.TipSetKey) (bool, error) + // MethodGroup: Mpool // The Mpool methods are for interacting with the message pool. The message pool // manages all incoming and outgoing 'messages' going over the network. diff --git a/api/apistruct/struct.go b/api/apistruct/struct.go index d5b6950ad..cc2b8b5b5 100644 --- a/api/apistruct/struct.go +++ b/api/apistruct/struct.go @@ -112,6 +112,7 @@ type FullNodeStruct struct { SyncMarkBad func(ctx context.Context, bcid cid.Cid) error `perm:"admin"` SyncUnmarkBad func(ctx context.Context, bcid cid.Cid) error `perm:"admin"` SyncCheckBad func(ctx context.Context, bcid cid.Cid) (string, error) `perm:"read"` + SyncValidateTipset func(ctx context.Context, tsk types.TipSetKey) (bool, error) `perm:"read"` MpoolGetConfig func(context.Context) (*types.MpoolConfig, error) `perm:"read"` MpoolSetConfig func(context.Context, *types.MpoolConfig) error `perm:"write"` @@ -735,6 +736,10 @@ func (c *FullNodeStruct) SyncCheckBad(ctx context.Context, bcid cid.Cid) (string return c.Internal.SyncCheckBad(ctx, bcid) } +func (c *FullNodeStruct) SyncValidateTipset(ctx context.Context, tsk types.TipSetKey) (bool, error) { + return c.Internal.SyncValidateTipset(ctx, tsk) +} + func (c *FullNodeStruct) StateNetworkName(ctx context.Context) (dtypes.NetworkName, error) { return c.Internal.StateNetworkName(ctx) } diff --git a/chain/store/store.go b/chain/store/store.go index 6c93db7a0..0806fb921 100644 --- a/chain/store/store.go +++ b/chain/store/store.go @@ -286,6 +286,16 @@ func (cs *ChainStore) MarkBlockAsValidated(ctx context.Context, blkid cid.Cid) e return nil } +func (cs *ChainStore) UnmarkBlockAsValidated(ctx context.Context, blkid cid.Cid) error { + key := blockValidationCacheKeyPrefix.Instance(blkid.String()) + + if err := cs.ds.Delete(key); err != nil { + return xerrors.Errorf("removing from valid block cache: %w", err) + } + + return nil +} + func (cs *ChainStore) SetGenesis(b *types.BlockHeader) error { ts, err := types.NewTipSet([]*types.BlockHeader{b}) if err != nil { diff --git a/cmd/lotus-shed/main.go b/cmd/lotus-shed/main.go index c7ded7a25..3864d3014 100644 --- a/cmd/lotus-shed/main.go +++ b/cmd/lotus-shed/main.go @@ -38,6 +38,7 @@ func main() { exportChainCmd, consensusCmd, serveDealStatsCmd, + syncCmd, } app := &cli.App{ diff --git a/cmd/lotus-shed/sync.go b/cmd/lotus-shed/sync.go new file mode 100644 index 000000000..bfe7cc8b7 --- /dev/null +++ b/cmd/lotus-shed/sync.go @@ -0,0 +1,64 @@ +package main + +import ( + "fmt" + + "github.com/ipfs/go-cid" + + "github.com/filecoin-project/lotus/chain/types" + lcli "github.com/filecoin-project/lotus/cli" + "github.com/urfave/cli/v2" +) + +var syncCmd = &cli.Command{ + Name: "sync", + Usage: "tools for diagnosing sync issues", + Flags: []cli.Flag{}, + Subcommands: []*cli.Command{ + syncValidateCmd, + }, +} + +var syncValidateCmd = &cli.Command{ + Name: "validate", + Usage: "checks whether a provided tipset is valid", + Action: func(cctx *cli.Context) error { + api, closer, err := lcli.GetFullNodeAPI(cctx) + if err != nil { + return err + } + + defer closer() + ctx := lcli.ReqContext(cctx) + + if cctx.Args().Len() < 1 { + fmt.Println("usage: ...") + fmt.Println("At least one block cid must be provided") + return nil + } + + args := cctx.Args().Slice() + + var tscids []cid.Cid + for _, s := range args { + c, err := cid.Decode(s) + if err != nil { + return fmt.Errorf("block cid was invalid: %s", err) + } + tscids = append(tscids, c) + } + + tsk := types.NewTipSetKey(tscids...) + + valid, err := api.SyncValidateTipset(ctx, tsk) + if err != nil { + fmt.Println("Tipset is invalid: ", err) + } + + if valid { + fmt.Println("Tipset is valid") + } + + return nil + }, +} diff --git a/node/impl/full/sync.go b/node/impl/full/sync.go index dc3bfe230..221942673 100644 --- a/node/impl/full/sync.go +++ b/node/impl/full/sync.go @@ -126,3 +126,29 @@ func (a *SyncAPI) SyncCheckBad(ctx context.Context, bcid cid.Cid) (string, error return reason, nil } + +func (a *SyncAPI) SyncValidateTipset(ctx context.Context, tsk types.TipSetKey) (bool, error) { + ts, err := a.Syncer.ChainStore().LoadTipSet(tsk) + if err != nil { + return false, err + } + + fts, err := a.Syncer.ChainStore().TryFillTipSet(ts) + if err != nil { + return false, err + } + + for _, blk := range tsk.Cids() { + err = a.Syncer.ChainStore().UnmarkBlockAsValidated(ctx, blk) + if err != nil { + return false, err + } + } + + err = a.Syncer.ValidateTipSet(ctx, fts) + if err != nil { + return false, err + } + + return true, nil +} From 73d193bd9cd1b4d5e9355058febed293087a9364 Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Sun, 27 Sep 2020 18:08:58 -0400 Subject: [PATCH 283/303] Update docs --- documentation/en/api-methods.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/documentation/en/api-methods.md b/documentation/en/api-methods.md index ed082ccbf..29271bdd5 100644 --- a/documentation/en/api-methods.md +++ b/documentation/en/api-methods.md @@ -169,6 +169,7 @@ * [SyncState](#SyncState) * [SyncSubmitBlock](#SyncSubmitBlock) * [SyncUnmarkBad](#SyncUnmarkBad) + * [SyncValidateTipset](#SyncValidateTipset) * [Wallet](#Wallet) * [WalletBalance](#WalletBalance) * [WalletDefaultAddress](#WalletDefaultAddress) @@ -4379,6 +4380,28 @@ Inputs: Response: `{}` +### SyncValidateTipset +SyncValidateTipset indicates whether the provided tipset is valid or not + + +Perms: read + +Inputs: +```json +[ + [ + { + "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + }, + { + "/": "bafy2bzacebp3shtrn43k7g3unredz7fxn4gj533d3o43tqn2p2ipxxhrvchve" + } + ] +] +``` + +Response: `true` + ## Wallet From c45c8f34a16605a087bd4c6b5b022f8828784156 Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Wed, 30 Sep 2020 01:39:06 -0400 Subject: [PATCH 284/303] Parametrise whether sync validators should use cache --- chain/sync.go | 28 ++++++++++++++++------------ chain/sync_test.go | 4 ++-- node/impl/full/sync.go | 9 +-------- 3 files changed, 19 insertions(+), 22 deletions(-) diff --git a/chain/sync.go b/chain/sync.go index 78e5178d1..b2e3bb7f1 100644 --- a/chain/sync.go +++ b/chain/sync.go @@ -597,7 +597,7 @@ func isPermanent(err error) bool { return !errors.Is(err, ErrTemporal) } -func (syncer *Syncer) ValidateTipSet(ctx context.Context, fts *store.FullTipSet) error { +func (syncer *Syncer) ValidateTipSet(ctx context.Context, fts *store.FullTipSet, useCache bool) error { ctx, span := trace.StartSpan(ctx, "validateTipSet") defer span.End() @@ -613,7 +613,7 @@ func (syncer *Syncer) ValidateTipSet(ctx context.Context, fts *store.FullTipSet) b := b // rebind to a scoped variable futures = append(futures, async.Err(func() error { - if err := syncer.ValidateBlock(ctx, b); err != nil { + if err := syncer.ValidateBlock(ctx, b, useCache); err != nil { if isPermanent(err) { syncer.bad.Add(b.Cid(), NewBadBlockReason([]cid.Cid{b.Cid()}, err.Error())) } @@ -680,7 +680,7 @@ func blockSanityChecks(h *types.BlockHeader) error { } // ValidateBlock should match up with 'Semantical Validation' in validation.md in the spec -func (syncer *Syncer) ValidateBlock(ctx context.Context, b *types.FullBlock) (err error) { +func (syncer *Syncer) ValidateBlock(ctx context.Context, b *types.FullBlock, useCache bool) (err error) { defer func() { // b.Cid() could panic for empty blocks that are used in tests. if rerr := recover(); rerr != nil { @@ -689,13 +689,15 @@ func (syncer *Syncer) ValidateBlock(ctx context.Context, b *types.FullBlock) (er } }() - isValidated, err := syncer.store.IsBlockValidated(ctx, b.Cid()) - if err != nil { - return xerrors.Errorf("check block validation cache %s: %w", b.Cid(), err) - } + if useCache { + isValidated, err := syncer.store.IsBlockValidated(ctx, b.Cid()) + if err != nil { + return xerrors.Errorf("check block validation cache %s: %w", b.Cid(), err) + } - if isValidated { - return nil + if isValidated { + return nil + } } validationStart := build.Clock.Now() @@ -959,8 +961,10 @@ func (syncer *Syncer) ValidateBlock(ctx context.Context, b *types.FullBlock) (er return mulErr } - if err := syncer.store.MarkBlockAsValidated(ctx, b.Cid()); err != nil { - return xerrors.Errorf("caching block validation %s: %w", b.Cid(), err) + if useCache { + if err := syncer.store.MarkBlockAsValidated(ctx, b.Cid()); err != nil { + return xerrors.Errorf("caching block validation %s: %w", b.Cid(), err) + } } return nil @@ -1462,7 +1466,7 @@ func (syncer *Syncer) syncMessagesAndCheckState(ctx context.Context, headers []* return syncer.iterFullTipsets(ctx, headers, func(ctx context.Context, fts *store.FullTipSet) error { log.Debugw("validating tipset", "height", fts.TipSet().Height(), "size", len(fts.TipSet().Cids())) - if err := syncer.ValidateTipSet(ctx, fts); err != nil { + if err := syncer.ValidateTipSet(ctx, fts, true); err != nil { log.Errorf("failed to validate tipset: %+v", err) return xerrors.Errorf("message processing failed: %w", err) } diff --git a/chain/sync_test.go b/chain/sync_test.go index 7a839be2b..1b06f604b 100644 --- a/chain/sync_test.go +++ b/chain/sync_test.go @@ -732,7 +732,7 @@ func TestSyncInputs(t *testing.T) { err := s.ValidateBlock(context.TODO(), &types.FullBlock{ Header: &types.BlockHeader{}, - }) + }, false) if err == nil { t.Fatal("should error on empty block") } @@ -741,7 +741,7 @@ func TestSyncInputs(t *testing.T) { h.ElectionProof = nil - err = s.ValidateBlock(context.TODO(), &types.FullBlock{Header: h}) + err = s.ValidateBlock(context.TODO(), &types.FullBlock{Header: h}, false) if err == nil { t.Fatal("should error on block with nil election proof") } diff --git a/node/impl/full/sync.go b/node/impl/full/sync.go index 221942673..1bd3af415 100644 --- a/node/impl/full/sync.go +++ b/node/impl/full/sync.go @@ -138,14 +138,7 @@ func (a *SyncAPI) SyncValidateTipset(ctx context.Context, tsk types.TipSetKey) ( return false, err } - for _, blk := range tsk.Cids() { - err = a.Syncer.ChainStore().UnmarkBlockAsValidated(ctx, blk) - if err != nil { - return false, err - } - } - - err = a.Syncer.ValidateTipSet(ctx, fts) + err = a.Syncer.ValidateTipSet(ctx, fts, false) if err != nil { return false, err } From a388bcfad61d90dc5718982095c1707f6d858cdf Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Wed, 30 Sep 2020 01:43:10 -0400 Subject: [PATCH 285/303] Add an endpoint to validate whether a string is a well-formed address --- api/api_full.go | 2 ++ api/apistruct/struct.go | 29 +++++++++++++++++------------ node/impl/full/wallet.go | 4 ++++ 3 files changed, 23 insertions(+), 12 deletions(-) diff --git a/api/api_full.go b/api/api_full.go index 6d2d0c7b5..7b7574c26 100644 --- a/api/api_full.go +++ b/api/api_full.go @@ -244,6 +244,8 @@ type FullNode interface { WalletImport(context.Context, *types.KeyInfo) (address.Address, error) // WalletDelete deletes an address from the wallet. WalletDelete(context.Context, address.Address) error + // WalletValidateAddress validates whether a given string can be decoded as a well-formed address + WalletValidateAddress(context.Context, string) (address.Address, error) // Other diff --git a/api/apistruct/struct.go b/api/apistruct/struct.go index d5b6950ad..73c4d8ed5 100644 --- a/api/apistruct/struct.go +++ b/api/apistruct/struct.go @@ -129,18 +129,19 @@ type FullNodeStruct struct { MinerGetBaseInfo func(context.Context, address.Address, abi.ChainEpoch, types.TipSetKey) (*api.MiningBaseInfo, error) `perm:"read"` MinerCreateBlock func(context.Context, *api.BlockTemplate) (*types.BlockMsg, error) `perm:"write"` - WalletNew func(context.Context, crypto.SigType) (address.Address, error) `perm:"write"` - WalletHas func(context.Context, address.Address) (bool, error) `perm:"write"` - WalletList func(context.Context) ([]address.Address, error) `perm:"write"` - WalletBalance func(context.Context, address.Address) (types.BigInt, error) `perm:"read"` - WalletSign func(context.Context, address.Address, []byte) (*crypto.Signature, error) `perm:"sign"` - WalletSignMessage func(context.Context, address.Address, *types.Message) (*types.SignedMessage, error) `perm:"sign"` - WalletVerify func(context.Context, address.Address, []byte, *crypto.Signature) (bool, error) `perm:"read"` - WalletDefaultAddress func(context.Context) (address.Address, error) `perm:"write"` - WalletSetDefault func(context.Context, address.Address) error `perm:"admin"` - WalletExport func(context.Context, address.Address) (*types.KeyInfo, error) `perm:"admin"` - WalletImport func(context.Context, *types.KeyInfo) (address.Address, error) `perm:"admin"` - WalletDelete func(context.Context, address.Address) error `perm:"write"` + WalletNew func(context.Context, crypto.SigType) (address.Address, error) `perm:"write"` + WalletHas func(context.Context, address.Address) (bool, error) `perm:"write"` + WalletList func(context.Context) ([]address.Address, error) `perm:"write"` + WalletBalance func(context.Context, address.Address) (types.BigInt, error) `perm:"read"` + WalletSign func(context.Context, address.Address, []byte) (*crypto.Signature, error) `perm:"sign"` + WalletSignMessage func(context.Context, address.Address, *types.Message) (*types.SignedMessage, error) `perm:"sign"` + WalletVerify func(context.Context, address.Address, []byte, *crypto.Signature) (bool, error) `perm:"read"` + WalletDefaultAddress func(context.Context) (address.Address, error) `perm:"write"` + WalletSetDefault func(context.Context, address.Address) error `perm:"admin"` + WalletExport func(context.Context, address.Address) (*types.KeyInfo, error) `perm:"admin"` + WalletImport func(context.Context, *types.KeyInfo) (address.Address, error) `perm:"admin"` + WalletDelete func(context.Context, address.Address) error `perm:"write"` + WalletValidateAddress func(context.Context, string) (address.Address, error) `perm:"read"` ClientImport func(ctx context.Context, ref api.FileRef) (*api.ImportRes, error) `perm:"admin"` ClientListImports func(ctx context.Context) ([]api.Import, error) `perm:"write"` @@ -631,6 +632,10 @@ func (c *FullNodeStruct) WalletDelete(ctx context.Context, addr address.Address) return c.Internal.WalletDelete(ctx, addr) } +func (c *FullNodeStruct) WalletValidateAddress(ctx context.Context, str string) (address.Address, error) { + return c.Internal.WalletValidateAddress(ctx, str) +} + func (c *FullNodeStruct) MpoolGetNonce(ctx context.Context, addr address.Address) (uint64, error) { return c.Internal.MpoolGetNonce(ctx, addr) } diff --git a/node/impl/full/wallet.go b/node/impl/full/wallet.go index 64231b74e..b2ecdebbd 100644 --- a/node/impl/full/wallet.go +++ b/node/impl/full/wallet.go @@ -90,3 +90,7 @@ func (a *WalletAPI) WalletImport(ctx context.Context, ki *types.KeyInfo) (addres func (a *WalletAPI) WalletDelete(ctx context.Context, addr address.Address) error { return a.Wallet.DeleteKey(addr) } + +func (a *WalletAPI) WalletValidateAddress(ctx context.Context, str string) (address.Address, error) { + return address.NewFromString(str) +} From bc4cbdc8957e45daca3b24ed5f434ebf72ced58b Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Wed, 30 Sep 2020 01:45:03 -0400 Subject: [PATCH 286/303] Update docs --- documentation/en/api-methods.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/documentation/en/api-methods.md b/documentation/en/api-methods.md index ed082ccbf..beaf7f3b6 100644 --- a/documentation/en/api-methods.md +++ b/documentation/en/api-methods.md @@ -181,6 +181,7 @@ * [WalletSetDefault](#WalletSetDefault) * [WalletSign](#WalletSign) * [WalletSignMessage](#WalletSignMessage) + * [WalletValidateAddress](#WalletValidateAddress) * [WalletVerify](#WalletVerify) ## @@ -4585,6 +4586,21 @@ Response: } ``` +### WalletValidateAddress +WalletValidateAddress validates whether a given string can be decoded as a well-formed address + + +Perms: read + +Inputs: +```json +[ + "string value" +] +``` + +Response: `"t01234"` + ### WalletVerify WalletVerify takes an address, a signature, and some bytes, and indicates whether the signature is valid. The address does not have to be in the wallet. From 1affd498c172ac7b29192b09f67be76b83fabe2e Mon Sep 17 00:00:00 2001 From: Dan Shao Date: Wed, 30 Sep 2020 14:23:35 +0800 Subject: [PATCH 287/303] Add --no-swap flag for worker --- cmd/lotus-seal-worker/main.go | 7 +++++++ extern/sector-storage/localworker.go | 10 +++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/cmd/lotus-seal-worker/main.go b/cmd/lotus-seal-worker/main.go index e36514bb8..d2c57e680 100644 --- a/cmd/lotus-seal-worker/main.go +++ b/cmd/lotus-seal-worker/main.go @@ -109,6 +109,11 @@ var runCmd = &cli.Command{ Name: "no-local-storage", Usage: "don't use storageminer repo for sector storage", }, + &cli.BoolFlag{ + Name: "no-swap", + Usage: "don't use swap", + Value: false, + }, &cli.BoolFlag{ Name: "addpiece", Usage: "enable addpiece", @@ -346,6 +351,7 @@ var runCmd = &cli.Command{ LocalWorker: sectorstorage.NewLocalWorker(sectorstorage.WorkerConfig{ SealProof: spt, TaskTypes: taskTypes, + NoSwap: cctx.Bool("no-swap"), }, remote, localStore, nodeApi), localStore: localStore, ls: lr, @@ -465,6 +471,7 @@ func watchMinerConn(ctx context.Context, cctx *cli.Context, nodeApi api.StorageM "run", fmt.Sprintf("--listen=%s", cctx.String("listen")), fmt.Sprintf("--no-local-storage=%t", cctx.Bool("no-local-storage")), + fmt.Sprintf("--no-swap=%t", cctx.Bool("no-swap")), fmt.Sprintf("--addpiece=%t", cctx.Bool("addpiece")), fmt.Sprintf("--precommit1=%t", cctx.Bool("precommit1")), fmt.Sprintf("--unseal=%t", cctx.Bool("unseal")), diff --git a/extern/sector-storage/localworker.go b/extern/sector-storage/localworker.go index 2c3c350f7..b1193a2e2 100644 --- a/extern/sector-storage/localworker.go +++ b/extern/sector-storage/localworker.go @@ -26,6 +26,7 @@ var pathTypes = []stores.SectorFileType{stores.FTUnsealed, stores.FTSealed, stor type WorkerConfig struct { SealProof abi.RegisteredSealProof TaskTypes []sealtasks.TaskType + NoSwap bool } type LocalWorker struct { @@ -33,6 +34,7 @@ type LocalWorker struct { storage stores.Store localStore *stores.Local sindex stores.SectorIndex + noSwap bool acceptTasks map[sealtasks.TaskType]struct{} } @@ -50,6 +52,7 @@ func NewLocalWorker(wcfg WorkerConfig, store stores.Store, local *stores.Local, storage: store, localStore: local, sindex: sindex, + noSwap: wcfg.NoSwap, acceptTasks: acceptTasks, } @@ -275,11 +278,16 @@ func (l *LocalWorker) Info(context.Context) (storiface.WorkerInfo, error) { return storiface.WorkerInfo{}, xerrors.Errorf("getting memory info: %w", err) } + memSwap := mem.VirtualTotal + if l.noSwap { + memSwap = 0 + } + return storiface.WorkerInfo{ Hostname: hostname, Resources: storiface.WorkerResources{ MemPhysical: mem.Total, - MemSwap: mem.VirtualTotal, + MemSwap: memSwap, MemReserved: mem.VirtualUsed + mem.Total - mem.Available, // TODO: sub this process CPUs: uint64(runtime.NumCPU()), GPUs: gpus, From 6abccc4d5ed9c977916a812b3aa3e4407fd124ae Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Wed, 30 Sep 2020 02:56:38 -0400 Subject: [PATCH 288/303] Add an option to set config --- cmd/lotus/daemon.go | 8 ++++++++ node/repo/fsrepo.go | 34 ++++++++++++++++++++-------------- 2 files changed, 28 insertions(+), 14 deletions(-) diff --git a/cmd/lotus/daemon.go b/cmd/lotus/daemon.go index b976fde79..a0f754a60 100644 --- a/cmd/lotus/daemon.go +++ b/cmd/lotus/daemon.go @@ -127,6 +127,10 @@ var DaemonCmd = &cli.Command{ Usage: "manage open file limit", Value: true, }, + &cli.StringFlag{ + Name: "config", + Usage: "specify path of config file to use", + }, }, Action: func(cctx *cli.Context) error { err := runmetrics.Enable(runmetrics.RunMetricOptions{ @@ -180,6 +184,10 @@ var DaemonCmd = &cli.Command{ return xerrors.Errorf("opening fs repo: %w", err) } + if cctx.String("config") != "" { + r.SetConfigPath(cctx.String("config")) + } + if err := r.Init(repo.FullNode); err != nil && err != repo.ErrRepoExists { return xerrors.Errorf("repo init error: %w", err) } diff --git a/node/repo/fsrepo.go b/node/repo/fsrepo.go index 709d78d3a..a69cdd55d 100644 --- a/node/repo/fsrepo.go +++ b/node/repo/fsrepo.go @@ -65,7 +65,8 @@ var ErrRepoExists = xerrors.New("repo exists") // FsRepo is struct for repo, use NewFS to create type FsRepo struct { - path string + path string + configPath string } var _ Repo = &FsRepo{} @@ -78,10 +79,15 @@ func NewFS(path string) (*FsRepo, error) { } return &FsRepo{ - path: path, + path: path, + configPath: filepath.Join(path, fsConfig), }, nil } +func (fsr *FsRepo) SetConfigPath(cfgPath string) { + fsr.configPath = cfgPath +} + func (fsr *FsRepo) Exists() (bool, error) { _, err := os.Stat(filepath.Join(fsr.path, fsDatastore)) notexist := os.IsNotExist(err) @@ -115,9 +121,7 @@ func (fsr *FsRepo) Init(t RepoType) error { } func (fsr *FsRepo) initConfig(t RepoType) error { - cfgP := filepath.Join(fsr.path, fsConfig) - - _, err := os.Stat(cfgP) + _, err := os.Stat(fsr.configPath) if err == nil { // exists return nil @@ -125,7 +129,7 @@ func (fsr *FsRepo) initConfig(t RepoType) error { return err } - c, err := os.Create(cfgP) + c, err := os.Create(fsr.configPath) if err != nil { return err } @@ -215,16 +219,18 @@ func (fsr *FsRepo) Lock(repoType RepoType) (LockedRepo, error) { return nil, xerrors.Errorf("could not lock the repo: %w", err) } return &fsLockedRepo{ - path: fsr.path, - repoType: repoType, - closer: closer, + path: fsr.path, + configPath: fsr.configPath, + repoType: repoType, + closer: closer, }, nil } type fsLockedRepo struct { - path string - repoType RepoType - closer io.Closer + path string + configPath string + repoType RepoType + closer io.Closer ds map[string]datastore.Batching dsErr error @@ -277,7 +283,7 @@ func (fsr *fsLockedRepo) Config() (interface{}, error) { } func (fsr *fsLockedRepo) loadConfigFromDisk() (interface{}, error) { - return config.FromFile(fsr.join(fsConfig), defConfForType(fsr.repoType)) + return config.FromFile(fsr.configPath, defConfForType(fsr.repoType)) } func (fsr *fsLockedRepo) SetConfig(c func(interface{})) error { @@ -306,7 +312,7 @@ func (fsr *fsLockedRepo) SetConfig(c func(interface{})) error { } // write buffer of TOML bytes to config file - err = ioutil.WriteFile(fsr.join(fsConfig), buf.Bytes(), 0644) + err = ioutil.WriteFile(fsr.configPath, buf.Bytes(), 0644) if err != nil { return err } From eb6191d0ffd01a7cf7f8544a31acf307b1799fb2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Kripalani?= Date: Wed, 30 Sep 2020 11:02:10 +0100 Subject: [PATCH 289/303] tvx: precursor selection modes; canonical message fetching; basefee. --- cmd/tvx/extract.go | 199 +++++++++++++++++++++++----------------- cmd/tvx/extract_many.go | 43 ++++++--- conformance/driver.go | 58 ++++++++---- conformance/runner.go | 19 +++- go.mod | 2 +- go.sum | 4 +- 6 files changed, 204 insertions(+), 121 deletions(-) diff --git a/cmd/tvx/extract.go b/cmd/tvx/extract.go index 0dc7f6aa0..fef245858 100644 --- a/cmd/tvx/extract.go +++ b/cmd/tvx/extract.go @@ -21,21 +21,27 @@ import ( lcli "github.com/filecoin-project/lotus/cli" "github.com/filecoin-project/lotus/conformance" - "github.com/filecoin-project/go-address" "github.com/filecoin-project/specs-actors/actors/builtin" + "github.com/filecoin-project/test-vectors/schema" "github.com/ipfs/go-cid" "github.com/urfave/cli/v2" ) +const ( + PrecursorSelectAll = "all" + PrecursorSelectSender = "sender" +) + type extractOpts struct { - id string - block string - class string - cid string - file string - retain string + id string + block string + class string + cid string + file string + retain string + precursor string } var extractFlags extractOpts @@ -81,6 +87,16 @@ var extractCmd = &cli.Command{ Value: "accessed-cids", Destination: &extractFlags.retain, }, + &cli.StringFlag{ + Name: "precursor-select", + Usage: "precursors to apply; values: 'all', 'sender'; 'all' selects all preceding" + + "messages in the canonicalised tipset, 'sender' selects only preceding messages from the same" + + "sender. Usually, 'sender' is a good tradeoff and gives you sufficient accuracy. If the receipt sanity" + + "check fails due to gas reasons, switch to 'all', as previous messages in the tipset may have" + + "affected state in a disruptive way", + Value: "sender", + Destination: &extractFlags.precursor, + }, }, } @@ -124,46 +140,38 @@ func doExtract(ctx context.Context, fapi api.FullNode, opts extractOpts) error { return fmt.Errorf("failed while fetching circulating supply: %w", err) } - circSupply := circSupplyDetail.FilCirculating.Int64() + circSupply := circSupplyDetail.FilCirculating log.Printf("message was executed in tipset: %s", execTs.Key()) log.Printf("message was included in tipset: %s", incTs.Key()) log.Printf("circulating supply at inclusion tipset: %d", circSupply) - log.Printf("finding precursor messages") + log.Printf("finding precursor messages using mode: %s", opts.precursor) - // Iterate through blocks, finding the one that contains the message and its - // precursors, if any. - var allmsgs []*types.Message - for _, b := range incTs.Blocks() { - messages, err := fapi.ChainGetBlockMessages(ctx, b.Cid()) - if err != nil { - return err - } - - related, found, err := findMsgAndPrecursors(messages, msg) - if err != nil { - return fmt.Errorf("invariant failed while scanning messages in block %s: %w", b.Cid(), err) - } - - if found { - var mcids []cid.Cid - for _, m := range related { - mcids = append(mcids, m.Cid()) - } - log.Printf("found message in block %s; precursors: %v", b.Cid(), mcids[:len(mcids)-1]) - allmsgs = related - break - } - - log.Printf("message not found in block %s; number of precursors found: %d; ignoring block", b.Cid(), len(related)) + // Fetch messages in canonical order from inclusion tipset. + msgs, err := fapi.ChainGetParentMessages(ctx, execTs.Blocks()[0].Cid()) + if err != nil { + return fmt.Errorf("failed to fetch messages in canonical order from inclusion tipset: %w", err) } - if allmsgs == nil { - // Message was not found; abort. - return fmt.Errorf("did not find a block containing the message") + related, found, err := findMsgAndPrecursors(opts.precursor, msg, msgs) + if err != nil { + return fmt.Errorf("failed while finding message and precursors: %w", err) } - precursors := allmsgs[:len(allmsgs)-1] + if !found { + return fmt.Errorf("message not found; precursors found: %d", len(related)) + } + + var ( + precursors = related[:len(related)-1] + precursorsCids []cid.Cid + ) + + for _, p := range precursors { + precursorsCids = append(precursorsCids, p.Cid()) + } + + log.Println(color.GreenString("found message; precursors (count: %d): %v", len(precursors), precursorsCids)) var ( // create a read-through store that uses ChainGetObject to fetch unknown CIDs. @@ -179,11 +187,20 @@ func doExtract(ctx context.Context, fapi api.FullNode, opts extractOpts) error { root := incTs.ParentState() log.Printf("base state tree root CID: %s", root) + basefee := incTs.Blocks()[0].ParentBaseFee + log.Printf("basefee: %s", basefee) + // on top of that state tree, we apply all precursors. log.Printf("number of precursors to apply: %d", len(precursors)) for i, m := range precursors { log.Printf("applying precursor %d, cid: %s", i, m.Cid()) - _, root, err = driver.ExecuteMessage(pst.Blockstore, root, execTs.Height(), m, &circSupplyDetail.FilCirculating) + _, root, err = driver.ExecuteMessage(pst.Blockstore, conformance.ExecuteMessageParams{ + Preroot: root, + Epoch: execTs.Height(), + Message: m, + CircSupply: &circSupplyDetail.FilCirculating, + BaseFee: &basefee, + }) if err != nil { return fmt.Errorf("failed to execute precursor message: %w", err) } @@ -208,7 +225,13 @@ func doExtract(ctx context.Context, fapi api.FullNode, opts extractOpts) error { tbs.StartTracing() preroot = root - applyret, postroot, err = driver.ExecuteMessage(pst.Blockstore, preroot, execTs.Height(), msg, &circSupplyDetail.FilCirculating) + applyret, postroot, err = driver.ExecuteMessage(pst.Blockstore, conformance.ExecuteMessageParams{ + Preroot: preroot, + Epoch: execTs.Height(), + Message: msg, + CircSupply: &circSupplyDetail.FilCirculating, + BaseFee: &basefee, + }) if err != nil { return fmt.Errorf("failed to execute message: %w", err) } @@ -233,7 +256,13 @@ func doExtract(ctx context.Context, fapi api.FullNode, opts extractOpts) error { if err != nil { return err } - applyret, postroot, err = driver.ExecuteMessage(pst.Blockstore, preroot, execTs.Height(), msg, &circSupplyDetail.FilCirculating) + applyret, postroot, err = driver.ExecuteMessage(pst.Blockstore, conformance.ExecuteMessageParams{ + Preroot: preroot, + Epoch: execTs.Height(), + Message: msg, + CircSupply: &circSupplyDetail.FilCirculating, + BaseFee: &basefee, + }) if err != nil { return fmt.Errorf("failed to execute message: %w", err) } @@ -248,21 +277,39 @@ func doExtract(ctx context.Context, fapi api.FullNode, opts extractOpts) error { log.Printf("message applied; preroot: %s, postroot: %s", preroot, postroot) log.Println("performing sanity check on receipt") - receipt := &schema.Receipt{ - ExitCode: int64(applyret.ExitCode), - ReturnValue: applyret.Return, - GasUsed: applyret.GasUsed, + // TODO sometimes this returns a nil receipt and no error ¯\_(ツ)_/¯ + // ex: https://filfox.info/en/message/bafy2bzacebpxw3yiaxzy2bako62akig46x3imji7fewszen6fryiz6nymu2b2 + // This code is lenient and skips receipt comparison in case of a nil receipt. + rec, err := fapi.StateGetReceipt(ctx, mcid, execTs.Key()) + if err != nil { + return fmt.Errorf("failed to find receipt on chain: %w", err) } + log.Printf("found receipt: %+v", rec) - reporter := new(conformance.LogReporter) - conformance.AssertMsgResult(reporter, receipt, applyret, "as locally executed") - if reporter.Failed() { - log.Println(color.RedString("receipt sanity check failed; aborting")) - return fmt.Errorf("vector generation aborted") + // generate the schema receipt; if we got + var receipt *schema.Receipt + if rec != nil { + receipt = &schema.Receipt{ + ExitCode: int64(rec.ExitCode), + ReturnValue: rec.Return, + GasUsed: rec.GasUsed, + } + reporter := new(conformance.LogReporter) + conformance.AssertMsgResult(reporter, receipt, applyret, "as locally executed") + if reporter.Failed() { + log.Println(color.RedString("receipt sanity check failed; aborting")) + return fmt.Errorf("vector generation aborted") + } + log.Println(color.GreenString("receipt sanity check succeeded")) + } else { + receipt = &schema.Receipt{ + ExitCode: int64(applyret.ExitCode), + ReturnValue: applyret.Return, + GasUsed: applyret.GasUsed, + } + log.Println(color.YellowString("skipping receipts comparison; we got back a nil receipt from lotus")) } - log.Println(color.GreenString("receipt sanity check succeeded")) - log.Println("generating vector") msgBytes, err := msg.Serialize() if err != nil { @@ -312,7 +359,8 @@ func doExtract(ctx context.Context, fapi api.FullNode, opts extractOpts) error { CAR: out.Bytes(), Pre: &schema.Preconditions{ Epoch: int64(execTs.Height()), - CircSupply: &circSupply, + CircSupply: circSupply.Int, + BaseFee: basefee.Int, StateTree: &schema.StateTree{ RootCID: preroot, }, @@ -428,41 +476,22 @@ func fetchThisAndPrevTipset(ctx context.Context, api api.FullNode, target types. return targetTs, prevTs, nil } -// findMsgAndPrecursors scans the messages in a block to locate the supplied -// message, looking into the BLS or SECP section depending on the sender's -// address type. -// -// It returns any precursors (if they exist), and the found message (if found), -// in a slice. -// -// It also returns a boolean indicating whether the message was actually found. -// -// This function also asserts invariants, and if those fail, it returns an error. -func findMsgAndPrecursors(messages *api.BlockMessages, target *types.Message) (related []*types.Message, found bool, err error) { - // Decide which block of messages to process, depending on whether the - // sender is a BLS or a SECP account. - input := messages.BlsMessages - if senderKind := target.From.Protocol(); senderKind == address.SECP256K1 { - input = make([]*types.Message, 0, len(messages.SecpkMessages)) - for _, sm := range messages.SecpkMessages { - input = append(input, &sm.Message) - } - } - - for _, other := range input { - if other.From != target.From { - continue - } - - // this message is from the same sender, so it's related. - related = append(related, other) - - if other.Nonce > target.Nonce { - return nil, false, fmt.Errorf("a message with nonce higher than the target was found before the target; offending mcid: %s", other.Cid()) +// findMsgAndPrecursors ranges through the canonical messages slice, locating +// the target message and returning precursors in accordance to the supplied +// mode. +func findMsgAndPrecursors(mode string, target *types.Message, msgs []api.Message) (related []*types.Message, found bool, err error) { + // Range through canonicalised messages, selecting only the precursors based + // on selection mode. + for _, other := range msgs { + switch { + case mode == PrecursorSelectAll: + fallthrough + case mode == PrecursorSelectSender && other.Message.From == target.From: + related = append(related, other.Message) } // this message is the target; we're done. - if other.Cid() == target.Cid() { + if other.Cid == target.Cid() { return related, true, nil } } diff --git a/cmd/tvx/extract_many.go b/cmd/tvx/extract_many.go index 83ec72b21..9de7aeab5 100644 --- a/cmd/tvx/extract_many.go +++ b/cmd/tvx/extract_many.go @@ -111,8 +111,12 @@ func runExtractMany(c *cli.Context) error { log.Println(color.GreenString("csv sanity check succeeded; header contains fields: %v", header)) } - var generated []string - merr := new(multierror.Error) + var ( + generated []string + merr = new(multierror.Error) + retry []extractOpts // to retry with 'canonical' precursor selection mode + ) + // Read each row and extract the requested message. for { row, err := reader.Read() @@ -164,19 +168,21 @@ func runExtractMany(c *cli.Context) error { // Vector filename, using a base of outdir. file := filepath.Join(outdir, actorcodename, methodname, exitcodename, id) + ".json" - log.Println(color.YellowString("processing message id: %s", id)) + log.Println(color.YellowString("processing message cid with 'sender' precursor mode: %s", id)) opts := extractOpts{ - id: id, - block: block, - class: "message", - cid: cid, - file: file, - retain: "accessed-cids", + id: id, + block: block, + class: "message", + cid: cid, + file: file, + retain: "accessed-cids", + precursor: PrecursorSelectSender, } if err := doExtract(ctx, fapi, opts); err != nil { - merr = multierror.Append(err, fmt.Errorf("failed to extract vector for message %s: %w", cid, err)) + log.Println(color.RedString("failed to extract vector for message %s: %s; queuing for 'canonical' precursor selection", cid, err)) + retry = append(retry, opts) continue } @@ -185,6 +191,21 @@ func runExtractMany(c *cli.Context) error { generated = append(generated, file) } + log.Printf("extractions to try with canonical precursor selection mode: %d", len(retry)) + + for _, r := range retry { + log.Printf("retrying %s: %s", r.cid, r.id) + + r.precursor = PrecursorSelectAll + if err := doExtract(ctx, fapi, r); err != nil { + merr = multierror.Append(merr, fmt.Errorf("failed to extract vector for message %s: %w", r.cid, err)) + continue + } + + log.Println(color.MagentaString("generated file: %s", r.file)) + generated = append(generated, r.file) + } + if len(generated) == 0 { log.Println("no files generated") } else { @@ -195,7 +216,7 @@ func runExtractMany(c *cli.Context) error { } if merr.ErrorOrNil() != nil { - log.Println(color.YellowString("done processing with errors: %s")) + log.Println(color.YellowString("done processing with errors: %s", err)) } else { log.Println(color.GreenString("done processing with no errors")) } diff --git a/conformance/driver.go b/conformance/driver.go index 3f50b67a9..9ced12d74 100644 --- a/conformance/driver.go +++ b/conformance/driver.go @@ -2,6 +2,7 @@ package conformance import ( "context" + "os" "github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/stmgr" @@ -23,15 +24,14 @@ import ( ds "github.com/ipfs/go-datastore" ) -// DefaultCirculatingSupply is the fallback circulating supply returned by -// the driver's CircSupplyCalculator function, used if the vector specifies -// no circulating supply. -var DefaultCirculatingSupply = types.TotalFilecoinInt - var ( - // BaseFee to use in the VM. - // TODO make parametrisable through vector. - BaseFee = abi.NewTokenAmount(100) + // DefaultCirculatingSupply is the fallback circulating supply returned by + // the driver's CircSupplyCalculator function, used if the vector specifies + // no circulating supply. + DefaultCirculatingSupply = types.TotalFilecoinInt + + // DefaultBaseFee to use in the VM, if one is not supplied in the vector. + DefaultBaseFee = abi.NewTokenAmount(100) ) type Driver struct { @@ -139,24 +139,46 @@ func (d *Driver) ExecuteTipset(bs blockstore.Blockstore, ds ds.Batching, preroot return ret, nil } +type ExecuteMessageParams struct { + Preroot cid.Cid + Epoch abi.ChainEpoch + Message *types.Message + CircSupply *abi.TokenAmount + BaseFee *abi.TokenAmount +} + // ExecuteMessage executes a conformance test vector message in a temporary VM. -func (d *Driver) ExecuteMessage(bs blockstore.Blockstore, preroot cid.Cid, epoch abi.ChainEpoch, msg *types.Message, circSupply *abi.TokenAmount) (*vm.ApplyRet, cid.Cid, error) { +func (d *Driver) ExecuteMessage(bs blockstore.Blockstore, params ExecuteMessageParams) (*vm.ApplyRet, cid.Cid, error) { + if !d.vmFlush { + // do not flush the VM, just the state tree; this should be used with + // LOTUS_DISABLE_VM_BUF enabled, so writes will anyway be visible. + _ = os.Setenv("LOTUS_DISABLE_VM_BUF", "iknowitsabadidea") + } + + basefee := DefaultBaseFee + if params.BaseFee != nil { + basefee = *params.BaseFee + } + + circSupply := DefaultCirculatingSupply + if params.CircSupply != nil { + circSupply = *params.CircSupply + } + // dummy state manager; only to reference the GetNetworkVersion method, // which does not depend on state. sm := new(stmgr.StateManager) + vmOpts := &vm.VMOpts{ - StateBase: preroot, - Epoch: epoch, + StateBase: params.Preroot, + Epoch: params.Epoch, Rand: &testRand{}, // TODO always succeeds; need more flexibility. Bstore: bs, Syscalls: mkFakedSigSyscalls(vm.Syscalls(ffiwrapper.ProofVerifier)), // TODO always succeeds; need more flexibility. CircSupplyCalc: func(_ context.Context, _ abi.ChainEpoch, _ *state.StateTree) (abi.TokenAmount, error) { - if circSupply != nil { - return *circSupply, nil - } - return DefaultCirculatingSupply, nil + return circSupply, nil }, - BaseFee: BaseFee, + BaseFee: basefee, NtwkVersion: sm.GetNtwkVersion, } @@ -174,7 +196,7 @@ func (d *Driver) ExecuteMessage(bs blockstore.Blockstore, preroot cid.Cid, epoch lvm.SetInvoker(invoker) - ret, err := lvm.ApplyMessage(d.ctx, toChainMsg(msg)) + ret, err := lvm.ApplyMessage(d.ctx, toChainMsg(params.Message)) if err != nil { return nil, cid.Undef, err } @@ -185,8 +207,6 @@ func (d *Driver) ExecuteMessage(bs blockstore.Blockstore, preroot cid.Cid, epoch // recursive copoy from the temporary blcokstore to the real blockstore. root, err = lvm.Flush(d.ctx) } else { - // do not flush the VM, just the state tree; this should be used with - // LOTUS_DISABLE_VM_BUF enabled, so writes will anyway be visible. root, err = lvm.StateTree().(*state.StateTree).Flush(d.ctx) } diff --git a/conformance/runner.go b/conformance/runner.go index 812f3cc08..2db53b3e4 100644 --- a/conformance/runner.go +++ b/conformance/runner.go @@ -13,6 +13,7 @@ import ( "github.com/fatih/color" "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/exitcode" "github.com/filecoin-project/test-vectors/schema" "github.com/ipfs/go-blockservice" @@ -43,14 +44,20 @@ func ExecuteMessageVector(r Reporter, vector *schema.TestVector) { } // Create a new Driver. - driver := NewDriver(ctx, vector.Selector, DriverOpts{}) + driver := NewDriver(ctx, vector.Selector, DriverOpts{DisableVMFlush: true}) var circSupply *abi.TokenAmount if cs := vector.Pre.CircSupply; cs != nil { - ta := abi.NewTokenAmount(*cs) + ta := big.NewFromGo(cs) circSupply = &ta } + var basefee *abi.TokenAmount + if bf := vector.Pre.BaseFee; bf != nil { + ta := big.NewFromGo(bf) + basefee = &ta + } + // Apply every message. for i, m := range vector.ApplyMessages { msg, err := types.DecodeMessage(m.Bytes) @@ -65,7 +72,13 @@ func ExecuteMessageVector(r Reporter, vector *schema.TestVector) { // Execute the message. var ret *vm.ApplyRet - ret, root, err = driver.ExecuteMessage(bs, root, abi.ChainEpoch(epoch), msg, circSupply) + ret, root, err = driver.ExecuteMessage(bs, ExecuteMessageParams{ + Preroot: root, + Epoch: abi.ChainEpoch(epoch), + Message: msg, + CircSupply: circSupply, + BaseFee: basefee, + }) if err != nil { r.Fatalf("fatal failure when executing message: %s", err) } diff --git a/go.mod b/go.mod index bf3748749..1ef228ee7 100644 --- a/go.mod +++ b/go.mod @@ -38,7 +38,7 @@ require ( github.com/filecoin-project/go-storedcounter v0.0.0-20200421200003-1c99c62e8a5b github.com/filecoin-project/specs-actors v0.9.11 github.com/filecoin-project/specs-storage v0.1.1-0.20200907031224-ed2e5cd13796 - github.com/filecoin-project/test-vectors/schema v0.0.2 + github.com/filecoin-project/test-vectors/schema v0.0.3 github.com/gbrlsnchs/jwt/v3 v3.0.0-beta.1 github.com/go-kit/kit v0.10.0 github.com/go-ole/go-ole v1.2.4 // indirect diff --git a/go.sum b/go.sum index 6a310ed3d..924e8f5c2 100644 --- a/go.sum +++ b/go.sum @@ -258,8 +258,8 @@ github.com/filecoin-project/specs-actors v0.9.11 h1:TnpG7HAeiUrfj0mJM7UaPW0P2137 github.com/filecoin-project/specs-actors v0.9.11/go.mod h1:czlvLQGEX0fjLLfdNHD7xLymy6L3n7aQzRWzsYGf+ys= github.com/filecoin-project/specs-storage v0.1.1-0.20200907031224-ed2e5cd13796 h1:dJsTPWpG2pcTeojO2pyn0c6l+x/3MZYCBgo/9d11JEk= github.com/filecoin-project/specs-storage v0.1.1-0.20200907031224-ed2e5cd13796/go.mod h1:nJRRM7Aa9XVvygr3W9k6xGF46RWzr2zxF/iGoAIfA/g= -github.com/filecoin-project/test-vectors/schema v0.0.2 h1:/Pp//88WBXe0h+ksntdL2HpEgAmbwXrftAfeVG39zdY= -github.com/filecoin-project/test-vectors/schema v0.0.2/go.mod h1:iQ9QXLpYWL3m7warwvK1JC/pTri8mnfEmKygNDqqY6E= +github.com/filecoin-project/test-vectors/schema v0.0.3 h1:1zuBo25B3016inbygYLgYFdpJ2m1BDTbAOCgABRleiU= +github.com/filecoin-project/test-vectors/schema v0.0.3/go.mod h1:iQ9QXLpYWL3m7warwvK1JC/pTri8mnfEmKygNDqqY6E= github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= github.com/flynn/noise v0.0.0-20180327030543-2492fe189ae6 h1:u/UEqS66A5ckRmS4yNpjmVH56sVtS/RfclBAYocb4as= github.com/flynn/noise v0.0.0-20180327030543-2492fe189ae6/go.mod h1:1i71OnUq3iUe1ma7Lr6yG6/rjvM3emb6yoL7xLFzcVQ= From 4d4bab12eba36261dca9c422a83f2640c7d7af2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Wed, 30 Sep 2020 13:33:42 +0200 Subject: [PATCH 290/303] Improve miner sectors list UX --- cli/util.go | 5 +- cmd/lotus-storage-miner/sectors.go | 111 ++++++++++++++++++++++++----- go.mod | 1 + go.sum | 2 + lib/tablewriter/tablewriter.go | 15 +++- 5 files changed, 111 insertions(+), 23 deletions(-) diff --git a/cli/util.go b/cli/util.go index 762cdb565..fb555e320 100644 --- a/cli/util.go +++ b/cli/util.go @@ -5,6 +5,7 @@ import ( "fmt" "time" + "github.com/hako/durafmt" "github.com/ipfs/go-cid" "github.com/filecoin-project/go-state-types/abi" @@ -36,11 +37,11 @@ func parseTipSet(ctx context.Context, api api.FullNode, vals []string) (*types.T func EpochTime(curr, e abi.ChainEpoch) string { switch { case curr > e: - return fmt.Sprintf("%d (%s ago)", e, time.Second*time.Duration(int64(build.BlockDelaySecs)*int64(curr-e))) + return fmt.Sprintf("%d (%s ago)", e, durafmt.Parse(time.Second*time.Duration(int64(build.BlockDelaySecs)*int64(curr-e))).LimitFirstN(2)) case curr == e: return fmt.Sprintf("%d (now)", e) case curr < e: - return fmt.Sprintf("%d (in %s)", e, time.Second*time.Duration(int64(build.BlockDelaySecs)*int64(e-curr))) + return fmt.Sprintf("%d (in %s)", e, durafmt.Parse(time.Second*time.Duration(int64(build.BlockDelaySecs)*int64(e-curr))).LimitFirstN(2)) } panic("math broke") diff --git a/cmd/lotus-storage-miner/sectors.go b/cmd/lotus-storage-miner/sectors.go index 370962bdc..b50f4a86d 100644 --- a/cmd/lotus-storage-miner/sectors.go +++ b/cmd/lotus-storage-miner/sectors.go @@ -5,19 +5,22 @@ import ( "os" "sort" "strconv" - "text/tabwriter" "time" + "github.com/docker/go-units" + "github.com/fatih/color" "github.com/urfave/cli/v2" "golang.org/x/xerrors" "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/big" miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/types" + "github.com/filecoin-project/lotus/lib/tablewriter" lcli "github.com/filecoin-project/lotus/cli" sealing "github.com/filecoin-project/lotus/extern/storage-sealing" @@ -144,8 +147,19 @@ var sectorsListCmd = &cli.Command{ Name: "show-removed", Usage: "show removed sectors", }, + &cli.BoolFlag{ + Name: "color", + Aliases: []string{"c"}, + Value: true, + }, + &cli.BoolFlag{ + Name: "fast", + Usage: "don't show on-chain info for better performance", + }, }, Action: func(cctx *cli.Context) error { + color.NoColor = !cctx.Bool("color") + nodeApi, closer, err := lcli.GetStorageMinerAPI(cctx) if err != nil { return err @@ -170,7 +184,12 @@ var sectorsListCmd = &cli.Command{ return err } - activeSet, err := fullApi.StateMinerActiveSectors(ctx, maddr, types.EmptyTSK) + head, err := fullApi.ChainHead(ctx) + if err != nil { + return err + } + + activeSet, err := fullApi.StateMinerActiveSectors(ctx, maddr, head.Key()) if err != nil { return err } @@ -179,7 +198,7 @@ var sectorsListCmd = &cli.Command{ activeIDs[info.SectorNumber] = struct{}{} } - sset, err := fullApi.StateMinerSectors(ctx, maddr, nil, types.EmptyTSK) + sset, err := fullApi.StateMinerSectors(ctx, maddr, nil, head.Key()) if err != nil { return err } @@ -192,12 +211,26 @@ var sectorsListCmd = &cli.Command{ return list[i] < list[j] }) - w := tabwriter.NewWriter(os.Stdout, 8, 4, 1, ' ', 0) + tw := tablewriter.New( + tablewriter.Col("ID"), + tablewriter.Col("State"), + tablewriter.Col("OnChain"), + tablewriter.Col("Active"), + tablewriter.Col("Expiration"), + tablewriter.Col("Deals"), + tablewriter.Col("DealWeight"), + tablewriter.NewLineCol("Error"), + tablewriter.NewLineCol("EarlyExpiration")) + + fast := cctx.Bool("fast") for _, s := range list { - st, err := nodeApi.SectorsStatus(ctx, s, false) + st, err := nodeApi.SectorsStatus(ctx, s, !fast) if err != nil { - fmt.Fprintf(w, "%d:\tError: %s\n", s, err) + tw.Write(map[string]interface{}{ + "ID": s, + "Error": err, + }) continue } @@ -205,20 +238,60 @@ var sectorsListCmd = &cli.Command{ _, inSSet := commitedIDs[s] _, inASet := activeIDs[s] - _, _ = fmt.Fprintf(w, "%d: %s\tsSet: %s\tactive: %s\ttktH: %d\tseedH: %d\tdeals: %v\t toUpgrade:%t\n", - s, - st.State, - yesno(inSSet), - yesno(inASet), - st.Ticket.Epoch, - st.Seed.Epoch, - st.Deals, - st.ToUpgrade, - ) + dw := .0 + if st.Expiration-st.Activation > 0 { + dw = float64(big.Div(st.DealWeight, big.NewInt(int64(st.Expiration-st.Activation))).Uint64()) + } + + var deals int + for _, deal := range st.Deals { + if deal != 0 { + deals++ + } + } + + exp := st.Expiration + if st.OnTime > 0 && st.OnTime < exp { + exp = st.OnTime // Can be different when the sector was CC upgraded + } + + m := map[string]interface{}{ + "ID": s, + "State": color.New(stateOrder[sealing.SectorState(st.State)].col).Sprint(st.State), + "OnChain": yesno(inSSet), + "Active": yesno(inASet), + } + + if deals > 0 { + m["Deals"] = color.GreenString("%d", deals) + } else { + m["Deals"] = color.BlueString("CC") + if st.ToUpgrade { + m["Deals"] = color.CyanString("CC(upgrade)") + } + } + + if !fast { + if !inSSet { + m["Expiration"] = "n/a" + } else { + m["Expiration"] = lcli.EpochTime(head.Height(), exp) + + if !fast && deals > 0 { + m["DealWeight"] = units.BytesSize(dw) + } + + if st.Early > 0 { + m["EarlyExpiration"] = color.YellowString(lcli.EpochTime(head.Height(), st.Early)) + } + } + } + + tw.Write(m) } } - return w.Flush() + return tw.Flush(os.Stdout) }, } @@ -447,7 +520,7 @@ var sectorsUpdateCmd = &cli.Command{ func yesno(b bool) string { if b { - return "YES" + return color.GreenString("YES") } - return "NO" + return color.RedString("NO") } diff --git a/go.mod b/go.mod index b8896d78f..b9b133f51 100644 --- a/go.mod +++ b/go.mod @@ -46,6 +46,7 @@ require ( github.com/google/uuid v1.1.1 github.com/gorilla/mux v1.7.4 github.com/gorilla/websocket v1.4.2 + github.com/hako/durafmt v0.0.0-20200710122514-c0fb7b4da026 github.com/hannahhoward/go-pubsub v0.0.0-20200423002714-8d62886cc36e github.com/hashicorp/go-multierror v1.1.0 github.com/hashicorp/golang-lru v0.5.4 diff --git a/go.sum b/go.sum index 0f309ce1a..2d9929705 100644 --- a/go.sum +++ b/go.sum @@ -415,6 +415,8 @@ github.com/gxed/go-shellwords v1.0.3/go.mod h1:N7paucT91ByIjmVJHhvoarjoQnmsi3Jd3 github.com/gxed/hashland/keccakpg v0.0.1/go.mod h1:kRzw3HkwxFU1mpmPP8v1WyQzwdGfmKFJ6tItnhQ67kU= github.com/gxed/hashland/murmur3 v0.0.1/go.mod h1:KjXop02n4/ckmZSnY2+HKcLud/tcmvhST0bie/0lS48= github.com/gxed/pubsub v0.0.0-20180201040156-26ebdf44f824/go.mod h1:OiEWyHgK+CWrmOlVquHaIK1vhpUJydC9m0Je6mhaiNE= +github.com/hako/durafmt v0.0.0-20200710122514-c0fb7b4da026 h1:BpJ2o0OR5FV7vrkDYfXYVJQeMNWa8RhklZOpW2ITAIQ= +github.com/hako/durafmt v0.0.0-20200710122514-c0fb7b4da026/go.mod h1:5Scbynm8dF1XAPwIwkGPqzkM/shndPm79Jd1003hTjE= github.com/hannahhoward/cbor-gen-for v0.0.0-20200817222906-ea96cece81f1 h1:F9k+7wv5OIk1zcq23QpdiL0hfDuXPjuOmMNaC6fgQ0Q= github.com/hannahhoward/cbor-gen-for v0.0.0-20200817222906-ea96cece81f1/go.mod h1:jvfsLIxk0fY/2BKSQ1xf2406AKA5dwMmKKv0ADcOfN8= github.com/hannahhoward/go-pubsub v0.0.0-20200423002714-8d62886cc36e h1:3YKHER4nmd7b5qy5t0GWDTwSn4OyRgfAXSmo6VnryBY= diff --git a/lib/tablewriter/tablewriter.go b/lib/tablewriter/tablewriter.go index d77611390..cd045710e 100644 --- a/lib/tablewriter/tablewriter.go +++ b/lib/tablewriter/tablewriter.go @@ -12,6 +12,7 @@ import ( type Column struct { Name string SeparateLine bool + Lines int } type TableWriter struct { @@ -50,6 +51,7 @@ cloop: for i, column := range w.cols { if column.Name == col { byColID[i] = fmt.Sprint(val) + w.cols[i].Lines++ continue cloop } } @@ -58,6 +60,7 @@ cloop: w.cols = append(w.cols, Column{ Name: col, SeparateLine: false, + Lines: 1, }) } @@ -77,7 +80,11 @@ func (w *TableWriter) Flush(out io.Writer) error { w.rows = append([]map[int]string{header}, w.rows...) - for col := range w.cols { + for col, c := range w.cols { + if c.Lines == 0 { + continue + } + for _, row := range w.rows { val, found := row[col] if !found { @@ -94,9 +101,13 @@ func (w *TableWriter) Flush(out io.Writer) error { cols := make([]string, len(w.cols)) for ci, col := range w.cols { + if col.Lines == 0 { + continue + } + e, _ := row[ci] pad := colLengths[ci] - cliStringLength(e) + 2 - if !col.SeparateLine { + if !col.SeparateLine && col.Lines > 0 { e = e + strings.Repeat(" ", pad) if _, err := fmt.Fprint(out, e); err != nil { return err From d2f279c3de755b267562cb0fdf8bb6b471ad0356 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Wed, 30 Sep 2020 13:51:52 +0200 Subject: [PATCH 291/303] Print heman-readable transferred bytes in client list-transfers --- cli/client.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cli/client.go b/cli/client.go index 5d40dce0d..272ab0bdd 100644 --- a/cli/client.go +++ b/cli/client.go @@ -1423,7 +1423,7 @@ func toChannelOutput(useColor bool, otherPartyColumn string, channel lapi.DataTr otherPartyColumn: otherParty, "Root Cid": rootCid, "Initiated?": initiated, - "Transferred": channel.Transferred, + "Transferred": units.BytesSize(float64(channel.Transferred)), "Voucher": voucher, "Message": channel.Message, } From f58881e966dbd087172ecd5e1e1958850a3d2455 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Kripalani?= Date: Wed, 30 Sep 2020 14:57:24 +0100 Subject: [PATCH 292/303] minor fixes. --- cmd/tvx/extract_many.go | 4 ++-- cmd/tvx/stores.go | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cmd/tvx/extract_many.go b/cmd/tvx/extract_many.go index 9de7aeab5..d7a25c10c 100644 --- a/cmd/tvx/extract_many.go +++ b/cmd/tvx/extract_many.go @@ -48,7 +48,7 @@ var extractManyCmd = &cli.Command{ Destination: &extractManyFlags.in, }, &cli.StringFlag{ - Name: "out-dir", + Name: "outdir", Usage: "output directory", Destination: &extractManyFlags.outdir, }, @@ -216,7 +216,7 @@ func runExtractMany(c *cli.Context) error { } if merr.ErrorOrNil() != nil { - log.Println(color.YellowString("done processing with errors: %s", err)) + log.Println(color.YellowString("done processing with errors: %v", merr)) } else { log.Println(color.GreenString("done processing with no errors")) } diff --git a/cmd/tvx/stores.go b/cmd/tvx/stores.go index 6e50e0839..93e0d215f 100644 --- a/cmd/tvx/stores.go +++ b/cmd/tvx/stores.go @@ -11,7 +11,7 @@ import ( "github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/lib/blockstore" - "github.com/filecoin-project/specs-actors/actors/util/adt" + "github.com/filecoin-project/lotus/chain/actors/adt" blocks "github.com/ipfs/go-block-format" "github.com/ipfs/go-blockservice" From ff8663faa0b3a7d1871f2c4c681e243c2cbc229d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Kripalani?= Date: Wed, 30 Sep 2020 14:58:22 +0100 Subject: [PATCH 293/303] update test-vectors submodule. --- extern/test-vectors | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extern/test-vectors b/extern/test-vectors index 6bea015ed..3a6e0b5e0 160000 --- a/extern/test-vectors +++ b/extern/test-vectors @@ -1 +1 @@ -Subproject commit 6bea015edddde116001a4251dce3c4a9966c25d9 +Subproject commit 3a6e0b5e069b1452ce1a032aa315354d645f3ec4 From 1c4f8e83d79d052d1e4408d635daf80b3e81d62c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Kripalani?= Date: Wed, 30 Sep 2020 16:11:44 +0100 Subject: [PATCH 294/303] tvx/extract-many: add batch id, change generated filename. --- cmd/tvx/extract_many.go | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/cmd/tvx/extract_many.go b/cmd/tvx/extract_many.go index d7a25c10c..9679a1dbd 100644 --- a/cmd/tvx/extract_many.go +++ b/cmd/tvx/extract_many.go @@ -20,8 +20,9 @@ import ( ) var extractManyFlags struct { - in string - outdir string + in string + outdir string + batchId string } var extractManyCmd = &cli.Command{ @@ -37,11 +38,17 @@ var extractManyCmd = &cli.Command{ The first row MUST be a header row. At the bare minimum, those seven fields must appear, in the order specified. Extra fields are accepted, but always - after these compulsory six. + after these compulsory seven. `, Action: runExtractMany, Flags: []cli.Flag{ &repoFlag, + &cli.StringFlag{ + Name: "batch-id", + Usage: "batch id; a four-digit left-zero-padded sequential number (e.g. 0041)", + Required: true, + Destination: &extractManyFlags.batchId, + }, &cli.StringFlag{ Name: "in", Usage: "path to input file (csv)", @@ -164,7 +171,7 @@ func runExtractMany(c *cli.Context) error { actorcodename := strings.ReplaceAll(actorcode, "/", "_") // Compute the ID of the vector. - id := fmt.Sprintf("extracted-msg-%s-%s-%s-%s", actorcodename, methodname, exitcodename, seq) + id := fmt.Sprintf("ext-%s-%s-%s-%s-%s", extractManyFlags.batchId, actorcodename, methodname, exitcodename, seq) // Vector filename, using a base of outdir. file := filepath.Join(outdir, actorcodename, methodname, exitcodename, id) + ".json" From be884e27bef3da5e0696c80363379cf8c75fc4a2 Mon Sep 17 00:00:00 2001 From: hannahhoward Date: Tue, 29 Sep 2020 04:53:30 -0700 Subject: [PATCH 295/303] feat(markets): update markets 0.7.0 --- api/api_full.go | 2 +- api/apistruct/struct.go | 4 ++-- cli/client.go | 10 +++++----- documentation/en/api-methods.md | 22 ++++++++------------- go.mod | 10 +++++----- go.sum | 20 +++++++++++-------- markets/loggers/loggers.go | 11 +++++++++++ markets/storageadapter/client.go | 31 ------------------------------ node/builder.go | 7 ++++--- node/impl/client/client.go | 9 +++++---- node/modules/client.go | 11 +++++++---- node/modules/services.go | 24 +++++++++++++++++------ node/modules/storageminer.go | 33 +++++++++++++++++++++++++------- 13 files changed, 104 insertions(+), 90 deletions(-) diff --git a/api/api_full.go b/api/api_full.go index 6d2d0c7b5..24f17d987 100644 --- a/api/api_full.go +++ b/api/api_full.go @@ -275,7 +275,7 @@ type FullNode interface { // of status updates. ClientRetrieveWithEvents(ctx context.Context, order RetrievalOrder, ref *FileRef) (<-chan marketevents.RetrievalEvent, error) // ClientQueryAsk returns a signed StorageAsk from the specified miner. - ClientQueryAsk(ctx context.Context, p peer.ID, miner address.Address) (*storagemarket.SignedStorageAsk, error) + ClientQueryAsk(ctx context.Context, p peer.ID, miner address.Address) (*storagemarket.StorageAsk, error) // ClientCalcCommP calculates the CommP for a specified file ClientCalcCommP(ctx context.Context, inpath string) (*CommPRet, error) // ClientGenCar generates a CAR file for the specified file. diff --git a/api/apistruct/struct.go b/api/apistruct/struct.go index d5b6950ad..a5a3651f4 100644 --- a/api/apistruct/struct.go +++ b/api/apistruct/struct.go @@ -154,7 +154,7 @@ type FullNodeStruct struct { ClientGetDealUpdates func(ctx context.Context) (<-chan api.DealInfo, error) `perm:"read"` ClientRetrieve func(ctx context.Context, order api.RetrievalOrder, ref *api.FileRef) error `perm:"admin"` ClientRetrieveWithEvents func(ctx context.Context, order api.RetrievalOrder, ref *api.FileRef) (<-chan marketevents.RetrievalEvent, error) `perm:"admin"` - ClientQueryAsk func(ctx context.Context, p peer.ID, miner address.Address) (*storagemarket.SignedStorageAsk, error) `perm:"read"` + ClientQueryAsk func(ctx context.Context, p peer.ID, miner address.Address) (*storagemarket.StorageAsk, error) `perm:"read"` ClientCalcCommP func(ctx context.Context, inpath string) (*api.CommPRet, error) `perm:"read"` ClientGenCar func(ctx context.Context, ref api.FileRef, outpath string) error `perm:"write"` ClientDealSize func(ctx context.Context, root cid.Cid) (api.DataSize, error) `perm:"read"` @@ -484,7 +484,7 @@ func (c *FullNodeStruct) ClientRetrieveWithEvents(ctx context.Context, order api return c.Internal.ClientRetrieveWithEvents(ctx, order, ref) } -func (c *FullNodeStruct) ClientQueryAsk(ctx context.Context, p peer.ID, miner address.Address) (*storagemarket.SignedStorageAsk, error) { +func (c *FullNodeStruct) ClientQueryAsk(ctx context.Context, p peer.ID, miner address.Address) (*storagemarket.StorageAsk, error) { return c.Internal.ClientQueryAsk(ctx, p, miner) } func (c *FullNodeStruct) ClientCalcCommP(ctx context.Context, inpath string) (*api.CommPRet, error) { diff --git a/cli/client.go b/cli/client.go index 5d40dce0d..7c3ac9946 100644 --- a/cli/client.go +++ b/cli/client.go @@ -569,7 +569,7 @@ func interactiveDeal(cctx *cli.Context) error { continue } - ask = *a.Ask + ask = *a // TODO: run more validation state = "confirm" @@ -951,15 +951,15 @@ var clientQueryAskCmd = &cli.Command{ } fmt.Printf("Ask: %s\n", maddr) - fmt.Printf("Price per GiB: %s\n", types.FIL(ask.Ask.Price)) - fmt.Printf("Verified Price per GiB: %s\n", types.FIL(ask.Ask.VerifiedPrice)) - fmt.Printf("Max Piece size: %s\n", types.SizeStr(types.NewInt(uint64(ask.Ask.MaxPieceSize)))) + fmt.Printf("Price per GiB: %s\n", types.FIL(ask.Price)) + fmt.Printf("Verified Price per GiB: %s\n", types.FIL(ask.VerifiedPrice)) + fmt.Printf("Max Piece size: %s\n", types.SizeStr(types.NewInt(uint64(ask.MaxPieceSize)))) size := cctx.Int64("size") if size == 0 { return nil } - perEpoch := types.BigDiv(types.BigMul(ask.Ask.Price, types.NewInt(uint64(size))), types.NewInt(1<<30)) + perEpoch := types.BigDiv(types.BigMul(ask.Price, types.NewInt(uint64(size))), types.NewInt(1<<30)) fmt.Printf("Price per Block: %s\n", types.FIL(perEpoch)) duration := cctx.Int64("duration") diff --git a/documentation/en/api-methods.md b/documentation/en/api-methods.md index ed082ccbf..f54aa866a 100644 --- a/documentation/en/api-methods.md +++ b/documentation/en/api-methods.md @@ -1120,20 +1120,14 @@ Inputs: Response: ```json { - "Ask": { - "Price": "0", - "VerifiedPrice": "0", - "MinPieceSize": 1032, - "MaxPieceSize": 1032, - "Miner": "t01234", - "Timestamp": 10101, - "Expiry": 10101, - "SeqNo": 42 - }, - "Signature": { - "Type": 2, - "Data": "Ynl0ZSBhcnJheQ==" - } + "Price": "0", + "VerifiedPrice": "0", + "MinPieceSize": 1032, + "MaxPieceSize": 1032, + "Miner": "t01234", + "Timestamp": 10101, + "Expiry": 10101, + "SeqNo": 42 } ``` diff --git a/go.mod b/go.mod index 2c0322ecc..db00ba2a6 100644 --- a/go.mod +++ b/go.mod @@ -25,15 +25,15 @@ require ( github.com/filecoin-project/go-bitfield v0.2.0 github.com/filecoin-project/go-cbor-util v0.0.0-20191219014500-08c40a1e63a2 github.com/filecoin-project/go-crypto v0.0.0-20191218222705-effae4ea9f03 - github.com/filecoin-project/go-data-transfer v0.6.6 + github.com/filecoin-project/go-data-transfer v0.6.7 github.com/filecoin-project/go-fil-commcid v0.0.0-20200716160307-8f644712406f - github.com/filecoin-project/go-fil-markets v0.6.3 + github.com/filecoin-project/go-fil-markets v0.7.0 github.com/filecoin-project/go-jsonrpc v0.1.2-0.20200822201400-474f4fdccc52 github.com/filecoin-project/go-multistore v0.0.3 github.com/filecoin-project/go-padreader v0.0.0-20200903213702-ed5fae088b20 github.com/filecoin-project/go-paramfetch v0.0.2-0.20200701152213-3e0f0afdc261 github.com/filecoin-project/go-state-types v0.0.0-20200911004822-964d6c679cfc - github.com/filecoin-project/go-statemachine v0.0.0-20200813232949-df9b130df370 + github.com/filecoin-project/go-statemachine v0.0.0-20200925024713-05bd7c71fbfe github.com/filecoin-project/go-statestore v0.1.0 github.com/filecoin-project/go-storedcounter v0.0.0-20200421200003-1c99c62e8a5b github.com/filecoin-project/specs-actors v0.9.11 @@ -54,7 +54,7 @@ require ( github.com/ipfs/go-blockservice v0.1.4-0.20200624145336-a978cec6e834 github.com/ipfs/go-cid v0.0.7 github.com/ipfs/go-cidutil v0.0.2 - github.com/ipfs/go-datastore v0.4.4 + github.com/ipfs/go-datastore v0.4.5 github.com/ipfs/go-ds-badger2 v0.1.1-0.20200708190120-187fc06f714e github.com/ipfs/go-ds-leveldb v0.4.2 github.com/ipfs/go-ds-measure v0.1.0 @@ -112,7 +112,7 @@ require ( github.com/syndtr/goleveldb v1.0.0 github.com/urfave/cli/v2 v2.2.0 github.com/whyrusleeping/bencher v0.0.0-20190829221104-bb6607aa8bba - github.com/whyrusleeping/cbor-gen v0.0.0-20200814224545-656e08ce49ee + github.com/whyrusleeping/cbor-gen v0.0.0-20200826160007-0b9f6c5fb163 github.com/whyrusleeping/multiaddr-filter v0.0.0-20160516205228-e903e4adabd7 github.com/whyrusleeping/pubsub v0.0.0-20131020042734-02de8aa2db3d github.com/xorcare/golden v0.6.1-0.20191112154924-b87f686d7542 diff --git a/go.sum b/go.sum index 05e643708..9d3ccc7e8 100644 --- a/go.sum +++ b/go.sum @@ -224,12 +224,14 @@ github.com/filecoin-project/go-cbor-util v0.0.0-20191219014500-08c40a1e63a2 h1:a github.com/filecoin-project/go-cbor-util v0.0.0-20191219014500-08c40a1e63a2/go.mod h1:pqTiPHobNkOVM5thSRsHYjyQfq7O5QSCMhvuu9JoDlg= github.com/filecoin-project/go-crypto v0.0.0-20191218222705-effae4ea9f03 h1:2pMXdBnCiXjfCYx/hLqFxccPoqsSveQFxVLvNxy9bus= github.com/filecoin-project/go-crypto v0.0.0-20191218222705-effae4ea9f03/go.mod h1:+viYnvGtUTgJRdy6oaeF4MTFKAfatX071MPDPBL11EQ= -github.com/filecoin-project/go-data-transfer v0.6.6 h1:2TccLSxPYJENcYRdov2WvpTvQ1qUMrPkWe8sBrfj36g= -github.com/filecoin-project/go-data-transfer v0.6.6/go.mod h1:C++k1U6+jMQODOaen5OPDo9XQbth9Yq3ie94vNjBJbk= +github.com/filecoin-project/go-data-transfer v0.6.7 h1:Kacr5qz2YWtd3sensU6aXFtES7joeapVDeXApeUD35I= +github.com/filecoin-project/go-data-transfer v0.6.7/go.mod h1:C++k1U6+jMQODOaen5OPDo9XQbth9Yq3ie94vNjBJbk= +github.com/filecoin-project/go-ds-versioning v0.1.0 h1:y/X6UksYTsK8TLCI7rttCKEvl8btmWxyFMEeeWGUxIQ= +github.com/filecoin-project/go-ds-versioning v0.1.0/go.mod h1:mp16rb4i2QPmxBnmanUx8i/XANp+PFCCJWiAb+VW4/s= github.com/filecoin-project/go-fil-commcid v0.0.0-20200716160307-8f644712406f h1:GxJzR3oRIMTPtpZ0b7QF8FKPK6/iPAc7trhlL5k/g+s= github.com/filecoin-project/go-fil-commcid v0.0.0-20200716160307-8f644712406f/go.mod h1:Eaox7Hvus1JgPrL5+M3+h7aSPHc0cVqpSxA+TxIEpZQ= -github.com/filecoin-project/go-fil-markets v0.6.3 h1:3kTxfquGvk3zQY+hJH1kEA28tRQ47phqSRqOI4+YcQM= -github.com/filecoin-project/go-fil-markets v0.6.3/go.mod h1:Ug1yhGhzTYC6qrpKsR2QpU8QRCeBpwkTA9RICVKuOMM= +github.com/filecoin-project/go-fil-markets v0.7.0 h1:tcEZiUNIYQJ4PBzgVpLwfdJ4ZdC4WCv9LsgvsoCXIls= +github.com/filecoin-project/go-fil-markets v0.7.0/go.mod h1:5Pt4DXQqUoUrp9QzlSdlYTpItXxwAtqKrxRWQ6hAOqk= github.com/filecoin-project/go-hamt-ipld v0.1.5 h1:uoXrKbCQZ49OHpsTCkrThPNelC4W3LPEk0OrS/ytIBM= github.com/filecoin-project/go-hamt-ipld v0.1.5 h1:uoXrKbCQZ49OHpsTCkrThPNelC4W3LPEk0OrS/ytIBM= github.com/filecoin-project/go-hamt-ipld v0.1.5/go.mod h1:6Is+ONR5Cd5R6XZoCse1CWaXZc0Hdb/JeX+EQCQzX24= @@ -248,8 +250,8 @@ github.com/filecoin-project/go-state-types v0.0.0-20200905071437-95828685f9df/go github.com/filecoin-project/go-state-types v0.0.0-20200911004822-964d6c679cfc h1:1vr/LoqGq5m5g37Q3sNSAjfwF1uJY0zmiHcvnxY6hik= github.com/filecoin-project/go-state-types v0.0.0-20200911004822-964d6c679cfc/go.mod h1:ezYnPf0bNkTsDibL/psSz5dy4B5awOJ/E7P2Saeep8g= github.com/filecoin-project/go-statemachine v0.0.0-20200714194326-a77c3ae20989/go.mod h1:FGwQgZAt2Gh5mjlwJUlVB62JeYdo+if0xWxSEfBD9ig= -github.com/filecoin-project/go-statemachine v0.0.0-20200813232949-df9b130df370 h1:Jbburj7Ih2iaJ/o5Q9A+EAeTabME6YII7FLi9SKUf5c= -github.com/filecoin-project/go-statemachine v0.0.0-20200813232949-df9b130df370/go.mod h1:FGwQgZAt2Gh5mjlwJUlVB62JeYdo+if0xWxSEfBD9ig= +github.com/filecoin-project/go-statemachine v0.0.0-20200925024713-05bd7c71fbfe h1:dF8u+LEWeIcTcfUcCf3WFVlc81Fr2JKg8zPzIbBDKDw= +github.com/filecoin-project/go-statemachine v0.0.0-20200925024713-05bd7c71fbfe/go.mod h1:FGwQgZAt2Gh5mjlwJUlVB62JeYdo+if0xWxSEfBD9ig= github.com/filecoin-project/go-statestore v0.1.0 h1:t56reH59843TwXHkMcwyuayStBIiWBRilQjQ+5IiwdQ= github.com/filecoin-project/go-statestore v0.1.0/go.mod h1:LFc9hD+fRxPqiHiaqUEZOinUJB4WARkRfNl10O7kTnI= github.com/filecoin-project/go-storedcounter v0.0.0-20200421200003-1c99c62e8a5b h1:fkRZSPrYpk42PV3/lIXiL0LHetxde7vyYYvSsttQtfg= @@ -481,6 +483,8 @@ github.com/ipfs/go-datastore v0.4.1/go.mod h1:SX/xMIKoCszPqp+z9JhPYCmoOoXTvaa13X github.com/ipfs/go-datastore v0.4.2/go.mod h1:SX/xMIKoCszPqp+z9JhPYCmoOoXTvaa13XEbGtsFUhA= github.com/ipfs/go-datastore v0.4.4 h1:rjvQ9+muFaJ+QZ7dN5B1MSDNQ0JVZKkkES/rMZmA8X8= github.com/ipfs/go-datastore v0.4.4/go.mod h1:SX/xMIKoCszPqp+z9JhPYCmoOoXTvaa13XEbGtsFUhA= +github.com/ipfs/go-datastore v0.4.5 h1:cwOUcGMLdLPWgu3SlrCckCMznaGADbPqE0r8h768/Dg= +github.com/ipfs/go-datastore v0.4.5/go.mod h1:eXTcaaiN6uOlVCLS9GjJUJtlvJfM3xk23w3fyfrmmJs= github.com/ipfs/go-detect-race v0.0.1 h1:qX/xay2W3E4Q1U7d9lNs1sU9nvguX0a7319XbyQ6cOk= github.com/ipfs/go-detect-race v0.0.1/go.mod h1:8BNT7shDZPo99Q74BpGMK+4D8Mn4j46UU0LZ723meps= github.com/ipfs/go-ds-badger v0.0.2/go.mod h1:Y3QpeSFWQf6MopLTiZD+VT6IC1yZqaGmjvRcKeSGij8= @@ -1371,8 +1375,8 @@ github.com/whyrusleeping/cbor-gen v0.0.0-20200710004633-5379fc63235d/go.mod h1:f github.com/whyrusleeping/cbor-gen v0.0.0-20200715143311-227fab5a2377/go.mod h1:fgkXqYy7bV2cFeIEOkVTZS/WjXARfBqSH6Q2qHL33hQ= github.com/whyrusleeping/cbor-gen v0.0.0-20200810223238-211df3b9e24c/go.mod h1:fgkXqYy7bV2cFeIEOkVTZS/WjXARfBqSH6Q2qHL33hQ= github.com/whyrusleeping/cbor-gen v0.0.0-20200812213548-958ddffe352c/go.mod h1:fgkXqYy7bV2cFeIEOkVTZS/WjXARfBqSH6Q2qHL33hQ= -github.com/whyrusleeping/cbor-gen v0.0.0-20200814224545-656e08ce49ee h1:U7zWWvvAjT76EiuWPSOiZlQDnaQYPxPoxugTtTAcJK0= -github.com/whyrusleeping/cbor-gen v0.0.0-20200814224545-656e08ce49ee/go.mod h1:fgkXqYy7bV2cFeIEOkVTZS/WjXARfBqSH6Q2qHL33hQ= +github.com/whyrusleeping/cbor-gen v0.0.0-20200826160007-0b9f6c5fb163 h1:TtcUeY2XZSriVWR1pXyfCBWIf/NGC2iUdNw1lofUjUU= +github.com/whyrusleeping/cbor-gen v0.0.0-20200826160007-0b9f6c5fb163/go.mod h1:fgkXqYy7bV2cFeIEOkVTZS/WjXARfBqSH6Q2qHL33hQ= github.com/whyrusleeping/chunker v0.0.0-20181014151217-fe64bd25879f h1:jQa4QT2UP9WYv2nzyawpKMOCl+Z/jW7djv2/J50lj9E= github.com/whyrusleeping/chunker v0.0.0-20181014151217-fe64bd25879f/go.mod h1:p9UJB6dDgdPgMJZs7UjUOdulKyRr9fqkS+6JKAInPy8= github.com/whyrusleeping/go-ctrlnet v0.0.0-20180313164037-f564fbbdaa95/go.mod h1:SJqKCCPXRfBFCwXjfNT/skfsceF7+MBFLI2OrvuRA7g= diff --git a/markets/loggers/loggers.go b/markets/loggers/loggers.go index 27a6b2c63..a8e1c20aa 100644 --- a/markets/loggers/loggers.go +++ b/markets/loggers/loggers.go @@ -29,6 +29,17 @@ func RetrievalProviderLogger(event retrievalmarket.ProviderEvent, deal retrieval log.Infow("retrieval event", "name", retrievalmarket.ProviderEvents[event], "deal ID", deal.ID, "receiver", deal.Receiver, "state", retrievalmarket.DealStatuses[deal.Status], "message", deal.Message) } +// ReadyLogger returns a function to log the results of module initialization +func ReadyLogger(module string) func(error) { + return func(err error) { + if err != nil { + log.Errorw("module initialization error", "module", module, "err", err) + } else { + log.Infow("module ready", "module", module) + } + } +} + type RetrievalEvent struct { Event retrievalmarket.ClientEvent Status retrievalmarket.DealStatus diff --git a/markets/storageadapter/client.go b/markets/storageadapter/client.go index fabc5b197..411c86ec9 100644 --- a/markets/storageadapter/client.go +++ b/markets/storageadapter/client.go @@ -438,37 +438,6 @@ func (c *ClientNodeAdapter) GetDefaultWalletAddress(ctx context.Context) (addres return addr, err } -func (c *ClientNodeAdapter) ValidateAskSignature(ctx context.Context, ask *storagemarket.SignedStorageAsk, encodedTs shared.TipSetToken) (bool, error) { - tsk, err := types.TipSetKeyFromBytes(encodedTs) - if err != nil { - return false, err - } - - mi, err := c.StateMinerInfo(ctx, ask.Ask.Miner, tsk) - if err != nil { - return false, xerrors.Errorf("failed to get worker for miner in ask: %w", err) - } - - sigb, err := cborutil.Dump(ask.Ask) - if err != nil { - return false, xerrors.Errorf("failed to re-serialize ask") - } - - ts, err := c.ChainGetTipSet(ctx, tsk) - if err != nil { - return false, xerrors.Errorf("failed to load tipset") - } - - m, err := c.StateManager.ResolveToKeyAddress(ctx, mi.Worker, ts) - - if err != nil { - return false, xerrors.Errorf("failed to resolve miner to key address") - } - - err = sigs.Verify(ask.Signature, m, sigb) - return err == nil, err -} - func (c *ClientNodeAdapter) GetChainHead(ctx context.Context) (shared.TipSetToken, abi.ChainEpoch, error) { head, err := c.ChainHead(ctx) if err != nil { diff --git a/node/builder.go b/node/builder.go index c37a5db58..734726116 100644 --- a/node/builder.go +++ b/node/builder.go @@ -20,8 +20,9 @@ import ( "go.uber.org/fx" "golang.org/x/xerrors" + "github.com/filecoin-project/go-fil-markets/discovery" + discoveryimpl "github.com/filecoin-project/go-fil-markets/discovery/impl" "github.com/filecoin-project/go-fil-markets/retrievalmarket" - "github.com/filecoin-project/go-fil-markets/retrievalmarket/discovery" "github.com/filecoin-project/go-fil-markets/storagemarket" "github.com/filecoin-project/go-fil-markets/storagemarket/impl/storedask" @@ -290,8 +291,8 @@ func Online() Option { Override(RunPeerMgrKey, modules.RunPeerMgr), Override(HandleIncomingBlocksKey, modules.HandleIncomingBlocks), - Override(new(*discovery.Local), modules.NewLocalDiscovery), - Override(new(retrievalmarket.PeerResolver), modules.RetrievalResolver), + Override(new(*discoveryimpl.Local), modules.NewLocalDiscovery), + Override(new(discovery.PeerResolver), modules.RetrievalResolver), Override(new(retrievalmarket.RetrievalClient), modules.RetrievalClient), Override(new(dtypes.ClientDatastore), modules.NewClientDatastore), diff --git a/node/impl/client/client.go b/node/impl/client/client.go index 81978af16..7cb087ec7 100644 --- a/node/impl/client/client.go +++ b/node/impl/client/client.go @@ -33,6 +33,7 @@ import ( "go.uber.org/fx" "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-fil-markets/discovery" "github.com/filecoin-project/go-fil-markets/pieceio" "github.com/filecoin-project/go-fil-markets/retrievalmarket" rm "github.com/filecoin-project/go-fil-markets/retrievalmarket" @@ -70,7 +71,7 @@ type API struct { paych.PaychAPI SMDealClient storagemarket.StorageClient - RetDiscovery rm.PeerResolver + RetDiscovery discovery.PeerResolver Retrieval rm.RetrievalClient Chain *store.ChainStore @@ -614,18 +615,18 @@ func (a *API) clientRetrieve(ctx context.Context, order api.RetrievalOrder, ref return } -func (a *API) ClientQueryAsk(ctx context.Context, p peer.ID, miner address.Address) (*storagemarket.SignedStorageAsk, error) { +func (a *API) ClientQueryAsk(ctx context.Context, p peer.ID, miner address.Address) (*storagemarket.StorageAsk, error) { mi, err := a.StateMinerInfo(ctx, miner, types.EmptyTSK) if err != nil { return nil, xerrors.Errorf("failed getting miner info: %w", err) } info := utils.NewStorageProviderInfo(miner, mi.Worker, mi.SectorSize, p, mi.Multiaddrs) - signedAsk, err := a.SMDealClient.GetAsk(ctx, info) + ask, err := a.SMDealClient.GetAsk(ctx, info) if err != nil { return nil, err } - return signedAsk, nil + return ask, nil } func (a *API) ClientCalcCommP(ctx context.Context, inpath string) (*api.CommPRet, error) { diff --git a/node/modules/client.go b/node/modules/client.go index 6aa3cbb0e..6972ca36e 100644 --- a/node/modules/client.go +++ b/node/modules/client.go @@ -12,8 +12,9 @@ import ( dtimpl "github.com/filecoin-project/go-data-transfer/impl" dtnet "github.com/filecoin-project/go-data-transfer/network" dtgstransport "github.com/filecoin-project/go-data-transfer/transport/graphsync" + "github.com/filecoin-project/go-fil-markets/discovery" + discoveryimpl "github.com/filecoin-project/go-fil-markets/discovery/impl" "github.com/filecoin-project/go-fil-markets/retrievalmarket" - "github.com/filecoin-project/go-fil-markets/retrievalmarket/discovery" retrievalimpl "github.com/filecoin-project/go-fil-markets/retrievalmarket/impl" rmnet "github.com/filecoin-project/go-fil-markets/retrievalmarket/network" "github.com/filecoin-project/go-fil-markets/storagemarket" @@ -112,12 +113,13 @@ func NewClientDealFunds(ds dtypes.MetadataDS) (ClientDealFunds, error) { return funds.NewDealFunds(ds, datastore.NewKey("/marketfunds/client")) } -func StorageClient(lc fx.Lifecycle, h host.Host, ibs dtypes.ClientBlockstore, mds dtypes.ClientMultiDstore, r repo.LockedRepo, dataTransfer dtypes.ClientDataTransfer, discovery *discovery.Local, deals dtypes.ClientDatastore, scn storagemarket.StorageClientNode, dealFunds ClientDealFunds) (storagemarket.StorageClient, error) { +func StorageClient(lc fx.Lifecycle, h host.Host, ibs dtypes.ClientBlockstore, mds dtypes.ClientMultiDstore, r repo.LockedRepo, dataTransfer dtypes.ClientDataTransfer, discovery *discoveryimpl.Local, deals dtypes.ClientDatastore, scn storagemarket.StorageClientNode, dealFunds ClientDealFunds) (storagemarket.StorageClient, error) { net := smnet.NewFromLibp2pHost(h) c, err := storageimpl.NewClient(net, ibs, mds, dataTransfer, discovery, deals, scn, dealFunds, storageimpl.DealPollingInterval(time.Second)) if err != nil { return nil, err } + c.OnReady(marketevents.ReadyLogger("storage client")) lc.Append(fx.Hook{ OnStart: func(ctx context.Context) error { c.SubscribeToEvents(marketevents.StorageClientLogger) @@ -135,7 +137,7 @@ func StorageClient(lc fx.Lifecycle, h host.Host, ibs dtypes.ClientBlockstore, md } // RetrievalClient creates a new retrieval client attached to the client blockstore -func RetrievalClient(lc fx.Lifecycle, h host.Host, mds dtypes.ClientMultiDstore, dt dtypes.ClientDataTransfer, payAPI payapi.PaychAPI, resolver retrievalmarket.PeerResolver, ds dtypes.MetadataDS, chainAPI full.ChainAPI, stateAPI full.StateAPI) (retrievalmarket.RetrievalClient, error) { +func RetrievalClient(lc fx.Lifecycle, h host.Host, mds dtypes.ClientMultiDstore, dt dtypes.ClientDataTransfer, payAPI payapi.PaychAPI, resolver discovery.PeerResolver, ds dtypes.MetadataDS, chainAPI full.ChainAPI, stateAPI full.StateAPI) (retrievalmarket.RetrievalClient, error) { adapter := retrievaladapter.NewRetrievalClientNode(payAPI, chainAPI, stateAPI) network := rmnet.NewFromLibp2pHost(h) sc := storedcounter.New(ds, datastore.NewKey("/retr")) @@ -143,6 +145,7 @@ func RetrievalClient(lc fx.Lifecycle, h host.Host, mds dtypes.ClientMultiDstore, if err != nil { return nil, err } + client.OnReady(marketevents.ReadyLogger("retrieval client")) lc.Append(fx.Hook{ OnStart: func(ctx context.Context) error { client.SubscribeToEvents(marketevents.RetrievalClientLogger) @@ -150,7 +153,7 @@ func RetrievalClient(lc fx.Lifecycle, h host.Host, mds dtypes.ClientMultiDstore, evtType := journal.J.RegisterEventType("markets/retrieval/client", "state_change") client.SubscribeToEvents(markets.RetrievalClientJournaler(evtType)) - return nil + return client.Start(ctx) }, }) return client, nil diff --git a/node/modules/services.go b/node/modules/services.go index 7bef434be..4ee0abacc 100644 --- a/node/modules/services.go +++ b/node/modules/services.go @@ -13,8 +13,9 @@ import ( "go.uber.org/fx" "golang.org/x/xerrors" - "github.com/filecoin-project/go-fil-markets/retrievalmarket" - "github.com/filecoin-project/go-fil-markets/retrievalmarket/discovery" + "github.com/filecoin-project/go-fil-markets/discovery" + discoveryimpl "github.com/filecoin-project/go-fil-markets/discovery/impl" + "github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain" "github.com/filecoin-project/lotus/chain/beacon" @@ -26,6 +27,7 @@ import ( "github.com/filecoin-project/lotus/chain/sub" "github.com/filecoin-project/lotus/journal" "github.com/filecoin-project/lotus/lib/peermgr" + marketevents "github.com/filecoin-project/lotus/markets/loggers" "github.com/filecoin-project/lotus/node/hello" "github.com/filecoin-project/lotus/node/modules/dtypes" "github.com/filecoin-project/lotus/node/modules/helpers" @@ -117,12 +119,22 @@ func HandleIncomingMessages(mctx helpers.MetricsCtx, lc fx.Lifecycle, ps *pubsub go sub.HandleIncomingMessages(ctx, mpool, msgsub) } -func NewLocalDiscovery(ds dtypes.MetadataDS) *discovery.Local { - return discovery.NewLocal(namespace.Wrap(ds, datastore.NewKey("/deals/local"))) +func NewLocalDiscovery(lc fx.Lifecycle, ds dtypes.MetadataDS) (*discoveryimpl.Local, error) { + local, err := discoveryimpl.NewLocal(namespace.Wrap(ds, datastore.NewKey("/deals/local"))) + if err != nil { + return nil, err + } + local.OnReady(marketevents.ReadyLogger("discovery")) + lc.Append(fx.Hook{ + OnStart: func(ctx context.Context) error { + return local.Start(ctx) + }, + }) + return local, nil } -func RetrievalResolver(l *discovery.Local) retrievalmarket.PeerResolver { - return discovery.Multi(l) +func RetrievalResolver(l *discoveryimpl.Local) discovery.PeerResolver { + return discoveryimpl.Multi(l) } type RandomBeaconParams struct { diff --git a/node/modules/storageminer.go b/node/modules/storageminer.go index de466b004..5eab2ec62 100644 --- a/node/modules/storageminer.go +++ b/node/modules/storageminer.go @@ -29,10 +29,11 @@ import ( dtnet "github.com/filecoin-project/go-data-transfer/network" dtgstransport "github.com/filecoin-project/go-data-transfer/transport/graphsync" piecefilestore "github.com/filecoin-project/go-fil-markets/filestore" - "github.com/filecoin-project/go-fil-markets/piecestore" + piecestoreimpl "github.com/filecoin-project/go-fil-markets/piecestore/impl" "github.com/filecoin-project/go-fil-markets/retrievalmarket" retrievalimpl "github.com/filecoin-project/go-fil-markets/retrievalmarket/impl" rmnet "github.com/filecoin-project/go-fil-markets/retrievalmarket/network" + "github.com/filecoin-project/go-fil-markets/shared" "github.com/filecoin-project/go-fil-markets/storagemarket" storageimpl "github.com/filecoin-project/go-fil-markets/storagemarket/impl" "github.com/filecoin-project/go-fil-markets/storagemarket/impl/funds" @@ -215,14 +216,16 @@ func StorageMiner(fc config.MinerFeeConfig) func(params StorageMinerParams) (*st } func HandleRetrieval(host host.Host, lc fx.Lifecycle, m retrievalmarket.RetrievalProvider) { + m.OnReady(marketevents.ReadyLogger("retrieval provider")) lc.Append(fx.Hook{ - OnStart: func(context.Context) error { + + OnStart: func(ctx context.Context) error { m.SubscribeToEvents(marketevents.RetrievalProviderLogger) evtType := journal.J.RegisterEventType("markets/retrieval/provider", "state_change") m.SubscribeToEvents(markets.RetrievalProviderJournaler(evtType)) - return m.Start() + return m.Start(ctx) }, OnStop: func(context.Context) error { return m.Stop() @@ -232,7 +235,7 @@ func HandleRetrieval(host host.Host, lc fx.Lifecycle, m retrievalmarket.Retrieva func HandleDeals(mctx helpers.MetricsCtx, lc fx.Lifecycle, host host.Host, h storagemarket.StorageProvider) { ctx := helpers.LifecycleCtx(mctx, lc) - + h.OnReady(marketevents.ReadyLogger("storage provider")) lc.Append(fx.Hook{ OnStart: func(context.Context) error { h.SubscribeToEvents(marketevents.StorageProviderLogger) @@ -274,8 +277,18 @@ func NewProviderDAGServiceDataTransfer(lc fx.Lifecycle, h host.Host, gs dtypes.S // NewProviderPieceStore creates a statestore for storing metadata about pieces // shared by the storage and retrieval providers -func NewProviderPieceStore(ds dtypes.MetadataDS) dtypes.ProviderPieceStore { - return piecestore.NewPieceStore(namespace.Wrap(ds, datastore.NewKey("/storagemarket"))) +func NewProviderPieceStore(lc fx.Lifecycle, ds dtypes.MetadataDS) (dtypes.ProviderPieceStore, error) { + ps, err := piecestoreimpl.NewPieceStore(namespace.Wrap(ds, datastore.NewKey("/storagemarket"))) + if err != nil { + return nil, err + } + ps.OnReady(marketevents.ReadyLogger("piecestore")) + lc.Append(fx.Hook{ + OnStart: func(ctx context.Context) error { + return ps.Start(ctx) + }, + }) + return ps, nil } func StagingMultiDatastore(lc fx.Lifecycle, r repo.LockedRepo) (dtypes.StagingMultiDstore, error) { @@ -370,7 +383,13 @@ func NewStorageAsk(ctx helpers.MetricsCtx, fapi lapi.FullNode, ds dtypes.Metadat return nil, err } - storedAsk, err := storedask.NewStoredAsk(namespace.Wrap(ds, datastore.NewKey("/deals/provider")), datastore.NewKey("latest-ask"), spn, address.Address(minerAddress)) + providerDs := namespace.Wrap(ds, datastore.NewKey("/deals/provider")) + // legacy this was mistake where this key was place -- so we move the legacy key if need be + err = shared.MoveKey(providerDs, "/latest-ask", "/storage-ask/latest") + if err != nil { + return nil, err + } + storedAsk, err := storedask.NewStoredAsk(namespace.Wrap(providerDs, datastore.NewKey("/storage-ask")), datastore.NewKey("latest"), spn, address.Address(minerAddress)) if err != nil { return nil, err } From 5e08d56630adae797e2f94e9279bb77ab3a7f820 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Thu, 1 Oct 2020 00:27:54 +0200 Subject: [PATCH 296/303] sched: Allow some single-thread tasks to run in parallel with PC2/C2 --- extern/sector-storage/resources.go | 116 ++++++++++++++--------- extern/sector-storage/sched_resources.go | 27 +----- 2 files changed, 75 insertions(+), 68 deletions(-) diff --git a/extern/sector-storage/resources.go b/extern/sector-storage/resources.go index 28ab47e6f..320fec71f 100644 --- a/extern/sector-storage/resources.go +++ b/extern/sector-storage/resources.go @@ -10,14 +10,38 @@ type Resources struct { MinMemory uint64 // What Must be in RAM for decent perf MaxMemory uint64 // Memory required (swap + ram) - Threads int // -1 = multithread - CanGPU bool + MaxParallelism int // -1 = multithread + CanGPU bool BaseMinMemory uint64 // What Must be in RAM for decent perf (shared between threads) } -func (r Resources) MultiThread() bool { - return r.Threads == -1 +/* + + Percent of threads to allocate to parallel tasks + + 12 * 0.92 = 11 + 16 * 0.92 = 14 + 24 * 0.92 = 22 + 32 * 0.92 = 29 + 64 * 0.92 = 58 + 128 * 0.92 = 117 + +*/ +var ParallelNum uint64 = 92 +var ParallelDenom uint64 = 100 + +// TODO: Take NUMA into account +func (r Resources) Threads(wcpus uint64) uint64 { + if r.MaxParallelism == -1 { + n := (wcpus * ParallelNum) / ParallelDenom + if n == 0 { + return wcpus + } + return n + } + + return uint64(r.MaxParallelism) } var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources{ @@ -26,7 +50,7 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 8 << 30, MinMemory: 8 << 30, - Threads: 1, + MaxParallelism: 1, BaseMinMemory: 1 << 30, }, @@ -34,7 +58,7 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 4 << 30, MinMemory: 4 << 30, - Threads: 1, + MaxParallelism: 1, BaseMinMemory: 1 << 30, }, @@ -42,7 +66,7 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 1 << 30, MinMemory: 1 << 30, - Threads: 1, + MaxParallelism: 1, BaseMinMemory: 1 << 30, }, @@ -50,7 +74,7 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 2 << 10, MinMemory: 2 << 10, - Threads: 1, + MaxParallelism: 1, BaseMinMemory: 2 << 10, }, @@ -58,7 +82,7 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 8 << 20, MinMemory: 8 << 20, - Threads: 1, + MaxParallelism: 1, BaseMinMemory: 8 << 20, }, @@ -68,7 +92,7 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 128 << 30, MinMemory: 112 << 30, - Threads: 1, + MaxParallelism: 1, BaseMinMemory: 10 << 20, }, @@ -76,7 +100,7 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 64 << 30, MinMemory: 56 << 30, - Threads: 1, + MaxParallelism: 1, BaseMinMemory: 10 << 20, }, @@ -84,7 +108,7 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 1 << 30, MinMemory: 768 << 20, - Threads: 1, + MaxParallelism: 1, BaseMinMemory: 1 << 20, }, @@ -92,7 +116,7 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 2 << 10, MinMemory: 2 << 10, - Threads: 1, + MaxParallelism: 1, BaseMinMemory: 2 << 10, }, @@ -100,7 +124,7 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 8 << 20, MinMemory: 8 << 20, - Threads: 1, + MaxParallelism: 1, BaseMinMemory: 8 << 20, }, @@ -110,8 +134,8 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 64 << 30, MinMemory: 64 << 30, - Threads: -1, - CanGPU: true, + MaxParallelism: -1, + CanGPU: true, BaseMinMemory: 60 << 30, }, @@ -119,8 +143,8 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 32 << 30, MinMemory: 32 << 30, - Threads: -1, - CanGPU: true, + MaxParallelism: -1, + CanGPU: true, BaseMinMemory: 30 << 30, }, @@ -128,7 +152,7 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 3 << 29, // 1.5G MinMemory: 1 << 30, - Threads: -1, + MaxParallelism: -1, BaseMinMemory: 1 << 30, }, @@ -136,7 +160,7 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 2 << 10, MinMemory: 2 << 10, - Threads: -1, + MaxParallelism: -1, BaseMinMemory: 2 << 10, }, @@ -144,7 +168,7 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 8 << 20, MinMemory: 8 << 20, - Threads: -1, + MaxParallelism: -1, BaseMinMemory: 8 << 20, }, @@ -154,7 +178,7 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 1 << 30, MinMemory: 1 << 30, - Threads: 0, + MaxParallelism: 0, BaseMinMemory: 1 << 30, }, @@ -162,7 +186,7 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 1 << 30, MinMemory: 1 << 30, - Threads: 0, + MaxParallelism: 0, BaseMinMemory: 1 << 30, }, @@ -170,7 +194,7 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 1 << 30, MinMemory: 1 << 30, - Threads: 0, + MaxParallelism: 0, BaseMinMemory: 1 << 30, }, @@ -178,7 +202,7 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 2 << 10, MinMemory: 2 << 10, - Threads: 0, + MaxParallelism: 0, BaseMinMemory: 2 << 10, }, @@ -186,7 +210,7 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 8 << 20, MinMemory: 8 << 20, - Threads: 0, + MaxParallelism: 0, BaseMinMemory: 8 << 20, }, @@ -196,8 +220,8 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 190 << 30, // TODO: Confirm MinMemory: 60 << 30, - Threads: -1, - CanGPU: true, + MaxParallelism: -1, + CanGPU: true, BaseMinMemory: 64 << 30, // params }, @@ -205,8 +229,8 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 150 << 30, // TODO: ~30G of this should really be BaseMaxMemory MinMemory: 30 << 30, - Threads: -1, - CanGPU: true, + MaxParallelism: -1, + CanGPU: true, BaseMinMemory: 32 << 30, // params }, @@ -214,8 +238,8 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 3 << 29, // 1.5G MinMemory: 1 << 30, - Threads: 1, // This is fine - CanGPU: true, + MaxParallelism: 1, // This is fine + CanGPU: true, BaseMinMemory: 10 << 30, }, @@ -223,8 +247,8 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 2 << 10, MinMemory: 2 << 10, - Threads: 1, - CanGPU: true, + MaxParallelism: 1, + CanGPU: true, BaseMinMemory: 2 << 10, }, @@ -232,8 +256,8 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 8 << 20, MinMemory: 8 << 20, - Threads: 1, - CanGPU: true, + MaxParallelism: 1, + CanGPU: true, BaseMinMemory: 8 << 20, }, @@ -243,8 +267,8 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 1 << 20, MinMemory: 1 << 20, - Threads: 0, - CanGPU: false, + MaxParallelism: 0, + CanGPU: false, BaseMinMemory: 0, }, @@ -252,8 +276,8 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 1 << 20, MinMemory: 1 << 20, - Threads: 0, - CanGPU: false, + MaxParallelism: 0, + CanGPU: false, BaseMinMemory: 0, }, @@ -261,8 +285,8 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 1 << 20, MinMemory: 1 << 20, - Threads: 0, - CanGPU: false, + MaxParallelism: 0, + CanGPU: false, BaseMinMemory: 0, }, @@ -270,8 +294,8 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 1 << 20, MinMemory: 1 << 20, - Threads: 0, - CanGPU: false, + MaxParallelism: 0, + CanGPU: false, BaseMinMemory: 0, }, @@ -279,8 +303,8 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources MaxMemory: 1 << 20, MinMemory: 1 << 20, - Threads: 0, - CanGPU: false, + MaxParallelism: 0, + CanGPU: false, BaseMinMemory: 0, }, diff --git a/extern/sector-storage/sched_resources.go b/extern/sector-storage/sched_resources.go index 623472a20..d6dae577b 100644 --- a/extern/sector-storage/sched_resources.go +++ b/extern/sector-storage/sched_resources.go @@ -28,12 +28,7 @@ func (a *activeResources) withResources(id WorkerID, wr storiface.WorkerResource func (a *activeResources) add(wr storiface.WorkerResources, r Resources) { a.gpuUsed = r.CanGPU - if r.MultiThread() { - a.cpuUse += wr.CPUs - } else { - a.cpuUse += uint64(r.Threads) - } - + a.cpuUse += r.Threads(wr.CPUs) a.memUsedMin += r.MinMemory a.memUsedMax += r.MaxMemory } @@ -42,12 +37,7 @@ func (a *activeResources) free(wr storiface.WorkerResources, r Resources) { if r.CanGPU { a.gpuUsed = false } - if r.MultiThread() { - a.cpuUse -= wr.CPUs - } else { - a.cpuUse -= uint64(r.Threads) - } - + a.cpuUse -= r.Threads(wr.CPUs) a.memUsedMin -= r.MinMemory a.memUsedMax -= r.MaxMemory } @@ -68,16 +58,9 @@ func (a *activeResources) canHandleRequest(needRes Resources, wid WorkerID, call return false } - if needRes.MultiThread() { - if a.cpuUse > 0 { - log.Debugf("sched: not scheduling on worker %d for %s; multicore process needs %d threads, %d in use, target %d", wid, caller, res.CPUs, a.cpuUse, res.CPUs) - return false - } - } else { - if a.cpuUse+uint64(needRes.Threads) > res.CPUs { - log.Debugf("sched: not scheduling on worker %d for %s; not enough threads, need %d, %d in use, target %d", wid, caller, needRes.Threads, a.cpuUse, res.CPUs) - return false - } + if a.cpuUse+needRes.Threads(res.CPUs) > res.CPUs { + log.Debugf("sched: not scheduling on worker %d for %s; not enough threads, need %d, %d in use, target %d", wid, caller, needRes.Threads(res.CPUs), a.cpuUse, res.CPUs) + return false } if len(res.GPUs) > 0 && needRes.CanGPU { From 1b7cdb9341c4cf6dce0c23790bb5b2beb68493dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Thu, 1 Oct 2020 00:54:34 +0200 Subject: [PATCH 297/303] Fix storage manager tests --- extern/sector-storage/sched_test.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/extern/sector-storage/sched_test.go b/extern/sector-storage/sched_test.go index c560a58f6..579a6d913 100644 --- a/extern/sector-storage/sched_test.go +++ b/extern/sector-storage/sched_test.go @@ -290,6 +290,9 @@ func TestSched(t *testing.T) { } testFunc := func(workers []workerSpec, tasks []task) func(t *testing.T) { + ParallelNum = 1 + ParallelDenom = 1 + return func(t *testing.T) { index := stores.NewIndex() From 6981f776f4b10fa7c255f86e2467e95d99f6aec9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Thu, 1 Oct 2020 00:54:53 +0200 Subject: [PATCH 298/303] Lower PC2 memory requirements --- extern/sector-storage/resources.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/extern/sector-storage/resources.go b/extern/sector-storage/resources.go index 320fec71f..6b531e82b 100644 --- a/extern/sector-storage/resources.go +++ b/extern/sector-storage/resources.go @@ -131,22 +131,22 @@ var ResourceTable = map[sealtasks.TaskType]map[abi.RegisteredSealProof]Resources }, sealtasks.TTPreCommit2: { abi.RegisteredSealProof_StackedDrg64GiBV1: Resources{ - MaxMemory: 64 << 30, - MinMemory: 64 << 30, + MaxMemory: 30 << 30, + MinMemory: 30 << 30, MaxParallelism: -1, CanGPU: true, - BaseMinMemory: 60 << 30, + BaseMinMemory: 1 << 30, }, abi.RegisteredSealProof_StackedDrg32GiBV1: Resources{ - MaxMemory: 32 << 30, - MinMemory: 32 << 30, + MaxMemory: 15 << 30, + MinMemory: 15 << 30, MaxParallelism: -1, CanGPU: true, - BaseMinMemory: 30 << 30, + BaseMinMemory: 1 << 30, }, abi.RegisteredSealProof_StackedDrg512MiBV1: Resources{ MaxMemory: 3 << 29, // 1.5G From 636810daa5e63a6ec132d78993d028a41f179276 Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Wed, 30 Sep 2020 21:30:52 -0400 Subject: [PATCH 299/303] Lotus version 0.8.1 --- CHANGELOG.md | 66 ++++++++++++++++++++++++++++++++++++++++++++++++ build/version.go | 2 +- 2 files changed, 67 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ac687675e..6de6ddc2c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,71 @@ # Lotus changelog +# 0.8.1 / 2020-09-30 + +This optional release of Lotus introduces a new version of markets which switches to CBOR-map encodings, and allows datastore migrations. The release also introduces several improvements to the mining process, a few performance optimizations, and a battery of UX additions and enhancements. + +## Changes + +#### Dependencies + +- Markets 0.7.0 with updated data stores (https://github.com/filecoin-project/lotus/pull/4089) +- Update ffi to code with blst fixes (https://github.com/filecoin-project/lotus/pull/3998) + +#### Core Lotus + +- Fix GetPower with no miner address (https://github.com/filecoin-project/lotus/pull/4049) +- Refactor: Move nonce generation out of mpool (https://github.com/filecoin-project/lotus/pull/3970) + +#### Performance + +- Implement caching syscalls for import-bench (https://github.com/filecoin-project/lotus/pull/3888) +- Fetch tipset blocks in parallel (https://github.com/filecoin-project/lotus/pull/4074) +- Optimize Tipset equals() (https://github.com/filecoin-project/lotus/pull/4056) +- Make state transition in validation async (https://github.com/filecoin-project/lotus/pull/3868) + +#### Mining + +- Add trace window post (https://github.com/filecoin-project/lotus/pull/4020) +- Use abstract types for Dont recompute post on revert (https://github.com/filecoin-project/lotus/pull/4022) +- Fix injectNulls logic in test miner (https://github.com/filecoin-project/lotus/pull/4058) +- Fix potential panic in FinalizeSector (https://github.com/filecoin-project/lotus/pull/4092) +- Don't recompute post on revert (https://github.com/filecoin-project/lotus/pull/3924) +- Fix some failed precommit handling (https://github.com/filecoin-project/lotus/pull/3445) +- Add --no-swap flag for worker (https://github.com/filecoin-project/lotus/pull/4107) +- Allow some single-thread tasks to run in parallel with PC2/C2 (https://github.com/filecoin-project/lotus/pull/4116) + +#### UX + +- Add an envvar to set address network version (https://github.com/filecoin-project/lotus/pull/4028) +- Add logging to chain export (https://github.com/filecoin-project/lotus/pull/4030) +- Add JSON output to state compute (https://github.com/filecoin-project/lotus/pull/4038) +- Wallet list CLI: Print balances/nonces (https://github.com/filecoin-project/lotus/pull/4088) +- Added an option to show or not show sector info for `lotus-miner info` (https://github.com/filecoin-project/lotus/pull/4003) +- Add a command to import an ipld object into the chainstore (https://github.com/filecoin-project/lotus/pull/3434) +- Improve the lotus-shed dealtracker (https://github.com/filecoin-project/lotus/pull/4051) +- Docs review and re-organization (https://github.com/filecoin-project/lotus/pull/3431) +- Fix wallet list (https://github.com/filecoin-project/lotus/pull/4104) +- Add an endpoint to validate whether a string is a well-formed address (https://github.com/filecoin-project/lotus/pull/4106) +- Add an option to set config path (https://github.com/filecoin-project/lotus/pull/4103) +- Add printf in TestWindowPost (https://github.com/filecoin-project/lotus/pull/4043) +- Improve miner sectors list UX (https://github.com/filecoin-project/lotus/pull/4108) + +#### Tooling + +- Move policy change to seal bench (https://github.com/filecoin-project/lotus/pull/4032) +- Add back network power to stats (https://github.com/filecoin-project/lotus/pull/4050) +- Conformance: Record and feed circulating supply (https://github.com/filecoin-project/lotus/pull/4078) +- Snapshot import progress bar, add HTTP support (https://github.com/filecoin-project/lotus/pull/4070) +- Add lotus shed util to validate a tipset (https://github.com/filecoin-project/lotus/pull/4065) +- tvx: a test vector extraction and execution tool (https://github.com/filecoin-project/lotus/pull/4064) + +#### Bootstrap + +- Add new bootstrappers (https://github.com/filecoin-project/lotus/pull/4007) +- Add Glif node to bootstrap peers (https://github.com/filecoin-project/lotus/pull/4004) +- Add one more node located in China (https://github.com/filecoin-project/lotus/pull/4041) +- Add ipfsmain bootstrapper (https://github.com/filecoin-project/lotus/pull/4067) + # 0.8.0 / 2020-09-26 This consensus-breaking release of Lotus introduces an upgrade to the network. The changes that break consensus are: diff --git a/build/version.go b/build/version.go index 77b98f008..0b317aa17 100644 --- a/build/version.go +++ b/build/version.go @@ -29,7 +29,7 @@ func buildType() string { } // BuildVersion is the local build version, set by build system -const BuildVersion = "0.8.0" +const BuildVersion = "0.8.1" func UserVersion() string { return BuildVersion + buildType() + CurrentCommit From 60d442e36a6cc6b32da3fa7541537cfee3b7b050 Mon Sep 17 00:00:00 2001 From: Aayush Rajasekaran Date: Wed, 30 Sep 2020 22:05:16 -0400 Subject: [PATCH 300/303] Slash filter shouldn't be trigerred if the same block is submitted multiple times --- chain/gen/slashfilter/slashfilter.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/chain/gen/slashfilter/slashfilter.go b/chain/gen/slashfilter/slashfilter.go index fadd3dd27..ee0435156 100644 --- a/chain/gen/slashfilter/slashfilter.go +++ b/chain/gen/slashfilter/slashfilter.go @@ -105,6 +105,10 @@ func checkFault(t ds.Datastore, key ds.Key, bh *types.BlockHeader, faultType str return err } + if other == bh.Cid() { + return nil + } + return xerrors.Errorf("produced block would trigger '%s' consensus fault; miner: %s; bh: %s, other: %s", faultType, bh.Miner, bh.Cid(), other) } From 889dd3cb3fa6e44c2e590fd1908df90db9360010 Mon Sep 17 00:00:00 2001 From: whyrusleeping Date: Thu, 1 Oct 2020 08:51:01 -0700 Subject: [PATCH 301/303] improve the UX for replacing messages --- cli/mpool.go | 65 +++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 47 insertions(+), 18 deletions(-) diff --git a/cli/mpool.go b/cli/mpool.go index 65f4ef942..a8c73b656 100644 --- a/cli/mpool.go +++ b/cli/mpool.go @@ -7,6 +7,7 @@ import ( "sort" "strconv" + cid "github.com/ipfs/go-cid" "github.com/urfave/cli/v2" "golang.org/x/xerrors" @@ -43,6 +44,10 @@ var mpoolPending = &cli.Command{ Name: "local", Usage: "print pending messages for addresses in local wallet only", }, + &cli.BoolFlag{ + Name: "cids", + Usage: "only print cids of messages in output", + }, }, Action: func(cctx *cli.Context) error { api, closer, err := GetFullNodeAPI(cctx) @@ -79,11 +84,15 @@ var mpoolPending = &cli.Command{ } } - out, err := json.MarshalIndent(msg, "", " ") - if err != nil { - return err + if cctx.Bool("cids") { + fmt.Println(msg.Cid()) + } else { + out, err := json.MarshalIndent(msg, "", " ") + if err != nil { + return err + } + fmt.Println(string(out)) } - fmt.Println(string(out)) } return nil @@ -308,21 +317,8 @@ var mpoolReplaceCmd = &cli.Command{ Usage: "Spend up to X FIL for this message (applicable for auto mode)", }, }, - ArgsUsage: "[from] [nonce]", + ArgsUsage: " | ", Action: func(cctx *cli.Context) error { - if cctx.Args().Len() < 2 { - return cli.ShowCommandHelp(cctx, cctx.Command.Name) - } - - from, err := address.NewFromString(cctx.Args().Get(0)) - if err != nil { - return err - } - - nonce, err := strconv.ParseUint(cctx.Args().Get(1), 10, 64) - if err != nil { - return err - } api, closer, err := GetFullNodeAPI(cctx) if err != nil { @@ -332,6 +328,39 @@ var mpoolReplaceCmd = &cli.Command{ ctx := ReqContext(cctx) + var from address.Address + var nonce uint64 + switch cctx.Args().Len() { + case 1: + mcid, err := cid.Decode(cctx.Args().First()) + if err != nil { + return err + } + + msg, err := api.ChainGetMessage(ctx, mcid) + if err != nil { + return fmt.Errorf("could not find referenced message: %w", err) + } + + from = msg.From + nonce = msg.Nonce + case 2: + f, err := address.NewFromString(cctx.Args().Get(0)) + if err != nil { + return err + } + + n, err := strconv.ParseUint(cctx.Args().Get(1), 10, 64) + if err != nil { + return err + } + + from = f + nonce = n + default: + return cli.ShowCommandHelp(cctx, cctx.Command.Name) + } + ts, err := api.ChainHead(ctx) if err != nil { return xerrors.Errorf("getting chain head: %w", err) From 9b4274638c55ee80a69520332325d91dceed5785 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Thu, 1 Oct 2020 20:51:36 +0200 Subject: [PATCH 302/303] pcr: fix build --- cmd/lotus-pcr/main.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/lotus-pcr/main.go b/cmd/lotus-pcr/main.go index 1545ec224..70568a17a 100644 --- a/cmd/lotus-pcr/main.go +++ b/cmd/lotus-pcr/main.go @@ -564,10 +564,10 @@ type refunderNodeApi interface { ChainGetTipSetByHeight(ctx context.Context, epoch abi.ChainEpoch, tsk types.TipSetKey) (*types.TipSet, error) ChainReadObj(context.Context, cid.Cid) ([]byte, error) StateMinerInitialPledgeCollateral(ctx context.Context, addr address.Address, precommitInfo miner.SectorPreCommitInfo, tsk types.TipSetKey) (types.BigInt, error) - StateMinerInfo(context.Context, address.Address, types.TipSetKey) (api.MinerInfo, error) + StateMinerInfo(context.Context, address.Address, types.TipSetKey) (miner.MinerInfo, error) StateSectorPreCommitInfo(ctx context.Context, addr address.Address, sector abi.SectorNumber, tsk types.TipSetKey) (miner.SectorPreCommitOnChainInfo, error) StateMinerAvailableBalance(context.Context, address.Address, types.TipSetKey) (types.BigInt, error) - StateMinerSectors(ctx context.Context, addr address.Address, filter *bitfield.BitField, filterOut bool, tsk types.TipSetKey) ([]*api.ChainSectorInfo, error) + StateMinerSectors(ctx context.Context, addr address.Address, filter *bitfield.BitField, tsk types.TipSetKey) ([]*miner.SectorOnChainInfo, error) StateMinerFaults(ctx context.Context, addr address.Address, tsk types.TipSetKey) (bitfield.BitField, error) StateListMiners(context.Context, types.TipSetKey) ([]address.Address, error) StateGetActor(ctx context.Context, actor address.Address, tsk types.TipSetKey) (*types.Actor, error) From 078044153f598e486b37c9044f52fc376e15e2cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Thu, 1 Oct 2020 21:07:39 +0200 Subject: [PATCH 303/303] pcr: Appease the linter --- cmd/lotus-pcr/main.go | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/cmd/lotus-pcr/main.go b/cmd/lotus-pcr/main.go index 70568a17a..4ce5bbb9f 100644 --- a/cmd/lotus-pcr/main.go +++ b/cmd/lotus-pcr/main.go @@ -615,6 +615,10 @@ func (r *refunder) FindMiners(ctx context.Context, tipset *types.TipSet, refunds // Look up and find all addresses associated with the miner minerInfo, err := r.api.StateMinerInfo(ctx, maddr, tipset.Key()) + if err != nil { + log.Errorw("failed", "err", err, "height", tipset.Height(), "key", tipset.Key(), "miner", maddr) + continue + } allAddresses := []address.Address{} @@ -673,7 +677,7 @@ func (r *refunder) EnsureMinerMinimums(ctx context.Context, tipset *types.TipSet return nil, err } - defer f.Close() + defer f.Close() // nolint:errcheck w = bufio.NewWriter(f) } @@ -703,6 +707,10 @@ func (r *refunder) EnsureMinerMinimums(ctx context.Context, tipset *types.TipSet // Look up and find all addresses associated with the miner minerInfo, err := r.api.StateMinerInfo(ctx, maddr, tipset.Key()) + if err != nil { + log.Errorw("failed", "err", err, "height", tipset.Height(), "key", tipset.Key(), "miner", maddr) + continue + } allAddresses := []address.Address{minerInfo.Worker, minerInfo.Owner} allAddresses = append(allAddresses, minerInfo.ControlAddresses...)