diff --git a/Makefile b/Makefile index 9488a049..5dd94d7f 100644 --- a/Makefile +++ b/Makefile @@ -35,6 +35,7 @@ gen: $(GO_BIN) run ./builtin/v15/gen/gen.go $(GO_BIN) run ./builtin/v16/gen/gen.go $(GO_BIN) run ./builtin/v17/gen/gen.go + $(GO_BIN) run ./builtin/v18/gen/gen.go .PHONY: gen lint: diff --git a/actors/version.go b/actors/version.go index 06240f24..4b4ef6f5 100644 --- a/actors/version.go +++ b/actors/version.go @@ -26,6 +26,7 @@ const ( Version15 Version = 15 Version16 Version = 16 Version17 Version = 17 + Version18 Version = 18 ) // Converts a network version into an actors adt version. @@ -65,6 +66,8 @@ func VersionForNetwork(version network.Version) (Version, error) { return Version16, nil case network.Version27: return Version17, nil + case network.Version28: + return Version18, nil default: return -1, fmt.Errorf("unsupported network version %d", version) } diff --git a/builtin/v18/account/account_state.go b/builtin/v18/account/account_state.go new file mode 100644 index 00000000..fb3d80b6 --- /dev/null +++ b/builtin/v18/account/account_state.go @@ -0,0 +1,9 @@ +package account + +import ( + addr "github.com/filecoin-project/go-address" +) + +type State struct { + Address addr.Address +} diff --git a/builtin/v18/account/account_types.go b/builtin/v18/account/account_types.go new file mode 100644 index 00000000..0a781ef3 --- /dev/null +++ b/builtin/v18/account/account_types.go @@ -0,0 +1,6 @@ +package account + +type AuthenticateMessageParams struct { + Signature []byte + Message []byte +} diff --git a/builtin/v18/account/cbor_gen.go b/builtin/v18/account/cbor_gen.go new file mode 100644 index 00000000..55e97f33 --- /dev/null +++ b/builtin/v18/account/cbor_gen.go @@ -0,0 +1,188 @@ +// Code generated by github.com/whyrusleeping/cbor-gen. DO NOT EDIT. + +package account + +import ( + "fmt" + "io" + "math" + "sort" + + cid "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" + xerrors "golang.org/x/xerrors" +) + +var _ = xerrors.Errorf +var _ = cid.Undef +var _ = math.E +var _ = sort.Sort + +var lengthBufState = []byte{129} + +func (t *State) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufState); err != nil { + return err + } + + // t.Address (address.Address) (struct) + if err := t.Address.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *State) UnmarshalCBOR(r io.Reader) (err error) { + *t = State{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Address (address.Address) (struct) + + { + + if err := t.Address.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Address: %w", err) + } + + } + return nil +} + +var lengthBufAuthenticateMessageParams = []byte{130} + +func (t *AuthenticateMessageParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufAuthenticateMessageParams); err != nil { + return err + } + + // t.Signature ([]uint8) (slice) + if len(t.Signature) > 2097152 { + return xerrors.Errorf("Byte array in field t.Signature was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.Signature))); err != nil { + return err + } + + if _, err := cw.Write(t.Signature); err != nil { + return err + } + + // t.Message ([]uint8) (slice) + if len(t.Message) > 2097152 { + return xerrors.Errorf("Byte array in field t.Message was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.Message))); err != nil { + return err + } + + if _, err := cw.Write(t.Message); err != nil { + return err + } + + return nil +} + +func (t *AuthenticateMessageParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = AuthenticateMessageParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Signature ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.Signature: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.Signature = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.Signature); err != nil { + return err + } + + // t.Message ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.Message: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.Message = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.Message); err != nil { + return err + } + + return nil +} diff --git a/builtin/v18/account/invariants.go b/builtin/v18/account/invariants.go new file mode 100644 index 00000000..9541982a --- /dev/null +++ b/builtin/v18/account/invariants.go @@ -0,0 +1,27 @@ +package account + +import ( + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/builtin" +) + +type StateSummary struct { + PubKeyAddr address.Address +} + +// Checks internal invariants of account state. +func CheckStateInvariants(st *State, idAddr address.Address) (*StateSummary, *builtin.MessageAccumulator) { + acc := &builtin.MessageAccumulator{} + accountSummary := &StateSummary{ + PubKeyAddr: st.Address, + } + + if id, err := address.IDFromAddress(idAddr); err != nil { + acc.Addf("error extracting actor ID from address: %v", err) + } else if id >= builtin.FirstNonSingletonActorId { + acc.Require(st.Address.Protocol() == address.BLS || st.Address.Protocol() == address.SECP256K1, + "actor address %v must be BLS or SECP256K1 protocol", st.Address) + } + + return accountSummary, acc +} diff --git a/builtin/v18/account/methods.go b/builtin/v18/account/methods.go new file mode 100644 index 00000000..1a727130 --- /dev/null +++ b/builtin/v18/account/methods.go @@ -0,0 +1,15 @@ +package account + +import ( + typegen "github.com/whyrusleeping/cbor-gen" + + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/builtin" +) + +var Methods = map[abi.MethodNum]builtin.MethodMeta{ + 1: builtin.NewMethodMeta("Constructor", *new(func(*address.Address) *abi.EmptyValue)), // Constructor + 2: builtin.NewMethodMeta("PubkeyAddress", *new(func(*abi.EmptyValue) *address.Address)), // PubkeyAddress + builtin.MustGenerateFRCMethodNum("AuthenticateMessage"): builtin.NewMethodMeta("AuthenticateMessage", *new(func(*AuthenticateMessageParams) *typegen.CborBool)), // AuthenticateMessage +} diff --git a/builtin/v18/check.go b/builtin/v18/check.go new file mode 100644 index 00000000..aa73ef4f --- /dev/null +++ b/builtin/v18/check.go @@ -0,0 +1,385 @@ +package v18 + +import ( + "bytes" + "fmt" + + "github.com/ipfs/go-cid" + "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/builtin" + "github.com/filecoin-project/go-state-types/builtin/v18/account" + "github.com/filecoin-project/go-state-types/builtin/v18/cron" + "github.com/filecoin-project/go-state-types/builtin/v18/datacap" + "github.com/filecoin-project/go-state-types/builtin/v18/evm" + init_ "github.com/filecoin-project/go-state-types/builtin/v18/init" + "github.com/filecoin-project/go-state-types/builtin/v18/market" + "github.com/filecoin-project/go-state-types/builtin/v18/miner" + "github.com/filecoin-project/go-state-types/builtin/v18/multisig" + "github.com/filecoin-project/go-state-types/builtin/v18/paych" + "github.com/filecoin-project/go-state-types/builtin/v18/power" + "github.com/filecoin-project/go-state-types/builtin/v18/reward" + "github.com/filecoin-project/go-state-types/builtin/v18/verifreg" + "github.com/filecoin-project/go-state-types/manifest" +) + +// Within this code, Go errors are not expected, but are often converted to messages so that execution +// can continue to find more errors rather than fail with no insight. +// Only errors thar are particularly troublesome to recover from should propagate as Go errors. +func CheckStateInvariants(tree *builtin.ActorTree, priorEpoch abi.ChainEpoch, actorCodes map[string]cid.Cid) (*builtin.MessageAccumulator, error) { + acc := &builtin.MessageAccumulator{} + totalFIl := big.Zero() + var initSummary *init_.StateSummary + var cronSummary *cron.StateSummary + var verifregSummary *verifreg.StateSummary + var datacapSummary *datacap.StateSummary + var marketSummary *market.StateSummary + var rewardSummary *reward.StateSummary + var accountSummaries []*account.StateSummary + var powerSummary *power.StateSummary + var paychSummaries []*paych.StateSummary + var multisigSummaries []*multisig.StateSummary + var delegatedAddrs []address.Address + minerSummaries := make(map[address.Address]*miner.StateSummary) + + emptyObjectCid, err := builtin.MakeEmptyState() + if err != nil { + return nil, err + } + + if err := tree.ForEachV5(func(key address.Address, actor *builtin.ActorV5) error { + acc := acc.WithPrefix("%v ", key) // Intentional shadow + if key.Protocol() != address.ID { + acc.Addf("unexpected address protocol in state tree root: %v", key) + } + totalFIl = big.Add(totalFIl, actor.Balance) + + if actor.DelegatedAddress != nil { + acc.Require(actor.DelegatedAddress.Protocol() == address.Delegated, "actor.Address %v is not a delegated address", *actor.DelegatedAddress) + if actor.DelegatedAddress.Protocol() == address.Delegated { + delegatedAddrs = append(delegatedAddrs, *actor.DelegatedAddress) + } + } + + switch actor.Code { + case actorCodes[manifest.SystemKey]: + + case actorCodes[manifest.InitKey]: + var st init_.State + if err := tree.Store.Get(tree.Store.Context(), actor.Head, &st); err != nil { + fmt.Println("init invariant error = ", err) + return err + } + summary, msgs := init_.CheckStateInvariants(&st, tree, actorCodes) + acc.WithPrefix("init: ").AddAll(msgs) + initSummary = summary + case actorCodes[manifest.CronKey]: + var st cron.State + if err := tree.Store.Get(tree.Store.Context(), actor.Head, &st); err != nil { + return err + } + summary, msgs := cron.CheckStateInvariants(&st, tree.Store) + acc.WithPrefix("cron: ").AddAll(msgs) + cronSummary = summary + case actorCodes[manifest.AccountKey]: + var st account.State + if err := tree.Store.Get(tree.Store.Context(), actor.Head, &st); err != nil { + return err + } + summary, msgs := account.CheckStateInvariants(&st, key) + acc.WithPrefix("account: ").AddAll(msgs) + accountSummaries = append(accountSummaries, summary) + case actorCodes[manifest.PowerKey]: + var st power.State + if err := tree.Store.Get(tree.Store.Context(), actor.Head, &st); err != nil { + return err + } + summary, msgs := power.CheckStateInvariants(&st, tree.Store) + acc.WithPrefix("power: ").AddAll(msgs) + powerSummary = summary + case actorCodes[manifest.MinerKey]: + var st miner.State + if err := tree.Store.Get(tree.Store.Context(), actor.Head, &st); err != nil { + return err + } + summary, msgs := miner.CheckStateInvariants(&st, tree.Store, actor.Balance) + acc.WithPrefix("miner: ").AddAll(msgs) + minerSummaries[key] = summary + case actorCodes[manifest.MarketKey]: + var st market.State + if err := tree.Store.Get(tree.Store.Context(), actor.Head, &st); err != nil { + return err + } + summary, msgs := market.CheckStateInvariants(&st, tree.Store, actor.Balance, priorEpoch) + acc.WithPrefix("market: ").AddAll(msgs) + marketSummary = summary + case actorCodes[manifest.PaychKey]: + var st paych.State + if err := tree.Store.Get(tree.Store.Context(), actor.Head, &st); err != nil { + return err + } + summary, msgs := paych.CheckStateInvariants(&st, tree.Store, actor.Balance) + acc.WithPrefix("paych: ").AddAll(msgs) + paychSummaries = append(paychSummaries, summary) + case actorCodes[manifest.MultisigKey]: + var st multisig.State + if err := tree.Store.Get(tree.Store.Context(), actor.Head, &st); err != nil { + return err + } + summary, msgs := multisig.CheckStateInvariants(&st, tree.Store) + acc.WithPrefix("multisig: ").AddAll(msgs) + multisigSummaries = append(multisigSummaries, summary) + case actorCodes[manifest.RewardKey]: + var st reward.State + if err := tree.Store.Get(tree.Store.Context(), actor.Head, &st); err != nil { + return err + } + summary, msgs := reward.CheckStateInvariants(&st, tree.Store, priorEpoch, actor.Balance) + acc.WithPrefix("reward: ").AddAll(msgs) + rewardSummary = summary + case actorCodes[manifest.VerifregKey]: + var st verifreg.State + if err := tree.Store.Get(tree.Store.Context(), actor.Head, &st); err != nil { + return err + } + summary, msgs := verifreg.CheckStateInvariants(&st, tree.Store, priorEpoch) + acc.WithPrefix("verifreg: ").AddAll(msgs) + verifregSummary = summary + case actorCodes[manifest.DatacapKey]: + var st datacap.State + if err := tree.Store.Get(tree.Store.Context(), actor.Head, &st); err != nil { + return err + } + summary, msgs := datacap.CheckStateInvariants(&st, tree.Store) + acc.WithPrefix("datacap: ").AddAll(msgs) + datacapSummary = summary + case actorCodes[manifest.EvmKey]: + var st evm.State + if err := tree.Store.Get(tree.Store.Context(), actor.Head, &st); err != nil { + return err + } + msgs := evm.CheckStateInvariants(&st, tree.Store) + acc.WithPrefix("evm: ").AddAll(msgs) + case actorCodes[manifest.PlaceholderKey]: + acc.Require(actor.Head == emptyObjectCid, "Placeholder actor head %v unequal to emptyObjectCid %v", actor.Head, emptyObjectCid) + case actorCodes[manifest.EthAccountKey]: + acc.Require(actor.Head == emptyObjectCid, "EthAccount actor head %v unequal to emptyObjectCid %v", actor.Head, emptyObjectCid) + case actorCodes[manifest.EamKey]: + acc.Require(actor.Head == emptyObjectCid, "Eam actor head %s unequal to emptyObjectCid %s", actor.Head, emptyObjectCid) + default: + return xerrors.Errorf("unexpected actor code CID %v for address %v", actor.Code, key) + } + return nil + }); err != nil { + return nil, err + } + + // Check if all delegated addresses are part of init actor + for _, addr := range delegatedAddrs { + _, found := initSummary.AddrIDs[addr] + acc.Require(found, "delegated address %v not found in init actor map", addr) + } + + // + // Perform cross-actor checks from state summaries here. + // + + CheckMinersAgainstPower(acc, minerSummaries, powerSummary) + CheckDealStatesAgainstSectors(acc, minerSummaries, marketSummary, priorEpoch) + CheckVerifregAgainstMiners(acc, verifregSummary, minerSummaries) + CheckMarketAgainstVerifreg(acc, verifregSummary, marketSummary) + CheckVerifregAgainstDatacap(acc, verifregSummary, datacapSummary) + + _ = initSummary + _ = verifregSummary + _ = cronSummary + _ = marketSummary + _ = rewardSummary + _ = datacapSummary + + if !totalFIl.Equals(builtin.TotalFilecoin) { + acc.Addf("total token balance is %v, expected %v", totalFIl, builtin.TotalFilecoin) + } + + return acc, nil +} + +func CheckMinersAgainstPower(acc *builtin.MessageAccumulator, minerSummaries map[address.Address]*miner.StateSummary, powerSummary *power.StateSummary) { + for addr, minerSummary := range minerSummaries { // nolint:nomaprange + // check claim + claim, ok := powerSummary.Claims[addr] + acc.Require(ok, "miner %v has no power claim", addr) + if ok { + claimPower := miner.NewPowerPair(claim.RawBytePower, claim.QualityAdjPower) + acc.Require(minerSummary.ActivePower.Equals(claimPower), + "miner %v computed active power %v does not match claim %v", addr, minerSummary.ActivePower, claimPower) + acc.Require(minerSummary.WindowPoStProofType == claim.WindowPoStProofType, + "miner seal proof type %d does not match claim proof type %d", minerSummary.WindowPoStProofType, claim.WindowPoStProofType) + } + + // check crons + crons, ok := powerSummary.Crons[addr] + if !ok { // with deferred and discontinued crons it is normal for a miner actor to have no cron events + continue + } + + var payload miner.CronEventPayload + var provingPeriodCron *power.MinerCronEvent + for _, event := range crons { + err := payload.UnmarshalCBOR(bytes.NewReader(event.Payload)) + acc.Require(err == nil, "miner %v registered cron at epoch %d with wrong or corrupt payload", + addr, event.Epoch) + acc.Require(payload.EventType == miner.CronEventProcessEarlyTerminations || payload.EventType == miner.CronEventProvingDeadline, + "miner %v has unexpected cron event type %v", addr, payload.EventType) + + if payload.EventType == miner.CronEventProvingDeadline { + if provingPeriodCron != nil { + acc.Require(false, "miner %v has duplicate proving period crons at epoch %d and %d", + addr, provingPeriodCron.Epoch, event.Epoch) + } + provingPeriodCron = &event + } + } + hasProvingPeriodCron := provingPeriodCron != nil + acc.Require(hasProvingPeriodCron == minerSummary.DeadlineCronActive, "miner %v has invalid DeadlineCronActive (%t) for hasProvingPeriodCron status (%t)", + addr, minerSummary.DeadlineCronActive, hasProvingPeriodCron) + + acc.Require(provingPeriodCron != nil, "miner %v has no proving period cron", addr) + } +} + +func CheckDealStatesAgainstSectors(acc *builtin.MessageAccumulator, minerSummaries map[address.Address]*miner.StateSummary, marketSummary *market.StateSummary, currEpoch abi.ChainEpoch) { + // Check that all active deals are included within a non-terminated sector. + // We cannot check that all deals referenced within a sector are in the market, because deals + // can be terminated independently of the sector in which they are included. + for dealID, deal := range marketSummary.Deals { // nolint:nomaprange + if deal.SectorStartEpoch == abi.ChainEpoch(-1) { + // deal hasn't been activated yet, make no assertions about sector state + continue + } + + minerSummary, found := minerSummaries[deal.Provider] + if !found { + acc.Addf("provider %v for deal %d not found among miners", deal.Provider, dealID) + continue + } + + sectorDeal, found := minerSummary.Deals[dealID] + if !found { + continue + } + + acc.Require(deal.SectorStartEpoch >= sectorDeal.SectorStart, + "deal state start %d does not match sector start %d for miner %v", + deal.SectorStartEpoch, sectorDeal.SectorStart, deal.Provider) + + acc.Require(deal.SectorStartEpoch <= sectorDeal.SectorExpiration, + "deal state start %d activated after sector expiration %d for miner %v", + deal.SectorStartEpoch, sectorDeal.SectorExpiration, deal.Provider) + + acc.Require(deal.LastUpdatedEpoch <= sectorDeal.SectorExpiration, + "deal state update at %d after sector expiration %d for miner %v", + deal.LastUpdatedEpoch, sectorDeal.SectorExpiration, deal.Provider) + + acc.Require(deal.SlashEpoch <= sectorDeal.SectorExpiration, + "deal state slashed at %d after sector expiration %d for miner %v", + deal.SlashEpoch, sectorDeal.SectorExpiration, deal.Provider) + + acc.Require((deal.SectorNumber == sectorDeal.SectorNumber) || (deal.SectorNumber == 0 && deal.SlashEpoch != -1) || (deal.SectorNumber == 0 && deal.EndEpoch < currEpoch), + "deal sector number %d does not match sector %d for miner %v (ds: %#v; ss %#v)", + deal.SectorNumber, sectorDeal.SectorNumber, deal.Provider, deal, sectorDeal) + } + + // HAMT[ActorID]HAMT[SectorNumber]SectorDealIDs + marketDealToSector := make(map[abi.DealID]abi.SectorID) + + for sectorID, dealIDs := range marketSummary.ProviderSectors { + + for _, dealID := range dealIDs { + + _, found := marketDealToSector[dealID] + acc.Require(!found, "deal %d found in multiple sectors", dealID) + + marketDealToSector[dealID] = sectorID + } + } +} + +func CheckVerifregAgainstDatacap(acc *builtin.MessageAccumulator, verifregSummary *verifreg.StateSummary, datacapSummary *datacap.StateSummary) { + // Check verifiers and clients are disjoint. + for verifier := range verifregSummary.Verifiers { + actorId, err := address.IDFromAddress(verifier) + acc.RequireNoError(err, "error getting actor ID: %v", err) + + _, found := datacapSummary.Balances[abi.ActorID(actorId)] + acc.Require(!found, "verifier %v is also a client", verifier) + } + + // Check verifreg token balance matches unclaimed allocations + var pendingAllocationsTotal = big.Zero() + for _, allocation := range verifregSummary.Allocations { + pendingAllocationsTotal = big.Add(pendingAllocationsTotal, big.NewIntUnsigned(uint64(allocation.Size))) + } + + pendingAllocationsTotal = big.Mul(pendingAllocationsTotal, verifreg.DataCapGranularity) + verifregId, err := address.IDFromAddress(builtin.VerifiedRegistryActorAddr) + acc.RequireNoError(err, "could not get verifreg ID from address") + verifregBalance, found := datacapSummary.Balances[abi.ActorID(verifregId)] + if !found { + verifregBalance = big.Zero() + } + + acc.Require(found, "verifreg not found in datacap actor balances map") + acc.Require(verifregBalance.Equals(pendingAllocationsTotal), "verifreg datacap balance %d does not match pending allocation size %d", verifregBalance, pendingAllocationsTotal) +} + +func CheckVerifregAgainstMiners(acc *builtin.MessageAccumulator, verifregSummary *verifreg.StateSummary, minerSummaries map[address.Address]*miner.StateSummary) { + for _, claim := range verifregSummary.Claims { + // all claims are indexed by valid providers + maddr, err := address.NewIDAddress(uint64(claim.Provider)) + acc.RequireNoError(err, "error creating ID address: %v", err) + + _, ok := minerSummaries[maddr] + acc.Require(ok, "claim provider %s is not found in miner summaries", maddr) + } +} + +func CheckMarketAgainstVerifreg(acc *builtin.MessageAccumulator, verifregSummary *verifreg.StateSummary, marketSummary *market.StateSummary) { + // all activated verified deals with claim ids reference a claim in verifreg state + // note that it is possible for claims to exist with no matching deal if the deal expires + for claimId, dealId := range marketSummary.ClaimIdToDealId { + claim, found := verifregSummary.Claims[claimId] + acc.Require(found, "claim %d not found for activated deal %d", claimId, dealId) + + info, found := marketSummary.Deals[dealId] + acc.Require(found, "internal invariant error invalid market state references missing deal %d", dealId) + + providerId, err := address.IDFromAddress(info.Provider) + acc.RequireNoError(err, "error getting ID from provider address") + acc.Require(abi.ActorID(providerId) == claim.Provider, "mismatches providers %d %d on claim %d and deal %d", providerId, claim.Provider, claimId, dealId) + + acc.Require(info.PieceCid == claim.Data, "mismatches piece cid %s %s on claim %d and deal %d", info.PieceCid, claim.Data, claimId, dealId) + } + + // all pending deal allocation ids have an associated allocation + // note that it is possible for allocations to exist that don't match any deal + // if they are created from a direct DataCap transfer + for allocationId, dealId := range marketSummary.AllocIdToDealId { + alloc, found := verifregSummary.Allocations[allocationId] + acc.Require(found, "allocation %d not found for pending deal %d", allocationId, dealId) + if !found { + continue + } + info, found := marketSummary.Deals[dealId] + acc.Require(found, "internal invariant error invalid market state references missing deal %d", dealId) + + providerId, err := address.IDFromAddress(info.Provider) + acc.RequireNoError(err, "error getting ID from provider address") + acc.Require(abi.ActorID(providerId) == alloc.Provider, "mismatched providers %d %d on alloc %d and deal %d", providerId, alloc.Provider, allocationId, dealId) + + acc.Require(info.PieceCid == alloc.Data, "mismatched piece cid %s %s on alloc %d and deal %d", info.PieceCid, alloc.Data, allocationId, dealId) + } +} diff --git a/builtin/v18/cron/cbor_gen.go b/builtin/v18/cron/cbor_gen.go new file mode 100644 index 00000000..b00c94d4 --- /dev/null +++ b/builtin/v18/cron/cbor_gen.go @@ -0,0 +1,192 @@ +// Code generated by github.com/whyrusleeping/cbor-gen. DO NOT EDIT. + +package cron + +import ( + "fmt" + "io" + "math" + "sort" + + abi "github.com/filecoin-project/go-state-types/abi" + cid "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" + xerrors "golang.org/x/xerrors" +) + +var _ = xerrors.Errorf +var _ = cid.Undef +var _ = math.E +var _ = sort.Sort + +var lengthBufState = []byte{129} + +func (t *State) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufState); err != nil { + return err + } + + // t.Entries ([]cron.Entry) (slice) + if len(t.Entries) > 8192 { + return xerrors.Errorf("Slice value in field t.Entries was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Entries))); err != nil { + return err + } + for _, v := range t.Entries { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *State) UnmarshalCBOR(r io.Reader) (err error) { + *t = State{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Entries ([]cron.Entry) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Entries: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Entries = make([]Entry, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Entries[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Entries[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufEntry = []byte{130} + +func (t *Entry) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufEntry); err != nil { + return err + } + + // t.Receiver (address.Address) (struct) + if err := t.Receiver.MarshalCBOR(cw); err != nil { + return err + } + + // t.MethodNum (abi.MethodNum) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.MethodNum)); err != nil { + return err + } + + return nil +} + +func (t *Entry) UnmarshalCBOR(r io.Reader) (err error) { + *t = Entry{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Receiver (address.Address) (struct) + + { + + if err := t.Receiver.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Receiver: %w", err) + } + + } + // t.MethodNum (abi.MethodNum) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.MethodNum = abi.MethodNum(extra) + + } + return nil +} diff --git a/builtin/v18/cron/cron_state.go b/builtin/v18/cron/cron_state.go new file mode 100644 index 00000000..9d2fb496 --- /dev/null +++ b/builtin/v18/cron/cron_state.go @@ -0,0 +1,34 @@ +package cron + +import ( + addr "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/builtin" +) + +type State struct { + Entries []Entry +} + +type Entry struct { + Receiver addr.Address // The actor to call (must be an ID-address) + MethodNum abi.MethodNum // The method number to call (must accept empty parameters) +} + +func ConstructState(entries []Entry) *State { + return &State{Entries: entries} +} + +// The default entries to install in the cron actor's state at genesis. +func BuiltInEntries() []Entry { + return []Entry{ + { + Receiver: builtin.StoragePowerActorAddr, + MethodNum: builtin.MethodsPower.CronTick, + }, + { + Receiver: builtin.StorageMarketActorAddr, + MethodNum: builtin.MethodsMarket.CronTick, + }, + } +} diff --git a/builtin/v18/cron/cron_types.go b/builtin/v18/cron/cron_types.go new file mode 100644 index 00000000..13290f88 --- /dev/null +++ b/builtin/v18/cron/cron_types.go @@ -0,0 +1,5 @@ +package cron + +type ConstructorParams struct { + Entries []Entry +} diff --git a/builtin/v18/cron/invariants.go b/builtin/v18/cron/invariants.go new file mode 100644 index 00000000..25ddc978 --- /dev/null +++ b/builtin/v18/cron/invariants.go @@ -0,0 +1,24 @@ +package cron + +import ( + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/builtin" + "github.com/filecoin-project/go-state-types/builtin/v18/util/adt" +) + +type StateSummary struct { + EntryCount int +} + +// Checks internal invariants of cron state. +func CheckStateInvariants(st *State, _ adt.Store) (*StateSummary, *builtin.MessageAccumulator) { + acc := &builtin.MessageAccumulator{} + cronSummary := &StateSummary{ + EntryCount: len(st.Entries), + } + for i, e := range st.Entries { + acc.Require(e.Receiver.Protocol() == address.ID, "entry %d receiver address %v must be ID protocol", i, e.Receiver) + acc.Require(e.MethodNum > 0, "entry %d has invalid method number %d", i, e.MethodNum) + } + return cronSummary, acc +} diff --git a/builtin/v18/cron/methods.go b/builtin/v18/cron/methods.go new file mode 100644 index 00000000..97669037 --- /dev/null +++ b/builtin/v18/cron/methods.go @@ -0,0 +1,11 @@ +package cron + +import ( + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/builtin" +) + +var Methods = map[abi.MethodNum]builtin.MethodMeta{ + 1: builtin.NewMethodMeta("Constructor", *new(func(*ConstructorParams) *abi.EmptyValue)), // Constructor + 2: builtin.NewMethodMeta("EpochTick", *new(func(*abi.EmptyValue) *abi.EmptyValue)), // EpochTick +} diff --git a/builtin/v18/datacap/cbor_gen.go b/builtin/v18/datacap/cbor_gen.go new file mode 100644 index 00000000..11e7cbb1 --- /dev/null +++ b/builtin/v18/datacap/cbor_gen.go @@ -0,0 +1,1472 @@ +// Code generated by github.com/whyrusleeping/cbor-gen. DO NOT EDIT. + +package datacap + +import ( + "fmt" + "io" + "math" + "sort" + + address "github.com/filecoin-project/go-address" + cid "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" + xerrors "golang.org/x/xerrors" +) + +var _ = xerrors.Errorf +var _ = cid.Undef +var _ = math.E +var _ = sort.Sort + +var lengthBufState = []byte{130} + +func (t *State) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufState); err != nil { + return err + } + + // t.Governor (address.Address) (struct) + if err := t.Governor.MarshalCBOR(cw); err != nil { + return err + } + + // t.Token (datacap.TokenState) (struct) + if err := t.Token.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *State) UnmarshalCBOR(r io.Reader) (err error) { + *t = State{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Governor (address.Address) (struct) + + { + + if err := t.Governor.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Governor: %w", err) + } + + } + // t.Token (datacap.TokenState) (struct) + + { + + if err := t.Token.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Token: %w", err) + } + + } + return nil +} + +var lengthBufTokenState = []byte{132} + +func (t *TokenState) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufTokenState); err != nil { + return err + } + + // t.Supply (big.Int) (struct) + if err := t.Supply.MarshalCBOR(cw); err != nil { + return err + } + + // t.Balances (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.Balances); err != nil { + return xerrors.Errorf("failed to write cid field t.Balances: %w", err) + } + + // t.Allowances (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.Allowances); err != nil { + return xerrors.Errorf("failed to write cid field t.Allowances: %w", err) + } + + // t.HamtBitWidth (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.HamtBitWidth)); err != nil { + return err + } + + return nil +} + +func (t *TokenState) UnmarshalCBOR(r io.Reader) (err error) { + *t = TokenState{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 4 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Supply (big.Int) (struct) + + { + + if err := t.Supply.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Supply: %w", err) + } + + } + // t.Balances (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.Balances: %w", err) + } + + t.Balances = c + + } + // t.Allowances (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.Allowances: %w", err) + } + + t.Allowances = c + + } + // t.HamtBitWidth (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.HamtBitWidth = uint64(extra) + + } + return nil +} + +var lengthBufMintParams = []byte{131} + +func (t *MintParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufMintParams); err != nil { + return err + } + + // t.To (address.Address) (struct) + if err := t.To.MarshalCBOR(cw); err != nil { + return err + } + + // t.Amount (big.Int) (struct) + if err := t.Amount.MarshalCBOR(cw); err != nil { + return err + } + + // t.Operators ([]address.Address) (slice) + if len(t.Operators) > 8192 { + return xerrors.Errorf("Slice value in field t.Operators was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Operators))); err != nil { + return err + } + for _, v := range t.Operators { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *MintParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = MintParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.To (address.Address) (struct) + + { + + if err := t.To.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.To: %w", err) + } + + } + // t.Amount (big.Int) (struct) + + { + + if err := t.Amount.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Amount: %w", err) + } + + } + // t.Operators ([]address.Address) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Operators: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Operators = make([]address.Address, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Operators[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Operators[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufMintReturn = []byte{131} + +func (t *MintReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufMintReturn); err != nil { + return err + } + + // t.Balance (big.Int) (struct) + if err := t.Balance.MarshalCBOR(cw); err != nil { + return err + } + + // t.Supply (big.Int) (struct) + if err := t.Supply.MarshalCBOR(cw); err != nil { + return err + } + + // t.RecipientData ([]uint8) (slice) + if len(t.RecipientData) > 2097152 { + return xerrors.Errorf("Byte array in field t.RecipientData was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.RecipientData))); err != nil { + return err + } + + if _, err := cw.Write(t.RecipientData); err != nil { + return err + } + + return nil +} + +func (t *MintReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = MintReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.Balance (big.Int) (struct) + + { + + if err := t.Balance.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Balance: %w", err) + } + + } + // t.Supply (big.Int) (struct) + + { + + if err := t.Supply.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Supply: %w", err) + } + + } + // t.RecipientData ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.RecipientData: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.RecipientData = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.RecipientData); err != nil { + return err + } + + return nil +} + +var lengthBufDestroyParams = []byte{130} + +func (t *DestroyParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufDestroyParams); err != nil { + return err + } + + // t.Owner (address.Address) (struct) + if err := t.Owner.MarshalCBOR(cw); err != nil { + return err + } + + // t.Amount (big.Int) (struct) + if err := t.Amount.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *DestroyParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = DestroyParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Owner (address.Address) (struct) + + { + + if err := t.Owner.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Owner: %w", err) + } + + } + // t.Amount (big.Int) (struct) + + { + + if err := t.Amount.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Amount: %w", err) + } + + } + return nil +} + +var lengthBufTransferParams = []byte{131} + +func (t *TransferParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufTransferParams); err != nil { + return err + } + + // t.To (address.Address) (struct) + if err := t.To.MarshalCBOR(cw); err != nil { + return err + } + + // t.Amount (big.Int) (struct) + if err := t.Amount.MarshalCBOR(cw); err != nil { + return err + } + + // t.OperatorData ([]uint8) (slice) + if len(t.OperatorData) > 2097152 { + return xerrors.Errorf("Byte array in field t.OperatorData was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.OperatorData))); err != nil { + return err + } + + if _, err := cw.Write(t.OperatorData); err != nil { + return err + } + + return nil +} + +func (t *TransferParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = TransferParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.To (address.Address) (struct) + + { + + if err := t.To.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.To: %w", err) + } + + } + // t.Amount (big.Int) (struct) + + { + + if err := t.Amount.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Amount: %w", err) + } + + } + // t.OperatorData ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.OperatorData: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.OperatorData = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.OperatorData); err != nil { + return err + } + + return nil +} + +var lengthBufTransferReturn = []byte{131} + +func (t *TransferReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufTransferReturn); err != nil { + return err + } + + // t.FromBalance (big.Int) (struct) + if err := t.FromBalance.MarshalCBOR(cw); err != nil { + return err + } + + // t.ToBalance (big.Int) (struct) + if err := t.ToBalance.MarshalCBOR(cw); err != nil { + return err + } + + // t.RecipientData ([]uint8) (slice) + if len(t.RecipientData) > 2097152 { + return xerrors.Errorf("Byte array in field t.RecipientData was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.RecipientData))); err != nil { + return err + } + + if _, err := cw.Write(t.RecipientData); err != nil { + return err + } + + return nil +} + +func (t *TransferReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = TransferReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.FromBalance (big.Int) (struct) + + { + + if err := t.FromBalance.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.FromBalance: %w", err) + } + + } + // t.ToBalance (big.Int) (struct) + + { + + if err := t.ToBalance.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ToBalance: %w", err) + } + + } + // t.RecipientData ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.RecipientData: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.RecipientData = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.RecipientData); err != nil { + return err + } + + return nil +} + +var lengthBufTransferFromParams = []byte{132} + +func (t *TransferFromParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufTransferFromParams); err != nil { + return err + } + + // t.From (address.Address) (struct) + if err := t.From.MarshalCBOR(cw); err != nil { + return err + } + + // t.To (address.Address) (struct) + if err := t.To.MarshalCBOR(cw); err != nil { + return err + } + + // t.Amount (big.Int) (struct) + if err := t.Amount.MarshalCBOR(cw); err != nil { + return err + } + + // t.OperatorData ([]uint8) (slice) + if len(t.OperatorData) > 2097152 { + return xerrors.Errorf("Byte array in field t.OperatorData was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.OperatorData))); err != nil { + return err + } + + if _, err := cw.Write(t.OperatorData); err != nil { + return err + } + + return nil +} + +func (t *TransferFromParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = TransferFromParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 4 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.From (address.Address) (struct) + + { + + if err := t.From.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.From: %w", err) + } + + } + // t.To (address.Address) (struct) + + { + + if err := t.To.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.To: %w", err) + } + + } + // t.Amount (big.Int) (struct) + + { + + if err := t.Amount.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Amount: %w", err) + } + + } + // t.OperatorData ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.OperatorData: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.OperatorData = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.OperatorData); err != nil { + return err + } + + return nil +} + +var lengthBufTransferFromReturn = []byte{132} + +func (t *TransferFromReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufTransferFromReturn); err != nil { + return err + } + + // t.FromBalance (big.Int) (struct) + if err := t.FromBalance.MarshalCBOR(cw); err != nil { + return err + } + + // t.ToBalance (big.Int) (struct) + if err := t.ToBalance.MarshalCBOR(cw); err != nil { + return err + } + + // t.Allowance (big.Int) (struct) + if err := t.Allowance.MarshalCBOR(cw); err != nil { + return err + } + + // t.RecipientData ([]uint8) (slice) + if len(t.RecipientData) > 2097152 { + return xerrors.Errorf("Byte array in field t.RecipientData was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.RecipientData))); err != nil { + return err + } + + if _, err := cw.Write(t.RecipientData); err != nil { + return err + } + + return nil +} + +func (t *TransferFromReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = TransferFromReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 4 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.FromBalance (big.Int) (struct) + + { + + if err := t.FromBalance.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.FromBalance: %w", err) + } + + } + // t.ToBalance (big.Int) (struct) + + { + + if err := t.ToBalance.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ToBalance: %w", err) + } + + } + // t.Allowance (big.Int) (struct) + + { + + if err := t.Allowance.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Allowance: %w", err) + } + + } + // t.RecipientData ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.RecipientData: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.RecipientData = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.RecipientData); err != nil { + return err + } + + return nil +} + +var lengthBufIncreaseAllowanceParams = []byte{130} + +func (t *IncreaseAllowanceParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufIncreaseAllowanceParams); err != nil { + return err + } + + // t.Operator (address.Address) (struct) + if err := t.Operator.MarshalCBOR(cw); err != nil { + return err + } + + // t.Increase (big.Int) (struct) + if err := t.Increase.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *IncreaseAllowanceParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = IncreaseAllowanceParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Operator (address.Address) (struct) + + { + + if err := t.Operator.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Operator: %w", err) + } + + } + // t.Increase (big.Int) (struct) + + { + + if err := t.Increase.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Increase: %w", err) + } + + } + return nil +} + +var lengthBufDecreaseAllowanceParams = []byte{130} + +func (t *DecreaseAllowanceParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufDecreaseAllowanceParams); err != nil { + return err + } + + // t.Operator (address.Address) (struct) + if err := t.Operator.MarshalCBOR(cw); err != nil { + return err + } + + // t.Decrease (big.Int) (struct) + if err := t.Decrease.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *DecreaseAllowanceParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = DecreaseAllowanceParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Operator (address.Address) (struct) + + { + + if err := t.Operator.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Operator: %w", err) + } + + } + // t.Decrease (big.Int) (struct) + + { + + if err := t.Decrease.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Decrease: %w", err) + } + + } + return nil +} + +var lengthBufRevokeAllowanceParams = []byte{129} + +func (t *RevokeAllowanceParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufRevokeAllowanceParams); err != nil { + return err + } + + // t.Operator (address.Address) (struct) + if err := t.Operator.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *RevokeAllowanceParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = RevokeAllowanceParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Operator (address.Address) (struct) + + { + + if err := t.Operator.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Operator: %w", err) + } + + } + return nil +} + +var lengthBufGetAllowanceParams = []byte{130} + +func (t *GetAllowanceParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufGetAllowanceParams); err != nil { + return err + } + + // t.Owner (address.Address) (struct) + if err := t.Owner.MarshalCBOR(cw); err != nil { + return err + } + + // t.Operator (address.Address) (struct) + if err := t.Operator.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *GetAllowanceParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = GetAllowanceParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Owner (address.Address) (struct) + + { + + if err := t.Owner.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Owner: %w", err) + } + + } + // t.Operator (address.Address) (struct) + + { + + if err := t.Operator.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Operator: %w", err) + } + + } + return nil +} + +var lengthBufBurnParams = []byte{129} + +func (t *BurnParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufBurnParams); err != nil { + return err + } + + // t.Amount (big.Int) (struct) + if err := t.Amount.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *BurnParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = BurnParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Amount (big.Int) (struct) + + { + + if err := t.Amount.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Amount: %w", err) + } + + } + return nil +} + +var lengthBufBurnReturn = []byte{129} + +func (t *BurnReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufBurnReturn); err != nil { + return err + } + + // t.Balance (big.Int) (struct) + if err := t.Balance.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *BurnReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = BurnReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Balance (big.Int) (struct) + + { + + if err := t.Balance.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Balance: %w", err) + } + + } + return nil +} + +var lengthBufBurnFromParams = []byte{130} + +func (t *BurnFromParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufBurnFromParams); err != nil { + return err + } + + // t.Owner (address.Address) (struct) + if err := t.Owner.MarshalCBOR(cw); err != nil { + return err + } + + // t.Amount (big.Int) (struct) + if err := t.Amount.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *BurnFromParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = BurnFromParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Owner (address.Address) (struct) + + { + + if err := t.Owner.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Owner: %w", err) + } + + } + // t.Amount (big.Int) (struct) + + { + + if err := t.Amount.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Amount: %w", err) + } + + } + return nil +} + +var lengthBufBurnFromReturn = []byte{130} + +func (t *BurnFromReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufBurnFromReturn); err != nil { + return err + } + + // t.Balance (big.Int) (struct) + if err := t.Balance.MarshalCBOR(cw); err != nil { + return err + } + + // t.Allowance (big.Int) (struct) + if err := t.Allowance.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *BurnFromReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = BurnFromReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Balance (big.Int) (struct) + + { + + if err := t.Balance.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Balance: %w", err) + } + + } + // t.Allowance (big.Int) (struct) + + { + + if err := t.Allowance.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Allowance: %w", err) + } + + } + return nil +} diff --git a/builtin/v18/datacap/datacap_state.go b/builtin/v18/datacap/datacap_state.go new file mode 100644 index 00000000..a0285e83 --- /dev/null +++ b/builtin/v18/datacap/datacap_state.go @@ -0,0 +1,40 @@ +package datacap + +import ( + "github.com/ipfs/go-cid" + "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/builtin/v18/util/adt" +) + +type State struct { + Governor address.Address + Token TokenState +} + +type TokenState struct { + Supply abi.TokenAmount + Balances cid.Cid // HAMT abi.ActorID[abi.TokenAmount] + Allowances cid.Cid // HAMT abi.ActorID[abi.ActorID[abi.TokenAmount]] + HamtBitWidth uint64 // uint32 in builtin-actors. uint64 here to satisfy cbor-gen +} + +func ConstructState(store adt.Store, governor address.Address, bitWidth uint64) (*State, error) { + emptyMapCid, err := adt.StoreEmptyMap(store, int(bitWidth)) + if err != nil { + return nil, xerrors.Errorf("failed to create empty map: %w", err) + } + + return &State{ + Governor: governor, + Token: TokenState{ + Supply: big.Zero(), + Balances: emptyMapCid, + Allowances: emptyMapCid, + HamtBitWidth: bitWidth, + }, + }, nil +} diff --git a/builtin/v18/datacap/datacap_types.go b/builtin/v18/datacap/datacap_types.go new file mode 100644 index 00000000..a329571e --- /dev/null +++ b/builtin/v18/datacap/datacap_types.go @@ -0,0 +1,94 @@ +package datacap + +import ( + cbg "github.com/whyrusleeping/cbor-gen" + + "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/builtin" +) + +var InfiniteAllowance = big.Mul(big.MustFromString("1000000000000000000000"), builtin.TokenPrecision) + +type MintParams struct { + To address.Address + Amount abi.TokenAmount + Operators []address.Address +} + +type DestroyParams struct { + Owner address.Address + Amount abi.TokenAmount +} + +type MintReturn struct { + Balance abi.TokenAmount + Supply abi.TokenAmount + RecipientData []byte +} + +type TransferParams struct { + To address.Address + Amount abi.TokenAmount + OperatorData []byte +} + +type TransferReturn struct { + FromBalance abi.TokenAmount + ToBalance abi.TokenAmount + RecipientData []byte +} + +type TransferFromParams struct { + From address.Address + To address.Address + Amount abi.TokenAmount + OperatorData []byte +} + +type TransferFromReturn struct { + FromBalance abi.TokenAmount + ToBalance abi.TokenAmount + Allowance abi.TokenAmount + RecipientData []byte +} + +type IncreaseAllowanceParams struct { + Operator address.Address + Increase abi.TokenAmount +} + +type DecreaseAllowanceParams struct { + Operator address.Address + Decrease abi.TokenAmount +} + +type RevokeAllowanceParams struct { + Operator address.Address +} + +type GetAllowanceParams struct { + Owner address.Address + Operator address.Address +} + +type BurnParams struct { + Amount abi.TokenAmount +} + +type BurnReturn struct { + Balance abi.TokenAmount +} + +type BurnFromParams struct { + Owner address.Address + Amount abi.TokenAmount +} + +type BurnFromReturn struct { + Balance abi.TokenAmount + Allowance abi.TokenAmount +} + +type GranularityReturn = cbg.CborInt diff --git a/builtin/v18/datacap/invariants.go b/builtin/v18/datacap/invariants.go new file mode 100644 index 00000000..e9900014 --- /dev/null +++ b/builtin/v18/datacap/invariants.go @@ -0,0 +1,130 @@ +package datacap + +import ( + "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" + + addr "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/builtin" + "github.com/filecoin-project/go-state-types/builtin/v18/util/adt" +) + +type StateSummary struct { + Balances map[abi.ActorID]abi.TokenAmount + Allowances map[abi.ActorID]map[abi.ActorID]abi.TokenAmount + TotalSupply abi.TokenAmount +} + +// Checks internal invariants of verified registry state. +func CheckStateInvariants(st *State, store adt.Store) (*StateSummary, *builtin.MessageAccumulator) { + acc := &builtin.MessageAccumulator{} + acc.Require(st.Governor.Protocol() == addr.ID, "governor %v must be ID address", st.Governor) + checkTokenInvariants(store, st.Token, acc) + + // Check clients + allBalances := make(map[abi.ActorID]abi.TokenAmount) + balances, err := adt.AsMap(store, st.Token.Balances, int(st.Token.HamtBitWidth)) + acc.RequireNoError(err, "error getting balances map") + + var balance abi.StoragePower + err = balances.ForEach(&balance, func(idKey string) error { + actorId, err := abi.ParseUIntKey(idKey) + acc.RequireNoError(err, "error parsing actor id to uint") + + allBalances[abi.ActorID(actorId)] = balance.Copy() + return nil + }) + acc.RequireNoError(err, "error iterating clients") + + allAllowances := make(map[abi.ActorID]map[abi.ActorID]abi.TokenAmount) + allowancesMap, err := adt.AsMap(store, st.Token.Allowances, int(st.Token.HamtBitWidth)) + acc.RequireNoError(err, "error getting allowances outer map") + + var innerHamtCid cbg.CborCid + err = allowancesMap.ForEach(&innerHamtCid, func(idKey string) error { + owner, err := abi.ParseUIntKey(idKey) + acc.RequireNoError(err, "error parsing operator id to uint") + + allowances := make(map[abi.ActorID]abi.TokenAmount) + allowancesInnerMap, err := adt.AsMap(store, cid.Cid(innerHamtCid), int(st.Token.HamtBitWidth)) + acc.RequireNoError(err, "error getting allowances inner map") + + var amount abi.TokenAmount + err = allowancesInnerMap.ForEach(&amount, func(idKey string) error { + operator, err := abi.ParseUIntKey(idKey) + acc.RequireNoError(err, "error parsing operator id to uint") + + allowances[abi.ActorID(operator)] = amount.Copy() + return nil + }) + acc.RequireNoError(err, "error iterating over inner allowances map") + + allAllowances[abi.ActorID(owner)] = allowances + + return nil + }) + acc.RequireNoError(err, "error iterating over outer allowances map") + + return &StateSummary{ + Balances: allBalances, + Allowances: allAllowances, + TotalSupply: st.Token.Supply.Copy(), + }, acc +} + +// this can be extracted out to check any token contract when we have more than one +func checkTokenInvariants(store adt.Store, tokenState TokenState, acc *builtin.MessageAccumulator) { + acc.Require(tokenState.Supply.GreaterThanEqual(big.Zero()), "token supply %d cannot be negative", tokenState.Supply) + + // Balances + balances, err := adt.AsMap(store, tokenState.Balances, int(tokenState.HamtBitWidth)) + acc.RequireNoError(err, "error getting balances map") + + var balanceSum = big.Zero() + var balance abi.StoragePower + err = balances.ForEach(&balance, func(idKey string) error { + actorId, err := abi.ParseUIntKey(idKey) + acc.RequireNoError(err, "error parsing actor id to uint") + + acc.Require(balance.GreaterThan(big.Zero()), "balance for actor %d is not positive %d", actorId, balance) + + balanceSum = big.Add(balanceSum, balance) + + return nil + }) + acc.RequireNoError(err, "error iterating clients") + + acc.Require(balanceSum.Equals(tokenState.Supply), "token supply %d does not equal sum of all balances %d", tokenState.Supply, balanceSum) + + // Allowances + allowancesMap, err := adt.AsMap(store, tokenState.Allowances, int(tokenState.HamtBitWidth)) + acc.RequireNoError(err, "error getting allowances outer map") + + var innerHamtCid cbg.CborCid + err = allowancesMap.ForEach(&innerHamtCid, func(idKey string) error { + owner, err := abi.ParseUIntKey(idKey) + acc.RequireNoError(err, "error parsing operator id to uint") + + allowances := make(map[abi.ActorID]abi.TokenAmount) + allowancesInnerMap, err := adt.AsMap(store, cid.Cid(innerHamtCid), int(tokenState.HamtBitWidth)) + acc.RequireNoError(err, "error getting allowances inner map") + + var amount abi.TokenAmount + err = allowancesInnerMap.ForEach(&amount, func(idKey string) error { + operator, err := abi.ParseUIntKey(idKey) + acc.RequireNoError(err, "error parsing operator id to uint") + + acc.Require(owner != operator, "owner %d cannot self-store allowance", owner) + acc.Require(amount.GreaterThan(big.Zero()), "balance %d must be positive", amount) + + allowances[abi.ActorID(operator)] = amount.Copy() + return nil + }) + acc.RequireNoError(err, "error iterating over inner allowances map") + + return nil + }) + acc.RequireNoError(err, "error iterating over outer allowances map") +} diff --git a/builtin/v18/datacap/methods.go b/builtin/v18/datacap/methods.go new file mode 100644 index 00000000..a19d4b41 --- /dev/null +++ b/builtin/v18/datacap/methods.go @@ -0,0 +1,26 @@ +package datacap + +import ( + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/builtin" +) + +var Methods = map[abi.MethodNum]builtin.MethodMeta{ + 1: builtin.NewMethodMeta("Constructor", *new(func(*address.Address) *abi.EmptyValue)), // Constructor + builtin.MustGenerateFRCMethodNum("Mint"): builtin.NewMethodMeta("MintExported", *new(func(*MintParams) *MintReturn)), // MintExported + builtin.MustGenerateFRCMethodNum("Destroy"): builtin.NewMethodMeta("DestroyExported", *new(func(*DestroyParams) *BurnReturn)), // DestroyExported + builtin.MustGenerateFRCMethodNum("Name"): builtin.NewMethodMeta("NameExported", *new(func(*abi.EmptyValue) *abi.CborString)), // NameExported + builtin.MustGenerateFRCMethodNum("Symbol"): builtin.NewMethodMeta("SymbolExported", *new(func(*abi.EmptyValue) *abi.CborString)), // SymbolExported + builtin.MustGenerateFRCMethodNum("TotalSupply"): builtin.NewMethodMeta("TotalSupplyExported", *new(func(*abi.EmptyValue) *abi.TokenAmount)), // TotalSupplyExported + builtin.MustGenerateFRCMethodNum("Balance"): builtin.NewMethodMeta("BalanceExported", *new(func(*address.Address) *abi.TokenAmount)), // BalanceExported + builtin.MustGenerateFRCMethodNum("Transfer"): builtin.NewMethodMeta("TransferExported", *new(func(*TransferParams) *TransferReturn)), // TransferExported + builtin.MustGenerateFRCMethodNum("TransferFrom"): builtin.NewMethodMeta("TransferFromExported", *new(func(*TransferFromParams) *TransferFromReturn)), // TransferFromExported + builtin.MustGenerateFRCMethodNum("IncreaseAllowance"): builtin.NewMethodMeta("IncreaseAllowanceExported", *new(func(*IncreaseAllowanceParams) *abi.TokenAmount)), // IncreaseAllowanceExported + builtin.MustGenerateFRCMethodNum("DecreaseAllowance"): builtin.NewMethodMeta("DecreaseAllowanceExported", *new(func(*DecreaseAllowanceParams) *abi.TokenAmount)), // DecreaseAllowanceExported + builtin.MustGenerateFRCMethodNum("RevokeAllowance"): builtin.NewMethodMeta("RevokeAllowanceExported", *new(func(*RevokeAllowanceParams) *abi.TokenAmount)), // RevokeAllowanceExported + builtin.MustGenerateFRCMethodNum("Burn"): builtin.NewMethodMeta("BurnExported", *new(func(*BurnParams) *BurnReturn)), // BurnExported + builtin.MustGenerateFRCMethodNum("BurnFrom"): builtin.NewMethodMeta("BurnFromExported", *new(func(*BurnFromParams) *BurnFromReturn)), // BurnFromExported + builtin.MustGenerateFRCMethodNum("Allowance"): builtin.NewMethodMeta("AllowanceExported", *new(func(*GetAllowanceParams) *abi.TokenAmount)), // AllowanceExported + builtin.MustGenerateFRCMethodNum("Granularity"): builtin.NewMethodMeta("GranularityExported", *new(func(value *abi.EmptyValue) *GranularityReturn)), // GranularityExported +} diff --git a/builtin/v18/eam/cbor_gen.go b/builtin/v18/eam/cbor_gen.go new file mode 100644 index 00000000..3c4b391a --- /dev/null +++ b/builtin/v18/eam/cbor_gen.go @@ -0,0 +1,589 @@ +// Code generated by github.com/whyrusleeping/cbor-gen. DO NOT EDIT. + +package eam + +import ( + "fmt" + "io" + "math" + "sort" + + address "github.com/filecoin-project/go-address" + cid "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" + xerrors "golang.org/x/xerrors" +) + +var _ = xerrors.Errorf +var _ = cid.Undef +var _ = math.E +var _ = sort.Sort + +var lengthBufCreateParams = []byte{130} + +func (t *CreateParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufCreateParams); err != nil { + return err + } + + // t.Initcode ([]uint8) (slice) + if len(t.Initcode) > 2097152 { + return xerrors.Errorf("Byte array in field t.Initcode was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.Initcode))); err != nil { + return err + } + + if _, err := cw.Write(t.Initcode); err != nil { + return err + } + + // t.Nonce (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Nonce)); err != nil { + return err + } + + return nil +} + +func (t *CreateParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = CreateParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Initcode ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.Initcode: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.Initcode = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.Initcode); err != nil { + return err + } + + // t.Nonce (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Nonce = uint64(extra) + + } + return nil +} + +var lengthBufCreateReturn = []byte{131} + +func (t *CreateReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufCreateReturn); err != nil { + return err + } + + // t.ActorID (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.ActorID)); err != nil { + return err + } + + // t.RobustAddress (address.Address) (struct) + if err := t.RobustAddress.MarshalCBOR(cw); err != nil { + return err + } + + // t.EthAddress ([20]uint8) (array) + if len(t.EthAddress) > 2097152 { + return xerrors.Errorf("Byte array in field t.EthAddress was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.EthAddress))); err != nil { + return err + } + + if _, err := cw.Write(t.EthAddress[:]); err != nil { + return err + } + return nil +} + +func (t *CreateReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = CreateReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.ActorID (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.ActorID = uint64(extra) + + } + // t.RobustAddress (address.Address) (struct) + + { + + b, err := cr.ReadByte() + if err != nil { + return err + } + if b != cbg.CborNull[0] { + if err := cr.UnreadByte(); err != nil { + return err + } + t.RobustAddress = new(address.Address) + if err := t.RobustAddress.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.RobustAddress pointer: %w", err) + } + } + + } + // t.EthAddress ([20]uint8) (array) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.EthAddress: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + if extra != 20 { + return fmt.Errorf("expected array to have 20 elements") + } + + t.EthAddress = [20]uint8{} + if _, err := io.ReadFull(cr, t.EthAddress[:]); err != nil { + return err + } + return nil +} + +var lengthBufCreate2Params = []byte{130} + +func (t *Create2Params) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufCreate2Params); err != nil { + return err + } + + // t.Initcode ([]uint8) (slice) + if len(t.Initcode) > 2097152 { + return xerrors.Errorf("Byte array in field t.Initcode was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.Initcode))); err != nil { + return err + } + + if _, err := cw.Write(t.Initcode); err != nil { + return err + } + + // t.Salt ([32]uint8) (array) + if len(t.Salt) > 2097152 { + return xerrors.Errorf("Byte array in field t.Salt was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.Salt))); err != nil { + return err + } + + if _, err := cw.Write(t.Salt[:]); err != nil { + return err + } + return nil +} + +func (t *Create2Params) UnmarshalCBOR(r io.Reader) (err error) { + *t = Create2Params{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Initcode ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.Initcode: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.Initcode = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.Initcode); err != nil { + return err + } + + // t.Salt ([32]uint8) (array) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.Salt: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + if extra != 32 { + return fmt.Errorf("expected array to have 32 elements") + } + + t.Salt = [32]uint8{} + if _, err := io.ReadFull(cr, t.Salt[:]); err != nil { + return err + } + return nil +} + +var lengthBufCreate2Return = []byte{131} + +func (t *Create2Return) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufCreate2Return); err != nil { + return err + } + + // t.ActorID (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.ActorID)); err != nil { + return err + } + + // t.RobustAddress (address.Address) (struct) + if err := t.RobustAddress.MarshalCBOR(cw); err != nil { + return err + } + + // t.EthAddress ([20]uint8) (array) + if len(t.EthAddress) > 2097152 { + return xerrors.Errorf("Byte array in field t.EthAddress was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.EthAddress))); err != nil { + return err + } + + if _, err := cw.Write(t.EthAddress[:]); err != nil { + return err + } + return nil +} + +func (t *Create2Return) UnmarshalCBOR(r io.Reader) (err error) { + *t = Create2Return{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.ActorID (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.ActorID = uint64(extra) + + } + // t.RobustAddress (address.Address) (struct) + + { + + b, err := cr.ReadByte() + if err != nil { + return err + } + if b != cbg.CborNull[0] { + if err := cr.UnreadByte(); err != nil { + return err + } + t.RobustAddress = new(address.Address) + if err := t.RobustAddress.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.RobustAddress pointer: %w", err) + } + } + + } + // t.EthAddress ([20]uint8) (array) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.EthAddress: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + if extra != 20 { + return fmt.Errorf("expected array to have 20 elements") + } + + t.EthAddress = [20]uint8{} + if _, err := io.ReadFull(cr, t.EthAddress[:]); err != nil { + return err + } + return nil +} + +var lengthBufCreateExternalReturn = []byte{131} + +func (t *CreateExternalReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufCreateExternalReturn); err != nil { + return err + } + + // t.ActorID (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.ActorID)); err != nil { + return err + } + + // t.RobustAddress (address.Address) (struct) + if err := t.RobustAddress.MarshalCBOR(cw); err != nil { + return err + } + + // t.EthAddress ([20]uint8) (array) + if len(t.EthAddress) > 2097152 { + return xerrors.Errorf("Byte array in field t.EthAddress was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.EthAddress))); err != nil { + return err + } + + if _, err := cw.Write(t.EthAddress[:]); err != nil { + return err + } + return nil +} + +func (t *CreateExternalReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = CreateExternalReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.ActorID (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.ActorID = uint64(extra) + + } + // t.RobustAddress (address.Address) (struct) + + { + + b, err := cr.ReadByte() + if err != nil { + return err + } + if b != cbg.CborNull[0] { + if err := cr.UnreadByte(); err != nil { + return err + } + t.RobustAddress = new(address.Address) + if err := t.RobustAddress.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.RobustAddress pointer: %w", err) + } + } + + } + // t.EthAddress ([20]uint8) (array) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.EthAddress: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + if extra != 20 { + return fmt.Errorf("expected array to have 20 elements") + } + + t.EthAddress = [20]uint8{} + if _, err := io.ReadFull(cr, t.EthAddress[:]); err != nil { + return err + } + return nil +} diff --git a/builtin/v18/eam/eam_types.go b/builtin/v18/eam/eam_types.go new file mode 100644 index 00000000..e3f65100 --- /dev/null +++ b/builtin/v18/eam/eam_types.go @@ -0,0 +1,25 @@ +package eam + +import ( + "github.com/filecoin-project/go-address" +) + +type CreateParams struct { + Initcode []byte + Nonce uint64 +} + +type Create2Params struct { + Initcode []byte + Salt [32]byte +} + +type Return struct { + ActorID uint64 + RobustAddress *address.Address + EthAddress [20]byte +} + +type CreateReturn Return +type Create2Return Return +type CreateExternalReturn Return diff --git a/builtin/v18/eam/methods.go b/builtin/v18/eam/methods.go new file mode 100644 index 00000000..fb816a51 --- /dev/null +++ b/builtin/v18/eam/methods.go @@ -0,0 +1,13 @@ +package eam + +import ( + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/builtin" +) + +var Methods = map[abi.MethodNum]builtin.MethodMeta{ + 1: builtin.NewMethodMeta("Constructor", *new(func(*abi.EmptyValue) *abi.EmptyValue)), // Constructor + 2: builtin.NewMethodMeta("Create", *new(func(*CreateParams) *CreateReturn)), // Create + 3: builtin.NewMethodMeta("Create2", *new(func(*Create2Params) *Create2Return)), // Create2 + 4: builtin.NewMethodMeta("CreateExternal", *new(func(*abi.CborBytes) *CreateExternalReturn)), // CreateExternal +} diff --git a/builtin/v18/ethaccount/methods.go b/builtin/v18/ethaccount/methods.go new file mode 100644 index 00000000..0a6ba48f --- /dev/null +++ b/builtin/v18/ethaccount/methods.go @@ -0,0 +1,10 @@ +package ethaccount + +import ( + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/builtin" +) + +var Methods = map[abi.MethodNum]builtin.MethodMeta{ + 1: builtin.NewMethodMeta("Constructor", *new(func(value *abi.EmptyValue) *abi.EmptyValue)), +} diff --git a/builtin/v18/ethaccount/types.go b/builtin/v18/ethaccount/types.go new file mode 100644 index 00000000..90d09292 --- /dev/null +++ b/builtin/v18/ethaccount/types.go @@ -0,0 +1,6 @@ +package ethaccount + +type AuthenticateMessageParams struct { + Signature []byte + Message []byte +} diff --git a/builtin/v18/evm/cbor_gen.go b/builtin/v18/evm/cbor_gen.go new file mode 100644 index 00000000..adf009f1 --- /dev/null +++ b/builtin/v18/evm/cbor_gen.go @@ -0,0 +1,771 @@ +// Code generated by github.com/whyrusleeping/cbor-gen. DO NOT EDIT. + +package evm + +import ( + "fmt" + "io" + "math" + "sort" + + abi "github.com/filecoin-project/go-state-types/abi" + cid "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" + xerrors "golang.org/x/xerrors" +) + +var _ = xerrors.Errorf +var _ = cid.Undef +var _ = math.E +var _ = sort.Sort + +var lengthBufTombstone = []byte{130} + +func (t *Tombstone) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufTombstone); err != nil { + return err + } + + // t.Origin (abi.ActorID) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Origin)); err != nil { + return err + } + + // t.Nonce (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Nonce)); err != nil { + return err + } + + return nil +} + +func (t *Tombstone) UnmarshalCBOR(r io.Reader) (err error) { + *t = Tombstone{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Origin (abi.ActorID) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Origin = abi.ActorID(extra) + + } + // t.Nonce (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Nonce = uint64(extra) + + } + return nil +} + +var lengthBufTransientDataLifespan = []byte{130} + +func (t *TransientDataLifespan) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufTransientDataLifespan); err != nil { + return err + } + + // t.Origin (abi.ActorID) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Origin)); err != nil { + return err + } + + // t.Nonce (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Nonce)); err != nil { + return err + } + + return nil +} + +func (t *TransientDataLifespan) UnmarshalCBOR(r io.Reader) (err error) { + *t = TransientDataLifespan{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Origin (abi.ActorID) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Origin = abi.ActorID(extra) + + } + // t.Nonce (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Nonce = uint64(extra) + + } + return nil +} + +var lengthBufTransientData = []byte{130} + +func (t *TransientData) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufTransientData); err != nil { + return err + } + + // t.TransientDataState (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.TransientDataState); err != nil { + return xerrors.Errorf("failed to write cid field t.TransientDataState: %w", err) + } + + // t.TransientDataLifespan (evm.TransientDataLifespan) (struct) + if err := t.TransientDataLifespan.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *TransientData) UnmarshalCBOR(r io.Reader) (err error) { + *t = TransientData{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.TransientDataState (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.TransientDataState: %w", err) + } + + t.TransientDataState = c + + } + // t.TransientDataLifespan (evm.TransientDataLifespan) (struct) + + { + + if err := t.TransientDataLifespan.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.TransientDataLifespan: %w", err) + } + + } + return nil +} + +var lengthBufState = []byte{134} + +func (t *State) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufState); err != nil { + return err + } + + // t.Bytecode (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.Bytecode); err != nil { + return xerrors.Errorf("failed to write cid field t.Bytecode: %w", err) + } + + // t.BytecodeHash ([32]uint8) (array) + if len(t.BytecodeHash) > 2097152 { + return xerrors.Errorf("Byte array in field t.BytecodeHash was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.BytecodeHash))); err != nil { + return err + } + + if _, err := cw.Write(t.BytecodeHash[:]); err != nil { + return err + } + + // t.ContractState (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.ContractState); err != nil { + return xerrors.Errorf("failed to write cid field t.ContractState: %w", err) + } + + // t.TransientData (evm.TransientData) (struct) + if err := t.TransientData.MarshalCBOR(cw); err != nil { + return err + } + + // t.Nonce (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Nonce)); err != nil { + return err + } + + // t.Tombstone (evm.Tombstone) (struct) + if err := t.Tombstone.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *State) UnmarshalCBOR(r io.Reader) (err error) { + *t = State{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 6 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Bytecode (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.Bytecode: %w", err) + } + + t.Bytecode = c + + } + // t.BytecodeHash ([32]uint8) (array) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.BytecodeHash: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + if extra != 32 { + return fmt.Errorf("expected array to have 32 elements") + } + + t.BytecodeHash = [32]uint8{} + if _, err := io.ReadFull(cr, t.BytecodeHash[:]); err != nil { + return err + } + // t.ContractState (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.ContractState: %w", err) + } + + t.ContractState = c + + } + // t.TransientData (evm.TransientData) (struct) + + { + + b, err := cr.ReadByte() + if err != nil { + return err + } + if b != cbg.CborNull[0] { + if err := cr.UnreadByte(); err != nil { + return err + } + t.TransientData = new(TransientData) + if err := t.TransientData.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.TransientData pointer: %w", err) + } + } + + } + // t.Nonce (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Nonce = uint64(extra) + + } + // t.Tombstone (evm.Tombstone) (struct) + + { + + b, err := cr.ReadByte() + if err != nil { + return err + } + if b != cbg.CborNull[0] { + if err := cr.UnreadByte(); err != nil { + return err + } + t.Tombstone = new(Tombstone) + if err := t.Tombstone.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Tombstone pointer: %w", err) + } + } + + } + return nil +} + +var lengthBufConstructorParams = []byte{130} + +func (t *ConstructorParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufConstructorParams); err != nil { + return err + } + + // t.Creator ([20]uint8) (array) + if len(t.Creator) > 2097152 { + return xerrors.Errorf("Byte array in field t.Creator was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.Creator))); err != nil { + return err + } + + if _, err := cw.Write(t.Creator[:]); err != nil { + return err + } + + // t.Initcode ([]uint8) (slice) + if len(t.Initcode) > 2097152 { + return xerrors.Errorf("Byte array in field t.Initcode was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.Initcode))); err != nil { + return err + } + + if _, err := cw.Write(t.Initcode); err != nil { + return err + } + + return nil +} + +func (t *ConstructorParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = ConstructorParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Creator ([20]uint8) (array) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.Creator: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + if extra != 20 { + return fmt.Errorf("expected array to have 20 elements") + } + + t.Creator = [20]uint8{} + if _, err := io.ReadFull(cr, t.Creator[:]); err != nil { + return err + } + // t.Initcode ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.Initcode: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.Initcode = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.Initcode); err != nil { + return err + } + + return nil +} + +var lengthBufGetStorageAtParams = []byte{129} + +func (t *GetStorageAtParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufGetStorageAtParams); err != nil { + return err + } + + // t.StorageKey ([32]uint8) (array) + if len(t.StorageKey) > 2097152 { + return xerrors.Errorf("Byte array in field t.StorageKey was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.StorageKey))); err != nil { + return err + } + + if _, err := cw.Write(t.StorageKey[:]); err != nil { + return err + } + return nil +} + +func (t *GetStorageAtParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = GetStorageAtParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.StorageKey ([32]uint8) (array) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.StorageKey: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + if extra != 32 { + return fmt.Errorf("expected array to have 32 elements") + } + + t.StorageKey = [32]uint8{} + if _, err := io.ReadFull(cr, t.StorageKey[:]); err != nil { + return err + } + return nil +} + +var lengthBufDelegateCallParams = []byte{132} + +func (t *DelegateCallParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufDelegateCallParams); err != nil { + return err + } + + // t.Code (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.Code); err != nil { + return xerrors.Errorf("failed to write cid field t.Code: %w", err) + } + + // t.Input ([]uint8) (slice) + if len(t.Input) > 2097152 { + return xerrors.Errorf("Byte array in field t.Input was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.Input))); err != nil { + return err + } + + if _, err := cw.Write(t.Input); err != nil { + return err + } + + // t.Caller ([20]uint8) (array) + if len(t.Caller) > 2097152 { + return xerrors.Errorf("Byte array in field t.Caller was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.Caller))); err != nil { + return err + } + + if _, err := cw.Write(t.Caller[:]); err != nil { + return err + } + + // t.Value (big.Int) (struct) + if err := t.Value.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *DelegateCallParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = DelegateCallParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 4 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Code (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.Code: %w", err) + } + + t.Code = c + + } + // t.Input ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.Input: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.Input = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.Input); err != nil { + return err + } + + // t.Caller ([20]uint8) (array) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.Caller: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + if extra != 20 { + return fmt.Errorf("expected array to have 20 elements") + } + + t.Caller = [20]uint8{} + if _, err := io.ReadFull(cr, t.Caller[:]); err != nil { + return err + } + // t.Value (big.Int) (struct) + + { + + if err := t.Value.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Value: %w", err) + } + + } + return nil +} diff --git a/builtin/v18/evm/evm_state.go b/builtin/v18/evm/evm_state.go new file mode 100644 index 00000000..73e9b431 --- /dev/null +++ b/builtin/v18/evm/evm_state.go @@ -0,0 +1,63 @@ +package evm + +import ( + "github.com/ipfs/go-cid" + xerrors "golang.org/x/xerrors" + + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/builtin" + "github.com/filecoin-project/go-state-types/builtin/v18/util/adt" +) + +// TransientDataLifespan represents the lifespan of transient data. +// It includes an origin ActorID and a unique nonce to track the transaction. +type TransientDataLifespan struct { + Origin abi.ActorID // The origin actor ID associated with the transient data. + Nonce uint64 // A unique nonce identifying the transaction. +} + +// TransientData represents transient storage data in an EVM contract. +// It consists of a state dictionary (KAMT) and a lifespan tracker. +type TransientData struct { + TransientDataState cid.Cid // CID of the transient data state dictionary. + TransientDataLifespan TransientDataLifespan // Data representing the transient data lifespan. +} + +// Tombstone represents a marker for contracts that have been self-destructed. +type Tombstone struct { + Origin abi.ActorID // The ActorID that initiated the self-destruct. + Nonce uint64 // The transaction nonce at the time of self-destruction. +} + +// State represents the on-chain state of an EVM contract. +// It includes the contract bytecode, its hash, storage state, transient data, and nonce tracking. +type State struct { + Bytecode cid.Cid // CID of the EVM contract bytecode. + BytecodeHash [32]byte // Keccak256 hash of the contract bytecode. + ContractState cid.Cid // CID of the contract's persistent state dictionary. + TransientData *TransientData // Optional transient storage data associated with the contract. + Nonce uint64 // Tracks how many times CREATE or CREATE2 have been invoked. + Tombstone *Tombstone // Optional marker indicating if the contract has been self-destructed. +} + +// ConstructState initializes and returns a new contract state with an empty state dictionary. +// +// Parameters: +// - store: The ADT store used for state management. +// - bytecode: CID representing the contract bytecode. +// +// Returns: +// - *State: A pointer to the newly constructed State object. +// - error: An error if state initialization fails. +func ConstructState(store adt.Store, bytecode cid.Cid) (*State, error) { + emptyMapCid, err := adt.StoreEmptyMap(store, builtin.DefaultHamtBitwidth) + if err != nil { + return nil, xerrors.Errorf("failed to create empty map: %w", err) + } + + return &State{ + Bytecode: bytecode, + ContractState: emptyMapCid, + Nonce: 0, + }, nil +} diff --git a/builtin/v18/evm/evm_types.go b/builtin/v18/evm/evm_types.go new file mode 100644 index 00000000..8751e724 --- /dev/null +++ b/builtin/v18/evm/evm_types.go @@ -0,0 +1,69 @@ +package evm + +import ( + "io" + + "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" + xerrors "golang.org/x/xerrors" + + "github.com/filecoin-project/go-state-types/abi" +) + +type ConstructorParams struct { + Creator [20]byte + Initcode []byte +} + +type ResurrectParams = ConstructorParams + +type GetStorageAtParams struct { + StorageKey [32]byte +} + +type DelegateCallParams struct { + Code cid.Cid + Input []byte + Caller [20]byte + Value abi.TokenAmount +} + +type GetBytecodeReturn struct { + Cid *cid.Cid +} + +func (bc *GetBytecodeReturn) UnmarshalCBOR(r io.Reader) error { + if bc == nil { + return xerrors.Errorf("cannot unmarshal into nil pointer") + } + + br := cbg.GetPeeker(r) + + // reset fields + bc.Cid = nil + + // Check if it's null + if byte, err := br.ReadByte(); err != nil { + return err + } else if byte == cbg.CborNull[0] { + return nil + } else if err := br.UnreadByte(); err != nil { + return err + } + + c, err := cbg.ReadCid(br) + if err != nil { + return xerrors.Errorf("failed to read cid field t.OldPtr: %w", err) + } + bc.Cid = &c + return nil +} + +func (bc *GetBytecodeReturn) MarshalCBOR(w io.Writer) error { + if bc == nil || bc.Cid == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + return cbg.WriteCid(w, *bc.Cid) +} diff --git a/builtin/v18/evm/evm_types_test.go b/builtin/v18/evm/evm_types_test.go new file mode 100644 index 00000000..35ed153f --- /dev/null +++ b/builtin/v18/evm/evm_types_test.go @@ -0,0 +1,37 @@ +package evm + +import ( + "bytes" + "testing" + + "github.com/ipfs/go-cid" + "github.com/stretchr/testify/require" + cbg "github.com/whyrusleeping/cbor-gen" +) + +func TestGetBytecodeReturn(t *testing.T) { + randomCid, err := cid.Decode("bafy2bzacecu7n7wbtogznrtuuvf73dsz7wasgyneqasksdblxupnyovmtwxxu") + require.NoError(t, err) + + var cidbuf bytes.Buffer + require.NoError(t, cbg.WriteCid(&cidbuf, randomCid)) + + in := &GetBytecodeReturn{ + Cid: &randomCid, + } + var buf bytes.Buffer + require.NoError(t, in.MarshalCBOR(&buf)) + require.Equal(t, cidbuf.Bytes(), buf.Bytes()) + + var out GetBytecodeReturn + require.NoError(t, out.UnmarshalCBOR(&buf)) + require.Equal(t, &randomCid, out.Cid) + + in.Cid = nil + buf.Reset() + require.NoError(t, in.MarshalCBOR(&buf)) + require.Equal(t, cbg.CborNull, buf.Bytes()) + + require.NoError(t, out.UnmarshalCBOR(&buf)) + require.Nil(t, out.Cid) +} diff --git a/builtin/v18/evm/invariants.go b/builtin/v18/evm/invariants.go new file mode 100644 index 00000000..a9a56bda --- /dev/null +++ b/builtin/v18/evm/invariants.go @@ -0,0 +1,39 @@ +package evm + +import ( + "bytes" + + "github.com/ipfs/go-cid" + "golang.org/x/crypto/sha3" + "golang.org/x/xerrors" + + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/builtin" + "github.com/filecoin-project/go-state-types/builtin/v18/util/adt" +) + +// Checks internal invariants of evm state. +func CheckStateInvariants(st *State, store adt.Store) *builtin.MessageAccumulator { + acc := &builtin.MessageAccumulator{} + + acc.Require(st.Nonce > 0, "EVM actor state nonce needs to be greater than 0") + + byteCode, err := getBytecode(st.Bytecode, store) + acc.RequireNoError(err, "Unable to retrieve bytecode") + + hasher := sha3.NewLegacyKeccak256() + hasher.Write(byteCode) + byteCodeHash := hasher.Sum(nil) + + acc.Require(bytes.Equal(byteCodeHash, st.BytecodeHash[:]), "Bytecode hash doesn't match bytecode cid, bytecode_hash: %x hash from bytecode cid: %x", st.BytecodeHash, byteCodeHash) + + return acc +} + +func getBytecode(byteCodeCid cid.Cid, store adt.Store) ([]byte, error) { + var bytecode abi.CborBytesTransparent + if err := store.Get(store.Context(), byteCodeCid, &bytecode); err != nil { + return nil, xerrors.Errorf("failed to get bytecode %w", err) + } + return bytecode, nil +} diff --git a/builtin/v18/evm/methods.go b/builtin/v18/evm/methods.go new file mode 100644 index 00000000..f89fd5fc --- /dev/null +++ b/builtin/v18/evm/methods.go @@ -0,0 +1,16 @@ +package evm + +import ( + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/builtin" +) + +var Methods = map[abi.MethodNum]builtin.MethodMeta{ + 1: builtin.NewMethodMeta("Constructor", *new(func(*ConstructorParams) *abi.EmptyValue)), + 2: builtin.NewMethodMeta("Resurrect", *new(func(*ResurrectParams) *abi.EmptyValue)), + 3: builtin.NewMethodMeta("GetBytecode", *new(func(*abi.EmptyValue) *GetBytecodeReturn)), + 4: builtin.NewMethodMeta("GetBytecodeHash", *new(func(*abi.EmptyValue) *abi.CborBytes)), + 5: builtin.NewMethodMeta("GetStorageAt", *new(func(*GetStorageAtParams) *abi.CborBytes)), + 6: builtin.NewMethodMeta("InvokeContractDelegate", *new(func(params *DelegateCallParams) *abi.CborBytes)), + builtin.MustGenerateFRCMethodNum("InvokeEVM"): builtin.NewMethodMeta("InvokeContract", *new(func(bytes *abi.CborBytes) *abi.CborBytes)), +} diff --git a/builtin/v18/gen/gen.go b/builtin/v18/gen/gen.go new file mode 100644 index 00000000..9f8a0f92 --- /dev/null +++ b/builtin/v18/gen/gen.go @@ -0,0 +1,333 @@ +package main + +import ( + gen "github.com/whyrusleeping/cbor-gen" + + "github.com/filecoin-project/go-state-types/builtin/v18/account" + "github.com/filecoin-project/go-state-types/builtin/v18/cron" + "github.com/filecoin-project/go-state-types/builtin/v18/datacap" + "github.com/filecoin-project/go-state-types/builtin/v18/eam" + "github.com/filecoin-project/go-state-types/builtin/v18/evm" + init_ "github.com/filecoin-project/go-state-types/builtin/v18/init" + "github.com/filecoin-project/go-state-types/builtin/v18/market" + "github.com/filecoin-project/go-state-types/builtin/v18/miner" + "github.com/filecoin-project/go-state-types/builtin/v18/multisig" + "github.com/filecoin-project/go-state-types/builtin/v18/paych" + "github.com/filecoin-project/go-state-types/builtin/v18/power" + "github.com/filecoin-project/go-state-types/builtin/v18/reward" + "github.com/filecoin-project/go-state-types/builtin/v18/system" + "github.com/filecoin-project/go-state-types/builtin/v18/util/smoothing" + "github.com/filecoin-project/go-state-types/builtin/v18/verifreg" +) + +func main() { + if err := gen.WriteTupleEncodersToFile("./builtin/v18/system/cbor_gen.go", "system", + // actor state + system.State{}, + ); err != nil { + panic(err) + } + + if err := gen.WriteTupleEncodersToFile("./builtin/v18/account/cbor_gen.go", "account", + // actor state + account.State{}, + // method params and returns + account.AuthenticateMessageParams{}, + ); err != nil { + panic(err) + } + + if err := gen.WriteTupleEncodersToFile("./builtin/v18/cron/cbor_gen.go", "cron", + // actor state + cron.State{}, + cron.Entry{}, + // method params and returns + ); err != nil { + panic(err) + } + + if err := gen.WriteTupleEncodersToFile("./builtin/v18/reward/cbor_gen.go", "reward", + // actor state + reward.State{}, + // method params and returns + reward.ThisEpochRewardReturn{}, + reward.AwardBlockRewardParams{}, + ); err != nil { + panic(err) + } + + if err := gen.WriteTupleEncodersToFile("./builtin/v18/multisig/cbor_gen.go", "multisig", + // actor state + multisig.State{}, + multisig.Transaction{}, + multisig.ProposalHashData{}, + // method params and returns + multisig.ConstructorParams{}, + multisig.ProposeParams{}, + multisig.ProposeReturn{}, + multisig.AddSignerParams{}, + multisig.RemoveSignerParams{}, + multisig.TxnIDParams{}, + multisig.ApproveReturn{}, + multisig.ChangeNumApprovalsThresholdParams{}, + multisig.SwapSignerParams{}, + multisig.LockBalanceParams{}, + ); err != nil { + panic(err) + } + + if err := gen.WriteTupleEncodersToFile("./builtin/v18/paych/cbor_gen.go", "paych", + // actor state + paych.State{}, + paych.LaneState{}, + //method params and returns + paych.ConstructorParams{}, + paych.UpdateChannelStateParams{}, + paych.SignedVoucher{}, + paych.ModVerifyParams{}, + //other types + paych.Merge{}, + ); err != nil { + panic(err) + } + + if err := gen.WriteTupleEncodersToFile("./builtin/v18/power/cbor_gen.go", "power", + // actors state + power.State{}, + power.Claim{}, + // method params and returns + power.UpdateClaimedPowerParams{}, + power.MinerConstructorParams{}, + power.CreateMinerParams{}, + power.CreateMinerReturn{}, + power.CurrentTotalPowerReturn{}, + power.EnrollCronEventParams{}, + power.MinerRawPowerReturn{}, + // other types + power.CronEvent{}, + power.MinerPowerReturn{}, + ); err != nil { + panic(err) + } + + if err := gen.WriteTupleEncodersToFile("./builtin/v18/market/cbor_gen.go", "market", + // actor state + market.State{}, + market.DealState{}, + market.SectorDealIDs{}, + // method params and returns + market.WithdrawBalanceParams{}, + market.PublishStorageDealsParams{}, + market.PublishStorageDealsReturn{}, + market.BatchActivateDealsParams{}, + market.ActivateDealsResult{}, + market.VerifyDealsForActivationParams{}, + market.VerifyDealsForActivationReturn{}, + market.GetBalanceReturn{}, + market.GetDealDataCommitmentReturn{}, + market.GetDealTermReturn{}, + market.GetDealActivationReturn{}, + market.OnMinerSectorsTerminateParams{}, + market.SettleDealPaymentsReturn{}, + + // other types + market.DealProposal{}, + market.ClientDealProposal{}, + market.SectorDeals{}, + market.DealSpaces{}, + market.SectorDataSpec{}, + market.VerifiedDealInfo{}, + market.DealSettlementSummary{}, + ); err != nil { + panic(err) + } + + if err := gen.WriteTupleEncodersToFile("./builtin/v18/miner/cbor_gen.go", "miner", + // actor state + miner.State{}, + miner.MinerInfo{}, + miner.Deadlines{}, + miner.Deadline{}, + miner.Partition{}, + miner.ExpirationSet{}, + miner.PowerPair{}, + miner.SectorPreCommitOnChainInfo{}, + miner.SectorPreCommitInfo{}, + miner.SectorOnChainInfo{}, + miner.WorkerKeyChange{}, + miner.VestingFundsTail{}, + miner.VestingFunds{}, + miner.VestingFund{}, + miner.WindowedPoSt{}, + miner.ActiveBeneficiary{}, + miner.BeneficiaryTerm{}, + miner.PendingBeneficiaryChange{}, + // method params and returns + + miner.GetControlAddressesReturn{}, + miner.ChangeWorkerAddressParams{}, + miner.ChangePeerIDParams{}, + miner.SubmitWindowedPoStParams{}, + miner.PreCommitSectorParams{}, + miner.ProveCommitSectorParams{}, + miner.ExtendSectorExpirationParams{}, + miner.ExtendSectorExpiration2Params{}, + miner.TerminateSectorsParams{}, + miner.TerminateSectorsReturn{}, + miner.DeclareFaultsParams{}, + miner.DeclareFaultsRecoveredParams{}, + miner.DeferredCronEventParams{}, + miner.CheckSectorProvenParams{}, + miner.ApplyRewardParams{}, + miner.ReportConsensusFaultParams{}, + miner.WithdrawBalanceParams{}, + miner.InternalSectorSetupForPresealParams{}, + miner.ChangeMultiaddrsParams{}, + miner.CompactPartitionsParams{}, + miner.CompactSectorNumbersParams{}, + miner.DisputeWindowedPoStParams{}, + miner.PreCommitSectorBatchParams{}, + miner.ProveCommitAggregateParams{}, + miner.ProveReplicaUpdatesParams{}, + miner.CronEventPayload{}, + miner.PreCommitSectorBatchParams2{}, + miner.ProveReplicaUpdatesParams2{}, + miner.ChangeBeneficiaryParams{}, + miner.GetBeneficiaryReturn{}, + miner.GetOwnerReturn{}, + miner.GetPeerIDReturn{}, + miner.GetMultiAddrsReturn{}, + miner.ProveCommitSectors3Params{}, + miner.SectorActivationManifest{}, + miner.PieceActivationManifest{}, + miner.VerifiedAllocationKey{}, + miner.DataActivationNotification{}, + miner.ProveReplicaUpdates3Params{}, + miner.SectorUpdateManifest{}, + miner.SectorContentChangedParams{}, + miner.SectorChanges{}, + miner.PieceChange{}, + // other types + miner.FaultDeclaration{}, + miner.RecoveryDeclaration{}, + miner.ExpirationExtension{}, + miner.TerminationDeclaration{}, + miner.PoStPartition{}, + miner.ReplicaUpdate{}, + miner.ReplicaUpdate2{}, + miner.ExpirationExtension2{}, + miner.SectorClaim{}, + miner.SectorNIActivationInfo{}, + miner.ProveCommitSectorsNIParams{}, + miner.MaxTerminationFeeParams{}, + ); err != nil { + panic(err) + } + + if err := gen.WriteTupleEncodersToFile("./builtin/v18/verifreg/cbor_gen.go", "verifreg", + // actor state + verifreg.State{}, + + // method params and returns + verifreg.AddVerifierParams{}, + verifreg.AddVerifiedClientParams{}, + verifreg.UseBytesParams{}, + verifreg.RestoreBytesParams{}, + verifreg.RemoveDataCapParams{}, + verifreg.RemoveDataCapReturn{}, + verifreg.RemoveExpiredAllocationsParams{}, + verifreg.RemoveExpiredAllocationsReturn{}, + verifreg.ClaimAllocationsParams{}, + verifreg.ClaimAllocationsReturn{}, + verifreg.GetClaimsParams{}, + verifreg.GetClaimsReturn{}, + verifreg.UniversalReceiverParams{}, + verifreg.AllocationsResponse{}, + verifreg.ExtendClaimTermsParams{}, + verifreg.ExtendClaimTermsReturn{}, + verifreg.RemoveExpiredClaimsParams{}, + verifreg.RemoveExpiredClaimsReturn{}, + // other types + verifreg.RemoveDataCapRequest{}, + verifreg.RemoveDataCapProposal{}, + verifreg.RmDcProposalID{}, + verifreg.SectorAllocationClaims{}, + verifreg.AllocationClaim{}, + verifreg.Claim{}, + verifreg.ClaimTerm{}, + verifreg.ClaimExtensionRequest{}, + verifreg.Allocation{}, + verifreg.AllocationRequest{}, + verifreg.AllocationRequests{}, + ); err != nil { + panic(err) + } + + if err := gen.WriteTupleEncodersToFile("./builtin/v18/datacap/cbor_gen.go", "datacap", + // actor state + datacap.State{}, + datacap.TokenState{}, + + // method params and returns + datacap.MintParams{}, + datacap.MintReturn{}, + datacap.DestroyParams{}, + datacap.TransferParams{}, + datacap.TransferReturn{}, + datacap.TransferFromParams{}, + datacap.TransferFromReturn{}, + datacap.IncreaseAllowanceParams{}, + datacap.DecreaseAllowanceParams{}, + datacap.RevokeAllowanceParams{}, + datacap.GetAllowanceParams{}, + datacap.BurnParams{}, + datacap.BurnReturn{}, + datacap.BurnFromParams{}, + datacap.BurnFromReturn{}, + ); err != nil { + panic(err) + } + + if err := gen.WriteTupleEncodersToFile("./builtin/v18/util/smoothing/cbor_gen.go", "smoothing", + smoothing.FilterEstimate{}, + ); err != nil { + panic(err) + } + + if err := gen.WriteTupleEncodersToFile("./builtin/v18/init/cbor_gen.go", "init", + // actor state + init_.State{}, + // method params and returns + init_.ConstructorParams{}, + init_.ExecParams{}, + init_.ExecReturn{}, + init_.Exec4Params{}, + ); err != nil { + panic(err) + } + + if err := gen.WriteTupleEncodersToFile("./builtin/v18/evm/cbor_gen.go", "evm", + // actor state + evm.Tombstone{}, + evm.TransientDataLifespan{}, + evm.TransientData{}, + evm.State{}, + // method params and returns + evm.ConstructorParams{}, + evm.GetStorageAtParams{}, + evm.DelegateCallParams{}, + ); err != nil { + panic(err) + } + + if err := gen.WriteTupleEncodersToFile("./builtin/v18/eam/cbor_gen.go", "eam", + // method params and returns + eam.CreateParams{}, + eam.CreateReturn{}, + eam.Create2Params{}, + eam.Create2Return{}, + eam.CreateExternalReturn{}, + ); err != nil { + panic(err) + } +} diff --git a/builtin/v18/init/cbor_gen.go b/builtin/v18/init/cbor_gen.go new file mode 100644 index 00000000..934e614c --- /dev/null +++ b/builtin/v18/init/cbor_gen.go @@ -0,0 +1,483 @@ +// Code generated by github.com/whyrusleeping/cbor-gen. DO NOT EDIT. + +package init + +import ( + "fmt" + "io" + "math" + "sort" + + abi "github.com/filecoin-project/go-state-types/abi" + cid "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" + xerrors "golang.org/x/xerrors" +) + +var _ = xerrors.Errorf +var _ = cid.Undef +var _ = math.E +var _ = sort.Sort + +var lengthBufState = []byte{131} + +func (t *State) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufState); err != nil { + return err + } + + // t.AddressMap (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.AddressMap); err != nil { + return xerrors.Errorf("failed to write cid field t.AddressMap: %w", err) + } + + // t.NextID (abi.ActorID) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.NextID)); err != nil { + return err + } + + // t.NetworkName (string) (string) + if len(t.NetworkName) > 8192 { + return xerrors.Errorf("Value in field t.NetworkName was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajTextString, uint64(len(t.NetworkName))); err != nil { + return err + } + if _, err := cw.WriteString(string(t.NetworkName)); err != nil { + return err + } + return nil +} + +func (t *State) UnmarshalCBOR(r io.Reader) (err error) { + *t = State{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.AddressMap (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.AddressMap: %w", err) + } + + t.AddressMap = c + + } + // t.NextID (abi.ActorID) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.NextID = abi.ActorID(extra) + + } + // t.NetworkName (string) (string) + + { + sval, err := cbg.ReadStringWithMax(cr, 8192) + if err != nil { + return err + } + + t.NetworkName = string(sval) + } + return nil +} + +var lengthBufConstructorParams = []byte{129} + +func (t *ConstructorParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufConstructorParams); err != nil { + return err + } + + // t.NetworkName (string) (string) + if len(t.NetworkName) > 8192 { + return xerrors.Errorf("Value in field t.NetworkName was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajTextString, uint64(len(t.NetworkName))); err != nil { + return err + } + if _, err := cw.WriteString(string(t.NetworkName)); err != nil { + return err + } + return nil +} + +func (t *ConstructorParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = ConstructorParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.NetworkName (string) (string) + + { + sval, err := cbg.ReadStringWithMax(cr, 8192) + if err != nil { + return err + } + + t.NetworkName = string(sval) + } + return nil +} + +var lengthBufExecParams = []byte{130} + +func (t *ExecParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufExecParams); err != nil { + return err + } + + // t.CodeCID (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.CodeCID); err != nil { + return xerrors.Errorf("failed to write cid field t.CodeCID: %w", err) + } + + // t.ConstructorParams ([]uint8) (slice) + if len(t.ConstructorParams) > 2097152 { + return xerrors.Errorf("Byte array in field t.ConstructorParams was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.ConstructorParams))); err != nil { + return err + } + + if _, err := cw.Write(t.ConstructorParams); err != nil { + return err + } + + return nil +} + +func (t *ExecParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = ExecParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.CodeCID (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.CodeCID: %w", err) + } + + t.CodeCID = c + + } + // t.ConstructorParams ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.ConstructorParams: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.ConstructorParams = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.ConstructorParams); err != nil { + return err + } + + return nil +} + +var lengthBufExecReturn = []byte{130} + +func (t *ExecReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufExecReturn); err != nil { + return err + } + + // t.IDAddress (address.Address) (struct) + if err := t.IDAddress.MarshalCBOR(cw); err != nil { + return err + } + + // t.RobustAddress (address.Address) (struct) + if err := t.RobustAddress.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *ExecReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = ExecReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.IDAddress (address.Address) (struct) + + { + + if err := t.IDAddress.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.IDAddress: %w", err) + } + + } + // t.RobustAddress (address.Address) (struct) + + { + + if err := t.RobustAddress.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.RobustAddress: %w", err) + } + + } + return nil +} + +var lengthBufExec4Params = []byte{131} + +func (t *Exec4Params) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufExec4Params); err != nil { + return err + } + + // t.CodeCID (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.CodeCID); err != nil { + return xerrors.Errorf("failed to write cid field t.CodeCID: %w", err) + } + + // t.ConstructorParams ([]uint8) (slice) + if len(t.ConstructorParams) > 2097152 { + return xerrors.Errorf("Byte array in field t.ConstructorParams was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.ConstructorParams))); err != nil { + return err + } + + if _, err := cw.Write(t.ConstructorParams); err != nil { + return err + } + + // t.SubAddress ([]uint8) (slice) + if len(t.SubAddress) > 2097152 { + return xerrors.Errorf("Byte array in field t.SubAddress was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.SubAddress))); err != nil { + return err + } + + if _, err := cw.Write(t.SubAddress); err != nil { + return err + } + + return nil +} + +func (t *Exec4Params) UnmarshalCBOR(r io.Reader) (err error) { + *t = Exec4Params{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.CodeCID (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.CodeCID: %w", err) + } + + t.CodeCID = c + + } + // t.ConstructorParams ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.ConstructorParams: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.ConstructorParams = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.ConstructorParams); err != nil { + return err + } + + // t.SubAddress ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.SubAddress: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.SubAddress = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.SubAddress); err != nil { + return err + } + + return nil +} diff --git a/builtin/v18/init/init_actor_params.go b/builtin/v18/init/init_actor_params.go new file mode 100644 index 00000000..66524e97 --- /dev/null +++ b/builtin/v18/init/init_actor_params.go @@ -0,0 +1,29 @@ +package init + +import ( + "github.com/ipfs/go-cid" + + addr "github.com/filecoin-project/go-address" +) + +type ConstructorParams struct { + NetworkName string +} + +type ExecParams struct { + CodeCID cid.Cid `checked:"true"` // invalid CIDs won't get committed to the state tree + ConstructorParams []byte +} + +type ExecReturn struct { + IDAddress addr.Address // The canonical ID-based address for the actor. + RobustAddress addr.Address // A more expensive but re-org-safe address for the newly created actor. +} + +type Exec4Params struct { + CodeCID cid.Cid `checked:"true"` // invalid CIDs won't get committed to the state tree + ConstructorParams []byte + SubAddress []byte +} + +type Exec4Return = ExecReturn diff --git a/builtin/v18/init/init_actor_state.go b/builtin/v18/init/init_actor_state.go new file mode 100644 index 00000000..991a375c --- /dev/null +++ b/builtin/v18/init/init_actor_state.go @@ -0,0 +1,87 @@ +package init + +import ( + "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" + "golang.org/x/xerrors" + + addr "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/builtin" + "github.com/filecoin-project/go-state-types/builtin/v18/util/adt" +) + +type State struct { + AddressMap cid.Cid // HAMT[addr.Address]abi.ActorID + NextID abi.ActorID + NetworkName string +} + +func ConstructState(store adt.Store, networkName string) (*State, error) { + emptyAddressMapCid, err := adt.StoreEmptyMap(store, builtin.DefaultHamtBitwidth) + if err != nil { + return nil, xerrors.Errorf("failed to create empty map: %w", err) + } + + return &State{ + AddressMap: emptyAddressMapCid, + NextID: abi.ActorID(builtin.FirstNonSingletonActorId), + NetworkName: networkName, + }, nil +} + +// ResolveAddress resolves an address to an ID-address, if possible. +// If the provided address is an ID address, it is returned as-is. +// This means that mapped ID-addresses (which should only appear as values, not keys) and +// singleton actor addresses (which are not in the map) pass through unchanged. +// +// Returns an ID-address and `true` if the address was already an ID-address or was resolved in the mapping. +// Returns an undefined address and `false` if the address was not an ID-address and not found in the mapping. +// Returns an error only if state was inconsistent. +func (s *State) ResolveAddress(store adt.Store, address addr.Address) (addr.Address, bool, error) { + // Short-circuit ID address resolution. + if address.Protocol() == addr.ID { + return address, true, nil + } + + // Lookup address. + m, err := adt.AsMap(store, s.AddressMap, builtin.DefaultHamtBitwidth) + if err != nil { + return addr.Undef, false, xerrors.Errorf("failed to load address map: %w", err) + } + + var actorID cbg.CborInt + if found, err := m.Get(abi.AddrKey(address), &actorID); err != nil { + return addr.Undef, false, xerrors.Errorf("failed to get from address map: %w", err) + } else if found { + // Reconstruct address from the ActorID. + idAddr, err := addr.NewIDAddress(uint64(actorID)) + return idAddr, true, err + } else { + return addr.Undef, false, nil + } +} + +// Allocates a new ID address and stores a mapping of the argument address to it. +// Returns the newly-allocated address. +func (s *State) MapAddressToNewID(store adt.Store, address addr.Address) (addr.Address, error) { + actorID := cbg.CborInt(s.NextID) + s.NextID++ + + m, err := adt.AsMap(store, s.AddressMap, builtin.DefaultHamtBitwidth) + if err != nil { + return addr.Undef, xerrors.Errorf("failed to load address map: %w", err) + } + err = m.Put(abi.AddrKey(address), &actorID) + if err != nil { + return addr.Undef, xerrors.Errorf("map address failed to store entry: %w", err) + } + amr, err := m.Root() + if err != nil { + return addr.Undef, xerrors.Errorf("failed to get address map root: %w", err) + } + s.AddressMap = amr + + idAddr, err := addr.NewIDAddress(uint64(actorID)) + return idAddr, err +} diff --git a/builtin/v18/init/invariants.go b/builtin/v18/init/invariants.go new file mode 100644 index 00000000..6884b73e --- /dev/null +++ b/builtin/v18/init/invariants.go @@ -0,0 +1,91 @@ +package init + +import ( + "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" + + addr "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/builtin" + "github.com/filecoin-project/go-state-types/builtin/v18/util/adt" + "github.com/filecoin-project/go-state-types/manifest" +) + +type StateSummary struct { + AddrIDs map[addr.Address]abi.ActorID + NextID abi.ActorID +} + +// Checks internal invariants of init state. +func CheckStateInvariants(st *State, tree *builtin.ActorTree, actorCodes map[string]cid.Cid) (*StateSummary, *builtin.MessageAccumulator) { + acc := &builtin.MessageAccumulator{} + store := tree.Store + + acc.Require(len(st.NetworkName) > 0, "network name is empty") + acc.Require(st.NextID >= builtin.FirstNonSingletonActorId, "next id %d is too low", st.NextID) + + initSummary := &StateSummary{ + AddrIDs: nil, + NextID: st.NextID, + } + + lut, err := adt.AsMap(store, st.AddressMap, builtin.DefaultHamtBitwidth) + if err != nil { + acc.Addf("error loading address map: %v", err) + // Stop here, it's hard to make other useful checks. + return initSummary, acc + } + + initSummary.AddrIDs = map[addr.Address]abi.ActorID{} + reverse := map[abi.ActorID]addr.Address{} + var value cbg.CborInt + err = lut.ForEach(&value, func(key string) error { + actorId := abi.ActorID(value) + keyAddr, err := addr.NewFromBytes([]byte(key)) + if err != nil { + return err + } + + acc.Require(keyAddr.Protocol() != addr.ID, "key %v is an ID address", keyAddr) + acc.Require(keyAddr.Protocol() <= addr.Delegated, "unknown address protocol for key %v", keyAddr) + acc.Require(actorId >= builtin.FirstNonSingletonActorId, "unexpected singleton ID value %v", actorId) + + foundAddr, found := reverse[actorId] + isPair := (keyAddr.Protocol() == addr.Actor && foundAddr.Protocol() == addr.Delegated) || + (keyAddr.Protocol() == addr.Delegated && foundAddr.Protocol() == addr.Actor) + dup := found && !isPair + acc.Require(!dup, "duplicate mapping to ID %v: %v, %v", actorId, keyAddr, foundAddr) + reverse[actorId] = keyAddr + + initSummary.AddrIDs[keyAddr] = actorId + + idaddr, err := addr.NewIDAddress(uint64(actorId)) + acc.RequireNoError(err, "unable to convert actorId %v to id address", actorId) + actor, found, err := tree.GetActorV5(idaddr) + acc.RequireNoError(err, "unable to retrieve actor with idaddr %v", idaddr) + if !found { + return nil // this can happen if actor self destructs as init is not informed + } + if keyAddr.Protocol() == addr.Delegated { + acc.Require(canHaveDelegatedAddress(actor, actorCodes), "actor %v not supposed to have a delegated address", idaddr) + } + + // we expect the address field to be populated for the below actors + if (actor.Code == actorCodes[manifest.EthAccountKey] || + actor.Code == actorCodes[manifest.EvmKey] || + actor.Code == actorCodes[manifest.PlaceholderKey]) && + keyAddr.Protocol() != addr.Actor { + acc.Require(keyAddr == *actor.DelegatedAddress, "address field in actor state differs from addr available in init actor map: actor=%v, init=%v", *actor.DelegatedAddress, keyAddr) + } + + return nil + }) + acc.RequireNoError(err, "error iterating address map") + return initSummary, acc +} + +func canHaveDelegatedAddress(actor *builtin.ActorV5, actorCodes map[string]cid.Cid) bool { + return actor.Code == actorCodes[manifest.EthAccountKey] || + actor.Code == actorCodes[manifest.EvmKey] || + actor.Code == actorCodes[manifest.PlaceholderKey] +} diff --git a/builtin/v18/init/methods.go b/builtin/v18/init/methods.go new file mode 100644 index 00000000..eee468b8 --- /dev/null +++ b/builtin/v18/init/methods.go @@ -0,0 +1,13 @@ +package init + +import ( + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/builtin" +) + +var Methods = map[abi.MethodNum]builtin.MethodMeta{ + 1: builtin.NewMethodMeta("Constructor", *new(func(*ConstructorParams) *abi.EmptyValue)), // Constructor + 2: builtin.NewMethodMeta("Exec", *new(func(*ExecParams) *ExecReturn)), // Exec + // TODO Are we exporting Exec4 + 3: builtin.NewMethodMeta("Exec4", *new(func(*Exec4Params) *ExecReturn)), // Exec4 +} diff --git a/builtin/v18/market/cbor_gen.go b/builtin/v18/market/cbor_gen.go new file mode 100644 index 00000000..f21a337b --- /dev/null +++ b/builtin/v18/market/cbor_gen.go @@ -0,0 +1,2823 @@ +// Code generated by github.com/whyrusleeping/cbor-gen. DO NOT EDIT. + +package market + +import ( + "fmt" + "io" + "math" + "sort" + + abi "github.com/filecoin-project/go-state-types/abi" + verifreg "github.com/filecoin-project/go-state-types/builtin/v18/verifreg" + cid "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" + xerrors "golang.org/x/xerrors" +) + +var _ = xerrors.Errorf +var _ = cid.Undef +var _ = math.E +var _ = sort.Sort + +var lengthBufState = []byte{141} + +func (t *State) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufState); err != nil { + return err + } + + // t.Proposals (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.Proposals); err != nil { + return xerrors.Errorf("failed to write cid field t.Proposals: %w", err) + } + + // t.States (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.States); err != nil { + return xerrors.Errorf("failed to write cid field t.States: %w", err) + } + + // t.PendingProposals (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.PendingProposals); err != nil { + return xerrors.Errorf("failed to write cid field t.PendingProposals: %w", err) + } + + // t.EscrowTable (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.EscrowTable); err != nil { + return xerrors.Errorf("failed to write cid field t.EscrowTable: %w", err) + } + + // t.LockedTable (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.LockedTable); err != nil { + return xerrors.Errorf("failed to write cid field t.LockedTable: %w", err) + } + + // t.NextID (abi.DealID) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.NextID)); err != nil { + return err + } + + // t.DealOpsByEpoch (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.DealOpsByEpoch); err != nil { + return xerrors.Errorf("failed to write cid field t.DealOpsByEpoch: %w", err) + } + + // t.LastCron (abi.ChainEpoch) (int64) + if t.LastCron >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.LastCron)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.LastCron-1)); err != nil { + return err + } + } + + // t.TotalClientLockedCollateral (big.Int) (struct) + if err := t.TotalClientLockedCollateral.MarshalCBOR(cw); err != nil { + return err + } + + // t.TotalProviderLockedCollateral (big.Int) (struct) + if err := t.TotalProviderLockedCollateral.MarshalCBOR(cw); err != nil { + return err + } + + // t.TotalClientStorageFee (big.Int) (struct) + if err := t.TotalClientStorageFee.MarshalCBOR(cw); err != nil { + return err + } + + // t.PendingDealAllocationIds (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.PendingDealAllocationIds); err != nil { + return xerrors.Errorf("failed to write cid field t.PendingDealAllocationIds: %w", err) + } + + // t.ProviderSectors (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.ProviderSectors); err != nil { + return xerrors.Errorf("failed to write cid field t.ProviderSectors: %w", err) + } + + return nil +} + +func (t *State) UnmarshalCBOR(r io.Reader) (err error) { + *t = State{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 13 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Proposals (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.Proposals: %w", err) + } + + t.Proposals = c + + } + // t.States (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.States: %w", err) + } + + t.States = c + + } + // t.PendingProposals (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.PendingProposals: %w", err) + } + + t.PendingProposals = c + + } + // t.EscrowTable (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.EscrowTable: %w", err) + } + + t.EscrowTable = c + + } + // t.LockedTable (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.LockedTable: %w", err) + } + + t.LockedTable = c + + } + // t.NextID (abi.DealID) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.NextID = abi.DealID(extra) + + } + // t.DealOpsByEpoch (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.DealOpsByEpoch: %w", err) + } + + t.DealOpsByEpoch = c + + } + // t.LastCron (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.LastCron = abi.ChainEpoch(extraI) + } + // t.TotalClientLockedCollateral (big.Int) (struct) + + { + + if err := t.TotalClientLockedCollateral.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.TotalClientLockedCollateral: %w", err) + } + + } + // t.TotalProviderLockedCollateral (big.Int) (struct) + + { + + if err := t.TotalProviderLockedCollateral.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.TotalProviderLockedCollateral: %w", err) + } + + } + // t.TotalClientStorageFee (big.Int) (struct) + + { + + if err := t.TotalClientStorageFee.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.TotalClientStorageFee: %w", err) + } + + } + // t.PendingDealAllocationIds (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.PendingDealAllocationIds: %w", err) + } + + t.PendingDealAllocationIds = c + + } + // t.ProviderSectors (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.ProviderSectors: %w", err) + } + + t.ProviderSectors = c + + } + return nil +} + +var lengthBufDealState = []byte{132} + +func (t *DealState) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufDealState); err != nil { + return err + } + + // t.SectorNumber (abi.SectorNumber) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SectorNumber)); err != nil { + return err + } + + // t.SectorStartEpoch (abi.ChainEpoch) (int64) + if t.SectorStartEpoch >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SectorStartEpoch)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.SectorStartEpoch-1)); err != nil { + return err + } + } + + // t.LastUpdatedEpoch (abi.ChainEpoch) (int64) + if t.LastUpdatedEpoch >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.LastUpdatedEpoch)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.LastUpdatedEpoch-1)); err != nil { + return err + } + } + + // t.SlashEpoch (abi.ChainEpoch) (int64) + if t.SlashEpoch >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SlashEpoch)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.SlashEpoch-1)); err != nil { + return err + } + } + + return nil +} + +func (t *DealState) UnmarshalCBOR(r io.Reader) (err error) { + *t = DealState{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 4 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.SectorNumber (abi.SectorNumber) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.SectorNumber = abi.SectorNumber(extra) + + } + // t.SectorStartEpoch (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.SectorStartEpoch = abi.ChainEpoch(extraI) + } + // t.LastUpdatedEpoch (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.LastUpdatedEpoch = abi.ChainEpoch(extraI) + } + // t.SlashEpoch (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.SlashEpoch = abi.ChainEpoch(extraI) + } + return nil +} + +func (t *SectorDealIDs) MarshalCBOR(w io.Writer) error { + cw := cbg.NewCborWriter(w) + + // (*t) (market.SectorDealIDs) (slice) + if len((*t)) > 8192 { + return xerrors.Errorf("Slice value in field (*t) was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len((*t)))); err != nil { + return err + } + for _, v := range *t { + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(v)); err != nil { + return err + } + + } + return nil +} + +func (t *SectorDealIDs) UnmarshalCBOR(r io.Reader) (err error) { + *t = SectorDealIDs{} + + cr := cbg.NewCborReader(r) + var maj byte + var extra uint64 + _ = maj + _ = extra + // (*t) (market.SectorDealIDs) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("(*t): array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + (*t) = make([]abi.DealID, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + (*t)[i] = abi.DealID(extra) + + } + + } + } + return nil +} + +var lengthBufWithdrawBalanceParams = []byte{130} + +func (t *WithdrawBalanceParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufWithdrawBalanceParams); err != nil { + return err + } + + // t.ProviderOrClientAddress (address.Address) (struct) + if err := t.ProviderOrClientAddress.MarshalCBOR(cw); err != nil { + return err + } + + // t.Amount (big.Int) (struct) + if err := t.Amount.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *WithdrawBalanceParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = WithdrawBalanceParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.ProviderOrClientAddress (address.Address) (struct) + + { + + if err := t.ProviderOrClientAddress.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ProviderOrClientAddress: %w", err) + } + + } + // t.Amount (big.Int) (struct) + + { + + if err := t.Amount.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Amount: %w", err) + } + + } + return nil +} + +var lengthBufPublishStorageDealsParams = []byte{129} + +func (t *PublishStorageDealsParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufPublishStorageDealsParams); err != nil { + return err + } + + // t.Deals ([]market.ClientDealProposal) (slice) + if len(t.Deals) > 8192 { + return xerrors.Errorf("Slice value in field t.Deals was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Deals))); err != nil { + return err + } + for _, v := range t.Deals { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *PublishStorageDealsParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = PublishStorageDealsParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Deals ([]market.ClientDealProposal) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Deals: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Deals = make([]ClientDealProposal, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Deals[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Deals[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufPublishStorageDealsReturn = []byte{130} + +func (t *PublishStorageDealsReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufPublishStorageDealsReturn); err != nil { + return err + } + + // t.IDs ([]abi.DealID) (slice) + if len(t.IDs) > 8192 { + return xerrors.Errorf("Slice value in field t.IDs was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.IDs))); err != nil { + return err + } + for _, v := range t.IDs { + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(v)); err != nil { + return err + } + + } + + // t.ValidDeals (bitfield.BitField) (struct) + if err := t.ValidDeals.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *PublishStorageDealsReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = PublishStorageDealsReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.IDs ([]abi.DealID) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.IDs: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.IDs = make([]abi.DealID, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.IDs[i] = abi.DealID(extra) + + } + + } + } + // t.ValidDeals (bitfield.BitField) (struct) + + { + + if err := t.ValidDeals.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ValidDeals: %w", err) + } + + } + return nil +} + +var lengthBufBatchActivateDealsParams = []byte{130} + +func (t *BatchActivateDealsParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufBatchActivateDealsParams); err != nil { + return err + } + + // t.Sectors ([]market.SectorDeals) (slice) + if len(t.Sectors) > 8192 { + return xerrors.Errorf("Slice value in field t.Sectors was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Sectors))); err != nil { + return err + } + for _, v := range t.Sectors { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + + // t.ComputeCid (bool) (bool) + if err := cbg.WriteBool(w, t.ComputeCid); err != nil { + return err + } + return nil +} + +func (t *BatchActivateDealsParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = BatchActivateDealsParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Sectors ([]market.SectorDeals) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Sectors: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Sectors = make([]SectorDeals, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Sectors[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Sectors[i]: %w", err) + } + + } + + } + } + // t.ComputeCid (bool) (bool) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajOther { + return fmt.Errorf("booleans must be major type 7") + } + switch extra { + case 20: + t.ComputeCid = false + case 21: + t.ComputeCid = true + default: + return fmt.Errorf("booleans are either major type 7, value 20 or 21 (got %d)", extra) + } + return nil +} + +var lengthBufActivateDealsResult = []byte{130} + +func (t *ActivateDealsResult) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufActivateDealsResult); err != nil { + return err + } + + // t.NonVerifiedDealSpace (big.Int) (struct) + if err := t.NonVerifiedDealSpace.MarshalCBOR(cw); err != nil { + return err + } + + // t.VerifiedInfos ([]market.VerifiedDealInfo) (slice) + if len(t.VerifiedInfos) > 8192 { + return xerrors.Errorf("Slice value in field t.VerifiedInfos was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.VerifiedInfos))); err != nil { + return err + } + for _, v := range t.VerifiedInfos { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *ActivateDealsResult) UnmarshalCBOR(r io.Reader) (err error) { + *t = ActivateDealsResult{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.NonVerifiedDealSpace (big.Int) (struct) + + { + + if err := t.NonVerifiedDealSpace.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.NonVerifiedDealSpace: %w", err) + } + + } + // t.VerifiedInfos ([]market.VerifiedDealInfo) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.VerifiedInfos: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.VerifiedInfos = make([]VerifiedDealInfo, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.VerifiedInfos[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.VerifiedInfos[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufVerifyDealsForActivationParams = []byte{129} + +func (t *VerifyDealsForActivationParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufVerifyDealsForActivationParams); err != nil { + return err + } + + // t.Sectors ([]market.SectorDeals) (slice) + if len(t.Sectors) > 8192 { + return xerrors.Errorf("Slice value in field t.Sectors was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Sectors))); err != nil { + return err + } + for _, v := range t.Sectors { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *VerifyDealsForActivationParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = VerifyDealsForActivationParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Sectors ([]market.SectorDeals) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Sectors: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Sectors = make([]SectorDeals, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Sectors[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Sectors[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufVerifyDealsForActivationReturn = []byte{129} + +func (t *VerifyDealsForActivationReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufVerifyDealsForActivationReturn); err != nil { + return err + } + + // t.UnsealedCIDs ([]*cid.Cid) (slice) + if len(t.UnsealedCIDs) > 8192 { + return xerrors.Errorf("Slice value in field t.UnsealedCIDs was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.UnsealedCIDs))); err != nil { + return err + } + for _, v := range t.UnsealedCIDs { + + if v == nil { + if _, err := cw.Write(cbg.CborNull); err != nil { + return err + } + } else { + if err := cbg.WriteCid(cw, *v); err != nil { + return xerrors.Errorf("failed to write cid field v: %w", err) + } + } + + } + return nil +} + +func (t *VerifyDealsForActivationReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = VerifyDealsForActivationReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.UnsealedCIDs ([]*cid.Cid) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.UnsealedCIDs: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.UnsealedCIDs = make([]*cid.Cid, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + b, err := cr.ReadByte() + if err != nil { + return err + } + if b != cbg.CborNull[0] { + if err := cr.UnreadByte(); err != nil { + return err + } + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.UnsealedCIDs[i]: %w", err) + } + + t.UnsealedCIDs[i] = &c + } + + } + + } + } + return nil +} + +var lengthBufGetBalanceReturn = []byte{130} + +func (t *GetBalanceReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufGetBalanceReturn); err != nil { + return err + } + + // t.Balance (big.Int) (struct) + if err := t.Balance.MarshalCBOR(cw); err != nil { + return err + } + + // t.Locked (big.Int) (struct) + if err := t.Locked.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *GetBalanceReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = GetBalanceReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Balance (big.Int) (struct) + + { + + if err := t.Balance.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Balance: %w", err) + } + + } + // t.Locked (big.Int) (struct) + + { + + if err := t.Locked.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Locked: %w", err) + } + + } + return nil +} + +var lengthBufGetDealDataCommitmentReturn = []byte{130} + +func (t *GetDealDataCommitmentReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufGetDealDataCommitmentReturn); err != nil { + return err + } + + // t.Data (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.Data); err != nil { + return xerrors.Errorf("failed to write cid field t.Data: %w", err) + } + + // t.Size (abi.PaddedPieceSize) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Size)); err != nil { + return err + } + + return nil +} + +func (t *GetDealDataCommitmentReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = GetDealDataCommitmentReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Data (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.Data: %w", err) + } + + t.Data = c + + } + // t.Size (abi.PaddedPieceSize) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Size = abi.PaddedPieceSize(extra) + + } + return nil +} + +var lengthBufGetDealTermReturn = []byte{130} + +func (t *GetDealTermReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufGetDealTermReturn); err != nil { + return err + } + + // t.Start (abi.ChainEpoch) (int64) + if t.Start >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Start)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.Start-1)); err != nil { + return err + } + } + + // t.Duration (abi.ChainEpoch) (int64) + if t.Duration >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Duration)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.Duration-1)); err != nil { + return err + } + } + + return nil +} + +func (t *GetDealTermReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = GetDealTermReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Start (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.Start = abi.ChainEpoch(extraI) + } + // t.Duration (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.Duration = abi.ChainEpoch(extraI) + } + return nil +} + +var lengthBufGetDealActivationReturn = []byte{130} + +func (t *GetDealActivationReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufGetDealActivationReturn); err != nil { + return err + } + + // t.Activated (abi.ChainEpoch) (int64) + if t.Activated >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Activated)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.Activated-1)); err != nil { + return err + } + } + + // t.Terminated (abi.ChainEpoch) (int64) + if t.Terminated >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Terminated)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.Terminated-1)); err != nil { + return err + } + } + + return nil +} + +func (t *GetDealActivationReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = GetDealActivationReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Activated (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.Activated = abi.ChainEpoch(extraI) + } + // t.Terminated (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.Terminated = abi.ChainEpoch(extraI) + } + return nil +} + +var lengthBufOnMinerSectorsTerminateParams = []byte{130} + +func (t *OnMinerSectorsTerminateParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufOnMinerSectorsTerminateParams); err != nil { + return err + } + + // t.Epoch (abi.ChainEpoch) (int64) + if t.Epoch >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Epoch)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.Epoch-1)); err != nil { + return err + } + } + + // t.DealIDs ([]abi.DealID) (slice) + if len(t.DealIDs) > 8192 { + return xerrors.Errorf("Slice value in field t.DealIDs was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.DealIDs))); err != nil { + return err + } + for _, v := range t.DealIDs { + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(v)); err != nil { + return err + } + + } + return nil +} + +func (t *OnMinerSectorsTerminateParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = OnMinerSectorsTerminateParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Epoch (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.Epoch = abi.ChainEpoch(extraI) + } + // t.DealIDs ([]abi.DealID) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + 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++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.DealIDs[i] = abi.DealID(extra) + + } + + } + } + return nil +} + +var lengthBufSettleDealPaymentsReturn = []byte{130} + +func (t *SettleDealPaymentsReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufSettleDealPaymentsReturn); err != nil { + return err + } + + // t.Results (batch.BatchReturn) (struct) + if err := t.Results.MarshalCBOR(cw); err != nil { + return err + } + + // t.Settlements ([]market.DealSettlementSummary) (slice) + if len(t.Settlements) > 8192 { + return xerrors.Errorf("Slice value in field t.Settlements was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Settlements))); err != nil { + return err + } + for _, v := range t.Settlements { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *SettleDealPaymentsReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = SettleDealPaymentsReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Results (batch.BatchReturn) (struct) + + { + + if err := t.Results.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Results: %w", err) + } + + } + // t.Settlements ([]market.DealSettlementSummary) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Settlements: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Settlements = make([]DealSettlementSummary, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Settlements[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Settlements[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufDealProposal = []byte{139} + +func (t *DealProposal) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufDealProposal); err != nil { + return err + } + + // t.PieceCID (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.PieceCID); err != nil { + return xerrors.Errorf("failed to write cid field t.PieceCID: %w", err) + } + + // t.PieceSize (abi.PaddedPieceSize) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.PieceSize)); err != nil { + return err + } + + // t.VerifiedDeal (bool) (bool) + if err := cbg.WriteBool(w, t.VerifiedDeal); err != nil { + return err + } + + // t.Client (address.Address) (struct) + if err := t.Client.MarshalCBOR(cw); err != nil { + return err + } + + // t.Provider (address.Address) (struct) + if err := t.Provider.MarshalCBOR(cw); err != nil { + return err + } + + // t.Label (market.DealLabel) (struct) + if err := t.Label.MarshalCBOR(cw); err != nil { + return err + } + + // t.StartEpoch (abi.ChainEpoch) (int64) + if t.StartEpoch >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.StartEpoch)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.StartEpoch-1)); err != nil { + return err + } + } + + // t.EndEpoch (abi.ChainEpoch) (int64) + if t.EndEpoch >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.EndEpoch)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.EndEpoch-1)); err != nil { + return err + } + } + + // t.StoragePricePerEpoch (big.Int) (struct) + if err := t.StoragePricePerEpoch.MarshalCBOR(cw); err != nil { + return err + } + + // t.ProviderCollateral (big.Int) (struct) + if err := t.ProviderCollateral.MarshalCBOR(cw); err != nil { + return err + } + + // t.ClientCollateral (big.Int) (struct) + if err := t.ClientCollateral.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *DealProposal) UnmarshalCBOR(r io.Reader) (err error) { + *t = DealProposal{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.PieceCID (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.PieceCID: %w", err) + } + + t.PieceCID = c + + } + // t.PieceSize (abi.PaddedPieceSize) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.PieceSize = abi.PaddedPieceSize(extra) + + } + // t.VerifiedDeal (bool) (bool) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajOther { + return fmt.Errorf("booleans must be major type 7") + } + switch extra { + case 20: + t.VerifiedDeal = false + case 21: + t.VerifiedDeal = true + default: + return fmt.Errorf("booleans are either major type 7, value 20 or 21 (got %d)", extra) + } + // t.Client (address.Address) (struct) + + { + + if err := t.Client.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Client: %w", err) + } + + } + // t.Provider (address.Address) (struct) + + { + + if err := t.Provider.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Provider: %w", err) + } + + } + // t.Label (market.DealLabel) (struct) + + { + + if err := t.Label.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Label: %w", err) + } + + } + // t.StartEpoch (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.StartEpoch = abi.ChainEpoch(extraI) + } + // t.EndEpoch (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.EndEpoch = abi.ChainEpoch(extraI) + } + // t.StoragePricePerEpoch (big.Int) (struct) + + { + + if err := t.StoragePricePerEpoch.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.StoragePricePerEpoch: %w", err) + } + + } + // t.ProviderCollateral (big.Int) (struct) + + { + + if err := t.ProviderCollateral.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ProviderCollateral: %w", err) + } + + } + // t.ClientCollateral (big.Int) (struct) + + { + + if err := t.ClientCollateral.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ClientCollateral: %w", err) + } + + } + return nil +} + +var lengthBufClientDealProposal = []byte{130} + +func (t *ClientDealProposal) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufClientDealProposal); err != nil { + return err + } + + // t.Proposal (market.DealProposal) (struct) + if err := t.Proposal.MarshalCBOR(cw); err != nil { + return err + } + + // t.ClientSignature (crypto.Signature) (struct) + if err := t.ClientSignature.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *ClientDealProposal) UnmarshalCBOR(r io.Reader) (err error) { + *t = ClientDealProposal{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Proposal (market.DealProposal) (struct) + + { + + if err := t.Proposal.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Proposal: %w", err) + } + + } + // t.ClientSignature (crypto.Signature) (struct) + + { + + if err := t.ClientSignature.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ClientSignature: %w", err) + } + + } + return nil +} + +var lengthBufSectorDeals = []byte{132} + +func (t *SectorDeals) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufSectorDeals); err != nil { + return err + } + + // t.SectorNumber (abi.SectorNumber) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SectorNumber)); err != nil { + return err + } + + // t.SectorType (abi.RegisteredSealProof) (int64) + if t.SectorType >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SectorType)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.SectorType-1)); err != nil { + return err + } + } + + // t.SectorExpiry (abi.ChainEpoch) (int64) + if t.SectorExpiry >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SectorExpiry)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.SectorExpiry-1)); err != nil { + return err + } + } + + // t.DealIDs ([]abi.DealID) (slice) + if len(t.DealIDs) > 8192 { + return xerrors.Errorf("Slice value in field t.DealIDs was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.DealIDs))); err != nil { + return err + } + for _, v := range t.DealIDs { + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(v)); err != nil { + return err + } + + } + return nil +} + +func (t *SectorDeals) UnmarshalCBOR(r io.Reader) (err error) { + *t = SectorDeals{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 4 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.SectorNumber (abi.SectorNumber) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.SectorNumber = abi.SectorNumber(extra) + + } + // t.SectorType (abi.RegisteredSealProof) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.SectorType = abi.RegisteredSealProof(extraI) + } + // t.SectorExpiry (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.SectorExpiry = abi.ChainEpoch(extraI) + } + // t.DealIDs ([]abi.DealID) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + 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++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.DealIDs[i] = abi.DealID(extra) + + } + + } + } + return nil +} + +var lengthBufDealSpaces = []byte{130} + +func (t *DealSpaces) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufDealSpaces); err != nil { + return err + } + + // t.DealSpace (big.Int) (struct) + if err := t.DealSpace.MarshalCBOR(cw); err != nil { + return err + } + + // t.VerifiedDealSpace (big.Int) (struct) + if err := t.VerifiedDealSpace.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *DealSpaces) UnmarshalCBOR(r io.Reader) (err error) { + *t = DealSpaces{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.DealSpace (big.Int) (struct) + + { + + if err := t.DealSpace.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.DealSpace: %w", err) + } + + } + // t.VerifiedDealSpace (big.Int) (struct) + + { + + if err := t.VerifiedDealSpace.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.VerifiedDealSpace: %w", err) + } + + } + return nil +} + +var lengthBufSectorDataSpec = []byte{130} + +func (t *SectorDataSpec) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufSectorDataSpec); err != nil { + return err + } + + // t.DealIDs ([]abi.DealID) (slice) + if len(t.DealIDs) > 8192 { + return xerrors.Errorf("Slice value in field t.DealIDs was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.DealIDs))); err != nil { + return err + } + for _, v := range t.DealIDs { + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(v)); err != nil { + return err + } + + } + + // t.SectorType (abi.RegisteredSealProof) (int64) + if t.SectorType >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SectorType)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.SectorType-1)); err != nil { + return err + } + } + + return nil +} + +func (t *SectorDataSpec) UnmarshalCBOR(r io.Reader) (err error) { + *t = SectorDataSpec{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.DealIDs ([]abi.DealID) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + 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++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.DealIDs[i] = abi.DealID(extra) + + } + + } + } + // t.SectorType (abi.RegisteredSealProof) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.SectorType = abi.RegisteredSealProof(extraI) + } + return nil +} + +var lengthBufVerifiedDealInfo = []byte{132} + +func (t *VerifiedDealInfo) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufVerifiedDealInfo); err != nil { + return err + } + + // t.Client (abi.ActorID) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Client)); err != nil { + return err + } + + // t.AllocationId (verifreg.AllocationId) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.AllocationId)); err != nil { + return err + } + + // t.Data (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.Data); err != nil { + return xerrors.Errorf("failed to write cid field t.Data: %w", err) + } + + // t.Size (abi.PaddedPieceSize) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Size)); err != nil { + return err + } + + return nil +} + +func (t *VerifiedDealInfo) UnmarshalCBOR(r io.Reader) (err error) { + *t = VerifiedDealInfo{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 4 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Client (abi.ActorID) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Client = abi.ActorID(extra) + + } + // t.AllocationId (verifreg.AllocationId) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.AllocationId = verifreg.AllocationId(extra) + + } + // t.Data (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.Data: %w", err) + } + + t.Data = c + + } + // t.Size (abi.PaddedPieceSize) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Size = abi.PaddedPieceSize(extra) + + } + return nil +} + +var lengthBufDealSettlementSummary = []byte{130} + +func (t *DealSettlementSummary) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufDealSettlementSummary); err != nil { + return err + } + + // t.Payment (big.Int) (struct) + if err := t.Payment.MarshalCBOR(cw); err != nil { + return err + } + + // t.Completed (bool) (bool) + if err := cbg.WriteBool(w, t.Completed); err != nil { + return err + } + return nil +} + +func (t *DealSettlementSummary) UnmarshalCBOR(r io.Reader) (err error) { + *t = DealSettlementSummary{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Payment (big.Int) (struct) + + { + + if err := t.Payment.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Payment: %w", err) + } + + } + // t.Completed (bool) (bool) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajOther { + return fmt.Errorf("booleans must be major type 7") + } + switch extra { + case 20: + t.Completed = false + case 21: + t.Completed = true + default: + return fmt.Errorf("booleans are either major type 7, value 20 or 21 (got %d)", extra) + } + return nil +} diff --git a/builtin/v18/market/deal.go b/builtin/v18/market/deal.go new file mode 100644 index 00000000..36b615ae --- /dev/null +++ b/builtin/v18/market/deal.go @@ -0,0 +1,249 @@ +package market + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "unicode/utf8" + + "github.com/ipfs/go-cid" + mh "github.com/multiformats/go-multihash" + cbg "github.com/whyrusleeping/cbor-gen" + "golang.org/x/xerrors" + + addr "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/big" + acrypto "github.com/filecoin-project/go-state-types/crypto" +) + +var PieceCIDPrefix = cid.Prefix{ + Version: 1, + Codec: cid.FilCommitmentUnsealed, + MhType: mh.SHA2_256_TRUNC254_PADDED, + MhLength: 32, +} + +type DealState struct { + SectorNumber abi.SectorNumber // 0 if not yet included in proven sector (0 is also a valid sector number) + 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 +} + +// The DealLabel is a kinded union of string or byte slice. +// It serializes to a CBOR string or CBOR byte string depending on which form it takes. +// The zero value is serialized as an empty CBOR string (maj type 3). +type DealLabel struct { + bs []byte + notString bool +} + +// Zero value of DealLabel is canonical EmptyDealLabel +var EmptyDealLabel = DealLabel{} + +func NewLabelFromString(s string) (DealLabel, error) { + if len(s) > DealMaxLabelSize { + return EmptyDealLabel, xerrors.Errorf("provided string is too large to be a label (%d), max length (%d)", len(s), DealMaxLabelSize) + } + if !utf8.ValidString(s) { + return EmptyDealLabel, xerrors.Errorf("provided string is invalid utf8") + } + return DealLabel{ + bs: []byte(s), + notString: false, + }, nil +} + +func NewLabelFromBytes(b []byte) (DealLabel, error) { + if len(b) > DealMaxLabelSize { + return EmptyDealLabel, xerrors.Errorf("provided bytes are too large to be a label (%d), max length (%d)", len(b), DealMaxLabelSize) + } + + return DealLabel{ + bs: b, + notString: true, + }, nil +} + +func (label DealLabel) IsString() bool { + return !label.notString +} + +func (label DealLabel) IsBytes() bool { + return label.notString +} + +func (label DealLabel) ToString() (string, error) { + if !label.IsString() { + return "", xerrors.Errorf("label is not string") + } + + return string(label.bs), nil +} + +func (label DealLabel) ToBytes() ([]byte, error) { + if !label.IsBytes() { + return nil, xerrors.Errorf("label is not bytes") + } + return label.bs, nil +} + +func (label DealLabel) Length() int { + return len(label.bs) +} + +func (l DealLabel) Equals(o DealLabel) bool { + return bytes.Equal(l.bs, o.bs) && l.notString == o.notString +} + +func (label *DealLabel) MarshalCBOR(w io.Writer) error { + scratch := make([]byte, 9) + + // nil *DealLabel counts as EmptyLabel + // on chain structures should never have a pointer to a DealLabel but the case is included for completeness + if label == nil { + if err := cbg.WriteMajorTypeHeaderBuf(scratch, w, cbg.MajTextString, 0); err != nil { + return err + } + _, err := io.WriteString(w, string("")) + return err + } + if uint64(len(label.bs)) > cbg.ByteArrayMaxLen { + return xerrors.Errorf("label is too long to marshal (%d), max allowed (%d)", len(label.bs), cbg.ByteArrayMaxLen) + } + + majorType := byte(cbg.MajByteString) + if label.IsString() { + majorType = cbg.MajTextString + } + + if err := cbg.WriteMajorTypeHeaderBuf(scratch, w, majorType, uint64(len(label.bs))); err != nil { + return err + } + _, err := w.Write(label.bs) + return err +} + +func (label *DealLabel) UnmarshalCBOR(br io.Reader) error { + if label == nil { + return xerrors.Errorf("cannot unmarshal into nil pointer") + } + + // reset fields + label.bs = nil + + scratch := make([]byte, 8) + + maj, length, err := cbg.CborReadHeaderBuf(br, scratch) + if err != nil { + return err + } + if maj != cbg.MajTextString && maj != cbg.MajByteString { + return fmt.Errorf("unexpected major tag (%d) when unmarshaling DealLabel: only textString (%d) or byteString (%d) expected", maj, cbg.MajTextString, cbg.MajByteString) + } + if length > cbg.ByteArrayMaxLen { + return fmt.Errorf("label was too long (%d), max allowed (%d)", length, cbg.ByteArrayMaxLen) + } + buf := make([]byte, length) + _, err = io.ReadAtLeast(br, buf, int(length)) + if err != nil { + return err + } + label.bs = buf + label.notString = maj != cbg.MajTextString + if !label.notString && !utf8.ValidString(string(buf)) { + return fmt.Errorf("label string not valid utf8") + } + + return nil +} + +func (label DealLabel) MarshalJSON() ([]byte, error) { + if !label.IsString() { + return json.Marshal("") + } + + str, err := label.ToString() + if err != nil { + return nil, xerrors.Errorf("failed to convert to string: %w", err) + } + + return json.Marshal(str) +} + +func (label *DealLabel) UnmarshalJSON(b []byte) error { + var str string + if err := json.Unmarshal(b, &str); err != nil { + return xerrors.Errorf("failed to unmarshal string: %w", err) + } + + newLabel, err := NewLabelFromString(str) + if err != nil { + return xerrors.Errorf("failed to create label from string: %w", err) + } + + *label = newLabel + return nil +} + +// Note: Deal Collateral is only released and returned to clients and miners +// when the storage deal stops counting towards power. In the current iteration, +// it will be released when the sector containing the storage deals expires, +// even though some storage deals can expire earlier than the sector does. +// Collaterals are denominated in PerEpoch to incur a cost for self dealing or +// minimal deals that last for a long time. +// Note: ClientCollateralPerEpoch may not be needed and removed pending future confirmation. +// There will be a Minimum value for both client and provider deal collateral. +type DealProposal struct { + PieceCID cid.Cid `checked:"true"` // Checked in validateDeal, CommP + PieceSize abi.PaddedPieceSize + VerifiedDeal bool + Client addr.Address + Provider addr.Address + + // Label is an arbitrary client chosen label to apply to the deal + Label DealLabel + + // Nominal start epoch. Deal payment is linear between StartEpoch and EndEpoch, + // with total amount StoragePricePerEpoch * (EndEpoch - StartEpoch). + // Storage deal must appear in a sealed (proven) sector no later than StartEpoch, + // otherwise it is invalid. + StartEpoch abi.ChainEpoch + EndEpoch abi.ChainEpoch + StoragePricePerEpoch abi.TokenAmount + + ProviderCollateral abi.TokenAmount + ClientCollateral abi.TokenAmount +} + +// ClientDealProposal is a DealProposal signed by a client +type ClientDealProposal struct { + Proposal DealProposal + ClientSignature acrypto.Signature +} + +func (p *DealProposal) Duration() abi.ChainEpoch { + return p.EndEpoch - p.StartEpoch +} + +func (p *DealProposal) TotalStorageFee() abi.TokenAmount { + return big.Mul(p.StoragePricePerEpoch, big.NewInt(int64(p.Duration()))) +} + +func (p *DealProposal) ClientBalanceRequirement() abi.TokenAmount { + return big.Add(p.ClientCollateral, p.TotalStorageFee()) +} + +func (p *DealProposal) ProviderBalanceRequirement() abi.TokenAmount { + return p.ProviderCollateral +} + +func (p *DealProposal) Cid() (cid.Cid, error) { + buf := new(bytes.Buffer) + if err := p.MarshalCBOR(buf); err != nil { + return cid.Undef, err + } + return abi.CidBuilder.Sum(buf.Bytes()) +} diff --git a/builtin/v18/market/deal_test.go b/builtin/v18/market/deal_test.go new file mode 100644 index 00000000..211a065e --- /dev/null +++ b/builtin/v18/market/deal_test.go @@ -0,0 +1,262 @@ +package market_test + +import ( + "bytes" + "encoding/json" + "testing" + + "github.com/ipfs/go-cid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/big" + "github.com/filecoin-project/go-state-types/builtin/v18/market" +) + +func TestDealLabel(t *testing.T) { + + // empty label serialize and deserialize to string label of empty string + label1 := market.EmptyDealLabel + buf := bytes.Buffer{} + require.NoError(t, label1.MarshalCBOR(&buf), "failed to marshal empty deal label") + ser := buf.Bytes() + assert.Equal(t, []byte{0x60}, ser) // cbor empty str (maj type 3) + label2 := &market.DealLabel{} + require.NoError(t, label2.UnmarshalCBOR(bytes.NewReader(ser))) + assert.True(t, label2.IsString()) + assert.False(t, label2.IsBytes()) + str, err := label2.ToString() + assert.NoError(t, err) + assert.Equal(t, "", str) + + // bytes label + label1, err = market.NewLabelFromBytes([]byte{0xca, 0xfe, 0xb0, 0x0a}) + assert.NoError(t, err) + buf = bytes.Buffer{} + require.NoError(t, label1.MarshalCBOR(&buf), "failed to marshal bytes deal label") + ser = buf.Bytes() + label2 = &market.DealLabel{} + require.NoError(t, label2.UnmarshalCBOR(bytes.NewReader(ser))) + assert.True(t, label2.IsBytes()) + assert.False(t, label2.IsString()) + bs, err := label2.ToBytes() + require.NoError(t, err) + assert.Equal(t, []byte{0xca, 0xfe, 0xb0, 0x0a}, bs) + + // string label + label1, err = market.NewLabelFromString("i am a label, turn me into cbor maj typ 3 plz") + assert.NoError(t, err) + buf = bytes.Buffer{} + require.NoError(t, label1.MarshalCBOR(&buf), "failed to marshal string deal label") + ser = buf.Bytes() + label2 = &market.DealLabel{} + require.NoError(t, label2.UnmarshalCBOR(bytes.NewReader(ser))) + assert.True(t, label2.IsString()) + assert.False(t, label2.IsBytes()) + str, err = label2.ToString() + assert.NoError(t, err) + assert.Equal(t, "i am a label, turn me into cbor maj typ 3 plz", str) + + // invalid utf8 string + _, err = market.NewLabelFromString(string([]byte{0xde, 0xad, 0xbe, 0xef})) + assert.Error(t, err) + assert.Contains(t, err.Error(), "invalid utf8") + + // nil label marshals + labelPtr := (*market.DealLabel)(nil) + buf = bytes.Buffer{} + require.NoError(t, labelPtr.MarshalCBOR(&buf), "failed to marshal empty deal label") + ser = buf.Bytes() + assert.Equal(t, []byte{0x60}, ser) // cbor empty str (maj type 3) + + // nil label unmarshal fails nicely + labelPtr = (*market.DealLabel)(nil) + err = labelPtr.UnmarshalCBOR(bytes.NewReader(ser)) + assert.Error(t, err) + assert.Contains(t, err.Error(), "cannot unmarshal into nil pointer") + +} +func TestDealLabelJSON(t *testing.T) { + + // Non-empty string + label1, err := market.NewLabelFromString("i am a label, json me correctly plz") + require.NoError(t, err, "failed to create label from string") + label1JSON, err := json.Marshal(&label1) + require.NoError(t, err, "failed to JSON marshal string label") + label2 := &market.DealLabel{} + require.NoError(t, label2.UnmarshalJSON(label1JSON)) + assert.True(t, label2.IsString()) + assert.False(t, label2.IsBytes()) + str, err := label2.ToString() + assert.NoError(t, err) + assert.Equal(t, "i am a label, json me correctly plz", str) + + dp := &market.DealProposal{ + PieceCID: cid.Undef, + PieceSize: 0, + VerifiedDeal: false, + Client: address.Undef, + Provider: address.Undef, + Label: label1, + StoragePricePerEpoch: big.Zero(), + ProviderCollateral: big.Zero(), + ClientCollateral: big.Zero(), + } + + dpJSON, err := json.Marshal(dp) + require.NoError(t, err, "failed to JSON marshal deal proposal") + dp2 := market.DealProposal{} + require.NoError(t, json.Unmarshal(dpJSON, &dp2)) + assert.True(t, dp2.Label.IsString()) + assert.False(t, dp2.Label.IsBytes()) + str, err = dp2.Label.ToString() + assert.NoError(t, err) + assert.Equal(t, "i am a label, json me correctly plz", str) + + // empty label + label1, err = market.NewLabelFromString("") + require.NoError(t, err, "failed to create label from string") + label1JSON, err = json.Marshal(&label1) + require.NoError(t, err, "failed to JSON marshal string label") + label2 = &market.DealLabel{} + require.NoError(t, label2.UnmarshalJSON(label1JSON)) + assert.True(t, label2.IsString()) + assert.False(t, label2.IsBytes()) + str, err = label2.ToString() + assert.NoError(t, err) + assert.Equal(t, "", str) + + dp = &market.DealProposal{ + PieceCID: cid.Undef, + PieceSize: 0, + VerifiedDeal: false, + Client: address.Undef, + Provider: address.Undef, + Label: label1, + StoragePricePerEpoch: big.Zero(), + ProviderCollateral: big.Zero(), + ClientCollateral: big.Zero(), + } + + dpJSON, err = json.Marshal(dp) + require.NoError(t, err, "failed to JSON marshal deal proposal") + dp2 = market.DealProposal{} + require.NoError(t, json.Unmarshal(dpJSON, &dp2)) + assert.True(t, dp2.Label.IsString()) + assert.False(t, dp2.Label.IsBytes()) + str, err = dp2.Label.ToString() + assert.NoError(t, err) + assert.Equal(t, "", str) + + // unset label + dp = &market.DealProposal{ + PieceCID: cid.Undef, + PieceSize: 0, + VerifiedDeal: false, + Client: address.Undef, + Provider: address.Undef, + StoragePricePerEpoch: big.Zero(), + ProviderCollateral: big.Zero(), + ClientCollateral: big.Zero(), + } + + dpJSON, err = json.Marshal(dp) + require.NoError(t, err, "failed to JSON marshal deal proposal") + dp2 = market.DealProposal{} + require.NoError(t, json.Unmarshal(dpJSON, &dp2)) + assert.True(t, dp2.Label.IsString()) + assert.False(t, dp2.Label.IsBytes()) + str, err = dp2.Label.ToString() + assert.NoError(t, err) + assert.Equal(t, "", str) + + // bytes label + label1, err = market.NewLabelFromBytes([]byte{0xde, 0xad, 0xbe, 0xef}) + assert.NoError(t, err) + assert.True(t, label1.IsBytes()) + assert.False(t, label1.IsString()) + + dp = &market.DealProposal{ + PieceCID: cid.Undef, + PieceSize: 0, + VerifiedDeal: false, + Client: address.Undef, + Provider: address.Undef, + Label: label1, + StoragePricePerEpoch: big.Zero(), + ProviderCollateral: big.Zero(), + ClientCollateral: big.Zero(), + } + + dpJSON, err = json.Marshal(dp) + require.NoError(t, err, "failed to JSON marshal deal proposal") + dp2 = market.DealProposal{} + require.NoError(t, json.Unmarshal(dpJSON, &dp2)) + // a JSON-unmarshaled label is always string type + assert.False(t, dp2.Label.IsBytes()) + assert.True(t, dp2.Label.IsString()) + + // it can be converted ToString, but it's empty + str, err = dp2.Label.ToString() + assert.NoError(t, err) + assert.Equal(t, str, "") +} + +func TestDealLabelFromCBOR(t *testing.T) { + // empty string + // b011_00000 + emptyCBORText := []byte{0x60} + var label1 market.DealLabel + require.NoError(t, label1.UnmarshalCBOR(bytes.NewReader(emptyCBORText))) + assert.True(t, label1.IsString()) + str, err := label1.ToString() + assert.NoError(t, err) + assert.Equal(t, "", str) + + // valid utf8 string + // b011_01000 "deadbeef" + cborTestValid := append([]byte{0x68}, []byte("deadbeef")...) + var label2 market.DealLabel + require.NoError(t, label2.UnmarshalCBOR(bytes.NewReader(cborTestValid))) + assert.True(t, label2.IsString()) + str, err = label2.ToString() + assert.NoError(t, err) + assert.Equal(t, "deadbeef", str) + + // invalid utf8 string + // b011_00100 0xde 0xad 0xbe 0xef + cborText := []byte{0x64, 0xde, 0xad, 0xbe, 0xef} + var label3 market.DealLabel + err = label3.UnmarshalCBOR(bytes.NewReader(cborText)) + assert.Error(t, err) + assert.Contains(t, err.Error(), "not valid utf8") + + // empty bytes + // b010_00000 + emptyCBORBytes := []byte{0x40} + var label4 market.DealLabel + require.NoError(t, label4.UnmarshalCBOR(bytes.NewReader(emptyCBORBytes))) + assert.True(t, label4.IsBytes()) + bs, err := label4.ToBytes() + require.NoError(t, err) + assert.Equal(t, []byte{}, bs) + + // bytes + // b010_00100 0xde 0xad 0xbe 0xef + cborBytes := []byte{0x44, 0xde, 0xad, 0xbe, 0xef} + var label5 market.DealLabel + require.NoError(t, label5.UnmarshalCBOR(bytes.NewReader(cborBytes))) + assert.True(t, label5.IsBytes()) + bs, err = label5.ToBytes() + require.NoError(t, err) + assert.Equal(t, []byte{0xde, 0xad, 0xbe, 0xef}, bs) + + // bad major type + // array of empty array b100_00001 b100_00000 + arrayBytes := []byte{0x81, 0x80} + var label6 market.DealLabel + err = label6.UnmarshalCBOR(bytes.NewReader(arrayBytes)) + assert.Error(t, err) + assert.Contains(t, err.Error(), "unexpected major tag") +} diff --git a/builtin/v18/market/invariants.go b/builtin/v18/market/invariants.go new file mode 100644 index 00000000..65691476 --- /dev/null +++ b/builtin/v18/market/invariants.go @@ -0,0 +1,345 @@ +package market + +import ( + "bytes" + "encoding/binary" + + "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" + + "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/builtin" + "github.com/filecoin-project/go-state-types/builtin/v18/util/adt" + "github.com/filecoin-project/go-state-types/builtin/v18/verifreg" +) + +type DealSummary struct { + Provider address.Address + StartEpoch abi.ChainEpoch + EndEpoch abi.ChainEpoch + SectorStartEpoch abi.ChainEpoch + LastUpdatedEpoch abi.ChainEpoch + SlashEpoch abi.ChainEpoch + // Populated from market's States, not the miner state + SectorNumber abi.SectorNumber + PieceCid cid.Cid +} + +type StateSummary struct { + Deals map[abi.DealID]*DealSummary + PendingDealAllocationIds map[abi.DealID]verifreg.AllocationId + ClaimIdToDealId map[verifreg.ClaimId]abi.DealID + AllocIdToDealId map[verifreg.AllocationId]abi.DealID + ProviderSectors map[abi.SectorID][]abi.DealID + PendingProposalCount uint64 + DealStateCount uint64 + LockTableCount uint64 + DealOpEpochCount uint64 + DealOpCount uint64 +} + +// Checks internal invariants of market state. +func CheckStateInvariants(st *State, store adt.Store, balance abi.TokenAmount, currEpoch abi.ChainEpoch) (*StateSummary, *builtin.MessageAccumulator) { + acc := &builtin.MessageAccumulator{} + + acc.Require( + st.TotalClientLockedCollateral.GreaterThanEqual(big.Zero()), + "negative total client locked collateral: %v", st.TotalClientLockedCollateral) + + acc.Require( + st.TotalProviderLockedCollateral.GreaterThanEqual(big.Zero()), + "negative total provider locked collateral: %v", st.TotalClientLockedCollateral) + + acc.Require( + st.TotalClientStorageFee.GreaterThanEqual(big.Zero()), + "negative total client storage fee: %v", st.TotalClientLockedCollateral) + + // + // Proposals + // + + proposalCids := make(map[cid.Cid]struct{}) + maxDealID := int64(-1) + proposalStats := make(map[abi.DealID]*DealSummary) + expectedDealOps := make(map[abi.DealID]struct{}) + totalProposalCollateral := abi.NewTokenAmount(0) + + if proposals, err := adt.AsArray(store, st.Proposals, ProposalsAmtBitwidth); err != nil { + acc.Addf("error loading proposals: %v", err) + } else { + var proposal DealProposal + err = proposals.ForEach(&proposal, func(dealID int64) error { + pcid, err := proposal.Cid() + acc.RequireNoError(err, "error getting cid from proposal") + + if proposal.StartEpoch >= currEpoch { + expectedDealOps[abi.DealID(dealID)] = struct{}{} + } + + // keep some state + proposalCids[pcid] = struct{}{} + if dealID > maxDealID { + maxDealID = dealID + } + proposalStats[abi.DealID(dealID)] = &DealSummary{ + Provider: proposal.Provider, + StartEpoch: proposal.StartEpoch, + EndEpoch: proposal.EndEpoch, + SectorStartEpoch: abi.ChainEpoch(-1), + LastUpdatedEpoch: abi.ChainEpoch(-1), + SlashEpoch: abi.ChainEpoch(-1), + PieceCid: proposal.PieceCID, + } + + totalProposalCollateral = big.Sum(totalProposalCollateral, proposal.ClientCollateral, proposal.ProviderCollateral) + + acc.Require(proposal.Client.Protocol() == address.ID, "client address for deal %d is not an ID address", dealID) + acc.Require(proposal.Provider.Protocol() == address.ID, "provider address for deal %d is not an ID address", dealID) + return nil + }) + acc.RequireNoError(err, "error iterating proposals") + } + + // next id should be higher than any existing deal + acc.Require(int64(st.NextID) > maxDealID, "next id, %d, is not greater than highest id in proposals, %d", st.NextID, maxDealID) + + // + // Deal States + // + + pendingDealAllocationIds, err := st.GetPendingDealAllocationIds(store) + acc.RequireNoError(err, "error loading pending deal proposal Ids") + + allocationIdToDealId := make(map[verifreg.AllocationId]abi.DealID) + for dealId, allocationId := range pendingDealAllocationIds { + _, found := proposalStats[dealId] + acc.Require(found, "pending deal allocation %d not found in proposals", dealId) + + allocationIdToDealId[allocationId] = dealId + } + + dealStateCount := uint64(0) + claimIdToDealId := make(map[verifreg.ClaimId]abi.DealID) + expectedProviderSectors := make(map[abi.DealID]struct{}) + if dealStates, err := adt.AsArray(store, st.States, StatesAmtBitwidth); err != nil { + acc.Addf("error loading deal states: %v", err) + } else { + var dealState DealState + err = dealStates.ForEach(&dealState, func(dealID int64) error { + acc.Require( + dealState.SectorStartEpoch >= 0, + "deal %d state start epoch undefined: %v", dealID, dealState) + + acc.Require( + dealState.LastUpdatedEpoch == EpochUndefined || dealState.LastUpdatedEpoch >= dealState.SectorStartEpoch, + "deal %d state last updated before sector start: %v", dealID, dealState) + + acc.Require( + dealState.LastUpdatedEpoch == EpochUndefined || dealState.LastUpdatedEpoch <= currEpoch, + "deal %d last updated epoch %d after current %d", dealID, dealState.LastUpdatedEpoch, currEpoch) + + acc.Require( + dealState.SlashEpoch == EpochUndefined || dealState.SlashEpoch >= dealState.SectorStartEpoch, + "deal %d state slashed before sector start: %v", dealID, dealState) + + acc.Require( + dealState.SlashEpoch == EpochUndefined || dealState.SlashEpoch <= currEpoch, + "deal %d state slashed after current epoch %d: %v", dealID, currEpoch, dealState) + + stats, found := proposalStats[abi.DealID(dealID)] + if !found { + acc.Addf("no deal proposal for deal state %d", dealID) + } else { + stats.SectorStartEpoch = dealState.SectorStartEpoch + stats.LastUpdatedEpoch = dealState.LastUpdatedEpoch + stats.SlashEpoch = dealState.SlashEpoch + stats.SectorNumber = dealState.SectorNumber + } + _, found = pendingDealAllocationIds[abi.DealID(dealID)] + acc.Require(!found, "deal %d has pending allocation", dealID) + + if dealState.SlashEpoch == EpochUndefined && dealState.SectorStartEpoch != EpochUndefined && stats.EndEpoch > currEpoch { + expectedProviderSectors[abi.DealID(dealID)] = struct{}{} + } + + dealStateCount++ + + return nil + }) + acc.RequireNoError(err, "error iterating deal states") + } + + // + // Pending Proposals + // + + pendingProposalCount := uint64(0) + if pendingProposals, err := adt.AsMap(store, st.PendingProposals, builtin.DefaultHamtBitwidth); err != nil { + acc.Addf("error loading pending proposals: %v", err) + } else { + err = pendingProposals.ForEach(nil, func(key string) error { + proposalCID, err := cid.Parse([]byte(key)) + acc.RequireNoError(err, "error getting cid from proposal") + + _, found := proposalCids[proposalCID] + acc.Require(found, "pending proposal with cid %v not found within proposals %v", proposalCID, pendingProposals) + + pendingProposalCount++ + return nil + }) + acc.RequireNoError(err, "error iterating pending proposals") + } + + // + // Escrow Table and Locked Table + // + + lockTableCount := uint64(0) + escrowTable, err := adt.AsBalanceTable(store, st.EscrowTable) + acc.RequireNoError(err, "error loading escrow table") + lockTable, err := adt.AsBalanceTable(store, st.LockedTable) + acc.RequireNoError(err, "error loading locked table") + if escrowTable != nil && lockTable != nil { + var lockedAmount abi.TokenAmount + lockedTotal := abi.NewTokenAmount(0) + err = (*adt.Map)(lockTable).ForEach(&lockedAmount, func(key string) error { + addr, err := address.NewFromBytes([]byte(key)) + acc.RequireNoError(err, "error getting address from bytes") + lockedTotal = big.Add(lockedTotal, lockedAmount) + + // every entry in locked table should have a corresponding entry in escrow table that is at least as high + escrowAmount, err := escrowTable.Get(addr) + acc.RequireNoError(err, "error escrow amount from table for %s", addr) + acc.Require(escrowAmount.GreaterThanEqual(lockedAmount), + "locked funds for %s, %s, greater than escrow amount, %s", addr, lockedAmount, escrowAmount) + + lockTableCount++ + return nil + }) + acc.RequireNoError(err, "error iterating locked table") + + // lockTable total should be sum of client and provider locked plus client storage fee + expectedLockTotal := big.Sum(st.TotalProviderLockedCollateral, st.TotalClientLockedCollateral, st.TotalClientStorageFee) + acc.Require(lockedTotal.Equals(expectedLockTotal), + "locked total, %s, does not sum to provider locked, %s, client locked, %s, and client storage fee, %s", + lockedTotal, st.TotalProviderLockedCollateral, st.TotalClientLockedCollateral, st.TotalClientStorageFee) + + // assert escrow <= actor balance + // lockTable item <= escrow item and escrowTotal <= balance implies lockTable total <= balance + escrowTotal, err := escrowTable.Total() + acc.RequireNoError(err, "error calculating escrow total") + acc.Require(escrowTotal.LessThanEqual(balance), "escrow total, %v, greater than actor balance, %v", escrowTotal, balance) + acc.Require(escrowTotal.GreaterThanEqual(totalProposalCollateral), "escrow total, %v, less than sum of proposal collateral, %v", escrowTotal, totalProposalCollateral) + } + + // + // Deal Ops by Epoch + // + + dealOpEpochCount := uint64(0) + dealOpCount := uint64(0) + if dealOps, err := AsSetMultimap(store, st.DealOpsByEpoch, builtin.DefaultHamtBitwidth, builtin.DefaultHamtBitwidth); err != nil { + acc.Addf("error loading deal ops: %v", err) + } else { + // get into internals just to iterate through full data structure + var setRoot cbg.CborCid + err = dealOps.mp.ForEach(&setRoot, func(key string) error { + epoch, err := binary.ReadUvarint(bytes.NewReader([]byte(key))) + acc.RequireNoError(err, "error epoch from bytes") + + dealOpEpochCount++ + return dealOps.ForEach(abi.ChainEpoch(epoch), func(id abi.DealID) error { + _, found := proposalStats[id] + acc.Require(found, "deal op found for deal id %d with missing proposal at epoch %d", id, epoch) + delete(expectedDealOps, id) + dealOpCount++ + return nil + }) + }) + acc.RequireNoError(err, "error iterating deal ops") + } + + acc.Require(len(expectedDealOps) == 0, "missing deal ops for proposals: %v", expectedDealOps) + + // + // Provider Sectors + // Provider->sector->deal mapping + // A deal may have expired but remain in the mapping until settlement. + + providerSectors := make(map[abi.SectorID][]abi.DealID) + if sectorDeals, err := adt.AsMap(store, st.ProviderSectors, ProviderSectorsHamtBitwidth); err != nil { + acc.Addf("error loading st.ProviderSectors: %v", err) + } else { + var sectorMapRoot cbg.CborCid + err = sectorDeals.ForEach(§orMapRoot, func(providerID string) error { + provider, err := abi.ParseUIntKey(providerID) + if err != nil { + acc.RequireNoError(err, "error getting address from bytes") + return nil + } + + sectorMap, err := adt.AsMap(store, cid.Cid(sectorMapRoot), ProviderSectorsHamtBitwidth) + if err != nil { + acc.RequireNoError(err, "error loading sector map for provider %s", provider) + return nil + } + + var dealIDs SectorDealIDs + err = sectorMap.ForEach(&dealIDs, func(sectorIDBytes string) error { + sectorNumber, err := abi.ParseUIntKey(sectorIDBytes) + acc.RequireNoError(err, "error sector number from bytes") + + acc.Require(len(dealIDs) > 0, "no deal ids in sector %d", sectorNumber) + + dealIDsCopy := make([]abi.DealID, len(dealIDs)) + copy(dealIDsCopy, dealIDs) + + providerSectors[abi.SectorID{Miner: abi.ActorID(provider), Number: abi.SectorNumber(sectorNumber)}] = dealIDsCopy + + // check against proposalStats + for _, dealID := range dealIDsCopy { + st, found := proposalStats[dealID] + if !found || st.SlashEpoch != EpochUndefined || st.EndEpoch < currEpoch { + continue + } + + acc.Require(st.SectorNumber == abi.SectorNumber(sectorNumber), "deal id %d sector number %d does not match sector id %d", dealID, st.SectorNumber, sectorNumber) + + _, ok := expectedProviderSectors[dealID] + acc.Require(ok, "found unexpected deal in ProviderSectors") + delete(expectedProviderSectors, dealID) + + provID, err := address.IDFromAddress(st.Provider) + if err != nil { + acc.Addf("error creating ID address: %v", err) + continue + } + + acc.Require(provider == provID, "deal %d has provider %v, expected %v", dealID, provID, provider) + } + + return nil + }) + acc.RequireNoError(err, "error iterating sector deals") + return nil + }) + acc.RequireNoError(err, "error iterating sector deals") + } + + acc.Require(len(expectedProviderSectors) == 0, "missing %d providersectors entries for deals", len(expectedProviderSectors)) + + return &StateSummary{ + Deals: proposalStats, + PendingDealAllocationIds: pendingDealAllocationIds, + PendingProposalCount: pendingProposalCount, + DealStateCount: dealStateCount, + LockTableCount: lockTableCount, + DealOpEpochCount: dealOpEpochCount, + DealOpCount: dealOpCount, + ClaimIdToDealId: claimIdToDealId, + AllocIdToDealId: allocationIdToDealId, + ProviderSectors: providerSectors, + }, acc +} diff --git a/builtin/v18/market/market_state.go b/builtin/v18/market/market_state.go new file mode 100644 index 00000000..1ddeaf7d --- /dev/null +++ b/builtin/v18/market/market_state.go @@ -0,0 +1,241 @@ +package market + +import ( + "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" + xerrors "golang.org/x/xerrors" + + addr "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/builtin" + "github.com/filecoin-project/go-state-types/builtin/v18/util/adt" + "github.com/filecoin-project/go-state-types/builtin/v18/verifreg" + "github.com/filecoin-project/go-state-types/exitcode" +) + +const EpochUndefined = abi.ChainEpoch(-1) + +// Bitwidth of AMTs determined empirically from mutation patterns and projections of mainnet data. +const ProposalsAmtBitwidth = 5 +const StatesAmtBitwidth = 6 +const ProviderSectorsHamtBitwidth = 5 + +type State struct { + // Proposals are deals that have been proposed and not yet cleaned up after expiry or termination. + Proposals cid.Cid // AMT[DealID]DealProposal + // States contains state for deals that have been activated and not yet cleaned up after expiry or termination. + // After expiration, the state exists until the proposal is cleaned up too. + // Invariant: keys(States) ⊆ keys(Proposals). + States cid.Cid // AMT[DealID]DealState + + // PendingProposals tracks dealProposals that have not yet reached their deal start date. + // We track them here to ensure that miners can't publish the same deal proposal twice + PendingProposals cid.Cid // Set[DealCid] + + // Total amount held in escrow, indexed by actor address (including both locked and unlocked amounts). + EscrowTable cid.Cid // BalanceTable + + // Amount locked, indexed by actor address. + // Note: the amounts in this table do not affect the overall amount in escrow: + // only the _portion_ of the total escrow amount that is locked. + LockedTable cid.Cid // BalanceTable + + NextID abi.DealID + + // Metadata cached for efficient iteration over deals. + DealOpsByEpoch cid.Cid // SetMultimap, HAMT[epoch]Set + LastCron abi.ChainEpoch + + // Total Client Collateral that is locked -> unlocked when deal is terminated + TotalClientLockedCollateral abi.TokenAmount + // Total Provider Collateral that is locked -> unlocked when deal is terminated + TotalProviderLockedCollateral abi.TokenAmount + // Total storage fee that is locked in escrow -> unlocked when payments are made + TotalClientStorageFee abi.TokenAmount + + // Verified registry allocation IDs for deals that are not yet activated. + PendingDealAllocationIds cid.Cid // HAMT[DealID]AllocationID + + /// Maps providers to their sector IDs to deal IDs. + /// This supports finding affected deals when a sector is terminated early + /// or has data replaced. + /// Grouping by provider limits the cost of operations in the expected use case + /// of multiple sectors all belonging to the same provider. + /// HAMT[ActorID]HAMT[SectorNumber]SectorDealIDs + ProviderSectors cid.Cid +} + +func ConstructState(store adt.Store) (*State, error) { + emptyProposalsArrayCid, err := adt.StoreEmptyArray(store, ProposalsAmtBitwidth) + if err != nil { + return nil, xerrors.Errorf("failed to create empty array: %w", err) + } + emptyStatesArrayCid, err := adt.StoreEmptyArray(store, StatesAmtBitwidth) + if err != nil { + return nil, xerrors.Errorf("failed to create empty states array: %w", err) + } + + emptyPendingProposalsMapCid, err := adt.StoreEmptyMap(store, builtin.DefaultHamtBitwidth) + if err != nil { + return nil, xerrors.Errorf("failed to create empty map: %w", err) + } + emptyDealOpsHamtCid, err := StoreEmptySetMultimap(store, builtin.DefaultHamtBitwidth) + if err != nil { + return nil, xerrors.Errorf("failed to create empty multiset: %w", err) + } + emptyBalanceTableCid, err := adt.StoreEmptyMap(store, adt.BalanceTableBitwidth) + if err != nil { + return nil, xerrors.Errorf("failed to create empty balance table: %w", err) + } + emptyPendingDealAllocationMapCid, err := adt.StoreEmptyMap(store, builtin.DefaultHamtBitwidth) + if err != nil { + return nil, xerrors.Errorf("failed to create empty map: %w", err) + } + emptyProviderSectorsMap, err := adt.StoreEmptyMap(store, ProviderSectorsHamtBitwidth) + if err != nil { + return nil, xerrors.Errorf("failed to create empty map: %w", err) + } + + return &State{ + Proposals: emptyProposalsArrayCid, + States: emptyStatesArrayCid, + PendingProposals: emptyPendingProposalsMapCid, + EscrowTable: emptyBalanceTableCid, + LockedTable: emptyBalanceTableCid, + NextID: abi.DealID(0), + DealOpsByEpoch: emptyDealOpsHamtCid, + LastCron: abi.ChainEpoch(-1), + PendingDealAllocationIds: emptyPendingDealAllocationMapCid, + ProviderSectors: emptyProviderSectorsMap, + + TotalClientLockedCollateral: abi.NewTokenAmount(0), + TotalProviderLockedCollateral: abi.NewTokenAmount(0), + TotalClientStorageFee: abi.NewTokenAmount(0), + }, nil +} + +// A specialization of a array to deals. +// It is an error to query for a key that doesn't exist. +type DealArray struct { + *adt.Array +} + +// Interprets a store as balance table with root `r`. +func AsDealProposalArray(s adt.Store, r cid.Cid) (*DealArray, error) { + a, err := adt.AsArray(s, r, ProposalsAmtBitwidth) + if err != nil { + return nil, err + } + return &DealArray{a}, nil +} + +// Returns the root cid of underlying AMT. +func (t *DealArray) Root() (cid.Cid, error) { + return t.Array.Root() +} + +// Gets the deal for a key. The entry must have been previously initialized. +func (t *DealArray) Get(id abi.DealID) (*DealProposal, bool, error) { + var value DealProposal + found, err := t.Array.Get(uint64(id), &value) + return &value, found, err +} + +func (t *DealArray) Set(k abi.DealID, value *DealProposal) error { + return t.Array.Set(uint64(k), value) +} + +func (t *DealArray) Delete(id abi.DealID) error { + return t.Array.Delete(uint64(id)) +} + +// Validates a collection of deal dealProposals for activation, and returns their combined weight, +// split into regular deal weight and verified deal weight. +func ValidateDealsForActivation( + st *State, store adt.Store, dealIDs []abi.DealID, minerAddr addr.Address, sectorExpiry, currEpoch abi.ChainEpoch, +) (big.Int, big.Int, uint64, error) { + proposals, err := AsDealProposalArray(store, st.Proposals) + if err != nil { + return big.Int{}, big.Int{}, 0, xerrors.Errorf("failed to load dealProposals: %w", err) + } + + return validateAndComputeDealWeight(proposals, dealIDs, minerAddr, sectorExpiry, currEpoch) +} + +//////////////////////////////////////////////////////////////////////////////// +// Checks +//////////////////////////////////////////////////////////////////////////////// + +func validateAndComputeDealWeight(proposals *DealArray, dealIDs []abi.DealID, minerAddr addr.Address, + sectorExpiry abi.ChainEpoch, sectorActivation abi.ChainEpoch) (big.Int, big.Int, uint64, error) { + + seenDealIDs := make(map[abi.DealID]struct{}, len(dealIDs)) + totalDealSpace := uint64(0) + totalDealSpaceTime := big.Zero() + totalVerifiedSpaceTime := big.Zero() + for _, dealID := range dealIDs { + // Make sure we don't double-count deals. + if _, seen := seenDealIDs[dealID]; seen { + return big.Int{}, big.Int{}, 0, exitcode.ErrIllegalArgument.Wrapf("deal ID %d present multiple times", dealID) + } + seenDealIDs[dealID] = struct{}{} + + proposal, found, err := proposals.Get(dealID) + if err != nil { + return big.Int{}, big.Int{}, 0, xerrors.Errorf("failed to load deal %d: %w", dealID, err) + } + if !found { + return big.Int{}, big.Int{}, 0, exitcode.ErrNotFound.Wrapf("no such deal %d", dealID) + } + if err = validateDealCanActivate(proposal, minerAddr, sectorExpiry, sectorActivation); err != nil { + return big.Int{}, big.Int{}, 0, xerrors.Errorf("cannot activate deal %d: %w", dealID, err) + } + + // Compute deal weight + totalDealSpace += uint64(proposal.PieceSize) + dealSpaceTime := DealWeight(proposal, sectorExpiry, sectorActivation) + if proposal.VerifiedDeal { + totalVerifiedSpaceTime = big.Add(totalVerifiedSpaceTime, dealSpaceTime) + } else { + totalDealSpaceTime = big.Add(totalDealSpaceTime, dealSpaceTime) + } + } + return totalDealSpaceTime, totalVerifiedSpaceTime, totalDealSpace, nil +} + +func validateDealCanActivate(proposal *DealProposal, minerAddr addr.Address, sectorExpiration, sectorActivation abi.ChainEpoch) error { + if proposal.Provider != minerAddr { + return exitcode.ErrForbidden.Wrapf("proposal has provider %v, must be %v", proposal.Provider, minerAddr) + } + if sectorActivation > proposal.StartEpoch { + return exitcode.ErrIllegalArgument.Wrapf("proposal start epoch %d has already elapsed at %d", proposal.StartEpoch, sectorActivation) + } + if proposal.EndEpoch > sectorExpiration { + return exitcode.ErrIllegalArgument.Wrapf("proposal expiration %d exceeds sector expiration %d", proposal.EndEpoch, sectorExpiration) + } + return nil +} + +func (st *State) GetPendingDealAllocationIds(store adt.Store) (map[abi.DealID]verifreg.AllocationId, error) { + adtMap, err := adt.AsMap(store, st.PendingDealAllocationIds, builtin.DefaultHamtBitwidth) + if err != nil { + return nil, xerrors.Errorf("couldn't get map: %x", err) + } + + var dealIdToAllocId = make(map[abi.DealID]verifreg.AllocationId) + var out cbg.CborInt + err = adtMap.ForEach(&out, func(key string) error { + uintKey, err := abi.ParseUIntKey(key) + if err != nil { + return xerrors.Errorf("couldn't parse key to uint: %w", err) + } + dealIdToAllocId[abi.DealID(uintKey)] = verifreg.AllocationId(out) + return nil + }) + if err != nil { + return nil, err + } + + return dealIdToAllocId, nil +} diff --git a/builtin/v18/market/market_types.go b/builtin/v18/market/market_types.go new file mode 100644 index 00000000..a8618cee --- /dev/null +++ b/builtin/v18/market/market_types.go @@ -0,0 +1,158 @@ +package market + +import ( + "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" + + addr "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/batch" + "github.com/filecoin-project/go-state-types/big" + "github.com/filecoin-project/go-state-types/builtin/v18/verifreg" +) + +type SectorDealIDs []abi.DealID + +type WithdrawBalanceParams struct { + ProviderOrClientAddress addr.Address + Amount abi.TokenAmount +} + +type PublishStorageDealsParams struct { + Deals []ClientDealProposal +} + +type PublishStorageDealsReturn struct { + IDs []abi.DealID + ValidDeals bitfield.BitField +} + +// - Array of sectors rather than just one +// - Removed SectorStart (which is unknown at call time) +type VerifyDealsForActivationParams struct { + Sectors []SectorDeals +} + +type SectorDeals struct { + SectorNumber abi.SectorNumber + SectorType abi.RegisteredSealProof + SectorExpiry abi.ChainEpoch + DealIDs []abi.DealID +} + +// Changed to an array of optional CIDs. +type VerifyDealsForActivationReturn struct { + UnsealedCIDs []*cid.Cid +} + +type BatchActivateDealsParams struct { + Sectors []SectorDeals + ComputeCid bool +} + +type ActivateDealsResult struct { + NonVerifiedDealSpace big.Int + VerifiedInfos []VerifiedDealInfo +} + +type VerifiedDealInfo struct { + Client abi.ActorID + AllocationId verifreg.AllocationId + Data cid.Cid + Size abi.PaddedPieceSize +} + +type SectorDataSpec struct { + DealIDs []abi.DealID + SectorType abi.RegisteredSealProof +} + +type DealSpaces struct { + DealSpace abi.DealWeight // Total space of submitted deals. + VerifiedDealSpace abi.DealWeight // Total space of submitted verified deals. +} + +type OnMinerSectorsTerminateParams struct { + Epoch abi.ChainEpoch + DealIDs []abi.DealID +} + +type GetBalanceReturn struct { + Balance abi.TokenAmount + Locked abi.TokenAmount +} + +type DealQueryParams = cbg.CborInt // abi.DealID + +type GetDealDataCommitmentParams = DealQueryParams + +type GetDealDataCommitmentReturn struct { + Data cid.Cid + Size abi.PaddedPieceSize +} + +type GetDealClientParams = DealQueryParams + +type GetDealClientReturn = cbg.CborInt // abi.ActorID + +type GetDealProviderParams = DealQueryParams + +type GetDealProviderReturn = cbg.CborInt // abi.ActorID + +type GetDealLabelParams = DealQueryParams + +type GetDealLabelReturn = DealLabel + +type GetDealTermParams = DealQueryParams + +type GetDealTermReturn struct { + Start abi.ChainEpoch + Duration abi.ChainEpoch +} + +type GetDealTotalPriceParams = DealQueryParams + +type GetDealTotalPriceReturn = abi.TokenAmount + +type GetDealClientCollateralParams = DealQueryParams + +type GetDealClientCollateralReturn = abi.TokenAmount + +type GetDealProviderCollateralParams = DealQueryParams + +type GetDealProviderCollateralReturn = abi.TokenAmount + +type GetDealVerifiedParams = DealQueryParams + +type GetDealVerifiedReturn = cbg.CborBool + +type GetDealActivationParams = DealQueryParams + +type GetDealActivationReturn struct { + // Epoch at which the deal was activated, or -1. + // This may be before the proposed start epoch. + Activated abi.ChainEpoch + // Epoch at which the deal was terminated abnormally, or -1. + Terminated abi.ChainEpoch +} + +type GetDealSectorParams = DealQueryParams + +type GetDealSectorReturn = abi.SectorNumber + +type SettleDealPaymentsParams = bitfield.BitField + +type DealSettlementSummary struct { + // Incremental amount paid to the provider. + Payment abi.TokenAmount + // Whether the deal has settled for the final time. + Completed bool +} + +type SettleDealPaymentsReturn struct { + // Indicators of success or failure for each deal. + Results batch.BatchReturn + // Results for those deals that successfully settled. + Settlements []DealSettlementSummary +} diff --git a/builtin/v18/market/methods.go b/builtin/v18/market/methods.go new file mode 100644 index 00000000..358a224c --- /dev/null +++ b/builtin/v18/market/methods.go @@ -0,0 +1,37 @@ +package market + +import ( + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/builtin" + "github.com/filecoin-project/go-state-types/builtin/v18/miner" +) + +var Methods = map[abi.MethodNum]builtin.MethodMeta{ + 1: builtin.NewMethodMeta("Constructor", *new(func(*abi.EmptyValue) *abi.EmptyValue)), // Constructor + 2: builtin.NewMethodMeta("AddBalance", *new(func(*address.Address) *abi.EmptyValue)), // AddBalance + builtin.MustGenerateFRCMethodNum("AddBalance"): builtin.NewMethodMeta("AddBalanceExported", *new(func(*address.Address) *abi.EmptyValue)), // AddBalanceExported + 3: builtin.NewMethodMeta("WithdrawBalance", *new(func(*WithdrawBalanceParams) *abi.TokenAmount)), // WithdrawBalance + builtin.MustGenerateFRCMethodNum("WithdrawBalance"): builtin.NewMethodMeta("WithdrawBalanceExported", *new(func(*WithdrawBalanceParams) *abi.TokenAmount)), // WithdrawBalanceExported + 4: builtin.NewMethodMeta("PublishStorageDeals", *new(func(*PublishStorageDealsParams) *PublishStorageDealsReturn)), // PublishStorageDeals + builtin.MustGenerateFRCMethodNum("PublishStorageDeals"): builtin.NewMethodMeta("PublishStorageDealsExported", *new(func(*PublishStorageDealsParams) *PublishStorageDealsReturn)), // PublishStorageDealsExported + 5: builtin.NewMethodMeta("VerifyDealsForActivation", *new(func(*VerifyDealsForActivationParams) *VerifyDealsForActivationReturn)), // VerifyDealsForActivation + 6: builtin.NewMethodMeta("BatchActivateDeals", *new(func(*BatchActivateDealsParams) *abi.EmptyValue)), // BatchActivateDeals + 7: builtin.NewMethodMeta("OnMinerSectorsTerminate", *new(func(*OnMinerSectorsTerminateParams) *abi.EmptyValue)), // OnMinerSectorsTerminate + 8: builtin.NewMethodMeta("ComputeDataCommitment", nil), // deprecated + 9: builtin.NewMethodMeta("CronTick", *new(func(*abi.EmptyValue) *abi.EmptyValue)), // CronTick + builtin.MustGenerateFRCMethodNum("GetBalance"): builtin.NewMethodMeta("GetBalanceExported", *new(func(*address.Address) *GetBalanceReturn)), // GetBalanceExported + builtin.MustGenerateFRCMethodNum("GetDealDataCommitment"): builtin.NewMethodMeta("GetDealDataCommitmentExported", *new(func(*GetDealDataCommitmentParams) *GetDealDataCommitmentReturn)), // GetDealDataCommitmentExported + builtin.MustGenerateFRCMethodNum("GetDealClient"): builtin.NewMethodMeta("GetDealClientExported", *new(func(*GetDealClientParams) *GetDealClientReturn)), // GetDealClientExported + builtin.MustGenerateFRCMethodNum("GetDealProvider"): builtin.NewMethodMeta("GetDealProviderExported", *new(func(*GetDealProviderParams) *GetDealProviderReturn)), // GetDealProviderExported + builtin.MustGenerateFRCMethodNum("GetDealLabel"): builtin.NewMethodMeta("GetDealLabelExported", *new(func(*GetDealLabelParams) *GetDealLabelReturn)), // GetDealLabelExported + builtin.MustGenerateFRCMethodNum("GetDealTerm"): builtin.NewMethodMeta("GetDealTermExported", *new(func(*GetDealTermParams) *GetDealTermReturn)), // GetDealTermExported + builtin.MustGenerateFRCMethodNum("GetDealTotalPrice"): builtin.NewMethodMeta("GetDealTotalPriceExported", *new(func(*GetDealTotalPriceParams) *GetDealTotalPriceReturn)), // GetDealTotalPriceExported + builtin.MustGenerateFRCMethodNum("GetDealClientCollateral"): builtin.NewMethodMeta("GetDealClientCollateralExported", *new(func(*GetDealClientCollateralParams) *GetDealClientCollateralReturn)), // GetDealClientCollateralExported + builtin.MustGenerateFRCMethodNum("GetDealProviderCollateral"): builtin.NewMethodMeta("GetDealProviderCollateralExported", *new(func(*GetDealProviderCollateralParams) *GetDealProviderCollateralReturn)), // GetDealProviderCollateralExported + builtin.MustGenerateFRCMethodNum("GetDealVerified"): builtin.NewMethodMeta("GetDealVerifiedExported", *new(func(*GetDealVerifiedParams) *GetDealVerifiedReturn)), // GetDealVerifiedExported + builtin.MustGenerateFRCMethodNum("GetDealActivation"): builtin.NewMethodMeta("GetDealActivationExported", *new(func(*GetDealActivationParams) *GetDealActivationReturn)), // GetDealActivationExported + builtin.MustGenerateFRCMethodNum("GetDealSector"): builtin.NewMethodMeta("GetDealSectorExported", *new(func(*GetDealSectorParams) *GetDealSectorReturn)), // GetDealSectorExported + builtin.MethodSectorContentChanged: builtin.NewMethodMeta("SectorContentChanged", *new(func(*miner.SectorContentChangedParams) *miner.SectorContentChangedReturn)), // SectorContentChanged + builtin.MustGenerateFRCMethodNum("SettleDealPayments"): builtin.NewMethodMeta("SettleDealPaymentsExported", *new(func(*SettleDealPaymentsParams) *SettleDealPaymentsReturn)), // SettleDealPaymentsExported +} diff --git a/builtin/v18/market/policy.go b/builtin/v18/market/policy.go new file mode 100644 index 00000000..b23af725 --- /dev/null +++ b/builtin/v18/market/policy.go @@ -0,0 +1,63 @@ +package market + +import ( + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/big" + "github.com/filecoin-project/go-state-types/builtin" +) + +// The percentage of normalized cirulating +// supply that must be covered by provider collateral in a deal +var ProviderCollateralSupplyTarget = builtin.BigFrac{ + Numerator: big.NewInt(1), // PARAM_SPEC + Denominator: big.NewInt(100), +} + +// Minimum deal duration. +var DealMinDuration = abi.ChainEpoch(180 * builtin.EpochsInDay) // PARAM_SPEC + +// Maximum deal duration +var DealMaxDuration = abi.ChainEpoch(1278 * builtin.EpochsInDay) // PARAM_SPEC + +var MarketDefaultAllocationTermBuffer = abi.ChainEpoch(90 * builtin.EpochsInDay) + +// Bounds (inclusive) on deal duration +func DealDurationBounds(_ abi.PaddedPieceSize) (min abi.ChainEpoch, max abi.ChainEpoch) { + return DealMinDuration, DealMaxDuration +} + +// DealMaxLabelSize is the maximum size of a deal label. +const DealMaxLabelSize = 256 + +func DealPricePerEpochBounds(_ abi.PaddedPieceSize, _ abi.ChainEpoch) (min abi.TokenAmount, max abi.TokenAmount) { + return abi.NewTokenAmount(0), builtin.TotalFilecoin +} + +func DealProviderCollateralBounds(pieceSize abi.PaddedPieceSize, verified bool, networkRawPower, networkQAPower, baselinePower abi.StoragePower, + networkCirculatingSupply abi.TokenAmount) (min, max abi.TokenAmount) { + // minimumProviderCollateral = ProviderCollateralSupplyTarget * normalizedCirculatingSupply + // normalizedCirculatingSupply = networkCirculatingSupply * dealPowerShare + // dealPowerShare = dealRawPower / max(BaselinePower(t), NetworkRawPower(t), dealRawPower) + + lockTargetNum := big.Mul(ProviderCollateralSupplyTarget.Numerator, networkCirculatingSupply) + lockTargetDenom := ProviderCollateralSupplyTarget.Denominator + powerShareNum := big.NewIntUnsigned(uint64(pieceSize)) + powerShareDenom := big.Max(big.Max(networkRawPower, baselinePower), powerShareNum) + + num := big.Mul(lockTargetNum, powerShareNum) + denom := big.Mul(lockTargetDenom, powerShareDenom) + minCollateral := big.Div(num, denom) + return minCollateral, builtin.TotalFilecoin +} + +func DealClientCollateralBounds(_ abi.PaddedPieceSize, _ abi.ChainEpoch) (min abi.TokenAmount, max abi.TokenAmount) { + return abi.NewTokenAmount(0), builtin.TotalFilecoin +} + +// Computes the weight for a deal proposal, which is a function of its size and duration. +func DealWeight(proposal *DealProposal, sectorExpiry abi.ChainEpoch, sectorActivation abi.ChainEpoch) abi.DealWeight { + dealDuration := big.NewInt(int64(sectorExpiry - sectorActivation)) + dealSize := big.NewIntUnsigned(uint64(proposal.PieceSize)) + dealSpaceTime := big.Mul(dealDuration, dealSize) + return dealSpaceTime +} diff --git a/builtin/v18/market/set_multimap.go b/builtin/v18/market/set_multimap.go new file mode 100644 index 00000000..00b13d48 --- /dev/null +++ b/builtin/v18/market/set_multimap.go @@ -0,0 +1,89 @@ +package market + +import ( + cid "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/go-state-types/builtin/v18/util/adt" +) + +type SetMultimap struct { + mp *adt.Map + store adt.Store + innerBitwidth int +} + +// Interprets a store as a HAMT-based map of HAMT-based sets with root `r`. +// Both inner and outer HAMTs are interpreted with branching factor 2^bitwidth. +func AsSetMultimap(s adt.Store, r cid.Cid, outerBitwidth, innerBitwidth int) (*SetMultimap, error) { + m, err := adt.AsMap(s, r, outerBitwidth) + if err != nil { + return nil, err + } + return &SetMultimap{mp: m, store: s, innerBitwidth: innerBitwidth}, nil +} + +// Creates a new map backed by an empty HAMT and flushes it to the store. +// Both inner and outer HAMTs have branching factor 2^bitwidth. +func MakeEmptySetMultimap(s adt.Store, bitwidth int) (*SetMultimap, error) { + m, err := adt.MakeEmptyMap(s, bitwidth) + if err != nil { + return nil, err + } + return &SetMultimap{mp: m, store: s, innerBitwidth: bitwidth}, nil +} + +// Writes a new empty map to the store and returns its CID. +func StoreEmptySetMultimap(s adt.Store, bitwidth int) (cid.Cid, error) { + mm, err := MakeEmptySetMultimap(s, bitwidth) + if err != nil { + return cid.Undef, err + } + return mm.Root() +} + +// Returns the root cid of the underlying HAMT. +func (mm *SetMultimap) Root() (cid.Cid, error) { + return mm.mp.Root() +} + +func parseDealKey(s string) (abi.DealID, error) { + key, err := abi.ParseUIntKey(s) + return abi.DealID(key), err +} + +func (mm *SetMultimap) get(key abi.Keyer) (*adt.Set, bool, error) { + var setRoot cbg.CborCid + found, err := mm.mp.Get(key, &setRoot) + if err != nil { + return nil, false, xerrors.Errorf("failed to load set key: %v: %w", key, err) + } + var set *adt.Set + if found { + set, err = adt.AsSet(mm.store, cid.Cid(setRoot), mm.innerBitwidth) + if err != nil { + return nil, false, err + } + } + return set, found, nil +} + +// Iterates all entries for a key, iteration halts if the function returns an error. +func (mm *SetMultimap) ForEach(epoch abi.ChainEpoch, fn func(id abi.DealID) error) error { + set, found, err := mm.get(abi.UIntKey(uint64(epoch))) + if err != nil { + return err + } + if found { + return set.ForEach(func(k string) error { + v, err := parseDealKey(k) + if err != nil { + return err + } + return fn(v) + }) + } + return nil +} diff --git a/builtin/v18/migration/system.go b/builtin/v18/migration/system.go new file mode 100644 index 00000000..89da9423 --- /dev/null +++ b/builtin/v18/migration/system.go @@ -0,0 +1,40 @@ +package migration + +import ( + "context" + + system18 "github.com/filecoin-project/go-state-types/builtin/v18/system" + + "github.com/filecoin-project/go-state-types/migration" + + "github.com/ipfs/go-cid" + cbor "github.com/ipfs/go-ipld-cbor" +) + +// System Actor migrator +type systemActorMigrator struct { + OutCodeCID cid.Cid + ManifestData cid.Cid +} + +func (m systemActorMigrator) MigratedCodeCID() cid.Cid { + return m.OutCodeCID +} + +func (m systemActorMigrator) MigrateState(ctx context.Context, store cbor.IpldStore, in migration.ActorMigrationInput) (*migration.ActorMigrationResult, error) { + // The ManifestData itself is already in the blockstore + state := system18.State{BuiltinActors: m.ManifestData} + stateHead, err := store.Put(ctx, &state) + if err != nil { + return nil, err + } + + return &migration.ActorMigrationResult{ + NewCodeCID: m.OutCodeCID, + NewHead: stateHead, + }, nil +} + +func (m systemActorMigrator) Deferred() bool { + return false +} diff --git a/builtin/v18/migration/top.go b/builtin/v18/migration/top.go new file mode 100644 index 00000000..fdbd5534 --- /dev/null +++ b/builtin/v18/migration/top.go @@ -0,0 +1,104 @@ +package migration + +import ( + "context" + + adt14 "github.com/filecoin-project/go-state-types/builtin/v14/util/adt" + + system17 "github.com/filecoin-project/go-state-types/builtin/v17/system" + + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/builtin" + "github.com/filecoin-project/go-state-types/manifest" + "github.com/filecoin-project/go-state-types/migration" + + "github.com/ipfs/go-cid" + cbor "github.com/ipfs/go-ipld-cbor" + "golang.org/x/xerrors" +) + +// MigrateStateTree Migrates the filecoin state tree starting from the global state tree and upgrading all actor state. +// The store must support concurrent writes (even if the configured worker count is 1). +func MigrateStateTree(ctx context.Context, store cbor.IpldStore, newManifestCID cid.Cid, actorsRootIn cid.Cid, priorEpoch abi.ChainEpoch, cfg migration.Config, log migration.Logger, cache migration.MigrationCache) (cid.Cid, error) { + if cfg.MaxWorkers <= 0 { + return cid.Undef, xerrors.Errorf("invalid migration config with %d workers", cfg.MaxWorkers) + } + + adtStore := adt14.WrapStore(ctx, store) + + // Load input and output state trees + actorsIn, err := builtin.LoadTree(adtStore, actorsRootIn) + if err != nil { + return cid.Undef, xerrors.Errorf("loading state tree: %w", err) + } + + // load old manifest data + systemActor, ok, err := actorsIn.GetActorV5(builtin.SystemActorAddr) + if err != nil { + return cid.Undef, xerrors.Errorf("failed to get system actor: %w", err) + } + + if !ok { + return cid.Undef, xerrors.New("didn't find system actor") + } + + var systemState system17.State + if err := store.Get(ctx, systemActor.Head, &systemState); err != nil { + return cid.Undef, xerrors.Errorf("failed to get system actor state: %w", err) + } + + var oldManifestData manifest.ManifestData + if err := store.Get(ctx, systemState.BuiltinActors, &oldManifestData); err != nil { + return cid.Undef, xerrors.Errorf("failed to get old manifest data: %w", err) + } + + // load new manifest + var newManifest manifest.Manifest + if err := adtStore.Get(ctx, newManifestCID, &newManifest); err != nil { + return cid.Undef, xerrors.Errorf("error reading actor manifest: %w", err) + } + + if err := newManifest.Load(ctx, adtStore); err != nil { + return cid.Undef, xerrors.Errorf("error loading actor manifest: %w", err) + } + + // Maps prior version code CIDs to migration functions. + migrations := make(map[cid.Cid]migration.ActorMigration) + // Set of prior version code CIDs for actors to defer during iteration, for explicit migration afterwards. + deferredCodeIDs := make(map[cid.Cid]struct{}) + + for _, oldEntry := range oldManifestData.Entries { + newCodeCID, ok := newManifest.Get(oldEntry.Name) + if !ok { + return cid.Undef, xerrors.Errorf("code cid for %s actor not found in new manifest", oldEntry.Name) + } + migrations[oldEntry.Code] = migration.CachedMigration(cache, migration.CodeMigrator{OutCodeCID: newCodeCID}) + } + + // migrations that migrate both code and state, override entries in `migrations` + + // The System Actor + + newSystemCodeCID, ok := newManifest.Get(manifest.SystemKey) + if !ok { + return cid.Undef, xerrors.Errorf("code cid for system actor not found in new manifest") + } + + migrations[systemActor.Code] = systemActorMigrator{OutCodeCID: newSystemCodeCID, ManifestData: newManifest.Data} + + if len(migrations)+len(deferredCodeIDs) != len(oldManifestData.Entries) { + return cid.Undef, xerrors.Errorf("incomplete migration specification with %d code CIDs, need %d", len(migrations)+len(deferredCodeIDs), len(oldManifestData.Entries)) + } + + actorsOut, err := migration.RunMigration(ctx, cfg, cache, store, log, actorsIn, migrations) + if err != nil { + return cid.Undef, xerrors.Errorf("failed to run migration: %w", err) + } + + outCid, err := actorsOut.Flush() + if err != nil { + return cid.Undef, xerrors.Errorf("failed to flush actorsOut: %w", err) + } + + return outCid, nil +} diff --git a/builtin/v18/miner/cbor_gen.go b/builtin/v18/miner/cbor_gen.go new file mode 100644 index 00000000..8ee3e78a --- /dev/null +++ b/builtin/v18/miner/cbor_gen.go @@ -0,0 +1,10071 @@ +// Code generated by github.com/whyrusleeping/cbor-gen. DO NOT EDIT. + +package miner + +import ( + "fmt" + "io" + "math" + "sort" + + address "github.com/filecoin-project/go-address" + abi "github.com/filecoin-project/go-state-types/abi" + big "github.com/filecoin-project/go-state-types/big" + verifreg "github.com/filecoin-project/go-state-types/builtin/v18/verifreg" + proof "github.com/filecoin-project/go-state-types/proof" + cid "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" + xerrors "golang.org/x/xerrors" +) + +var _ = xerrors.Errorf +var _ = cid.Undef +var _ = math.E +var _ = sort.Sort + +var lengthBufState = []byte{143} + +func (t *State) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufState); err != nil { + return err + } + + // t.Info (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.Info); err != nil { + return xerrors.Errorf("failed to write cid field t.Info: %w", err) + } + + // t.PreCommitDeposits (big.Int) (struct) + if err := t.PreCommitDeposits.MarshalCBOR(cw); err != nil { + return err + } + + // t.LockedFunds (big.Int) (struct) + if err := t.LockedFunds.MarshalCBOR(cw); err != nil { + return err + } + + // t.VestingFunds (miner.VestingFunds) (struct) + if err := t.VestingFunds.MarshalCBOR(cw); err != nil { + return err + } + + // t.FeeDebt (big.Int) (struct) + if err := t.FeeDebt.MarshalCBOR(cw); err != nil { + return err + } + + // t.InitialPledge (big.Int) (struct) + if err := t.InitialPledge.MarshalCBOR(cw); err != nil { + return err + } + + // t.PreCommittedSectors (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.PreCommittedSectors); err != nil { + return xerrors.Errorf("failed to write cid field t.PreCommittedSectors: %w", err) + } + + // t.PreCommittedSectorsCleanUp (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.PreCommittedSectorsCleanUp); err != nil { + return xerrors.Errorf("failed to write cid field t.PreCommittedSectorsCleanUp: %w", err) + } + + // t.AllocatedSectors (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.AllocatedSectors); err != nil { + return xerrors.Errorf("failed to write cid field t.AllocatedSectors: %w", err) + } + + // t.Sectors (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.Sectors); err != nil { + return xerrors.Errorf("failed to write cid field t.Sectors: %w", err) + } + + // t.ProvingPeriodStart (abi.ChainEpoch) (int64) + if t.ProvingPeriodStart >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.ProvingPeriodStart)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.ProvingPeriodStart-1)); err != nil { + return err + } + } + + // t.CurrentDeadline (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.CurrentDeadline)); err != nil { + return err + } + + // t.Deadlines (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.Deadlines); err != nil { + return xerrors.Errorf("failed to write cid field t.Deadlines: %w", err) + } + + // t.EarlyTerminations (bitfield.BitField) (struct) + if err := t.EarlyTerminations.MarshalCBOR(cw); err != nil { + return err + } + + // t.DeadlineCronActive (bool) (bool) + if err := cbg.WriteBool(w, t.DeadlineCronActive); err != nil { + return err + } + return nil +} + +func (t *State) UnmarshalCBOR(r io.Reader) (err error) { + *t = State{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 15 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Info (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.Info: %w", err) + } + + t.Info = c + + } + // t.PreCommitDeposits (big.Int) (struct) + + { + + if err := t.PreCommitDeposits.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.PreCommitDeposits: %w", err) + } + + } + // t.LockedFunds (big.Int) (struct) + + { + + if err := t.LockedFunds.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.LockedFunds: %w", err) + } + + } + // t.VestingFunds (miner.VestingFunds) (struct) + + { + + b, err := cr.ReadByte() + if err != nil { + return err + } + if b != cbg.CborNull[0] { + if err := cr.UnreadByte(); err != nil { + return err + } + t.VestingFunds = new(VestingFunds) + if err := t.VestingFunds.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.VestingFunds pointer: %w", err) + } + } + + } + // t.FeeDebt (big.Int) (struct) + + { + + if err := t.FeeDebt.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.FeeDebt: %w", err) + } + + } + // t.InitialPledge (big.Int) (struct) + + { + + if err := t.InitialPledge.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.InitialPledge: %w", err) + } + + } + // t.PreCommittedSectors (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.PreCommittedSectors: %w", err) + } + + t.PreCommittedSectors = c + + } + // t.PreCommittedSectorsCleanUp (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.PreCommittedSectorsCleanUp: %w", err) + } + + t.PreCommittedSectorsCleanUp = c + + } + // t.AllocatedSectors (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.AllocatedSectors: %w", err) + } + + t.AllocatedSectors = c + + } + // t.Sectors (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.Sectors: %w", err) + } + + t.Sectors = c + + } + // t.ProvingPeriodStart (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.ProvingPeriodStart = abi.ChainEpoch(extraI) + } + // t.CurrentDeadline (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.CurrentDeadline = uint64(extra) + + } + // t.Deadlines (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.Deadlines: %w", err) + } + + t.Deadlines = c + + } + // t.EarlyTerminations (bitfield.BitField) (struct) + + { + + if err := t.EarlyTerminations.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.EarlyTerminations: %w", err) + } + + } + // t.DeadlineCronActive (bool) (bool) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajOther { + return fmt.Errorf("booleans must be major type 7") + } + switch extra { + case 20: + t.DeadlineCronActive = false + case 21: + t.DeadlineCronActive = true + default: + return fmt.Errorf("booleans are either major type 7, value 20 or 21 (got %d)", extra) + } + return nil +} + +var lengthBufMinerInfo = []byte{142} + +func (t *MinerInfo) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufMinerInfo); err != nil { + return err + } + + // t.Owner (address.Address) (struct) + if err := t.Owner.MarshalCBOR(cw); err != nil { + return err + } + + // t.Worker (address.Address) (struct) + if err := t.Worker.MarshalCBOR(cw); err != nil { + return err + } + + // t.ControlAddresses ([]address.Address) (slice) + if len(t.ControlAddresses) > 8192 { + return xerrors.Errorf("Slice value in field t.ControlAddresses was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.ControlAddresses))); err != nil { + return err + } + for _, v := range t.ControlAddresses { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + + // t.PendingWorkerKey (miner.WorkerKeyChange) (struct) + if err := t.PendingWorkerKey.MarshalCBOR(cw); err != nil { + return err + } + + // t.PeerId ([]uint8) (slice) + if len(t.PeerId) > 2097152 { + return xerrors.Errorf("Byte array in field t.PeerId was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.PeerId))); err != nil { + return err + } + + if _, err := cw.Write(t.PeerId); err != nil { + return err + } + + // t.Multiaddrs ([][]uint8) (slice) + if len(t.Multiaddrs) > 8192 { + return xerrors.Errorf("Slice value in field t.Multiaddrs was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Multiaddrs))); err != nil { + return err + } + for _, v := range t.Multiaddrs { + if len(v) > 2097152 { + return xerrors.Errorf("Byte array in field v was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(v))); err != nil { + return err + } + + if _, err := cw.Write(v); err != nil { + return err + } + + } + + // t.WindowPoStProofType (abi.RegisteredPoStProof) (int64) + if t.WindowPoStProofType >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.WindowPoStProofType)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.WindowPoStProofType-1)); err != nil { + return err + } + } + + // t.SectorSize (abi.SectorSize) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SectorSize)); err != nil { + return err + } + + // t.WindowPoStPartitionSectors (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.WindowPoStPartitionSectors)); err != nil { + return err + } + + // t.ConsensusFaultElapsed (abi.ChainEpoch) (int64) + if t.ConsensusFaultElapsed >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.ConsensusFaultElapsed)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.ConsensusFaultElapsed-1)); err != nil { + return err + } + } + + // t.PendingOwnerAddress (address.Address) (struct) + if err := t.PendingOwnerAddress.MarshalCBOR(cw); err != nil { + return err + } + + // t.Beneficiary (address.Address) (struct) + if err := t.Beneficiary.MarshalCBOR(cw); err != nil { + return err + } + + // t.BeneficiaryTerm (miner.BeneficiaryTerm) (struct) + if err := t.BeneficiaryTerm.MarshalCBOR(cw); err != nil { + return err + } + + // t.PendingBeneficiaryTerm (miner.PendingBeneficiaryChange) (struct) + if err := t.PendingBeneficiaryTerm.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *MinerInfo) UnmarshalCBOR(r io.Reader) (err error) { + *t = MinerInfo{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 14 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Owner (address.Address) (struct) + + { + + if err := t.Owner.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Owner: %w", err) + } + + } + // t.Worker (address.Address) (struct) + + { + + if err := t.Worker.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Worker: %w", err) + } + + } + // t.ControlAddresses ([]address.Address) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.ControlAddresses: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.ControlAddresses = make([]address.Address, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.ControlAddresses[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ControlAddresses[i]: %w", err) + } + + } + + } + } + // t.PendingWorkerKey (miner.WorkerKeyChange) (struct) + + { + + b, err := cr.ReadByte() + if err != nil { + return err + } + if b != cbg.CborNull[0] { + if err := cr.UnreadByte(); err != nil { + return err + } + t.PendingWorkerKey = new(WorkerKeyChange) + if err := t.PendingWorkerKey.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.PendingWorkerKey pointer: %w", err) + } + } + + } + // t.PeerId ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.PeerId: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.PeerId = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.PeerId); err != nil { + return err + } + + // t.Multiaddrs ([][]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Multiaddrs: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Multiaddrs = make([][]uint8, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.Multiaddrs[i]: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.Multiaddrs[i] = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.Multiaddrs[i]); err != nil { + return err + } + + } + } + // t.WindowPoStProofType (abi.RegisteredPoStProof) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.WindowPoStProofType = abi.RegisteredPoStProof(extraI) + } + // t.SectorSize (abi.SectorSize) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.SectorSize = abi.SectorSize(extra) + + } + // t.WindowPoStPartitionSectors (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.WindowPoStPartitionSectors = uint64(extra) + + } + // t.ConsensusFaultElapsed (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.ConsensusFaultElapsed = abi.ChainEpoch(extraI) + } + // t.PendingOwnerAddress (address.Address) (struct) + + { + + b, err := cr.ReadByte() + if err != nil { + return err + } + if b != cbg.CborNull[0] { + if err := cr.UnreadByte(); err != nil { + return err + } + t.PendingOwnerAddress = new(address.Address) + if err := t.PendingOwnerAddress.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.PendingOwnerAddress pointer: %w", err) + } + } + + } + // t.Beneficiary (address.Address) (struct) + + { + + if err := t.Beneficiary.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Beneficiary: %w", err) + } + + } + // t.BeneficiaryTerm (miner.BeneficiaryTerm) (struct) + + { + + if err := t.BeneficiaryTerm.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.BeneficiaryTerm: %w", err) + } + + } + // t.PendingBeneficiaryTerm (miner.PendingBeneficiaryChange) (struct) + + { + + b, err := cr.ReadByte() + if err != nil { + return err + } + if b != cbg.CborNull[0] { + if err := cr.UnreadByte(); err != nil { + return err + } + t.PendingBeneficiaryTerm = new(PendingBeneficiaryChange) + if err := t.PendingBeneficiaryTerm.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.PendingBeneficiaryTerm pointer: %w", err) + } + } + + } + return nil +} + +var lengthBufDeadlines = []byte{129} + +func (t *Deadlines) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufDeadlines); err != nil { + return err + } + + // t.Due ([48]cid.Cid) (array) + if len(t.Due) > 8192 { + return xerrors.Errorf("Slice value in field t.Due was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Due))); err != nil { + return err + } + for _, v := range t.Due { + + if err := cbg.WriteCid(cw, v); err != nil { + return xerrors.Errorf("failed to write cid field v: %w", err) + } + + } + return nil +} + +func (t *Deadlines) UnmarshalCBOR(r io.Reader) (err error) { + *t = Deadlines{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Due ([48]cid.Cid) (array) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Due: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + if extra != 48 { + return fmt.Errorf("expected array to have 48 elements") + } + + t.Due = [48]cid.Cid{} + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.Due[i]: %w", err) + } + + t.Due[i] = c + + } + } + } + + return nil +} + +var lengthBufDeadline = []byte{141} + +func (t *Deadline) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufDeadline); err != nil { + return err + } + + // t.Partitions (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.Partitions); err != nil { + return xerrors.Errorf("failed to write cid field t.Partitions: %w", err) + } + + // t.ExpirationsEpochs (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.ExpirationsEpochs); err != nil { + return xerrors.Errorf("failed to write cid field t.ExpirationsEpochs: %w", err) + } + + // t.PartitionsPoSted (bitfield.BitField) (struct) + if err := t.PartitionsPoSted.MarshalCBOR(cw); err != nil { + return err + } + + // t.EarlyTerminations (bitfield.BitField) (struct) + if err := t.EarlyTerminations.MarshalCBOR(cw); err != nil { + return err + } + + // t.LiveSectors (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.LiveSectors)); err != nil { + return err + } + + // t.TotalSectors (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.TotalSectors)); err != nil { + return err + } + + // t.FaultyPower (miner.PowerPair) (struct) + if err := t.FaultyPower.MarshalCBOR(cw); err != nil { + return err + } + + // t.OptimisticPoStSubmissions (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.OptimisticPoStSubmissions); err != nil { + return xerrors.Errorf("failed to write cid field t.OptimisticPoStSubmissions: %w", err) + } + + // t.SectorsSnapshot (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.SectorsSnapshot); err != nil { + return xerrors.Errorf("failed to write cid field t.SectorsSnapshot: %w", err) + } + + // t.PartitionsSnapshot (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.PartitionsSnapshot); err != nil { + return xerrors.Errorf("failed to write cid field t.PartitionsSnapshot: %w", err) + } + + // t.OptimisticPoStSubmissionsSnapshot (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.OptimisticPoStSubmissionsSnapshot); err != nil { + return xerrors.Errorf("failed to write cid field t.OptimisticPoStSubmissionsSnapshot: %w", err) + } + + // t.LivePower (miner.PowerPair) (struct) + if err := t.LivePower.MarshalCBOR(cw); err != nil { + return err + } + + // t.DailyFee (big.Int) (struct) + if err := t.DailyFee.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *Deadline) UnmarshalCBOR(r io.Reader) (err error) { + *t = Deadline{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 13 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Partitions (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.Partitions: %w", err) + } + + t.Partitions = c + + } + // t.ExpirationsEpochs (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.ExpirationsEpochs: %w", err) + } + + t.ExpirationsEpochs = c + + } + // t.PartitionsPoSted (bitfield.BitField) (struct) + + { + + if err := t.PartitionsPoSted.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.PartitionsPoSted: %w", err) + } + + } + // t.EarlyTerminations (bitfield.BitField) (struct) + + { + + if err := t.EarlyTerminations.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.EarlyTerminations: %w", err) + } + + } + // t.LiveSectors (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.LiveSectors = uint64(extra) + + } + // t.TotalSectors (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.TotalSectors = uint64(extra) + + } + // t.FaultyPower (miner.PowerPair) (struct) + + { + + if err := t.FaultyPower.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.FaultyPower: %w", err) + } + + } + // t.OptimisticPoStSubmissions (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.OptimisticPoStSubmissions: %w", err) + } + + t.OptimisticPoStSubmissions = c + + } + // t.SectorsSnapshot (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.SectorsSnapshot: %w", err) + } + + t.SectorsSnapshot = c + + } + // t.PartitionsSnapshot (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.PartitionsSnapshot: %w", err) + } + + t.PartitionsSnapshot = c + + } + // t.OptimisticPoStSubmissionsSnapshot (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.OptimisticPoStSubmissionsSnapshot: %w", err) + } + + t.OptimisticPoStSubmissionsSnapshot = c + + } + // t.LivePower (miner.PowerPair) (struct) + + { + + if err := t.LivePower.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.LivePower: %w", err) + } + + } + // t.DailyFee (big.Int) (struct) + + { + + if err := t.DailyFee.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.DailyFee: %w", err) + } + + } + return nil +} + +var lengthBufPartition = []byte{139} + +func (t *Partition) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufPartition); err != nil { + return err + } + + // t.Sectors (bitfield.BitField) (struct) + if err := t.Sectors.MarshalCBOR(cw); err != nil { + return err + } + + // t.Unproven (bitfield.BitField) (struct) + if err := t.Unproven.MarshalCBOR(cw); err != nil { + return err + } + + // t.Faults (bitfield.BitField) (struct) + if err := t.Faults.MarshalCBOR(cw); err != nil { + return err + } + + // t.Recoveries (bitfield.BitField) (struct) + if err := t.Recoveries.MarshalCBOR(cw); err != nil { + return err + } + + // t.Terminated (bitfield.BitField) (struct) + if err := t.Terminated.MarshalCBOR(cw); err != nil { + return err + } + + // t.ExpirationsEpochs (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.ExpirationsEpochs); err != nil { + return xerrors.Errorf("failed to write cid field t.ExpirationsEpochs: %w", err) + } + + // t.EarlyTerminated (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.EarlyTerminated); err != nil { + return xerrors.Errorf("failed to write cid field t.EarlyTerminated: %w", err) + } + + // t.LivePower (miner.PowerPair) (struct) + if err := t.LivePower.MarshalCBOR(cw); err != nil { + return err + } + + // t.UnprovenPower (miner.PowerPair) (struct) + if err := t.UnprovenPower.MarshalCBOR(cw); err != nil { + return err + } + + // t.FaultyPower (miner.PowerPair) (struct) + if err := t.FaultyPower.MarshalCBOR(cw); err != nil { + return err + } + + // t.RecoveringPower (miner.PowerPair) (struct) + if err := t.RecoveringPower.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *Partition) UnmarshalCBOR(r io.Reader) (err error) { + *t = Partition{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.Sectors (bitfield.BitField) (struct) + + { + + if err := t.Sectors.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Sectors: %w", err) + } + + } + // t.Unproven (bitfield.BitField) (struct) + + { + + if err := t.Unproven.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Unproven: %w", err) + } + + } + // t.Faults (bitfield.BitField) (struct) + + { + + if err := t.Faults.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Faults: %w", err) + } + + } + // t.Recoveries (bitfield.BitField) (struct) + + { + + if err := t.Recoveries.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Recoveries: %w", err) + } + + } + // t.Terminated (bitfield.BitField) (struct) + + { + + if err := t.Terminated.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Terminated: %w", err) + } + + } + // t.ExpirationsEpochs (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.ExpirationsEpochs: %w", err) + } + + t.ExpirationsEpochs = c + + } + // t.EarlyTerminated (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.EarlyTerminated: %w", err) + } + + t.EarlyTerminated = c + + } + // t.LivePower (miner.PowerPair) (struct) + + { + + if err := t.LivePower.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.LivePower: %w", err) + } + + } + // t.UnprovenPower (miner.PowerPair) (struct) + + { + + if err := t.UnprovenPower.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.UnprovenPower: %w", err) + } + + } + // t.FaultyPower (miner.PowerPair) (struct) + + { + + if err := t.FaultyPower.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.FaultyPower: %w", err) + } + + } + // t.RecoveringPower (miner.PowerPair) (struct) + + { + + if err := t.RecoveringPower.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.RecoveringPower: %w", err) + } + + } + return nil +} + +var lengthBufExpirationSet = []byte{134} + +func (t *ExpirationSet) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufExpirationSet); err != nil { + return err + } + + // t.OnTimeSectors (bitfield.BitField) (struct) + if err := t.OnTimeSectors.MarshalCBOR(cw); err != nil { + return err + } + + // t.EarlySectors (bitfield.BitField) (struct) + if err := t.EarlySectors.MarshalCBOR(cw); err != nil { + return err + } + + // t.OnTimePledge (big.Int) (struct) + if err := t.OnTimePledge.MarshalCBOR(cw); err != nil { + return err + } + + // t.ActivePower (miner.PowerPair) (struct) + if err := t.ActivePower.MarshalCBOR(cw); err != nil { + return err + } + + // t.FaultyPower (miner.PowerPair) (struct) + if err := t.FaultyPower.MarshalCBOR(cw); err != nil { + return err + } + + // t.FeeDeduction (big.Int) (struct) + if err := t.FeeDeduction.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *ExpirationSet) UnmarshalCBOR(r io.Reader) (err error) { + *t = ExpirationSet{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra > 6 { + return fmt.Errorf("cbor input has too many fields %d > 6", extra) + } + + if extra < 5 { + return fmt.Errorf("cbor input has too few fields %d < 5", extra) + } + + fieldCount := extra + + // t.OnTimeSectors (bitfield.BitField) (struct) + + { + + if err := t.OnTimeSectors.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.OnTimeSectors: %w", err) + } + + } + // t.EarlySectors (bitfield.BitField) (struct) + + { + + if err := t.EarlySectors.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.EarlySectors: %w", err) + } + + } + // t.OnTimePledge (big.Int) (struct) + + { + + if err := t.OnTimePledge.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.OnTimePledge: %w", err) + } + + } + // t.ActivePower (miner.PowerPair) (struct) + + { + + if err := t.ActivePower.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ActivePower: %w", err) + } + + } + // t.FaultyPower (miner.PowerPair) (struct) + + { + + if err := t.FaultyPower.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.FaultyPower: %w", err) + } + + } + // t.FeeDeduction (big.Int) (struct) + if fieldCount < 6 { + return nil + } + + { + + if err := t.FeeDeduction.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.FeeDeduction: %w", err) + } + + } + return nil +} + +var lengthBufPowerPair = []byte{130} + +func (t *PowerPair) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufPowerPair); err != nil { + return err + } + + // t.Raw (big.Int) (struct) + if err := t.Raw.MarshalCBOR(cw); err != nil { + return err + } + + // t.QA (big.Int) (struct) + if err := t.QA.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *PowerPair) UnmarshalCBOR(r io.Reader) (err error) { + *t = PowerPair{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Raw (big.Int) (struct) + + { + + if err := t.Raw.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Raw: %w", err) + } + + } + // t.QA (big.Int) (struct) + + { + + if err := t.QA.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.QA: %w", err) + } + + } + return nil +} + +var lengthBufSectorPreCommitOnChainInfo = []byte{131} + +func (t *SectorPreCommitOnChainInfo) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufSectorPreCommitOnChainInfo); err != nil { + return err + } + + // t.Info (miner.SectorPreCommitInfo) (struct) + if err := t.Info.MarshalCBOR(cw); err != nil { + return err + } + + // t.PreCommitDeposit (big.Int) (struct) + if err := t.PreCommitDeposit.MarshalCBOR(cw); err != nil { + return err + } + + // t.PreCommitEpoch (abi.ChainEpoch) (int64) + if t.PreCommitEpoch >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.PreCommitEpoch)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.PreCommitEpoch-1)); err != nil { + return err + } + } + + return nil +} + +func (t *SectorPreCommitOnChainInfo) UnmarshalCBOR(r io.Reader) (err error) { + *t = SectorPreCommitOnChainInfo{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.Info (miner.SectorPreCommitInfo) (struct) + + { + + if err := t.Info.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Info: %w", err) + } + + } + // t.PreCommitDeposit (big.Int) (struct) + + { + + if err := t.PreCommitDeposit.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.PreCommitDeposit: %w", err) + } + + } + // t.PreCommitEpoch (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.PreCommitEpoch = abi.ChainEpoch(extraI) + } + return nil +} + +var lengthBufSectorPreCommitInfo = []byte{135} + +func (t *SectorPreCommitInfo) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufSectorPreCommitInfo); err != nil { + return err + } + + // t.SealProof (abi.RegisteredSealProof) (int64) + if t.SealProof >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SealProof)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.SealProof-1)); err != nil { + return err + } + } + + // t.SectorNumber (abi.SectorNumber) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SectorNumber)); err != nil { + return err + } + + // t.SealedCID (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.SealedCID); err != nil { + return xerrors.Errorf("failed to write cid field t.SealedCID: %w", err) + } + + // t.SealRandEpoch (abi.ChainEpoch) (int64) + if t.SealRandEpoch >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SealRandEpoch)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.SealRandEpoch-1)); err != nil { + return err + } + } + + // t.DealIDs ([]abi.DealID) (slice) + if len(t.DealIDs) > 8192 { + return xerrors.Errorf("Slice value in field t.DealIDs was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.DealIDs))); err != nil { + return err + } + for _, v := range t.DealIDs { + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(v)); err != nil { + return err + } + + } + + // t.Expiration (abi.ChainEpoch) (int64) + if t.Expiration >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Expiration)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.Expiration-1)); err != nil { + return err + } + } + + // t.UnsealedCid (cid.Cid) (struct) + + if t.UnsealedCid == nil { + if _, err := cw.Write(cbg.CborNull); err != nil { + return err + } + } else { + if err := cbg.WriteCid(cw, *t.UnsealedCid); err != nil { + return xerrors.Errorf("failed to write cid field t.UnsealedCid: %w", err) + } + } + + return nil +} + +func (t *SectorPreCommitInfo) UnmarshalCBOR(r io.Reader) (err error) { + *t = SectorPreCommitInfo{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 7 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.SealProof (abi.RegisteredSealProof) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.SealProof = abi.RegisteredSealProof(extraI) + } + // t.SectorNumber (abi.SectorNumber) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.SectorNumber = abi.SectorNumber(extra) + + } + // t.SealedCID (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.SealedCID: %w", err) + } + + t.SealedCID = c + + } + // t.SealRandEpoch (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.SealRandEpoch = abi.ChainEpoch(extraI) + } + // t.DealIDs ([]abi.DealID) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + 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++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.DealIDs[i] = abi.DealID(extra) + + } + + } + } + // t.Expiration (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.Expiration = abi.ChainEpoch(extraI) + } + // t.UnsealedCid (cid.Cid) (struct) + + { + + b, err := cr.ReadByte() + if err != nil { + return err + } + if b != cbg.CborNull[0] { + if err := cr.UnreadByte(); err != nil { + return err + } + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.UnsealedCid: %w", err) + } + + t.UnsealedCid = &c + } + + } + return nil +} + +var lengthBufSectorOnChainInfo = []byte{144} + +func (t *SectorOnChainInfo) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufSectorOnChainInfo); err != nil { + return err + } + + // t.SectorNumber (abi.SectorNumber) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SectorNumber)); err != nil { + return err + } + + // t.SealProof (abi.RegisteredSealProof) (int64) + if t.SealProof >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SealProof)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.SealProof-1)); err != nil { + return err + } + } + + // t.SealedCID (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.SealedCID); err != nil { + return xerrors.Errorf("failed to write cid field t.SealedCID: %w", err) + } + + // t.DeprecatedDealIDs ([]abi.DealID) (slice) + if len(t.DeprecatedDealIDs) > 8192 { + return xerrors.Errorf("Slice value in field t.DeprecatedDealIDs was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.DeprecatedDealIDs))); err != nil { + return err + } + for _, v := range t.DeprecatedDealIDs { + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(v)); err != nil { + return err + } + + } + + // t.Activation (abi.ChainEpoch) (int64) + if t.Activation >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Activation)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.Activation-1)); err != nil { + return err + } + } + + // t.Expiration (abi.ChainEpoch) (int64) + if t.Expiration >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Expiration)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.Expiration-1)); err != nil { + return err + } + } + + // t.DealWeight (big.Int) (struct) + if err := t.DealWeight.MarshalCBOR(cw); err != nil { + return err + } + + // t.VerifiedDealWeight (big.Int) (struct) + if err := t.VerifiedDealWeight.MarshalCBOR(cw); err != nil { + return err + } + + // t.InitialPledge (big.Int) (struct) + if err := t.InitialPledge.MarshalCBOR(cw); err != nil { + return err + } + + // t.ExpectedDayReward (big.Int) (struct) + if err := t.ExpectedDayReward.MarshalCBOR(cw); err != nil { + return err + } + + // t.ExpectedStoragePledge (big.Int) (struct) + if err := t.ExpectedStoragePledge.MarshalCBOR(cw); err != nil { + return err + } + + // t.PowerBaseEpoch (abi.ChainEpoch) (int64) + if t.PowerBaseEpoch >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.PowerBaseEpoch)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.PowerBaseEpoch-1)); err != nil { + return err + } + } + + // t.ReplacedDayReward (big.Int) (struct) + if err := t.ReplacedDayReward.MarshalCBOR(cw); err != nil { + return err + } + + // t.SectorKeyCID (cid.Cid) (struct) + + if t.SectorKeyCID == nil { + if _, err := cw.Write(cbg.CborNull); err != nil { + return err + } + } else { + if err := cbg.WriteCid(cw, *t.SectorKeyCID); err != nil { + return xerrors.Errorf("failed to write cid field t.SectorKeyCID: %w", err) + } + } + + // t.Flags (miner.SectorOnChainInfoFlags) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Flags)); err != nil { + return err + } + + // t.DailyFee (big.Int) (struct) + if err := t.DailyFee.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *SectorOnChainInfo) UnmarshalCBOR(r io.Reader) (err error) { + *t = SectorOnChainInfo{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra > 16 { + return fmt.Errorf("cbor input has too many fields %d > 16", extra) + } + + if extra < 15 { + return fmt.Errorf("cbor input has too few fields %d < 15", extra) + } + + fieldCount := extra + + // t.SectorNumber (abi.SectorNumber) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + 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 := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + 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(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.SealedCID: %w", err) + } + + t.SealedCID = c + + } + // t.DeprecatedDealIDs ([]abi.DealID) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.DeprecatedDealIDs: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.DeprecatedDealIDs = make([]abi.DealID, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.DeprecatedDealIDs[i] = abi.DealID(extra) + + } + + } + } + // t.Activation (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + 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 := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + 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(cr); err != nil { + return xerrors.Errorf("unmarshaling t.DealWeight: %w", err) + } + + } + // t.VerifiedDealWeight (big.Int) (struct) + + { + + if err := t.VerifiedDealWeight.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.VerifiedDealWeight: %w", err) + } + + } + // t.InitialPledge (big.Int) (struct) + + { + + if err := t.InitialPledge.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.InitialPledge: %w", err) + } + + } + // t.ExpectedDayReward (big.Int) (struct) + + { + + b, err := cr.ReadByte() + if err != nil { + return err + } + if b != cbg.CborNull[0] { + if err := cr.UnreadByte(); err != nil { + return err + } + t.ExpectedDayReward = new(big.Int) + if err := t.ExpectedDayReward.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ExpectedDayReward pointer: %w", err) + } + } + + } + // t.ExpectedStoragePledge (big.Int) (struct) + + { + + b, err := cr.ReadByte() + if err != nil { + return err + } + if b != cbg.CborNull[0] { + if err := cr.UnreadByte(); err != nil { + return err + } + t.ExpectedStoragePledge = new(big.Int) + if err := t.ExpectedStoragePledge.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ExpectedStoragePledge pointer: %w", err) + } + } + + } + // t.PowerBaseEpoch (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.PowerBaseEpoch = abi.ChainEpoch(extraI) + } + // t.ReplacedDayReward (big.Int) (struct) + + { + + b, err := cr.ReadByte() + if err != nil { + return err + } + if b != cbg.CborNull[0] { + if err := cr.UnreadByte(); err != nil { + return err + } + t.ReplacedDayReward = new(big.Int) + if err := t.ReplacedDayReward.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ReplacedDayReward pointer: %w", err) + } + } + + } + // t.SectorKeyCID (cid.Cid) (struct) + + { + + b, err := cr.ReadByte() + if err != nil { + return err + } + if b != cbg.CborNull[0] { + if err := cr.UnreadByte(); err != nil { + return err + } + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.SectorKeyCID: %w", err) + } + + t.SectorKeyCID = &c + } + + } + // t.Flags (miner.SectorOnChainInfoFlags) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Flags = SectorOnChainInfoFlags(extra) + + } + // t.DailyFee (big.Int) (struct) + if fieldCount < 16 { + return nil + } + + { + + if err := t.DailyFee.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.DailyFee: %w", err) + } + + } + return nil +} + +var lengthBufWorkerKeyChange = []byte{130} + +func (t *WorkerKeyChange) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufWorkerKeyChange); err != nil { + return err + } + + // t.NewWorker (address.Address) (struct) + if err := t.NewWorker.MarshalCBOR(cw); err != nil { + return err + } + + // t.EffectiveAt (abi.ChainEpoch) (int64) + if t.EffectiveAt >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.EffectiveAt)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.EffectiveAt-1)); err != nil { + return err + } + } + + return nil +} + +func (t *WorkerKeyChange) UnmarshalCBOR(r io.Reader) (err error) { + *t = WorkerKeyChange{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.NewWorker (address.Address) (struct) + + { + + if err := t.NewWorker.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.NewWorker: %w", err) + } + + } + // t.EffectiveAt (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.EffectiveAt = abi.ChainEpoch(extraI) + } + return nil +} + +func (t *VestingFundsTail) MarshalCBOR(w io.Writer) error { + cw := cbg.NewCborWriter(w) + + // t.Funds ([]miner.VestingFund) (slice) + if len(t.Funds) > 8192 { + return xerrors.Errorf("Slice value in field t.Funds was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Funds))); err != nil { + return err + } + for _, v := range t.Funds { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *VestingFundsTail) UnmarshalCBOR(r io.Reader) (err error) { + *t = VestingFundsTail{} + + cr := cbg.NewCborReader(r) + var maj byte + var extra uint64 + _ = maj + _ = extra + // t.Funds ([]miner.VestingFund) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Funds: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Funds = make([]VestingFund, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Funds[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Funds[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufVestingFunds = []byte{130} + +func (t *VestingFunds) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufVestingFunds); err != nil { + return err + } + + // t.Head (miner.VestingFund) (struct) + if err := t.Head.MarshalCBOR(cw); err != nil { + return err + } + + // t.Tail (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.Tail); err != nil { + return xerrors.Errorf("failed to write cid field t.Tail: %w", err) + } + + return nil +} + +func (t *VestingFunds) UnmarshalCBOR(r io.Reader) (err error) { + *t = VestingFunds{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Head (miner.VestingFund) (struct) + + { + + if err := t.Head.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Head: %w", err) + } + + } + // t.Tail (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.Tail: %w", err) + } + + t.Tail = c + + } + return nil +} + +var lengthBufVestingFund = []byte{130} + +func (t *VestingFund) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufVestingFund); err != nil { + return err + } + + // t.Epoch (abi.ChainEpoch) (int64) + if t.Epoch >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Epoch)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.Epoch-1)); err != nil { + return err + } + } + + // t.Amount (big.Int) (struct) + if err := t.Amount.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *VestingFund) UnmarshalCBOR(r io.Reader) (err error) { + *t = VestingFund{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Epoch (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.Epoch = abi.ChainEpoch(extraI) + } + // t.Amount (big.Int) (struct) + + { + + if err := t.Amount.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Amount: %w", err) + } + + } + return nil +} + +var lengthBufWindowedPoSt = []byte{130} + +func (t *WindowedPoSt) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufWindowedPoSt); err != nil { + return err + } + + // t.Partitions (bitfield.BitField) (struct) + if err := t.Partitions.MarshalCBOR(cw); err != nil { + return err + } + + // t.Proofs ([]proof.PoStProof) (slice) + if len(t.Proofs) > 8192 { + return xerrors.Errorf("Slice value in field t.Proofs was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Proofs))); err != nil { + return err + } + for _, v := range t.Proofs { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *WindowedPoSt) UnmarshalCBOR(r io.Reader) (err error) { + *t = WindowedPoSt{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Partitions (bitfield.BitField) (struct) + + { + + if err := t.Partitions.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Partitions: %w", err) + } + + } + // t.Proofs ([]proof.PoStProof) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Proofs: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Proofs = make([]proof.PoStProof, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Proofs[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Proofs[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufActiveBeneficiary = []byte{130} + +func (t *ActiveBeneficiary) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufActiveBeneficiary); err != nil { + return err + } + + // t.Beneficiary (address.Address) (struct) + if err := t.Beneficiary.MarshalCBOR(cw); err != nil { + return err + } + + // t.Term (miner.BeneficiaryTerm) (struct) + if err := t.Term.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *ActiveBeneficiary) UnmarshalCBOR(r io.Reader) (err error) { + *t = ActiveBeneficiary{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Beneficiary (address.Address) (struct) + + { + + if err := t.Beneficiary.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Beneficiary: %w", err) + } + + } + // t.Term (miner.BeneficiaryTerm) (struct) + + { + + if err := t.Term.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Term: %w", err) + } + + } + return nil +} + +var lengthBufBeneficiaryTerm = []byte{131} + +func (t *BeneficiaryTerm) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufBeneficiaryTerm); err != nil { + return err + } + + // t.Quota (big.Int) (struct) + if err := t.Quota.MarshalCBOR(cw); err != nil { + return err + } + + // t.UsedQuota (big.Int) (struct) + if err := t.UsedQuota.MarshalCBOR(cw); err != nil { + return err + } + + // t.Expiration (abi.ChainEpoch) (int64) + if t.Expiration >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Expiration)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.Expiration-1)); err != nil { + return err + } + } + + return nil +} + +func (t *BeneficiaryTerm) UnmarshalCBOR(r io.Reader) (err error) { + *t = BeneficiaryTerm{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.Quota (big.Int) (struct) + + { + + if err := t.Quota.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Quota: %w", err) + } + + } + // t.UsedQuota (big.Int) (struct) + + { + + if err := t.UsedQuota.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.UsedQuota: %w", err) + } + + } + // t.Expiration (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.Expiration = abi.ChainEpoch(extraI) + } + return nil +} + +var lengthBufPendingBeneficiaryChange = []byte{133} + +func (t *PendingBeneficiaryChange) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufPendingBeneficiaryChange); err != nil { + return err + } + + // t.NewBeneficiary (address.Address) (struct) + if err := t.NewBeneficiary.MarshalCBOR(cw); err != nil { + return err + } + + // t.NewQuota (big.Int) (struct) + if err := t.NewQuota.MarshalCBOR(cw); err != nil { + return err + } + + // t.NewExpiration (abi.ChainEpoch) (int64) + if t.NewExpiration >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.NewExpiration)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.NewExpiration-1)); err != nil { + return err + } + } + + // t.ApprovedByBeneficiary (bool) (bool) + if err := cbg.WriteBool(w, t.ApprovedByBeneficiary); err != nil { + return err + } + + // t.ApprovedByNominee (bool) (bool) + if err := cbg.WriteBool(w, t.ApprovedByNominee); err != nil { + return err + } + return nil +} + +func (t *PendingBeneficiaryChange) UnmarshalCBOR(r io.Reader) (err error) { + *t = PendingBeneficiaryChange{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 5 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.NewBeneficiary (address.Address) (struct) + + { + + if err := t.NewBeneficiary.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.NewBeneficiary: %w", err) + } + + } + // t.NewQuota (big.Int) (struct) + + { + + if err := t.NewQuota.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.NewQuota: %w", err) + } + + } + // t.NewExpiration (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.NewExpiration = abi.ChainEpoch(extraI) + } + // t.ApprovedByBeneficiary (bool) (bool) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajOther { + return fmt.Errorf("booleans must be major type 7") + } + switch extra { + case 20: + t.ApprovedByBeneficiary = false + case 21: + t.ApprovedByBeneficiary = true + default: + return fmt.Errorf("booleans are either major type 7, value 20 or 21 (got %d)", extra) + } + // t.ApprovedByNominee (bool) (bool) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajOther { + return fmt.Errorf("booleans must be major type 7") + } + switch extra { + case 20: + t.ApprovedByNominee = false + case 21: + t.ApprovedByNominee = true + default: + return fmt.Errorf("booleans are either major type 7, value 20 or 21 (got %d)", extra) + } + return nil +} + +var lengthBufGetControlAddressesReturn = []byte{131} + +func (t *GetControlAddressesReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufGetControlAddressesReturn); err != nil { + return err + } + + // t.Owner (address.Address) (struct) + if err := t.Owner.MarshalCBOR(cw); err != nil { + return err + } + + // t.Worker (address.Address) (struct) + if err := t.Worker.MarshalCBOR(cw); err != nil { + return err + } + + // t.ControlAddrs ([]address.Address) (slice) + if len(t.ControlAddrs) > 8192 { + return xerrors.Errorf("Slice value in field t.ControlAddrs was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.ControlAddrs))); err != nil { + return err + } + for _, v := range t.ControlAddrs { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *GetControlAddressesReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = GetControlAddressesReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.Owner (address.Address) (struct) + + { + + if err := t.Owner.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Owner: %w", err) + } + + } + // t.Worker (address.Address) (struct) + + { + + if err := t.Worker.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Worker: %w", err) + } + + } + // t.ControlAddrs ([]address.Address) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.ControlAddrs: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.ControlAddrs = make([]address.Address, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.ControlAddrs[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ControlAddrs[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufChangeWorkerAddressParams = []byte{130} + +func (t *ChangeWorkerAddressParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufChangeWorkerAddressParams); err != nil { + return err + } + + // t.NewWorker (address.Address) (struct) + if err := t.NewWorker.MarshalCBOR(cw); err != nil { + return err + } + + // t.NewControlAddrs ([]address.Address) (slice) + if len(t.NewControlAddrs) > 8192 { + return xerrors.Errorf("Slice value in field t.NewControlAddrs was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.NewControlAddrs))); err != nil { + return err + } + for _, v := range t.NewControlAddrs { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *ChangeWorkerAddressParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = ChangeWorkerAddressParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.NewWorker (address.Address) (struct) + + { + + if err := t.NewWorker.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.NewWorker: %w", err) + } + + } + // t.NewControlAddrs ([]address.Address) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.NewControlAddrs: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.NewControlAddrs = make([]address.Address, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.NewControlAddrs[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.NewControlAddrs[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufChangePeerIDParams = []byte{129} + +func (t *ChangePeerIDParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufChangePeerIDParams); err != nil { + return err + } + + // t.NewID ([]uint8) (slice) + if len(t.NewID) > 2097152 { + return xerrors.Errorf("Byte array in field t.NewID was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.NewID))); err != nil { + return err + } + + if _, err := cw.Write(t.NewID); err != nil { + return err + } + + return nil +} + +func (t *ChangePeerIDParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = ChangePeerIDParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.NewID ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.NewID: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.NewID = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.NewID); err != nil { + return err + } + + return nil +} + +var lengthBufSubmitWindowedPoStParams = []byte{133} + +func (t *SubmitWindowedPoStParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufSubmitWindowedPoStParams); err != nil { + return err + } + + // t.Deadline (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Deadline)); err != nil { + return err + } + + // t.Partitions ([]miner.PoStPartition) (slice) + if len(t.Partitions) > 8192 { + return xerrors.Errorf("Slice value in field t.Partitions was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Partitions))); err != nil { + return err + } + for _, v := range t.Partitions { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + + // t.Proofs ([]proof.PoStProof) (slice) + if len(t.Proofs) > 8192 { + return xerrors.Errorf("Slice value in field t.Proofs was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Proofs))); err != nil { + return err + } + for _, v := range t.Proofs { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + + // t.ChainCommitEpoch (abi.ChainEpoch) (int64) + if t.ChainCommitEpoch >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.ChainCommitEpoch)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.ChainCommitEpoch-1)); err != nil { + return err + } + } + + // t.ChainCommitRand (abi.Randomness) (slice) + if len(t.ChainCommitRand) > 2097152 { + return xerrors.Errorf("Byte array in field t.ChainCommitRand was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.ChainCommitRand))); err != nil { + return err + } + + if _, err := cw.Write(t.ChainCommitRand); err != nil { + return err + } + + return nil +} + +func (t *SubmitWindowedPoStParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = SubmitWindowedPoStParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 5 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Deadline (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Deadline = uint64(extra) + + } + // t.Partitions ([]miner.PoStPartition) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Partitions: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Partitions = make([]PoStPartition, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Partitions[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Partitions[i]: %w", err) + } + + } + + } + } + // t.Proofs ([]proof.PoStProof) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Proofs: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Proofs = make([]proof.PoStProof, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Proofs[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Proofs[i]: %w", err) + } + + } + + } + } + // t.ChainCommitEpoch (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.ChainCommitEpoch = abi.ChainEpoch(extraI) + } + // t.ChainCommitRand (abi.Randomness) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.ChainCommitRand: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.ChainCommitRand = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.ChainCommitRand); err != nil { + return err + } + + return nil +} + +var lengthBufPreCommitSectorParams = []byte{138} + +func (t *PreCommitSectorParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufPreCommitSectorParams); err != nil { + return err + } + + // t.SealProof (abi.RegisteredSealProof) (int64) + if t.SealProof >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SealProof)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.SealProof-1)); err != nil { + return err + } + } + + // t.SectorNumber (abi.SectorNumber) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SectorNumber)); err != nil { + return err + } + + // t.SealedCID (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.SealedCID); err != nil { + return xerrors.Errorf("failed to write cid field t.SealedCID: %w", err) + } + + // t.SealRandEpoch (abi.ChainEpoch) (int64) + if t.SealRandEpoch >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SealRandEpoch)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.SealRandEpoch-1)); err != nil { + return err + } + } + + // t.DealIDs ([]abi.DealID) (slice) + if len(t.DealIDs) > 8192 { + return xerrors.Errorf("Slice value in field t.DealIDs was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.DealIDs))); err != nil { + return err + } + for _, v := range t.DealIDs { + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(v)); err != nil { + return err + } + + } + + // t.Expiration (abi.ChainEpoch) (int64) + if t.Expiration >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Expiration)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.Expiration-1)); err != nil { + return err + } + } + + // t.ReplaceCapacity (bool) (bool) + if err := cbg.WriteBool(w, t.ReplaceCapacity); err != nil { + return err + } + + // t.ReplaceSectorDeadline (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.ReplaceSectorDeadline)); err != nil { + return err + } + + // t.ReplaceSectorPartition (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.ReplaceSectorPartition)); err != nil { + return err + } + + // t.ReplaceSectorNumber (abi.SectorNumber) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.ReplaceSectorNumber)); err != nil { + return err + } + + return nil +} + +func (t *PreCommitSectorParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = PreCommitSectorParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 10 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.SealProof (abi.RegisteredSealProof) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.SealProof = abi.RegisteredSealProof(extraI) + } + // t.SectorNumber (abi.SectorNumber) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.SectorNumber = abi.SectorNumber(extra) + + } + // t.SealedCID (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.SealedCID: %w", err) + } + + t.SealedCID = c + + } + // t.SealRandEpoch (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.SealRandEpoch = abi.ChainEpoch(extraI) + } + // t.DealIDs ([]abi.DealID) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + 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++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.DealIDs[i] = abi.DealID(extra) + + } + + } + } + // t.Expiration (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.Expiration = abi.ChainEpoch(extraI) + } + // t.ReplaceCapacity (bool) (bool) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajOther { + return fmt.Errorf("booleans must be major type 7") + } + switch extra { + case 20: + t.ReplaceCapacity = false + case 21: + t.ReplaceCapacity = true + default: + return fmt.Errorf("booleans are either major type 7, value 20 or 21 (got %d)", extra) + } + // t.ReplaceSectorDeadline (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.ReplaceSectorDeadline = uint64(extra) + + } + // t.ReplaceSectorPartition (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.ReplaceSectorPartition = uint64(extra) + + } + // t.ReplaceSectorNumber (abi.SectorNumber) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.ReplaceSectorNumber = abi.SectorNumber(extra) + + } + return nil +} + +var lengthBufProveCommitSectorParams = []byte{130} + +func (t *ProveCommitSectorParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufProveCommitSectorParams); err != nil { + return err + } + + // t.SectorNumber (abi.SectorNumber) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SectorNumber)); err != nil { + return err + } + + // t.Proof ([]uint8) (slice) + if len(t.Proof) > 2097152 { + return xerrors.Errorf("Byte array in field t.Proof was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.Proof))); err != nil { + return err + } + + if _, err := cw.Write(t.Proof); err != nil { + return err + } + + return nil +} + +func (t *ProveCommitSectorParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = ProveCommitSectorParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.SectorNumber (abi.SectorNumber) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.SectorNumber = abi.SectorNumber(extra) + + } + // t.Proof ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.Proof: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.Proof = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.Proof); err != nil { + return err + } + + return nil +} + +var lengthBufExtendSectorExpirationParams = []byte{129} + +func (t *ExtendSectorExpirationParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufExtendSectorExpirationParams); err != nil { + return err + } + + // t.Extensions ([]miner.ExpirationExtension) (slice) + if len(t.Extensions) > 8192 { + return xerrors.Errorf("Slice value in field t.Extensions was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Extensions))); err != nil { + return err + } + for _, v := range t.Extensions { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *ExtendSectorExpirationParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = ExtendSectorExpirationParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Extensions ([]miner.ExpirationExtension) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Extensions: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Extensions = make([]ExpirationExtension, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Extensions[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Extensions[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufExtendSectorExpiration2Params = []byte{129} + +func (t *ExtendSectorExpiration2Params) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufExtendSectorExpiration2Params); err != nil { + return err + } + + // t.Extensions ([]miner.ExpirationExtension2) (slice) + if len(t.Extensions) > 8192 { + return xerrors.Errorf("Slice value in field t.Extensions was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Extensions))); err != nil { + return err + } + for _, v := range t.Extensions { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *ExtendSectorExpiration2Params) UnmarshalCBOR(r io.Reader) (err error) { + *t = ExtendSectorExpiration2Params{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Extensions ([]miner.ExpirationExtension2) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Extensions: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Extensions = make([]ExpirationExtension2, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Extensions[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Extensions[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufTerminateSectorsParams = []byte{129} + +func (t *TerminateSectorsParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufTerminateSectorsParams); err != nil { + return err + } + + // t.Terminations ([]miner.TerminationDeclaration) (slice) + if len(t.Terminations) > 8192 { + return xerrors.Errorf("Slice value in field t.Terminations was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Terminations))); err != nil { + return err + } + for _, v := range t.Terminations { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *TerminateSectorsParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = TerminateSectorsParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Terminations ([]miner.TerminationDeclaration) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Terminations: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Terminations = make([]TerminationDeclaration, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Terminations[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Terminations[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufTerminateSectorsReturn = []byte{129} + +func (t *TerminateSectorsReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufTerminateSectorsReturn); err != nil { + return err + } + + // t.Done (bool) (bool) + if err := cbg.WriteBool(w, t.Done); err != nil { + return err + } + return nil +} + +func (t *TerminateSectorsReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = TerminateSectorsReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Done (bool) (bool) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajOther { + return fmt.Errorf("booleans must be major type 7") + } + switch extra { + case 20: + t.Done = false + case 21: + t.Done = true + default: + return fmt.Errorf("booleans are either major type 7, value 20 or 21 (got %d)", extra) + } + return nil +} + +var lengthBufDeclareFaultsParams = []byte{129} + +func (t *DeclareFaultsParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufDeclareFaultsParams); err != nil { + return err + } + + // t.Faults ([]miner.FaultDeclaration) (slice) + if len(t.Faults) > 8192 { + return xerrors.Errorf("Slice value in field t.Faults was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Faults))); err != nil { + return err + } + for _, v := range t.Faults { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *DeclareFaultsParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = DeclareFaultsParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Faults ([]miner.FaultDeclaration) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Faults: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Faults = make([]FaultDeclaration, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Faults[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Faults[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufDeclareFaultsRecoveredParams = []byte{129} + +func (t *DeclareFaultsRecoveredParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufDeclareFaultsRecoveredParams); err != nil { + return err + } + + // t.Recoveries ([]miner.RecoveryDeclaration) (slice) + if len(t.Recoveries) > 8192 { + return xerrors.Errorf("Slice value in field t.Recoveries was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Recoveries))); err != nil { + return err + } + for _, v := range t.Recoveries { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *DeclareFaultsRecoveredParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = DeclareFaultsRecoveredParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Recoveries ([]miner.RecoveryDeclaration) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Recoveries: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Recoveries = make([]RecoveryDeclaration, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Recoveries[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Recoveries[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufDeferredCronEventParams = []byte{131} + +func (t *DeferredCronEventParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufDeferredCronEventParams); err != nil { + return err + } + + // t.EventPayload ([]uint8) (slice) + if len(t.EventPayload) > 2097152 { + return xerrors.Errorf("Byte array in field t.EventPayload was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.EventPayload))); err != nil { + return err + } + + if _, err := cw.Write(t.EventPayload); err != nil { + return err + } + + // t.RewardSmoothed (smoothing.FilterEstimate) (struct) + if err := t.RewardSmoothed.MarshalCBOR(cw); err != nil { + return err + } + + // t.QualityAdjPowerSmoothed (smoothing.FilterEstimate) (struct) + if err := t.QualityAdjPowerSmoothed.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *DeferredCronEventParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = DeferredCronEventParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.EventPayload ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.EventPayload: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.EventPayload = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.EventPayload); err != nil { + return err + } + + // t.RewardSmoothed (smoothing.FilterEstimate) (struct) + + { + + if err := t.RewardSmoothed.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.RewardSmoothed: %w", err) + } + + } + // t.QualityAdjPowerSmoothed (smoothing.FilterEstimate) (struct) + + { + + if err := t.QualityAdjPowerSmoothed.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.QualityAdjPowerSmoothed: %w", err) + } + + } + return nil +} + +var lengthBufCheckSectorProvenParams = []byte{129} + +func (t *CheckSectorProvenParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufCheckSectorProvenParams); err != nil { + return err + } + + // t.SectorNumber (abi.SectorNumber) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SectorNumber)); err != nil { + return err + } + + return nil +} + +func (t *CheckSectorProvenParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = CheckSectorProvenParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.SectorNumber (abi.SectorNumber) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.SectorNumber = abi.SectorNumber(extra) + + } + return nil +} + +var lengthBufApplyRewardParams = []byte{130} + +func (t *ApplyRewardParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufApplyRewardParams); err != nil { + return err + } + + // t.Reward (big.Int) (struct) + if err := t.Reward.MarshalCBOR(cw); err != nil { + return err + } + + // t.Penalty (big.Int) (struct) + if err := t.Penalty.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *ApplyRewardParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = ApplyRewardParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Reward (big.Int) (struct) + + { + + if err := t.Reward.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Reward: %w", err) + } + + } + // t.Penalty (big.Int) (struct) + + { + + if err := t.Penalty.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Penalty: %w", err) + } + + } + return nil +} + +var lengthBufReportConsensusFaultParams = []byte{131} + +func (t *ReportConsensusFaultParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufReportConsensusFaultParams); err != nil { + return err + } + + // t.BlockHeader1 ([]uint8) (slice) + if len(t.BlockHeader1) > 2097152 { + return xerrors.Errorf("Byte array in field t.BlockHeader1 was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.BlockHeader1))); err != nil { + return err + } + + if _, err := cw.Write(t.BlockHeader1); err != nil { + return err + } + + // t.BlockHeader2 ([]uint8) (slice) + if len(t.BlockHeader2) > 2097152 { + return xerrors.Errorf("Byte array in field t.BlockHeader2 was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.BlockHeader2))); err != nil { + return err + } + + if _, err := cw.Write(t.BlockHeader2); err != nil { + return err + } + + // t.BlockHeaderExtra ([]uint8) (slice) + if len(t.BlockHeaderExtra) > 2097152 { + return xerrors.Errorf("Byte array in field t.BlockHeaderExtra was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.BlockHeaderExtra))); err != nil { + return err + } + + if _, err := cw.Write(t.BlockHeaderExtra); err != nil { + return err + } + + return nil +} + +func (t *ReportConsensusFaultParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = ReportConsensusFaultParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.BlockHeader1 ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.BlockHeader1: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.BlockHeader1 = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.BlockHeader1); err != nil { + return err + } + + // t.BlockHeader2 ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.BlockHeader2: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.BlockHeader2 = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.BlockHeader2); err != nil { + return err + } + + // t.BlockHeaderExtra ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.BlockHeaderExtra: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.BlockHeaderExtra = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.BlockHeaderExtra); err != nil { + return err + } + + return nil +} + +var lengthBufWithdrawBalanceParams = []byte{129} + +func (t *WithdrawBalanceParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufWithdrawBalanceParams); err != nil { + return err + } + + // t.AmountRequested (big.Int) (struct) + if err := t.AmountRequested.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *WithdrawBalanceParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = WithdrawBalanceParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.AmountRequested (big.Int) (struct) + + { + + if err := t.AmountRequested.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.AmountRequested: %w", err) + } + + } + return nil +} + +var lengthBufInternalSectorSetupForPresealParams = []byte{132} + +func (t *InternalSectorSetupForPresealParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufInternalSectorSetupForPresealParams); err != nil { + return err + } + + // t.Sectors ([]abi.SectorNumber) (slice) + if len(t.Sectors) > 8192 { + return xerrors.Errorf("Slice value in field t.Sectors was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Sectors))); err != nil { + return err + } + for _, v := range t.Sectors { + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(v)); err != nil { + return err + } + + } + + // t.RewardSmoothed (smoothing.FilterEstimate) (struct) + if err := t.RewardSmoothed.MarshalCBOR(cw); err != nil { + return err + } + + // t.RewardBaselinePower (big.Int) (struct) + if err := t.RewardBaselinePower.MarshalCBOR(cw); err != nil { + return err + } + + // t.QualityAdjPowerSmoothed (smoothing.FilterEstimate) (struct) + if err := t.QualityAdjPowerSmoothed.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *InternalSectorSetupForPresealParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = InternalSectorSetupForPresealParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 4 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Sectors ([]abi.SectorNumber) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Sectors: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Sectors = make([]abi.SectorNumber, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Sectors[i] = abi.SectorNumber(extra) + + } + + } + } + // t.RewardSmoothed (smoothing.FilterEstimate) (struct) + + { + + if err := t.RewardSmoothed.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.RewardSmoothed: %w", err) + } + + } + // t.RewardBaselinePower (big.Int) (struct) + + { + + if err := t.RewardBaselinePower.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.RewardBaselinePower: %w", err) + } + + } + // t.QualityAdjPowerSmoothed (smoothing.FilterEstimate) (struct) + + { + + if err := t.QualityAdjPowerSmoothed.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.QualityAdjPowerSmoothed: %w", err) + } + + } + return nil +} + +var lengthBufChangeMultiaddrsParams = []byte{129} + +func (t *ChangeMultiaddrsParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufChangeMultiaddrsParams); err != nil { + return err + } + + // t.NewMultiaddrs ([][]uint8) (slice) + if len(t.NewMultiaddrs) > 8192 { + return xerrors.Errorf("Slice value in field t.NewMultiaddrs was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.NewMultiaddrs))); err != nil { + return err + } + for _, v := range t.NewMultiaddrs { + if len(v) > 2097152 { + return xerrors.Errorf("Byte array in field v was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(v))); err != nil { + return err + } + + if _, err := cw.Write(v); err != nil { + return err + } + + } + return nil +} + +func (t *ChangeMultiaddrsParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = ChangeMultiaddrsParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.NewMultiaddrs ([][]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.NewMultiaddrs: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.NewMultiaddrs = make([][]uint8, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.NewMultiaddrs[i]: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.NewMultiaddrs[i] = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.NewMultiaddrs[i]); err != nil { + return err + } + + } + } + return nil +} + +var lengthBufCompactPartitionsParams = []byte{130} + +func (t *CompactPartitionsParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufCompactPartitionsParams); err != nil { + return err + } + + // t.Deadline (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Deadline)); err != nil { + return err + } + + // t.Partitions (bitfield.BitField) (struct) + if err := t.Partitions.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *CompactPartitionsParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = CompactPartitionsParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Deadline (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Deadline = uint64(extra) + + } + // t.Partitions (bitfield.BitField) (struct) + + { + + if err := t.Partitions.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Partitions: %w", err) + } + + } + return nil +} + +var lengthBufCompactSectorNumbersParams = []byte{129} + +func (t *CompactSectorNumbersParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufCompactSectorNumbersParams); err != nil { + return err + } + + // t.MaskSectorNumbers (bitfield.BitField) (struct) + if err := t.MaskSectorNumbers.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *CompactSectorNumbersParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = CompactSectorNumbersParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.MaskSectorNumbers (bitfield.BitField) (struct) + + { + + if err := t.MaskSectorNumbers.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.MaskSectorNumbers: %w", err) + } + + } + return nil +} + +var lengthBufDisputeWindowedPoStParams = []byte{130} + +func (t *DisputeWindowedPoStParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufDisputeWindowedPoStParams); err != nil { + return err + } + + // t.Deadline (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Deadline)); err != nil { + return err + } + + // t.PoStIndex (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.PoStIndex)); err != nil { + return err + } + + return nil +} + +func (t *DisputeWindowedPoStParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = DisputeWindowedPoStParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Deadline (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Deadline = uint64(extra) + + } + // t.PoStIndex (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.PoStIndex = uint64(extra) + + } + return nil +} + +var lengthBufPreCommitSectorBatchParams = []byte{129} + +func (t *PreCommitSectorBatchParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufPreCommitSectorBatchParams); err != nil { + return err + } + + // t.Sectors ([]miner.PreCommitSectorParams) (slice) + if len(t.Sectors) > 8192 { + return xerrors.Errorf("Slice value in field t.Sectors was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Sectors))); err != nil { + return err + } + for _, v := range t.Sectors { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *PreCommitSectorBatchParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = PreCommitSectorBatchParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Sectors ([]miner.PreCommitSectorParams) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Sectors: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Sectors = make([]PreCommitSectorParams, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Sectors[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Sectors[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufProveCommitAggregateParams = []byte{130} + +func (t *ProveCommitAggregateParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufProveCommitAggregateParams); err != nil { + return err + } + + // t.SectorNumbers (bitfield.BitField) (struct) + if err := t.SectorNumbers.MarshalCBOR(cw); err != nil { + return err + } + + // t.AggregateProof ([]uint8) (slice) + if len(t.AggregateProof) > 2097152 { + return xerrors.Errorf("Byte array in field t.AggregateProof was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.AggregateProof))); err != nil { + return err + } + + if _, err := cw.Write(t.AggregateProof); err != nil { + return err + } + + return nil +} + +func (t *ProveCommitAggregateParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = ProveCommitAggregateParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.SectorNumbers (bitfield.BitField) (struct) + + { + + if err := t.SectorNumbers.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.SectorNumbers: %w", err) + } + + } + // t.AggregateProof ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.AggregateProof: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.AggregateProof = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.AggregateProof); err != nil { + return err + } + + return nil +} + +var lengthBufProveReplicaUpdatesParams = []byte{129} + +func (t *ProveReplicaUpdatesParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufProveReplicaUpdatesParams); err != nil { + return err + } + + // t.Updates ([]miner.ReplicaUpdate) (slice) + if len(t.Updates) > 8192 { + return xerrors.Errorf("Slice value in field t.Updates was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Updates))); err != nil { + return err + } + for _, v := range t.Updates { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *ProveReplicaUpdatesParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = ProveReplicaUpdatesParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Updates ([]miner.ReplicaUpdate) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Updates: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Updates = make([]ReplicaUpdate, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Updates[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Updates[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufCronEventPayload = []byte{129} + +func (t *CronEventPayload) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufCronEventPayload); err != nil { + return err + } + + // t.EventType (miner.CronEventType) (int64) + if t.EventType >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.EventType)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.EventType-1)); err != nil { + return err + } + } + + return nil +} + +func (t *CronEventPayload) UnmarshalCBOR(r io.Reader) (err error) { + *t = CronEventPayload{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.EventType (miner.CronEventType) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.EventType = CronEventType(extraI) + } + return nil +} + +var lengthBufPreCommitSectorBatchParams2 = []byte{129} + +func (t *PreCommitSectorBatchParams2) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufPreCommitSectorBatchParams2); err != nil { + return err + } + + // t.Sectors ([]miner.SectorPreCommitInfo) (slice) + if len(t.Sectors) > 8192 { + return xerrors.Errorf("Slice value in field t.Sectors was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Sectors))); err != nil { + return err + } + for _, v := range t.Sectors { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *PreCommitSectorBatchParams2) UnmarshalCBOR(r io.Reader) (err error) { + *t = PreCommitSectorBatchParams2{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Sectors ([]miner.SectorPreCommitInfo) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Sectors: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Sectors = make([]SectorPreCommitInfo, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Sectors[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Sectors[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufProveReplicaUpdatesParams2 = []byte{129} + +func (t *ProveReplicaUpdatesParams2) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufProveReplicaUpdatesParams2); err != nil { + return err + } + + // t.Updates ([]miner.ReplicaUpdate2) (slice) + if len(t.Updates) > 8192 { + return xerrors.Errorf("Slice value in field t.Updates was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Updates))); err != nil { + return err + } + for _, v := range t.Updates { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *ProveReplicaUpdatesParams2) UnmarshalCBOR(r io.Reader) (err error) { + *t = ProveReplicaUpdatesParams2{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Updates ([]miner.ReplicaUpdate2) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Updates: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Updates = make([]ReplicaUpdate2, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Updates[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Updates[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufChangeBeneficiaryParams = []byte{131} + +func (t *ChangeBeneficiaryParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufChangeBeneficiaryParams); err != nil { + return err + } + + // t.NewBeneficiary (address.Address) (struct) + if err := t.NewBeneficiary.MarshalCBOR(cw); err != nil { + return err + } + + // t.NewQuota (big.Int) (struct) + if err := t.NewQuota.MarshalCBOR(cw); err != nil { + return err + } + + // t.NewExpiration (abi.ChainEpoch) (int64) + if t.NewExpiration >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.NewExpiration)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.NewExpiration-1)); err != nil { + return err + } + } + + return nil +} + +func (t *ChangeBeneficiaryParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = ChangeBeneficiaryParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.NewBeneficiary (address.Address) (struct) + + { + + if err := t.NewBeneficiary.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.NewBeneficiary: %w", err) + } + + } + // t.NewQuota (big.Int) (struct) + + { + + if err := t.NewQuota.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.NewQuota: %w", err) + } + + } + // t.NewExpiration (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.NewExpiration = abi.ChainEpoch(extraI) + } + return nil +} + +var lengthBufGetBeneficiaryReturn = []byte{130} + +func (t *GetBeneficiaryReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufGetBeneficiaryReturn); err != nil { + return err + } + + // t.Active (miner.ActiveBeneficiary) (struct) + if err := t.Active.MarshalCBOR(cw); err != nil { + return err + } + + // t.Proposed (miner.PendingBeneficiaryChange) (struct) + if err := t.Proposed.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *GetBeneficiaryReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = GetBeneficiaryReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Active (miner.ActiveBeneficiary) (struct) + + { + + if err := t.Active.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Active: %w", err) + } + + } + // t.Proposed (miner.PendingBeneficiaryChange) (struct) + + { + + b, err := cr.ReadByte() + if err != nil { + return err + } + if b != cbg.CborNull[0] { + if err := cr.UnreadByte(); err != nil { + return err + } + t.Proposed = new(PendingBeneficiaryChange) + if err := t.Proposed.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Proposed pointer: %w", err) + } + } + + } + return nil +} + +var lengthBufGetOwnerReturn = []byte{130} + +func (t *GetOwnerReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufGetOwnerReturn); err != nil { + return err + } + + // t.Owner (address.Address) (struct) + if err := t.Owner.MarshalCBOR(cw); err != nil { + return err + } + + // t.Proposed (address.Address) (struct) + if err := t.Proposed.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *GetOwnerReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = GetOwnerReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Owner (address.Address) (struct) + + { + + if err := t.Owner.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Owner: %w", err) + } + + } + // t.Proposed (address.Address) (struct) + + { + + b, err := cr.ReadByte() + if err != nil { + return err + } + if b != cbg.CborNull[0] { + if err := cr.UnreadByte(); err != nil { + return err + } + t.Proposed = new(address.Address) + if err := t.Proposed.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Proposed pointer: %w", err) + } + } + + } + return nil +} + +var lengthBufGetPeerIDReturn = []byte{129} + +func (t *GetPeerIDReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufGetPeerIDReturn); err != nil { + return err + } + + // t.PeerId ([]uint8) (slice) + if len(t.PeerId) > 2097152 { + return xerrors.Errorf("Byte array in field t.PeerId was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.PeerId))); err != nil { + return err + } + + if _, err := cw.Write(t.PeerId); err != nil { + return err + } + + return nil +} + +func (t *GetPeerIDReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = GetPeerIDReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.PeerId ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.PeerId: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.PeerId = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.PeerId); err != nil { + return err + } + + return nil +} + +var lengthBufGetMultiAddrsReturn = []byte{129} + +func (t *GetMultiAddrsReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufGetMultiAddrsReturn); err != nil { + return err + } + + // t.MultiAddrs ([]uint8) (slice) + if len(t.MultiAddrs) > 2097152 { + return xerrors.Errorf("Byte array in field t.MultiAddrs was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.MultiAddrs))); err != nil { + return err + } + + if _, err := cw.Write(t.MultiAddrs); err != nil { + return err + } + + return nil +} + +func (t *GetMultiAddrsReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = GetMultiAddrsReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.MultiAddrs ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.MultiAddrs: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.MultiAddrs = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.MultiAddrs); err != nil { + return err + } + + return nil +} + +var lengthBufProveCommitSectors3Params = []byte{134} + +func (t *ProveCommitSectors3Params) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufProveCommitSectors3Params); err != nil { + return err + } + + // t.SectorActivations ([]miner.SectorActivationManifest) (slice) + if len(t.SectorActivations) > 8192 { + return xerrors.Errorf("Slice value in field t.SectorActivations was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.SectorActivations))); err != nil { + return err + } + for _, v := range t.SectorActivations { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + + // t.SectorProofs ([][]uint8) (slice) + if len(t.SectorProofs) > 8192 { + return xerrors.Errorf("Slice value in field t.SectorProofs was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.SectorProofs))); err != nil { + return err + } + for _, v := range t.SectorProofs { + if len(v) > 2097152 { + return xerrors.Errorf("Byte array in field v was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(v))); err != nil { + return err + } + + if _, err := cw.Write(v); err != nil { + return err + } + + } + + // t.AggregateProof ([]uint8) (slice) + if len(t.AggregateProof) > 2097152 { + return xerrors.Errorf("Byte array in field t.AggregateProof was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.AggregateProof))); err != nil { + return err + } + + if _, err := cw.Write(t.AggregateProof); err != nil { + return err + } + + // t.AggregateProofType (abi.RegisteredAggregationProof) (int64) + if t.AggregateProofType == nil { + if _, err := cw.Write(cbg.CborNull); err != nil { + return err + } + } else { + if *t.AggregateProofType >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(*t.AggregateProofType)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-*t.AggregateProofType-1)); err != nil { + return err + } + } + } + + // t.RequireActivationSuccess (bool) (bool) + if err := cbg.WriteBool(w, t.RequireActivationSuccess); err != nil { + return err + } + + // t.RequireNotificationSuccess (bool) (bool) + if err := cbg.WriteBool(w, t.RequireNotificationSuccess); err != nil { + return err + } + return nil +} + +func (t *ProveCommitSectors3Params) UnmarshalCBOR(r io.Reader) (err error) { + *t = ProveCommitSectors3Params{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 6 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.SectorActivations ([]miner.SectorActivationManifest) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.SectorActivations: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.SectorActivations = make([]SectorActivationManifest, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.SectorActivations[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.SectorActivations[i]: %w", err) + } + + } + + } + } + // t.SectorProofs ([][]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.SectorProofs: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.SectorProofs = make([][]uint8, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.SectorProofs[i]: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.SectorProofs[i] = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.SectorProofs[i]); err != nil { + return err + } + + } + } + // t.AggregateProof ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.AggregateProof: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.AggregateProof = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.AggregateProof); err != nil { + return err + } + + // t.AggregateProofType (abi.RegisteredAggregationProof) (int64) + { + + b, err := cr.ReadByte() + if err != nil { + return err + } + if b != cbg.CborNull[0] { + if err := cr.UnreadByte(); err != nil { + return err + } + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.AggregateProofType = (*abi.RegisteredAggregationProof)(&extraI) + } + } + // t.RequireActivationSuccess (bool) (bool) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajOther { + return fmt.Errorf("booleans must be major type 7") + } + switch extra { + case 20: + t.RequireActivationSuccess = false + case 21: + t.RequireActivationSuccess = true + default: + return fmt.Errorf("booleans are either major type 7, value 20 or 21 (got %d)", extra) + } + // t.RequireNotificationSuccess (bool) (bool) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajOther { + return fmt.Errorf("booleans must be major type 7") + } + switch extra { + case 20: + t.RequireNotificationSuccess = false + case 21: + t.RequireNotificationSuccess = true + default: + return fmt.Errorf("booleans are either major type 7, value 20 or 21 (got %d)", extra) + } + return nil +} + +var lengthBufSectorActivationManifest = []byte{130} + +func (t *SectorActivationManifest) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufSectorActivationManifest); err != nil { + return err + } + + // t.SectorNumber (abi.SectorNumber) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SectorNumber)); err != nil { + return err + } + + // t.Pieces ([]miner.PieceActivationManifest) (slice) + if len(t.Pieces) > 8192 { + return xerrors.Errorf("Slice value in field t.Pieces was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Pieces))); err != nil { + return err + } + for _, v := range t.Pieces { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *SectorActivationManifest) UnmarshalCBOR(r io.Reader) (err error) { + *t = SectorActivationManifest{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.SectorNumber (abi.SectorNumber) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.SectorNumber = abi.SectorNumber(extra) + + } + // t.Pieces ([]miner.PieceActivationManifest) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Pieces: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Pieces = make([]PieceActivationManifest, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Pieces[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Pieces[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufPieceActivationManifest = []byte{132} + +func (t *PieceActivationManifest) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufPieceActivationManifest); err != nil { + return err + } + + // t.CID (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.CID); err != nil { + return xerrors.Errorf("failed to write cid field t.CID: %w", err) + } + + // t.Size (abi.PaddedPieceSize) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Size)); err != nil { + return err + } + + // t.VerifiedAllocationKey (miner.VerifiedAllocationKey) (struct) + if err := t.VerifiedAllocationKey.MarshalCBOR(cw); err != nil { + return err + } + + // t.Notify ([]miner.DataActivationNotification) (slice) + if len(t.Notify) > 8192 { + return xerrors.Errorf("Slice value in field t.Notify was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Notify))); err != nil { + return err + } + for _, v := range t.Notify { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *PieceActivationManifest) UnmarshalCBOR(r io.Reader) (err error) { + *t = PieceActivationManifest{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 4 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.CID (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.CID: %w", err) + } + + t.CID = c + + } + // t.Size (abi.PaddedPieceSize) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Size = abi.PaddedPieceSize(extra) + + } + // t.VerifiedAllocationKey (miner.VerifiedAllocationKey) (struct) + + { + + b, err := cr.ReadByte() + if err != nil { + return err + } + if b != cbg.CborNull[0] { + if err := cr.UnreadByte(); err != nil { + return err + } + t.VerifiedAllocationKey = new(VerifiedAllocationKey) + if err := t.VerifiedAllocationKey.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.VerifiedAllocationKey pointer: %w", err) + } + } + + } + // t.Notify ([]miner.DataActivationNotification) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Notify: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Notify = make([]DataActivationNotification, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Notify[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Notify[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufVerifiedAllocationKey = []byte{130} + +func (t *VerifiedAllocationKey) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufVerifiedAllocationKey); err != nil { + return err + } + + // t.Client (abi.ActorID) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Client)); err != nil { + return err + } + + // t.ID (verifreg.AllocationId) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.ID)); err != nil { + return err + } + + return nil +} + +func (t *VerifiedAllocationKey) UnmarshalCBOR(r io.Reader) (err error) { + *t = VerifiedAllocationKey{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Client (abi.ActorID) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Client = abi.ActorID(extra) + + } + // t.ID (verifreg.AllocationId) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.ID = verifreg.AllocationId(extra) + + } + return nil +} + +var lengthBufDataActivationNotification = []byte{130} + +func (t *DataActivationNotification) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufDataActivationNotification); err != nil { + return err + } + + // t.Address (address.Address) (struct) + if err := t.Address.MarshalCBOR(cw); err != nil { + return err + } + + // t.Payload ([]uint8) (slice) + if len(t.Payload) > 2097152 { + return xerrors.Errorf("Byte array in field t.Payload was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.Payload))); err != nil { + return err + } + + if _, err := cw.Write(t.Payload); err != nil { + return err + } + + return nil +} + +func (t *DataActivationNotification) UnmarshalCBOR(r io.Reader) (err error) { + *t = DataActivationNotification{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Address (address.Address) (struct) + + { + + if err := t.Address.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Address: %w", err) + } + + } + // t.Payload ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.Payload: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.Payload = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.Payload); err != nil { + return err + } + + return nil +} + +var lengthBufProveReplicaUpdates3Params = []byte{135} + +func (t *ProveReplicaUpdates3Params) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufProveReplicaUpdates3Params); err != nil { + return err + } + + // t.SectorUpdates ([]miner.SectorUpdateManifest) (slice) + if len(t.SectorUpdates) > 8192 { + return xerrors.Errorf("Slice value in field t.SectorUpdates was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.SectorUpdates))); err != nil { + return err + } + for _, v := range t.SectorUpdates { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + + // t.SectorProofs ([][]uint8) (slice) + if len(t.SectorProofs) > 8192 { + return xerrors.Errorf("Slice value in field t.SectorProofs was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.SectorProofs))); err != nil { + return err + } + for _, v := range t.SectorProofs { + if len(v) > 2097152 { + return xerrors.Errorf("Byte array in field v was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(v))); err != nil { + return err + } + + if _, err := cw.Write(v); err != nil { + return err + } + + } + + // t.AggregateProof ([]uint8) (slice) + if len(t.AggregateProof) > 2097152 { + return xerrors.Errorf("Byte array in field t.AggregateProof was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.AggregateProof))); err != nil { + return err + } + + if _, err := cw.Write(t.AggregateProof); err != nil { + return err + } + + // t.UpdateProofsType (abi.RegisteredUpdateProof) (int64) + if t.UpdateProofsType >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.UpdateProofsType)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.UpdateProofsType-1)); err != nil { + return err + } + } + + // t.AggregateProofType (abi.RegisteredAggregationProof) (int64) + if t.AggregateProofType == nil { + if _, err := cw.Write(cbg.CborNull); err != nil { + return err + } + } else { + if *t.AggregateProofType >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(*t.AggregateProofType)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-*t.AggregateProofType-1)); err != nil { + return err + } + } + } + + // t.RequireActivationSuccess (bool) (bool) + if err := cbg.WriteBool(w, t.RequireActivationSuccess); err != nil { + return err + } + + // t.RequireNotificationSuccess (bool) (bool) + if err := cbg.WriteBool(w, t.RequireNotificationSuccess); err != nil { + return err + } + return nil +} + +func (t *ProveReplicaUpdates3Params) UnmarshalCBOR(r io.Reader) (err error) { + *t = ProveReplicaUpdates3Params{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 7 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.SectorUpdates ([]miner.SectorUpdateManifest) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.SectorUpdates: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.SectorUpdates = make([]SectorUpdateManifest, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.SectorUpdates[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.SectorUpdates[i]: %w", err) + } + + } + + } + } + // t.SectorProofs ([][]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.SectorProofs: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.SectorProofs = make([][]uint8, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.SectorProofs[i]: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.SectorProofs[i] = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.SectorProofs[i]); err != nil { + return err + } + + } + } + // t.AggregateProof ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.AggregateProof: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.AggregateProof = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.AggregateProof); err != nil { + return err + } + + // t.UpdateProofsType (abi.RegisteredUpdateProof) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.UpdateProofsType = abi.RegisteredUpdateProof(extraI) + } + // t.AggregateProofType (abi.RegisteredAggregationProof) (int64) + { + + b, err := cr.ReadByte() + if err != nil { + return err + } + if b != cbg.CborNull[0] { + if err := cr.UnreadByte(); err != nil { + return err + } + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.AggregateProofType = (*abi.RegisteredAggregationProof)(&extraI) + } + } + // t.RequireActivationSuccess (bool) (bool) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajOther { + return fmt.Errorf("booleans must be major type 7") + } + switch extra { + case 20: + t.RequireActivationSuccess = false + case 21: + t.RequireActivationSuccess = true + default: + return fmt.Errorf("booleans are either major type 7, value 20 or 21 (got %d)", extra) + } + // t.RequireNotificationSuccess (bool) (bool) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajOther { + return fmt.Errorf("booleans must be major type 7") + } + switch extra { + case 20: + t.RequireNotificationSuccess = false + case 21: + t.RequireNotificationSuccess = true + default: + return fmt.Errorf("booleans are either major type 7, value 20 or 21 (got %d)", extra) + } + return nil +} + +var lengthBufSectorUpdateManifest = []byte{133} + +func (t *SectorUpdateManifest) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufSectorUpdateManifest); err != nil { + return err + } + + // t.Sector (abi.SectorNumber) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Sector)); err != nil { + return err + } + + // t.Deadline (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Deadline)); err != nil { + return err + } + + // t.Partition (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Partition)); err != nil { + return err + } + + // t.NewSealedCID (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.NewSealedCID); err != nil { + return xerrors.Errorf("failed to write cid field t.NewSealedCID: %w", err) + } + + // t.Pieces ([]miner.PieceActivationManifest) (slice) + if len(t.Pieces) > 8192 { + return xerrors.Errorf("Slice value in field t.Pieces was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Pieces))); err != nil { + return err + } + for _, v := range t.Pieces { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *SectorUpdateManifest) UnmarshalCBOR(r io.Reader) (err error) { + *t = SectorUpdateManifest{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 5 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Sector (abi.SectorNumber) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Sector = abi.SectorNumber(extra) + + } + // t.Deadline (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Deadline = uint64(extra) + + } + // t.Partition (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Partition = uint64(extra) + + } + // t.NewSealedCID (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.NewSealedCID: %w", err) + } + + t.NewSealedCID = c + + } + // t.Pieces ([]miner.PieceActivationManifest) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Pieces: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Pieces = make([]PieceActivationManifest, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Pieces[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Pieces[i]: %w", err) + } + + } + + } + } + return nil +} + +func (t *SectorContentChangedParams) MarshalCBOR(w io.Writer) error { + cw := cbg.NewCborWriter(w) + + // (*t) (miner.SectorContentChangedParams) (slice) + if len((*t)) > 8192 { + return xerrors.Errorf("Slice value in field (*t) was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len((*t)))); err != nil { + return err + } + for _, v := range *t { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *SectorContentChangedParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = SectorContentChangedParams{} + + cr := cbg.NewCborReader(r) + var maj byte + var extra uint64 + _ = maj + _ = extra + // (*t) (miner.SectorContentChangedParams) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("(*t): array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + (*t) = make([]SectorChanges, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := (*t)[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling (*t)[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufSectorChanges = []byte{131} + +func (t *SectorChanges) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufSectorChanges); err != nil { + return err + } + + // t.Sector (abi.SectorNumber) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Sector)); err != nil { + return err + } + + // t.MinimumCommitmentEpoch (abi.ChainEpoch) (int64) + if t.MinimumCommitmentEpoch >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.MinimumCommitmentEpoch)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.MinimumCommitmentEpoch-1)); err != nil { + return err + } + } + + // t.Added ([]miner.PieceChange) (slice) + if len(t.Added) > 8192 { + return xerrors.Errorf("Slice value in field t.Added was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Added))); err != nil { + return err + } + for _, v := range t.Added { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *SectorChanges) UnmarshalCBOR(r io.Reader) (err error) { + *t = SectorChanges{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.Sector (abi.SectorNumber) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Sector = abi.SectorNumber(extra) + + } + // t.MinimumCommitmentEpoch (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.MinimumCommitmentEpoch = abi.ChainEpoch(extraI) + } + // t.Added ([]miner.PieceChange) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Added: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Added = make([]PieceChange, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Added[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Added[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufPieceChange = []byte{131} + +func (t *PieceChange) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufPieceChange); err != nil { + return err + } + + // t.Data (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.Data); err != nil { + return xerrors.Errorf("failed to write cid field t.Data: %w", err) + } + + // t.Size (abi.PaddedPieceSize) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Size)); err != nil { + return err + } + + // t.Payload ([]uint8) (slice) + if len(t.Payload) > 2097152 { + return xerrors.Errorf("Byte array in field t.Payload was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.Payload))); err != nil { + return err + } + + if _, err := cw.Write(t.Payload); err != nil { + return err + } + + return nil +} + +func (t *PieceChange) UnmarshalCBOR(r io.Reader) (err error) { + *t = PieceChange{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.Data (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.Data: %w", err) + } + + t.Data = c + + } + // t.Size (abi.PaddedPieceSize) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Size = abi.PaddedPieceSize(extra) + + } + // t.Payload ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.Payload: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.Payload = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.Payload); err != nil { + return err + } + + return nil +} + +var lengthBufFaultDeclaration = []byte{131} + +func (t *FaultDeclaration) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufFaultDeclaration); err != nil { + return err + } + + // t.Deadline (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Deadline)); err != nil { + return err + } + + // t.Partition (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Partition)); err != nil { + return err + } + + // t.Sectors (bitfield.BitField) (struct) + if err := t.Sectors.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *FaultDeclaration) UnmarshalCBOR(r io.Reader) (err error) { + *t = FaultDeclaration{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.Deadline (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Deadline = uint64(extra) + + } + // t.Partition (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Partition = uint64(extra) + + } + // t.Sectors (bitfield.BitField) (struct) + + { + + if err := t.Sectors.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Sectors: %w", err) + } + + } + return nil +} + +var lengthBufRecoveryDeclaration = []byte{131} + +func (t *RecoveryDeclaration) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufRecoveryDeclaration); err != nil { + return err + } + + // t.Deadline (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Deadline)); err != nil { + return err + } + + // t.Partition (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Partition)); err != nil { + return err + } + + // t.Sectors (bitfield.BitField) (struct) + if err := t.Sectors.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *RecoveryDeclaration) UnmarshalCBOR(r io.Reader) (err error) { + *t = RecoveryDeclaration{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.Deadline (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Deadline = uint64(extra) + + } + // t.Partition (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Partition = uint64(extra) + + } + // t.Sectors (bitfield.BitField) (struct) + + { + + if err := t.Sectors.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Sectors: %w", err) + } + + } + return nil +} + +var lengthBufExpirationExtension = []byte{132} + +func (t *ExpirationExtension) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufExpirationExtension); err != nil { + return err + } + + // t.Deadline (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Deadline)); err != nil { + return err + } + + // t.Partition (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Partition)); err != nil { + return err + } + + // t.Sectors (bitfield.BitField) (struct) + if err := t.Sectors.MarshalCBOR(cw); err != nil { + return err + } + + // t.NewExpiration (abi.ChainEpoch) (int64) + if t.NewExpiration >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.NewExpiration)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.NewExpiration-1)); err != nil { + return err + } + } + + return nil +} + +func (t *ExpirationExtension) UnmarshalCBOR(r io.Reader) (err error) { + *t = ExpirationExtension{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 4 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Deadline (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Deadline = uint64(extra) + + } + // t.Partition (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Partition = uint64(extra) + + } + // t.Sectors (bitfield.BitField) (struct) + + { + + if err := t.Sectors.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Sectors: %w", err) + } + + } + // t.NewExpiration (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.NewExpiration = abi.ChainEpoch(extraI) + } + return nil +} + +var lengthBufTerminationDeclaration = []byte{131} + +func (t *TerminationDeclaration) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufTerminationDeclaration); err != nil { + return err + } + + // t.Deadline (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Deadline)); err != nil { + return err + } + + // t.Partition (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Partition)); err != nil { + return err + } + + // t.Sectors (bitfield.BitField) (struct) + if err := t.Sectors.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *TerminationDeclaration) UnmarshalCBOR(r io.Reader) (err error) { + *t = TerminationDeclaration{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.Deadline (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Deadline = uint64(extra) + + } + // t.Partition (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Partition = uint64(extra) + + } + // t.Sectors (bitfield.BitField) (struct) + + { + + if err := t.Sectors.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Sectors: %w", err) + } + + } + return nil +} + +var lengthBufPoStPartition = []byte{130} + +func (t *PoStPartition) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufPoStPartition); err != nil { + return err + } + + // t.Index (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Index)); err != nil { + return err + } + + // t.Skipped (bitfield.BitField) (struct) + if err := t.Skipped.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *PoStPartition) UnmarshalCBOR(r io.Reader) (err error) { + *t = PoStPartition{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Index (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Index = uint64(extra) + + } + // t.Skipped (bitfield.BitField) (struct) + + { + + if err := t.Skipped.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Skipped: %w", err) + } + + } + return nil +} + +var lengthBufReplicaUpdate = []byte{135} + +func (t *ReplicaUpdate) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufReplicaUpdate); err != nil { + return err + } + + // t.SectorID (abi.SectorNumber) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SectorID)); err != nil { + return err + } + + // t.Deadline (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Deadline)); err != nil { + return err + } + + // t.Partition (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Partition)); err != nil { + return err + } + + // t.NewSealedSectorCID (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.NewSealedSectorCID); err != nil { + return xerrors.Errorf("failed to write cid field t.NewSealedSectorCID: %w", err) + } + + // t.Deals ([]abi.DealID) (slice) + if len(t.Deals) > 8192 { + return xerrors.Errorf("Slice value in field t.Deals was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Deals))); err != nil { + return err + } + for _, v := range t.Deals { + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(v)); err != nil { + return err + } + + } + + // t.UpdateProofType (abi.RegisteredUpdateProof) (int64) + if t.UpdateProofType >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.UpdateProofType)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.UpdateProofType-1)); err != nil { + return err + } + } + + // t.ReplicaProof ([]uint8) (slice) + if len(t.ReplicaProof) > 2097152 { + return xerrors.Errorf("Byte array in field t.ReplicaProof was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.ReplicaProof))); err != nil { + return err + } + + if _, err := cw.Write(t.ReplicaProof); err != nil { + return err + } + + return nil +} + +func (t *ReplicaUpdate) UnmarshalCBOR(r io.Reader) (err error) { + *t = ReplicaUpdate{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 7 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.SectorID (abi.SectorNumber) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.SectorID = abi.SectorNumber(extra) + + } + // t.Deadline (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Deadline = uint64(extra) + + } + // t.Partition (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Partition = uint64(extra) + + } + // t.NewSealedSectorCID (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.NewSealedSectorCID: %w", err) + } + + t.NewSealedSectorCID = c + + } + // t.Deals ([]abi.DealID) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Deals: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Deals = make([]abi.DealID, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Deals[i] = abi.DealID(extra) + + } + + } + } + // t.UpdateProofType (abi.RegisteredUpdateProof) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.UpdateProofType = abi.RegisteredUpdateProof(extraI) + } + // t.ReplicaProof ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.ReplicaProof: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.ReplicaProof = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.ReplicaProof); err != nil { + return err + } + + return nil +} + +var lengthBufReplicaUpdate2 = []byte{136} + +func (t *ReplicaUpdate2) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufReplicaUpdate2); err != nil { + return err + } + + // t.SectorID (abi.SectorNumber) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SectorID)); err != nil { + return err + } + + // t.Deadline (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Deadline)); err != nil { + return err + } + + // t.Partition (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Partition)); err != nil { + return err + } + + // t.NewSealedSectorCID (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.NewSealedSectorCID); err != nil { + return xerrors.Errorf("failed to write cid field t.NewSealedSectorCID: %w", err) + } + + // t.NewUnsealedSectorCID (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.NewUnsealedSectorCID); err != nil { + return xerrors.Errorf("failed to write cid field t.NewUnsealedSectorCID: %w", err) + } + + // t.Deals ([]abi.DealID) (slice) + if len(t.Deals) > 8192 { + return xerrors.Errorf("Slice value in field t.Deals was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Deals))); err != nil { + return err + } + for _, v := range t.Deals { + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(v)); err != nil { + return err + } + + } + + // t.UpdateProofType (abi.RegisteredUpdateProof) (int64) + if t.UpdateProofType >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.UpdateProofType)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.UpdateProofType-1)); err != nil { + return err + } + } + + // t.ReplicaProof ([]uint8) (slice) + if len(t.ReplicaProof) > 2097152 { + return xerrors.Errorf("Byte array in field t.ReplicaProof was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.ReplicaProof))); err != nil { + return err + } + + if _, err := cw.Write(t.ReplicaProof); err != nil { + return err + } + + return nil +} + +func (t *ReplicaUpdate2) UnmarshalCBOR(r io.Reader) (err error) { + *t = ReplicaUpdate2{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 8 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.SectorID (abi.SectorNumber) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.SectorID = abi.SectorNumber(extra) + + } + // t.Deadline (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Deadline = uint64(extra) + + } + // t.Partition (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Partition = uint64(extra) + + } + // t.NewSealedSectorCID (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.NewSealedSectorCID: %w", err) + } + + t.NewSealedSectorCID = c + + } + // t.NewUnsealedSectorCID (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.NewUnsealedSectorCID: %w", err) + } + + t.NewUnsealedSectorCID = c + + } + // t.Deals ([]abi.DealID) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Deals: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Deals = make([]abi.DealID, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Deals[i] = abi.DealID(extra) + + } + + } + } + // t.UpdateProofType (abi.RegisteredUpdateProof) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.UpdateProofType = abi.RegisteredUpdateProof(extraI) + } + // t.ReplicaProof ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.ReplicaProof: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.ReplicaProof = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.ReplicaProof); err != nil { + return err + } + + return nil +} + +var lengthBufExpirationExtension2 = []byte{133} + +func (t *ExpirationExtension2) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufExpirationExtension2); err != nil { + return err + } + + // t.Deadline (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Deadline)); err != nil { + return err + } + + // t.Partition (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Partition)); err != nil { + return err + } + + // t.Sectors (bitfield.BitField) (struct) + if err := t.Sectors.MarshalCBOR(cw); err != nil { + return err + } + + // t.SectorsWithClaims ([]miner.SectorClaim) (slice) + if len(t.SectorsWithClaims) > 8192 { + return xerrors.Errorf("Slice value in field t.SectorsWithClaims was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.SectorsWithClaims))); err != nil { + return err + } + for _, v := range t.SectorsWithClaims { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + + // t.NewExpiration (abi.ChainEpoch) (int64) + if t.NewExpiration >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.NewExpiration)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.NewExpiration-1)); err != nil { + return err + } + } + + return nil +} + +func (t *ExpirationExtension2) UnmarshalCBOR(r io.Reader) (err error) { + *t = ExpirationExtension2{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 5 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Deadline (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Deadline = uint64(extra) + + } + // t.Partition (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Partition = uint64(extra) + + } + // t.Sectors (bitfield.BitField) (struct) + + { + + if err := t.Sectors.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Sectors: %w", err) + } + + } + // t.SectorsWithClaims ([]miner.SectorClaim) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.SectorsWithClaims: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.SectorsWithClaims = make([]SectorClaim, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.SectorsWithClaims[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.SectorsWithClaims[i]: %w", err) + } + + } + + } + } + // t.NewExpiration (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.NewExpiration = abi.ChainEpoch(extraI) + } + return nil +} + +var lengthBufSectorClaim = []byte{131} + +func (t *SectorClaim) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufSectorClaim); err != nil { + return err + } + + // t.SectorNumber (abi.SectorNumber) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SectorNumber)); err != nil { + return err + } + + // t.MaintainClaims ([]verifreg.ClaimId) (slice) + if len(t.MaintainClaims) > 8192 { + return xerrors.Errorf("Slice value in field t.MaintainClaims was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.MaintainClaims))); err != nil { + return err + } + for _, v := range t.MaintainClaims { + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(v)); err != nil { + return err + } + + } + + // t.DropClaims ([]verifreg.ClaimId) (slice) + if len(t.DropClaims) > 8192 { + return xerrors.Errorf("Slice value in field t.DropClaims was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.DropClaims))); err != nil { + return err + } + for _, v := range t.DropClaims { + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(v)); err != nil { + return err + } + + } + return nil +} + +func (t *SectorClaim) UnmarshalCBOR(r io.Reader) (err error) { + *t = SectorClaim{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.SectorNumber (abi.SectorNumber) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.SectorNumber = abi.SectorNumber(extra) + + } + // t.MaintainClaims ([]verifreg.ClaimId) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.MaintainClaims: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.MaintainClaims = make([]verifreg.ClaimId, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.MaintainClaims[i] = verifreg.ClaimId(extra) + + } + + } + } + // t.DropClaims ([]verifreg.ClaimId) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.DropClaims: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.DropClaims = make([]verifreg.ClaimId, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.DropClaims[i] = verifreg.ClaimId(extra) + + } + + } + } + return nil +} + +var lengthBufSectorNIActivationInfo = []byte{134} + +func (t *SectorNIActivationInfo) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufSectorNIActivationInfo); err != nil { + return err + } + + // t.SealingNumber (abi.SectorNumber) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SealingNumber)); err != nil { + return err + } + + // t.SealerID (abi.ActorID) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SealerID)); err != nil { + return err + } + + // t.SealedCID (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.SealedCID); err != nil { + return xerrors.Errorf("failed to write cid field t.SealedCID: %w", err) + } + + // t.SectorNumber (abi.SectorNumber) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SectorNumber)); err != nil { + return err + } + + // t.SealRandEpoch (abi.ChainEpoch) (int64) + if t.SealRandEpoch >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SealRandEpoch)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.SealRandEpoch-1)); err != nil { + return err + } + } + + // t.Expiration (abi.ChainEpoch) (int64) + if t.Expiration >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Expiration)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.Expiration-1)); err != nil { + return err + } + } + + return nil +} + +func (t *SectorNIActivationInfo) UnmarshalCBOR(r io.Reader) (err error) { + *t = SectorNIActivationInfo{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 6 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.SealingNumber (abi.SectorNumber) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.SealingNumber = abi.SectorNumber(extra) + + } + // t.SealerID (abi.ActorID) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.SealerID = abi.ActorID(extra) + + } + // t.SealedCID (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.SealedCID: %w", err) + } + + t.SealedCID = c + + } + // t.SectorNumber (abi.SectorNumber) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.SectorNumber = abi.SectorNumber(extra) + + } + // t.SealRandEpoch (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.SealRandEpoch = abi.ChainEpoch(extraI) + } + // t.Expiration (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.Expiration = abi.ChainEpoch(extraI) + } + return nil +} + +var lengthBufProveCommitSectorsNIParams = []byte{134} + +func (t *ProveCommitSectorsNIParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufProveCommitSectorsNIParams); err != nil { + return err + } + + // t.Sectors ([]miner.SectorNIActivationInfo) (slice) + if len(t.Sectors) > 8192 { + return xerrors.Errorf("Slice value in field t.Sectors was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Sectors))); err != nil { + return err + } + for _, v := range t.Sectors { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + + // t.AggregateProof ([]uint8) (slice) + if len(t.AggregateProof) > 2097152 { + return xerrors.Errorf("Byte array in field t.AggregateProof was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.AggregateProof))); err != nil { + return err + } + + if _, err := cw.Write(t.AggregateProof); err != nil { + return err + } + + // t.SealProofType (abi.RegisteredSealProof) (int64) + if t.SealProofType >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SealProofType)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.SealProofType-1)); err != nil { + return err + } + } + + // t.AggregateProofType (abi.RegisteredAggregationProof) (int64) + if t.AggregateProofType >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.AggregateProofType)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.AggregateProofType-1)); err != nil { + return err + } + } + + // t.ProvingDeadline (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.ProvingDeadline)); err != nil { + return err + } + + // t.RequireActivationSuccess (bool) (bool) + if err := cbg.WriteBool(w, t.RequireActivationSuccess); err != nil { + return err + } + return nil +} + +func (t *ProveCommitSectorsNIParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = ProveCommitSectorsNIParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 6 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Sectors ([]miner.SectorNIActivationInfo) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Sectors: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Sectors = make([]SectorNIActivationInfo, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Sectors[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Sectors[i]: %w", err) + } + + } + + } + } + // t.AggregateProof ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.AggregateProof: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.AggregateProof = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.AggregateProof); err != nil { + return err + } + + // t.SealProofType (abi.RegisteredSealProof) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.SealProofType = abi.RegisteredSealProof(extraI) + } + // t.AggregateProofType (abi.RegisteredAggregationProof) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.AggregateProofType = abi.RegisteredAggregationProof(extraI) + } + // t.ProvingDeadline (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.ProvingDeadline = uint64(extra) + + } + // t.RequireActivationSuccess (bool) (bool) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajOther { + return fmt.Errorf("booleans must be major type 7") + } + switch extra { + case 20: + t.RequireActivationSuccess = false + case 21: + t.RequireActivationSuccess = true + default: + return fmt.Errorf("booleans are either major type 7, value 20 or 21 (got %d)", extra) + } + return nil +} + +var lengthBufMaxTerminationFeeParams = []byte{130} + +func (t *MaxTerminationFeeParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufMaxTerminationFeeParams); err != nil { + return err + } + + // t.Power (big.Int) (struct) + if err := t.Power.MarshalCBOR(cw); err != nil { + return err + } + + // t.InitialPledge (big.Int) (struct) + if err := t.InitialPledge.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *MaxTerminationFeeParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = MaxTerminationFeeParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Power (big.Int) (struct) + + { + + if err := t.Power.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Power: %w", err) + } + + } + // t.InitialPledge (big.Int) (struct) + + { + + if err := t.InitialPledge.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.InitialPledge: %w", err) + } + + } + return nil +} diff --git a/builtin/v18/miner/deadline_state.go b/builtin/v18/miner/deadline_state.go new file mode 100644 index 00000000..5ef06c66 --- /dev/null +++ b/builtin/v18/miner/deadline_state.go @@ -0,0 +1,249 @@ +package miner + +import ( + "github.com/ipfs/go-cid" + "golang.org/x/xerrors" + + "github.com/filecoin-project/go-bitfield" + abi "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/big" + "github.com/filecoin-project/go-state-types/builtin/v18/util/adt" + xc "github.com/filecoin-project/go-state-types/exitcode" + "github.com/filecoin-project/go-state-types/proof" +) + +// Deadlines contains Deadline objects, describing the sectors due at the given +// deadline and their state (faulty, terminated, recovering, etc.). +type Deadlines struct { + // Note: we could inline part of the deadline struct (e.g., active/assigned sectors) + // to make new sector assignment cheaper. At the moment, assigning a sector requires + // loading all deadlines to figure out where best to assign new sectors. + Due [WPoStPeriodDeadlines]cid.Cid // []Deadline +} + +// Deadline holds the state for all sectors due at a specific deadline. +type Deadline struct { + // Partitions in this deadline, in order. + // The keys of this AMT are always sequential integers beginning with zero. + Partitions cid.Cid // AMT[PartitionNumber]Partition + + // Maps epochs to partitions that _may_ have sectors that expire in or + // before that epoch, either on-time or early as faults. + // Keys are quantized to final epochs in each proving deadline. + // + // NOTE: Partitions MUST NOT be removed from this queue (until the + // associated epoch has passed) even if they no longer have sectors + // expiring at that epoch. Sectors expiring at this epoch may later be + // recovered, and this queue will not be updated at that time. + ExpirationsEpochs cid.Cid // AMT[ChainEpoch]BitField + + // Partitions that have been proved by window PoSts so far during the + // current challenge window. + // NOTE: This bitfield includes both partitions whose proofs + // were optimistically accepted and stored in + // OptimisticPoStSubmissions, and those whose proofs were + // verified on-chain. + PartitionsPoSted bitfield.BitField + + // Partitions with sectors that terminated early. + EarlyTerminations bitfield.BitField + + // The number of non-terminated sectors in this deadline (incl faulty). + LiveSectors uint64 + + // The total number of sectors in this deadline (incl dead). + TotalSectors uint64 + + // Memoized sum of faulty power in partitions. + FaultyPower PowerPair + + // AMT of optimistically accepted WindowPoSt proofs, submitted during + // the current challenge window. At the end of the challenge window, + // this AMT will be moved to OptimisticPoStSubmissionsSnapshot. WindowPoSt proofs + // verified on-chain do not appear in this AMT. + OptimisticPoStSubmissions cid.Cid // AMT[]WindowedPoSt + + // Snapshot of the miner's sectors AMT at the end of the previous challenge + // window for this deadline. + SectorsSnapshot cid.Cid // Array, AMT[SectorNumber]SectorOnChainInfo (sparse) + + // Snapshot of partition state at the end of the previous challenge + // window for this deadline. + PartitionsSnapshot cid.Cid + + // Snapshot of the proofs submitted by the end of the previous challenge + // window for this deadline. + // + // These proofs may be disputed via DisputeWindowedPoSt. Successfully + // disputed window PoSts are removed from the snapshot. + OptimisticPoStSubmissionsSnapshot cid.Cid + + // Memoized sum of all non-terminated power in partitions, including active, faulty, and + // unproven. Used to cap the daily fee as a proportion of expected block reward. + LivePower PowerPair + + // Memoized sum of daily fee payable to the network for the active sectors + // in this deadline. + DailyFee abi.TokenAmount +} + +type WindowedPoSt struct { + // Partitions proved by this WindowedPoSt. + Partitions bitfield.BitField + // Array of proofs, one per distinct registered proof type present in + // the sectors being proven. In the usual case of a single proof type, + // this array will always have a single element (independent of number + // of partitions). + Proofs []proof.PoStProof +} + +// Bitwidth of AMTs determined empirically from mutation patterns and projections of mainnet data. +const DeadlinePartitionsAmtBitwidth = 3 // Usually a small array +const DeadlineExpirationAmtBitwidth = 5 + +// Given that 4 partitions can be proven in one post, this AMT's height will +// only exceed the partition AMT's height at ~0.75EiB of storage. +const DeadlineOptimisticPoStSubmissionsAmtBitwidth = 2 + +// +// Deadline (singular) +// + +func ConstructDeadline(store adt.Store) (*Deadline, error) { + emptyPartitionsArrayCid, err := adt.StoreEmptyArray(store, DeadlinePartitionsAmtBitwidth) + if err != nil { + return nil, xerrors.Errorf("failed to construct empty partitions array: %w", err) + } + emptyDeadlineExpirationArrayCid, err := adt.StoreEmptyArray(store, DeadlineExpirationAmtBitwidth) + if err != nil { + return nil, xerrors.Errorf("failed to construct empty deadline expiration array: %w", err) + } + + emptySectorsSnapshotArrayCid, err := adt.StoreEmptyArray(store, SectorsAmtBitwidth) + if err != nil { + return nil, xerrors.Errorf("failed to construct empty sectors snapshot array: %w", err) + } + + emptyPoStSubmissionsArrayCid, err := adt.StoreEmptyArray(store, DeadlineOptimisticPoStSubmissionsAmtBitwidth) + if err != nil { + return nil, xerrors.Errorf("failed to construct empty proofs array: %w", err) + } + + return &Deadline{ + Partitions: emptyPartitionsArrayCid, + ExpirationsEpochs: emptyDeadlineExpirationArrayCid, + EarlyTerminations: bitfield.New(), + LiveSectors: 0, + TotalSectors: 0, + FaultyPower: NewPowerPairZero(), + PartitionsPoSted: bitfield.New(), + OptimisticPoStSubmissions: emptyPoStSubmissionsArrayCid, + PartitionsSnapshot: emptyPartitionsArrayCid, + SectorsSnapshot: emptySectorsSnapshotArrayCid, + OptimisticPoStSubmissionsSnapshot: emptyPoStSubmissionsArrayCid, + }, nil +} + +// +// Deadlines (plural) +// + +func ConstructDeadlines(emptyDeadlineCid cid.Cid) *Deadlines { + d := new(Deadlines) + for i := range d.Due { + d.Due[i] = emptyDeadlineCid + } + return d +} + +func (d *Deadlines) LoadDeadline(store adt.Store, dlIdx uint64) (*Deadline, error) { + if dlIdx >= uint64(len(d.Due)) { + return nil, xc.ErrIllegalArgument.Wrapf("invalid deadline %d", dlIdx) + } + deadline := new(Deadline) + err := store.Get(store.Context(), d.Due[dlIdx], deadline) + if err != nil { + return nil, xc.ErrIllegalState.Wrapf("failed to lookup deadline %d: %w", dlIdx, err) + } + return deadline, nil +} + +func (d *Deadlines) ForEach(store adt.Store, cb func(dlIdx uint64, dl *Deadline) error) error { + for dlIdx := range d.Due { + dl, err := d.LoadDeadline(store, uint64(dlIdx)) + if err != nil { + return err + } + err = cb(uint64(dlIdx), dl) + if err != nil { + return err + } + } + return nil +} + +func (d *Deadlines) UpdateDeadline(store adt.Store, dlIdx uint64, deadline *Deadline) error { + if dlIdx >= uint64(len(d.Due)) { + return xerrors.Errorf("invalid deadline %d", dlIdx) + } + + if err := deadline.ValidateState(); err != nil { + return err + } + + dlCid, err := store.Put(store.Context(), deadline) + if err != nil { + return err + } + d.Due[dlIdx] = dlCid + + return nil +} + +// +// Deadline (singular) +// + +func (d *Deadline) PartitionsArray(store adt.Store) (*adt.Array, error) { + arr, err := adt.AsArray(store, d.Partitions, DeadlinePartitionsAmtBitwidth) + if err != nil { + return nil, xc.ErrIllegalState.Wrapf("failed to load partitions: %w", err) + } + return arr, nil +} + +func (d *Deadline) OptimisticProofsSnapshotArray(store adt.Store) (*adt.Array, error) { + arr, err := adt.AsArray(store, d.OptimisticPoStSubmissionsSnapshot, DeadlineOptimisticPoStSubmissionsAmtBitwidth) + if err != nil { + return nil, xerrors.Errorf("failed to load proofs snapshot: %w", err) + } + return arr, nil +} + +func (d *Deadline) LoadPartition(store adt.Store, partIdx uint64) (*Partition, error) { + partitions, err := d.PartitionsArray(store) + if err != nil { + return nil, err + } + var partition Partition + found, err := partitions.Get(partIdx, &partition) + if err != nil { + return nil, xc.ErrIllegalState.Wrapf("failed to lookup partition %d: %w", partIdx, err) + } + if !found { + return nil, xc.ErrNotFound.Wrapf("no partition %d", partIdx) + } + return &partition, nil +} + +func (d *Deadline) ValidateState() error { + if d.LiveSectors > d.TotalSectors { + return xerrors.Errorf("Deadline left with more live sectors than total: %v", d) + } + + if d.FaultyPower.Raw.LessThan(big.Zero()) || d.FaultyPower.QA.LessThan(big.Zero()) { + return xerrors.Errorf("Deadline left with negative faulty power: %v", d) + } + + return nil +} diff --git a/builtin/v18/miner/deadlines.go b/builtin/v18/miner/deadlines.go new file mode 100644 index 00000000..8dc25957 --- /dev/null +++ b/builtin/v18/miner/deadlines.go @@ -0,0 +1,59 @@ +package miner + +import ( + "errors" + + "golang.org/x/xerrors" + + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/builtin" + "github.com/filecoin-project/go-state-types/builtin/v18/util/adt" + "github.com/filecoin-project/go-state-types/dline" +) + +// Returns deadline-related calculations for a deadline in some proving period and the current epoch. +func NewDeadlineInfo(periodStart abi.ChainEpoch, deadlineIdx uint64, currEpoch abi.ChainEpoch) *dline.Info { + return dline.NewInfo(periodStart, deadlineIdx, currEpoch, WPoStPeriodDeadlines, WPoStProvingPeriod, WPoStChallengeWindow, WPoStChallengeLookback, FaultDeclarationCutoff) +} + +func QuantSpecForDeadline(di *dline.Info) builtin.QuantSpec { + return builtin.NewQuantSpec(WPoStProvingPeriod, di.Last()) +} + +// FindSector returns the deadline and partition index for a sector number. +// It returns an error if the sector number is not tracked by deadlines. +func FindSector(store adt.Store, deadlines *Deadlines, sectorNum abi.SectorNumber) (uint64, uint64, error) { + for dlIdx := range deadlines.Due { + dl, err := deadlines.LoadDeadline(store, uint64(dlIdx)) + if err != nil { + return 0, 0, err + } + + partitions, err := adt.AsArray(store, dl.Partitions, DeadlinePartitionsAmtBitwidth) + if err != nil { + return 0, 0, err + } + var partition Partition + + partIdx := uint64(0) + stopErr := errors.New("stop") + err = partitions.ForEach(&partition, func(i int64) error { + found, err := partition.Sectors.IsSet(uint64(sectorNum)) + if err != nil { + return err + } + if found { + partIdx = uint64(i) + return stopErr + } + return nil + }) + if err == stopErr { + return uint64(dlIdx), partIdx, nil + } else if err != nil { + return 0, 0, err + } + + } + return 0, 0, xerrors.Errorf("sector %d not due at any deadline", sectorNum) +} diff --git a/builtin/v18/miner/invariants.go b/builtin/v18/miner/invariants.go new file mode 100644 index 00000000..8258ed45 --- /dev/null +++ b/builtin/v18/miner/invariants.go @@ -0,0 +1,924 @@ +package miner + +import ( + "errors" + + addr "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/builtin" + "github.com/filecoin-project/go-state-types/builtin/v18/util" + "github.com/filecoin-project/go-state-types/builtin/v18/util/adt" +) + +type DealSummary struct { + SectorStart abi.ChainEpoch + SectorExpiration abi.ChainEpoch + SectorNumber abi.SectorNumber +} + +type StateSummary struct { + LivePower PowerPair + ActivePower PowerPair + FaultyPower PowerPair + Deals map[abi.DealID]DealSummary + WindowPoStProofType abi.RegisteredPoStProof + DeadlineCronActive bool +} + +// Checks internal invariants of init state. +func CheckStateInvariants(st *State, store adt.Store, balance abi.TokenAmount) (*StateSummary, *builtin.MessageAccumulator) { + acc := &builtin.MessageAccumulator{} + sectorSize := abi.SectorSize(0) + minerSummary := &StateSummary{ + LivePower: NewPowerPairZero(), + ActivePower: NewPowerPairZero(), + FaultyPower: NewPowerPairZero(), + WindowPoStProofType: 0, + DeadlineCronActive: st.DeadlineCronActive, + } + + // Load data from linked structures. + if info, err := st.GetInfo(store); err != nil { + acc.Addf("error loading miner info: %v", err) + // Stop here, it's too hard to make other useful checks. + return minerSummary, acc + } else { + minerSummary.WindowPoStProofType = info.WindowPoStProofType + sectorSize = info.SectorSize + CheckMinerInfo(info, acc) + } + + CheckMinerBalances(st, store, balance, acc) + + var allocatedSectors bitfield.BitField + var allocatedSectorsMap map[uint64]bool + if err := store.Get(store.Context(), st.AllocatedSectors, &allocatedSectors); err != nil { + acc.Addf("error loading allocated sector bitfield: %v", err) + } else { + allocatedSectorsMap, err = allocatedSectors.AllMap(1 << 30) + // if it's too big to expand, we'll fall back on the bitfield directly + if err != nil && !errors.Is(err, bitfield.ErrBitFieldTooMany) { + acc.Addf("error expanding allocated sector bitfield: %v", err) + allocatedSectorsMap = nil + } + } + + CheckPreCommits(st, store, allocatedSectorsMap, allocatedSectors, acc) + + minerSummary.Deals = map[abi.DealID]DealSummary{} + var allSectors map[abi.SectorNumber]*SectorOnChainInfo + if sectorsArr, err := adt.AsArray(store, st.Sectors, SectorsAmtBitwidth); err != nil { + acc.Addf("error loading sectors") + } else { + allSectors = map[abi.SectorNumber]*SectorOnChainInfo{} + var sector SectorOnChainInfo + err = sectorsArr.ForEach(§or, func(sno int64) error { + acc.Require(sector.PowerBaseEpoch >= sector.Activation, "sector %d has PBE %d < Activation %d", + sector.SectorNumber, + sector.PowerBaseEpoch, + sector.Activation) + + cpy := sector + allSectors[abi.SectorNumber(sno)] = &cpy + + allocated := false + if allocatedSectorsMap != nil { + allocated = allocatedSectorsMap[uint64(sno)] + } else { + allocated, err = allocatedSectors.IsSet(uint64(sno)) + if err != nil { + acc.Addf("error checking allocated sectors: %v", err) + return nil + } + } + + acc.Require(allocated, + "on chain sector's sector number has not been allocated %d", sno) + + for _, dealID := range sector.DeprecatedDealIDs { + minerSummary.Deals[dealID] = DealSummary{ + SectorStart: sector.Activation, + SectorExpiration: sector.Expiration, + SectorNumber: sector.SectorNumber, + } + } + + return nil + }) + acc.RequireNoError(err, "error iterating sectors") + } + + // Check deadlines + acc.Require(st.CurrentDeadline < WPoStPeriodDeadlines, + "current deadline index is greater than deadlines per period(%d): %d", WPoStPeriodDeadlines, st.CurrentDeadline) + + deadlines, err := st.LoadDeadlines(store) + if err != nil { + acc.Addf("error loading deadlines: %v", err) + deadlines = nil + } + + if allSectors != nil && deadlines != nil { + err = deadlines.ForEach(store, func(dlIdx uint64, dl *Deadline) error { + acc := acc.WithPrefix("deadline %d: ", dlIdx) // Shadow + quant := st.QuantSpecForDeadline(dlIdx) + dlSummary := CheckDeadlineStateInvariants(dl, store, quant, sectorSize, allSectors, acc) + + minerSummary.LivePower = minerSummary.LivePower.Add(dlSummary.LivePower) + minerSummary.ActivePower = minerSummary.ActivePower.Add(dlSummary.ActivePower) + minerSummary.FaultyPower = minerSummary.FaultyPower.Add(dlSummary.FaultyPower) + return nil + }) + acc.RequireNoError(err, "error iterating deadlines") + } + + return minerSummary, acc +} + +type DeadlineStateSummary struct { + AllSectors bitfield.BitField + LiveSectors bitfield.BitField + FaultySectors bitfield.BitField + RecoveringSectors bitfield.BitField + UnprovenSectors bitfield.BitField + TerminatedSectors bitfield.BitField + LivePower PowerPair + ActivePower PowerPair + FaultyPower PowerPair +} + +func CheckDeadlineStateInvariants(deadline *Deadline, store adt.Store, quant builtin.QuantSpec, ssize abi.SectorSize, + sectors map[abi.SectorNumber]*SectorOnChainInfo, acc *builtin.MessageAccumulator) *DeadlineStateSummary { + + // Load linked structures. + partitions, err := deadline.PartitionsArray(store) + if err != nil { + acc.Addf("error loading partitions: %v", err) + // Hard to do any useful checks. + return &DeadlineStateSummary{ + AllSectors: bitfield.New(), + LiveSectors: bitfield.New(), + FaultySectors: bitfield.New(), + RecoveringSectors: bitfield.New(), + UnprovenSectors: bitfield.New(), + TerminatedSectors: bitfield.New(), + LivePower: NewPowerPairZero(), + ActivePower: NewPowerPairZero(), + FaultyPower: NewPowerPairZero(), + } + } + + allSectors := bitfield.New() + var allLiveSectors []bitfield.BitField + var allFaultySectors []bitfield.BitField + var allRecoveringSectors []bitfield.BitField + var allUnprovenSectors []bitfield.BitField + var allTerminatedSectors []bitfield.BitField + allLivePower := NewPowerPairZero() + allActivePower := NewPowerPairZero() + allFaultyPower := NewPowerPairZero() + allDailyFee := big.Zero() + + // Check partitions. + partitionsWithExpirations := map[abi.ChainEpoch][]uint64{} + var partitionsWithEarlyTerminations []uint64 + partitionCount := uint64(0) + var partition Partition + err = partitions.ForEach(&partition, func(i int64) error { + pIdx := uint64(i) + // Check sequential partitions. + acc.Require(pIdx == partitionCount, "Non-sequential partitions, expected index %d, found %d", partitionCount, pIdx) + partitionCount++ + + acc := acc.WithPrefix("partition %d: ", pIdx) // Shadow + summary := CheckPartitionStateInvariants(&partition, store, quant, ssize, sectors, acc) + + if contains, err := util.BitFieldContainsAny(allSectors, summary.AllSectors); err != nil { + acc.Addf("error checking bitfield contains: %v", err) + } else { + acc.Require(!contains, "duplicate sector in partition %d", pIdx) + } + + for _, e := range summary.ExpirationEpochs { + partitionsWithExpirations[e] = append(partitionsWithExpirations[e], pIdx) + } + if summary.EarlyTerminationCount > 0 { + partitionsWithEarlyTerminations = append(partitionsWithEarlyTerminations, pIdx) + } + + allSectors, err = bitfield.MergeBitFields(allSectors, summary.AllSectors) + if err != nil { + acc.Addf("error merging partition sector numbers with all: %v", err) + allSectors = bitfield.New() + } + allLiveSectors = append(allLiveSectors, summary.LiveSectors) + allFaultySectors = append(allFaultySectors, summary.FaultySectors) + allRecoveringSectors = append(allRecoveringSectors, summary.RecoveringSectors) + allUnprovenSectors = append(allUnprovenSectors, summary.UnprovenSectors) + allTerminatedSectors = append(allTerminatedSectors, summary.TerminatedSectors) + allLivePower = allLivePower.Add(summary.LivePower) + allActivePower = allActivePower.Add(summary.ActivePower) + allFaultyPower = allFaultyPower.Add(summary.FaultyPower) + allDailyFee = big.Add(allDailyFee, summary.DailyFee) + return nil + }) + acc.RequireNoError(err, "error iterating partitions") + + // Check invariants on partitions proven. + { + if lastProof, err := deadline.PartitionsPoSted.Last(); err != nil { + if err != bitfield.ErrNoBitsSet { + acc.Addf("error determining the last partition proven: %v", err) + } + } else { + acc.Require(partitionCount >= (lastProof+1), "expected at least %d partitions, found %d", lastProof+1, partitionCount) + acc.Require(deadline.LiveSectors > 0, "expected at least one live sector when partitions have been proven") + } + } + + // Check partitions snapshot to make sure we take the snapshot after + // dealing with recovering power and unproven power. + partitionsSnapshot, err := deadline.PartitionsSnapshotArray(store) + acc.RequireNoError(err, "error loading partitions snapshot") + err = partitionsSnapshot.ForEach(&partition, func(i int64) error { + acc := acc.WithPrefix("partition snapshot %d: ", i) // Shadow + + acc.Require(partition.RecoveringPower.IsZero(), "snapshot partition has recovering power") + if noRecoveries, err := partition.Recoveries.IsEmpty(); err != nil { + acc.Addf("error counting recoveries: %v", err) + } else { + acc.Require(noRecoveries, "snapshot partition has pending recoveries") + } + + acc.Require(partition.UnprovenPower.IsZero(), "snapshot partition has unproven power") + if noUnproven, err := partition.Unproven.IsEmpty(); err != nil { + acc.Addf("error counting unproven: %v", err) + } else { + acc.Require(noUnproven, "snapshot partition has unproven sectors") + } + + return nil + }) + acc.RequireNoError(err, "error iterating partitions snapshot") + + // Check that we don't have any proofs proving partitions that are not in the snapshot. + proofsSnapshot, err := deadline.OptimisticProofsSnapshotArray(store) + acc.RequireNoError(err, "error loading proofs snapshot") + var proof WindowedPoSt + err = proofsSnapshot.ForEach(&proof, func(_ int64) error { + err = proof.Partitions.ForEach(func(i uint64) error { + found, err := partitionsSnapshot.Get(i, &partition) + acc.RequireNoError(err, "error loading partition snapshot") + acc.Require(found, "failed to find partition for recorded proof in the snapshot") + return nil + }) + acc.RequireNoError(err, "error iterating proof partitions bitfield") + return nil + }) + acc.RequireNoError(err, "error iterating proofs snapshot") + + // Check memoized sector and power values. + live, err := bitfield.MultiMerge(allLiveSectors...) + if err != nil { + acc.Addf("error merging live sector numbers: %v", err) + live = bitfield.New() + } else { + if liveCount, err := live.Count(); err != nil { + acc.Addf("error counting live sectors: %v", err) + } else { + acc.Require(deadline.LiveSectors == liveCount, "deadline live sectors %d != partitions count %d", deadline.LiveSectors, liveCount) + } + } + + if allCount, err := allSectors.Count(); err != nil { + acc.Addf("error counting all sectors: %v", err) + } else { + acc.Require(deadline.TotalSectors == allCount, "deadline total sectors %d != partitions count %d", deadline.TotalSectors, allCount) + } + + faulty, err := bitfield.MultiMerge(allFaultySectors...) + if err != nil { + acc.Addf("error merging faulty sector numbers: %v", err) + faulty = bitfield.New() + } + recovering, err := bitfield.MultiMerge(allRecoveringSectors...) + if err != nil { + acc.Addf("error merging recovering sector numbers: %v", err) + recovering = bitfield.New() + } + unproven, err := bitfield.MultiMerge(allUnprovenSectors...) + if err != nil { + acc.Addf("error merging unproven sector numbers: %v", err) + unproven = bitfield.New() + } + terminated, err := bitfield.MultiMerge(allTerminatedSectors...) + if err != nil { + acc.Addf("error merging terminated sector numbers: %v", err) + terminated = bitfield.New() + } + + acc.Require(deadline.FaultyPower.Equals(allFaultyPower), "deadline faulty power %v != partitions total %v", deadline.FaultyPower, allFaultyPower) + acc.Require(deadline.LivePower.Equals(allLivePower), "deadline live power %v != partitions total %v", deadline.LivePower, allLivePower) + acc.Require(deadline.DailyFee.Equals(allDailyFee), "deadline daily fee %v != partitions total %v", deadline.DailyFee, allDailyFee) + + { + // Validate partition expiration queue contains an entry for each partition and epoch with an expiration. + // The queue may be a superset of the partitions that have expirations because we never remove from it. + if expirationEpochs, err := adt.AsArray(store, deadline.ExpirationsEpochs, DeadlineExpirationAmtBitwidth); err != nil { + acc.Addf("error loading expiration queue: %v", err) + } else { + for epoch, expiringPIdxs := range partitionsWithExpirations { // nolint:nomaprange + var bf bitfield.BitField + if found, err := expirationEpochs.Get(uint64(epoch), &bf); err != nil { + acc.Addf("error fetching expiration bitfield: %v", err) + } else { + acc.Require(found, "expected to find partition expiration entry at epoch %d", epoch) + } + + if queuedPIdxs, err := bf.AllMap(1 << 20); err != nil { + acc.Addf("error expanding expirating partitions: %v", err) + } else { + for _, p := range expiringPIdxs { + acc.Require(queuedPIdxs[p], "expected partition %d to be present in deadline expiration queue at epoch %d", p, epoch) + } + } + } + } + } + { + // Validate the early termination queue contains exactly the partitions with early terminations. + expected := bitfield.NewFromSet(partitionsWithEarlyTerminations) + requireEqual(expected, deadline.EarlyTerminations, acc, "deadline early terminations doesn't match expected partitions") + } + + return &DeadlineStateSummary{ + AllSectors: allSectors, + LiveSectors: live, + FaultySectors: faulty, + RecoveringSectors: recovering, + UnprovenSectors: unproven, + TerminatedSectors: terminated, + LivePower: allLivePower, + ActivePower: allActivePower, + FaultyPower: allFaultyPower, + } +} + +type PartitionStateSummary struct { + AllSectors bitfield.BitField + LiveSectors bitfield.BitField + FaultySectors bitfield.BitField + RecoveringSectors bitfield.BitField + UnprovenSectors bitfield.BitField + TerminatedSectors bitfield.BitField + LivePower PowerPair + ActivePower PowerPair + FaultyPower PowerPair + RecoveringPower PowerPair + DailyFee abi.TokenAmount + ExpirationEpochs []abi.ChainEpoch // Epochs at which some sector is scheduled to expire. + EarlyTerminationCount int +} + +func CheckPartitionStateInvariants( + partition *Partition, + store adt.Store, + quant builtin.QuantSpec, + sectorSize abi.SectorSize, + sectors map[abi.SectorNumber]*SectorOnChainInfo, + acc *builtin.MessageAccumulator, +) *PartitionStateSummary { + irrecoverable := false // State is so broken we can't make useful checks. + live, err := partition.LiveSectors() + if err != nil { + acc.Addf("error computing live sectors: %v", err) + irrecoverable = true + } + active, err := partition.ActiveSectors() + if err != nil { + acc.Addf("error computing active sectors: %v", err) + irrecoverable = true + } + + if irrecoverable { + return &PartitionStateSummary{ + AllSectors: partition.Sectors, + LiveSectors: bitfield.New(), + FaultySectors: partition.Faults, + RecoveringSectors: partition.Recoveries, + UnprovenSectors: partition.Unproven, + TerminatedSectors: partition.Terminated, + LivePower: partition.LivePower, + ActivePower: partition.ActivePower(), + FaultyPower: partition.FaultyPower, + RecoveringPower: partition.RecoveringPower, + ExpirationEpochs: nil, + EarlyTerminationCount: 0, + } + } + + // Live contains all active sectors. + requireContainsAll(live, active, acc, "live does not contain active") + + // Live contains all faults. + requireContainsAll(live, partition.Faults, acc, "live does not contain faults") + + // Live contains all unproven. + requireContainsAll(live, partition.Unproven, acc, "live does not contain unproven") + + // Active contains no faults + requireContainsNone(active, partition.Faults, acc, "active includes faults") + + // Active contains no unproven + requireContainsNone(active, partition.Unproven, acc, "active includes unproven") + + // Faults contains all recoveries. + requireContainsAll(partition.Faults, partition.Recoveries, acc, "faults do not contain recoveries") + + // Live contains no terminated sectors + requireContainsNone(live, partition.Terminated, acc, "live includes terminations") + + // Unproven contains no faults + requireContainsNone(partition.Faults, partition.Unproven, acc, "unproven includes faults") + + // All terminated sectors are part of the partition. + requireContainsAll(partition.Sectors, partition.Terminated, acc, "sectors do not contain terminations") + + // Validate power + var liveSectors map[abi.SectorNumber]*SectorOnChainInfo + var missing []abi.SectorNumber + livePower := NewPowerPairZero() + faultyPower := NewPowerPairZero() + unprovenPower := NewPowerPairZero() + + if liveSectors, missing, err = selectSectorsMap(sectors, live); err != nil { + acc.Addf("error selecting live sectors: %v", err) + } else if len(missing) > 0 { + acc.Addf("live sectors missing from all sectors: %v", missing) + } else { + livePower = powerForSectors(liveSectors, sectorSize) + acc.Require(partition.LivePower.Equals(livePower), "live power was %v, expected %v", partition.LivePower, livePower) + } + + if unprovenSectors, missing, err := selectSectorsMap(sectors, partition.Unproven); err != nil { + acc.Addf("error selecting unproven sectors: %v", err) + } else if len(missing) > 0 { + acc.Addf("unproven sectors missing from all sectors: %v", missing) + } else { + unprovenPower = powerForSectors(unprovenSectors, sectorSize) + acc.Require(partition.UnprovenPower.Equals(unprovenPower), "unproven power was %v, expected %v", partition.UnprovenPower, unprovenPower) + } + + if faultySectors, missing, err := selectSectorsMap(sectors, partition.Faults); err != nil { + acc.Addf("error selecting faulty sectors: %v", err) + } else if len(missing) > 0 { + acc.Addf("faulty sectors missing from all sectors: %v", missing) + } else { + faultyPower = powerForSectors(faultySectors, sectorSize) + acc.Require(partition.FaultyPower.Equals(faultyPower), "faulty power was %v, expected %v", partition.FaultyPower, faultyPower) + } + + if recoveringSectors, missing, err := selectSectorsMap(sectors, partition.Recoveries); err != nil { + acc.Addf("error selecting recovering sectors: %v", err) + } else if len(missing) > 0 { + acc.Addf("recovering sectors missing from all sectors: %v", missing) + } else { + recoveringPower := powerForSectors(recoveringSectors, sectorSize) + acc.Require(partition.RecoveringPower.Equals(recoveringPower), "recovering power was %v, expected %v", partition.RecoveringPower, recoveringPower) + } + + activePower := livePower.Sub(faultyPower).Sub(unprovenPower) + partitionActivePower := partition.ActivePower() + acc.Require(partitionActivePower.Equals(activePower), "active power was %v, expected %v", partitionActivePower, activePower) + + // Validate the expiration queue. + var expirationEpochs []abi.ChainEpoch + feeDeduction := big.Zero() + if expQ, err := LoadExpirationQueue(store, partition.ExpirationsEpochs, quant, PartitionExpirationAmtBitwidth); err != nil { + acc.Addf("error loading expiration queue: %v", err) + } else if liveSectors != nil { + qsummary := CheckExpirationQueue(expQ, liveSectors, partition.Faults, quant, sectorSize, acc) + expirationEpochs = qsummary.ExpirationEpochs + feeDeduction = qsummary.FeeDeduction + + // Check the queue is compatible with partition fields + if qSectors, err := bitfield.MergeBitFields(qsummary.OnTimeSectors, qsummary.EarlySectors); err != nil { + acc.Addf("error merging summary on-time and early sectors: %v", err) + } else { + requireEqual(live, qSectors, acc, "live does not equal all expirations") + } + } + + // Validate the early termination queue. + earlyTerminationCount := 0 + if earlyQ, err := util.LoadBitfieldQueue(store, partition.EarlyTerminated, builtin.NoQuantization, PartitionEarlyTerminationArrayAmtBitwidth); err != nil { + acc.Addf("error loading early termination queue: %v", err) + } else { + earlyTerminationCount = CheckEarlyTerminationQueue(earlyQ, partition.Terminated, acc) + } + + return &PartitionStateSummary{ + AllSectors: partition.Sectors, + LiveSectors: live, + FaultySectors: partition.Faults, + RecoveringSectors: partition.Recoveries, + UnprovenSectors: partition.Unproven, + TerminatedSectors: partition.Terminated, + LivePower: livePower, + ActivePower: activePower, + FaultyPower: partition.FaultyPower, + RecoveringPower: partition.RecoveringPower, + ExpirationEpochs: expirationEpochs, + EarlyTerminationCount: earlyTerminationCount, + DailyFee: feeDeduction, + } +} + +type ExpirationQueueStateSummary struct { + OnTimeSectors bitfield.BitField + EarlySectors bitfield.BitField + ActivePower PowerPair + FaultyPower PowerPair + OnTimePledge abi.TokenAmount + FeeDeduction abi.TokenAmount + ExpirationEpochs []abi.ChainEpoch +} + +// Checks the expiration queue for consistency. +func CheckExpirationQueue(expQ ExpirationQueue, liveSectors map[abi.SectorNumber]*SectorOnChainInfo, + partitionFaults bitfield.BitField, quant builtin.QuantSpec, sectorSize abi.SectorSize, acc *builtin.MessageAccumulator) *ExpirationQueueStateSummary { + partitionFaultsMap, err := partitionFaults.AllMap(1 << 30) + if err != nil { + acc.Addf("error loading partition faults map: %v", err) + partitionFaultsMap = nil + } + + seenSectors := make(map[abi.SectorNumber]bool) + var allOnTime []bitfield.BitField + var allEarly []bitfield.BitField + var expirationEpochs []abi.ChainEpoch + allActivePower := NewPowerPairZero() + allFaultyPower := NewPowerPairZero() + allOnTimePledge := big.Zero() + allFeeDeduction := big.Zero() + firstQueueEpoch := abi.ChainEpoch(-1) + var exp ExpirationSet + err = expQ.ForEach(&exp, func(e int64) error { + epoch := abi.ChainEpoch(e) + acc := acc.WithPrefix("expiration epoch %d: ", epoch) + if firstQueueEpoch == abi.ChainEpoch(-1) { + firstQueueEpoch = epoch + } + expirationEpochs = append(expirationEpochs, epoch) + + dailyFee := big.Zero() + onTimeSectorsPledge := big.Zero() + err := exp.OnTimeSectors.ForEach(func(n uint64) error { + sno := abi.SectorNumber(n) + // Check sectors are present only once. + acc.Require(!seenSectors[sno], "sector %d in expiration queue twice", sno) + seenSectors[sno] = true + + // Check expiring sectors are still alive. + if sector, ok := liveSectors[sno]; ok { + // The sector can be "on time" either at its target expiration epoch, or in the first queue entry + // (a CC-replaced sector moved forward). + target := quant.QuantizeUp(sector.Expiration) + acc.Require(epoch == target || epoch == firstQueueEpoch, "invalid expiration %d for sector %d, expected %d or %d", + epoch, sector.SectorNumber, firstQueueEpoch, target) + + onTimeSectorsPledge = big.Add(onTimeSectorsPledge, sector.InitialPledge) + dailyFee = big.Add(dailyFee, sector.DailyFee) + } else { + acc.Addf("on-time expiration sector %d isn't live", n) + } + return nil + }) + acc.RequireNoError(err, "error iterating on-time sectors") + + err = exp.EarlySectors.ForEach(func(n uint64) error { + sno := abi.SectorNumber(n) + // Check sectors are present only once. + acc.Require(!seenSectors[sno], "sector %d in expiration queue twice", sno) + seenSectors[sno] = true + + // Check early sectors are faulty + acc.Require(partitionFaultsMap == nil || partitionFaultsMap[n], "sector %d expiring early but not faulty", sno) + + // Check expiring sectors are still alive. + if sector, ok := liveSectors[sno]; ok { + target := quant.QuantizeUp(sector.Expiration) + acc.Require(epoch < target, "invalid early expiration %d for sector %d, expected < %d", + epoch, sector.SectorNumber, target) + dailyFee = big.Add(dailyFee, sector.DailyFee) + } else { + acc.Addf("on-time expiration sector %d isn't live", n) + } + return nil + }) + acc.RequireNoError(err, "error iterating early sectors") + + // Validate power and pledge. + var activeSectors, faultySectors map[abi.SectorNumber]*SectorOnChainInfo + var missing []abi.SectorNumber + + all, err := bitfield.MergeBitFields(exp.OnTimeSectors, exp.EarlySectors) + if err != nil { + acc.Addf("error merging all on-time and early bitfields: %v", err) + } else { + if allActive, err := bitfield.SubtractBitField(all, partitionFaults); err != nil { + acc.Addf("error computing active sectors: %v", err) + } else { + activeSectors, missing, err = selectSectorsMap(liveSectors, allActive) + if err != nil { + acc.Addf("error selecting active sectors: %v", err) + activeSectors = nil + } else if len(missing) > 0 { + acc.Addf("active sectors missing from live: %v", missing) + } + } + + if allFaulty, err := bitfield.IntersectBitField(all, partitionFaults); err != nil { + acc.Addf("error computing faulty sectors: %v", err) + } else { + faultySectors, missing, err = selectSectorsMap(liveSectors, allFaulty) + if err != nil { + acc.Addf("error selecting faulty sectors: %v", err) + faultySectors = nil + } else if len(missing) > 0 { + acc.Addf("faulty sectors missing from live: %v", missing) + } + } + } + + if activeSectors != nil && faultySectors != nil { + activeSectorsPower := powerForSectors(activeSectors, sectorSize) + acc.Require(exp.ActivePower.Equals(activeSectorsPower), "active power recorded %v doesn't match computed %v", exp.ActivePower, activeSectorsPower) + + faultySectorsPower := powerForSectors(faultySectors, sectorSize) + acc.Require(exp.FaultyPower.Equals(faultySectorsPower), "faulty power recorded %v doesn't match computed %v", exp.FaultyPower, faultySectorsPower) + } + + acc.Require(exp.OnTimePledge.Equals(onTimeSectorsPledge), "on time pledge recorded %v doesn't match computed %v", exp.OnTimePledge, onTimeSectorsPledge) + acc.Require(exp.FeeDeduction.Equals(dailyFee), "daily fee recorded %v doesn't match computed %v", exp.FeeDeduction, dailyFee) + + allOnTime = append(allOnTime, exp.OnTimeSectors) + allEarly = append(allEarly, exp.EarlySectors) + allActivePower = allActivePower.Add(exp.ActivePower) + allFaultyPower = allFaultyPower.Add(exp.FaultyPower) + allOnTimePledge = big.Add(allOnTimePledge, exp.OnTimePledge) + allFeeDeduction = big.Add(allFeeDeduction, exp.FeeDeduction) + return nil + }) + acc.RequireNoError(err, "error iterating expiration queue") + + unionOnTime, err := bitfield.MultiMerge(allOnTime...) + if err != nil { + acc.Addf("error merging on-time sector numbers: %v", err) + unionOnTime = bitfield.New() + } + unionEarly, err := bitfield.MultiMerge(allEarly...) + if err != nil { + acc.Addf("error merging early sector numbers: %v", err) + unionEarly = bitfield.New() + } + return &ExpirationQueueStateSummary{ + OnTimeSectors: unionOnTime, + EarlySectors: unionEarly, + ActivePower: allActivePower, + FaultyPower: allFaultyPower, + OnTimePledge: allOnTimePledge, + FeeDeduction: allFeeDeduction, + ExpirationEpochs: expirationEpochs, + } +} + +// Checks the early termination queue for consistency. +// Returns the number of sectors in the queue. +func CheckEarlyTerminationQueue(earlyQ util.BitfieldQueue, terminated bitfield.BitField, acc *builtin.MessageAccumulator) int { + seenMap := make(map[uint64]bool) + seenBf := bitfield.New() + err := earlyQ.ForEach(func(epoch abi.ChainEpoch, bf bitfield.BitField) error { + acc := acc.WithPrefix("early termination epoch %d: ", epoch) + err := bf.ForEach(func(i uint64) error { + acc.Require(!seenMap[i], "sector %v in early termination queue twice", i) + seenMap[i] = true + seenBf.Set(i) + return nil + }) + acc.RequireNoError(err, "error iterating early termination bitfield") + return nil + }) + acc.RequireNoError(err, "error iterating early termination queue") + + requireContainsAll(terminated, seenBf, acc, "terminated sectors missing early termination entry") + return len(seenMap) +} + +func CheckMinerInfo(info *MinerInfo, acc *builtin.MessageAccumulator) { + acc.Require(info.Owner.Protocol() == addr.ID, "owner address %v is not an ID address", info.Owner) + acc.Require(info.Worker.Protocol() == addr.ID, "worker address %v is not an ID address", info.Worker) + for _, a := range info.ControlAddresses { + acc.Require(a.Protocol() == addr.ID, "control address %v is not an ID address", a) + } + + if info.PendingWorkerKey != nil { + acc.Require(info.PendingWorkerKey.NewWorker.Protocol() == addr.ID, + "pending worker address %v is not an ID address", info.PendingWorkerKey.NewWorker) + acc.Require(info.PendingWorkerKey.NewWorker != info.Worker, + "pending worker key %v is same as existing worker %v", info.PendingWorkerKey.NewWorker, info.Worker) + } + + if info.PendingOwnerAddress != nil { + acc.Require(info.PendingOwnerAddress.Protocol() == addr.ID, + "pending owner address %v is not an ID address", info.PendingOwnerAddress) + acc.Require(*info.PendingOwnerAddress != info.Owner, + "pending owner address %v is same as existing owner %v", info.PendingOwnerAddress, info.Owner) + } + + windowPoStProofInfo, found := abi.PoStProofInfos[info.WindowPoStProofType] + acc.Require(found, "miner has unrecognized Window PoSt proof type %d", info.WindowPoStProofType) + if found { + acc.Require(windowPoStProofInfo.SectorSize == info.SectorSize, + "sector size %d is wrong for Window PoSt proof type %d: %d", info.SectorSize, info.WindowPoStProofType, windowPoStProofInfo.SectorSize) + } + + poStProofPolicy, found := builtin.PoStProofPolicies[info.WindowPoStProofType] + acc.Require(found, "no PoSt proof policy exists for proof type %d", info.WindowPoStProofType) + if found { + acc.Require(poStProofPolicy.WindowPoStPartitionSectors == info.WindowPoStPartitionSectors, + "miner partition sectors %d does not match partition sectors %d for PoSt proof type %d", + info.WindowPoStPartitionSectors, poStProofPolicy.WindowPoStPartitionSectors, info.WindowPoStProofType) + } +} + +func CheckMinerBalances(st *State, store adt.Store, balance abi.TokenAmount, acc *builtin.MessageAccumulator) { + acc.Require(balance.GreaterThanEqual(big.Zero()), "miner actor balance is less than zero: %v", balance) + acc.Require(st.LockedFunds.GreaterThanEqual(big.Zero()), "miner locked funds is less than zero: %v", st.LockedFunds) + acc.Require(st.PreCommitDeposits.GreaterThanEqual(big.Zero()), "miner precommit deposit is less than zero: %v", st.PreCommitDeposits) + acc.Require(st.InitialPledge.GreaterThanEqual(big.Zero()), "miner initial pledge is less than zero: %v", st.InitialPledge) + acc.Require(st.FeeDebt.GreaterThanEqual(big.Zero()), "miner fee debt is less than zero: %v", st.FeeDebt) + + acc.Require(big.Subtract(balance, st.LockedFunds, st.PreCommitDeposits, st.InitialPledge).GreaterThanEqual(big.Zero()), + "miner balance (%v) is less than sum of locked funds (%v), precommit deposit (%v), and initial pledge (%v)", + balance, st.LockedFunds, st.PreCommitDeposits, st.InitialPledge) + + // locked funds must be sum of vesting table and vesting table payments must be quantized + vestingSum := big.Zero() + if funds, err := st.LoadVestingFunds(store); err != nil { + acc.Addf("error loading vesting funds: %v", err) + } else { + quant := st.QuantSpecEveryDeadline() + for _, entry := range funds { + acc.Require(entry.Amount.GreaterThan(big.Zero()), "non-positive amount in miner vesting table entry %v", entry) + vestingSum = big.Add(vestingSum, entry.Amount) + + quantized := quant.QuantizeUp(entry.Epoch) + acc.Require(entry.Epoch == quantized, "vesting table entry has non-quantized epoch %d (should be %d)", entry.Epoch, quantized) + } + } + + acc.Require(st.LockedFunds.Equals(vestingSum), + "locked funds %d is not sum of vesting table entries %d", st.LockedFunds, vestingSum) + + // Non zero funds implies that DeadlineCronActive is true. + if st.ContinueDeadlineCron() { + acc.Require(st.DeadlineCronActive, "DeadlineCronActive == false when IP+PCD+LF > 0") + } +} + +func CheckPreCommits(st *State, store adt.Store, allocatedSectorsMap map[uint64]bool, allocatedSectorsBf bitfield.BitField, acc *builtin.MessageAccumulator) { + quant := st.QuantSpecEveryDeadline() + + // invert pre-commit clean up queue into a lookup by sector number + cleanUpEpochs := make(map[uint64]abi.ChainEpoch) + if cleanUpQ, err := util.LoadBitfieldQueue(store, st.PreCommittedSectorsCleanUp, st.QuantSpecEveryDeadline(), PrecommitCleanUpAmtBitwidth); err != nil { + acc.Addf("error loading pre-commit clean up queue: %v", err) + } else { + err = cleanUpQ.ForEach(func(epoch abi.ChainEpoch, bf bitfield.BitField) error { + quantized := quant.QuantizeUp(epoch) + acc.Require(quantized == epoch, "precommit expiration %d is not quantized", epoch) + if err = bf.ForEach(func(secNum uint64) error { + cleanUpEpochs[secNum] = epoch + return nil + }); err != nil { + acc.Addf("error iteration pre-commit expiration bitfield: %v", err) + } + return nil + }) + acc.RequireNoError(err, "error iterating pre-commit clean up queue") + } + + precommitTotal := big.Zero() + if precommitted, err := adt.AsMap(store, st.PreCommittedSectors, builtin.DefaultHamtBitwidth); err != nil { + acc.Addf("error loading precommitted sectors: %v", err) + } else { + var precommit SectorPreCommitOnChainInfo + err = precommitted.ForEach(&precommit, func(key string) error { + secNum, err := abi.ParseUIntKey(key) + if err != nil { + acc.Addf("error parsing pre-commit key as uint: %v", err) + return nil + } + + allocated := false + if allocatedSectorsMap != nil { + allocated = allocatedSectorsMap[secNum] + } else { + allocated, err = allocatedSectorsBf.IsSet(secNum) + if err != nil { + acc.Addf("error checking allocated sectors: %v", err) + return nil + } + } + acc.Require(allocated, "pre-committed sector number has not been allocated %d", secNum) + + _, found := cleanUpEpochs[secNum] + acc.Require(found, "no clean up epoch for pre-commit at %d", precommit.PreCommitEpoch) + + precommitTotal = big.Add(precommitTotal, precommit.PreCommitDeposit) + return nil + }) + acc.RequireNoError(err, "error iterating pre-committed sectors") + } + + acc.Require(st.PreCommitDeposits.Equals(precommitTotal), + "sum of precommit deposits %v does not equal recorded precommit deposit %v", precommitTotal, st.PreCommitDeposits) +} + +// Selects a subset of sectors from a map by sector number. +// Returns the selected sectors, and a slice of any sector numbers not found. +func selectSectorsMap(sectors map[abi.SectorNumber]*SectorOnChainInfo, include bitfield.BitField) (map[abi.SectorNumber]*SectorOnChainInfo, []abi.SectorNumber, error) { + included := map[abi.SectorNumber]*SectorOnChainInfo{} + missing := []abi.SectorNumber{} + if err := include.ForEach(func(n uint64) error { + if s, ok := sectors[abi.SectorNumber(n)]; ok { + included[abi.SectorNumber(n)] = s + } else { + missing = append(missing, abi.SectorNumber(n)) + } + return nil + }); err != nil { + return nil, nil, err + } + return included, missing, nil +} + +func powerForSectors(sectors map[abi.SectorNumber]*SectorOnChainInfo, ssize abi.SectorSize) PowerPair { + qa := big.Zero() + for _, s := range sectors { // nolint:nomaprange + qa = big.Add(qa, QAPowerForSector(ssize, s)) + } + + return PowerPair{ + Raw: big.Mul(big.NewIntUnsigned(uint64(ssize)), big.NewIntUnsigned(uint64(len(sectors)))), + QA: qa, + } +} + +func requireContainsAll(superset, subset bitfield.BitField, acc *builtin.MessageAccumulator, msg string) { + if contains, err := util.BitFieldContainsAll(superset, subset); err != nil { + acc.Addf("error in BitfieldContainsAll(): %v", err) + } else if !contains { + acc.Addf(msg+": %v, %v", superset, subset) + // Verbose output for debugging + //sup, err := superset.All(1 << 20) + //if err != nil { + // acc.Addf("error in Bitfield.All(): %v", err) + // return + //} + //sub, err := subset.All(1 << 20) + //if err != nil { + // acc.Addf("error in Bitfield.All(): %v", err) + // return + //} + //acc.Addf(msg+": %v, %v", sup, sub) + } +} + +func requireContainsNone(superset, subset bitfield.BitField, acc *builtin.MessageAccumulator, msg string) { + if contains, err := util.BitFieldContainsAny(superset, subset); err != nil { + acc.Addf("error in BitfieldContainsAny(): %v", err) + } else if contains { + acc.Addf(msg+": %v, %v", superset, subset) + // Verbose output for debugging + //sup, err := superset.All(1 << 20) + //if err != nil { + // acc.Addf("error in Bitfield.All(): %v", err) + // return + //} + //sub, err := subset.All(1 << 20) + //if err != nil { + // acc.Addf("error in Bitfield.All(): %v", err) + // return + //} + //acc.Addf(msg+": %v, %v", sup, sub) + } +} + +func requireEqual(a, b bitfield.BitField, acc *builtin.MessageAccumulator, msg string) { + requireContainsAll(a, b, acc, msg) + requireContainsAll(b, a, acc, msg) +} diff --git a/builtin/v18/miner/methods.go b/builtin/v18/miner/methods.go new file mode 100644 index 00000000..4c471151 --- /dev/null +++ b/builtin/v18/miner/methods.go @@ -0,0 +1,66 @@ +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/go-state-types/builtin" + "github.com/filecoin-project/go-state-types/builtin/v18/power" +) + +var Methods = map[abi.MethodNum]builtin.MethodMeta{ + 1: builtin.NewMethodMeta("Constructor", *new(func(*power.MinerConstructorParams) *abi.EmptyValue)), // Constructor + 2: builtin.NewMethodMeta("ControlAddresses", *new(func(*abi.EmptyValue) *GetControlAddressesReturn)), // ControlAddresses + 3: builtin.NewMethodMeta("ChangeWorkerAddress", *new(func(*ChangeWorkerAddressParams) *abi.EmptyValue)), // ChangeWorkerAddress + builtin.MustGenerateFRCMethodNum("ChangeWorkerAddress"): builtin.NewMethodMeta("ChangeWorkerAddressExported", *new(func(*ChangeWorkerAddressParams) *abi.EmptyValue)), // ChangeWorkerAddressExported + 4: builtin.NewMethodMeta("ChangePeerID", *new(func(*ChangePeerIDParams) *abi.EmptyValue)), // ChangePeerID + builtin.MustGenerateFRCMethodNum("ChangePeerID"): builtin.NewMethodMeta("ChangePeerIDExported", *new(func(*ChangePeerIDParams) *abi.EmptyValue)), // ChangePeerIDExported + 5: builtin.NewMethodMeta("SubmitWindowedPoSt", *new(func(*SubmitWindowedPoStParams) *abi.EmptyValue)), // SubmitWindowedPoSt + 6: builtin.NewMethodMeta("PreCommitSector", *new(func(*PreCommitSectorParams) *abi.EmptyValue)), // PreCommitSector + 7: builtin.NewMethodMeta("ProveCommitSector", *new(func(*ProveCommitSectorParams) *abi.EmptyValue)), // ProveCommitSector + 8: builtin.NewMethodMeta("ExtendSectorExpiration", *new(func(*ExtendSectorExpirationParams) *abi.EmptyValue)), // ExtendSectorExpiration + 9: builtin.NewMethodMeta("TerminateSectors", *new(func(*TerminateSectorsParams) *TerminateSectorsReturn)), // TerminateSectors + 10: builtin.NewMethodMeta("DeclareFaults", *new(func(*DeclareFaultsParams) *abi.EmptyValue)), // DeclareFaults + 11: builtin.NewMethodMeta("DeclareFaultsRecovered", *new(func(*DeclareFaultsRecoveredParams) *abi.EmptyValue)), // DeclareFaultsRecovered + 12: builtin.NewMethodMeta("OnDeferredCronEvent", *new(func(*DeferredCronEventParams) *abi.EmptyValue)), // OnDeferredCronEvent + 13: builtin.NewMethodMeta("CheckSectorProven", *new(func(*CheckSectorProvenParams) *abi.EmptyValue)), // CheckSectorProven + 14: builtin.NewMethodMeta("ApplyRewards", *new(func(*ApplyRewardParams) *abi.EmptyValue)), // ApplyRewards + 15: builtin.NewMethodMeta("ReportConsensusFault", *new(func(*ReportConsensusFaultParams) *abi.EmptyValue)), // ReportConsensusFault + 16: builtin.NewMethodMeta("WithdrawBalance", *new(func(*WithdrawBalanceParams) *abi.TokenAmount)), // WithdrawBalance + builtin.MustGenerateFRCMethodNum("WithdrawBalance"): builtin.NewMethodMeta("WithdrawBalanceExported", *new(func(*WithdrawBalanceParams) *abi.TokenAmount)), // WithdrawBalanceExported + 17: builtin.NewMethodMeta("InternalSectorSetupForPreseal", *new(func(*InternalSectorSetupForPresealParams) *abi.EmptyValue)), // InternalSectorSetupForPreseal + 18: builtin.NewMethodMeta("ChangeMultiaddrs", *new(func(*ChangeMultiaddrsParams) *abi.EmptyValue)), // ChangeMultiaddrs + builtin.MustGenerateFRCMethodNum("ChangeMultiaddrs"): builtin.NewMethodMeta("ChangeMultiaddrsExported", *new(func(*ChangeMultiaddrsParams) *abi.EmptyValue)), // ChangeMultiaddrsExported + 19: builtin.NewMethodMeta("CompactPartitions", *new(func(*CompactPartitionsParams) *abi.EmptyValue)), // CompactPartitions + 20: builtin.NewMethodMeta("CompactSectorNumbers", *new(func(*CompactSectorNumbersParams) *abi.EmptyValue)), // CompactSectorNumbers + 21: builtin.NewMethodMeta("ConfirmChangeWorkerAddress", *new(func(*abi.EmptyValue) *abi.EmptyValue)), // ConfirmChangeWorkerAddress + builtin.MustGenerateFRCMethodNum("ConfirmChangeWorkerAddress"): builtin.NewMethodMeta("ConfirmChangeWorkerAddressExported", *new(func(*abi.EmptyValue) *abi.EmptyValue)), // ConfirmChangeWorkerAddressExported + 22: builtin.NewMethodMeta("RepayDebt", *new(func(*abi.EmptyValue) *abi.EmptyValue)), // RepayDebt + builtin.MustGenerateFRCMethodNum("RepayDebt"): builtin.NewMethodMeta("RepayDebtExported", *new(func(*abi.EmptyValue) *abi.EmptyValue)), // RepayDebtExported + 23: builtin.NewMethodMeta("ChangeOwnerAddress", *new(func(*address.Address) *abi.EmptyValue)), // ChangeOwnerAddress + builtin.MustGenerateFRCMethodNum("ChangeOwnerAddress"): builtin.NewMethodMeta("ChangeOwnerAddressExported", *new(func(*address.Address) *abi.EmptyValue)), // ChangeOwnerAddressExported + 24: builtin.NewMethodMeta("DisputeWindowedPoSt", *new(func(*DisputeWindowedPoStParams) *abi.EmptyValue)), // DisputeWindowedPoSt + 25: builtin.NewMethodMeta("PreCommitSectorBatch", *new(func(*PreCommitSectorBatchParams) *abi.EmptyValue)), // PreCommitSectorBatch + 26: builtin.NewMethodMeta("ProveCommitAggregate", *new(func(*ProveCommitAggregateParams) *abi.EmptyValue)), // ProveCommitAggregate + 27: builtin.NewMethodMeta("ProveReplicaUpdates", *new(func(*ProveReplicaUpdatesParams) *bitfield.BitField)), // ProveReplicaUpdates + // NB: the name of this method must not change across actor/network versions + 28: builtin.NewMethodMeta("PreCommitSectorBatch2", *new(func(*PreCommitSectorBatchParams2) *abi.EmptyValue)), // PreCommitSectorBatch2 + // NB: the name of this method must not change across actor/network versions + 29: builtin.NewMethodMeta("ProveReplicaUpdates2", *new(func(*ProveReplicaUpdatesParams2) *bitfield.BitField)), // ProveReplicaUpdates2 + 30: builtin.NewMethodMeta("ChangeBeneficiary", *new(func(*ChangeBeneficiaryParams) *abi.EmptyValue)), // ChangeBeneficiary + builtin.MustGenerateFRCMethodNum("ChangeBeneficiary"): builtin.NewMethodMeta("ChangeBeneficiaryExported", *new(func(*ChangeBeneficiaryParams) *abi.EmptyValue)), // ChangeBeneficiaryExported + 31: builtin.NewMethodMeta("GetBeneficiary", *new(func(*abi.EmptyValue) *GetBeneficiaryReturn)), // GetBeneficiary + // NB: the name of this method must not change across actor/network versions + 32: builtin.NewMethodMeta("ExtendSectorExpiration2", *new(func(*ExtendSectorExpiration2Params) *abi.EmptyValue)), // ExtendSectorExpiration2 + builtin.MustGenerateFRCMethodNum("GetOwner"): builtin.NewMethodMeta("GetOwnerExported", *new(func(*abi.EmptyValue) *GetOwnerReturn)), // GetOwnerExported + builtin.MustGenerateFRCMethodNum("IsControllingAddress"): builtin.NewMethodMeta("IsControllingAddressExported", *new(func(params *IsControllingAddressParams) *IsControllingAddressReturn)), // IsControllingAddressExported + builtin.MustGenerateFRCMethodNum("GetSectorSize"): builtin.NewMethodMeta("GetSectorSizeExported", *new(func(*abi.EmptyValue) *GetSectorSizeReturn)), // GetSectorSizeExported + builtin.MustGenerateFRCMethodNum("GetAvailableBalance"): builtin.NewMethodMeta("GetAvailableBalanceExported", *new(func(*abi.EmptyValue) *GetAvailableBalanceReturn)), // GetAvailableBalanceExported + builtin.MustGenerateFRCMethodNum("GetVestingFunds"): builtin.NewMethodMeta("GetVestingFundsExported", *new(func(*abi.EmptyValue) *GetVestingFundsReturn)), // GetVestingFundsExported + builtin.MustGenerateFRCMethodNum("GetPeerID"): builtin.NewMethodMeta("GetPeerIDExported", *new(func(*abi.EmptyValue) *GetPeerIDReturn)), // GetPeerIDExported + builtin.MustGenerateFRCMethodNum("GetMultiaddrs"): builtin.NewMethodMeta("GetMultiaddrsExported", *new(func(*abi.EmptyValue) *GetMultiAddrsReturn)), // GetMultiaddrsExported + // 33 MovePartitions + 34: builtin.NewMethodMeta("ProveCommitSectors3", *new(func(*ProveCommitSectors3Params) *ProveCommitSectors3Return)), // ProveCommitSectors3 + 35: builtin.NewMethodMeta("ProveReplicaUpdates3", *new(func(*ProveReplicaUpdates3Params) *ProveReplicaUpdates3Return)), // ProveReplicaUpdates3 + 36: builtin.NewMethodMeta("ProveCommitSectorsNI", *new(func(*ProveCommitSectorsNIParams) *abi.EmptyValue)), // ProveCommitSectorsNI +} diff --git a/builtin/v18/miner/miner_state.go b/builtin/v18/miner/miner_state.go new file mode 100644 index 00000000..d5afa08b --- /dev/null +++ b/builtin/v18/miner/miner_state.go @@ -0,0 +1,357 @@ +package miner + +import ( + cid "github.com/ipfs/go-cid" + "golang.org/x/xerrors" + + addr "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/builtin" + "github.com/filecoin-project/go-state-types/builtin/v18/util/adt" + "github.com/filecoin-project/go-state-types/dline" + xc "github.com/filecoin-project/go-state-types/exitcode" +) + +// Balance of Miner Actor should be greater than or equal to +// the sum of PreCommitDeposits and LockedFunds. +// It is possible for balance to fall below the sum of +// PCD, LF and InitialPledgeRequirements, and this is a bad +// state (IP Debt) that limits a miner actor's behavior (i.e. no balance withdrawals) +// Excess balance as computed by st.GetAvailableBalance will be +// withdrawable or usable for pre-commit deposit or pledge lock-up. +type State struct { + // Information not related to sectors. + Info cid.Cid + + PreCommitDeposits abi.TokenAmount // Total funds locked as PreCommitDeposits + LockedFunds abi.TokenAmount // Total rewards and added funds locked in vesting table + + VestingFunds *VestingFunds // Vesting Funds schedule for the miner. + + FeeDebt abi.TokenAmount // Absolute value of debt this miner owes from unpaid fees + + InitialPledge abi.TokenAmount // Sum of initial pledge requirements of all active sectors + + // Sectors that have been pre-committed but not yet proven. + PreCommittedSectors cid.Cid // Map, HAMT[SectorNumber]SectorPreCommitOnChainInfo + + // PreCommittedSectorsCleanUp maintains the state required to cleanup expired PreCommittedSectors. + PreCommittedSectorsCleanUp cid.Cid // BitFieldQueue (AMT[Epoch]*BitField) + + // Allocated sector IDs. Sector IDs can never be reused once allocated. + AllocatedSectors cid.Cid // BitField + + // Information for all proven and not-yet-garbage-collected sectors. + // + // Sectors are removed from this AMT when the partition to which the + // sector belongs is compacted. + Sectors cid.Cid // Array, AMT[SectorNumber]SectorOnChainInfo (sparse) + + // DEPRECATED. This field will change names and no longer be updated every proving period in a future upgrade + // The first epoch in this miner's current proving period. This is the first epoch in which a PoSt for a + // partition at the miner's first deadline may arrive. Alternatively, it is after the last epoch at which + // a PoSt for the previous window is valid. + // Always greater than zero, this may be greater than the current epoch for genesis miners in the first + // WPoStProvingPeriod epochs of the chain; the epochs before the first proving period starts are exempt from Window + // PoSt requirements. + // Updated at the end of every period by a cron callback. + ProvingPeriodStart abi.ChainEpoch + + // DEPRECATED. This field will be removed from state in a future upgrade. + // Index of the deadline within the proving period beginning at ProvingPeriodStart that has not yet been + // finalized. + // Updated at the end of each deadline window by a cron callback. + CurrentDeadline uint64 + + // The sector numbers due for PoSt at each deadline in the current proving period, frozen at period start. + // New sectors are added and expired ones removed at proving period boundary. + // Faults are not subtracted from this in state, but on the fly. + Deadlines cid.Cid + + // Deadlines with outstanding fees for early sector termination. + EarlyTerminations bitfield.BitField + + // True when miner cron is active, false otherwise + DeadlineCronActive bool +} + +// Bitwidth of AMTs determined empirically from mutation patterns and projections of mainnet data. +const PrecommitCleanUpAmtBitwidth = 6 +const SectorsAmtBitwidth = 5 + +type MinerInfo struct { + // Account that owns this miner. + // - Income and returned collateral are paid to this address. + // - This address is also allowed to change the worker address for the miner. + Owner addr.Address // Must be an ID-address. + + // Worker account for this miner. + // The associated pubkey-type address is used to sign blocks and messages on behalf of this miner. + Worker addr.Address // Must be an ID-address. + + // Additional addresses that are permitted to submit messages controlling this actor (optional). + ControlAddresses []addr.Address // Must all be ID addresses. + + PendingWorkerKey *WorkerKeyChange + + // Byte array representing a Libp2p identity that should be used when connecting to this miner. + PeerId abi.PeerID + + // Slice of byte arrays representing Libp2p multi-addresses used for establishing a connection with this miner. + Multiaddrs []abi.Multiaddrs + + // The proof type used for Window PoSt for this miner. + // A miner may commit sectors with different seal proof types (but compatible sector size and + // corresponding PoSt proof types). + WindowPoStProofType abi.RegisteredPoStProof + + // Amount of space in each sector committed by this miner. + // This is computed from the proof type and represented here redundantly. + SectorSize abi.SectorSize + + // The number of sectors in each Window PoSt partition (proof). + // This is computed from the proof type and represented here redundantly. + WindowPoStPartitionSectors uint64 + + // The next epoch this miner is eligible for certain permissioned actor methods + // and winning block elections as a result of being reported for a consensus fault. + ConsensusFaultElapsed abi.ChainEpoch + + // A proposed new owner account for this miner. + // Must be confirmed by a message from the pending address itself. + PendingOwnerAddress *addr.Address + + // Beneficiary address for this miner. + // This is the address that tokens will be withdrawn to + Beneficiary addr.Address + + // Beneficiary's withdrawal quota, how much of the quota has been withdrawn, + // and when the Beneficiary expires. + BeneficiaryTerm BeneficiaryTerm + + // A proposed change to `BenificiaryTerm` + PendingBeneficiaryTerm *PendingBeneficiaryChange +} + +type WorkerKeyChange struct { + NewWorker addr.Address // Must be an ID address + EffectiveAt abi.ChainEpoch +} + +// Information provided by a miner when pre-committing a sector. +type SectorPreCommitInfo struct { + SealProof abi.RegisteredSealProof + SectorNumber abi.SectorNumber + SealedCID cid.Cid `checked:"true"` // CommR + SealRandEpoch abi.ChainEpoch + DealIDs []abi.DealID + Expiration abi.ChainEpoch + UnsealedCid *cid.Cid +} + +// Information stored on-chain for a pre-committed sector. +type SectorPreCommitOnChainInfo struct { + Info SectorPreCommitInfo + PreCommitDeposit abi.TokenAmount + PreCommitEpoch abi.ChainEpoch +} + +type SectorOnChainInfoFlags uint64 + +const ( + SIMPLE_QA_POWER SectorOnChainInfoFlags = 1 << iota // QA power mechanism introduced in FIP-0045 +) + +// Information stored on-chain for a proven sector. +type SectorOnChainInfo struct { + SectorNumber abi.SectorNumber + SealProof abi.RegisteredSealProof // The seal proof type implies the PoSt proof/s + SealedCID cid.Cid // CommR + DeprecatedDealIDs []abi.DealID `json:"-"` + Activation abi.ChainEpoch // Epoch during which the sector proof was accepted + Expiration abi.ChainEpoch // Epoch during which the sector expires + DealWeight abi.DealWeight // Integral of active deals over sector lifetime + VerifiedDealWeight abi.DealWeight // Integral of active verified deals over sector lifetime + InitialPledge abi.TokenAmount // Pledge collected to commit this sector + ExpectedDayReward *abi.TokenAmount // Expected one day projection of reward for sector computed at activation time + ExpectedStoragePledge *abi.TokenAmount // Expected twenty day projection of reward for sector computed at activation time + PowerBaseEpoch abi.ChainEpoch // Epoch at which this sector's power was most recently updated + ReplacedDayReward *abi.TokenAmount // Day reward of this sector before its power was most recently updated + SectorKeyCID *cid.Cid // The original SealedSectorCID, only gets set on the first ReplicaUpdate + Flags SectorOnChainInfoFlags // Additional flags + // The total fee payable per day for this sector. The value of this field is set at the time of + // sector activation, extension and whenever a sector's QAP is changed. This fee is payable for + // the lifetime of the sector and is aggregated in the deadline's `daily_fee` field. + // + // This field is not included in the serialised form of the struct prior to the activation of + // FIP-0100, and is added as the 16th element of the array after that point only for new sectors + // or sectors that are updated after that point. For old sectors, the value of this field will + // always be zero. + // + // This field is OPTIONAL, meaning that it may present as a nil BigInt (not a nil pointer). + // If FeeDeduction.Nil() then it should be treated the same as if it were zero (but cannot be + // used in place of a zero value). + DailyFee abi.TokenAmount `cborgen:"optional"` +} + +func (st *State) GetInfo(store adt.Store) (*MinerInfo, error) { + var info MinerInfo + if err := store.Get(store.Context(), st.Info, &info); err != nil { + return nil, xerrors.Errorf("failed to get miner info %w", err) + } + return &info, nil +} + +type BeneficiaryTerm struct { + Quota abi.TokenAmount + UsedQuota abi.TokenAmount + Expiration abi.ChainEpoch +} + +type PendingBeneficiaryChange struct { + NewBeneficiary addr.Address + NewQuota abi.TokenAmount + NewExpiration abi.ChainEpoch + ApprovedByBeneficiary bool + ApprovedByNominee bool +} + +// Returns deadline calculations for the state recorded proving period and deadline. This is out of date if the a +// miner does not have an active miner cron +func (st *State) RecordedDeadlineInfo(currEpoch abi.ChainEpoch) *dline.Info { + return NewDeadlineInfo(st.ProvingPeriodStart, st.CurrentDeadline, currEpoch) +} + +// Returns deadline calculations for the current (according to state) proving period +func (st *State) QuantSpecForDeadline(dlIdx uint64) builtin.QuantSpec { + return QuantSpecForDeadline(NewDeadlineInfo(st.ProvingPeriodStart, dlIdx, 0)) +} + +func (st *State) GetPrecommittedSector(store adt.Store, sectorNo abi.SectorNumber) (*SectorPreCommitOnChainInfo, bool, error) { + precommitted, err := adt.AsMap(store, st.PreCommittedSectors, builtin.DefaultHamtBitwidth) + if err != nil { + return nil, false, err + } + + var info SectorPreCommitOnChainInfo + found, err := precommitted.Get(SectorKey(sectorNo), &info) + if err != nil { + return nil, false, xerrors.Errorf("failed to load precommitment for %v: %w", sectorNo, err) + } + return &info, found, nil +} + +func (st *State) GetSector(store adt.Store, sectorNo abi.SectorNumber) (*SectorOnChainInfo, bool, error) { + sectors, err := LoadSectors(store, st.Sectors) + if err != nil { + return nil, false, err + } + + return sectors.Get(sectorNo) +} + +func (st *State) FindSector(store adt.Store, sno abi.SectorNumber) (uint64, uint64, error) { + deadlines, err := st.LoadDeadlines(store) + if err != nil { + return 0, 0, err + } + return FindSector(store, deadlines, sno) +} + +func (st *State) LoadDeadlines(store adt.Store) (*Deadlines, error) { + var deadlines Deadlines + if err := store.Get(store.Context(), st.Deadlines, &deadlines); err != nil { + return nil, xc.ErrIllegalState.Wrapf("failed to load deadlines (%s): %w", st.Deadlines, err) + } + + return &deadlines, nil +} + +func (st *State) SaveDeadlines(store adt.Store, deadlines *Deadlines) error { + c, err := store.Put(store.Context(), deadlines) + if err != nil { + return err + } + st.Deadlines = c + return nil +} + +// LoadVestingFunds loads the vesting funds table from the store +func (st *State) LoadVestingFunds(store adt.Store) ([]VestingFund, error) { + if st.VestingFunds == nil { + return nil, nil + } + + var tail VestingFundsTail + if err := store.Get(store.Context(), st.VestingFunds.Tail, &tail); err != nil { + return nil, xerrors.Errorf("failed to load vesting funds (%s): %w", st.VestingFunds, err) + } + + return append([]VestingFund{st.VestingFunds.Head}, tail.Funds...), nil +} + +// CheckVestedFunds returns the amount of vested funds that have vested before the provided epoch. +func (st *State) CheckVestedFunds(store adt.Store, currEpoch abi.ChainEpoch) (abi.TokenAmount, error) { + vestingFunds, err := st.LoadVestingFunds(store) + if err != nil { + return big.Zero(), xerrors.Errorf("failed to load vesting funds: %w", err) + } + + amountVested := abi.NewTokenAmount(0) + + for i := range vestingFunds { + vf := vestingFunds[i] + epoch := vf.Epoch + amount := vf.Amount + + if epoch >= currEpoch { + break + } + + amountVested = big.Add(amountVested, amount) + } + + return amountVested, nil +} + +// Unclaimed funds that are not locked -- includes free funds and does not +// account for fee debt. Always greater than or equal to zero +func (st *State) GetUnlockedBalance(actorBalance abi.TokenAmount) (abi.TokenAmount, error) { + unlockedBalance := big.Subtract(actorBalance, st.LockedFunds, st.PreCommitDeposits, st.InitialPledge) + if unlockedBalance.LessThan(big.Zero()) { + return big.Zero(), xerrors.Errorf("negative unlocked balance %v", unlockedBalance) + } + return unlockedBalance, nil +} + +// Unclaimed funds. Actor balance - (locked funds, precommit deposit, initial pledge, fee debt) +// Can go negative if the miner is in IP debt +func (st *State) GetAvailableBalance(actorBalance abi.TokenAmount) (abi.TokenAmount, error) { + unlockedBalance, err := st.GetUnlockedBalance(actorBalance) + if err != nil { + return big.Zero(), err + } + return big.Subtract(unlockedBalance, st.FeeDebt), nil +} + +// +// Misc helpers +// + +func SectorKey(e abi.SectorNumber) abi.Keyer { + return abi.UIntKey(uint64(e)) +} + +// pre-commit clean up +func (st *State) QuantSpecEveryDeadline() builtin.QuantSpec { + return builtin.NewQuantSpec(WPoStChallengeWindow, st.ProvingPeriodStart) +} + +// Return true when the miner actor needs to continue scheduling deadline crons +func (st *State) ContinueDeadlineCron() bool { + return !st.PreCommitDeposits.IsZero() || + !st.InitialPledge.IsZero() || + !st.LockedFunds.IsZero() +} diff --git a/builtin/v18/miner/miner_types.go b/builtin/v18/miner/miner_types.go new file mode 100644 index 00000000..10dc1c7d --- /dev/null +++ b/builtin/v18/miner/miner_types.go @@ -0,0 +1,527 @@ +package miner + +import ( + cid "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" + "golang.org/x/xerrors" + + addr "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/batch" + "github.com/filecoin-project/go-state-types/builtin" + "github.com/filecoin-project/go-state-types/builtin/v18/power" + "github.com/filecoin-project/go-state-types/builtin/v18/util/adt" + "github.com/filecoin-project/go-state-types/builtin/v18/util/smoothing" + "github.com/filecoin-project/go-state-types/builtin/v18/verifreg" + xc "github.com/filecoin-project/go-state-types/exitcode" + "github.com/filecoin-project/go-state-types/proof" +) + +type DeclareFaultsRecoveredParams struct { + Recoveries []RecoveryDeclaration +} + +type RecoveryDeclaration struct { + // The deadline to which the recovered sectors are assigned, in range [0..WPoStPeriodDeadlines) + Deadline uint64 + // Partition index within the deadline containing the recovered sectors. + Partition uint64 + // Sectors in the partition being declared recovered. + Sectors bitfield.BitField +} + +type DeclareFaultsParams struct { + Faults []FaultDeclaration +} + +type FaultDeclaration struct { + // The deadline to which the faulty sectors are assigned, in range [0..WPoStPeriodDeadlines) + Deadline uint64 + // Partition index within the deadline containing the faulty sectors. + Partition uint64 + // Sectors in the partition being declared faulty. + Sectors bitfield.BitField +} + +type ReplicaUpdate struct { + SectorID abi.SectorNumber + Deadline uint64 + Partition uint64 + NewSealedSectorCID cid.Cid `checked:"true"` + Deals []abi.DealID + UpdateProofType abi.RegisteredUpdateProof + ReplicaProof []byte +} + +type ProveReplicaUpdatesParams struct { + Updates []ReplicaUpdate +} + +type ReplicaUpdate2 struct { + SectorID abi.SectorNumber + Deadline uint64 + Partition uint64 + NewSealedSectorCID cid.Cid `checked:"true"` + NewUnsealedSectorCID cid.Cid `checked:"true"` + Deals []abi.DealID + UpdateProofType abi.RegisteredUpdateProof + ReplicaProof []byte +} + +type ProveReplicaUpdatesParams2 struct { + Updates []ReplicaUpdate2 +} + +type PoStPartition struct { + // Partitions are numbered per-deadline, from zero. + Index uint64 + // Sectors skipped while proving that weren't already declared faulty + Skipped bitfield.BitField +} + +// Information submitted by a miner to provide a Window PoSt. +type SubmitWindowedPoStParams struct { + // The deadline index which the submission targets. + Deadline uint64 + // The partitions being proven. + Partitions []PoStPartition + // Array of proofs, one per distinct registered proof type present in the sectors being proven. + // In the usual case of a single proof type, this array will always have a single element (independent of number of partitions). + Proofs []proof.PoStProof + // The epoch at which these proofs is being committed to a particular chain. + ChainCommitEpoch abi.ChainEpoch + // The ticket randomness on the chain at the ChainCommitEpoch on the chain this post is committed to + ChainCommitRand abi.Randomness +} + +type DisputeWindowedPoStParams struct { + Deadline uint64 + PoStIndex uint64 // only one is allowed at a time to avoid loading too many sector infos. +} + +type ProveCommitAggregateParams struct { + SectorNumbers bitfield.BitField + AggregateProof []byte +} + +type ProveCommitSectorParams struct { + SectorNumber abi.SectorNumber + Proof []byte +} + +type MinerConstructorParams = power.MinerConstructorParams + +type TerminateSectorsParams struct { + Terminations []TerminationDeclaration +} + +type TerminationDeclaration struct { + Deadline uint64 + Partition uint64 + Sectors bitfield.BitField +} + +type TerminateSectorsReturn struct { + // Set to true if all early termination work has been completed. When + // false, the miner may choose to repeatedly invoke TerminateSectors + // with no new sectors to process the remainder of the pending + // terminations. While pending terminations are outstanding, the miner + // will not be able to withdraw funds. + Done bool +} + +type ChangePeerIDParams struct { + NewID abi.PeerID +} + +type ChangeMultiaddrsParams struct { + NewMultiaddrs []abi.Multiaddrs +} + +type ChangeWorkerAddressParams struct { + NewWorker addr.Address + NewControlAddrs []addr.Address +} + +type ExtendSectorExpirationParams struct { + Extensions []ExpirationExtension +} + +type ExpirationExtension struct { + Deadline uint64 + Partition uint64 + Sectors bitfield.BitField + NewExpiration abi.ChainEpoch +} + +type ReportConsensusFaultParams struct { + BlockHeader1 []byte + BlockHeader2 []byte + BlockHeaderExtra []byte +} + +type GetControlAddressesReturn struct { + Owner addr.Address + Worker addr.Address + ControlAddrs []addr.Address +} + +type CheckSectorProvenParams struct { + SectorNumber abi.SectorNumber +} + +type WithdrawBalanceParams struct { + AmountRequested abi.TokenAmount +} + +type CompactPartitionsParams struct { + Deadline uint64 + Partitions bitfield.BitField +} + +type CompactSectorNumbersParams struct { + MaskSectorNumbers bitfield.BitField +} + +type CronEventType int64 + +const ( + CronEventWorkerKeyChange CronEventType = iota + CronEventProvingDeadline + CronEventProcessEarlyTerminations +) + +type CronEventPayload struct { + EventType CronEventType +} + +// Identifier for a single partition within a miner. +type PartitionKey struct { + Deadline uint64 + Partition uint64 +} + +type PreCommitSectorParams struct { + SealProof abi.RegisteredSealProof + SectorNumber abi.SectorNumber + SealedCID cid.Cid `checked:"true"` // CommR + SealRandEpoch abi.ChainEpoch + DealIDs []abi.DealID + Expiration abi.ChainEpoch + ReplaceCapacity bool // DEPRECATED: Whether to replace a "committed capacity" no-deal sector (requires non-empty DealIDs) + // DEPRECATED: The committed capacity sector to replace, and it's deadline/partition location + ReplaceSectorDeadline uint64 + ReplaceSectorPartition uint64 + ReplaceSectorNumber abi.SectorNumber +} + +type PreCommitSectorBatchParams struct { + Sectors []PreCommitSectorParams +} + +type PreCommitSectorBatchParams2 struct { + Sectors []SectorPreCommitInfo +} + +type ChangeBeneficiaryParams struct { + NewBeneficiary addr.Address + NewQuota abi.TokenAmount + NewExpiration abi.ChainEpoch +} + +type ActiveBeneficiary struct { + Beneficiary addr.Address + Term BeneficiaryTerm +} + +type GetBeneficiaryReturn struct { + Active ActiveBeneficiary + Proposed *PendingBeneficiaryChange +} + +// ExpirationSet is a collection of sector numbers that are expiring, either due to +// expected "on-time" expiration at the end of their life, or unexpected "early" termination +// due to being faulty for too long consecutively. +// Note that there is not a direct correspondence between on-time sectors and active power; +// a sector may be faulty but expiring on-time if it faults just prior to expected termination. +// Early sectors are always faulty, and active power always represents on-time sectors. +type ExpirationSet struct { + OnTimeSectors bitfield.BitField // Sectors expiring "on time" at the end of their committed life + EarlySectors bitfield.BitField // Sectors expiring "early" due to being faulty for too long + OnTimePledge abi.TokenAmount // Pledge total for the on-time sectors + ActivePower PowerPair // Power that is currently active (not faulty) + FaultyPower PowerPair // Power that is currently faulty + // Adjustment to the daily fee recorded for the deadline associated with this expiration set + // to account for expiring sectors. + // + // This field is OPTIONAL, meaning that it may present as a nil BigInt (not a nil pointer). + // If FeeDeduction.Nil() then it should be treated the same as if it were zero (but cannot be + // used in place of a zero value). + FeeDeduction abi.TokenAmount `cborgen:"optional"` +} + +// A queue of expiration sets by epoch, representing the on-time or early termination epoch for a collection of sectors. +// Wraps an AMT[ChainEpoch]*ExpirationSet. +// Keys in the queue are quantized (upwards), modulo some offset, to reduce the cardinality of keys. +type ExpirationQueue struct { + *adt.Array + quant builtin.QuantSpec +} + +// Loads a queue root. +// Epochs provided to subsequent method calls will be quantized upwards to quanta mod offsetSeed before being +// written to/read from queue entries. +func LoadExpirationQueue(store adt.Store, root cid.Cid, quant builtin.QuantSpec, bitwidth int) (ExpirationQueue, error) { + arr, err := adt.AsArray(store, root, bitwidth) + if err != nil { + return ExpirationQueue{}, xerrors.Errorf("failed to load epoch queue %v: %w", root, err) + } + return ExpirationQueue{arr, quant}, nil +} +func LoadSectors(store adt.Store, root cid.Cid) (Sectors, error) { + sectorsArr, err := adt.AsArray(store, root, SectorsAmtBitwidth) + if err != nil { + return Sectors{}, err + } + return Sectors{sectorsArr}, nil +} + +// Sectors is a helper type for accessing/modifying a miner's sectors. It's safe +// to pass this object around as needed. +type Sectors struct { + *adt.Array +} + +func (sa Sectors) Load(sectorNos bitfield.BitField) ([]*SectorOnChainInfo, error) { + var sectorInfos []*SectorOnChainInfo + if err := sectorNos.ForEach(func(i uint64) error { + var sectorOnChain SectorOnChainInfo + found, err := sa.Array.Get(i, §orOnChain) + if err != nil { + return xc.ErrIllegalState.Wrapf("failed to load sector %v: %w", abi.SectorNumber(i), err) + } else if !found { + return xc.ErrNotFound.Wrapf("can't find sector %d", i) + } + sectorInfos = append(sectorInfos, §orOnChain) + return nil + }); err != nil { + // Keep the underlying error code, unless the error was from + // traversing the bitfield. In that case, it's an illegal + // argument error. + return nil, xc.Unwrap(err, xc.ErrIllegalArgument).Wrapf("failed to load sectors: %w", err) + } + return sectorInfos, nil +} + +func (sa Sectors) Get(sectorNumber abi.SectorNumber) (info *SectorOnChainInfo, found bool, err error) { + var res SectorOnChainInfo + if found, err := sa.Array.Get(uint64(sectorNumber), &res); err != nil { + return nil, false, xerrors.Errorf("failed to get sector %d: %w", sectorNumber, err) + } else if !found { + return nil, false, nil + } + return &res, true, nil +} + +// VestingFunds represents the vesting table state for the miner. +type VestingFunds struct { + // The next batch of vesting funds. + Head VestingFund + // The rest of the vesting funds. + Tail cid.Cid // VestingFundsTail +} + +// VestingFundTail represents the tail of a vesting funds table in the miner. It's an array of +// (VestingEpoch, VestingAmount) tuples. The slice will always be sorted by the VestingEpoch. +type VestingFundsTail struct { + Funds []VestingFund `cborgen:"transparent"` +} + +// VestingFund represents miner funds that will vest at the given epoch. +type VestingFund struct { + Epoch abi.ChainEpoch + Amount abi.TokenAmount +} + +type DeferredCronEventParams struct { + EventPayload []byte + RewardSmoothed smoothing.FilterEstimate + QualityAdjPowerSmoothed smoothing.FilterEstimate +} + +type ApplyRewardParams struct { + Reward abi.TokenAmount + Penalty abi.TokenAmount +} + +type InternalSectorSetupForPresealParams struct { + Sectors []abi.SectorNumber + RewardSmoothed smoothing.FilterEstimate + RewardBaselinePower abi.StoragePower + QualityAdjPowerSmoothed smoothing.FilterEstimate +} + +type ExtendSectorExpiration2Params struct { + Extensions []ExpirationExtension2 +} + +type ExpirationExtension2 struct { + Deadline uint64 + Partition uint64 + Sectors bitfield.BitField + SectorsWithClaims []SectorClaim + NewExpiration abi.ChainEpoch +} + +type SectorClaim struct { + SectorNumber abi.SectorNumber + MaintainClaims []verifreg.ClaimId + DropClaims []verifreg.ClaimId +} + +type GetOwnerReturn struct { + Owner addr.Address + Proposed *addr.Address +} + +type IsControllingAddressParams = addr.Address + +type IsControllingAddressReturn = cbg.CborBool + +type GetSectorSizeReturn = abi.SectorSize + +type GetAvailableBalanceReturn = abi.TokenAmount + +type GetVestingFundsReturn = VestingFunds + +type GetPeerIDReturn struct { + PeerId []byte +} + +type GetMultiAddrsReturn struct { + MultiAddrs []byte +} + +// ProveCommitSectors3Params represents the parameters for proving committed sectors. +type ProveCommitSectors3Params struct { + SectorActivations []SectorActivationManifest + SectorProofs [][]byte + AggregateProof []byte + AggregateProofType *abi.RegisteredAggregationProof + RequireActivationSuccess bool + RequireNotificationSuccess bool +} + +// SectorActivationManifest contains data to activate a commitment to one sector and its data. +// All pieces of data must be specified, whether or not not claiming a FIL+ activation or being +// notified to a data consumer. +// An implicit zero piece fills any remaining sector capacity. +type SectorActivationManifest struct { + SectorNumber abi.SectorNumber + Pieces []PieceActivationManifest +} + +// PieceActivationManifest represents the manifest for activating a piece. +type PieceActivationManifest struct { + CID cid.Cid + Size abi.PaddedPieceSize + VerifiedAllocationKey *VerifiedAllocationKey + Notify []DataActivationNotification +} + +// VerifiedAllocationKey represents the key for a verified allocation. +type VerifiedAllocationKey struct { + Client abi.ActorID + ID verifreg.AllocationId +} + +// DataActivationNotification represents a notification for data activation. +type DataActivationNotification struct { + Address addr.Address + Payload []byte +} + +// ProveCommitSectors3Return represents the return value for the ProveCommit2 function. +type ProveCommitSectors3Return = batch.BatchReturn + +// ProveReplicaUpdates3Params represents the parameters for proving replica updates. +type ProveReplicaUpdates3Params struct { + SectorUpdates []SectorUpdateManifest + SectorProofs [][]byte + AggregateProof []byte + UpdateProofsType abi.RegisteredUpdateProof + AggregateProofType *abi.RegisteredAggregationProof + RequireActivationSuccess bool + RequireNotificationSuccess bool +} + +// SectorUpdateManifest contains data for sector update. +type SectorUpdateManifest struct { + Sector abi.SectorNumber + Deadline uint64 + Partition uint64 + NewSealedCID cid.Cid + Pieces []PieceActivationManifest +} + +// ProveReplicaUpdates3Return represents the return value for the ProveReplicaUpdates3 function. +type ProveReplicaUpdates3Return = batch.BatchReturn + +// SectorContentChangedParams represents a notification of change committed to sectors. +type SectorContentChangedParams []SectorChanges + +// SectorChanges describes changes to one sector's content. +type SectorChanges struct { + Sector abi.SectorNumber + MinimumCommitmentEpoch abi.ChainEpoch + Added []PieceChange +} + +// PieceChange describes a piece of data committed to a sector. +type PieceChange struct { + Data cid.Cid + Size abi.PaddedPieceSize + Payload []byte +} + +// SectorContentChangedReturn represents the return value for the SectorContentChanged function. +type SectorContentChangedReturn = []SectorReturn + +// SectorReturn represents a result for each sector that was notified. +type SectorReturn = []PieceReturn + +// PieceReturn represents a result for each piece for the sector that was notified. +type PieceReturn = bool // Accepted = true + +// SectorNIActivationInfo is the information needed to activate a sector with a "zero" replica. +type SectorNIActivationInfo struct { + SealingNumber abi.SectorNumber // Sector number used to generate replica id + SealerID abi.ActorID // Must be set to ID of receiving actor for now + SealedCID cid.Cid // CommR + SectorNumber abi.SectorNumber // Unique id of sector in actor state + SealRandEpoch abi.ChainEpoch + Expiration abi.ChainEpoch +} + +// ProveCommitSectorsNIParams is the parameters for non-interactive prove committing of sectors +// via the miner actor method ProveCommitSectorsNI. +type ProveCommitSectorsNIParams struct { + Sectors []SectorNIActivationInfo // Information about sealing of each sector + AggregateProof []byte // Aggregate proof for all sectors + SealProofType abi.RegisteredSealProof // Proof type for each seal (must be an NI-PoRep variant) + AggregateProofType abi.RegisteredAggregationProof // Proof type for aggregation + ProvingDeadline uint64 // The Window PoST deadline index at which to schedule the new sectors + RequireActivationSuccess bool // Whether to abort if any sector activation fails +} + +type ProveCommitSectorsNIReturn = batch.BatchReturn + +type MaxTerminationFeeParams struct { + Power abi.StoragePower + InitialPledge abi.TokenAmount +} + +type MaxTerminationFeeReturn = abi.TokenAmount + +type InitialPledgeReturn = abi.TokenAmount diff --git a/builtin/v18/miner/miner_types_test.go b/builtin/v18/miner/miner_types_test.go new file mode 100644 index 00000000..79d7be8e --- /dev/null +++ b/builtin/v18/miner/miner_types_test.go @@ -0,0 +1,370 @@ +package miner + +import ( + "bytes" + "encoding/hex" + "testing" + + "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/builtin" + cid "github.com/ipfs/go-cid" + "github.com/stretchr/testify/require" +) + +// Tests to match with Rust fil_actor_miner::serialization + +// defaultCid as a Rust Default::default() value +var defaultCid = cid.MustParse("baeaaaaa") + +func TestSerializationProveCommitSectorsNIParams(t *testing.T) { + testCases := []struct { + params ProveCommitSectorsNIParams + hex string + }{ + { + params: ProveCommitSectorsNIParams{ + Sectors: nil, + AggregateProof: nil, + SealProofType: abi.RegisteredSealProof_StackedDrg32GiBV1_1, + AggregateProofType: abi.RegisteredAggregationProof_SnarkPackV2, + ProvingDeadline: 2, + RequireActivationSuccess: false, + }, + // [[],byte[],8,1,2,false] + hex: "868040080102f4", + }, + { + params: ProveCommitSectorsNIParams{ + Sectors: []SectorNIActivationInfo{{ + SealingNumber: 1, + SealerID: 2, + SealedCID: cid.MustParse("bagboea4seaaqa"), + SectorNumber: 3, + SealRandEpoch: 4, + Expiration: 5, + }}, + SealProofType: abi.RegisteredSealProof_StackedDrg32GiBV1_2_Feat_NiPoRep, + AggregateProof: []byte{0xde, 0xad, 0xbe, 0xef}, + AggregateProofType: abi.RegisteredAggregationProof_SnarkPackV2, + ProvingDeadline: 6, + RequireActivationSuccess: true, + }, + // [[[1,2,bagboea4seaaqa,3,4,5]],byte[deadbeef],18,1,6,true] + hex: "8681860102d82a49000182e2039220010003040544deadbeef120106f5", + }, + { + params: ProveCommitSectorsNIParams{ + Sectors: []SectorNIActivationInfo{ + { + SealingNumber: 1, + SealerID: 2, + SealedCID: cid.MustParse("bagboea4seaaqa"), + SectorNumber: 3, + SealRandEpoch: 4, + Expiration: 5, + }, + { + SealingNumber: 6, + SealerID: 7, + SealedCID: cid.MustParse("bagboea4seaaqc"), + SectorNumber: 8, + SealRandEpoch: 9, + Expiration: 10, + }, + }, + SealProofType: abi.RegisteredSealProof_StackedDrg32GiBV1_2_Feat_NiPoRep, + AggregateProof: []byte{0xde, 0xad, 0xbe, 0xef}, + AggregateProofType: abi.RegisteredAggregationProof_SnarkPackV2, + ProvingDeadline: 11, + RequireActivationSuccess: false, + }, + // [[[1,2,bagboea4seaaqa,3,4,5],[6,7,bagboea4seaaqc,8,9,10]],byte[deadbeef],18,1,11,false] + hex: "8682860102d82a49000182e20392200100030405860607d82a49000182e2039220010108090a44deadbeef12010bf4", + }, + } + + for _, tc := range testCases { + t.Run("", func(t *testing.T) { + req := require.New(t) + + var buf bytes.Buffer + req.NoError(tc.params.MarshalCBOR(&buf)) + req.Equal(tc.hex, hex.EncodeToString(buf.Bytes())) + var rt ProveCommitSectorsNIParams + req.NoError(rt.UnmarshalCBOR(&buf)) + req.Equal(tc.params, rt) + }) + } +} + +func TestSectorOnChainInfo(t *testing.T) { + sectorKey := cid.MustParse("baga6ea4seaaqc") + zero := big.Zero() + + testCases := []struct { + sector SectorOnChainInfo + readHex string + writeHex string + }{ + { + sector: SectorOnChainInfo{ + SealProof: -1, + SealedCID: defaultCid, + DealWeight: zero, + VerifiedDealWeight: zero, + InitialPledge: zero, + ExpectedDayReward: nil, + ExpectedStoragePledge: nil, + ReplacedDayReward: nil, + DailyFee: zero, + }, + // [0,-1,{"/":"baeaaaaa"},[],0,0,[],[],[],null,null,0,null,null,0,[]] + readHex: "900020d82a450001000000800000404040f6f600f6f60040", + // same on write as read + writeHex: "900020d82a450001000000800000404040f6f600f6f60040", + }, + { + sector: SectorOnChainInfo{ + SectorNumber: 1, + SealProof: abi.RegisteredSealProof_StackedDrg32GiBV1_1, + SealedCID: cid.MustParse("bagboea4seaaqa"), + DeprecatedDealIDs: nil, + Activation: 2, + Expiration: 3, + DealWeight: big.NewInt(4), + VerifiedDealWeight: big.NewInt(5), + InitialPledge: filWhole(6), + ExpectedDayReward: nil, + ExpectedStoragePledge: nil, + PowerBaseEpoch: 9, + ReplacedDayReward: nil, + SectorKeyCID: nil, + Flags: 0, + DailyFee: filWhole(11), + }, + // '[1,8,{"/":"bagboea4seaaqa"},[],2,3,[AAQ],[AAU],[AFNESDXsWAAA],null,null,9,null,null,0,[AJin2bgxTAAA]]' + readHex: "900108d82a49000182e20392200100800203420004420005490053444835ec580000f6f609f6f600490098a7d9b8314c0000", + // same on write as read + writeHex: "900108d82a49000182e20392200100800203420004420005490053444835ec580000f6f609f6f600490098a7d9b8314c0000", + }, + { + sector: SectorOnChainInfo{ + SectorNumber: 1, + SealProof: abi.RegisteredSealProof_StackedDrg32GiBV1_1, + SealedCID: cid.MustParse("bagboea4seaaqa"), + DeprecatedDealIDs: nil, + Activation: 2, + Expiration: 3, + DealWeight: big.NewInt(4), + VerifiedDealWeight: big.NewInt(5), + InitialPledge: filWhole(6), + ExpectedDayReward: nil, + ExpectedStoragePledge: nil, + PowerBaseEpoch: 9, + ReplacedDayReward: nil, + SectorKeyCID: §orKey, + Flags: SIMPLE_QA_POWER, + DailyFee: filWhole(11), + }, + // [1,8,{"/":"bagboea4seaaqa"},[],2,3,[AAQ],[AAU],[AFNESDXsWAAA],null,null,9,null,{"/":"baga6ea4seaaqc"},1,[AJin2bgxTAAA]] + readHex: "900108d82a49000182e20392200100800203420004420005490053444835ec580000f6f609f6d82a49000181e2039220010101490098a7d9b8314c0000", + // same on write as read + writeHex: "900108d82a49000182e20392200100800203420004420005490053444835ec580000f6f609f6d82a49000181e2039220010101490098a7d9b8314c0000", + }, + { + // old format stored on chain but materialised as the new format with a default value at the end + sector: SectorOnChainInfo{ + SectorNumber: 1, + SealProof: abi.RegisteredSealProof_StackedDrg64GiBV1_1, + SealedCID: cid.MustParse("bagboea4seaaqa"), + DeprecatedDealIDs: nil, + Activation: 2, + Expiration: 3, + DealWeight: big.NewInt(4), + VerifiedDealWeight: big.NewInt(5), + InitialPledge: filWhole(6), + ExpectedDayReward: nil, + ExpectedStoragePledge: nil, + PowerBaseEpoch: 9, + ReplacedDayReward: nil, + SectorKeyCID: nil, + Flags: SIMPLE_QA_POWER, + DailyFee: big.Int{}, // default, not present in the binary + }, + // [1,9,{"/":"bagboea4seaaqa"},[],2,3,[AAQ],[AAU],[AFNESDXsWAAA],null,null,9,null,null,1] + readHex: "8f0109d82a49000182e20392200100800203420004420005490053444835ec580000f6f609f6f601", + // extra field at the end on write, zero BigInt (bytes) for daily_fee + // [1,9,{"/":"bagboea4seaaqa"},[],2,3,[AAQ],[AAU],[AFNESDXsWAAA],null,null,9,null,null,1,[]] + writeHex: "900109d82a49000182e20392200100800203420004420005490053444835ec580000f6f609f6f60140", + }, + } + + for _, tc := range testCases { + t.Run("", func(t *testing.T) { + req := require.New(t) + + // write + var buf bytes.Buffer + req.NoError(tc.sector.MarshalCBOR(&buf)) + req.Equal(tc.writeHex, hex.EncodeToString(buf.Bytes())) + + // read + byts, err := hex.DecodeString(tc.readHex) + req.NoError(err) + var rt SectorOnChainInfo + req.NoError(rt.UnmarshalCBOR(bytes.NewReader(byts))) + req.Equal(tc.sector, rt) + }) + } +} + +func TestExpirationSet(t *testing.T) { + zero := big.Zero() + + testCases := []struct { + set ExpirationSet + readHex string + writeHex string + }{ + { + set: ExpirationSet{ + OnTimeSectors: bitfield.New(), + EarlySectors: bitfield.New(), + OnTimePledge: zero, + ActivePower: NewPowerPairZero(), + FaultyPower: NewPowerPairZero(), + FeeDeduction: zero, + }, + // [[],[],[],[[],[]],[[],[]],[]] + readHex: "8640404082404082404040", + // same on write as read + writeHex: "8640404082404082404040", + }, + { + set: ExpirationSet{ + OnTimeSectors: bfrt(0), + EarlySectors: bfrt(1), + OnTimePledge: filWhole(2), + ActivePower: NewPowerPair(big.NewInt(3), big.NewInt(4)), + FaultyPower: NewPowerPair(big.NewInt(5), big.NewInt(6)), + FeeDeduction: filWhole(7), + }, + // [[DA],[GA],[ABvBbWdOyAAA],[[AAM],[AAQ]],[[AAU],[AAY]],[AGEk/umTvAAA]] + readHex: "86410c411849001bc16d674ec80000824200034200048242000542000649006124fee993bc0000", + // same on write as read + writeHex: "86410c411849001bc16d674ec80000824200034200048242000542000649006124fee993bc0000", + }, + { + set: ExpirationSet{ + OnTimeSectors: bfrt(0), + EarlySectors: bfrt(1), + OnTimePledge: filWhole(2), + ActivePower: NewPowerPair(big.NewInt(3), big.NewInt(4)), + FaultyPower: NewPowerPair(big.NewInt(5), big.NewInt(6)), + FeeDeduction: big.Int{}, + }, + // [[DA],[GA],[ABvBbWdOyAAA],[[AAM],[AAQ]],[[AAU],[AAY]]] + readHex: "85410c411849001bc16d674ec800008242000342000482420005420006", + // [[DA],[GA],[ABvBbWdOyAAA],[[AAM],[AAQ]],[[AAU],[AAY]],[]] + writeHex: "86410c411849001bc16d674ec80000824200034200048242000542000640", + }, + } + + for _, tc := range testCases { + t.Run("", func(t *testing.T) { + req := require.New(t) + + // write + var buf bytes.Buffer + req.NoError(tc.set.MarshalCBOR(&buf)) + req.Equal(tc.writeHex, hex.EncodeToString(buf.Bytes())) + + // read + byts, err := hex.DecodeString(tc.readHex) + req.NoError(err) + var rt ExpirationSet + req.NoError(rt.UnmarshalCBOR(bytes.NewReader(byts))) + req.Equal(tc.set, rt) + }) + } +} + +func TestDeadline(t *testing.T) { + zero := big.Zero() + + testCases := []struct { + deadline Deadline + hex string + }{ + { + deadline: Deadline{ + Partitions: defaultCid, + ExpirationsEpochs: defaultCid, + PartitionsPoSted: bfrt(), + EarlyTerminations: bfrt(), + FaultyPower: NewPowerPairZero(), + OptimisticPoStSubmissions: defaultCid, + SectorsSnapshot: defaultCid, + PartitionsSnapshot: defaultCid, + OptimisticPoStSubmissionsSnapshot: defaultCid, + LivePower: NewPowerPairZero(), + DailyFee: zero, + }, + // [baeaaaaa,baeaaaaa,[],[],0,0,[[],[]],baeaaaaa,baeaaaaa,baeaaaaa,baeaaaaa,[[],[]],[]] + hex: "8dd82a450001000000d82a45000100000040400000824040d82a450001000000d82a450001000000d82a450001000000d82a45000100000082404040", + }, + { + deadline: Deadline{ + Partitions: cid.MustParse("bagboea4seaaqa"), + ExpirationsEpochs: cid.MustParse("bagboea4seaaqc"), + PartitionsPoSted: bfrt(0), + EarlyTerminations: bfrt(1), + LiveSectors: 2, + TotalSectors: 3, + FaultyPower: NewPowerPair(big.NewInt(4), big.NewInt(5)), + OptimisticPoStSubmissions: cid.MustParse("bagboea4seaaqe"), + SectorsSnapshot: cid.MustParse("bagboea4seaaqg"), + PartitionsSnapshot: cid.MustParse("bagboea4seaaqi"), + OptimisticPoStSubmissionsSnapshot: cid.MustParse("bagboea4seaaqk"), + LivePower: NewPowerPair(big.NewInt(6), big.NewInt(7)), + DailyFee: filWhole(8), + }, + // [bagboea4seaaqa,bagboea4seaaqc,[DA],[GA],2,3,[[AAQ],[AAU]],bagboea4seaaqe,bagboea4seaaqg,bagboea4seaaqi,bagboea4seaaqk,[[AAY],[AAc]],[AG8FtZ07IAAA]] + hex: "8dd82a49000182e20392200100d82a49000182e20392200101410c4118020382420004420005d82a49000182e20392200102d82a49000182e20392200103d82a49000182e20392200104d82a49000182e203922001058242000642000749006f05b59d3b200000", + }, + } + + for _, tc := range testCases { + t.Run("", func(t *testing.T) { + req := require.New(t) + + var buf bytes.Buffer + req.NoError(tc.deadline.MarshalCBOR(&buf)) + req.Equal(tc.hex, hex.EncodeToString(buf.Bytes())) + var rt Deadline + req.NoError(rt.UnmarshalCBOR(&buf)) + req.Equal(tc.deadline, rt) + }) + } +} + +func filWhole(i int64) abi.TokenAmount { + return big.Mul(big.NewInt(i), builtin.TokenPrecision) +} + +// bfrt makes a bitfield from a list of integers and round-trips it through encoding +// so that the internal representation is set properly for a deep equals() test +func bfrt(b ...uint64) bitfield.BitField { + bf := bitfield.NewFromSet(b) + var buf bytes.Buffer + if err := bf.MarshalCBOR(&buf); err != nil { + panic(err) + } + var rt bitfield.BitField + if err := rt.UnmarshalCBOR(&buf); err != nil { + panic(err) + } + return rt +} diff --git a/builtin/v18/miner/monies.go b/builtin/v18/miner/monies.go new file mode 100644 index 00000000..cb6d292f --- /dev/null +++ b/builtin/v18/miner/monies.go @@ -0,0 +1,192 @@ +package miner + +import ( + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/big" + "github.com/filecoin-project/go-state-types/builtin" + "github.com/filecoin-project/go-state-types/builtin/v18/util/math" + "github.com/filecoin-project/go-state-types/builtin/v18/util/smoothing" +) + +// Projection period of expected sector block reward for deposit required to pre-commit a sector. +// This deposit is lost if the pre-commitment is not timely followed up by a commitment proof. +var PreCommitDepositFactor = 20 +var PreCommitDepositProjectionPeriod = abi.ChainEpoch(PreCommitDepositFactor) * builtin.EpochsInDay + +// Projection period of expected sector block rewards for storage pledge required to commit a sector. +// This pledge is lost if a sector is terminated before its full committed lifetime. +var InitialPledgeFactor = 20 +var InitialPledgeProjectionPeriod = abi.ChainEpoch(InitialPledgeFactor) * builtin.EpochsInDay + +// Cap on initial pledge requirement for sectors. +// The target is 1 FIL (10**18 attoFIL) per 32GiB. +// This does not divide evenly, so the result is fractionally smaller. +var InitialPledgeMaxPerByte = big.Div(big.NewInt(1e18), big.NewInt(32<<30)) + +// Multiplier of share of circulating money supply for consensus pledge required to commit a sector. +// This pledge is lost if a sector is terminated before its full committed lifetime. +var InitialPledgeLockTarget = builtin.BigFrac{ + Numerator: big.NewInt(3), + Denominator: big.NewInt(10), +} + +const GammaFixedPointFactor = 1000 // 3 decimal places + +// The projected block reward a sector would earn over some period. +// Also known as "BR(t)". +// BR(t) = ProjectedRewardFraction(t) * SectorQualityAdjustedPower +// ProjectedRewardFraction(t) is the sum of estimated reward over estimated total power +// over all epochs in the projection period [t t+projectionDuration] +func ExpectedRewardForPower(rewardEstimate, networkQAPowerEstimate smoothing.FilterEstimate, qaSectorPower abi.StoragePower, projectionDuration abi.ChainEpoch) abi.TokenAmount { + networkQAPowerSmoothed := smoothing.Estimate(&networkQAPowerEstimate) + if networkQAPowerSmoothed.IsZero() { + return smoothing.Estimate(&rewardEstimate) + } + expectedRewardForProvingPeriod := smoothing.ExtrapolatedCumSumOfRatio(projectionDuration, 0, rewardEstimate, networkQAPowerEstimate) + br128 := big.Mul(qaSectorPower, expectedRewardForProvingPeriod) // Q.0 * Q.128 => Q.128 + br := big.Rsh(br128, math.Precision128) + + return big.Max(br, big.Zero()) +} + +// BR but zero values are clamped at 1 attofil +// Some uses of BR (PCD, IP) require a strictly positive value for BR derived values so +// accounting variables can be used as succinct indicators of miner activity. +func ExpectedRewardForPowerClampedAtAttoFIL(rewardEstimate, networkQAPowerEstimate smoothing.FilterEstimate, qaSectorPower abi.StoragePower, projectionDuration abi.ChainEpoch) abi.TokenAmount { + br := ExpectedRewardForPower(rewardEstimate, networkQAPowerEstimate, qaSectorPower, projectionDuration) + if br.LessThanEqual(big.Zero()) { + br = abi.NewTokenAmount(1) + } + return br +} + +// Computes the PreCommit deposit given sector qa weight and current network conditions. +// PreCommit Deposit = BR(PreCommitDepositProjectionPeriod) +func PreCommitDepositForPower(rewardEstimate, networkQAPowerEstimate smoothing.FilterEstimate, qaSectorPower abi.StoragePower) abi.TokenAmount { + return ExpectedRewardForPowerClampedAtAttoFIL(rewardEstimate, networkQAPowerEstimate, qaSectorPower, PreCommitDepositProjectionPeriod) +} + +// InitialPledgeForPower computes the pledge requirement for committing new quality-adjusted power +// to the network, given the current network total and baseline power, per-epoch reward, and +// circulating token supply. +// The pledge comprises two parts: +// - storage pledge, aka IP base: a multiple of the reward expected to be earned by newly-committed power +// - consensus pledge, aka additional IP: a pro-rata fraction of the circulating money supply +// +// IP = IPBase(t) + AdditionalIP(t) +// IPBase(t) = BR(t, InitialPledgeProjectionPeriod) +// AdditionalIP(t) = LockTarget(t)*PledgeShare(t) +// LockTarget = (LockTargetFactorNum / LockTargetFactorDenom) * FILCirculatingSupply(t) +// PledgeShare(t) = sectorQAPower / max(BaselinePower(t), NetworkQAPower(t)) +func InitialPledgeForPower( + qaPower, + baselinePower abi.StoragePower, + rewardEstimate, + networkQAPowerEstimate smoothing.FilterEstimate, + circulatingSupply abi.TokenAmount, + epochsSinceRampStart int64, + rampDurationEpochs uint64, +) abi.TokenAmount { + ipBase := ExpectedRewardForPowerClampedAtAttoFIL(rewardEstimate, networkQAPowerEstimate, qaPower, InitialPledgeProjectionPeriod) + + lockTargetNum := big.Mul(InitialPledgeLockTarget.Numerator, circulatingSupply) + lockTargetDenom := InitialPledgeLockTarget.Denominator + pledgeShareNum := qaPower + networkQAPower := smoothing.Estimate(&networkQAPowerEstimate) + + // Once FIP-0081 has fully activated, additional pledge will be 70% baseline + // pledge + 30% simple pledge. + const fip0081ActivationPermille = 300 + // Gamma/GAMMA_FIXED_POINT_FACTOR is the share of pledge coming from the + // baseline formulation, with 1-(gamma/GAMMA_FIXED_POINT_FACTOR) coming from + // simple pledge. + // gamma = 1000 - 300 * (epochs_since_ramp_start / ramp_duration_epochs).max(0).min(1) + var skew uint64 + switch { + case epochsSinceRampStart < 0: + // No skew before ramp start + skew = 0 + case rampDurationEpochs == 0 || epochsSinceRampStart >= int64(rampDurationEpochs): + // 100% skew after ramp end + skew = fip0081ActivationPermille + case epochsSinceRampStart > 0: + skew = (uint64(epochsSinceRampStart*fip0081ActivationPermille) / rampDurationEpochs) + } + gamma := big.NewInt(int64(GammaFixedPointFactor - skew)) + + additionalIPNum := big.Mul(lockTargetNum, pledgeShareNum) + + pledgeShareDenomBaseline := big.Max(big.Max(networkQAPower, baselinePower), qaPower) + pledgeShareDenomSimple := big.Max(networkQAPower, qaPower) + + additionalIPDenomBaseline := big.Mul(pledgeShareDenomBaseline, lockTargetDenom) + additionalIPBaseline := big.Div(big.Mul(gamma, additionalIPNum), big.Mul(additionalIPDenomBaseline, big.NewInt(GammaFixedPointFactor))) + additionalIPDenomSimple := big.Mul(pledgeShareDenomSimple, lockTargetDenom) + additionalIPSimple := big.Div(big.Mul(big.Sub(big.NewInt(GammaFixedPointFactor), gamma), additionalIPNum), big.Mul(additionalIPDenomSimple, big.NewInt(GammaFixedPointFactor))) + + // convex combination of simple and baseline pledge + additionalIP := big.Add(additionalIPBaseline, additionalIPSimple) + + nominalPledge := big.Add(ipBase, additionalIP) + pledgeCap := big.Mul(InitialPledgeMaxPerByte, qaPower) + + return big.Min(nominalPledge, pledgeCap) +} + +// Maximum number of lifetime days penalized when a sector is terminated. +const TerminationLifetimeCap abi.ChainEpoch = 140 + +// Used to compute termination fees in the base case by multiplying against initial pledge. +var TermFeePledgeMultiple = builtin.BigFrac{ + Numerator: big.NewInt(85), + Denominator: big.NewInt(1000), +} + +// Used to ensure the termination fee for young sectors is not arbitrarily low. +var TermFeeMinPledgeMultiple = builtin.BigFrac{ + Numerator: big.NewInt(2), + Denominator: big.NewInt(100), +} + +// Used to compute termination fees when the termination fee of a sector is less than the fault fee for the same sector. +var TermFeeMaxFaultFeeMultiple = builtin.BigFrac{ + Numerator: big.NewInt(105), + Denominator: big.NewInt(100), +} + +const ContinuedFaultFactorNum = 351 +const ContinuedFaultFactorDenom = 100 +const ContinuedFaultProjectionPeriod abi.ChainEpoch = (builtin.EpochsInDay * ContinuedFaultFactorNum) / ContinuedFaultFactorDenom + +// PledgePenaltyForContinuedFault calculates the penalty for a sector continuing faulty for another +// proving period. +// It is a projection of the expected reward earned by the sector. Also known as "FF(t)" +func PledgePenaltyForContinuedFault(rewardEstimate smoothing.FilterEstimate, networkQaPowerEstimate smoothing.FilterEstimate, qaSectorPower abi.StoragePower) abi.TokenAmount { + return ExpectedRewardForPower(rewardEstimate, networkQaPowerEstimate, qaSectorPower, ContinuedFaultProjectionPeriod) +} + +// PledgePenaltyForTermination Calculates termination fee for a given sector. Normally, it's +// calculated as a fixed percentage of the initial pledge. However, there are some special cases +// outlined in [FIP-0098](https://github.com/filecoin-project/FIPs/blob/master/FIPS/fip-0098.md). +func PledgePenaltyForTermination( + initialPledge abi.TokenAmount, + sectorAge abi.ChainEpoch, + faultFee abi.TokenAmount, +) abi.TokenAmount { + // Use the Percentage of the initial pledge strategy to determine the termination fee. + simpleTerminationFee := + big.Div(big.Mul(initialPledge, TermFeePledgeMultiple.Numerator), TermFeePledgeMultiple.Denominator) + + durationTerminationFee := + big.Div(big.Mul(big.NewInt(int64(sectorAge)), simpleTerminationFee), big.NewInt(int64(TerminationLifetimeCap*builtin.EpochsInDay))) + + // Apply the age adjustment for young sectors to arrive at the base termination fee. + baseTerminationFee := big.Min(simpleTerminationFee, durationTerminationFee) + + // Calculate the minimum allowed fee (a lower bound on the termination fee) by comparing the absolute minimum termination fee value against the fault fee. Whatever result is Larger sets the lower bound for the termination fee. + minimumFeeAbs := big.Div(big.Mul(initialPledge, TermFeeMinPledgeMultiple.Numerator), TermFeeMinPledgeMultiple.Denominator) + minimumFeeFf := big.Div(big.Mul(faultFee, TermFeeMaxFaultFeeMultiple.Numerator), TermFeeMaxFaultFeeMultiple.Denominator) + minimumFee := big.Max(minimumFeeAbs, minimumFeeFf) + + return big.Max(baseTerminationFee, minimumFee) +} diff --git a/builtin/v18/miner/monies_test.go b/builtin/v18/miner/monies_test.go new file mode 100644 index 00000000..20b11061 --- /dev/null +++ b/builtin/v18/miner/monies_test.go @@ -0,0 +1,331 @@ +package miner_test + +import ( + "fmt" + "testing" + + abi "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/big" + "github.com/filecoin-project/go-state-types/builtin" + "github.com/filecoin-project/go-state-types/builtin/v18/miner" + "github.com/filecoin-project/go-state-types/builtin/v18/util/smoothing" +) + +// See filecoin-project/builtin-actors actors/miner/tests/fip0081_initial_pledge.rs +func TestInitialPledgeForPowerFip0081(t *testing.T) { + filPrecision := big.NewInt(1_000_000_000_000_000_000) + + epochTargetReward := abi.TokenAmount(big.Zero()) + qaSectorPower := abi.StoragePower(big.NewInt(1 << 36)) + networkQAPower := abi.StoragePower(big.NewInt(1 << 10)) + powerRateOfChange := abi.StoragePower(big.NewInt(1 << 10)) + rewardEstimate := smoothing.FilterEstimate{ + PositionEstimate: epochTargetReward, + VelocityEstimate: big.Zero(), + } + powerEstimate := smoothing.FilterEstimate{ + PositionEstimate: networkQAPower, + VelocityEstimate: powerRateOfChange, + } + circulatingSupply := abi.TokenAmount(filPrecision) + + testCases := []struct { + name string + qaSectorPower abi.StoragePower + rewardEstimate smoothing.FilterEstimate + powerEstimate smoothing.FilterEstimate + circulatingSupply abi.TokenAmount + epochsSinceRampStart int64 + rampDurationEpochs uint64 + expectedInitialPledge abi.TokenAmount + }{ + { + name: "pre-ramp where 'baseline power' dominates (negative epochsSinceRampStart)", + qaSectorPower: qaSectorPower, + rewardEstimate: rewardEstimate, + powerEstimate: powerEstimate, + circulatingSupply: circulatingSupply, + epochsSinceRampStart: -100, + rampDurationEpochs: 100, + expectedInitialPledge: big.Add(big.Div(big.Mul(big.NewInt(1500), filPrecision), big.NewInt(10000)), big.NewInt(1)), + }, + { + name: "zero ramp duration", + qaSectorPower: qaSectorPower, + rewardEstimate: rewardEstimate, + powerEstimate: powerEstimate, + circulatingSupply: circulatingSupply, + epochsSinceRampStart: 0, + rampDurationEpochs: 0, + expectedInitialPledge: big.Add(big.Div(big.Mul(big.NewInt(1950), filPrecision), big.NewInt(10000)), big.NewInt(1)), + }, + { + name: "zero ramp duration (10 epochs since)", + qaSectorPower: qaSectorPower, + rewardEstimate: rewardEstimate, + powerEstimate: powerEstimate, + circulatingSupply: circulatingSupply, + epochsSinceRampStart: 10, + rampDurationEpochs: 0, + expectedInitialPledge: big.Add(big.Div(big.Mul(big.NewInt(1950), filPrecision), big.NewInt(10000)), big.NewInt(1)), + }, + { + name: "pre-ramp where 'baseline power' dominates", + qaSectorPower: qaSectorPower, + rewardEstimate: rewardEstimate, + powerEstimate: powerEstimate, + circulatingSupply: circulatingSupply, + epochsSinceRampStart: 0, + rampDurationEpochs: 100, + expectedInitialPledge: big.Add(big.Div(big.Mul(big.NewInt(1500), filPrecision), big.NewInt(10000)), big.NewInt(1)), + }, + { + name: "on-ramp where 'baseline power' is at 85% and `simple power` is at 15%", + qaSectorPower: qaSectorPower, + rewardEstimate: rewardEstimate, + powerEstimate: powerEstimate, + circulatingSupply: circulatingSupply, + epochsSinceRampStart: 50, + rampDurationEpochs: 100, + expectedInitialPledge: big.Add(big.Div(big.Mul(big.NewInt(1725), filPrecision), big.NewInt(10000)), big.NewInt(1)), + }, + { + name: "after-ramp where 'baseline power' is at 70% and `simple power` is at 30%", + qaSectorPower: qaSectorPower, + rewardEstimate: rewardEstimate, + powerEstimate: powerEstimate, + circulatingSupply: circulatingSupply, + epochsSinceRampStart: 150, + rampDurationEpochs: 100, + expectedInitialPledge: big.Add(big.Div(big.Mul(big.NewInt(1950), filPrecision), big.NewInt(10000)), big.NewInt(1)), + }, + { + name: "on-ramp where 'baseline power' has reduced effect (97%)", + qaSectorPower: qaSectorPower, + rewardEstimate: rewardEstimate, + powerEstimate: powerEstimate, + circulatingSupply: circulatingSupply, + epochsSinceRampStart: 10, + rampDurationEpochs: 100, + expectedInitialPledge: big.Add(big.Div(big.Mul(big.NewInt(1545), filPrecision), big.NewInt(10000)), big.NewInt(1)), + }, + { + name: "on-ramp, first epoch, pledge should be 97% 'baseline' + 3% simple", + qaSectorPower: qaSectorPower, + rewardEstimate: rewardEstimate, + powerEstimate: powerEstimate, + circulatingSupply: circulatingSupply, + epochsSinceRampStart: 1, + rampDurationEpochs: 10, + expectedInitialPledge: big.Add(big.Div(big.Mul(big.NewInt(1545), filPrecision), big.NewInt(10000)), big.NewInt(1)), + }, + { + name: "validate pledges 1 epoch before and after ramp start: before ramp start", + qaSectorPower: qaSectorPower, + rewardEstimate: rewardEstimate, + powerEstimate: powerEstimate, + circulatingSupply: circulatingSupply, + epochsSinceRampStart: -1, + rampDurationEpochs: 10, + expectedInitialPledge: big.Add(big.Div(big.Mul(big.NewInt(1500), filPrecision), big.NewInt(10000)), big.NewInt(1)), + }, + { + name: "validate pledges 1 epoch before and after ramp start: at ramp start", + qaSectorPower: qaSectorPower, + rewardEstimate: rewardEstimate, + powerEstimate: powerEstimate, + circulatingSupply: circulatingSupply, + epochsSinceRampStart: 0, + rampDurationEpochs: 10, + expectedInitialPledge: big.Add(big.Div(big.Mul(big.NewInt(1500), filPrecision), big.NewInt(10000)), big.NewInt(1)), + }, + { + name: "validate pledges 1 epoch before and after ramp start: on ramp start", + qaSectorPower: qaSectorPower, + rewardEstimate: rewardEstimate, + powerEstimate: powerEstimate, + circulatingSupply: circulatingSupply, + epochsSinceRampStart: 1, + rampDurationEpochs: 10, + expectedInitialPledge: big.Add(big.Div(big.Mul(big.NewInt(1545), filPrecision), big.NewInt(10000)), big.NewInt(1)), + }, + { + name: "post-ramp where 'baseline power' has reduced effect (70%)", + qaSectorPower: qaSectorPower, + rewardEstimate: rewardEstimate, + powerEstimate: powerEstimate, + circulatingSupply: circulatingSupply, + epochsSinceRampStart: 500, + rampDurationEpochs: 100, + expectedInitialPledge: big.Add(big.Div(big.Mul(big.NewInt(1950), filPrecision), big.NewInt(10000)), big.NewInt(1)), + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + initialPledge := miner.InitialPledgeForPower( + tc.qaSectorPower, + abi.StoragePower(big.NewInt(1<<37)), + tc.rewardEstimate, + tc.powerEstimate, + tc.circulatingSupply, + tc.epochsSinceRampStart, + tc.rampDurationEpochs, + ) + if !initialPledge.Equals(tc.expectedInitialPledge) { + t.Fatalf("expected initial pledge %v, got %v", tc.expectedInitialPledge, initialPledge) + } + }) + } +} + +func TestNegativeBRClamp(t *testing.T) { + epochTargetReward := big.NewInt(1 << 50) + qaSectorPower := abi.StoragePower(big.NewInt(1 << 36)) + networkQAPower := abi.StoragePower(big.NewInt(1 << 10)) + powerRateOfChange := big.NewInt(1 << 10).Neg() + rewardEstimate := smoothing.FilterEstimate{ + PositionEstimate: abi.TokenAmount(epochTargetReward), + VelocityEstimate: big.Zero(), + } + powerEstimate := smoothing.FilterEstimate{ + PositionEstimate: networkQAPower, + VelocityEstimate: powerRateOfChange, + } + + if big.Add(powerEstimate.PositionEstimate, big.Mul(powerEstimate.VelocityEstimate, big.NewInt(4))).GreaterThan(networkQAPower) { + t.Fatalf("power estimate extrapolated incorrectly") + } + + fourBR := miner.ExpectedRewardForPower(rewardEstimate, powerEstimate, qaSectorPower, 4) + if !fourBR.IsZero() { + t.Fatalf("expected zero BR, got %v", fourBR) + } +} + +func TestZeroPowerMeansZeroFaultPenalty(t *testing.T) { + epochTargetReward := big.NewInt(1 << 50) + zeroQAPower := abi.StoragePower(big.Zero()) + networkQAPower := abi.StoragePower(big.NewInt(1 << 10)) + powerRateOfChange := big.NewInt(1 << 10) + rewardEstimate := smoothing.FilterEstimate{ + PositionEstimate: abi.TokenAmount(epochTargetReward), + VelocityEstimate: big.Zero(), + } + powerEstimate := smoothing.FilterEstimate{ + PositionEstimate: networkQAPower, + VelocityEstimate: powerRateOfChange, + } + + penaltyForZeroPowerFaulted := miner.PledgePenaltyForContinuedFault(rewardEstimate, powerEstimate, zeroQAPower) + if !penaltyForZeroPowerFaulted.IsZero() { + t.Fatalf("expected zero penalty, got %v", penaltyForZeroPowerFaulted) + } +} + +func TestAggregatePowerPledgePenaltyForContinuedFault(t *testing.T) { + epochTargetReward := big.NewInt(1 << 50) + networkQAPower := abi.StoragePower(big.NewInt(1 << 10)) + powerRateOfChange := big.NewInt(1 << 10) + rewardEstimate := smoothing.NewEstimate(abi.TokenAmount(epochTargetReward), big.Zero()) + powerEstimate := smoothing.NewEstimate(networkQAPower, powerRateOfChange) + + testCases := []struct { + sectorMultiple int64 + qaPower abi.StoragePower + }{ + {10, abi.StoragePower(big.NewInt(1 << 6))}, + {10, abi.StoragePower(big.NewInt(1 << 36))}, + {10, abi.StoragePower(big.NewInt(1 << 50))}, + {1000, abi.StoragePower(big.NewInt(1 << 6))}, + {1000, abi.StoragePower(big.NewInt(1 << 36))}, + {1000, abi.StoragePower(big.NewInt(1 << 50))}, + } + + for _, tc := range testCases { + t.Run(fmt.Sprintf("%d sectors, %s qap", tc.sectorMultiple, tc.qaPower), func(t *testing.T) { + sectorMultiple := tc.sectorMultiple + qaPower := tc.qaPower + + aggregatePenalty := miner.PledgePenaltyForContinuedFault( + rewardEstimate, + powerEstimate, + big.Mul(qaPower, big.NewInt(sectorMultiple)), + ) + + individualPenalties := big.Zero() + for i := int64(0); i < sectorMultiple; i++ { + individualPenalty := miner.PledgePenaltyForContinuedFault(rewardEstimate, powerEstimate, qaPower) + individualPenalties = big.Add(individualPenalties, individualPenalty) + } + if aggregatePenalty.LessThanEqual(big.Zero()) { + t.Fatalf("aggregate penalty is not positive: %s", aggregatePenalty) + } + + diff := big.Sub(aggregatePenalty, individualPenalties).Abs() + allowedAttoDifference := big.NewInt(sectorMultiple) + if diff.GreaterThan(allowedAttoDifference) { + t.Fatalf("aggregate_penalty: %v, individual_penalties: %v, diff: %v", aggregatePenalty, individualPenalties, diff) + } + }) + } +} + +func TestPledgePenaltyForTermination(t *testing.T) { + t.Run("when sector age exceeds cap returns percentage of initial pledge", func(t *testing.T) { + sectorAgeInDays := miner.TerminationLifetimeCap + 1 + sectorAge := sectorAgeInDays * builtin.EpochsInDay + + initialPledge := abi.NewTokenAmount(1 << 10) + faultFee := abi.NewTokenAmount(0) + fee := miner.PledgePenaltyForTermination(initialPledge, sectorAge, faultFee) + + expectedFee := big.Div(big.Mul(initialPledge, miner.TermFeePledgeMultiple.Numerator), miner.TermFeePledgeMultiple.Denominator) + if !fee.Equals(abi.TokenAmount(expectedFee)) { + t.Fatalf("expected fee %v, got %v", expectedFee, fee) + } + }) + + t.Run("when sector age below cap returns percentage of initial pledge percentage", func(t *testing.T) { + sectorAgeInDays := miner.TerminationLifetimeCap / 2 + sectorAge := sectorAgeInDays * builtin.EpochsInDay + + initialPledge := abi.NewTokenAmount(1 << 10) + faultFee := abi.NewTokenAmount(0) + fee := miner.PledgePenaltyForTermination(initialPledge, sectorAge, faultFee) + + simpleTerminationFee := big.Div(big.Mul(initialPledge, miner.TermFeePledgeMultiple.Numerator), miner.TermFeePledgeMultiple.Denominator) + expectedFee := big.Div(big.Mul(simpleTerminationFee, big.NewInt(int64(sectorAgeInDays))), big.NewInt(int64(miner.TerminationLifetimeCap))) + + if !fee.Equals(abi.TokenAmount(expectedFee)) { + t.Fatalf("expected fee %v, got %v", expectedFee, fee) + } + }) + + t.Run("when termination fee less than fault fee returns multiple of fault fee", func(t *testing.T) { + sectorAgeInDays := miner.TerminationLifetimeCap + 1 + sectorAge := sectorAgeInDays * builtin.EpochsInDay + + initialPledge := abi.NewTokenAmount(1 << 10) + faultFee := abi.NewTokenAmount(1 << 10) + fee := miner.PledgePenaltyForTermination(initialPledge, sectorAge, faultFee) + + expectedFee := big.Div(big.Mul(faultFee, miner.TermFeeMaxFaultFeeMultiple.Numerator), miner.TermFeeMaxFaultFeeMultiple.Denominator) + if !fee.Equals(abi.TokenAmount(expectedFee)) { + t.Fatalf("expected fee %v, got %v", expectedFee, fee) + } + }) + + t.Run("when termination fee less than minimum returns minimum", func(t *testing.T) { + sectorAge := abi.ChainEpoch(0) + + initialPledge := abi.NewTokenAmount(1 << 10) + faultFee := abi.NewTokenAmount(0) + fee := miner.PledgePenaltyForTermination(initialPledge, sectorAge, faultFee) + + expectedFee := big.Div(big.Mul(initialPledge, miner.TermFeeMinPledgeMultiple.Numerator), miner.TermFeeMinPledgeMultiple.Denominator) + if !fee.Equals(abi.TokenAmount(expectedFee)) { + t.Fatalf("expected fee %v, got %v", expectedFee, fee) + } + }) +} diff --git a/builtin/v18/miner/partition_state.go b/builtin/v18/miner/partition_state.go new file mode 100644 index 00000000..4ad18c9e --- /dev/null +++ b/builtin/v18/miner/partition_state.go @@ -0,0 +1,139 @@ +package miner + +import ( + "github.com/ipfs/go-cid" + "golang.org/x/xerrors" + + "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/builtin/v18/util/adt" +) + +type Partition struct { + // Sector numbers in this partition, including faulty, unproven, and terminated sectors. + Sectors bitfield.BitField + // Unproven sectors in this partition. This bitfield will be cleared on + // a successful window post (or at the end of the partition's next + // deadline). At that time, any still unproven sectors will be added to + // the faulty sector bitfield. + Unproven bitfield.BitField + // Subset of sectors detected/declared faulty and not yet recovered (excl. from PoSt). + // Faults ∩ Terminated = ∅ + Faults bitfield.BitField + // Subset of faulty sectors expected to recover on next PoSt + // Recoveries ∩ Terminated = ∅ + Recoveries bitfield.BitField + // Subset of sectors terminated but not yet removed from partition (excl. from PoSt) + Terminated bitfield.BitField + // Maps epochs sectors that expire in or before that epoch. + // An expiration may be an "on-time" scheduled expiration, or early "faulty" expiration. + // Keys are quantized to last-in-deadline epochs. + ExpirationsEpochs cid.Cid // AMT[ChainEpoch]ExpirationSet + // Subset of terminated that were before their committed expiration epoch, by termination epoch. + // Termination fees have not yet been calculated or paid and associated deals have not yet been + // canceled but effective power has already been adjusted. + // Not quantized. + EarlyTerminated cid.Cid // AMT[ChainEpoch]BitField + + // Power of not-yet-terminated sectors (incl faulty & unproven). + LivePower PowerPair + // Power of yet-to-be-proved sectors (never faulty). + UnprovenPower PowerPair + // Power of currently-faulty sectors. FaultyPower <= LivePower. + FaultyPower PowerPair + // Power of expected-to-recover sectors. RecoveringPower <= FaultyPower. + RecoveringPower PowerPair +} + +// Bitwidth of AMTs determined empirically from mutation patterns and projections of mainnet data. +const PartitionExpirationAmtBitwidth = 4 +const PartitionEarlyTerminationArrayAmtBitwidth = 3 + +// Value type for a pair of raw and QA power. +type PowerPair struct { + Raw abi.StoragePower + QA abi.StoragePower +} + +// Live sectors are those that are not terminated (but may be faulty). +func (p *Partition) LiveSectors() (bitfield.BitField, error) { + live, err := bitfield.SubtractBitField(p.Sectors, p.Terminated) + if err != nil { + return bitfield.BitField{}, xerrors.Errorf("failed to compute live sectors: %w", err) + } + return live, nil + +} + +// Active sectors are those that are neither terminated nor faulty nor unproven, i.e. actively contributing power. +func (p *Partition) ActiveSectors() (bitfield.BitField, error) { + live, err := p.LiveSectors() + if err != nil { + return bitfield.BitField{}, err + } + nonFaulty, err := bitfield.SubtractBitField(live, p.Faults) + if err != nil { + return bitfield.BitField{}, xerrors.Errorf("failed to compute active sectors: %w", err) + } + active, err := bitfield.SubtractBitField(nonFaulty, p.Unproven) + if err != nil { + return bitfield.BitField{}, xerrors.Errorf("failed to compute active sectors: %w", err) + } + return active, err +} + +// Activates unproven sectors, returning the activated power. +func (p *Partition) ActivateUnproven() PowerPair { + newPower := p.UnprovenPower + p.UnprovenPower = NewPowerPairZero() + p.Unproven = bitfield.New() + return newPower +} + +func (d *Deadline) PartitionsSnapshotArray(store adt.Store) (*adt.Array, error) { + arr, err := adt.AsArray(store, d.PartitionsSnapshot, DeadlinePartitionsAmtBitwidth) + if err != nil { + return nil, xerrors.Errorf("failed to load partitions snapshot: %w", err) + } + return arr, nil +} + +// +// PowerPair +// + +func NewPowerPairZero() PowerPair { + return NewPowerPair(big.Zero(), big.Zero()) +} + +func NewPowerPair(raw, qa abi.StoragePower) PowerPair { + return PowerPair{Raw: raw, QA: qa} +} + +func (pp PowerPair) Add(other PowerPair) PowerPair { + return PowerPair{ + Raw: big.Add(pp.Raw, other.Raw), + QA: big.Add(pp.QA, other.QA), + } +} + +func (pp PowerPair) Sub(other PowerPair) PowerPair { + return PowerPair{ + Raw: big.Sub(pp.Raw, other.Raw), + QA: big.Sub(pp.QA, other.QA), + } +} + +func (pp *PowerPair) Equals(other PowerPair) bool { + return pp.Raw.Equals(other.Raw) && pp.QA.Equals(other.QA) +} + +func (pp PowerPair) IsZero() bool { + return pp.Raw.IsZero() && pp.QA.IsZero() +} + +// Active power is power of non-faulty sectors. +func (p *Partition) ActivePower() PowerPair { + return p.LivePower.Sub(p.FaultyPower).Sub(p.UnprovenPower) +} diff --git a/builtin/v18/miner/policy.go b/builtin/v18/miner/policy.go new file mode 100644 index 00000000..aa4ab263 --- /dev/null +++ b/builtin/v18/miner/policy.go @@ -0,0 +1,231 @@ +package miner + +import ( + "github.com/ipfs/go-cid" + mh "github.com/multiformats/go-multihash" + + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/big" + "github.com/filecoin-project/go-state-types/builtin" +) + +// The period over which a miner's active sectors are expected to be proven via WindowPoSt. +// This guarantees that (1) user data is proven daily, (2) user data is stored for 24h by a rational miner +// (due to Window PoSt cost assumption). +var WPoStProvingPeriod = abi.ChainEpoch(builtin.EpochsInDay) // 24 hours PARAM_SPEC + +// The period between the opening and the closing of a WindowPoSt deadline in which the miner is expected to +// provide a Window PoSt proof. +// This provides a miner enough time to compute and propagate a Window PoSt proof. +var WPoStChallengeWindow = abi.ChainEpoch(30 * 60 / builtin.EpochDurationSeconds) // 30 minutes (48 per day) PARAM_SPEC + +// WPoStDisputeWindow is the period after a challenge window ends during which +// PoSts submitted during that period may be disputed. +var WPoStDisputeWindow = 2 * ChainFinality // PARAM_SPEC + +// The number of non-overlapping PoSt deadlines in a proving period. +// This spreads a miner's Window PoSt work across a proving period. +const WPoStPeriodDeadlines = uint64(48) // PARAM_SPEC + +// MaxPartitionsPerDeadline is the maximum number of partitions that will be assigned to a deadline. +// For a minimum storage of upto 1Eib, we need 300 partitions per deadline. +// 48 * 32GiB * 2349 * 300 = 1.00808144 EiB +// So, to support upto 10Eib storage, we set this to 3000. +const MaxPartitionsPerDeadline = 3000 + +// The maximum number of partitions that can be loaded in a single invocation. +// This limits the number of simultaneous fault, recovery, or sector-extension declarations. +// We set this to same as MaxPartitionsPerDeadline so we can process that many partitions every deadline. +const AddressedPartitionsMax = MaxPartitionsPerDeadline + +// The maximum number of partitions that can be proven in a single PoSt message. +const PoStedPartitionsMax = 3 + +// Maximum number of unique "declarations" in batch operations. +const DeclarationsMax = AddressedPartitionsMax + +// The maximum number of sector infos that can be loaded in a single invocation. +// This limits the amount of state to be read in a single message execution. +const AddressedSectorsMax = 25_000 // PARAM_SPEC + +// Epochs after which chain state is final with overwhelming probability (hence the likelihood of two fork of this size is negligible) +// This is a conservative value that is chosen via simulations of all known attacks. +const ChainFinality = abi.ChainEpoch(900) // PARAM_SPEC + +// Prefix for sealed sector CIDs (CommR). +var SealedCIDPrefix = cid.Prefix{ + Version: 1, + Codec: cid.FilCommitmentSealed, + MhType: mh.POSEIDON_BLS12_381_A1_FC1, + MhLength: 32, +} + +// List of proof types which may be used when creating a new miner actor. +// This is mutable to allow configuration of testing and development networks. +var WindowPoStProofTypes = map[abi.RegisteredPoStProof]struct{}{ + abi.RegisteredPoStProof_StackedDrgWindow32GiBV1: {}, + abi.RegisteredPoStProof_StackedDrgWindow64GiBV1: {}, +} + +// Maximum delay to allow between sector pre-commit and subsequent proof. +// The allowable delay depends on seal proof algorithm. +var MaxProveCommitDuration = map[abi.RegisteredSealProof]abi.ChainEpoch{ + abi.RegisteredSealProof_StackedDrg32GiBV1: builtin.EpochsInDay + PreCommitChallengeDelay, // PARAM_SPEC + abi.RegisteredSealProof_StackedDrg2KiBV1: builtin.EpochsInDay + PreCommitChallengeDelay, + abi.RegisteredSealProof_StackedDrg8MiBV1: builtin.EpochsInDay + PreCommitChallengeDelay, + abi.RegisteredSealProof_StackedDrg512MiBV1: builtin.EpochsInDay + PreCommitChallengeDelay, + abi.RegisteredSealProof_StackedDrg64GiBV1: builtin.EpochsInDay + PreCommitChallengeDelay, + + abi.RegisteredSealProof_StackedDrg32GiBV1_1: 30*builtin.EpochsInDay + PreCommitChallengeDelay, // PARAM_SPEC + abi.RegisteredSealProof_StackedDrg2KiBV1_1: 30*builtin.EpochsInDay + PreCommitChallengeDelay, + abi.RegisteredSealProof_StackedDrg8MiBV1_1: 30*builtin.EpochsInDay + PreCommitChallengeDelay, + abi.RegisteredSealProof_StackedDrg512MiBV1_1: 30*builtin.EpochsInDay + PreCommitChallengeDelay, + abi.RegisteredSealProof_StackedDrg64GiBV1_1: 30*builtin.EpochsInDay + PreCommitChallengeDelay, + + abi.RegisteredSealProof_StackedDrg32GiBV1_1_Feat_SyntheticPoRep: 30*builtin.EpochsInDay + PreCommitChallengeDelay, // PARAM_SPEC + abi.RegisteredSealProof_StackedDrg2KiBV1_1_Feat_SyntheticPoRep: 30*builtin.EpochsInDay + PreCommitChallengeDelay, + abi.RegisteredSealProof_StackedDrg8MiBV1_1_Feat_SyntheticPoRep: 30*builtin.EpochsInDay + PreCommitChallengeDelay, + abi.RegisteredSealProof_StackedDrg512MiBV1_1_Feat_SyntheticPoRep: 30*builtin.EpochsInDay + PreCommitChallengeDelay, + abi.RegisteredSealProof_StackedDrg64GiBV1_1_Feat_SyntheticPoRep: 30*builtin.EpochsInDay + PreCommitChallengeDelay, +} + +// The maximum number of sector pre-commitments in a single batch. +// 32 sectors per epoch would support a single miner onboarding 1EiB of 32GiB sectors in 1 year. +const PreCommitSectorBatchMaxSize = 256 + +// The maximum number of sector replica updates in a single batch. +// Same as PreCommitSectorBatchMaxSize for consistency +const ProveReplicaUpdatesMaxSize = PreCommitSectorBatchMaxSize + +// Maximum delay between challenge and pre-commitment. +// This prevents a miner sealing sectors far in advance of committing them to the chain, thus committing to a +// particular chain. +var MaxPreCommitRandomnessLookback = builtin.EpochsInDay + ChainFinality // PARAM_SPEC + +// Number of epochs between publishing a sector pre-commitment and when the challenge for interactive PoRep is drawn. +// This (1) prevents a miner predicting a challenge before staking their pre-commit deposit, and +// (2) prevents a miner attempting a long fork in the past to insert a pre-commitment after seeing the challenge. +var PreCommitChallengeDelay = abi.ChainEpoch(150) // PARAM_SPEC + +// Maximum number of epochs within which to fetch a valid seal randomness from the chain for +// a non-interactive PoRep proof. This balances the need to tie the seal to a particular chain with +// but makes allowance for service providers to offer pre-sealed sectors within a larger window of +// time. +var MaxProveCommitNiLookback = abi.ChainEpoch(180 * builtin.EpochsInDay) // PARAM_SPEC + +// Lookback from the deadline's challenge window opening from which to sample chain randomness for the WindowPoSt challenge seed. +// This means that deadline windows can be non-overlapping (which make the programming simpler) without requiring a +// miner to wait for chain stability during the challenge window. +// This value cannot be too large lest it compromise the rationality of honest storage (from Window PoSt cost assumptions). +const WPoStChallengeLookback = abi.ChainEpoch(20) // PARAM_SPEC + +// Minimum period between fault declaration and the next deadline opening. +// If the number of epochs between fault declaration and deadline's challenge window opening is lower than FaultDeclarationCutoff, +// the fault declaration is considered invalid for that deadline. +// This guarantees that a miner is not likely to successfully fork the chain and declare a fault after seeing the challenges. +const FaultDeclarationCutoff = WPoStChallengeLookback + 50 // PARAM_SPEC + +// The maximum age of a fault before the sector is terminated. +// This bounds the time a miner can lose client's data before sacrificing pledge and deal collateral. +var FaultMaxAge = WPoStProvingPeriod * 42 // PARAM_SPEC + +// Staging period for a miner worker key change. +// This delay prevents a miner choosing a more favorable worker key that wins leader elections. +const WorkerKeyChangeDelay = ChainFinality // PARAM_SPEC + +// Minimum number of epochs past the current epoch a sector may be set to expire. +const MinSectorExpiration = 180 * builtin.EpochsInDay // PARAM_SPEC + +// The maximum number of epochs past the current epoch that sector lifetime may be extended. +// A sector may be extended multiple times, however, the total maximum lifetime is also bounded by +// the associated seal proof's maximum lifetime. +const MaxSectorExpirationExtension = 1278 * builtin.EpochsInDay // PARAM_SPEC + +// Numerator of the fraction of circulating supply that will be used to calculate +// the daily fee for new sectors. +// +// 5.56e-15 / 32GiB = 5.56e-15 / (32 * 2^30) = 5.56e-15 / 34,359,738,368 ≈ 1.61817e-25 +// +// (i.e. slightly rounded for simplicity and a more direct multiplication). +// We implement this as 161817e-30. +const DailyFeeCirculatingSupplyQAPMultiplierNum = 161817 + +// Denominator of the fraction of circulating supply that will be used to calculate +// the daily fee for new sectors. +var DailyFeeCirculatingSupplyQAPMultiplierDenom = (func() big.Int { + bi, err := big.FromString("1000000000000000000000000000000") // 10^30 + if err != nil { + panic(err) + } + return bi +})() + +// Denominator for the fraction of estimated daily block reward for the sector(s) +// attracting a fee, to be used as a cap for the fees when payable. +// No numerator is provided as the fee is calculated as a fraction of the estimated +// daily block reward. +const DailyFeeBlockRewardCapDenom = 2 + +// QualityForWeight calculates the quality of a sector with the given size, duration, and verified weight. +// VerifiedDealWeight is spacetime occupied by verified pieces in a sector. +// VerifiedDealWeight should be less than or equal to total SpaceTime of a sector. +// Sectors full of VerifiedDeals will have a BigInt of VerifiedDealWeightMultiplier/QualityBaseMultiplier. +// Sectors without VerifiedDeals will have a BigInt of QualityBaseMultiplier/QualityBaseMultiplier. +// BigInt of a sector is a weighted average of multipliers based on their proportions. +func QualityForWeight(size abi.SectorSize, duration abi.ChainEpoch, verifiedWeight abi.DealWeight) abi.SectorQuality { + // sectorSpaceTime = size * duration + sectorSpaceTime := big.Mul(big.NewIntUnsigned(uint64(size)), big.NewInt(int64(duration))) + // Base - all size * duration of non-verified deals + // weightedBaseSpaceTime = (sectorSpaceTime - verifiedWeight) * QualityBaseMultiplier + weightedBaseSpaceTime := big.Mul(big.Sub(sectorSpaceTime, verifiedWeight), builtin.QualityBaseMultiplier) + // Verified - all verified deal size * verified deal duration * 100 + // weightedVerifiedSpaceTime = verifiedWeight * VerifiedDealWeightMultiplier + weightedVerifiedSpaceTime := big.Mul(verifiedWeight, builtin.VerifiedDealWeightMultiplier) + // Sum - sum of all spacetime + // weightedSumSpaceTime = weightedBaseSpaceTime + weightedVerifiedSpaceTime + weightedSumSpaceTime := big.Sum(weightedBaseSpaceTime, weightedVerifiedSpaceTime) + // scaledUpWeightedSumSpaceTime = weightedSumSpaceTime * 2^20 + scaledUpWeightedSumSpaceTime := big.Lsh(weightedSumSpaceTime, builtin.SectorQualityPrecision) + + // Average of weighted space time: (scaledUpWeightedSumSpaceTime / sectorSpaceTime * 10) + return big.Div(big.Div(scaledUpWeightedSumSpaceTime, sectorSpaceTime), builtin.QualityBaseMultiplier) +} + +// The power for a sector size, committed duration, and weight. +func QAPowerForWeight(size abi.SectorSize, duration abi.ChainEpoch, verifiedWeight abi.DealWeight) abi.StoragePower { + quality := QualityForWeight(size, duration, verifiedWeight) + return big.Rsh(big.Mul(big.NewIntUnsigned(uint64(size)), quality), builtin.SectorQualityPrecision) +} + +// The quality-adjusted power for a sector. +func QAPowerForSector(size abi.SectorSize, sector *SectorOnChainInfo) abi.StoragePower { + duration := sector.Expiration - sector.PowerBaseEpoch + return QAPowerForWeight(size, duration, sector.VerifiedDealWeight) +} + +const MaxAggregatedSectors = 819 +const MinAggregatedSectors = 4 +const MaxAggregateProofSize = 81960 + +// Specification for a linear vesting schedule. +type VestSpec struct { + InitialDelay abi.ChainEpoch // Delay before any amount starts vesting. + VestPeriod abi.ChainEpoch // Period over which the total should vest, after the initial delay. + StepDuration abi.ChainEpoch // Duration between successive incremental vests (independent of vesting period). + Quantization abi.ChainEpoch // Maximum precision of vesting table (limits cardinality of table). +} + +// Returns maximum achievable QA power. +func QAPowerMax(size abi.SectorSize) abi.StoragePower { + return big.Div( + big.Mul(big.NewInt(int64(size)), builtin.VerifiedDealWeightMultiplier), + builtin.QualityBaseMultiplier) +} + +// DailyProofFee calculates the daily fee for a sector's quality-adjusted power based on the current +// circulating supply. +func DailyProofFee(circulatingSupply abi.TokenAmount, qaPower abi.StoragePower) abi.TokenAmount { + numerator := big.NewInt(DailyFeeCirculatingSupplyQAPMultiplierNum) + result := big.Mul(big.Mul(numerator, qaPower), circulatingSupply) + return big.Div(result, DailyFeeCirculatingSupplyQAPMultiplierDenom) +} diff --git a/builtin/v18/miner/policy_test.go b/builtin/v18/miner/policy_test.go new file mode 100644 index 00000000..e21e601a --- /dev/null +++ b/builtin/v18/miner/policy_test.go @@ -0,0 +1,83 @@ +package miner_test + +import ( + "testing" + + abi "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/big" + "github.com/filecoin-project/go-state-types/builtin" + v14miner "github.com/filecoin-project/go-state-types/builtin/v14/miner" + "github.com/filecoin-project/go-state-types/builtin/v18/miner" + "github.com/stretchr/testify/require" +) + +func TestQualityForWeight(t *testing.T) { + emptyQuality := big.NewInt(1 << builtin.SectorQualityPrecision) + verifiedQuality := big.Mul(emptyQuality, big.Div(builtin.VerifiedDealWeightMultiplier, builtin.QualityBaseMultiplier)) + halfVerifiedQuality := big.Add(big.Div(emptyQuality, big.NewInt(2)), big.Div(verifiedQuality, big.NewInt(2))) + + sizeRange := []abi.SectorSize{ + abi.SectorSize(2 << 10), + abi.SectorSize(8 << 20), + abi.SectorSize(512 << 20), + abi.SectorSize(32 << 30), + abi.SectorSize(64 << 30), + } + durationRange := []abi.ChainEpoch{ + abi.ChainEpoch(1), + abi.ChainEpoch(10), + abi.ChainEpoch(1000), + 1000 * builtin.EpochsInDay, + } + + for _, size := range sizeRange { + for _, duration := range durationRange { + fullWeight := big.NewInt(int64(size) * int64(duration)) + halfWeight := big.Div(fullWeight, big.NewInt(2)) + + require.Equal(t, emptyQuality, miner.QualityForWeight(size, duration, big.Zero())) + require.Equal(t, verifiedQuality, miner.QualityForWeight(size, duration, fullWeight)) + require.Equal(t, halfVerifiedQuality, miner.QualityForWeight(size, duration, halfWeight)) + + // test against old form that takes a dealWeight argument + require.Equal(t, emptyQuality, v14miner.QualityForWeight(size, duration, big.Zero(), big.Zero())) + require.Equal(t, emptyQuality, v14miner.QualityForWeight(size, duration, halfWeight, big.Zero())) + require.Equal(t, emptyQuality, v14miner.QualityForWeight(size, duration, fullWeight, big.Zero())) + require.Equal(t, verifiedQuality, v14miner.QualityForWeight(size, duration, big.Zero(), fullWeight)) + require.Equal(t, verifiedQuality, v14miner.QualityForWeight(size, duration, fullWeight, fullWeight)) + require.Equal(t, halfVerifiedQuality, v14miner.QualityForWeight(size, duration, big.Zero(), halfWeight)) + require.Equal(t, halfVerifiedQuality, v14miner.QualityForWeight(size, duration, halfWeight, halfWeight)) + } + } +} + +// matches builtin-actors/actors/miner/tests/policy_test.rs +func TestDailyProofFeeCalc(t *testing.T) { + // Given a CS of 680M FIL, 32GiB QAP, a fee multiplier of 7.4e-15 per 32GiB QAP, the daily proof + // fee should be 5032 nanoFIL. + // 680M * 7.4e-15 = 0.000005032 FIL + // 0.000005032 * 1e9 = 5032 nanoFIL + // 0.000005032 * 1e18 = 5032000000000 attoFIL + // As a per-byte multiplier we use 2.1536e-25, a close approximation of 7.4e-15 / 32GiB. + // 680M * 32GiB * 2.1536e-25 = 0.000005031805013354 FIL + // 0.000005031805013354 * 1e18 = 5031805013354 attoFIL + circulatingSupply := big.Mul(big.NewInt(680_000_000), builtin.TokenPrecision) + ref32GibFee := big.NewInt(3780793052776) + + for _, tc := range []struct { + size uint64 + expected big.Int + }{ + {32, ref32GibFee}, + {64, big.Mul(ref32GibFee, big.NewInt(2))}, + {32 * 10, big.Mul(ref32GibFee, big.NewInt(10))}, + {32 * 5, big.Mul(ref32GibFee, big.NewInt(5))}, + {64 * 10, big.Mul(ref32GibFee, big.NewInt(20))}, + } { + power := big.NewInt(int64(tc.size << 30)) // 32GiB raw QAP + fee := miner.DailyProofFee(circulatingSupply, power) + delta := big.Sub(fee, tc.expected).Abs() + require.LessOrEqual(t, delta.Uint64(), uint64(10), + "size: %s, fee: %s, expected_fee: %s (±10)", tc.size, fee, tc.expected) + } +} diff --git a/builtin/v18/miner/unmarshall_test.go b/builtin/v18/miner/unmarshall_test.go new file mode 100644 index 00000000..1bca47ba --- /dev/null +++ b/builtin/v18/miner/unmarshall_test.go @@ -0,0 +1,42 @@ +package miner + +import ( + "bytes" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/big" +) + +func TestCborVestingFundsTail(t *testing.T) { + var vf = VestingFundsTail{ + Funds: []VestingFund{ + { + Epoch: 1, + Amount: big.NewInt(3), + }, + { + Epoch: 2, + Amount: big.NewInt(4), + }, + }, + } + buf := new(bytes.Buffer) + err := vf.MarshalCBOR(buf) + require.NoError(t, err) + + // This encodes as a bare CBOR list (no wrapping struct). + b := []byte{130, 130, 1, 66, 0, 3, 130, 2, 66, 0, 4} + + require.Equal(t, b, buf.Bytes()) + + var vf2 VestingFundsTail + err = vf2.UnmarshalCBOR(bytes.NewReader(b)) + require.NoError(t, err) + require.Equal(t, abi.ChainEpoch(1), vf2.Funds[0].Epoch) + require.Equal(t, abi.ChainEpoch(2), vf2.Funds[1].Epoch) + require.Equal(t, big.NewInt(3), vf2.Funds[0].Amount) + require.Equal(t, big.NewInt(4), vf2.Funds[1].Amount) +} diff --git a/builtin/v18/multisig/cbor_gen.go b/builtin/v18/multisig/cbor_gen.go new file mode 100644 index 00000000..c9a552a1 --- /dev/null +++ b/builtin/v18/multisig/cbor_gen.go @@ -0,0 +1,1749 @@ +// Code generated by github.com/whyrusleeping/cbor-gen. DO NOT EDIT. + +package multisig + +import ( + "fmt" + "io" + "math" + "sort" + + 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" +) + +var _ = xerrors.Errorf +var _ = cid.Undef +var _ = math.E +var _ = sort.Sort + +var lengthBufState = []byte{135} + +func (t *State) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufState); err != nil { + return err + } + + // t.Signers ([]address.Address) (slice) + if len(t.Signers) > 8192 { + return xerrors.Errorf("Slice value in field t.Signers was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Signers))); err != nil { + return err + } + for _, v := range t.Signers { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + + // t.NumApprovalsThreshold (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.NumApprovalsThreshold)); err != nil { + return err + } + + // t.NextTxnID (multisig.TxnID) (int64) + if t.NextTxnID >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.NextTxnID)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.NextTxnID-1)); err != nil { + return err + } + } + + // t.InitialBalance (big.Int) (struct) + if err := t.InitialBalance.MarshalCBOR(cw); err != nil { + return err + } + + // t.StartEpoch (abi.ChainEpoch) (int64) + if t.StartEpoch >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.StartEpoch)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.StartEpoch-1)); err != nil { + return err + } + } + + // t.UnlockDuration (abi.ChainEpoch) (int64) + if t.UnlockDuration >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.UnlockDuration)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.UnlockDuration-1)); err != nil { + return err + } + } + + // t.PendingTxns (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.PendingTxns); err != nil { + return xerrors.Errorf("failed to write cid field t.PendingTxns: %w", err) + } + + return nil +} + +func (t *State) UnmarshalCBOR(r io.Reader) (err error) { + *t = State{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 7 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Signers ([]address.Address) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Signers: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Signers = make([]address.Address, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Signers[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Signers[i]: %w", err) + } + + } + + } + } + // t.NumApprovalsThreshold (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.NumApprovalsThreshold = uint64(extra) + + } + // t.NextTxnID (multisig.TxnID) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.NextTxnID = TxnID(extraI) + } + // t.InitialBalance (big.Int) (struct) + + { + + if err := t.InitialBalance.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.InitialBalance: %w", err) + } + + } + // t.StartEpoch (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.StartEpoch = abi.ChainEpoch(extraI) + } + // t.UnlockDuration (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.UnlockDuration = abi.ChainEpoch(extraI) + } + // t.PendingTxns (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.PendingTxns: %w", err) + } + + t.PendingTxns = c + + } + return nil +} + +var lengthBufTransaction = []byte{133} + +func (t *Transaction) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufTransaction); err != nil { + return err + } + + // t.To (address.Address) (struct) + if err := t.To.MarshalCBOR(cw); err != nil { + return err + } + + // t.Value (big.Int) (struct) + if err := t.Value.MarshalCBOR(cw); err != nil { + return err + } + + // t.Method (abi.MethodNum) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Method)); err != nil { + return err + } + + // t.Params ([]uint8) (slice) + if len(t.Params) > 2097152 { + return xerrors.Errorf("Byte array in field t.Params was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.Params))); err != nil { + return err + } + + if _, err := cw.Write(t.Params); err != nil { + return err + } + + // t.Approved ([]address.Address) (slice) + if len(t.Approved) > 8192 { + return xerrors.Errorf("Slice value in field t.Approved was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Approved))); err != nil { + return err + } + for _, v := range t.Approved { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *Transaction) UnmarshalCBOR(r io.Reader) (err error) { + *t = Transaction{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 5 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.To (address.Address) (struct) + + { + + if err := t.To.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.To: %w", err) + } + + } + // t.Value (big.Int) (struct) + + { + + if err := t.Value.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Value: %w", err) + } + + } + // t.Method (abi.MethodNum) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Method = abi.MethodNum(extra) + + } + // t.Params ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.Params: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.Params = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.Params); err != nil { + return err + } + + // t.Approved ([]address.Address) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Approved: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Approved = make([]address.Address, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Approved[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Approved[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufProposalHashData = []byte{133} + +func (t *ProposalHashData) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufProposalHashData); err != nil { + return err + } + + // t.Requester (address.Address) (struct) + if err := t.Requester.MarshalCBOR(cw); err != nil { + return err + } + + // t.To (address.Address) (struct) + if err := t.To.MarshalCBOR(cw); err != nil { + return err + } + + // t.Value (big.Int) (struct) + if err := t.Value.MarshalCBOR(cw); err != nil { + return err + } + + // t.Method (abi.MethodNum) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Method)); err != nil { + return err + } + + // t.Params ([]uint8) (slice) + if len(t.Params) > 2097152 { + return xerrors.Errorf("Byte array in field t.Params was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.Params))); err != nil { + return err + } + + if _, err := cw.Write(t.Params); err != nil { + return err + } + + return nil +} + +func (t *ProposalHashData) UnmarshalCBOR(r io.Reader) (err error) { + *t = ProposalHashData{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 5 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Requester (address.Address) (struct) + + { + + if err := t.Requester.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Requester: %w", err) + } + + } + // t.To (address.Address) (struct) + + { + + if err := t.To.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.To: %w", err) + } + + } + // t.Value (big.Int) (struct) + + { + + if err := t.Value.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Value: %w", err) + } + + } + // t.Method (abi.MethodNum) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Method = abi.MethodNum(extra) + + } + // t.Params ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.Params: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.Params = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.Params); err != nil { + return err + } + + return nil +} + +var lengthBufConstructorParams = []byte{132} + +func (t *ConstructorParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufConstructorParams); err != nil { + return err + } + + // t.Signers ([]address.Address) (slice) + if len(t.Signers) > 8192 { + return xerrors.Errorf("Slice value in field t.Signers was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Signers))); err != nil { + return err + } + for _, v := range t.Signers { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + + // t.NumApprovalsThreshold (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.NumApprovalsThreshold)); err != nil { + return err + } + + // t.UnlockDuration (abi.ChainEpoch) (int64) + if t.UnlockDuration >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.UnlockDuration)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.UnlockDuration-1)); err != nil { + return err + } + } + + // t.StartEpoch (abi.ChainEpoch) (int64) + if t.StartEpoch >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.StartEpoch)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.StartEpoch-1)); err != nil { + return err + } + } + + return nil +} + +func (t *ConstructorParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = ConstructorParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 4 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Signers ([]address.Address) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Signers: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Signers = make([]address.Address, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Signers[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Signers[i]: %w", err) + } + + } + + } + } + // t.NumApprovalsThreshold (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.NumApprovalsThreshold = uint64(extra) + + } + // t.UnlockDuration (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.UnlockDuration = abi.ChainEpoch(extraI) + } + // t.StartEpoch (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.StartEpoch = abi.ChainEpoch(extraI) + } + return nil +} + +var lengthBufProposeParams = []byte{132} + +func (t *ProposeParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufProposeParams); err != nil { + return err + } + + // t.To (address.Address) (struct) + if err := t.To.MarshalCBOR(cw); err != nil { + return err + } + + // t.Value (big.Int) (struct) + if err := t.Value.MarshalCBOR(cw); err != nil { + return err + } + + // t.Method (abi.MethodNum) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Method)); err != nil { + return err + } + + // t.Params ([]uint8) (slice) + if len(t.Params) > 2097152 { + return xerrors.Errorf("Byte array in field t.Params was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.Params))); err != nil { + return err + } + + if _, err := cw.Write(t.Params); err != nil { + return err + } + + return nil +} + +func (t *ProposeParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = ProposeParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 4 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.To (address.Address) (struct) + + { + + if err := t.To.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.To: %w", err) + } + + } + // t.Value (big.Int) (struct) + + { + + if err := t.Value.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Value: %w", err) + } + + } + // t.Method (abi.MethodNum) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Method = abi.MethodNum(extra) + + } + // t.Params ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.Params: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.Params = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.Params); err != nil { + return err + } + + return nil +} + +var lengthBufProposeReturn = []byte{132} + +func (t *ProposeReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufProposeReturn); err != nil { + return err + } + + // t.TxnID (multisig.TxnID) (int64) + if t.TxnID >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.TxnID)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.TxnID-1)); err != nil { + return err + } + } + + // t.Applied (bool) (bool) + if err := cbg.WriteBool(w, t.Applied); err != nil { + return err + } + + // t.Code (exitcode.ExitCode) (int64) + if t.Code >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Code)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.Code-1)); err != nil { + return err + } + } + + // t.Ret ([]uint8) (slice) + if len(t.Ret) > 2097152 { + return xerrors.Errorf("Byte array in field t.Ret was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.Ret))); err != nil { + return err + } + + if _, err := cw.Write(t.Ret); err != nil { + return err + } + + return nil +} + +func (t *ProposeReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = ProposeReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 4 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.TxnID (multisig.TxnID) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.TxnID = TxnID(extraI) + } + // t.Applied (bool) (bool) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajOther { + return fmt.Errorf("booleans must be major type 7") + } + switch extra { + case 20: + t.Applied = false + case 21: + t.Applied = true + default: + return fmt.Errorf("booleans are either major type 7, value 20 or 21 (got %d)", extra) + } + // t.Code (exitcode.ExitCode) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.Code = exitcode.ExitCode(extraI) + } + // t.Ret ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.Ret: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.Ret = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.Ret); err != nil { + return err + } + + return nil +} + +var lengthBufAddSignerParams = []byte{130} + +func (t *AddSignerParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufAddSignerParams); err != nil { + return err + } + + // t.Signer (address.Address) (struct) + if err := t.Signer.MarshalCBOR(cw); err != nil { + return err + } + + // t.Increase (bool) (bool) + if err := cbg.WriteBool(w, t.Increase); err != nil { + return err + } + return nil +} + +func (t *AddSignerParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = AddSignerParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Signer (address.Address) (struct) + + { + + if err := t.Signer.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Signer: %w", err) + } + + } + // t.Increase (bool) (bool) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajOther { + return fmt.Errorf("booleans must be major type 7") + } + switch extra { + case 20: + t.Increase = false + case 21: + t.Increase = true + default: + return fmt.Errorf("booleans are either major type 7, value 20 or 21 (got %d)", extra) + } + return nil +} + +var lengthBufRemoveSignerParams = []byte{130} + +func (t *RemoveSignerParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufRemoveSignerParams); err != nil { + return err + } + + // t.Signer (address.Address) (struct) + if err := t.Signer.MarshalCBOR(cw); err != nil { + return err + } + + // t.Decrease (bool) (bool) + if err := cbg.WriteBool(w, t.Decrease); err != nil { + return err + } + return nil +} + +func (t *RemoveSignerParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = RemoveSignerParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Signer (address.Address) (struct) + + { + + if err := t.Signer.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Signer: %w", err) + } + + } + // t.Decrease (bool) (bool) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajOther { + return fmt.Errorf("booleans must be major type 7") + } + switch extra { + case 20: + t.Decrease = false + case 21: + t.Decrease = true + default: + return fmt.Errorf("booleans are either major type 7, value 20 or 21 (got %d)", extra) + } + return nil +} + +var lengthBufTxnIDParams = []byte{130} + +func (t *TxnIDParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufTxnIDParams); err != nil { + return err + } + + // t.ID (multisig.TxnID) (int64) + if t.ID >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.ID)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.ID-1)); err != nil { + return err + } + } + + // t.ProposalHash ([]uint8) (slice) + if len(t.ProposalHash) > 2097152 { + return xerrors.Errorf("Byte array in field t.ProposalHash was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.ProposalHash))); err != nil { + return err + } + + if _, err := cw.Write(t.ProposalHash); err != nil { + return err + } + + return nil +} + +func (t *TxnIDParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = TxnIDParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.ID (multisig.TxnID) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.ID = TxnID(extraI) + } + // t.ProposalHash ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.ProposalHash: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.ProposalHash = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.ProposalHash); err != nil { + return err + } + + return nil +} + +var lengthBufApproveReturn = []byte{131} + +func (t *ApproveReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufApproveReturn); err != nil { + return err + } + + // t.Applied (bool) (bool) + if err := cbg.WriteBool(w, t.Applied); err != nil { + return err + } + + // t.Code (exitcode.ExitCode) (int64) + if t.Code >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Code)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.Code-1)); err != nil { + return err + } + } + + // t.Ret ([]uint8) (slice) + if len(t.Ret) > 2097152 { + return xerrors.Errorf("Byte array in field t.Ret was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.Ret))); err != nil { + return err + } + + if _, err := cw.Write(t.Ret); err != nil { + return err + } + + return nil +} + +func (t *ApproveReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = ApproveReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.Applied (bool) (bool) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajOther { + return fmt.Errorf("booleans must be major type 7") + } + switch extra { + case 20: + t.Applied = false + case 21: + t.Applied = true + default: + return fmt.Errorf("booleans are either major type 7, value 20 or 21 (got %d)", extra) + } + // t.Code (exitcode.ExitCode) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.Code = exitcode.ExitCode(extraI) + } + // t.Ret ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.Ret: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.Ret = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.Ret); err != nil { + return err + } + + return nil +} + +var lengthBufChangeNumApprovalsThresholdParams = []byte{129} + +func (t *ChangeNumApprovalsThresholdParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufChangeNumApprovalsThresholdParams); err != nil { + return err + } + + // t.NewThreshold (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.NewThreshold)); err != nil { + return err + } + + return nil +} + +func (t *ChangeNumApprovalsThresholdParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = ChangeNumApprovalsThresholdParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.NewThreshold (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.NewThreshold = uint64(extra) + + } + return nil +} + +var lengthBufSwapSignerParams = []byte{130} + +func (t *SwapSignerParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufSwapSignerParams); err != nil { + return err + } + + // t.From (address.Address) (struct) + if err := t.From.MarshalCBOR(cw); err != nil { + return err + } + + // t.To (address.Address) (struct) + if err := t.To.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *SwapSignerParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = SwapSignerParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.From (address.Address) (struct) + + { + + if err := t.From.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.From: %w", err) + } + + } + // t.To (address.Address) (struct) + + { + + if err := t.To.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.To: %w", err) + } + + } + return nil +} + +var lengthBufLockBalanceParams = []byte{131} + +func (t *LockBalanceParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufLockBalanceParams); err != nil { + return err + } + + // t.StartEpoch (abi.ChainEpoch) (int64) + if t.StartEpoch >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.StartEpoch)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.StartEpoch-1)); err != nil { + return err + } + } + + // t.UnlockDuration (abi.ChainEpoch) (int64) + if t.UnlockDuration >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.UnlockDuration)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.UnlockDuration-1)); err != nil { + return err + } + } + + // t.Amount (big.Int) (struct) + if err := t.Amount.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *LockBalanceParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = LockBalanceParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.StartEpoch (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.StartEpoch = abi.ChainEpoch(extraI) + } + // t.UnlockDuration (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.UnlockDuration = abi.ChainEpoch(extraI) + } + // t.Amount (big.Int) (struct) + + { + + if err := t.Amount.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Amount: %w", err) + } + + } + return nil +} diff --git a/builtin/v18/multisig/invariants.go b/builtin/v18/multisig/invariants.go new file mode 100644 index 00000000..d03544f7 --- /dev/null +++ b/builtin/v18/multisig/invariants.go @@ -0,0 +1,82 @@ +package multisig + +import ( + "bytes" + "encoding/binary" + + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/builtin" + "github.com/filecoin-project/go-state-types/builtin/v18/util/adt" +) + +type StateSummary struct { + PendingTxnCount uint64 + NumApprovalsThreshold uint64 + SignerCount int +} + +// Checks internal invariants of multisig state. +func CheckStateInvariants(st *State, store adt.Store) (*StateSummary, *builtin.MessageAccumulator) { + acc := &builtin.MessageAccumulator{} + + // assert invariants involving signers + acc.Require(len(st.Signers) <= SignersMax, "multisig has too many signers: %d", len(st.Signers)) + acc.Require(uint64(len(st.Signers)) >= st.NumApprovalsThreshold, + "multisig has insufficient signers to meet threshold (%d < %d)", len(st.Signers), st.NumApprovalsThreshold) + + if st.UnlockDuration == 0 { // See https://github.com/filecoin-project/specs-actors/issues/1185 + acc.Require(st.StartEpoch == 0, "non-zero start epoch %d with zero unlock duration", st.StartEpoch) + acc.Require(st.InitialBalance.IsZero(), "non-zero locked balance %v with zero unlock duration", st.InitialBalance) + } + + // create lookup to test transaction approvals are multisig signers. + signers := make(map[address.Address]struct{}) + for _, a := range st.Signers { + signers[a] = struct{}{} + } + + // test pending transactions + maxTxnID := TxnID(-1) + numPending := uint64(0) + if transactions, err := adt.AsMap(store, st.PendingTxns, builtin.DefaultHamtBitwidth); err != nil { + acc.Addf("error loading transactions: %v", err) + } else { + var txn Transaction + err = transactions.ForEach(&txn, func(txnIDStr string) error { + txnID, err := ParseTxnIDKey(txnIDStr) + if err != nil { + return err + } + if txnID > maxTxnID { + maxTxnID = txnID + } + + seenApprovals := make(map[address.Address]struct{}) + for _, approval := range txn.Approved { + _, found := signers[approval] + acc.Require(found, "approval %v for transaction %d is not in signers list", approval, txnID) + + _, seen := seenApprovals[approval] + acc.Require(!seen, "duplicate approval %v for transaction %d", approval, txnID) + + seenApprovals[approval] = struct{}{} + } + + numPending++ + return nil + }) + acc.RequireNoError(err, "error iterating transactions") + } + + acc.Require(st.NextTxnID > maxTxnID, "next transaction id %d is not greater than pending ids", st.NextTxnID) + return &StateSummary{ + PendingTxnCount: numPending, + NumApprovalsThreshold: st.NumApprovalsThreshold, + SignerCount: len(st.Signers), + }, acc +} + +func ParseTxnIDKey(key string) (TxnID, error) { + id, err := binary.ReadVarint(bytes.NewReader([]byte(key))) + return TxnID(id), err +} diff --git a/builtin/v18/multisig/methods.go b/builtin/v18/multisig/methods.go new file mode 100644 index 00000000..3970193a --- /dev/null +++ b/builtin/v18/multisig/methods.go @@ -0,0 +1,27 @@ +package multisig + +import ( + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/builtin" +) + +var Methods = map[abi.MethodNum]builtin.MethodMeta{ + 1: builtin.NewMethodMeta("Constructor", *new(func(*ConstructorParams) *abi.EmptyValue)), // Constructor + 2: builtin.NewMethodMeta("Propose", *new(func(*ProposeParams) *ProposeReturn)), // Propose + builtin.MustGenerateFRCMethodNum("Propose"): builtin.NewMethodMeta("ProposeExported", *new(func(*ProposeParams) *ProposeReturn)), // ProposeExported + 3: builtin.NewMethodMeta("Approve", *new(func(*TxnIDParams) *ApproveReturn)), // Approve + builtin.MustGenerateFRCMethodNum("Approve"): builtin.NewMethodMeta("ApproveExported", *new(func(*TxnIDParams) *ApproveReturn)), // ApproveExported + 4: builtin.NewMethodMeta("Cancel", *new(func(*TxnIDParams) *abi.EmptyValue)), // Cancel + builtin.MustGenerateFRCMethodNum("Cancel"): builtin.NewMethodMeta("CancelExported", *new(func(*TxnIDParams) *abi.EmptyValue)), // CancelExported + 5: builtin.NewMethodMeta("AddSigner", *new(func(*AddSignerParams) *abi.EmptyValue)), // AddSigner + builtin.MustGenerateFRCMethodNum("AddSigner"): builtin.NewMethodMeta("AddSignerExported", *new(func(*AddSignerParams) *abi.EmptyValue)), // AddSignerExported + 6: builtin.NewMethodMeta("RemoveSigner", *new(func(*RemoveSignerParams) *abi.EmptyValue)), // RemoveSigner + builtin.MustGenerateFRCMethodNum("RemoveSigner"): builtin.NewMethodMeta("RemoveSignerExported", *new(func(*RemoveSignerParams) *abi.EmptyValue)), // RemoveSignerExported + 7: builtin.NewMethodMeta("SwapSigner", *new(func(*SwapSignerParams) *abi.EmptyValue)), // SwapSigner + builtin.MustGenerateFRCMethodNum("SwapSigner"): builtin.NewMethodMeta("SwapSignerExported", *new(func(*SwapSignerParams) *abi.EmptyValue)), // SwapSignerExported + 8: builtin.NewMethodMeta("ChangeNumApprovalsThreshold", *new(func(*ChangeNumApprovalsThresholdParams) *abi.EmptyValue)), // ChangeNumApprovalsThreshold + builtin.MustGenerateFRCMethodNum("ChangeNumApprovalsThreshold"): builtin.NewMethodMeta("ChangeNumApprovalsThresholdExported", *new(func(*ChangeNumApprovalsThresholdParams) *abi.EmptyValue)), // ChangeNumApprovalsThresholdExported + 9: builtin.NewMethodMeta("LockBalance", *new(func(*LockBalanceParams) *abi.EmptyValue)), // LockBalance + builtin.MustGenerateFRCMethodNum("LockBalance"): builtin.NewMethodMeta("LockBalanceExported", *new(func(*LockBalanceParams) *abi.EmptyValue)), // LockBalanceExported + builtin.MustGenerateFRCMethodNum("Receive"): builtin.NewMethodMeta("UniversalReceiverHook", *new(func(*abi.CborBytesTransparent) *abi.EmptyValue)), // UniversalReceiverHook +} diff --git a/builtin/v18/multisig/multisig_state.go b/builtin/v18/multisig/multisig_state.go new file mode 100644 index 00000000..5a3f87aa --- /dev/null +++ b/builtin/v18/multisig/multisig_state.go @@ -0,0 +1,46 @@ +package multisig + +import ( + "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" +) + +type State struct { + Signers []address.Address // Signers must be canonical ID-addresses. + NumApprovalsThreshold uint64 + NextTxnID TxnID + + // Linear unlock + InitialBalance abi.TokenAmount + StartEpoch abi.ChainEpoch + UnlockDuration abi.ChainEpoch + + PendingTxns cid.Cid // HAMT[TxnID]Transaction +} + +func (st *State) AmountLocked(elapsedEpoch abi.ChainEpoch) abi.TokenAmount { + if elapsedEpoch >= st.UnlockDuration { + return abi.NewTokenAmount(0) + } + if elapsedEpoch <= 0 { + return st.InitialBalance + } + + unlockDuration := big.NewInt(int64(st.UnlockDuration)) + remainingLockDuration := big.Sub(unlockDuration, big.NewInt(int64(elapsedEpoch))) + + // locked = ceil(InitialBalance * remainingLockDuration / UnlockDuration) + numerator := big.Mul(st.InitialBalance, remainingLockDuration) + denominator := unlockDuration + quot := big.Div(numerator, denominator) + rem := big.Mod(numerator, denominator) + + locked := quot + if !rem.IsZero() { + locked = big.Add(locked, big.NewInt(1)) + } + return locked +} diff --git a/builtin/v18/multisig/multisig_types.go b/builtin/v18/multisig/multisig_types.go new file mode 100644 index 00000000..c5616291 --- /dev/null +++ b/builtin/v18/multisig/multisig_types.go @@ -0,0 +1,109 @@ +package multisig + +import ( + "bytes" + + addr "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/exitcode" +) + +type TxnID int64 + +type Transaction struct { + To addr.Address + Value abi.TokenAmount + Method abi.MethodNum + Params []byte + + // This address at index 0 is the transaction proposer, order of this slice must be preserved. + Approved []addr.Address +} + +// Data for a BLAKE2B-256 to be attached to methods referencing proposals via TXIDs. +// Ensures the existence of a cryptographic reference to the original proposal. Useful +// for offline signers and for protection when reorgs change a multisig TXID. +// +// Requester - The requesting multisig wallet member. +// All other fields - From the "Transaction" struct. +type ProposalHashData struct { + Requester addr.Address + To addr.Address + Value abi.TokenAmount + Method abi.MethodNum + Params []byte +} + +type ConstructorParams struct { + Signers []addr.Address + NumApprovalsThreshold uint64 + UnlockDuration abi.ChainEpoch + StartEpoch abi.ChainEpoch +} + +type ProposeParams struct { + To addr.Address + Value abi.TokenAmount + Method abi.MethodNum + Params []byte +} + +type ProposeReturn struct { + // TxnID is the ID of the proposed transaction + TxnID TxnID + // Applied indicates if the transaction was applied as opposed to proposed but not applied due to lack of approvals + Applied bool + // Code is the exitcode of the transaction, if Applied is false this field should be ignored. + Code exitcode.ExitCode + // Ret is the return vale of the transaction, if Applied is false this field should be ignored. + Ret []byte +} + +type TxnIDParams struct { + ID TxnID + // Optional hash of proposal to ensure an operation can only apply to a + // specific proposal. + ProposalHash []byte +} + +type ApproveReturn struct { + // Applied indicates if the transaction was applied as opposed to proposed but not applied due to lack of approvals + Applied bool + // Code is the exitcode of the transaction, if Applied is false this field should be ignored. + Code exitcode.ExitCode + // Ret is the return vale of the transaction, if Applied is false this field should be ignored. + Ret []byte +} + +type AddSignerParams struct { + Signer addr.Address + Increase bool +} + +type RemoveSignerParams struct { + Signer addr.Address + Decrease bool +} + +type SwapSignerParams struct { + From addr.Address + To addr.Address +} + +type ChangeNumApprovalsThresholdParams struct { + NewThreshold uint64 +} + +type LockBalanceParams struct { + StartEpoch abi.ChainEpoch + UnlockDuration abi.ChainEpoch + Amount abi.TokenAmount +} + +func (phd *ProposalHashData) Serialize() ([]byte, error) { + buf := new(bytes.Buffer) + if err := phd.MarshalCBOR(buf); err != nil { + return nil, err + } + return buf.Bytes(), nil +} diff --git a/builtin/v18/multisig/policy.go b/builtin/v18/multisig/policy.go new file mode 100644 index 00000000..537c0ea6 --- /dev/null +++ b/builtin/v18/multisig/policy.go @@ -0,0 +1,5 @@ +package multisig + +// SignersMax is the maximum number of signers allowed in a multisig. If more +// are required, please use a combining tree of multisigs. +const SignersMax = 256 diff --git a/builtin/v18/paych/cbor_gen.go b/builtin/v18/paych/cbor_gen.go new file mode 100644 index 00000000..1bff11b5 --- /dev/null +++ b/builtin/v18/paych/cbor_gen.go @@ -0,0 +1,984 @@ +// Code generated by github.com/whyrusleeping/cbor-gen. DO NOT EDIT. + +package paych + +import ( + "fmt" + "io" + "math" + "sort" + + abi "github.com/filecoin-project/go-state-types/abi" + crypto "github.com/filecoin-project/go-state-types/crypto" + cid "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" + xerrors "golang.org/x/xerrors" +) + +var _ = xerrors.Errorf +var _ = cid.Undef +var _ = math.E +var _ = sort.Sort + +var lengthBufState = []byte{134} + +func (t *State) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufState); err != nil { + return err + } + + // t.From (address.Address) (struct) + if err := t.From.MarshalCBOR(cw); err != nil { + return err + } + + // t.To (address.Address) (struct) + if err := t.To.MarshalCBOR(cw); err != nil { + return err + } + + // t.ToSend (big.Int) (struct) + if err := t.ToSend.MarshalCBOR(cw); err != nil { + return err + } + + // t.SettlingAt (abi.ChainEpoch) (int64) + if t.SettlingAt >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SettlingAt)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.SettlingAt-1)); err != nil { + return err + } + } + + // t.MinSettleHeight (abi.ChainEpoch) (int64) + if t.MinSettleHeight >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.MinSettleHeight)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.MinSettleHeight-1)); err != nil { + return err + } + } + + // t.LaneStates (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.LaneStates); err != nil { + return xerrors.Errorf("failed to write cid field t.LaneStates: %w", err) + } + + return nil +} + +func (t *State) UnmarshalCBOR(r io.Reader) (err error) { + *t = State{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 6 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.From (address.Address) (struct) + + { + + if err := t.From.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.From: %w", err) + } + + } + // t.To (address.Address) (struct) + + { + + if err := t.To.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.To: %w", err) + } + + } + // t.ToSend (big.Int) (struct) + + { + + if err := t.ToSend.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ToSend: %w", err) + } + + } + // t.SettlingAt (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.SettlingAt = abi.ChainEpoch(extraI) + } + // t.MinSettleHeight (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.MinSettleHeight = abi.ChainEpoch(extraI) + } + // t.LaneStates (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.LaneStates: %w", err) + } + + t.LaneStates = c + + } + return nil +} + +var lengthBufLaneState = []byte{130} + +func (t *LaneState) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufLaneState); err != nil { + return err + } + + // t.Redeemed (big.Int) (struct) + if err := t.Redeemed.MarshalCBOR(cw); err != nil { + return err + } + + // t.Nonce (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Nonce)); err != nil { + return err + } + + return nil +} + +func (t *LaneState) UnmarshalCBOR(r io.Reader) (err error) { + *t = LaneState{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Redeemed (big.Int) (struct) + + { + + if err := t.Redeemed.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Redeemed: %w", err) + } + + } + // t.Nonce (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Nonce = uint64(extra) + + } + return nil +} + +var lengthBufConstructorParams = []byte{130} + +func (t *ConstructorParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufConstructorParams); err != nil { + return err + } + + // t.From (address.Address) (struct) + if err := t.From.MarshalCBOR(cw); err != nil { + return err + } + + // t.To (address.Address) (struct) + if err := t.To.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *ConstructorParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = ConstructorParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.From (address.Address) (struct) + + { + + if err := t.From.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.From: %w", err) + } + + } + // t.To (address.Address) (struct) + + { + + if err := t.To.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.To: %w", err) + } + + } + return nil +} + +var lengthBufUpdateChannelStateParams = []byte{130} + +func (t *UpdateChannelStateParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufUpdateChannelStateParams); err != nil { + return err + } + + // t.Sv (paych.SignedVoucher) (struct) + if err := t.Sv.MarshalCBOR(cw); err != nil { + return err + } + + // t.Secret ([]uint8) (slice) + if len(t.Secret) > 2097152 { + return xerrors.Errorf("Byte array in field t.Secret was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.Secret))); err != nil { + return err + } + + if _, err := cw.Write(t.Secret); err != nil { + return err + } + + return nil +} + +func (t *UpdateChannelStateParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = UpdateChannelStateParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Sv (paych.SignedVoucher) (struct) + + { + + if err := t.Sv.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Sv: %w", err) + } + + } + // t.Secret ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.Secret: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.Secret = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.Secret); err != nil { + return err + } + + return nil +} + +var lengthBufSignedVoucher = []byte{139} + +func (t *SignedVoucher) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufSignedVoucher); err != nil { + return err + } + + // t.ChannelAddr (address.Address) (struct) + if err := t.ChannelAddr.MarshalCBOR(cw); err != nil { + return err + } + + // t.TimeLockMin (abi.ChainEpoch) (int64) + if t.TimeLockMin >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.TimeLockMin)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.TimeLockMin-1)); err != nil { + return err + } + } + + // t.TimeLockMax (abi.ChainEpoch) (int64) + if t.TimeLockMax >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.TimeLockMax)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.TimeLockMax-1)); err != nil { + return err + } + } + + // t.SecretHash ([]uint8) (slice) + if len(t.SecretHash) > 2097152 { + return xerrors.Errorf("Byte array in field t.SecretHash was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.SecretHash))); err != nil { + return err + } + + if _, err := cw.Write(t.SecretHash); err != nil { + return err + } + + // t.Extra (paych.ModVerifyParams) (struct) + if err := t.Extra.MarshalCBOR(cw); err != nil { + return err + } + + // t.Lane (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Lane)); err != nil { + return err + } + + // t.Nonce (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Nonce)); err != nil { + return err + } + + // t.Amount (big.Int) (struct) + if err := t.Amount.MarshalCBOR(cw); err != nil { + return err + } + + // t.MinSettleHeight (abi.ChainEpoch) (int64) + if t.MinSettleHeight >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.MinSettleHeight)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.MinSettleHeight-1)); err != nil { + return err + } + } + + // t.Merges ([]paych.Merge) (slice) + if len(t.Merges) > 8192 { + return xerrors.Errorf("Slice value in field t.Merges was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Merges))); err != nil { + return err + } + for _, v := range t.Merges { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + + // t.Signature (crypto.Signature) (struct) + if err := t.Signature.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *SignedVoucher) UnmarshalCBOR(r io.Reader) (err error) { + *t = SignedVoucher{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.ChannelAddr (address.Address) (struct) + + { + + if err := t.ChannelAddr.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ChannelAddr: %w", err) + } + + } + // t.TimeLockMin (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.TimeLockMin = abi.ChainEpoch(extraI) + } + // t.TimeLockMax (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.TimeLockMax = abi.ChainEpoch(extraI) + } + // t.SecretHash ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.SecretHash: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.SecretHash = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.SecretHash); err != nil { + return err + } + + // t.Extra (paych.ModVerifyParams) (struct) + + { + + b, err := cr.ReadByte() + if err != nil { + return err + } + if b != cbg.CborNull[0] { + if err := cr.UnreadByte(); err != nil { + return err + } + t.Extra = new(ModVerifyParams) + if err := t.Extra.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Extra pointer: %w", err) + } + } + + } + // t.Lane (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Lane = uint64(extra) + + } + // t.Nonce (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Nonce = uint64(extra) + + } + // t.Amount (big.Int) (struct) + + { + + if err := t.Amount.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Amount: %w", err) + } + + } + // t.MinSettleHeight (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.MinSettleHeight = abi.ChainEpoch(extraI) + } + // t.Merges ([]paych.Merge) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Merges: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Merges = make([]Merge, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Merges[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Merges[i]: %w", err) + } + + } + + } + } + // t.Signature (crypto.Signature) (struct) + + { + + b, err := cr.ReadByte() + if err != nil { + return err + } + if b != cbg.CborNull[0] { + if err := cr.UnreadByte(); err != nil { + return err + } + t.Signature = new(crypto.Signature) + if err := t.Signature.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Signature pointer: %w", err) + } + } + + } + return nil +} + +var lengthBufModVerifyParams = []byte{131} + +func (t *ModVerifyParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufModVerifyParams); err != nil { + return err + } + + // t.Actor (address.Address) (struct) + if err := t.Actor.MarshalCBOR(cw); err != nil { + return err + } + + // t.Method (abi.MethodNum) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Method)); err != nil { + return err + } + + // t.Data ([]uint8) (slice) + if len(t.Data) > 2097152 { + return xerrors.Errorf("Byte array in field t.Data was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.Data))); err != nil { + return err + } + + if _, err := cw.Write(t.Data); err != nil { + return err + } + + return nil +} + +func (t *ModVerifyParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = ModVerifyParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.Actor (address.Address) (struct) + + { + + if err := t.Actor.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Actor: %w", err) + } + + } + // t.Method (abi.MethodNum) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Method = abi.MethodNum(extra) + + } + // t.Data ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.Data: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.Data = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.Data); err != nil { + return err + } + + return nil +} + +var lengthBufMerge = []byte{130} + +func (t *Merge) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufMerge); err != nil { + return err + } + + // t.Lane (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Lane)); err != nil { + return err + } + + // t.Nonce (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Nonce)); err != nil { + return err + } + + return nil +} + +func (t *Merge) UnmarshalCBOR(r io.Reader) (err error) { + *t = Merge{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Lane (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Lane = uint64(extra) + + } + // t.Nonce (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Nonce = uint64(extra) + + } + return nil +} diff --git a/builtin/v18/paych/invariants.go b/builtin/v18/paych/invariants.go new file mode 100644 index 00000000..2a3324e6 --- /dev/null +++ b/builtin/v18/paych/invariants.go @@ -0,0 +1,43 @@ +package paych + +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/builtin" + "github.com/filecoin-project/go-state-types/builtin/v18/util/adt" +) + +type StateSummary struct { + Redeemed abi.TokenAmount +} + +// Checks internal invariants of paych state. +func CheckStateInvariants(st *State, store adt.Store, balance abi.TokenAmount) (*StateSummary, *builtin.MessageAccumulator) { + acc := &builtin.MessageAccumulator{} + paychSummary := &StateSummary{ + Redeemed: big.Zero(), + } + + acc.Require(st.From.Protocol() == address.ID, "from address is not ID address %v", st.From) + acc.Require(st.To.Protocol() == address.ID, "to address is not ID address %v", st.To) + acc.Require(st.SettlingAt >= st.MinSettleHeight, + "channel is setting at epoch %d before min settle height %d", st.SettlingAt, st.MinSettleHeight) + + if lanes, err := adt.AsArray(store, st.LaneStates, LaneStatesAmtBitwidth); err != nil { + acc.Addf("error loading lanes: %v", err) + } else { + var lane LaneState + err = lanes.ForEach(&lane, func(i int64) error { + acc.Require(lane.Redeemed.GreaterThan(big.Zero()), "land %d redeemed is not greater than zero %v", i, lane.Redeemed) + paychSummary.Redeemed = big.Add(paychSummary.Redeemed, lane.Redeemed) + return nil + }) + acc.RequireNoError(err, "error iterating lanes") + } + + acc.Require(balance.GreaterThanEqual(st.ToSend), + "channel has insufficient funds to send (%v < %v)", balance, st.ToSend) + + return paychSummary, acc +} diff --git a/builtin/v18/paych/methods.go b/builtin/v18/paych/methods.go new file mode 100644 index 00000000..e034d4aa --- /dev/null +++ b/builtin/v18/paych/methods.go @@ -0,0 +1,13 @@ +package paych + +import ( + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/builtin" +) + +var Methods = map[abi.MethodNum]builtin.MethodMeta{ + 1: builtin.NewMethodMeta("Constructor", *new(func(*ConstructorParams) *abi.EmptyValue)), // Constructor + 2: builtin.NewMethodMeta("UpdateChannelState", *new(func(*UpdateChannelStateParams) *abi.EmptyValue)), // UpdateChannelState + 3: builtin.NewMethodMeta("Settle", *new(func(*abi.EmptyValue) *abi.EmptyValue)), // Settle + 4: builtin.NewMethodMeta("Collect", *new(func(*abi.EmptyValue) *abi.EmptyValue)), // Collect +} diff --git a/builtin/v18/paych/paych_state.go b/builtin/v18/paych/paych_state.go new file mode 100644 index 00000000..67a068be --- /dev/null +++ b/builtin/v18/paych/paych_state.go @@ -0,0 +1,39 @@ +package paych + +import ( + "github.com/ipfs/go-cid" + + addr "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/big" +) + +// A given payment channel actor is established by From +// to enable off-chain microtransactions to To to be reconciled +// and tallied on chain. +type State struct { + // Channel owner, who has funded the actor + From addr.Address + // Recipient of payouts from channel + To addr.Address + + // Amount successfully redeemed through the payment channel, paid out on `Collect()` + ToSend abi.TokenAmount + + // Height at which the channel can be `Collected` + SettlingAt abi.ChainEpoch + // Height before which the channel `ToSend` cannot be collected + MinSettleHeight abi.ChainEpoch + + // Collections of lane states for the channel, maintained in ID order. + LaneStates cid.Cid // AMT +} + +// The Lane state tracks the latest (highest) voucher nonce used to merge the lane +// as well as the amount it has already redeemed. +type LaneState struct { + Redeemed big.Int + Nonce uint64 +} + +const LaneStatesAmtBitwidth = 3 diff --git a/builtin/v18/paych/paych_types.go b/builtin/v18/paych/paych_types.go new file mode 100644 index 00000000..cdc7dc78 --- /dev/null +++ b/builtin/v18/paych/paych_types.go @@ -0,0 +1,78 @@ +package paych + +import ( + "bytes" + + addr "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" +) + +type UpdateChannelStateParams struct { + Sv SignedVoucher + Secret []byte +} + +// A voucher is sent by `From` to `To` off-chain in order to enable +// `To` to redeem payments on-chain in the future +type SignedVoucher struct { + // ChannelAddr is the address of the payment channel this signed voucher is valid for + ChannelAddr addr.Address + // TimeLockMin sets a min epoch before which the voucher cannot be redeemed + TimeLockMin abi.ChainEpoch + // TimeLockMax sets a max epoch beyond which the voucher cannot be redeemed + // TimeLockMax set to 0 means no timeout + TimeLockMax abi.ChainEpoch + // (optional) The SecretHash is used by `To` to validate + SecretHash []byte + // (optional) Extra can be specified by `From` to add a verification method to the voucher. + Extra *ModVerifyParams + // Specifies which lane the Voucher merges into (will be created if does not exist) + Lane uint64 + // Nonce is set by `From` to prevent redemption of stale vouchers on a lane + Nonce uint64 + // Amount voucher can be redeemed for + Amount big.Int + // (optional) MinSettleHeight can extend channel MinSettleHeight if needed + MinSettleHeight abi.ChainEpoch + + // (optional) Set of lanes to be merged into `Lane` + Merges []Merge + + // Sender's signature over the voucher + Signature *crypto.Signature +} + +func (t *SignedVoucher) SigningBytes() ([]byte, error) { + osv := *t + osv.Signature = nil + + buf := new(bytes.Buffer) + if err := osv.MarshalCBOR(buf); err != nil { + return nil, err + } + + return buf.Bytes(), nil +} + +type ConstructorParams struct { + From addr.Address // Payer + To addr.Address // Payee +} + +// Modular Verification method +type ModVerifyParams struct { + // Actor on which to invoke the method. + Actor addr.Address + // Method to invoke. + Method abi.MethodNum + // Pre-serialized method parameters. + Data []byte +} + +// Specifies which `Lane`s to be merged with what `Nonce` on channelUpdate +type Merge struct { + Lane uint64 + Nonce uint64 +} diff --git a/builtin/v18/paych/policy.go b/builtin/v18/paych/policy.go new file mode 100644 index 00000000..d76cc57e --- /dev/null +++ b/builtin/v18/paych/policy.go @@ -0,0 +1,7 @@ +package paych + +import ( + "github.com/filecoin-project/go-state-types/builtin" +) + +const SettleDelay = builtin.EpochsInHour * 12 diff --git a/builtin/v18/placeholder/methods.go b/builtin/v18/placeholder/methods.go new file mode 100644 index 00000000..7faf41c8 --- /dev/null +++ b/builtin/v18/placeholder/methods.go @@ -0,0 +1,9 @@ +package placeholder + +import ( + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/builtin" +) + +// Placeholder has no methods, not even a constructor +var Methods = map[abi.MethodNum]builtin.MethodMeta{} diff --git a/builtin/v18/power/cbor_gen.go b/builtin/v18/power/cbor_gen.go new file mode 100644 index 00000000..b93d205c --- /dev/null +++ b/builtin/v18/power/cbor_gen.go @@ -0,0 +1,1660 @@ +// Code generated by github.com/whyrusleeping/cbor-gen. DO NOT EDIT. + +package power + +import ( + "fmt" + "io" + "math" + "sort" + + address "github.com/filecoin-project/go-address" + abi "github.com/filecoin-project/go-state-types/abi" + cid "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" + xerrors "golang.org/x/xerrors" +) + +var _ = xerrors.Errorf +var _ = cid.Undef +var _ = math.E +var _ = sort.Sort + +var lengthBufState = []byte{145} + +func (t *State) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufState); err != nil { + return err + } + + // t.TotalRawBytePower (big.Int) (struct) + if err := t.TotalRawBytePower.MarshalCBOR(cw); err != nil { + return err + } + + // t.TotalBytesCommitted (big.Int) (struct) + if err := t.TotalBytesCommitted.MarshalCBOR(cw); err != nil { + return err + } + + // t.TotalQualityAdjPower (big.Int) (struct) + if err := t.TotalQualityAdjPower.MarshalCBOR(cw); err != nil { + return err + } + + // t.TotalQABytesCommitted (big.Int) (struct) + if err := t.TotalQABytesCommitted.MarshalCBOR(cw); err != nil { + return err + } + + // t.TotalPledgeCollateral (big.Int) (struct) + if err := t.TotalPledgeCollateral.MarshalCBOR(cw); err != nil { + return err + } + + // t.ThisEpochRawBytePower (big.Int) (struct) + if err := t.ThisEpochRawBytePower.MarshalCBOR(cw); err != nil { + return err + } + + // t.ThisEpochQualityAdjPower (big.Int) (struct) + if err := t.ThisEpochQualityAdjPower.MarshalCBOR(cw); err != nil { + return err + } + + // t.ThisEpochPledgeCollateral (big.Int) (struct) + if err := t.ThisEpochPledgeCollateral.MarshalCBOR(cw); err != nil { + return err + } + + // t.ThisEpochQAPowerSmoothed (smoothing.FilterEstimate) (struct) + if err := t.ThisEpochQAPowerSmoothed.MarshalCBOR(cw); err != nil { + return err + } + + // t.MinerCount (int64) (int64) + if t.MinerCount >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.MinerCount)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.MinerCount-1)); err != nil { + return err + } + } + + // t.MinerAboveMinPowerCount (int64) (int64) + if t.MinerAboveMinPowerCount >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.MinerAboveMinPowerCount)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.MinerAboveMinPowerCount-1)); err != nil { + return err + } + } + + // t.RampStartEpoch (int64) (int64) + if t.RampStartEpoch >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.RampStartEpoch)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.RampStartEpoch-1)); err != nil { + return err + } + } + + // t.RampDurationEpochs (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.RampDurationEpochs)); err != nil { + return err + } + + // t.CronEventQueue (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.CronEventQueue); err != nil { + return xerrors.Errorf("failed to write cid field t.CronEventQueue: %w", err) + } + + // t.FirstCronEpoch (abi.ChainEpoch) (int64) + if t.FirstCronEpoch >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.FirstCronEpoch)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.FirstCronEpoch-1)); err != nil { + return err + } + } + + // t.Claims (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.Claims); err != nil { + return xerrors.Errorf("failed to write cid field t.Claims: %w", err) + } + + // t.ProofValidationBatch (cid.Cid) (struct) + + if t.ProofValidationBatch == nil { + if _, err := cw.Write(cbg.CborNull); err != nil { + return err + } + } else { + if err := cbg.WriteCid(cw, *t.ProofValidationBatch); err != nil { + return xerrors.Errorf("failed to write cid field t.ProofValidationBatch: %w", err) + } + } + + return nil +} + +func (t *State) UnmarshalCBOR(r io.Reader) (err error) { + *t = State{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 17 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.TotalRawBytePower (big.Int) (struct) + + { + + if err := t.TotalRawBytePower.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.TotalRawBytePower: %w", err) + } + + } + // t.TotalBytesCommitted (big.Int) (struct) + + { + + if err := t.TotalBytesCommitted.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.TotalBytesCommitted: %w", err) + } + + } + // t.TotalQualityAdjPower (big.Int) (struct) + + { + + if err := t.TotalQualityAdjPower.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.TotalQualityAdjPower: %w", err) + } + + } + // t.TotalQABytesCommitted (big.Int) (struct) + + { + + if err := t.TotalQABytesCommitted.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.TotalQABytesCommitted: %w", err) + } + + } + // t.TotalPledgeCollateral (big.Int) (struct) + + { + + if err := t.TotalPledgeCollateral.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.TotalPledgeCollateral: %w", err) + } + + } + // t.ThisEpochRawBytePower (big.Int) (struct) + + { + + if err := t.ThisEpochRawBytePower.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ThisEpochRawBytePower: %w", err) + } + + } + // t.ThisEpochQualityAdjPower (big.Int) (struct) + + { + + if err := t.ThisEpochQualityAdjPower.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ThisEpochQualityAdjPower: %w", err) + } + + } + // t.ThisEpochPledgeCollateral (big.Int) (struct) + + { + + if err := t.ThisEpochPledgeCollateral.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ThisEpochPledgeCollateral: %w", err) + } + + } + // t.ThisEpochQAPowerSmoothed (smoothing.FilterEstimate) (struct) + + { + + if err := t.ThisEpochQAPowerSmoothed.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ThisEpochQAPowerSmoothed: %w", err) + } + + } + // t.MinerCount (int64) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.MinerCount = int64(extraI) + } + // t.MinerAboveMinPowerCount (int64) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.MinerAboveMinPowerCount = int64(extraI) + } + // t.RampStartEpoch (int64) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.RampStartEpoch = int64(extraI) + } + // t.RampDurationEpochs (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.RampDurationEpochs = uint64(extra) + + } + // t.CronEventQueue (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.CronEventQueue: %w", err) + } + + t.CronEventQueue = c + + } + // t.FirstCronEpoch (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.FirstCronEpoch = abi.ChainEpoch(extraI) + } + // t.Claims (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.Claims: %w", err) + } + + t.Claims = c + + } + // t.ProofValidationBatch (cid.Cid) (struct) + + { + + b, err := cr.ReadByte() + if err != nil { + return err + } + if b != cbg.CborNull[0] { + if err := cr.UnreadByte(); err != nil { + return err + } + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.ProofValidationBatch: %w", err) + } + + t.ProofValidationBatch = &c + } + + } + return nil +} + +var lengthBufClaim = []byte{131} + +func (t *Claim) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufClaim); err != nil { + return err + } + + // t.WindowPoStProofType (abi.RegisteredPoStProof) (int64) + if t.WindowPoStProofType >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.WindowPoStProofType)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.WindowPoStProofType-1)); err != nil { + return err + } + } + + // t.RawBytePower (big.Int) (struct) + if err := t.RawBytePower.MarshalCBOR(cw); err != nil { + return err + } + + // t.QualityAdjPower (big.Int) (struct) + if err := t.QualityAdjPower.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *Claim) UnmarshalCBOR(r io.Reader) (err error) { + *t = Claim{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.WindowPoStProofType (abi.RegisteredPoStProof) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.WindowPoStProofType = abi.RegisteredPoStProof(extraI) + } + // t.RawBytePower (big.Int) (struct) + + { + + if err := t.RawBytePower.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.RawBytePower: %w", err) + } + + } + // t.QualityAdjPower (big.Int) (struct) + + { + + if err := t.QualityAdjPower.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.QualityAdjPower: %w", err) + } + + } + return nil +} + +var lengthBufUpdateClaimedPowerParams = []byte{130} + +func (t *UpdateClaimedPowerParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufUpdateClaimedPowerParams); err != nil { + return err + } + + // t.RawByteDelta (big.Int) (struct) + if err := t.RawByteDelta.MarshalCBOR(cw); err != nil { + return err + } + + // t.QualityAdjustedDelta (big.Int) (struct) + if err := t.QualityAdjustedDelta.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *UpdateClaimedPowerParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = UpdateClaimedPowerParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.RawByteDelta (big.Int) (struct) + + { + + if err := t.RawByteDelta.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.RawByteDelta: %w", err) + } + + } + // t.QualityAdjustedDelta (big.Int) (struct) + + { + + if err := t.QualityAdjustedDelta.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.QualityAdjustedDelta: %w", err) + } + + } + return nil +} + +var lengthBufMinerConstructorParams = []byte{134} + +func (t *MinerConstructorParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufMinerConstructorParams); err != nil { + return err + } + + // t.OwnerAddr (address.Address) (struct) + if err := t.OwnerAddr.MarshalCBOR(cw); err != nil { + return err + } + + // t.WorkerAddr (address.Address) (struct) + if err := t.WorkerAddr.MarshalCBOR(cw); err != nil { + return err + } + + // t.ControlAddrs ([]address.Address) (slice) + if len(t.ControlAddrs) > 8192 { + return xerrors.Errorf("Slice value in field t.ControlAddrs was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.ControlAddrs))); err != nil { + return err + } + for _, v := range t.ControlAddrs { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + + // t.WindowPoStProofType (abi.RegisteredPoStProof) (int64) + if t.WindowPoStProofType >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.WindowPoStProofType)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.WindowPoStProofType-1)); err != nil { + return err + } + } + + // t.PeerId ([]uint8) (slice) + if len(t.PeerId) > 2097152 { + return xerrors.Errorf("Byte array in field t.PeerId was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.PeerId))); err != nil { + return err + } + + if _, err := cw.Write(t.PeerId); err != nil { + return err + } + + // t.Multiaddrs ([][]uint8) (slice) + if len(t.Multiaddrs) > 8192 { + return xerrors.Errorf("Slice value in field t.Multiaddrs was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Multiaddrs))); err != nil { + return err + } + for _, v := range t.Multiaddrs { + if len(v) > 2097152 { + return xerrors.Errorf("Byte array in field v was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(v))); err != nil { + return err + } + + if _, err := cw.Write(v); err != nil { + return err + } + + } + return nil +} + +func (t *MinerConstructorParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = MinerConstructorParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 6 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.OwnerAddr (address.Address) (struct) + + { + + if err := t.OwnerAddr.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.OwnerAddr: %w", err) + } + + } + // t.WorkerAddr (address.Address) (struct) + + { + + if err := t.WorkerAddr.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.WorkerAddr: %w", err) + } + + } + // t.ControlAddrs ([]address.Address) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.ControlAddrs: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.ControlAddrs = make([]address.Address, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.ControlAddrs[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ControlAddrs[i]: %w", err) + } + + } + + } + } + // t.WindowPoStProofType (abi.RegisteredPoStProof) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.WindowPoStProofType = abi.RegisteredPoStProof(extraI) + } + // t.PeerId ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.PeerId: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.PeerId = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.PeerId); err != nil { + return err + } + + // t.Multiaddrs ([][]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Multiaddrs: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Multiaddrs = make([][]uint8, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.Multiaddrs[i]: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.Multiaddrs[i] = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.Multiaddrs[i]); err != nil { + return err + } + + } + } + return nil +} + +var lengthBufCreateMinerParams = []byte{133} + +func (t *CreateMinerParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufCreateMinerParams); err != nil { + return err + } + + // t.Owner (address.Address) (struct) + if err := t.Owner.MarshalCBOR(cw); err != nil { + return err + } + + // t.Worker (address.Address) (struct) + if err := t.Worker.MarshalCBOR(cw); err != nil { + return err + } + + // t.WindowPoStProofType (abi.RegisteredPoStProof) (int64) + if t.WindowPoStProofType >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.WindowPoStProofType)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.WindowPoStProofType-1)); err != nil { + return err + } + } + + // t.Peer ([]uint8) (slice) + if len(t.Peer) > 2097152 { + return xerrors.Errorf("Byte array in field t.Peer was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.Peer))); err != nil { + return err + } + + if _, err := cw.Write(t.Peer); err != nil { + return err + } + + // t.Multiaddrs ([][]uint8) (slice) + if len(t.Multiaddrs) > 8192 { + return xerrors.Errorf("Slice value in field t.Multiaddrs was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Multiaddrs))); err != nil { + return err + } + for _, v := range t.Multiaddrs { + if len(v) > 2097152 { + return xerrors.Errorf("Byte array in field v was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(v))); err != nil { + return err + } + + if _, err := cw.Write(v); err != nil { + return err + } + + } + return nil +} + +func (t *CreateMinerParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = CreateMinerParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 5 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Owner (address.Address) (struct) + + { + + if err := t.Owner.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Owner: %w", err) + } + + } + // t.Worker (address.Address) (struct) + + { + + if err := t.Worker.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Worker: %w", err) + } + + } + // t.WindowPoStProofType (abi.RegisteredPoStProof) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.WindowPoStProofType = abi.RegisteredPoStProof(extraI) + } + // t.Peer ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.Peer: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.Peer = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.Peer); err != nil { + return err + } + + // t.Multiaddrs ([][]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Multiaddrs: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Multiaddrs = make([][]uint8, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.Multiaddrs[i]: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.Multiaddrs[i] = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.Multiaddrs[i]); err != nil { + return err + } + + } + } + return nil +} + +var lengthBufCreateMinerReturn = []byte{130} + +func (t *CreateMinerReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufCreateMinerReturn); err != nil { + return err + } + + // t.IDAddress (address.Address) (struct) + if err := t.IDAddress.MarshalCBOR(cw); err != nil { + return err + } + + // t.RobustAddress (address.Address) (struct) + if err := t.RobustAddress.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *CreateMinerReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = CreateMinerReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.IDAddress (address.Address) (struct) + + { + + if err := t.IDAddress.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.IDAddress: %w", err) + } + + } + // t.RobustAddress (address.Address) (struct) + + { + + if err := t.RobustAddress.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.RobustAddress: %w", err) + } + + } + return nil +} + +var lengthBufCurrentTotalPowerReturn = []byte{134} + +func (t *CurrentTotalPowerReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufCurrentTotalPowerReturn); err != nil { + return err + } + + // t.RawBytePower (big.Int) (struct) + if err := t.RawBytePower.MarshalCBOR(cw); err != nil { + return err + } + + // t.QualityAdjPower (big.Int) (struct) + if err := t.QualityAdjPower.MarshalCBOR(cw); err != nil { + return err + } + + // t.PledgeCollateral (big.Int) (struct) + if err := t.PledgeCollateral.MarshalCBOR(cw); err != nil { + return err + } + + // t.QualityAdjPowerSmoothed (smoothing.FilterEstimate) (struct) + if err := t.QualityAdjPowerSmoothed.MarshalCBOR(cw); err != nil { + return err + } + + // t.RampStartEpoch (int64) (int64) + if t.RampStartEpoch >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.RampStartEpoch)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.RampStartEpoch-1)); err != nil { + return err + } + } + + // t.RampDurationEpochs (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.RampDurationEpochs)); err != nil { + return err + } + + return nil +} + +func (t *CurrentTotalPowerReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = CurrentTotalPowerReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 6 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.RawBytePower (big.Int) (struct) + + { + + if err := t.RawBytePower.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.RawBytePower: %w", err) + } + + } + // t.QualityAdjPower (big.Int) (struct) + + { + + if err := t.QualityAdjPower.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.QualityAdjPower: %w", err) + } + + } + // t.PledgeCollateral (big.Int) (struct) + + { + + if err := t.PledgeCollateral.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.PledgeCollateral: %w", err) + } + + } + // t.QualityAdjPowerSmoothed (smoothing.FilterEstimate) (struct) + + { + + if err := t.QualityAdjPowerSmoothed.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.QualityAdjPowerSmoothed: %w", err) + } + + } + // t.RampStartEpoch (int64) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.RampStartEpoch = int64(extraI) + } + // t.RampDurationEpochs (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.RampDurationEpochs = uint64(extra) + + } + return nil +} + +var lengthBufEnrollCronEventParams = []byte{130} + +func (t *EnrollCronEventParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufEnrollCronEventParams); err != nil { + return err + } + + // t.EventEpoch (abi.ChainEpoch) (int64) + if t.EventEpoch >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.EventEpoch)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.EventEpoch-1)); err != nil { + return err + } + } + + // t.Payload ([]uint8) (slice) + if len(t.Payload) > 2097152 { + return xerrors.Errorf("Byte array in field t.Payload was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.Payload))); err != nil { + return err + } + + if _, err := cw.Write(t.Payload); err != nil { + return err + } + + return nil +} + +func (t *EnrollCronEventParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = EnrollCronEventParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.EventEpoch (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.EventEpoch = abi.ChainEpoch(extraI) + } + // t.Payload ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.Payload: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.Payload = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.Payload); err != nil { + return err + } + + return nil +} + +var lengthBufMinerRawPowerReturn = []byte{130} + +func (t *MinerRawPowerReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufMinerRawPowerReturn); err != nil { + return err + } + + // t.RawBytePower (big.Int) (struct) + if err := t.RawBytePower.MarshalCBOR(cw); err != nil { + return err + } + + // t.MeetsConsensusMinimum (bool) (bool) + if err := cbg.WriteBool(w, t.MeetsConsensusMinimum); err != nil { + return err + } + return nil +} + +func (t *MinerRawPowerReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = MinerRawPowerReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.RawBytePower (big.Int) (struct) + + { + + if err := t.RawBytePower.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.RawBytePower: %w", err) + } + + } + // t.MeetsConsensusMinimum (bool) (bool) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajOther { + return fmt.Errorf("booleans must be major type 7") + } + switch extra { + case 20: + t.MeetsConsensusMinimum = false + case 21: + t.MeetsConsensusMinimum = true + default: + return fmt.Errorf("booleans are either major type 7, value 20 or 21 (got %d)", extra) + } + return nil +} + +var lengthBufCronEvent = []byte{130} + +func (t *CronEvent) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufCronEvent); err != nil { + return err + } + + // t.MinerAddr (address.Address) (struct) + if err := t.MinerAddr.MarshalCBOR(cw); err != nil { + return err + } + + // t.CallbackPayload ([]uint8) (slice) + if len(t.CallbackPayload) > 2097152 { + return xerrors.Errorf("Byte array in field t.CallbackPayload was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.CallbackPayload))); err != nil { + return err + } + + if _, err := cw.Write(t.CallbackPayload); err != nil { + return err + } + + return nil +} + +func (t *CronEvent) UnmarshalCBOR(r io.Reader) (err error) { + *t = CronEvent{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.MinerAddr (address.Address) (struct) + + { + + if err := t.MinerAddr.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.MinerAddr: %w", err) + } + + } + // t.CallbackPayload ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.CallbackPayload: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.CallbackPayload = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.CallbackPayload); err != nil { + return err + } + + return nil +} + +var lengthBufMinerPowerReturn = []byte{130} + +func (t *MinerPowerReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufMinerPowerReturn); err != nil { + return err + } + + // t.RawBytePower (big.Int) (struct) + if err := t.RawBytePower.MarshalCBOR(cw); err != nil { + return err + } + + // t.QualityAdjPower (big.Int) (struct) + if err := t.QualityAdjPower.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *MinerPowerReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = MinerPowerReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.RawBytePower (big.Int) (struct) + + { + + if err := t.RawBytePower.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.RawBytePower: %w", err) + } + + } + // t.QualityAdjPower (big.Int) (struct) + + { + + if err := t.QualityAdjPower.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.QualityAdjPower: %w", err) + } + + } + return nil +} diff --git a/builtin/v18/power/invariants.go b/builtin/v18/power/invariants.go new file mode 100644 index 00000000..acc91a12 --- /dev/null +++ b/builtin/v18/power/invariants.go @@ -0,0 +1,189 @@ +package power + +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/builtin" + "github.com/filecoin-project/go-state-types/builtin/v18/util/adt" + "github.com/filecoin-project/go-state-types/network" + "github.com/filecoin-project/go-state-types/proof" +) + +type MinerCronEvent struct { + Epoch abi.ChainEpoch + Payload []byte +} + +type CronEventsByAddress map[address.Address][]MinerCronEvent +type ClaimsByAddress map[address.Address]Claim +type ProofsByAddress map[address.Address][]proof.SealVerifyInfo + +type StateSummary struct { + Crons CronEventsByAddress + Claims ClaimsByAddress + Proofs ProofsByAddress +} + +// Checks internal invariants of power state. +func CheckStateInvariants(st *State, store adt.Store) (*StateSummary, *builtin.MessageAccumulator) { + acc := &builtin.MessageAccumulator{} + + // basic invariants around recorded power + acc.Require(st.TotalRawBytePower.GreaterThanEqual(big.Zero()), "total raw power is negative %v", st.TotalRawBytePower) + acc.Require(st.TotalQualityAdjPower.GreaterThanEqual(big.Zero()), "total qa power is negative %v", st.TotalQualityAdjPower) + acc.Require(st.TotalBytesCommitted.GreaterThanEqual(big.Zero()), "total raw power committed is negative %v", st.TotalBytesCommitted) + acc.Require(st.TotalQABytesCommitted.GreaterThanEqual(big.Zero()), "total qa power committed is negative %v", st.TotalQABytesCommitted) + + acc.Require(st.TotalRawBytePower.LessThanEqual(st.TotalQualityAdjPower), + "total raw power %v is greater than total quality adjusted power %v", st.TotalRawBytePower, st.TotalQualityAdjPower) + acc.Require(st.TotalBytesCommitted.LessThanEqual(st.TotalQABytesCommitted), + "committed raw power %v is greater than committed quality adjusted power %v", st.TotalBytesCommitted, st.TotalQABytesCommitted) + acc.Require(st.TotalRawBytePower.LessThanEqual(st.TotalBytesCommitted), + "total raw power %v is greater than raw power committed %v", st.TotalRawBytePower, st.TotalBytesCommitted) + acc.Require(st.TotalQualityAdjPower.LessThanEqual(st.TotalQABytesCommitted), + "total qa power %v is greater than qa power committed %v", st.TotalQualityAdjPower, st.TotalQABytesCommitted) + + crons := CheckCronInvariants(st, store, acc) + claims := CheckClaimInvariants(st, store, acc) + proofs := CheckProofValidationInvariants(st, store, claims, acc) + + return &StateSummary{ + Crons: crons, + Claims: claims, + Proofs: proofs, + }, acc +} + +func CheckCronInvariants(st *State, store adt.Store, acc *builtin.MessageAccumulator) CronEventsByAddress { + byAddress := make(CronEventsByAddress) + queue, err := adt.AsMultimap(store, st.CronEventQueue, CronQueueHamtBitwidth, CronQueueAmtBitwidth) + if err != nil { + acc.Addf("error loading cron event queue: %v", err) + // Bail here. + return byAddress + } + + err = queue.ForAll(func(ekey string, arr *adt.Array) error { + epoch, err := abi.ParseIntKey(ekey) + acc.Require(err == nil, "non-int key in cron array") + if err != nil { + return nil // error noted above + } + + acc.Require(abi.ChainEpoch(epoch) >= st.FirstCronEpoch, "cron event at epoch %d before FirstCronEpoch %d", + epoch, st.FirstCronEpoch) + + var event CronEvent + return arr.ForEach(&event, func(i int64) error { + byAddress[event.MinerAddr] = append(byAddress[event.MinerAddr], MinerCronEvent{ + Epoch: abi.ChainEpoch(epoch), + Payload: event.CallbackPayload, + }) + + return nil + }) + }) + acc.RequireNoError(err, "error iterating cron tasks") + return byAddress +} + +func CheckClaimInvariants(st *State, store adt.Store, acc *builtin.MessageAccumulator) ClaimsByAddress { + byAddress := make(ClaimsByAddress) + claims, err := adt.AsMap(store, st.Claims, builtin.DefaultHamtBitwidth) + if err != nil { + acc.Addf("error loading power claims: %v", err) + // Bail here + return byAddress + } + + committedRawPower := abi.NewStoragePower(0) + committedQAPower := abi.NewStoragePower(0) + rawPower := abi.NewStoragePower(0) + qaPower := abi.NewStoragePower(0) + claimsWithSufficientPowerCount := int64(0) + var claim Claim + err = claims.ForEach(&claim, func(key string) error { + addr, err := address.NewFromBytes([]byte(key)) + if err != nil { + return err + } + byAddress[addr] = claim + committedRawPower = big.Add(committedRawPower, claim.RawBytePower) + committedQAPower = big.Add(committedQAPower, claim.QualityAdjPower) + + minPower, err := builtin.ConsensusMinerMinPower(claim.WindowPoStProofType) + acc.Require(err == nil, "could not get consensus miner min power for miner %v: %v", addr, err) + if err != nil { + return nil // noted above + } + + if claim.RawBytePower.GreaterThanEqual(minPower) { + claimsWithSufficientPowerCount += 1 + rawPower = big.Add(rawPower, claim.RawBytePower) + qaPower = big.Add(qaPower, claim.QualityAdjPower) + } + return nil + }) + acc.RequireNoError(err, "error iterating power claims") + + acc.Require(committedRawPower.Equals(st.TotalBytesCommitted), + "sum of raw power in claims %v does not match recorded bytes committed %v", + committedRawPower, st.TotalBytesCommitted) + acc.Require(committedQAPower.Equals(st.TotalQABytesCommitted), + "sum of qa power in claims %v does not match recorded qa power committed %v", + committedQAPower, st.TotalQABytesCommitted) + + acc.Require(claimsWithSufficientPowerCount == st.MinerAboveMinPowerCount, + "claims with sufficient power %d does not match MinerAboveMinPowerCount %d", + claimsWithSufficientPowerCount, st.MinerAboveMinPowerCount) + + acc.Require(st.TotalRawBytePower.Equals(rawPower), + "recorded raw power %v does not match raw power in claims %v", st.TotalRawBytePower, rawPower) + acc.Require(st.TotalQualityAdjPower.Equals(qaPower), + "recorded qa power %v does not match qa power in claims %v", st.TotalQualityAdjPower, qaPower) + + return byAddress +} + +func CheckProofValidationInvariants(st *State, store adt.Store, claims ClaimsByAddress, acc *builtin.MessageAccumulator) ProofsByAddress { + if st.ProofValidationBatch == nil { + return nil + } + + proofs := make(ProofsByAddress) + if queue, err := adt.AsMultimap(store, *st.ProofValidationBatch, builtin.DefaultHamtBitwidth, ProofValidationBatchAmtBitwidth); err != nil { + acc.Addf("error loading proof validation queue: %v", err) + } else { + err = queue.ForAll(func(key string, arr *adt.Array) error { + addr, err := address.NewFromBytes([]byte(key)) + if err != nil { + return err + } + + claim, found := claims[addr] + acc.Require(found, "miner %v has proofs awaiting validation but no claim", addr) + if !found { + return nil + } + + var info proof.SealVerifyInfo + err = arr.ForEach(&info, func(i int64) error { + sectorWindowPoStProofType, err := info.SealProof.RegisteredWindowPoStProofByNetworkVersion(network.Version19) + acc.RequireNoError(err, "failed to get PoSt proof type for seal proof %d", info.SealProof) + acc.Require(claim.WindowPoStProofType == sectorWindowPoStProofType, "miner submitted proof with proof type %d different from claim %d", + sectorWindowPoStProofType, claim.WindowPoStProofType) + proofs[addr] = append(proofs[addr], info) + return nil + }) + if err != nil { + return err + } + acc.Require(len(proofs[addr]) <= MaxMinerProveCommitsPerEpoch, + "miner %v has submitted too many proofs (%d) for batch verification", addr, len(proofs[addr])) + return nil + }) + acc.RequireNoError(err, "error iterating proof validation queue") + } + return proofs +} diff --git a/builtin/v18/power/methods.go b/builtin/v18/power/methods.go new file mode 100644 index 00000000..8d3839e8 --- /dev/null +++ b/builtin/v18/power/methods.go @@ -0,0 +1,24 @@ +package power + +import ( + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/builtin" + "github.com/filecoin-project/go-state-types/proof" +) + +var Methods = map[abi.MethodNum]builtin.MethodMeta{ + 1: builtin.NewMethodMeta("Constructor", *new(func(*abi.EmptyValue) *abi.EmptyValue)), // Constructor + 2: builtin.NewMethodMeta("CreateMiner", *new(func(*CreateMinerParams) *CreateMinerReturn)), // CreateMiner + builtin.MustGenerateFRCMethodNum("CreateMiner"): builtin.NewMethodMeta("CreateMinerExported", *new(func(*CreateMinerParams) *CreateMinerReturn)), // CreateMinerExported + 3: builtin.NewMethodMeta("UpdateClaimedPower", *new(func(*UpdateClaimedPowerParams) *abi.EmptyValue)), // UpdateClaimedPower + 4: builtin.NewMethodMeta("EnrollCronEvent", *new(func(*EnrollCronEventParams) *abi.EmptyValue)), // EnrollCronEvent + 5: builtin.NewMethodMeta("CronTick", *new(func(*abi.EmptyValue) *abi.EmptyValue)), // CronTick + 6: builtin.NewMethodMeta("UpdatePledgeTotal", *new(func(*abi.TokenAmount) *abi.EmptyValue)), // UpdatePledgeTotal + 7: builtin.NewMethodMeta("OnConsensusFault", nil), // deprecated + 8: builtin.NewMethodMeta("SubmitPoRepForBulkVerify", *new(func(*proof.SealVerifyInfo) *abi.EmptyValue)), // SubmitPoRepForBulkVerify + 9: builtin.NewMethodMeta("CurrentTotalPower", *new(func(*abi.EmptyValue) *CurrentTotalPowerReturn)), // CurrentTotalPower + builtin.MustGenerateFRCMethodNum("NetworkRawPower"): builtin.NewMethodMeta("NetworkRawPowerExported", *new(func(*abi.EmptyValue) *NetworkRawPowerReturn)), // NetworkRawPowerExported + builtin.MustGenerateFRCMethodNum("MinerRawPower"): builtin.NewMethodMeta("MinerRawPowerExported", *new(func(*MinerRawPowerParams) *MinerRawPowerReturn)), // MinerRawPowerExported + builtin.MustGenerateFRCMethodNum("MinerCount"): builtin.NewMethodMeta("MinerCountExported", *new(func(*abi.EmptyValue) *MinerCountReturn)), // MinerCountExported + builtin.MustGenerateFRCMethodNum("MinerConsensusCount"): builtin.NewMethodMeta("MinerConsensusCountExported", *new(func(*abi.EmptyValue) *MinerConsensusCountReturn)), // MinerConsensusCountExported +} diff --git a/builtin/v18/power/power_state.go b/builtin/v18/power/power_state.go new file mode 100644 index 00000000..afa7083d --- /dev/null +++ b/builtin/v18/power/power_state.go @@ -0,0 +1,274 @@ +package power + +import ( + "github.com/ipfs/go-cid" + "golang.org/x/xerrors" + + addr "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-hamt-ipld/v3" + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/big" + "github.com/filecoin-project/go-state-types/builtin" + "github.com/filecoin-project/go-state-types/builtin/v18/util/adt" + "github.com/filecoin-project/go-state-types/builtin/v18/util/smoothing" +) + +// genesis power in bytes = 750,000 GiB +var InitialQAPowerEstimatePosition = big.Mul(big.NewInt(750_000), big.NewInt(1<<30)) + +// max chain throughput in bytes per epoch = 120 ProveCommits / epoch = 3,840 GiB +var InitialQAPowerEstimateVelocity = big.Mul(big.NewInt(3_840), big.NewInt(1<<30)) + +// Bitwidth of CronEventQueue HAMT determined empirically from mutation +// patterns and projections of mainnet data. +const CronQueueHamtBitwidth = 6 + +// Bitwidth of CronEventQueue AMT determined empirically from mutation +// patterns and projections of mainnet data. +const CronQueueAmtBitwidth = 6 + +// Bitwidth of ProofValidationBatch AMT determined empirically from mutation +// patterns and projections of mainnet data. +const ProofValidationBatchAmtBitwidth = 4 + +// The number of miners that must meet the consensus minimum miner power before that minimum power is enforced +// as a condition of leader election. +// This ensures a network still functions before any miners reach that threshold. +const ConsensusMinerMinMiners = 4 // PARAM_SPEC + +// PARAM_SPEC// Maximum number of prove-commits each miner can submit in one epoch. +// +// This limits the number of proof partitions we may need to load in the cron call path. +// Onboarding 1EiB/year requires at least 32 prove-commits per epoch. +const MaxMinerProveCommitsPerEpoch = 200 // PARAM_SPEC + +type State struct { + TotalRawBytePower abi.StoragePower + // TotalBytesCommitted includes claims from miners below min power threshold + TotalBytesCommitted abi.StoragePower + TotalQualityAdjPower abi.StoragePower + // TotalQABytesCommitted includes claims from miners below min power threshold + TotalQABytesCommitted abi.StoragePower + TotalPledgeCollateral abi.TokenAmount + + // These fields are set once per epoch in the previous cron tick and used + // for consistent values across a single epoch's state transition. + ThisEpochRawBytePower abi.StoragePower + ThisEpochQualityAdjPower abi.StoragePower + ThisEpochPledgeCollateral abi.TokenAmount + ThisEpochQAPowerSmoothed smoothing.FilterEstimate + + MinerCount int64 + // Number of miners having proven the minimum consensus power. + MinerAboveMinPowerCount int64 + + // FIP0081 changed pledge calculations, moving from ruleset A to ruleset B. + // This change is spread over several epochs to avoid sharp jumps in pledge + // amounts. At `RampStartEpoch`, we use the old ruleset. At + // `RampStartEpoch + RampDurationEpochs`, we use 70% old rules + 30% + // new rules. See FIP0081 for more details. + RampStartEpoch int64 + // Number of epochs over which the new pledge calculation is ramped up. + RampDurationEpochs uint64 + + // A queue of events to be triggered by cron, indexed by epoch. + CronEventQueue cid.Cid // Multimap, (HAMT[ChainEpoch]AMT[CronEvent]) + + // First epoch in which a cron task may be stored. + // Cron will iterate every epoch between this and the current epoch inclusively to find tasks to execute. + FirstCronEpoch abi.ChainEpoch + + // Claimed power for each miner. + Claims cid.Cid // Map, HAMT[address]Claim + + ProofValidationBatch *cid.Cid // Multimap, (HAMT[Address]AMT[SealVerifyInfo]) +} + +func ConstructState(store adt.Store) (*State, error) { + emptyClaimsMapCid, err := adt.StoreEmptyMap(store, builtin.DefaultHamtBitwidth) + if err != nil { + return nil, xerrors.Errorf("failed to create empty map: %w", err) + } + emptyCronQueueMMapCid, err := adt.StoreEmptyMultimap(store, CronQueueHamtBitwidth, CronQueueAmtBitwidth) + if err != nil { + return nil, xerrors.Errorf("failed to create empty multimap: %w", err) + } + + return &State{ + TotalRawBytePower: abi.NewStoragePower(0), + TotalBytesCommitted: abi.NewStoragePower(0), + TotalQualityAdjPower: abi.NewStoragePower(0), + TotalQABytesCommitted: abi.NewStoragePower(0), + TotalPledgeCollateral: abi.NewTokenAmount(0), + ThisEpochRawBytePower: abi.NewStoragePower(0), + ThisEpochQualityAdjPower: abi.NewStoragePower(0), + ThisEpochPledgeCollateral: abi.NewTokenAmount(0), + ThisEpochQAPowerSmoothed: smoothing.NewEstimate(InitialQAPowerEstimatePosition, InitialQAPowerEstimateVelocity), + FirstCronEpoch: 0, + CronEventQueue: emptyCronQueueMMapCid, + Claims: emptyClaimsMapCid, + MinerCount: 0, + MinerAboveMinPowerCount: 0, + RampStartEpoch: 0, + RampDurationEpochs: 0, + }, nil +} + +type Claim struct { + // Miner's proof type used to determine minimum miner size + WindowPoStProofType abi.RegisteredPoStProof + + // 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 +} + +type CronEvent struct { + MinerAddr addr.Address + CallbackPayload []byte +} + +// ClaimMeetsConsensusMinimums checks if given claim meets the minimums set by the network for mining. +func (st *State) ClaimMeetsConsensusMinimums(claim *Claim) (bool, error) { + minerNominalPower := claim.RawBytePower + minerMinPower, err := builtin.ConsensusMinerMinPower(claim.WindowPoStProofType) + if err != nil { + return false, xerrors.Errorf("could not get miner min power from proof type: %w", err) + } + + // if miner is larger than min power requirement, we're set + if minerNominalPower.GreaterThanEqual(minerMinPower) { + return true, nil + } + + // otherwise, if ConsensusMinerMinMiners miners meet min power requirement, return false + if st.MinerAboveMinPowerCount >= ConsensusMinerMinMiners { + return false, nil + } + + // If fewer than ConsensusMinerMinMiners over threshold miner can win a block with non-zero power + return minerNominalPower.GreaterThan(abi.NewStoragePower(0)), nil +} + +type powerMapReduceCache struct { + cmr *hamt.CachedMapReduce[Claim, *Claim, []builtin.OwnedClaim] +} + +func (st *State) CollectEligibleClaims(s adt.Store, cacheInOut *builtin.MapReduceCache) ([]builtin.OwnedClaim, error) { + if st.MinerAboveMinPowerCount < ConsensusMinerMinMiners { + // simple collect all claims, + var res []builtin.OwnedClaim + claims, err := adt.AsMap(s, st.Claims, builtin.DefaultHamtBitwidth) + if err != nil { + return nil, xerrors.Errorf("failed to load claims: %w", err) + } + var out Claim + err = claims.ForEach(&out, func(k string) error { + if !out.RawBytePower.GreaterThan(abi.NewStoragePower(0)) { + return nil + } + addr, err := addr.NewFromBytes([]byte(k)) + if err != nil { + return xerrors.Errorf("parsing address from bytes: %w", err) + } + res = append(res, builtin.OwnedClaim{ + Address: addr, + RawBytePower: out.RawBytePower, + QualityAdjPower: out.QualityAdjPower, + }) + return nil + }) + return res, err + } + cache, ok := (*cacheInOut).(powerMapReduceCache) + if !ok { + mapper := func(k string, claim Claim) ([]builtin.OwnedClaim, error) { + minerMinPower, err := builtin.ConsensusMinerMinPower(claim.WindowPoStProofType) + if err != nil { + return nil, xerrors.Errorf("could not get miner min power from proof type: %w", err) + } + if !claim.RawBytePower.GreaterThanEqual(minerMinPower) { + return nil, nil + } + addr, err := addr.NewFromBytes([]byte(k)) + if err != nil { + return nil, err + } + return []builtin.OwnedClaim{ + { + Address: addr, + RawBytePower: claim.RawBytePower, + QualityAdjPower: claim.QualityAdjPower, + }, + }, nil + } + reducer := func(in [][]builtin.OwnedClaim) ([]builtin.OwnedClaim, error) { + var out []builtin.OwnedClaim + for _, v := range in { + out = append(out, v...) + } + return out, nil + } + // cache size of 2000 is arbitrary, but seems to work well mith 600k claims with room for it to grow + cmr, err := hamt.NewCachedMapReduce[Claim, *Claim, []builtin.OwnedClaim](mapper, reducer, 2000) + if err != nil { + return nil, err + } + + cache = powerMapReduceCache{ + cmr: cmr, + } + (*cacheInOut) = cache + } + + claims, err := cache.cmr.MapReduce(s.Context(), s, st.Claims, + hamt.UseTreeBitWidth(builtin.DefaultHamtBitwidth)) + if err != nil { + return nil, xerrors.Errorf("failed to map reduce claims: %w", err) + } + + return claims, nil +} + +// MinerNominalPowerMeetsConsensusMinimum is used to validate Election PoSt +// winners outside the chain state. If the miner has over a threshold of power +// the miner meets the minimum. If the network is a below a threshold of +// miners and has power > zero the miner meets the minimum. +func (st *State) MinerNominalPowerMeetsConsensusMinimum(s adt.Store, miner addr.Address) (bool, error) { //nolint:deadcode,unused + claims, err := adt.AsMap(s, st.Claims, builtin.DefaultHamtBitwidth) + if err != nil { + return false, xerrors.Errorf("failed to load claims: %w", err) + } + + claim, ok, err := getClaim(claims, miner) + if err != nil { + return false, err + } + if !ok { + return false, xerrors.Errorf("no claim for actor %w", miner) + } + + return st.ClaimMeetsConsensusMinimums(claim) +} + +func (st *State) GetClaim(s adt.Store, a addr.Address) (*Claim, bool, error) { + claims, err := adt.AsMap(s, st.Claims, builtin.DefaultHamtBitwidth) + if err != nil { + return nil, false, xerrors.Errorf("failed to load claims: %w", err) + } + return getClaim(claims, a) +} + +func getClaim(claims *adt.Map, a addr.Address) (*Claim, bool, error) { + var out Claim + found, err := claims.Get(abi.AddrKey(a), &out) + if err != nil { + return nil, false, xerrors.Errorf("failed to get claim for address %v: %w", a, err) + } + if !found { + return nil, false, nil + } + return &out, true, nil +} diff --git a/builtin/v18/power/power_types.go b/builtin/v18/power/power_types.go new file mode 100644 index 00000000..ab80f52f --- /dev/null +++ b/builtin/v18/power/power_types.go @@ -0,0 +1,72 @@ +package power + +import ( + cbg "github.com/whyrusleeping/cbor-gen" + + addr "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/builtin/v18/util/smoothing" +) + +// Storage miner actor constructor params are defined here so the power actor can send them to the init actor +// to instantiate miners. +type MinerConstructorParams struct { + OwnerAddr addr.Address + WorkerAddr addr.Address + ControlAddrs []addr.Address + WindowPoStProofType abi.RegisteredPoStProof + PeerId abi.PeerID + Multiaddrs []abi.Multiaddrs +} + +type CreateMinerParams struct { + Owner addr.Address + Worker addr.Address + WindowPoStProofType abi.RegisteredPoStProof + Peer abi.PeerID + Multiaddrs []abi.Multiaddrs +} + +type CreateMinerReturn struct { + IDAddress addr.Address // The canonical ID-based address for the actor. + RobustAddress addr.Address // A more expensive but re-org-safe address for the newly created actor. +} + +type UpdateClaimedPowerParams struct { + RawByteDelta abi.StoragePower + QualityAdjustedDelta abi.StoragePower +} + +type EnrollCronEventParams struct { + EventEpoch abi.ChainEpoch + Payload []byte +} + +type CurrentTotalPowerReturn struct { + RawBytePower abi.StoragePower + QualityAdjPower abi.StoragePower + PledgeCollateral abi.TokenAmount + QualityAdjPowerSmoothed smoothing.FilterEstimate + RampStartEpoch int64 + RampDurationEpochs uint64 +} + +type NetworkRawPowerReturn = abi.StoragePower + +type MinerRawPowerParams = cbg.CborInt // abi.ActorID + +type MinerRawPowerReturn struct { + RawBytePower abi.StoragePower + MeetsConsensusMinimum bool +} + +type MinerCountReturn = cbg.CborInt + +type MinerConsensusCountReturn = cbg.CborInt + +type MinerPowerParams = cbg.CborInt // abi.ActorID + +type MinerPowerReturn struct { + RawBytePower abi.StoragePower + QualityAdjPower abi.StoragePower +} diff --git a/builtin/v18/power/power_types_test.go b/builtin/v18/power/power_types_test.go new file mode 100644 index 00000000..4a101e0f --- /dev/null +++ b/builtin/v18/power/power_types_test.go @@ -0,0 +1,59 @@ +package power + +import ( + "bytes" + "encoding/hex" + "testing" + + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/big" + "github.com/filecoin-project/go-state-types/builtin/v18/util/smoothing" + "github.com/stretchr/testify/require" +) + +// Test to match with Rust fil_actor_power::serialization +func TestSerializationCurrentTotalPowerReturn(t *testing.T) { + testCases := []struct { + params CurrentTotalPowerReturn + hex string + }{ + { + params: CurrentTotalPowerReturn{ + RawBytePower: abi.NewStoragePower(0), + QualityAdjPower: abi.NewStoragePower(0), + PledgeCollateral: abi.NewTokenAmount(0), + QualityAdjPowerSmoothed: smoothing.NewEstimate(big.Zero(), big.Zero()), + RampStartEpoch: 0, + RampDurationEpochs: 0, + }, + // [byte[],byte[],byte[],[byte[],byte[]],0,0] + hex: "864040408240400000", + }, + { + params: CurrentTotalPowerReturn{ + RawBytePower: abi.NewStoragePower(1 << 20), + QualityAdjPower: abi.NewStoragePower(1 << 21), + PledgeCollateral: abi.NewTokenAmount(1 << 22), + QualityAdjPowerSmoothed: smoothing.NewEstimate(big.NewInt(1<<23), big.NewInt(1<<24)), + RampStartEpoch: 25, + RampDurationEpochs: 26, + }, + // FilterEstimate BigInts have a precision shift of 128, so they end up larger than the others. + // [byte[00100000],byte[00200000],byte[00400000],[byte[0080000000000000000000000000000000000000],byte[000100000000000000000000000000000000000000]],25,26] + hex: "8644001000004400200000440040000082540080000000000000000000000000000000000000550001000000000000000000000000000000000000001819181a", + }, + } + + for _, tc := range testCases { + t.Run("", func(t *testing.T) { + req := require.New(t) + + var buf bytes.Buffer + req.NoError(tc.params.MarshalCBOR(&buf)) + req.Equal(tc.hex, hex.EncodeToString(buf.Bytes())) + var rt CurrentTotalPowerReturn + req.NoError(rt.UnmarshalCBOR(&buf)) + req.Equal(tc.params, rt) + }) + } +} diff --git a/builtin/v18/reward/cbor_gen.go b/builtin/v18/reward/cbor_gen.go new file mode 100644 index 00000000..568037e7 --- /dev/null +++ b/builtin/v18/reward/cbor_gen.go @@ -0,0 +1,451 @@ +// Code generated by github.com/whyrusleeping/cbor-gen. DO NOT EDIT. + +package reward + +import ( + "fmt" + "io" + "math" + "sort" + + abi "github.com/filecoin-project/go-state-types/abi" + cid "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" + xerrors "golang.org/x/xerrors" +) + +var _ = xerrors.Errorf +var _ = cid.Undef +var _ = math.E +var _ = sort.Sort + +var lengthBufState = []byte{139} + +func (t *State) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufState); err != nil { + return err + } + + // t.CumsumBaseline (big.Int) (struct) + if err := t.CumsumBaseline.MarshalCBOR(cw); err != nil { + return err + } + + // t.CumsumRealized (big.Int) (struct) + if err := t.CumsumRealized.MarshalCBOR(cw); err != nil { + return err + } + + // t.EffectiveNetworkTime (abi.ChainEpoch) (int64) + if t.EffectiveNetworkTime >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.EffectiveNetworkTime)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.EffectiveNetworkTime-1)); err != nil { + return err + } + } + + // t.EffectiveBaselinePower (big.Int) (struct) + if err := t.EffectiveBaselinePower.MarshalCBOR(cw); err != nil { + return err + } + + // t.ThisEpochReward (big.Int) (struct) + if err := t.ThisEpochReward.MarshalCBOR(cw); err != nil { + return err + } + + // t.ThisEpochRewardSmoothed (smoothing.FilterEstimate) (struct) + if err := t.ThisEpochRewardSmoothed.MarshalCBOR(cw); err != nil { + return err + } + + // t.ThisEpochBaselinePower (big.Int) (struct) + if err := t.ThisEpochBaselinePower.MarshalCBOR(cw); err != nil { + return err + } + + // t.Epoch (abi.ChainEpoch) (int64) + if t.Epoch >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Epoch)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.Epoch-1)); err != nil { + return err + } + } + + // t.TotalStoragePowerReward (big.Int) (struct) + if err := t.TotalStoragePowerReward.MarshalCBOR(cw); err != nil { + return err + } + + // t.SimpleTotal (big.Int) (struct) + if err := t.SimpleTotal.MarshalCBOR(cw); err != nil { + return err + } + + // t.BaselineTotal (big.Int) (struct) + if err := t.BaselineTotal.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *State) UnmarshalCBOR(r io.Reader) (err error) { + *t = State{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.CumsumBaseline (big.Int) (struct) + + { + + if err := t.CumsumBaseline.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.CumsumBaseline: %w", err) + } + + } + // t.CumsumRealized (big.Int) (struct) + + { + + if err := t.CumsumRealized.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.CumsumRealized: %w", err) + } + + } + // t.EffectiveNetworkTime (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.EffectiveNetworkTime = abi.ChainEpoch(extraI) + } + // t.EffectiveBaselinePower (big.Int) (struct) + + { + + if err := t.EffectiveBaselinePower.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.EffectiveBaselinePower: %w", err) + } + + } + // t.ThisEpochReward (big.Int) (struct) + + { + + if err := t.ThisEpochReward.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ThisEpochReward: %w", err) + } + + } + // t.ThisEpochRewardSmoothed (smoothing.FilterEstimate) (struct) + + { + + if err := t.ThisEpochRewardSmoothed.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ThisEpochRewardSmoothed: %w", err) + } + + } + // t.ThisEpochBaselinePower (big.Int) (struct) + + { + + if err := t.ThisEpochBaselinePower.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ThisEpochBaselinePower: %w", err) + } + + } + // t.Epoch (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.Epoch = abi.ChainEpoch(extraI) + } + // t.TotalStoragePowerReward (big.Int) (struct) + + { + + if err := t.TotalStoragePowerReward.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.TotalStoragePowerReward: %w", err) + } + + } + // t.SimpleTotal (big.Int) (struct) + + { + + if err := t.SimpleTotal.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.SimpleTotal: %w", err) + } + + } + // t.BaselineTotal (big.Int) (struct) + + { + + if err := t.BaselineTotal.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.BaselineTotal: %w", err) + } + + } + return nil +} + +var lengthBufThisEpochRewardReturn = []byte{130} + +func (t *ThisEpochRewardReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufThisEpochRewardReturn); err != nil { + return err + } + + // t.ThisEpochRewardSmoothed (smoothing.FilterEstimate) (struct) + if err := t.ThisEpochRewardSmoothed.MarshalCBOR(cw); err != nil { + return err + } + + // t.ThisEpochBaselinePower (big.Int) (struct) + if err := t.ThisEpochBaselinePower.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *ThisEpochRewardReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = ThisEpochRewardReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.ThisEpochRewardSmoothed (smoothing.FilterEstimate) (struct) + + { + + if err := t.ThisEpochRewardSmoothed.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ThisEpochRewardSmoothed: %w", err) + } + + } + // t.ThisEpochBaselinePower (big.Int) (struct) + + { + + if err := t.ThisEpochBaselinePower.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ThisEpochBaselinePower: %w", err) + } + + } + return nil +} + +var lengthBufAwardBlockRewardParams = []byte{132} + +func (t *AwardBlockRewardParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufAwardBlockRewardParams); err != nil { + return err + } + + // t.Miner (address.Address) (struct) + if err := t.Miner.MarshalCBOR(cw); err != nil { + return err + } + + // t.Penalty (big.Int) (struct) + if err := t.Penalty.MarshalCBOR(cw); err != nil { + return err + } + + // t.GasReward (big.Int) (struct) + if err := t.GasReward.MarshalCBOR(cw); err != nil { + return err + } + + // t.WinCount (int64) (int64) + if t.WinCount >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.WinCount)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.WinCount-1)); err != nil { + return err + } + } + + return nil +} + +func (t *AwardBlockRewardParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = AwardBlockRewardParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 4 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Miner (address.Address) (struct) + + { + + if err := t.Miner.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Miner: %w", err) + } + + } + // t.Penalty (big.Int) (struct) + + { + + if err := t.Penalty.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Penalty: %w", err) + } + + } + // t.GasReward (big.Int) (struct) + + { + + if err := t.GasReward.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.GasReward: %w", err) + } + + } + // t.WinCount (int64) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.WinCount = int64(extraI) + } + return nil +} diff --git a/builtin/v18/reward/invariants.go b/builtin/v18/reward/invariants.go new file mode 100644 index 00000000..0df84141 --- /dev/null +++ b/builtin/v18/reward/invariants.go @@ -0,0 +1,29 @@ +package reward + +import ( + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/big" + "github.com/filecoin-project/go-state-types/builtin" + "github.com/filecoin-project/go-state-types/builtin/v18/util/adt" +) + +type StateSummary struct{} + +var FIL = big.NewInt(1e18) +var StorageMiningAllocationCheck = big.Mul(big.NewInt(1_100_000_000), FIL) + +func CheckStateInvariants(st *State, _ adt.Store, priorEpoch abi.ChainEpoch, balance abi.TokenAmount) (*StateSummary, *builtin.MessageAccumulator) { + acc := &builtin.MessageAccumulator{} + + // Can't assert equality because anyone can send funds to reward actor (and already have on mainnet) + acc.Require(big.Add(st.TotalStoragePowerReward, balance).GreaterThanEqual(StorageMiningAllocationCheck), "reward given %v + reward left %v < storage mining allocation %v", st.TotalStoragePowerReward, balance, StorageMiningAllocationCheck) + + acc.Require(st.Epoch == priorEpoch+1, "reward state epoch %d does not match priorEpoch+1 %d", st.Epoch, priorEpoch+1) + acc.Require(st.EffectiveNetworkTime <= st.Epoch, "effective network time greater than state epoch") + + acc.Require(st.CumsumRealized.LessThanEqual(st.CumsumBaseline), "cumsum realized > cumsum baseline") + acc.Require(st.CumsumRealized.GreaterThanEqual(big.Zero()), "cumsum realized < 0") + acc.Require(st.EffectiveBaselinePower.LessThanEqual(st.ThisEpochBaselinePower), "effective baseline power > baseline power") + + return &StateSummary{}, acc +} diff --git a/builtin/v18/reward/methods.go b/builtin/v18/reward/methods.go new file mode 100644 index 00000000..b0d043e5 --- /dev/null +++ b/builtin/v18/reward/methods.go @@ -0,0 +1,13 @@ +package reward + +import ( + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/builtin" +) + +var Methods = map[abi.MethodNum]builtin.MethodMeta{ + 1: builtin.NewMethodMeta("Constructor", *new(func(*abi.StoragePower) *abi.EmptyValue)), // Constructor + 2: builtin.NewMethodMeta("AwardBlockReward", *new(func(*AwardBlockRewardParams) *abi.EmptyValue)), // AwardBlockReward + 3: builtin.NewMethodMeta("ThisEpochReward", *new(func(*abi.EmptyValue) *ThisEpochRewardReturn)), // ThisEpochReward + 4: builtin.NewMethodMeta("UpdateNetworkKPI", *new(func(*abi.StoragePower) *abi.EmptyValue)), // UpdateNetworkKPI +} diff --git a/builtin/v18/reward/reward_logic.go b/builtin/v18/reward/reward_logic.go new file mode 100644 index 00000000..bbbe1a4e --- /dev/null +++ b/builtin/v18/reward/reward_logic.go @@ -0,0 +1,105 @@ +package reward + +import ( + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/big" + "github.com/filecoin-project/go-state-types/builtin/v18/util/math" +) + +// Baseline function = BaselineInitialValue * (BaselineExponent) ^(t), t in epochs +// Note: we compute exponential iteratively using recurrence e(n) = e * e(n-1). +// Caller of baseline power function is responsible for keeping track of intermediate, +// state e(n-1), the baseline power function just does the next multiplication + +// Floor(e^(ln[1 + 100%] / epochsInYear) * 2^128 +// Q.128 formatted number such that f(epoch) = baseExponent^epoch grows 100% in one year of epochs +// Calculation here: https://www.wolframalpha.com/input/?i=IntegerPart%5BExp%5BLog%5B1%2B100%25%5D%2F%28%28365+days%29%2F%2830+seconds%29%29%5D*2%5E128%5D +var BaselineExponent = big.MustFromString("340282591298641078465964189926313473653") // Q.128 + +// 2.5057116798121726 EiB +var BaselineInitialValue = big.NewInt(2_888_888_880_000_000_000) // Q.0 + +// Initialize baseline power for epoch -1 so that baseline power at epoch 0 is +// BaselineInitialValue. +func InitBaselinePower() abi.StoragePower { + baselineInitialValue256 := big.Lsh(BaselineInitialValue, 2*math.Precision128) // Q.0 => Q.256 + baselineAtMinusOne := big.Div(baselineInitialValue256, BaselineExponent) // Q.256 / Q.128 => Q.128 + return big.Rsh(baselineAtMinusOne, math.Precision128) // Q.128 => Q.0 +} + +// Compute BaselinePower(t) from BaselinePower(t-1) with an additional multiplication +// of the base exponent. +func BaselinePowerFromPrev(prevEpochBaselinePower abi.StoragePower) abi.StoragePower { + thisEpochBaselinePower := big.Mul(prevEpochBaselinePower, BaselineExponent) // Q.0 * Q.128 => Q.128 + return big.Rsh(thisEpochBaselinePower, math.Precision128) // Q.128 => Q.0 +} + +// These numbers are estimates of the onchain constants. They are good for initializing state in +// devnets and testing but will not match the on chain values exactly which depend on storage onboarding +// and upgrade epoch history. They are in units of attoFIL, 10^-18 FIL +var DefaultSimpleTotal = big.Mul(big.NewInt(330e6), big.NewInt(1e18)) // 330M +var DefaultBaselineTotal = big.Mul(big.NewInt(770e6), big.NewInt(1e18)) // 770M + +// Computes RewardTheta which is is precise fractional value of effectiveNetworkTime. +// The effectiveNetworkTime is defined by CumsumBaselinePower(theta) == CumsumRealizedPower +// As baseline power is defined over integers and the RewardTheta is required to be fractional, +// we perform linear interpolation between CumsumBaseline(⌊theta⌋) and CumsumBaseline(⌈theta⌉). +// The effectiveNetworkTime argument is ceiling of theta. +// The result is a fractional effectiveNetworkTime (theta) in Q.128 format. +func ComputeRTheta(effectiveNetworkTime abi.ChainEpoch, baselinePowerAtEffectiveNetworkTime, cumsumRealized, cumsumBaseline big.Int) big.Int { + var rewardTheta big.Int + if effectiveNetworkTime != 0 { + rewardTheta = big.NewInt(int64(effectiveNetworkTime)) // Q.0 + rewardTheta = big.Lsh(rewardTheta, math.Precision128) // Q.0 => Q.128 + diff := big.Sub(cumsumBaseline, cumsumRealized) + diff = big.Lsh(diff, math.Precision128) // Q.0 => Q.128 + diff = big.Div(diff, baselinePowerAtEffectiveNetworkTime) // Q.128 / Q.0 => Q.128 + rewardTheta = big.Sub(rewardTheta, diff) // Q.128 + } else { + // special case for initialization + rewardTheta = big.Zero() + } + return rewardTheta +} + +var ( + // lambda = ln(2) / (6 * epochsInYear) + // for Q.128: int(lambda * 2^128) + // Calculation here: https://www.wolframalpha.com/input/?i=IntegerPart%5BLog%5B2%5D+%2F+%286+*+%281+year+%2F+30+seconds%29%29+*+2%5E128%5D + Lambda = big.MustFromString("37396271439864487274534522888786") + // expLamSubOne = e^lambda - 1 + // for Q.128: int(expLamSubOne * 2^128) + // Calculation here: https://www.wolframalpha.com/input/?i=IntegerPart%5B%5BExp%5BLog%5B2%5D+%2F+%286+*+%281+year+%2F+30+seconds%29%29%5D+-+1%5D+*+2%5E128%5D + ExpLamSubOne = big.MustFromString("37396273494747879394193016954629") +) + +// Computes a reward for all expected leaders when effective network time changes from prevTheta to currTheta +// Inputs are in Q.128 format +func computeReward(epoch abi.ChainEpoch, prevTheta, currTheta, simpleTotal, baselineTotal big.Int) abi.TokenAmount { + simpleReward := big.Mul(simpleTotal, ExpLamSubOne) //Q.0 * Q.128 => Q.128 + epochLam := big.Mul(big.NewInt(int64(epoch)), Lambda) // Q.0 * Q.128 => Q.128 + + simpleReward = big.Mul(simpleReward, big.NewFromGo(math.ExpNeg(epochLam.Int))) // Q.128 * Q.128 => Q.256 + simpleReward = big.Rsh(simpleReward, math.Precision128) // Q.256 >> 128 => Q.128 + + baselineReward := big.Sub(computeBaselineSupply(currTheta, baselineTotal), computeBaselineSupply(prevTheta, baselineTotal)) // Q.128 + + reward := big.Add(simpleReward, baselineReward) // Q.128 + + return big.Rsh(reward, math.Precision128) // Q.128 => Q.0 +} + +// Computes baseline supply based on theta in Q.128 format. +// Return is in Q.128 format +func computeBaselineSupply(theta, baselineTotal big.Int) big.Int { + thetaLam := big.Mul(theta, Lambda) // Q.128 * Q.128 => Q.256 + thetaLam = big.Rsh(thetaLam, math.Precision128) // Q.256 >> 128 => Q.128 + + eTL := big.NewFromGo(math.ExpNeg(thetaLam.Int)) // Q.128 + + one := big.NewInt(1) + one = big.Lsh(one, math.Precision128) // Q.0 => Q.128 + oneSub := big.Sub(one, eTL) // Q.128 + + return big.Mul(baselineTotal, oneSub) // Q.0 * Q.128 => Q.128 +} diff --git a/builtin/v18/reward/reward_state.go b/builtin/v18/reward/reward_state.go new file mode 100644 index 00000000..2dab0dd9 --- /dev/null +++ b/builtin/v18/reward/reward_state.go @@ -0,0 +1,112 @@ +package reward + +import ( + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/big" + "github.com/filecoin-project/go-state-types/builtin/v18/util/smoothing" +) + +// A quantity of space * time (in byte-epochs) representing power committed to the network for some duration. +type Spacetime = big.Int + +// 36.266260308195979333 FIL +// https://www.wolframalpha.com/input/?i=IntegerPart%5B330%2C000%2C000+*+%281+-+Exp%5B-Log%5B2%5D+%2F+%286+*+%281+year+%2F+30+seconds%29%29%5D%29+*+10%5E18%5D +const InitialRewardPositionEstimateStr = "36266260308195979333" + +var InitialRewardPositionEstimate = big.MustFromString(InitialRewardPositionEstimateStr) + +// -1.0982489*10^-7 FIL per epoch. Change of simple minted tokens between epochs 0 and 1 +// https://www.wolframalpha.com/input/?i=IntegerPart%5B%28Exp%5B-Log%5B2%5D+%2F+%286+*+%281+year+%2F+30+seconds%29%29%5D+-+1%29+*+10%5E18%5D +var InitialRewardVelocityEstimate = abi.NewTokenAmount(-109897758509) + +// Changed since v0: +// - ThisEpochRewardSmoothed is not a pointer +type State struct { + // CumsumBaseline is a target CumsumRealized needs to reach for EffectiveNetworkTime to increase + // CumsumBaseline and CumsumRealized are expressed in byte-epochs. + CumsumBaseline Spacetime + + // CumsumRealized is cumulative sum of network power capped by BaselinePower(epoch) + CumsumRealized Spacetime + + // EffectiveNetworkTime is ceiling of real effective network time `theta` based on + // CumsumBaselinePower(theta) == CumsumRealizedPower + // Theta captures the notion of how much the network has progressed in its baseline + // and in advancing network time. + EffectiveNetworkTime abi.ChainEpoch + + // EffectiveBaselinePower is the baseline power at the EffectiveNetworkTime epoch + EffectiveBaselinePower abi.StoragePower + + // The reward to be paid in per WinCount to block producers. + // The actual reward total paid out depends on the number of winners in any round. + // This value is recomputed every non-null epoch and used in the next non-null epoch. + ThisEpochReward abi.TokenAmount + // Smoothed ThisEpochReward + ThisEpochRewardSmoothed smoothing.FilterEstimate + + // The baseline power the network is targeting at st.Epoch + ThisEpochBaselinePower abi.StoragePower + + // Epoch tracks for which epoch the Reward was computed + Epoch abi.ChainEpoch + + // TotalStoragePowerReward tracks the total FIL awarded to block miners + TotalStoragePowerReward abi.TokenAmount + + // Simple and Baseline totals are constants used for computing rewards. + // They are on chain because of a historical fix resetting baseline value + // in a way that depended on the history leading immediately up to the + // migration fixing the value. These values can be moved from state back + // into a code constant in a subsequent upgrade. + SimpleTotal abi.TokenAmount + BaselineTotal abi.TokenAmount +} + +func ConstructState(currRealizedPower abi.StoragePower) *State { + st := &State{ + CumsumBaseline: big.Zero(), + CumsumRealized: big.Zero(), + EffectiveNetworkTime: 0, + EffectiveBaselinePower: BaselineInitialValue, + + ThisEpochReward: big.Zero(), + ThisEpochBaselinePower: InitBaselinePower(), + Epoch: -1, + + ThisEpochRewardSmoothed: smoothing.NewEstimate(InitialRewardPositionEstimate, InitialRewardVelocityEstimate), + TotalStoragePowerReward: big.Zero(), + + SimpleTotal: DefaultSimpleTotal, + BaselineTotal: DefaultBaselineTotal, + } + + st.updateToNextEpochWithReward(currRealizedPower) + + return st +} + +// Takes in current realized power and updates internal state +// Used for update of internal state during null rounds +func (st *State) updateToNextEpoch(currRealizedPower abi.StoragePower) { + st.Epoch++ + st.ThisEpochBaselinePower = BaselinePowerFromPrev(st.ThisEpochBaselinePower) + cappedRealizedPower := big.Min(st.ThisEpochBaselinePower, currRealizedPower) + st.CumsumRealized = big.Add(st.CumsumRealized, cappedRealizedPower) + + for st.CumsumRealized.GreaterThan(st.CumsumBaseline) { + st.EffectiveNetworkTime++ + st.EffectiveBaselinePower = BaselinePowerFromPrev(st.EffectiveBaselinePower) + st.CumsumBaseline = big.Add(st.CumsumBaseline, st.EffectiveBaselinePower) + } +} + +// Takes in a current realized power for a reward epoch and computes +// and updates reward state to track reward for the next epoch +func (st *State) updateToNextEpochWithReward(currRealizedPower abi.StoragePower) { + prevRewardTheta := ComputeRTheta(st.EffectiveNetworkTime, st.EffectiveBaselinePower, st.CumsumRealized, st.CumsumBaseline) + st.updateToNextEpoch(currRealizedPower) + currRewardTheta := ComputeRTheta(st.EffectiveNetworkTime, st.EffectiveBaselinePower, st.CumsumRealized, st.CumsumBaseline) + + st.ThisEpochReward = computeReward(st.Epoch, prevRewardTheta, currRewardTheta, st.SimpleTotal, st.BaselineTotal) +} diff --git a/builtin/v18/reward/reward_types.go b/builtin/v18/reward/reward_types.go new file mode 100644 index 00000000..36bb61e0 --- /dev/null +++ b/builtin/v18/reward/reward_types.go @@ -0,0 +1,19 @@ +package reward + +import ( + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/builtin/v18/util/smoothing" +) + +type AwardBlockRewardParams struct { + Miner address.Address + Penalty abi.TokenAmount // penalty for including bad messages in a block, >= 0 + GasReward abi.TokenAmount // gas reward from all gas fees in a block, >= 0 + WinCount int64 // number of reward units won, > 0 +} + +type ThisEpochRewardReturn struct { + ThisEpochRewardSmoothed smoothing.FilterEstimate + ThisEpochBaselinePower abi.StoragePower +} diff --git a/builtin/v18/system/cbor_gen.go b/builtin/v18/system/cbor_gen.go new file mode 100644 index 00000000..923f631b --- /dev/null +++ b/builtin/v18/system/cbor_gen.go @@ -0,0 +1,80 @@ +// Code generated by github.com/whyrusleeping/cbor-gen. DO NOT EDIT. + +package system + +import ( + "fmt" + "io" + "math" + "sort" + + cid "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" + xerrors "golang.org/x/xerrors" +) + +var _ = xerrors.Errorf +var _ = cid.Undef +var _ = math.E +var _ = sort.Sort + +var lengthBufState = []byte{129} + +func (t *State) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufState); err != nil { + return err + } + + // t.BuiltinActors (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.BuiltinActors); err != nil { + return xerrors.Errorf("failed to write cid field t.BuiltinActors: %w", err) + } + + return nil +} + +func (t *State) UnmarshalCBOR(r io.Reader) (err error) { + *t = State{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.BuiltinActors (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.BuiltinActors: %w", err) + } + + t.BuiltinActors = c + + } + return nil +} diff --git a/builtin/v18/system/methods.go b/builtin/v18/system/methods.go new file mode 100644 index 00000000..22e7cf89 --- /dev/null +++ b/builtin/v18/system/methods.go @@ -0,0 +1,10 @@ +package system + +import ( + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/builtin" +) + +var Methods = map[abi.MethodNum]builtin.MethodMeta{ + 1: builtin.NewMethodMeta("Constructor", *new(func(*abi.EmptyValue) *abi.EmptyValue)), // Constructor +} diff --git a/builtin/v18/system/system_actor_state.go b/builtin/v18/system/system_actor_state.go new file mode 100644 index 00000000..fea9ab24 --- /dev/null +++ b/builtin/v18/system/system_actor_state.go @@ -0,0 +1,24 @@ +package system + +import ( + "context" + + "github.com/ipfs/go-cid" + "golang.org/x/xerrors" + + "github.com/filecoin-project/go-state-types/builtin/v18/util/adt" + "github.com/filecoin-project/go-state-types/manifest" +) + +type State struct { + BuiltinActors cid.Cid // ManifestData +} + +func ConstructState(store adt.Store) (*State, error) { + empty, err := store.Put(context.TODO(), &manifest.ManifestData{}) + if err != nil { + return nil, xerrors.Errorf("failed to create empty manifest: %w", err) + } + + return &State{BuiltinActors: empty}, nil +} diff --git a/builtin/v18/util/adt/array.go b/builtin/v18/util/adt/array.go new file mode 100644 index 00000000..3d7cde17 --- /dev/null +++ b/builtin/v18/util/adt/array.go @@ -0,0 +1,153 @@ +package adt + +import ( + "bytes" + + cid "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" + "golang.org/x/xerrors" + + amt "github.com/filecoin-project/go-amt-ipld/v4" + "github.com/filecoin-project/go-state-types/cbor" +) + +var DefaultAmtOptions = []amt.Option{} + +// Array stores a sparse sequence of values in an AMT. +type Array struct { + root *amt.Root + store Store +} + +// AsArray interprets a store as an AMT-based array with root `r`. +func AsArray(s Store, r cid.Cid, bitwidth int) (*Array, error) { + options := append(DefaultAmtOptions, amt.UseTreeBitWidth(uint(bitwidth))) + root, err := amt.LoadAMT(s.Context(), s, r, options...) + if err != nil { + return nil, xerrors.Errorf("failed to root: %w", err) + } + + return &Array{ + root: root, + store: s, + }, nil +} + +// Creates a new array backed by an empty AMT. +func MakeEmptyArray(s Store, bitwidth int) (*Array, error) { + options := append(DefaultAmtOptions, amt.UseTreeBitWidth(uint(bitwidth))) + root, err := amt.NewAMT(s, options...) + if err != nil { + return nil, err + } + return &Array{ + root: root, + store: s, + }, nil +} + +// Writes a new empty array to the store, returning its CID. +func StoreEmptyArray(s Store, bitwidth int) (cid.Cid, error) { + arr, err := MakeEmptyArray(s, bitwidth) + if err != nil { + return cid.Undef, err + } + return arr.Root() +} + +// Returns the root CID of the underlying AMT. +func (a *Array) Root() (cid.Cid, error) { + return a.root.Flush(a.store.Context()) +} + +// Appends a value to the end of the array. Assumes continuous array. +// If the array isn't continuous use Set and a separate counter +func (a *Array) AppendContinuous(value cbor.Marshaler) error { + if err := a.root.Set(a.store.Context(), a.root.Len(), value); err != nil { + return xerrors.Errorf("append failed to set index %v value %v in root %v: %w", a.root.Len(), value, a.root, err) + } + return nil +} + +func (a *Array) Set(i uint64, value cbor.Marshaler) error { + if err := a.root.Set(a.store.Context(), i, value); err != nil { + return xerrors.Errorf("failed to set index %v value %v in root %v: %w", i, value, a.root, err) + } + return nil +} + +// Removes the value at index `i` from the AMT, if it exists. +// Returns whether the index was previously present. +func (a *Array) TryDelete(i uint64) (bool, error) { + if found, err := a.root.Delete(a.store.Context(), i); err != nil { + return false, xerrors.Errorf("array delete failed to delete index %v in root %v: %w", i, a.root, err) + } else { + return found, nil + } +} + +// Removes the value at index `i` from the AMT, expecting it to exist. +func (a *Array) Delete(i uint64) error { + if found, err := a.root.Delete(a.store.Context(), i); err != nil { + return xerrors.Errorf("failed to delete index %v in root %v: %w", i, a.root, err) + } else if !found { + return xerrors.Errorf("no such index %v in root %v to delete: %w", i, a.root, err) + } + return nil +} + +func (a *Array) BatchDelete(ix []uint64, strict bool) error { + if _, err := a.root.BatchDelete(a.store.Context(), ix, strict); err != nil { + return xerrors.Errorf("failed to batch delete keys %v: %w", ix, err) + } + return nil +} + +// Iterates all entries in the array, deserializing each value in turn into `out` and then calling a function. +// Iteration halts if the function returns an error. +// If the output parameter is nil, deserialization is skipped. +func (a *Array) ForEach(out cbor.Unmarshaler, fn func(i int64) error) error { + return a.root.ForEach(a.store.Context(), func(k uint64, val *cbg.Deferred) error { + if out != nil { + if deferred, ok := out.(*cbg.Deferred); ok { + // fast-path deferred -> deferred to avoid re-decoding. + *deferred = *val + } else if err := out.UnmarshalCBOR(bytes.NewReader(val.Raw)); err != nil { + return err + } + } + return fn(int64(k)) + }) +} + +func (a *Array) Length() uint64 { + return a.root.Len() +} + +// Get retrieves array element into the 'out' unmarshaler, returning a boolean +// +// indicating whether the element was found in the array +func (a *Array) Get(k uint64, out cbor.Unmarshaler) (bool, error) { + if found, err := a.root.Get(a.store.Context(), k, out); err != nil { + return false, xerrors.Errorf("failed to get index %v in root %v: %w", k, a.root, err) + } else { + return found, nil + } +} + +// Retrieves an array value into the 'out' unmarshaler (if non-nil), and removes the entry. +// Returns a boolean indicating whether the element was previously in the array. +func (a *Array) Pop(k uint64, out cbor.Unmarshaler) (bool, error) { + if found, err := a.root.Get(a.store.Context(), k, out); err != nil { + return false, xerrors.Errorf("failed to get index %v in root %v: %w", k, a.root, err) + } else if !found { + return false, nil + } + + if found, err := a.root.Delete(a.store.Context(), k); err != nil { + return false, xerrors.Errorf("failed to delete index %v in root %v: %w", k, a.root, err) + } else if !found { + return false, xerrors.Errorf("can't find index %v to delete in root %v", k, a.root) + } + return true, nil +} diff --git a/builtin/v18/util/adt/balancetable.go b/builtin/v18/util/adt/balancetable.go new file mode 100644 index 00000000..921d733d --- /dev/null +++ b/builtin/v18/util/adt/balancetable.go @@ -0,0 +1,52 @@ +package adt + +import ( + cid "github.com/ipfs/go-cid" + + addr "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/big" +) + +// Bitwidth of balance table HAMTs, determined empirically from mutation +// patterns and projections of mainnet data +const BalanceTableBitwidth = 6 + +// A specialization of a map of addresses to (positive) token amounts. +// Absent keys implicitly have a balance of zero. +type BalanceTable Map + +// Interprets a store as balance table with root `r`. +func AsBalanceTable(s Store, r cid.Cid) (*BalanceTable, error) { + m, err := AsMap(s, r, BalanceTableBitwidth) + if err != nil { + return nil, err + } + + return &BalanceTable{ + root: m.root, + store: s, + }, nil +} + +// Gets the balance for a key, which is zero if they key has never been added to. +func (t *BalanceTable) Get(key addr.Address) (abi.TokenAmount, error) { + var value abi.TokenAmount + found, err := (*Map)(t).Get(abi.AddrKey(key), &value) + if !found || err != nil { + value = big.Zero() + } + + return value, err +} + +// Returns the total balance held by this BalanceTable +func (t *BalanceTable) Total() (abi.TokenAmount, error) { + total := big.Zero() + var cur abi.TokenAmount + err := (*Map)(t).ForEach(&cur, func(key string) error { + total = big.Add(total, cur) + return nil + }) + return total, err +} diff --git a/builtin/v18/util/adt/map.go b/builtin/v18/util/adt/map.go new file mode 100644 index 00000000..9037410d --- /dev/null +++ b/builtin/v18/util/adt/map.go @@ -0,0 +1,211 @@ +package adt + +import ( + "bytes" + "crypto/sha256" + "errors" + "io" + + cid "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" + "golang.org/x/xerrors" + + hamt "github.com/filecoin-project/go-hamt-ipld/v3" + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/cbor" +) + +// DefaultHamtOptions specifies default options used to construct Filecoin HAMTs. +// Specific HAMT instances may specify additional options, especially the bitwidth. +var DefaultHamtOptions = []hamt.Option{ + hamt.UseHashFunction(func(input []byte) []byte { + res := sha256.Sum256(input) + return res[:] + }), +} + +// Map stores key-value pairs in a HAMT. +type Map struct { + lastCid cid.Cid + root *hamt.Node + store Store +} + +func (m *Map) MarshalCBOR(w io.Writer) error { + rootCid, err := m.Root() + if err != nil { + return xerrors.Errorf("failed to flush map: %w", err) + } + + cborCid := cbg.CborCid(rootCid) + return cborCid.MarshalCBOR(w) +} + +// AsMap interprets a store as a HAMT-based map with root `r`. +// The HAMT is interpreted with branching factor 2^bitwidth. +// We could drop this parameter if https://github.com/filecoin-project/go-hamt-ipld/issues/79 is implemented. +func AsMap(s Store, root cid.Cid, bitwidth int) (*Map, error) { + options := append(DefaultHamtOptions, hamt.UseTreeBitWidth(bitwidth)) + nd, err := hamt.LoadNode(s.Context(), s, root, options...) + if err != nil { + return nil, xerrors.Errorf("failed to load hamt node: %w", err) + } + + return &Map{ + lastCid: root, + root: nd, + store: s, + }, nil +} + +// Creates a new map backed by an empty HAMT. +func MakeEmptyMap(s Store, bitwidth int) (*Map, error) { + options := append(DefaultHamtOptions, hamt.UseTreeBitWidth(bitwidth)) + nd, err := hamt.NewNode(s, options...) + if err != nil { + return nil, err + } + return &Map{ + lastCid: cid.Undef, + root: nd, + store: s, + }, nil +} + +// Creates and stores a new empty map, returning its CID. +func StoreEmptyMap(s Store, bitwidth int) (cid.Cid, error) { + m, err := MakeEmptyMap(s, bitwidth) + if err != nil { + return cid.Undef, err + } + return m.Root() +} + +// Returns the root cid of underlying HAMT. +func (m *Map) Root() (cid.Cid, error) { + if err := m.root.Flush(m.store.Context()); err != nil { + return cid.Undef, xerrors.Errorf("failed to flush map root: %w", err) + } + + c, err := m.store.Put(m.store.Context(), m.root) + if err != nil { + return cid.Undef, xerrors.Errorf("writing map root object: %w", err) + } + m.lastCid = c + + return c, nil +} + +// Put adds value `v` with key `k` to the hamt store. +func (m *Map) Put(k abi.Keyer, v cbor.Marshaler) error { + if err := m.root.Set(m.store.Context(), k.Key(), v); err != nil { + return xerrors.Errorf("failed to set key %v value %v in node %v: %w", k.Key(), v, m.lastCid, err) + } + return nil +} + +// Get retrieves the value at `k` into `out`, if the `k` is present and `out` is non-nil. +// Returns whether the key was found. +func (m *Map) Get(k abi.Keyer, out cbor.Unmarshaler) (bool, error) { + if found, err := m.root.Find(m.store.Context(), k.Key(), out); err != nil { + return false, xerrors.Errorf("failed to get key %v in node %v: %w", m.lastCid, k.Key(), err) + } else { + return found, nil + } +} + +// Has checks for the existence of a key without deserializing its value. +func (m *Map) Has(k abi.Keyer) (bool, error) { + if found, err := m.root.Find(m.store.Context(), k.Key(), nil); err != nil { + return false, xerrors.Errorf("failed to check key %v in node %v: %w", m.lastCid, k.Key(), err) + } else { + return found, nil + } +} + +// Sets key key `k` to value `v` iff the key is not already present. +func (m *Map) PutIfAbsent(k abi.Keyer, v cbor.Marshaler) (bool, error) { + if modified, err := m.root.SetIfAbsent(m.store.Context(), k.Key(), v); err != nil { + return false, xerrors.Errorf("failed to set key %v value %v in node %v: %w", k.Key(), v, m.lastCid, err) + } else { + return modified, nil + } +} + +// Removes the value at `k` from the hamt store, if it exists. +// Returns whether the key was previously present. +func (m *Map) TryDelete(k abi.Keyer) (bool, error) { + if found, err := m.root.Delete(m.store.Context(), k.Key()); err != nil { + return false, xerrors.Errorf("failed to delete key %v in node %v: %v", k.Key(), m.root, err) + } else { + return found, nil + } +} + +// Removes the value at `k` from the hamt store, expecting it to exist. +func (m *Map) Delete(k abi.Keyer) error { + if found, err := m.root.Delete(m.store.Context(), k.Key()); err != nil { + return xerrors.Errorf("failed to delete key %v in node %v: %v", k.Key(), m.root, err) + } else if !found { + return xerrors.Errorf("no such key %v to delete in node %v", k.Key(), m.root) + } + return nil +} + +// Iterates all entries in the map, deserializing each value in turn into `out` and then +// calling a function with the corresponding key. +// Iteration halts if the function returns an error. +// If the output parameter is nil, deserialization is skipped. +func (m *Map) ForEach(out cbor.Unmarshaler, fn func(key string) error) error { + return m.root.ForEach(m.store.Context(), func(k string, val *cbg.Deferred) error { + if out != nil { + // Why doesn't hamt.ForEach() just return the value as bytes? + err := out.UnmarshalCBOR(bytes.NewReader(val.Raw)) + if err != nil { + return err + } + } + return fn(k) + }) +} + +// Collects all the keys from the map into a slice of strings. +func (m *Map) CollectKeys() (out []string, err error) { + err = m.ForEach(nil, func(key string) error { + out = append(out, key) + return nil + }) + return +} + +// Retrieves the value for `k` into the 'out' unmarshaler (if non-nil), and removes the entry. +// Returns a boolean indicating whether the element was previously in the map. +func (m *Map) Pop(k abi.Keyer, out cbor.Unmarshaler) (bool, error) { + key := k.Key() + if found, err := m.root.Find(m.store.Context(), key, out); err != nil || !found { + return found, err + } + + if found, err := m.root.Delete(m.store.Context(), key); err != nil { + return false, err + } else if !found { + return false, xerrors.Errorf("failed to find key %v to delete", k.Key()) + } + return true, nil +} + +// IsEmpty returns false if there are any elements in the Map, true otherwise. +func (m *Map) IsEmpty() (bool, error) { + var errItemFound = errors.New("item found") + err := m.ForEach(nil, func(k string) error { + return errItemFound + }) + + if err == errItemFound { + return false, nil + } else if err != nil { + return false, xerrors.Errorf("failed to iterate over map: %w", err) + } + + return true, nil +} diff --git a/builtin/v18/util/adt/map_test.go b/builtin/v18/util/adt/map_test.go new file mode 100644 index 00000000..5fe0188d --- /dev/null +++ b/builtin/v18/util/adt/map_test.go @@ -0,0 +1,29 @@ +package adt + +import ( + "context" + "testing" + + "github.com/filecoin-project/go-state-types/abi" + + "github.com/filecoin-project/go-state-types/test_util" + cbor "github.com/ipfs/go-ipld-cbor" + + "github.com/stretchr/testify/require" +) + +func TestIsEmpty(t *testing.T) { + m, err := MakeEmptyMap(WrapStore(context.Background(), cbor.NewCborStore(test_util.NewBlockStoreInMemory())), 5) + require.NoError(t, err) + + isEmpty, err := m.IsEmpty() + require.NoError(t, err) + require.True(t, isEmpty) + + val := abi.CborString("val") + require.NoError(t, m.Put(abi.IntKey(5), &val)) + + isEmpty, err = m.IsEmpty() + require.NoError(t, err) + require.False(t, isEmpty) +} diff --git a/builtin/v18/util/adt/multimap.go b/builtin/v18/util/adt/multimap.go new file mode 100644 index 00000000..b3b17c55 --- /dev/null +++ b/builtin/v18/util/adt/multimap.go @@ -0,0 +1,64 @@ +package adt + +import ( + "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" +) + +// Multimap stores multiple values per key in a HAMT of AMTs. +// The order of insertion of values for each key is retained. +type Multimap struct { + mp *Map + innerBitwidth int +} + +// Interprets a store as a HAMT-based map of AMTs with root `r`. +// The outer map is interpreted with a branching factor of 2^bitwidth. +func AsMultimap(s Store, r cid.Cid, outerBitwidth, innerBitwidth int) (*Multimap, error) { + m, err := AsMap(s, r, outerBitwidth) + if err != nil { + return nil, err + } + + return &Multimap{m, innerBitwidth}, nil +} + +// Creates a new map backed by an empty HAMT and flushes it to the store. +// The outer map has a branching factor of 2^bitwidth. +func MakeEmptyMultimap(s Store, outerBitwidth, innerBitwidth int) (*Multimap, error) { + m, err := MakeEmptyMap(s, outerBitwidth) + if err != nil { + return nil, err + } + return &Multimap{m, innerBitwidth}, nil +} + +// Creates and stores a new empty multimap, returning its CID. +func StoreEmptyMultimap(store Store, outerBitwidth, innerBitwidth int) (cid.Cid, error) { + mmap, err := MakeEmptyMultimap(store, outerBitwidth, innerBitwidth) + if err != nil { + return cid.Undef, err + } + return mmap.Root() +} + +// Returns the root cid of the underlying HAMT. +func (mm *Multimap) Root() (cid.Cid, error) { + return mm.mp.Root() +} + +func (mm *Multimap) ForAll(fn func(k string, arr *Array) error) error { + var arrRoot cbg.CborCid + if err := mm.mp.ForEach(&arrRoot, func(k string) error { + arr, err := AsArray(mm.mp.store, cid.Cid(arrRoot), mm.innerBitwidth) + if err != nil { + return err + } + + return fn(k, arr) + }); err != nil { + return err + } + + return nil +} diff --git a/builtin/v18/util/adt/set.go b/builtin/v18/util/adt/set.go new file mode 100644 index 00000000..123e7d93 --- /dev/null +++ b/builtin/v18/util/adt/set.go @@ -0,0 +1,74 @@ +// Ported from specs-actors: https://github.com/filecoin-project/specs-actors/blob/845089a6d2580e46055c24415a6c32ee688e5186/actors/util/adt/set.go#L8 + +package adt + +import ( + "github.com/ipfs/go-cid" + + "github.com/filecoin-project/go-state-types/abi" +) + +// Set interprets a Map as a set, storing keys (with empty values) in a HAMT. +type Set struct { + m *Map +} + +// AsSet interprets a store as a HAMT-based set with root `r`. +// The HAMT is interpreted with branching factor 2^bitwidth. +func AsSet(s Store, r cid.Cid, bitwidth int) (*Set, error) { + m, err := AsMap(s, r, bitwidth) + if err != nil { + return nil, err + } + + return &Set{ + m: m, + }, nil +} + +// NewSet creates a new HAMT with root `r` and store `s`. +// The HAMT has branching factor 2^bitwidth. +func MakeEmptySet(s Store, bitwidth int) (*Set, error) { + m, err := MakeEmptyMap(s, bitwidth) + if err != nil { + return nil, err + } + return &Set{m}, nil +} + +// Root return the root cid of HAMT. +func (h *Set) Root() (cid.Cid, error) { + return h.m.Root() +} + +// Put adds `k` to the set. +func (h *Set) Put(k abi.Keyer) error { + return h.m.Put(k, nil) +} + +// Has returns true iff `k` is in the set. +func (h *Set) Has(k abi.Keyer) (bool, error) { + return h.m.Get(k, nil) +} + +// Removes `k` from the set, if present. +// Returns whether the key was previously present. +func (h *Set) TryDelete(k abi.Keyer) (bool, error) { + return h.m.TryDelete(k) +} + +// Removes `k` from the set, expecting it to be present. +func (h *Set) Delete(k abi.Keyer) error { + return h.m.Delete(k) +} + +// ForEach iterates over all values in the set, calling the callback for each value. +// Returning error from the callback stops the iteration. +func (h *Set) ForEach(cb func(k string) error) error { + return h.m.ForEach(nil, cb) +} + +// Collects all the keys from the set into a slice of strings. +func (h *Set) CollectKeys() (out []string, err error) { + return h.m.CollectKeys() +} diff --git a/builtin/v18/util/adt/store.go b/builtin/v18/util/adt/store.go new file mode 100644 index 00000000..004b409c --- /dev/null +++ b/builtin/v18/util/adt/store.go @@ -0,0 +1,32 @@ +package adt + +import ( + "context" + + ipldcbor "github.com/ipfs/go-ipld-cbor" +) + +// Store defines an interface required to back the ADTs in this package. +type Store interface { + Context() context.Context + ipldcbor.IpldStore +} + +// Adapts a vanilla IPLD store as an ADT store. +func WrapStore(ctx context.Context, store ipldcbor.IpldStore) Store { + return &wstore{ + ctx: ctx, + IpldStore: store, + } +} + +type wstore struct { + ctx context.Context + ipldcbor.IpldStore +} + +var _ Store = &wstore{} + +func (s *wstore) Context() context.Context { + return s.ctx +} diff --git a/builtin/v18/util/bitfield.go b/builtin/v18/util/bitfield.go new file mode 100644 index 00000000..44d4aa9e --- /dev/null +++ b/builtin/v18/util/bitfield.go @@ -0,0 +1,69 @@ +package util + +import ( + "github.com/filecoin-project/go-bitfield" + rlepluslazy "github.com/filecoin-project/go-bitfield/rle" +) + +type BitField = bitfield.BitField + +func isEmpty(iter rlepluslazy.RunIterator) (bool, error) { + // Look for the first non-zero bit. + for iter.HasNext() { + r, err := iter.NextRun() + if err != nil { + return false, err + } + if r.Val { + return false, nil + } + } + return true, nil +} + +// Checks whether bitfield `a` contains any bit that is set in bitfield `b`. +func BitFieldContainsAny(a, b BitField) (bool, error) { + aruns, err := a.RunIterator() + if err != nil { + return false, err + } + + bruns, err := b.RunIterator() + if err != nil { + return false, err + } + + // Take the intersection of the two bitfields. + combined, err := rlepluslazy.And(aruns, bruns) + if err != nil { + return false, err + } + + // Look for the first non-zero bit. + empty, err := isEmpty(combined) + if err != nil { + return false, err + } + return !empty, nil +} + +// Checks whether bitfield `a` contains all bits set in bitfield `b`. +func BitFieldContainsAll(a, b BitField) (bool, error) { + aruns, err := a.RunIterator() + if err != nil { + return false, err + } + + bruns, err := b.RunIterator() + if err != nil { + return false, err + } + + // Remove any elements in a from b. If b contains bits not in a, some + // bits will remain. + combined, err := rlepluslazy.Subtract(bruns, aruns) + if err != nil { + return false, err + } + return isEmpty(combined) +} diff --git a/builtin/v18/util/bitfield_queue.go b/builtin/v18/util/bitfield_queue.go new file mode 100644 index 00000000..48567950 --- /dev/null +++ b/builtin/v18/util/bitfield_queue.go @@ -0,0 +1,38 @@ +package util + +import ( + "github.com/ipfs/go-cid" + "golang.org/x/xerrors" + + "github.com/filecoin-project/go-bitfield" + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/builtin" + "github.com/filecoin-project/go-state-types/builtin/v18/util/adt" +) + +// Wrapper for working with an AMT[ChainEpoch]*Bitfield functioning as a queue, bucketed by epoch. +// Keys in the queue are quantized (upwards), modulo some offset, to reduce the cardinality of keys. +type BitfieldQueue struct { + *adt.Array + quant builtin.QuantSpec +} + +func LoadBitfieldQueue(store adt.Store, root cid.Cid, quant builtin.QuantSpec, bitwidth int) (BitfieldQueue, error) { + arr, err := adt.AsArray(store, root, bitwidth) + if err != nil { + return BitfieldQueue{}, xerrors.Errorf("failed to load epoch queue %v: %w", root, err) + } + return BitfieldQueue{arr, quant}, nil +} + +// Iterates the queue. +func (q BitfieldQueue) ForEach(cb func(epoch abi.ChainEpoch, bf bitfield.BitField) error) error { + var bf bitfield.BitField + return q.Array.ForEach(&bf, func(i int64) error { + cpy, err := bf.Copy() + if err != nil { + return xerrors.Errorf("failed to copy bitfield in queue: %w", err) + } + return cb(abi.ChainEpoch(i), cpy) + }) +} diff --git a/builtin/v18/util/math/expneg.go b/builtin/v18/util/math/expneg.go new file mode 100644 index 00000000..6432230d --- /dev/null +++ b/builtin/v18/util/math/expneg.go @@ -0,0 +1,61 @@ +package math + +import ( + "math/big" +) + +var ( + // Coefficents in Q.128 format + expNumCoef []*big.Int + expDenoCoef []*big.Int +) + +func init() { + + // parameters are in integer format, + // coefficients are *2^-128 of that + // so we can just load them if we treat them as Q.128 + num := []string{ + "-648770010757830093818553637600", + "67469480939593786226847644286976", + "-3197587544499098424029388939001856", + "89244641121992890118377641805348864", + "-1579656163641440567800982336819953664", + "17685496037279256458459817590917169152", + "-115682590513835356866803355398940131328", + "340282366920938463463374607431768211456", + } + expNumCoef = Parse(num) + + deno := []string{ + "1225524182432722209606361", + "114095592300906098243859450", + "5665570424063336070530214243", + "194450132448609991765137938448", + "5068267641632683791026134915072", + "104716890604972796896895427629056", + "1748338658439454459487681798864896", + "23704654329841312470660182937960448", + "259380097567996910282699886670381056", + "2250336698853390384720606936038375424", + "14978272436876548034486263159246028800", + "72144088983913131323343765784380833792", + "224599776407103106596571252037123047424", + "340282366920938463463374607431768211456", + } + expDenoCoef = Parse(deno) +} + +// ExpNeg accepts x in Q.128 format and computes e^-x. +// It is most precise within [0, 1.725) range, where error is less than 3.4e-30. +// Over the [0, 5) range its error is less than 4.6e-15. +// Output is in Q.128 format. +func ExpNeg(x *big.Int) *big.Int { + // exp is approximated by rational function + // polynomials of the rational function are evaluated using Horner's method + num := Polyval(expNumCoef, x) // Q.128 + deno := Polyval(expDenoCoef, x) // Q.128 + + num = num.Lsh(num, Precision128) // Q.256 + return num.Div(num, deno) // Q.256 / Q.128 => Q.128 +} diff --git a/builtin/v18/util/math/ln.go b/builtin/v18/util/math/ln.go new file mode 100644 index 00000000..cd54c7e6 --- /dev/null +++ b/builtin/v18/util/math/ln.go @@ -0,0 +1,78 @@ +package math + +import ( + gbig "math/big" + + "github.com/filecoin-project/go-state-types/big" +) + +var ( + // Coefficients in Q.128 format + lnNumCoef []*gbig.Int + lnDenomCoef []*gbig.Int + ln2 big.Int +) + +func init() { + // ln approximation coefficients + // parameters are in integer format, + // coefficients are *2^-128 of that + // so we can just load them if we treat them as Q.128 + num := []string{ + "261417938209272870992496419296200268025", + "7266615505142943436908456158054846846897", + "32458783941900493142649393804518050491988", + "17078670566130897220338060387082146864806", + "-35150353308172866634071793531642638290419", + "-20351202052858059355702509232125230498980", + "-1563932590352680681114104005183375350999", + } + lnNumCoef = Parse(num) + + denom := []string{ + "49928077726659937662124949977867279384", + "2508163877009111928787629628566491583994", + "21757751789594546643737445330202599887121", + "53400635271583923415775576342898617051826", + "41248834748603606604000911015235164348839", + "9015227820322455780436733526367238305537", + "340282366920938463463374607431768211456", + } + lnDenomCoef = Parse(denom) + + constStrs := []string{ + "235865763225513294137944142764154484399", // ln(2) + } + constBigs := Parse(constStrs) + ln2 = big.NewFromGo(constBigs[0]) +} + +// The natural log of Q.128 x. +func Ln(z big.Int) big.Int { + // bitlen - 1 - precision + k := int64(z.BitLen()) - 1 - Precision128 // Q.0 + var x big.Int + + if k > 0 { + x = big.Rsh(z, uint(k)) // Q.128 + } else { + x = big.Lsh(z, uint(-k)) // Q.128 + } + + // ln(z) = ln(x * 2^k) = ln(x) + k * ln2 + lnz := big.Mul(big.NewInt(k), ln2) // Q.0 * Q.128 => Q.128 + return big.Sum(lnz, lnBetweenOneAndTwo(x)) // Q.128 +} + +// The natural log of x, specified in Q.128 format +// Should only use with 1 <= x <= 2 +// Output is in Q.128 format. +func lnBetweenOneAndTwo(x big.Int) big.Int { + // ln is approximated by rational function + // polynomials of the rational function are evaluated using Horner's method + num := Polyval(lnNumCoef, x.Int) // Q.128 + denom := Polyval(lnDenomCoef, x.Int) // Q.128 + + num = num.Lsh(num, Precision128) // Q.128 => Q.256 + return big.NewFromGo(num.Div(num, denom)) // Q.256 / Q.128 => Q.128 +} diff --git a/builtin/v18/util/math/ln_test.go b/builtin/v18/util/math/ln_test.go new file mode 100644 index 00000000..f9e8ac28 --- /dev/null +++ b/builtin/v18/util/math/ln_test.go @@ -0,0 +1,40 @@ +package math_test + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/filecoin-project/go-state-types/big" + "github.com/filecoin-project/go-state-types/builtin/v18/util/math" +) + +func TestNaturalLog(t *testing.T) { + lnInputs := math.Parse([]string{ + "340282366920938463463374607431768211456", // Q.128 format of 1 + "924990000000000000000000000000000000000", // Q.128 format of e (rounded up in 5th decimal place to handle truncation) + "34028236692093846346337460743176821145600000000000000000000", // Q.128 format of 100e18 + "6805647338418769269267492148635364229120000000000000000000000", // Q.128 format of 2e22 + "204169000000000000000000000000000000", // Q.128 format of 0.0006 + "34028236692093846346337460743", // Q.128 format of 1e-10 + }) + + expectedLnOutputs := math.Parse([]string{ + "0", // Q.128 format of 0 = ln(1) + "340282366920938463463374607431768211456", // Q.128 format of 1 = ln(e) + "15670582109617661336106769654068947397831", // Q.128 format of 46.051... = ln(100e18) + "17473506083804940763855390762239996622013", // Q.128 format of 51.35... = ln(2e22) + "-2524410000000000000000000000000000000000", // Q.128 format of -7.41.. = ln(0.0006) + "-7835291054808830668053384827034473698915", // Q.128 format of -23.02.. = ln(1e-10) + }) + fmt.Printf("%v %v\n", lnInputs, expectedLnOutputs) + require.Equal(t, len(lnInputs), len(expectedLnOutputs)) + for i := 0; i < len(lnInputs); i++ { + z := big.NewFromGo(lnInputs[i]) + lnOfZ := math.Ln(z) + expectedZ := big.NewFromGo(expectedLnOutputs[i]) + assert.Equal(t, big.Rsh(expectedZ, math.Precision128), big.Rsh(lnOfZ, math.Precision128), "failed ln of %v", z) + } +} diff --git a/builtin/v18/util/math/parse.go b/builtin/v18/util/math/parse.go new file mode 100644 index 00000000..aee6c168 --- /dev/null +++ b/builtin/v18/util/math/parse.go @@ -0,0 +1,18 @@ +package math + +import "math/big" + +// Parse a slice of strings (representing integers in decimal) +// Convention: this function is to be applied to strings representing Q.128 fixed-point numbers, and thus returns numbers in binary Q.128 representation +func Parse(coefs []string) []*big.Int { + out := make([]*big.Int, len(coefs)) + for i, coef := range coefs { + c, ok := new(big.Int).SetString(coef, 10) + if !ok { + panic("could not parse q128 parameter") + } + // << 128 (Q.0 to Q.128) >> 128 to transform integer params to coefficients + out[i] = c + } + return out +} diff --git a/builtin/v18/util/math/polyval.go b/builtin/v18/util/math/polyval.go new file mode 100644 index 00000000..833dd9a0 --- /dev/null +++ b/builtin/v18/util/math/polyval.go @@ -0,0 +1,22 @@ +package math + +import "math/big" + +// note: all coefficients for which Polyval is used would need to be updated if this precision changes +const Precision128 = 128 + +// Polyval evaluates a polynomial given by coefficients `p` in Q.128 format +// at point `x` in Q.128 format. Output is in Q.128. +// Coefficients should be ordered from the highest order coefficient to the lowest. +func Polyval(p []*big.Int, x *big.Int) *big.Int { + // evaluation using Horner's method + res := new(big.Int).Set(p[0]) // Q.128 + tmp := new(big.Int) // big.Int.Mul doesn't like when input is reused as output + for _, c := range p[1:] { + tmp = tmp.Mul(res, x) // Q.128 * Q.128 => Q.256 + res = res.Rsh(tmp, Precision128) // Q.256 >> 128 => Q.128 + res = res.Add(res, c) + } + + return res +} diff --git a/builtin/v18/util/smoothing/alpha_beta_filter.go b/builtin/v18/util/smoothing/alpha_beta_filter.go new file mode 100644 index 00000000..9b272199 --- /dev/null +++ b/builtin/v18/util/smoothing/alpha_beta_filter.go @@ -0,0 +1,101 @@ +package smoothing + +import ( + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/big" + "github.com/filecoin-project/go-state-types/builtin/v18/util/math" +) + +var ( + DefaultAlpha big.Int // Q.128 value of 9.25e-4 + DefaultBeta big.Int // Q.128 value of 2.84e-7 + + ExtrapolatedCumSumRatioEpsilon big.Int // Q.128 value of 2^-50 +) + +func init() { + // Alpha Beta Filter constants + constStrs := []string{ + "314760000000000000000000000000000000", // DefaultAlpha + "96640100000000000000000000000000", // DefaultBeta + "302231454903657293676544", // Epsilon + + } + constBigs := math.Parse(constStrs) + DefaultAlpha = big.NewFromGo(constBigs[0]) + DefaultBeta = big.NewFromGo(constBigs[1]) + ExtrapolatedCumSumRatioEpsilon = big.NewFromGo(constBigs[2]) + +} + +// Alpha Beta Filter "position" (value) and "velocity" (rate of change of value) estimates +// Estimates are in Q.128 format +type FilterEstimate struct { + PositionEstimate big.Int // Q.128 + VelocityEstimate big.Int // Q.128 +} + +// Returns the Q.0 position estimate of the filter +func Estimate(fe *FilterEstimate) big.Int { + return big.Rsh(fe.PositionEstimate, math.Precision128) // Q.128 => Q.0 +} + +// Create a new filter estimate given two Q.0 format ints. +func NewEstimate(position, velocity big.Int) FilterEstimate { + return FilterEstimate{ + PositionEstimate: big.Lsh(position, math.Precision128), // Q.0 => Q.128 + VelocityEstimate: big.Lsh(velocity, math.Precision128), // Q.0 => Q.128 + } +} + +// Extrapolate the CumSumRatio given two filters. +// Output is in Q.128 format +func ExtrapolatedCumSumOfRatio(delta abi.ChainEpoch, relativeStart abi.ChainEpoch, estimateNum, estimateDenom FilterEstimate) big.Int { + deltaT := big.Lsh(big.NewInt(int64(delta)), math.Precision128) // Q.0 => Q.128 + t0 := big.Lsh(big.NewInt(int64(relativeStart)), math.Precision128) // Q.0 => Q.128 + // Renaming for ease of following spec and clarity + position1 := estimateNum.PositionEstimate + position2 := estimateDenom.PositionEstimate + velocity1 := estimateNum.VelocityEstimate + velocity2 := estimateDenom.VelocityEstimate + + squaredVelocity2 := big.Mul(velocity2, velocity2) // Q.128 * Q.128 => Q.256 + squaredVelocity2 = big.Rsh(squaredVelocity2, math.Precision128) // Q.256 => Q.128 + + if squaredVelocity2.GreaterThan(ExtrapolatedCumSumRatioEpsilon) { + x2a := big.Mul(t0, velocity2) // Q.128 * Q.128 => Q.256 + x2a = big.Rsh(x2a, math.Precision128) // Q.256 => Q.128 + x2a = big.Sum(position2, x2a) + + x2b := big.Mul(deltaT, velocity2) // Q.128 * Q.128 => Q.256 + x2b = big.Rsh(x2b, math.Precision128) // Q.256 => Q.128 + x2b = big.Sum(x2a, x2b) + + x2a = math.Ln(x2a) // Q.128 + x2b = math.Ln(x2b) // Q.128 + + m1 := big.Sub(x2b, x2a) + m1 = big.Mul(velocity2, big.Mul(position1, m1)) // Q.128 * Q.128 * Q.128 => Q.384 + m1 = big.Rsh(m1, math.Precision128) //Q.384 => Q.256 + + m2L := big.Sub(x2a, x2b) + m2L = big.Mul(position2, m2L) // Q.128 * Q.128 => Q.256 + m2R := big.Mul(velocity2, deltaT) // Q.128 * Q.128 => Q.256 + m2 := big.Sum(m2L, m2R) + m2 = big.Mul(velocity1, m2) // Q.256 => Q.384 + m2 = big.Rsh(m2, math.Precision128) //Q.384 => Q.256 + + return big.Div(big.Sum(m1, m2), squaredVelocity2) // Q.256 / Q.128 => Q.128 + + } + + halfDeltaT := big.Rsh(deltaT, 1) // Q.128 / Q.0 => Q.128 + x1m := big.Mul(velocity1, big.Sum(t0, halfDeltaT)) // Q.128 * Q.128 => Q.256 + x1m = big.Rsh(x1m, math.Precision128) // Q.256 => Q.128 + x1m = big.Add(position1, x1m) + + cumsumRatio := big.Mul(x1m, deltaT) // Q.128 * Q.128 => Q.256 + cumsumRatio = big.Div(cumsumRatio, position2) // Q.256 / Q.128 => Q.128 + return cumsumRatio + +} diff --git a/builtin/v18/util/smoothing/cbor_gen.go b/builtin/v18/util/smoothing/cbor_gen.go new file mode 100644 index 00000000..1c89e05c --- /dev/null +++ b/builtin/v18/util/smoothing/cbor_gen.go @@ -0,0 +1,89 @@ +// Code generated by github.com/whyrusleeping/cbor-gen. DO NOT EDIT. + +package smoothing + +import ( + "fmt" + "io" + "math" + "sort" + + cid "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" + xerrors "golang.org/x/xerrors" +) + +var _ = xerrors.Errorf +var _ = cid.Undef +var _ = math.E +var _ = sort.Sort + +var lengthBufFilterEstimate = []byte{130} + +func (t *FilterEstimate) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufFilterEstimate); err != nil { + return err + } + + // t.PositionEstimate (big.Int) (struct) + if err := t.PositionEstimate.MarshalCBOR(cw); err != nil { + return err + } + + // t.VelocityEstimate (big.Int) (struct) + if err := t.VelocityEstimate.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *FilterEstimate) UnmarshalCBOR(r io.Reader) (err error) { + *t = FilterEstimate{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.PositionEstimate (big.Int) (struct) + + { + + if err := t.PositionEstimate.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.PositionEstimate: %w", err) + } + + } + // t.VelocityEstimate (big.Int) (struct) + + { + + if err := t.VelocityEstimate.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.VelocityEstimate: %w", err) + } + + } + return nil +} diff --git a/builtin/v18/verifreg/cbor_gen.go b/builtin/v18/verifreg/cbor_gen.go new file mode 100644 index 00000000..94700784 --- /dev/null +++ b/builtin/v18/verifreg/cbor_gen.go @@ -0,0 +1,3520 @@ +// Code generated by github.com/whyrusleeping/cbor-gen. DO NOT EDIT. + +package verifreg + +import ( + "fmt" + "io" + "math" + "sort" + + abi "github.com/filecoin-project/go-state-types/abi" + batch "github.com/filecoin-project/go-state-types/batch" + cid "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" + xerrors "golang.org/x/xerrors" +) + +var _ = xerrors.Errorf +var _ = cid.Undef +var _ = math.E +var _ = sort.Sort + +var lengthBufState = []byte{134} + +func (t *State) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufState); err != nil { + return err + } + + // t.RootKey (address.Address) (struct) + if err := t.RootKey.MarshalCBOR(cw); err != nil { + return err + } + + // t.Verifiers (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.Verifiers); err != nil { + return xerrors.Errorf("failed to write cid field t.Verifiers: %w", err) + } + + // t.RemoveDataCapProposalIDs (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.RemoveDataCapProposalIDs); err != nil { + return xerrors.Errorf("failed to write cid field t.RemoveDataCapProposalIDs: %w", err) + } + + // t.Allocations (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.Allocations); err != nil { + return xerrors.Errorf("failed to write cid field t.Allocations: %w", err) + } + + // t.NextAllocationId (verifreg.AllocationId) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.NextAllocationId)); err != nil { + return err + } + + // t.Claims (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.Claims); err != nil { + return xerrors.Errorf("failed to write cid field t.Claims: %w", err) + } + + return nil +} + +func (t *State) UnmarshalCBOR(r io.Reader) (err error) { + *t = State{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 6 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.RootKey (address.Address) (struct) + + { + + if err := t.RootKey.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.RootKey: %w", err) + } + + } + // t.Verifiers (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.Verifiers: %w", err) + } + + t.Verifiers = c + + } + // t.RemoveDataCapProposalIDs (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.RemoveDataCapProposalIDs: %w", err) + } + + t.RemoveDataCapProposalIDs = c + + } + // t.Allocations (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.Allocations: %w", err) + } + + t.Allocations = c + + } + // t.NextAllocationId (verifreg.AllocationId) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.NextAllocationId = AllocationId(extra) + + } + // t.Claims (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.Claims: %w", err) + } + + t.Claims = c + + } + return nil +} + +var lengthBufAddVerifierParams = []byte{130} + +func (t *AddVerifierParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufAddVerifierParams); err != nil { + return err + } + + // t.Address (address.Address) (struct) + if err := t.Address.MarshalCBOR(cw); err != nil { + return err + } + + // t.Allowance (big.Int) (struct) + if err := t.Allowance.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *AddVerifierParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = AddVerifierParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Address (address.Address) (struct) + + { + + if err := t.Address.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Address: %w", err) + } + + } + // t.Allowance (big.Int) (struct) + + { + + if err := t.Allowance.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Allowance: %w", err) + } + + } + return nil +} + +var lengthBufAddVerifiedClientParams = []byte{130} + +func (t *AddVerifiedClientParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufAddVerifiedClientParams); err != nil { + return err + } + + // t.Address (address.Address) (struct) + if err := t.Address.MarshalCBOR(cw); err != nil { + return err + } + + // t.Allowance (big.Int) (struct) + if err := t.Allowance.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *AddVerifiedClientParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = AddVerifiedClientParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Address (address.Address) (struct) + + { + + if err := t.Address.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Address: %w", err) + } + + } + // t.Allowance (big.Int) (struct) + + { + + if err := t.Allowance.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Allowance: %w", err) + } + + } + return nil +} + +var lengthBufUseBytesParams = []byte{130} + +func (t *UseBytesParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufUseBytesParams); err != nil { + return err + } + + // t.Address (address.Address) (struct) + if err := t.Address.MarshalCBOR(cw); err != nil { + return err + } + + // t.DealSize (big.Int) (struct) + if err := t.DealSize.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *UseBytesParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = UseBytesParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Address (address.Address) (struct) + + { + + if err := t.Address.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Address: %w", err) + } + + } + // t.DealSize (big.Int) (struct) + + { + + if err := t.DealSize.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.DealSize: %w", err) + } + + } + return nil +} + +var lengthBufRestoreBytesParams = []byte{130} + +func (t *RestoreBytesParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufRestoreBytesParams); err != nil { + return err + } + + // t.Address (address.Address) (struct) + if err := t.Address.MarshalCBOR(cw); err != nil { + return err + } + + // t.DealSize (big.Int) (struct) + if err := t.DealSize.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *RestoreBytesParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = RestoreBytesParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Address (address.Address) (struct) + + { + + if err := t.Address.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Address: %w", err) + } + + } + // t.DealSize (big.Int) (struct) + + { + + if err := t.DealSize.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.DealSize: %w", err) + } + + } + return nil +} + +var lengthBufRemoveDataCapParams = []byte{132} + +func (t *RemoveDataCapParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufRemoveDataCapParams); err != nil { + return err + } + + // t.VerifiedClientToRemove (address.Address) (struct) + if err := t.VerifiedClientToRemove.MarshalCBOR(cw); err != nil { + return err + } + + // t.DataCapAmountToRemove (big.Int) (struct) + if err := t.DataCapAmountToRemove.MarshalCBOR(cw); err != nil { + return err + } + + // t.VerifierRequest1 (verifreg.RemoveDataCapRequest) (struct) + if err := t.VerifierRequest1.MarshalCBOR(cw); err != nil { + return err + } + + // t.VerifierRequest2 (verifreg.RemoveDataCapRequest) (struct) + if err := t.VerifierRequest2.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *RemoveDataCapParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = RemoveDataCapParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 4 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.VerifiedClientToRemove (address.Address) (struct) + + { + + if err := t.VerifiedClientToRemove.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.VerifiedClientToRemove: %w", err) + } + + } + // t.DataCapAmountToRemove (big.Int) (struct) + + { + + if err := t.DataCapAmountToRemove.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.DataCapAmountToRemove: %w", err) + } + + } + // t.VerifierRequest1 (verifreg.RemoveDataCapRequest) (struct) + + { + + if err := t.VerifierRequest1.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.VerifierRequest1: %w", err) + } + + } + // t.VerifierRequest2 (verifreg.RemoveDataCapRequest) (struct) + + { + + if err := t.VerifierRequest2.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.VerifierRequest2: %w", err) + } + + } + return nil +} + +var lengthBufRemoveDataCapReturn = []byte{130} + +func (t *RemoveDataCapReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufRemoveDataCapReturn); err != nil { + return err + } + + // t.VerifiedClient (address.Address) (struct) + if err := t.VerifiedClient.MarshalCBOR(cw); err != nil { + return err + } + + // t.DataCapRemoved (big.Int) (struct) + if err := t.DataCapRemoved.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *RemoveDataCapReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = RemoveDataCapReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.VerifiedClient (address.Address) (struct) + + { + + if err := t.VerifiedClient.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.VerifiedClient: %w", err) + } + + } + // t.DataCapRemoved (big.Int) (struct) + + { + + if err := t.DataCapRemoved.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.DataCapRemoved: %w", err) + } + + } + return nil +} + +var lengthBufRemoveExpiredAllocationsParams = []byte{130} + +func (t *RemoveExpiredAllocationsParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufRemoveExpiredAllocationsParams); err != nil { + return err + } + + // t.Client (abi.ActorID) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Client)); err != nil { + return err + } + + // t.AllocationIds ([]verifreg.AllocationId) (slice) + if len(t.AllocationIds) > 8192 { + return xerrors.Errorf("Slice value in field t.AllocationIds was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.AllocationIds))); err != nil { + return err + } + for _, v := range t.AllocationIds { + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(v)); err != nil { + return err + } + + } + return nil +} + +func (t *RemoveExpiredAllocationsParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = RemoveExpiredAllocationsParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Client (abi.ActorID) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Client = abi.ActorID(extra) + + } + // t.AllocationIds ([]verifreg.AllocationId) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.AllocationIds: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.AllocationIds = make([]AllocationId, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.AllocationIds[i] = AllocationId(extra) + + } + + } + } + return nil +} + +var lengthBufRemoveExpiredAllocationsReturn = []byte{131} + +func (t *RemoveExpiredAllocationsReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufRemoveExpiredAllocationsReturn); err != nil { + return err + } + + // t.Considered ([]verifreg.AllocationId) (slice) + if len(t.Considered) > 8192 { + return xerrors.Errorf("Slice value in field t.Considered was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Considered))); err != nil { + return err + } + for _, v := range t.Considered { + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(v)); err != nil { + return err + } + + } + + // t.Results (batch.BatchReturn) (struct) + if err := t.Results.MarshalCBOR(cw); err != nil { + return err + } + + // t.DataCapRecovered (big.Int) (struct) + if err := t.DataCapRecovered.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *RemoveExpiredAllocationsReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = RemoveExpiredAllocationsReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.Considered ([]verifreg.AllocationId) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Considered: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Considered = make([]AllocationId, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Considered[i] = AllocationId(extra) + + } + + } + } + // t.Results (batch.BatchReturn) (struct) + + { + + if err := t.Results.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Results: %w", err) + } + + } + // t.DataCapRecovered (big.Int) (struct) + + { + + if err := t.DataCapRecovered.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.DataCapRecovered: %w", err) + } + + } + return nil +} + +var lengthBufClaimAllocationsParams = []byte{130} + +func (t *ClaimAllocationsParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufClaimAllocationsParams); err != nil { + return err + } + + // t.Sectors ([]verifreg.SectorAllocationClaims) (slice) + if len(t.Sectors) > 8192 { + return xerrors.Errorf("Slice value in field t.Sectors was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Sectors))); err != nil { + return err + } + for _, v := range t.Sectors { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + + // t.AllOrNothing (bool) (bool) + if err := cbg.WriteBool(w, t.AllOrNothing); err != nil { + return err + } + return nil +} + +func (t *ClaimAllocationsParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = ClaimAllocationsParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Sectors ([]verifreg.SectorAllocationClaims) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Sectors: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Sectors = make([]SectorAllocationClaims, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Sectors[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Sectors[i]: %w", err) + } + + } + + } + } + // t.AllOrNothing (bool) (bool) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajOther { + return fmt.Errorf("booleans must be major type 7") + } + switch extra { + case 20: + t.AllOrNothing = false + case 21: + t.AllOrNothing = true + default: + return fmt.Errorf("booleans are either major type 7, value 20 or 21 (got %d)", extra) + } + return nil +} + +var lengthBufClaimAllocationsReturn = []byte{130} + +func (t *ClaimAllocationsReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufClaimAllocationsReturn); err != nil { + return err + } + + // t.BatchInfo (batch.BatchReturn) (struct) + if err := t.BatchInfo.MarshalCBOR(cw); err != nil { + return err + } + + // t.ClaimedSpace (big.Int) (struct) + if err := t.ClaimedSpace.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *ClaimAllocationsReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = ClaimAllocationsReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.BatchInfo (batch.BatchReturn) (struct) + + { + + if err := t.BatchInfo.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.BatchInfo: %w", err) + } + + } + // t.ClaimedSpace (big.Int) (struct) + + { + + if err := t.ClaimedSpace.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ClaimedSpace: %w", err) + } + + } + return nil +} + +var lengthBufGetClaimsParams = []byte{130} + +func (t *GetClaimsParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufGetClaimsParams); err != nil { + return err + } + + // t.Provider (abi.ActorID) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Provider)); err != nil { + return err + } + + // t.ClaimIds ([]verifreg.ClaimId) (slice) + if len(t.ClaimIds) > 8192 { + return xerrors.Errorf("Slice value in field t.ClaimIds was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.ClaimIds))); err != nil { + return err + } + for _, v := range t.ClaimIds { + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(v)); err != nil { + return err + } + + } + return nil +} + +func (t *GetClaimsParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = GetClaimsParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Provider (abi.ActorID) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Provider = abi.ActorID(extra) + + } + // t.ClaimIds ([]verifreg.ClaimId) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.ClaimIds: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.ClaimIds = make([]ClaimId, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.ClaimIds[i] = ClaimId(extra) + + } + + } + } + return nil +} + +var lengthBufGetClaimsReturn = []byte{130} + +func (t *GetClaimsReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufGetClaimsReturn); err != nil { + return err + } + + // t.BatchInfo (batch.BatchReturn) (struct) + if err := t.BatchInfo.MarshalCBOR(cw); err != nil { + return err + } + + // t.Claims ([]verifreg.Claim) (slice) + if len(t.Claims) > 8192 { + return xerrors.Errorf("Slice value in field t.Claims was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Claims))); err != nil { + return err + } + for _, v := range t.Claims { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *GetClaimsReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = GetClaimsReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.BatchInfo (batch.BatchReturn) (struct) + + { + + if err := t.BatchInfo.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.BatchInfo: %w", err) + } + + } + // t.Claims ([]verifreg.Claim) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Claims: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Claims = make([]Claim, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Claims[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Claims[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufUniversalReceiverParams = []byte{130} + +func (t *UniversalReceiverParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufUniversalReceiverParams); err != nil { + return err + } + + // t.Type_ (verifreg.ReceiverType) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Type_)); err != nil { + return err + } + + // t.Payload ([]uint8) (slice) + if len(t.Payload) > 2097152 { + return xerrors.Errorf("Byte array in field t.Payload was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajByteString, uint64(len(t.Payload))); err != nil { + return err + } + + if _, err := cw.Write(t.Payload); err != nil { + return err + } + + return nil +} + +func (t *UniversalReceiverParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = UniversalReceiverParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Type_ (verifreg.ReceiverType) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Type_ = ReceiverType(extra) + + } + // t.Payload ([]uint8) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 2097152 { + return fmt.Errorf("t.Payload: byte array too large (%d)", extra) + } + if maj != cbg.MajByteString { + return fmt.Errorf("expected byte array") + } + + if extra > 0 { + t.Payload = make([]uint8, extra) + } + + if _, err := io.ReadFull(cr, t.Payload); err != nil { + return err + } + + return nil +} + +var lengthBufAllocationsResponse = []byte{131} + +func (t *AllocationsResponse) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufAllocationsResponse); err != nil { + return err + } + + // t.AllocationResults (batch.BatchReturn) (struct) + if err := t.AllocationResults.MarshalCBOR(cw); err != nil { + return err + } + + // t.ExtensionResults (batch.BatchReturn) (struct) + if err := t.ExtensionResults.MarshalCBOR(cw); err != nil { + return err + } + + // t.NewAllocations ([]verifreg.AllocationId) (slice) + if len(t.NewAllocations) > 8192 { + return xerrors.Errorf("Slice value in field t.NewAllocations was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.NewAllocations))); err != nil { + return err + } + for _, v := range t.NewAllocations { + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(v)); err != nil { + return err + } + + } + return nil +} + +func (t *AllocationsResponse) UnmarshalCBOR(r io.Reader) (err error) { + *t = AllocationsResponse{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.AllocationResults (batch.BatchReturn) (struct) + + { + + if err := t.AllocationResults.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.AllocationResults: %w", err) + } + + } + // t.ExtensionResults (batch.BatchReturn) (struct) + + { + + if err := t.ExtensionResults.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.ExtensionResults: %w", err) + } + + } + // t.NewAllocations ([]verifreg.AllocationId) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.NewAllocations: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.NewAllocations = make([]AllocationId, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.NewAllocations[i] = AllocationId(extra) + + } + + } + } + return nil +} + +var lengthBufExtendClaimTermsParams = []byte{129} + +func (t *ExtendClaimTermsParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufExtendClaimTermsParams); err != nil { + return err + } + + // t.Terms ([]verifreg.ClaimTerm) (slice) + if len(t.Terms) > 8192 { + return xerrors.Errorf("Slice value in field t.Terms was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Terms))); err != nil { + return err + } + for _, v := range t.Terms { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *ExtendClaimTermsParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = ExtendClaimTermsParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Terms ([]verifreg.ClaimTerm) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Terms: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Terms = make([]ClaimTerm, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Terms[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Terms[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufExtendClaimTermsReturn = []byte{130} + +func (t *ExtendClaimTermsReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufExtendClaimTermsReturn); err != nil { + return err + } + + // t.SuccessCount (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SuccessCount)); err != nil { + return err + } + + // t.FailCodes ([]batch.FailCode) (slice) + if len(t.FailCodes) > 8192 { + return xerrors.Errorf("Slice value in field t.FailCodes was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.FailCodes))); err != nil { + return err + } + for _, v := range t.FailCodes { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *ExtendClaimTermsReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = ExtendClaimTermsReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.SuccessCount (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.SuccessCount = uint64(extra) + + } + // t.FailCodes ([]batch.FailCode) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.FailCodes: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.FailCodes = make([]batch.FailCode, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.FailCodes[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.FailCodes[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufRemoveExpiredClaimsParams = []byte{130} + +func (t *RemoveExpiredClaimsParams) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufRemoveExpiredClaimsParams); err != nil { + return err + } + + // t.Provider (abi.ActorID) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Provider)); err != nil { + return err + } + + // t.ClaimIds ([]verifreg.ClaimId) (slice) + if len(t.ClaimIds) > 8192 { + return xerrors.Errorf("Slice value in field t.ClaimIds was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.ClaimIds))); err != nil { + return err + } + for _, v := range t.ClaimIds { + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(v)); err != nil { + return err + } + + } + return nil +} + +func (t *RemoveExpiredClaimsParams) UnmarshalCBOR(r io.Reader) (err error) { + *t = RemoveExpiredClaimsParams{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Provider (abi.ActorID) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Provider = abi.ActorID(extra) + + } + // t.ClaimIds ([]verifreg.ClaimId) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.ClaimIds: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.ClaimIds = make([]ClaimId, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.ClaimIds[i] = ClaimId(extra) + + } + + } + } + return nil +} + +var lengthBufRemoveExpiredClaimsReturn = []byte{130} + +func (t *RemoveExpiredClaimsReturn) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufRemoveExpiredClaimsReturn); err != nil { + return err + } + + // t.Considered ([]verifreg.AllocationId) (slice) + if len(t.Considered) > 8192 { + return xerrors.Errorf("Slice value in field t.Considered was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Considered))); err != nil { + return err + } + for _, v := range t.Considered { + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(v)); err != nil { + return err + } + + } + + // t.Results (batch.BatchReturn) (struct) + if err := t.Results.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *RemoveExpiredClaimsReturn) UnmarshalCBOR(r io.Reader) (err error) { + *t = RemoveExpiredClaimsReturn{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Considered ([]verifreg.AllocationId) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Considered: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Considered = make([]AllocationId, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Considered[i] = AllocationId(extra) + + } + + } + } + // t.Results (batch.BatchReturn) (struct) + + { + + if err := t.Results.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Results: %w", err) + } + + } + return nil +} + +var lengthBufRemoveDataCapRequest = []byte{130} + +func (t *RemoveDataCapRequest) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufRemoveDataCapRequest); err != nil { + return err + } + + // t.Verifier (address.Address) (struct) + if err := t.Verifier.MarshalCBOR(cw); err != nil { + return err + } + + // t.VerifierSignature (crypto.Signature) (struct) + if err := t.VerifierSignature.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *RemoveDataCapRequest) UnmarshalCBOR(r io.Reader) (err error) { + *t = RemoveDataCapRequest{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Verifier (address.Address) (struct) + + { + + if err := t.Verifier.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Verifier: %w", err) + } + + } + // t.VerifierSignature (crypto.Signature) (struct) + + { + + if err := t.VerifierSignature.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.VerifierSignature: %w", err) + } + + } + return nil +} + +var lengthBufRemoveDataCapProposal = []byte{131} + +func (t *RemoveDataCapProposal) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufRemoveDataCapProposal); err != nil { + return err + } + + // t.VerifiedClient (address.Address) (struct) + if err := t.VerifiedClient.MarshalCBOR(cw); err != nil { + return err + } + + // t.DataCapAmount (big.Int) (struct) + if err := t.DataCapAmount.MarshalCBOR(cw); err != nil { + return err + } + + // t.RemovalProposalID (verifreg.RmDcProposalID) (struct) + if err := t.RemovalProposalID.MarshalCBOR(cw); err != nil { + return err + } + return nil +} + +func (t *RemoveDataCapProposal) UnmarshalCBOR(r io.Reader) (err error) { + *t = RemoveDataCapProposal{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.VerifiedClient (address.Address) (struct) + + { + + if err := t.VerifiedClient.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.VerifiedClient: %w", err) + } + + } + // t.DataCapAmount (big.Int) (struct) + + { + + if err := t.DataCapAmount.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.DataCapAmount: %w", err) + } + + } + // t.RemovalProposalID (verifreg.RmDcProposalID) (struct) + + { + + if err := t.RemovalProposalID.UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.RemovalProposalID: %w", err) + } + + } + return nil +} + +var lengthBufRmDcProposalID = []byte{129} + +func (t *RmDcProposalID) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufRmDcProposalID); err != nil { + return err + } + + // t.ProposalID (uint64) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.ProposalID)); err != nil { + return err + } + + return nil +} + +func (t *RmDcProposalID) UnmarshalCBOR(r io.Reader) (err error) { + *t = RmDcProposalID{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 1 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.ProposalID (uint64) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.ProposalID = uint64(extra) + + } + return nil +} + +var lengthBufSectorAllocationClaims = []byte{131} + +func (t *SectorAllocationClaims) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufSectorAllocationClaims); err != nil { + return err + } + + // t.Sector (abi.SectorNumber) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Sector)); err != nil { + return err + } + + // t.SectorExpiry (abi.ChainEpoch) (int64) + if t.SectorExpiry >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.SectorExpiry)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.SectorExpiry-1)); err != nil { + return err + } + } + + // t.Claims ([]verifreg.AllocationClaim) (slice) + if len(t.Claims) > 8192 { + return xerrors.Errorf("Slice value in field t.Claims was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Claims))); err != nil { + return err + } + for _, v := range t.Claims { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *SectorAllocationClaims) UnmarshalCBOR(r io.Reader) (err error) { + *t = SectorAllocationClaims{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.Sector (abi.SectorNumber) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Sector = abi.SectorNumber(extra) + + } + // t.SectorExpiry (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.SectorExpiry = abi.ChainEpoch(extraI) + } + // t.Claims ([]verifreg.AllocationClaim) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Claims: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Claims = make([]AllocationClaim, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Claims[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Claims[i]: %w", err) + } + + } + + } + } + return nil +} + +var lengthBufAllocationClaim = []byte{132} + +func (t *AllocationClaim) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufAllocationClaim); err != nil { + return err + } + + // t.Client (abi.ActorID) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Client)); err != nil { + return err + } + + // t.AllocationId (verifreg.AllocationId) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.AllocationId)); err != nil { + return err + } + + // t.Data (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.Data); err != nil { + return xerrors.Errorf("failed to write cid field t.Data: %w", err) + } + + // t.Size (abi.PaddedPieceSize) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Size)); err != nil { + return err + } + + return nil +} + +func (t *AllocationClaim) UnmarshalCBOR(r io.Reader) (err error) { + *t = AllocationClaim{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 4 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Client (abi.ActorID) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Client = abi.ActorID(extra) + + } + // t.AllocationId (verifreg.AllocationId) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.AllocationId = AllocationId(extra) + + } + // t.Data (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.Data: %w", err) + } + + t.Data = c + + } + // t.Size (abi.PaddedPieceSize) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Size = abi.PaddedPieceSize(extra) + + } + return nil +} + +var lengthBufClaim = []byte{136} + +func (t *Claim) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufClaim); err != nil { + return err + } + + // t.Provider (abi.ActorID) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Provider)); err != nil { + return err + } + + // t.Client (abi.ActorID) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Client)); err != nil { + return err + } + + // t.Data (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.Data); err != nil { + return xerrors.Errorf("failed to write cid field t.Data: %w", err) + } + + // t.Size (abi.PaddedPieceSize) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Size)); err != nil { + return err + } + + // t.TermMin (abi.ChainEpoch) (int64) + if t.TermMin >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.TermMin)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.TermMin-1)); err != nil { + return err + } + } + + // t.TermMax (abi.ChainEpoch) (int64) + if t.TermMax >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.TermMax)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.TermMax-1)); err != nil { + return err + } + } + + // t.TermStart (abi.ChainEpoch) (int64) + if t.TermStart >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.TermStart)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.TermStart-1)); err != nil { + return err + } + } + + // t.Sector (abi.SectorNumber) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Sector)); err != nil { + return err + } + + return nil +} + +func (t *Claim) UnmarshalCBOR(r io.Reader) (err error) { + *t = Claim{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 8 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Provider (abi.ActorID) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Provider = abi.ActorID(extra) + + } + // t.Client (abi.ActorID) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Client = abi.ActorID(extra) + + } + // t.Data (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.Data: %w", err) + } + + t.Data = c + + } + // t.Size (abi.PaddedPieceSize) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Size = abi.PaddedPieceSize(extra) + + } + // t.TermMin (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.TermMin = abi.ChainEpoch(extraI) + } + // t.TermMax (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.TermMax = abi.ChainEpoch(extraI) + } + // t.TermStart (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.TermStart = abi.ChainEpoch(extraI) + } + // t.Sector (abi.SectorNumber) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Sector = abi.SectorNumber(extra) + + } + return nil +} + +var lengthBufClaimTerm = []byte{131} + +func (t *ClaimTerm) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufClaimTerm); err != nil { + return err + } + + // t.Provider (abi.ActorID) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Provider)); err != nil { + return err + } + + // t.ClaimId (verifreg.ClaimId) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.ClaimId)); err != nil { + return err + } + + // t.TermMax (abi.ChainEpoch) (int64) + if t.TermMax >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.TermMax)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.TermMax-1)); err != nil { + return err + } + } + + return nil +} + +func (t *ClaimTerm) UnmarshalCBOR(r io.Reader) (err error) { + *t = ClaimTerm{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.Provider (abi.ActorID) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Provider = abi.ActorID(extra) + + } + // t.ClaimId (verifreg.ClaimId) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.ClaimId = ClaimId(extra) + + } + // t.TermMax (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.TermMax = abi.ChainEpoch(extraI) + } + return nil +} + +var lengthBufClaimExtensionRequest = []byte{131} + +func (t *ClaimExtensionRequest) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufClaimExtensionRequest); err != nil { + return err + } + + // t.Provider (abi.ActorID) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Provider)); err != nil { + return err + } + + // t.Claim (verifreg.ClaimId) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Claim)); err != nil { + return err + } + + // t.TermMax (abi.ChainEpoch) (int64) + if t.TermMax >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.TermMax)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.TermMax-1)); err != nil { + return err + } + } + + return nil +} + +func (t *ClaimExtensionRequest) UnmarshalCBOR(r io.Reader) (err error) { + *t = ClaimExtensionRequest{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + 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.Provider (abi.ActorID) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Provider = abi.ActorID(extra) + + } + // t.Claim (verifreg.ClaimId) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Claim = ClaimId(extra) + + } + // t.TermMax (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.TermMax = abi.ChainEpoch(extraI) + } + return nil +} + +var lengthBufAllocation = []byte{135} + +func (t *Allocation) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufAllocation); err != nil { + return err + } + + // t.Client (abi.ActorID) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Client)); err != nil { + return err + } + + // t.Provider (abi.ActorID) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Provider)); err != nil { + return err + } + + // t.Data (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.Data); err != nil { + return xerrors.Errorf("failed to write cid field t.Data: %w", err) + } + + // t.Size (abi.PaddedPieceSize) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Size)); err != nil { + return err + } + + // t.TermMin (abi.ChainEpoch) (int64) + if t.TermMin >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.TermMin)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.TermMin-1)); err != nil { + return err + } + } + + // t.TermMax (abi.ChainEpoch) (int64) + if t.TermMax >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.TermMax)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.TermMax-1)); err != nil { + return err + } + } + + // t.Expiration (abi.ChainEpoch) (int64) + if t.Expiration >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Expiration)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.Expiration-1)); err != nil { + return err + } + } + + return nil +} + +func (t *Allocation) UnmarshalCBOR(r io.Reader) (err error) { + *t = Allocation{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 7 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Client (abi.ActorID) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Client = abi.ActorID(extra) + + } + // t.Provider (abi.ActorID) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Provider = abi.ActorID(extra) + + } + // t.Data (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.Data: %w", err) + } + + t.Data = c + + } + // t.Size (abi.PaddedPieceSize) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Size = abi.PaddedPieceSize(extra) + + } + // t.TermMin (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.TermMin = abi.ChainEpoch(extraI) + } + // t.TermMax (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.TermMax = abi.ChainEpoch(extraI) + } + // t.Expiration (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.Expiration = abi.ChainEpoch(extraI) + } + return nil +} + +var lengthBufAllocationRequest = []byte{134} + +func (t *AllocationRequest) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufAllocationRequest); err != nil { + return err + } + + // t.Provider (abi.ActorID) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Provider)); err != nil { + return err + } + + // t.Data (cid.Cid) (struct) + + if err := cbg.WriteCid(cw, t.Data); err != nil { + return xerrors.Errorf("failed to write cid field t.Data: %w", err) + } + + // t.Size (abi.PaddedPieceSize) (uint64) + + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Size)); err != nil { + return err + } + + // t.TermMin (abi.ChainEpoch) (int64) + if t.TermMin >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.TermMin)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.TermMin-1)); err != nil { + return err + } + } + + // t.TermMax (abi.ChainEpoch) (int64) + if t.TermMax >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.TermMax)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.TermMax-1)); err != nil { + return err + } + } + + // t.Expiration (abi.ChainEpoch) (int64) + if t.Expiration >= 0 { + if err := cw.WriteMajorTypeHeader(cbg.MajUnsignedInt, uint64(t.Expiration)); err != nil { + return err + } + } else { + if err := cw.WriteMajorTypeHeader(cbg.MajNegativeInt, uint64(-t.Expiration-1)); err != nil { + return err + } + } + + return nil +} + +func (t *AllocationRequest) UnmarshalCBOR(r io.Reader) (err error) { + *t = AllocationRequest{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 6 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Provider (abi.ActorID) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Provider = abi.ActorID(extra) + + } + // t.Data (cid.Cid) (struct) + + { + + c, err := cbg.ReadCid(cr) + if err != nil { + return xerrors.Errorf("failed to read cid field t.Data: %w", err) + } + + t.Data = c + + } + // t.Size (abi.PaddedPieceSize) (uint64) + + { + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + if maj != cbg.MajUnsignedInt { + return fmt.Errorf("wrong type for uint64 field") + } + t.Size = abi.PaddedPieceSize(extra) + + } + // t.TermMin (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.TermMin = abi.ChainEpoch(extraI) + } + // t.TermMax (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.TermMax = abi.ChainEpoch(extraI) + } + // t.Expiration (abi.ChainEpoch) (int64) + { + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + var extraI int64 + 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 overflow") + } + extraI = -1 - extraI + default: + return fmt.Errorf("wrong type for int64 field: %d", maj) + } + + t.Expiration = abi.ChainEpoch(extraI) + } + return nil +} + +var lengthBufAllocationRequests = []byte{130} + +func (t *AllocationRequests) MarshalCBOR(w io.Writer) error { + if t == nil { + _, err := w.Write(cbg.CborNull) + return err + } + + cw := cbg.NewCborWriter(w) + + if _, err := cw.Write(lengthBufAllocationRequests); err != nil { + return err + } + + // t.Allocations ([]verifreg.AllocationRequest) (slice) + if len(t.Allocations) > 8192 { + return xerrors.Errorf("Slice value in field t.Allocations was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Allocations))); err != nil { + return err + } + for _, v := range t.Allocations { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + + // t.Extensions ([]verifreg.ClaimExtensionRequest) (slice) + if len(t.Extensions) > 8192 { + return xerrors.Errorf("Slice value in field t.Extensions was too long") + } + + if err := cw.WriteMajorTypeHeader(cbg.MajArray, uint64(len(t.Extensions))); err != nil { + return err + } + for _, v := range t.Extensions { + if err := v.MarshalCBOR(cw); err != nil { + return err + } + + } + return nil +} + +func (t *AllocationRequests) UnmarshalCBOR(r io.Reader) (err error) { + *t = AllocationRequests{} + + cr := cbg.NewCborReader(r) + + maj, extra, err := cr.ReadHeader() + if err != nil { + return err + } + defer func() { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + }() + + if maj != cbg.MajArray { + return fmt.Errorf("cbor input should be of type array") + } + + if extra != 2 { + return fmt.Errorf("cbor input had wrong number of fields") + } + + // t.Allocations ([]verifreg.AllocationRequest) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Allocations: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Allocations = make([]AllocationRequest, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Allocations[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Allocations[i]: %w", err) + } + + } + + } + } + // t.Extensions ([]verifreg.ClaimExtensionRequest) (slice) + + maj, extra, err = cr.ReadHeader() + if err != nil { + return err + } + + if extra > 8192 { + return fmt.Errorf("t.Extensions: array too large (%d)", extra) + } + + if maj != cbg.MajArray { + return fmt.Errorf("expected cbor array") + } + + if extra > 0 { + t.Extensions = make([]ClaimExtensionRequest, extra) + } + + for i := 0; i < int(extra); i++ { + { + var maj byte + var extra uint64 + var err error + _ = maj + _ = extra + _ = err + + { + + if err := t.Extensions[i].UnmarshalCBOR(cr); err != nil { + return xerrors.Errorf("unmarshaling t.Extensions[i]: %w", err) + } + + } + + } + } + return nil +} diff --git a/builtin/v18/verifreg/invariants.go b/builtin/v18/verifreg/invariants.go new file mode 100644 index 00000000..26cce3fd --- /dev/null +++ b/builtin/v18/verifreg/invariants.go @@ -0,0 +1,130 @@ +package verifreg + +import ( + "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" + + addr "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/builtin" + "github.com/filecoin-project/go-state-types/builtin/v18/util/adt" +) + +type StateSummary struct { + Verifiers map[addr.Address]DataCap + Claims map[ClaimId]Claim + Allocations map[AllocationId]Allocation +} + +// Checks internal invariants of verified registry state. +func CheckStateInvariants(st *State, store adt.Store, priorEpoch abi.ChainEpoch) (*StateSummary, *builtin.MessageAccumulator) { + acc := &builtin.MessageAccumulator{} + acc.Require(st.RootKey.Protocol() == addr.ID, "root key %v should have ID protocol", st.RootKey) + + // Check verifiers + allVerifiers := map[addr.Address]DataCap{} + if verifiers, err := adt.AsMap(store, st.Verifiers, builtin.DefaultHamtBitwidth); err != nil { + acc.Addf("error loading verifiers: %v", err) + } else { + var vcap abi.StoragePower + err = verifiers.ForEach(&vcap, func(key string) error { + verifier, err := addr.NewFromBytes([]byte(key)) + acc.RequireNoError(err, "error getting verifier from bytes") + + acc.Require(verifier.Protocol() == addr.ID, "verifier %v should have ID protocol", verifier) + acc.Require(vcap.GreaterThanEqual(big.Zero()), "verifier %v cap %v is negative", verifier, vcap) + allVerifiers[verifier] = vcap.Copy() + return nil + }) + acc.RequireNoError(err, "error iterating verifiers") + } + + // Check Claims + allClaims := make(map[ClaimId]Claim) + outerClaimsMap, err := adt.AsMap(store, st.Claims, builtin.DefaultHamtBitwidth) + acc.RequireNoError(err, "error getting outer claims map") + + var innerClaimHamtCid cbg.CborCid + err = outerClaimsMap.ForEach(&innerClaimHamtCid, func(idKey string) error { + providerId, err := abi.ParseUIntKey(idKey) + acc.RequireNoError(err, "error parsing provider id to uint") + innerMap, err := adt.AsMap(store, cid.Cid(innerClaimHamtCid), builtin.DefaultHamtBitwidth) + acc.RequireNoError(err, "error getting inner claims map") + + var out Claim + err = innerMap.ForEach(&out, func(claimIdStr string) error { + claimId, err := abi.ParseUIntKey(claimIdStr) + acc.RequireNoError(err, "error parsing claim id to uint") + + checkClaimState(ClaimId(claimId), &out, abi.ActorID(providerId), st.NextAllocationId, priorEpoch, acc) + allClaims[ClaimId(claimId)] = out + return nil + }) + acc.RequireNoError(err, "error iterating over inner claims map") + return nil + }) + acc.RequireNoError(err, "error iterating over claims") + + // Check Allocations + allAllocations := make(map[AllocationId]Allocation) + outerAllocMap, err := adt.AsMap(store, st.Allocations, builtin.DefaultHamtBitwidth) + acc.RequireNoError(err, "error getting outer allocations map") + + var innerAllocHamtCid cbg.CborCid + err = outerAllocMap.ForEach(&innerAllocHamtCid, func(idKey string) error { + clientId, err := abi.ParseUIntKey(idKey) + acc.RequireNoError(err, "error parsing client id to uint") + innerMap, err := adt.AsMap(store, cid.Cid(innerAllocHamtCid), builtin.DefaultHamtBitwidth) + acc.RequireNoError(err, "error getting inner allocations map") + + var alloc Allocation + err = innerMap.ForEach(&alloc, func(claimIdStr string) error { + allocId, err := abi.ParseUIntKey(claimIdStr) + acc.RequireNoError(err, "error parsing allocation id to uint") + + checkAllocationState(AllocationId(allocId), &alloc, abi.ActorID(clientId), st.NextAllocationId, priorEpoch, acc) + allAllocations[AllocationId(allocId)] = alloc + return nil + }) + acc.RequireNoError(err, "error iterating over inner allocations map") + return nil + }) + acc.RequireNoError(err, "error iterating over allocations") + + return &StateSummary{ + Verifiers: allVerifiers, + Claims: allClaims, + Allocations: allAllocations, + }, acc +} + +func checkAllocationState(id AllocationId, alloc *Allocation, client abi.ActorID, nextAllocId AllocationId, priorEpoch abi.ChainEpoch, acc *builtin.MessageAccumulator) { + acc.Require(id < nextAllocId, "allocation id %d exceeds next %d", id, nextAllocId) + + acc.Require(alloc.Client == client, "allocation %d client %d doesn't match key %d", id, alloc.Client, client) + + acc.Require(alloc.Size >= MinimumVerifiedAllocationSize, "allocation %d size %d too small", id, alloc.Size) + + acc.Require(alloc.TermMin >= MinimumVerifiedAllocationTerm, "allocation %d term min %d too small", id, alloc.TermMin) + + acc.Require(alloc.TermMax <= MaximumVerifiedAllocationTerm, "allocation %d term max %d too large", id, alloc.TermMax) + + acc.Require(alloc.TermMin <= alloc.TermMax, "allocation %d term min %d exceeds max %d", id, alloc.TermMin, alloc.TermMin) + + acc.Require(alloc.Expiration <= priorEpoch+MaximumVerifiedAllocationExpiration, "allocation %d expiration %d too far from now %d", id, alloc.Expiration, priorEpoch) +} + +func checkClaimState(id ClaimId, claim *Claim, provider abi.ActorID, nextAllocId AllocationId, priorEpoch abi.ChainEpoch, acc *builtin.MessageAccumulator) { + acc.Require(AllocationId(id) < nextAllocId, "claim id %d exceeds next %d", id, nextAllocId) + + acc.Require(claim.Provider == provider, "claim %d provider %d doesn't match key %d", id, claim.Provider, provider) + + acc.Require(claim.Size >= MinimumVerifiedAllocationSize, "claim %d size %d too small", id, claim.Size) + + acc.Require(claim.TermMin >= MinimumVerifiedAllocationTerm, "claim %d term min %d too small", id, claim.TermMin) + + acc.Require(claim.TermMin <= claim.TermMax, "claim %d term min %d exceeds max %d", id, claim.TermMin, claim.TermMin) + + acc.Require(claim.TermStart <= priorEpoch, "claim %d term start %d after now %d", id, claim.TermStart, priorEpoch) +} diff --git a/builtin/v18/verifreg/methods.go b/builtin/v18/verifreg/methods.go new file mode 100644 index 00000000..ee8769db --- /dev/null +++ b/builtin/v18/verifreg/methods.go @@ -0,0 +1,28 @@ +package verifreg + +import ( + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/builtin" +) + +var Methods = map[abi.MethodNum]builtin.MethodMeta{ + 1: builtin.NewMethodMeta("Constructor", *new(func(*address.Address) *abi.EmptyValue)), // Constructor + 2: builtin.NewMethodMeta("AddVerifier", *new(func(*AddVerifierParams) *abi.EmptyValue)), // AddVerifier + 3: builtin.NewMethodMeta("RemoveVerifier", *new(func(*address.Address) *abi.EmptyValue)), // RemoveVerifier + 4: builtin.NewMethodMeta("AddVerifiedClient", *new(func(*AddVerifiedClientParams) *abi.EmptyValue)), // AddVerifiedClient + builtin.MustGenerateFRCMethodNum("AddVerifiedClient"): builtin.NewMethodMeta("AddVerifiedClientExported", *new(func(*AddVerifiedClientParams) *abi.EmptyValue)), // AddVerifiedClientExported + 5: builtin.NewMethodMeta("UseBytes", nil), // deprecated + 6: builtin.NewMethodMeta("RestoreBytes", nil), // deprecated + 7: builtin.NewMethodMeta("RemoveVerifiedClientDataCap", *new(func(*RemoveDataCapParams) *RemoveDataCapReturn)), // RemoveVerifiedClientDataCap + 8: builtin.NewMethodMeta("RemoveExpiredAllocations", *new(func(*RemoveExpiredAllocationsParams) *RemoveExpiredAllocationsReturn)), // RemoveExpiredAllocations + builtin.MustGenerateFRCMethodNum("RemoveExpiredAllocations"): builtin.NewMethodMeta("RemoveExpiredAllocationsExported", *new(func(*RemoveExpiredAllocationsParams) *RemoveExpiredAllocationsReturn)), // RemoveExpiredAllocationsExported + 9: builtin.NewMethodMeta("ClaimAllocations", *new(func(*ClaimAllocationsParams) *ClaimAllocationsReturn)), // ClaimAllocations + 10: builtin.NewMethodMeta("GetClaims", *new(func(*GetClaimsParams) *GetClaimsReturn)), // GetClaims + builtin.MustGenerateFRCMethodNum("GetClaims"): builtin.NewMethodMeta("GetClaimsExported", *new(func(*GetClaimsParams) *GetClaimsReturn)), // GetClaimsExported + 11: builtin.NewMethodMeta("ExtendClaimTerms", *new(func(*ExtendClaimTermsParams) *ExtendClaimTermsReturn)), // ExtendClaimTerms + builtin.MustGenerateFRCMethodNum("ExtendClaimTerms"): builtin.NewMethodMeta("ExtendClaimTermsExported", *new(func(*ExtendClaimTermsParams) *ExtendClaimTermsReturn)), // ExtendClaimTermsExported + 12: builtin.NewMethodMeta("RemoveExpiredClaims", *new(func(*RemoveExpiredClaimsParams) *RemoveExpiredClaimsReturn)), // RemoveExpiredClaims + builtin.MustGenerateFRCMethodNum("RemoveExpiredClaims"): builtin.NewMethodMeta("RemoveExpiredClaimsExported", *new(func(*RemoveExpiredClaimsParams) *RemoveExpiredClaimsReturn)), // RemoveExpiredClaimsExported + builtin.MustGenerateFRCMethodNum("Receive"): builtin.NewMethodMeta("UniversalReceiverHook", *new(func(*UniversalReceiverParams) *AllocationsResponse)), // UniversalReceiverHook +} diff --git a/builtin/v18/verifreg/policy.go b/builtin/v18/verifreg/policy.go new file mode 100644 index 00000000..fa3f2230 --- /dev/null +++ b/builtin/v18/verifreg/policy.go @@ -0,0 +1,17 @@ +package verifreg + +import ( + "github.com/filecoin-project/go-state-types/builtin" +) + +const EndOfLifeClaimDropPeriod = 30 * builtin.EpochsInDay + +const MaximumVerifiedAllocationExpiration = 60 * builtin.EpochsInDay + +const MinimumVerifiedAllocationTerm = 180 * builtin.EpochsInDay + +const MaximumVerifiedAllocationTerm = 5 * builtin.EpochsInYear + +const NoAllocationID = AllocationId(0) + +const MinimumVerifiedAllocationSize = 1 << 20 diff --git a/builtin/v18/verifreg/verified_registry_state.go b/builtin/v18/verifreg/verified_registry_state.go new file mode 100644 index 00000000..af9aa7fc --- /dev/null +++ b/builtin/v18/verifreg/verified_registry_state.go @@ -0,0 +1,305 @@ +package verifreg + +import ( + "github.com/ipfs/go-cid" + cbg "github.com/whyrusleeping/cbor-gen" + "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/builtin" + "github.com/filecoin-project/go-state-types/builtin/v18/util/adt" +) + +// DataCap is an integer number of bytes. +// We can introduce policy changes and replace this in the future. +type DataCap = abi.StoragePower + +var DataCapGranularity = builtin.TokenPrecision + +const SignatureDomainSeparation_RemoveDataCap = "fil_removedatacap:" + +type RmDcProposalID struct { + ProposalID uint64 +} + +type State struct { + // Root key holder multisig. + // Authorize and remove verifiers. + RootKey address.Address + + // Verifiers authorize VerifiedClients. + // Verifiers delegate their DataCap. + Verifiers cid.Cid // HAMT[addr.Address]DataCap + + // RemoveDataCapProposalIDs keeps the counters of the datacap removal proposal a verifier has submitted for a + //specific client. Unique proposal ids ensure that removal proposals cannot be replayed.√ + // AddrPairKey is constructed as , both using ID addresses. + RemoveDataCapProposalIDs cid.Cid // HAMT[AddrPairKey]RmDcProposalID + + // Maps client IDs to allocations made by that client. + Allocations cid.Cid // HAMT[ActorID]HAMT[AllocationID]Allocation + + // Next allocation identifier to use. + // The value 0 is reserved to mean "no allocation". + NextAllocationId AllocationId + + // Maps provider IDs to allocations claimed by that provider. + Claims cid.Cid // HAMT[ActorID]HAMT[ClaimID]Claim +} + +var MinVerifiedDealSize = abi.NewStoragePower(1 << 20) + +// rootKeyAddress comes from genesis. +func ConstructState(store adt.Store, rootKeyAddress address.Address) (*State, error) { + emptyMapCid, err := adt.StoreEmptyMap(store, builtin.DefaultHamtBitwidth) + if err != nil { + return nil, xerrors.Errorf("failed to create empty map: %w", err) + } + + return &State{ + RootKey: rootKeyAddress, + Verifiers: emptyMapCid, + RemoveDataCapProposalIDs: emptyMapCid, + Allocations: emptyMapCid, + NextAllocationId: 1, + Claims: emptyMapCid, + }, nil +} + +func (st *State) FindAllocation(store adt.Store, clientIdAddr address.Address, allocationId AllocationId) (*Allocation, bool, error) { + if clientIdAddr.Protocol() != address.ID { + return nil, false, xerrors.Errorf("can only look up ID addresses") + } + + innerHamtCid, ok, err := getInnerHamtCid(store, abi.IdAddrKey(clientIdAddr), st.Allocations) + if err != nil { + return nil, false, xerrors.Errorf("failed to get inner hamt cid: %w", err) + } + + if !ok { + return nil, ok, nil + } + + idToAllocationMap, err := adt.AsMap(store, innerHamtCid, builtin.DefaultHamtBitwidth) + if err != nil { + return nil, false, xerrors.Errorf("couldn't get inner map: %x", err) + } + + var allocation Allocation + if found, err := idToAllocationMap.Get(allocationId, &allocation); err != nil { + return nil, false, xerrors.Errorf("looking up allocation ID: %d: %w", allocationId, err) + } else if !found { + return nil, false, nil + } + + clientId, err := address.IDFromAddress(clientIdAddr) + if err != nil { + return nil, false, xerrors.Errorf("couldn't get ID from clientIdAddr: %s", clientIdAddr) + } + + if uint64(allocation.Client) != clientId { + return nil, false, xerrors.Errorf("clientId: %d did not match client in allocation: %d", clientId, allocation.Client) + } + + return &allocation, true, nil +} + +func (st *State) FindClaim(store adt.Store, providerIdAddr address.Address, claimId ClaimId) (*Claim, bool, error) { + if providerIdAddr.Protocol() != address.ID { + return nil, false, xerrors.Errorf("can only look up ID addresses") + } + + innerHamtCid, ok, err := getInnerHamtCid(store, abi.IdAddrKey(providerIdAddr), st.Claims) + if err != nil { + return nil, false, xerrors.Errorf("failed to get inner hamt cid: %w", err) + } + + if !ok { + return nil, ok, nil + } + + idToClaimsMap, err := adt.AsMap(store, innerHamtCid, builtin.DefaultHamtBitwidth) + if err != nil { + return nil, false, xerrors.Errorf("couldn't get inner map: %x", err) + } + + var claim Claim + if found, err := idToClaimsMap.Get(claimId, &claim); err != nil { + return nil, false, xerrors.Errorf("looking up allocation ID: %d: %w", claimId, err) + } else if !found { + return nil, false, nil + } + + providerId, err := address.IDFromAddress(providerIdAddr) + if err != nil { + return nil, false, xerrors.Errorf("couldn't get ID from providerIdAddr: %s", providerIdAddr) + } + + if uint64(claim.Provider) != providerId { + return nil, false, xerrors.Errorf("providerId: %d did not match provider in claim: %d", providerId, claim.Provider) + } + + return &claim, true, nil +} + +func getInnerHamtCid(store adt.Store, key abi.Keyer, mapCid cid.Cid) (cid.Cid, bool, error) { + actorToHamtMap, err := adt.AsMap(store, mapCid, builtin.DefaultHamtBitwidth) + if err != nil { + return cid.Undef, false, xerrors.Errorf("couldn't get outer map: %x", err) + } + + var innerHamtCid cbg.CborCid + found, err := actorToHamtMap.Get(key, &innerHamtCid) + if err != nil { + return cid.Undef, false, xerrors.Errorf("looking up key: %s: %w", key, err) + } + + return cid.Cid(innerHamtCid), found, nil +} + +func (st *State) LoadAllocationsToMap(store adt.Store, clientIdAddr address.Address) (map[AllocationId]Allocation, error) { + if clientIdAddr.Protocol() != address.ID { + return nil, xerrors.Errorf("can only look up ID addresses") + } + + allocIdToAlloc := make(map[AllocationId]Allocation) + innerHamtCid, ok, err := getInnerHamtCid(store, abi.IdAddrKey(clientIdAddr), st.Allocations) + if err != nil { + return nil, xerrors.Errorf("failed to get inner hamt cid: %w", err) + } + + if !ok { + return allocIdToAlloc, nil + } + + adtMap, err := adt.AsMap(store, innerHamtCid, builtin.DefaultHamtBitwidth) + if err != nil { + return nil, xerrors.Errorf("couldn't get map: %x", err) + } + + var out Allocation + err = adtMap.ForEach(&out, func(key string) error { + uintKey, err := abi.ParseUIntKey(key) + if err != nil { + return xerrors.Errorf("couldn't parse key to uint: %x", err) + } + allocIdToAlloc[AllocationId(uintKey)] = out + return nil + }) + if err != nil { + return nil, xerrors.Errorf("failed to iterate: %w", err) + } + + return allocIdToAlloc, nil +} + +func (st *State) LoadClaimsToMap(store adt.Store, providerIdAddr address.Address) (map[ClaimId]Claim, error) { + if providerIdAddr.Protocol() != address.ID { + return nil, xerrors.Errorf("can only look up ID addresses") + } + + claimIdToClaim := make(map[ClaimId]Claim) + innerHamtCid, ok, err := getInnerHamtCid(store, abi.IdAddrKey(providerIdAddr), st.Claims) + if err != nil { + return nil, xerrors.Errorf("failed to get inner hamt cid: %w", err) + } + + if !ok { + return claimIdToClaim, nil + } + + adtMap, err := adt.AsMap(store, innerHamtCid, builtin.DefaultHamtBitwidth) + if err != nil { + return nil, xerrors.Errorf("couldn't get map: %x", err) + } + + var out Claim + err = adtMap.ForEach(&out, func(key string) error { + uintKey, err := abi.ParseUIntKey(key) + if err != nil { + return xerrors.Errorf("couldn't parse key to uint: %w", err) + } + claimIdToClaim[ClaimId(uintKey)] = out + return nil + }) + if err != nil { + return nil, xerrors.Errorf("failed to iterate: %w", err) + } + + return claimIdToClaim, nil +} + +func (st *State) GetAllClaims(store adt.Store) (map[ClaimId]Claim, error) { + allClaims := make(map[ClaimId]Claim) + + actorToHamtMap, err := adt.AsMap(store, st.Claims, builtin.DefaultHamtBitwidth) + if err != nil { + return nil, xerrors.Errorf("couldn't get outer map: %x", err) + } + + var innerHamtCid cbg.CborCid + err = actorToHamtMap.ForEach(&innerHamtCid, func(idKey string) error { + innerMap, err := adt.AsMap(store, cid.Cid(innerHamtCid), builtin.DefaultHamtBitwidth) + if err != nil { + return xerrors.Errorf("couldn't get inner map: %x", err) + } + + var out Claim + err = innerMap.ForEach(&out, func(key string) error { + uintKey, err := abi.ParseUIntKey(key) + if err != nil { + return xerrors.Errorf("couldn't parse idKey to uint: %w", err) + } + allClaims[ClaimId(uintKey)] = out + return nil + }) + if err != nil { + return err + } + + return nil + }) + if err != nil { + return nil, err + } + + return allClaims, nil +} + +func (st *State) GetAllAllocations(store adt.Store) (map[AllocationId]Allocation, error) { + allAllocations := make(map[AllocationId]Allocation) + + actorToHamtMap, err := adt.AsMap(store, st.Allocations, builtin.DefaultHamtBitwidth) + if err != nil { + return nil, xerrors.Errorf("couldn't get outer map: %x", err) + } + + var innerHamtCid cbg.CborCid + err = actorToHamtMap.ForEach(&innerHamtCid, func(idKey string) error { + innerMap, err := adt.AsMap(store, cid.Cid(innerHamtCid), builtin.DefaultHamtBitwidth) + if err != nil { + return xerrors.Errorf("couldn't get inner map: %x", err) + } + + var out Allocation + err = innerMap.ForEach(&out, func(key string) error { + uintKey, err := abi.ParseUIntKey(key) + if err != nil { + return xerrors.Errorf("couldn't parse idKey to uint: %w", err) + } + allAllocations[AllocationId(uintKey)] = out + return nil + }) + if err != nil { + return err + } + + return nil + }) + if err != nil { + return nil, err + } + + return allAllocations, nil +} diff --git a/builtin/v18/verifreg/verifreg_types.go b/builtin/v18/verifreg/verifreg_types.go new file mode 100644 index 00000000..d711ca76 --- /dev/null +++ b/builtin/v18/verifreg/verifreg_types.go @@ -0,0 +1,227 @@ +package verifreg + +import ( + "github.com/ipfs/go-cid" + "github.com/multiformats/go-varint" + + addr "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-state-types/abi" + "github.com/filecoin-project/go-state-types/batch" + "github.com/filecoin-project/go-state-types/big" + "github.com/filecoin-project/go-state-types/crypto" +) + +// RemoveDataCapProposal A verifier who wants to send/agree to a RemoveDataCapRequest should sign a RemoveDataCapProposal and send the signed proposal to the root key holder. +type RemoveDataCapProposal struct { + // VerifiedClient is the client address to remove the DataCap from + // The address must be an ID address + VerifiedClient addr.Address + // DataCapAmount is the amount of DataCap to be removed from the VerifiedClient address + DataCapAmount DataCap + // RemovalProposalID is the counter of the proposal sent by the Verifier for the VerifiedClient + RemovalProposalID RmDcProposalID +} + +// RemoveDataCapRequest A verifier who wants to submit a request should send their RemoveDataCapRequest to the RKH. +type RemoveDataCapRequest struct { + // Verifier is the verifier address used for VerifierSignature. + // The address can be address.SECP256K1 or address.BLS + Verifier addr.Address + // VerifierSignature is the Verifier's signature over a RemoveDataCapProposal + VerifierSignature crypto.Signature +} + +type AddVerifierParams struct { + Address addr.Address + Allowance DataCap +} + +type AddVerifiedClientParams struct { + Address addr.Address + Allowance DataCap +} + +type UseBytesParams struct { + // Address of verified client. + Address addr.Address + // Number of bytes to use. + DealSize abi.StoragePower +} + +type RestoreBytesParams struct { + Address addr.Address + DealSize abi.StoragePower +} + +type RemoveDataCapParams struct { + VerifiedClientToRemove addr.Address + DataCapAmountToRemove DataCap + VerifierRequest1 RemoveDataCapRequest + VerifierRequest2 RemoveDataCapRequest +} + +type RemoveDataCapReturn struct { + VerifiedClient addr.Address + DataCapRemoved DataCap +} + +type RemoveExpiredAllocationsParams struct { + Client abi.ActorID + AllocationIds []AllocationId +} + +type RemoveExpiredAllocationsReturn struct { + Considered []AllocationId + Results batch.BatchReturn + DataCapRecovered DataCap +} + +type AllocationId uint64 + +func (a AllocationId) Key() string { + return string(varint.ToUvarint(uint64(a))) +} + +type ClaimId uint64 + +func (a ClaimId) Key() string { + return string(varint.ToUvarint(uint64(a))) +} + +type ClaimAllocationsParams struct { + Sectors []SectorAllocationClaims + AllOrNothing bool +} + +type SectorAllocationClaims struct { + Sector abi.SectorNumber + SectorExpiry abi.ChainEpoch + Claims []AllocationClaim +} + +type AllocationClaim struct { + Client abi.ActorID + AllocationId AllocationId + Data cid.Cid + Size abi.PaddedPieceSize +} + +type ClaimAllocationsReturn struct { + BatchInfo batch.BatchReturn + ClaimedSpace big.Int +} + +type GetClaimsParams struct { + Provider abi.ActorID + ClaimIds []ClaimId +} + +type GetClaimsReturn struct { + BatchInfo batch.BatchReturn + Claims []Claim +} + +type Claim struct { + // The provider storing the data (from allocation). + Provider abi.ActorID + // The client which allocated the DataCap (from allocation). + Client abi.ActorID + // Identifier of the data committed (from allocation). + Data cid.Cid + // The (padded) size of data (from allocation). + Size abi.PaddedPieceSize + // The min period which the provider must commit to storing data + TermMin abi.ChainEpoch + // The max period for which provider can earn QA-power for the data + TermMax abi.ChainEpoch + // The epoch at which the (first range of the) piece was committed. + TermStart abi.ChainEpoch + // ID of the provider's sector in which the data is committed. + Sector abi.SectorNumber +} + +type Allocation struct { + // The verified client which allocated the DataCap. + Client abi.ActorID + // The provider (miner actor) which may claim the allocation. + Provider abi.ActorID + // Identifier of the data to be committed. + Data cid.Cid + // The (padded) size of data. + Size abi.PaddedPieceSize + // The minimum duration which the provider must commit to storing the piece to avoid + // early-termination penalties (epochs). + TermMin abi.ChainEpoch + // The maximum period for which a provider can earn quality-adjusted power + // for the piece (epochs). + TermMax abi.ChainEpoch + // The latest epoch by which a provider must commit data before the allocation expires. + Expiration abi.ChainEpoch +} + +type UniversalReceiverParams struct { + Type_ ReceiverType + Payload []byte +} + +type ReceiverType uint64 + +type AllocationsResponse struct { + AllocationResults batch.BatchReturn + ExtensionResults batch.BatchReturn + NewAllocations []AllocationId +} + +type ExtendClaimTermsParams struct { + Terms []ClaimTerm +} + +type ClaimTerm struct { + Provider abi.ActorID + ClaimId ClaimId + TermMax abi.ChainEpoch +} + +type ExtendClaimTermsReturn batch.BatchReturn + +type RemoveExpiredClaimsParams struct { + Provider abi.ActorID + ClaimIds []ClaimId +} + +type RemoveExpiredClaimsReturn struct { + Considered []AllocationId + Results batch.BatchReturn +} + +type AllocationRequest struct { + // The provider (miner actor) which may claim the allocation. + Provider abi.ActorID + // Identifier of the data to be committed. + Data cid.Cid + // The (padded) size of data. + Size abi.PaddedPieceSize + // The minimum duration which the provider must commit to storing the piece to avoid + // early-termination penalties (epochs). + TermMin abi.ChainEpoch + // The maximum period for which a provider can earn quality-adjusted power + // for the piece (epochs). + TermMax abi.ChainEpoch + // The latest epoch by which a provider must commit data before the allocation expires. + Expiration abi.ChainEpoch +} + +type ClaimExtensionRequest struct { + // The provider (miner actor) which may claim the allocation. + Provider abi.ActorID + // Identifier of the claim to be extended. + Claim ClaimId + // The new maximum period for which a provider can earn quality-adjusted power + // for the piece (epochs). + TermMax abi.ChainEpoch +} + +type AllocationRequests struct { + Allocations []AllocationRequest + Extensions []ClaimExtensionRequest +} diff --git a/builtin/v18/verifreg/verifreg_types_test.go b/builtin/v18/verifreg/verifreg_types_test.go new file mode 100644 index 00000000..3d8f6068 --- /dev/null +++ b/builtin/v18/verifreg/verifreg_types_test.go @@ -0,0 +1,77 @@ +package verifreg + +import ( + "bytes" + "encoding/hex" + "testing" + + "github.com/ipfs/go-cid" + "github.com/stretchr/testify/require" +) + +// Tests to match with Rust fil_actor_verifreg::serialization + +func TestSerializationClaimAllocationsParams(t *testing.T) { + testCases := []struct { + params ClaimAllocationsParams + hex string + }{ + { + params: ClaimAllocationsParams{Sectors: nil, AllOrNothing: false}, + // [[],false] + hex: "8280f4", + }, + { + params: ClaimAllocationsParams{ + Sectors: []SectorAllocationClaims{{ + Sector: 101, + SectorExpiry: 202, + Claims: nil, + }}, + AllOrNothing: true, + }, + // [[[101,202,[]]],true] + hex: "828183186518ca80f5", + }, + { + params: ClaimAllocationsParams{ + Sectors: []SectorAllocationClaims{{ + Sector: 101, + SectorExpiry: 202, + Claims: []AllocationClaim{ + { + Client: 303, + AllocationId: 404, + Data: cid.MustParse("baga6ea4seaaqa"), + Size: 505, + }, + { + Client: 606, + AllocationId: 707, + Data: cid.MustParse("baga6ea4seaaqc"), + Size: 808, + }, + }, + }, + {Sector: 303, SectorExpiry: 404, Claims: nil}, + }, + AllOrNothing: true, + }, + // [[[101,202,[[303,404,baga6ea4seaaqa,505],[606,707,baga6ea4seaaqc,808]]],[303,404,[]]],true] + hex: "828283186518ca828419012f190194d82a49000181e203922001001901f98419025e1902c3d82a49000181e203922001011903288319012f19019480f5", + }, + } + + for _, tc := range testCases { + t.Run("", func(t *testing.T) { + req := require.New(t) + + var buf bytes.Buffer + req.NoError(tc.params.MarshalCBOR(&buf)) + req.Equal(tc.hex, hex.EncodeToString(buf.Bytes())) + var rt ClaimAllocationsParams + req.NoError(rt.UnmarshalCBOR(&buf)) + req.Equal(tc.params, rt) + }) + } +} diff --git a/network/version.go b/network/version.go index 11a69a6e..a92695e6 100644 --- a/network/version.go +++ b/network/version.go @@ -34,7 +34,8 @@ const ( Version24 // TukTuk Version25 // Teep Version26 // Tock - Version27 // TBD + Version27 // GoldenWeek + Version28 // TBD // VersionMax is the maximum version number VersionMax = Version(math.MaxUint32)