Merge pull request #3936 from filecoin-project/asr/spec-v1

Introduce v2 actors
This commit is contained in:
Aayush Rajasekaran 2020-10-06 17:34:28 -04:00 committed by GitHub
commit 8739b938db
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
121 changed files with 3239 additions and 1191 deletions

View File

@ -12,15 +12,36 @@ import (
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/lotus/build"
"github.com/filecoin-project/lotus/chain/stmgr"
"github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/types"
"github.com/filecoin-project/lotus/node"
"github.com/filecoin-project/lotus/node/impl" "github.com/filecoin-project/lotus/node/impl"
) )
func TestCCUpgrade(t *testing.T, b APIBuilder, blocktime time.Duration) { func TestCCUpgrade(t *testing.T, b APIBuilder, blocktime time.Duration) {
_ = os.Setenv("BELLMAN_NO_GPU", "1") _ = os.Setenv("BELLMAN_NO_GPU", "1")
for _, height := range []abi.ChainEpoch{
1, // before
162, // while sealing
520, // after upgrade deal
5000, // after
} {
height := height // make linters happy by copying
t.Run(fmt.Sprintf("upgrade-%d", height), func(t *testing.T) {
testCCUpgrade(t, b, blocktime, height)
})
}
}
func testCCUpgrade(t *testing.T, b APIBuilder, blocktime time.Duration, upgradeHeight abi.ChainEpoch) {
ctx := context.Background() ctx := context.Background()
n, sn := b(t, 1, OneMiner) n, sn := b(t, 1, OneMiner, node.Override(new(stmgr.UpgradeSchedule), stmgr.UpgradeSchedule{{
Network: build.ActorUpgradeNetworkVersion,
Height: upgradeHeight,
Migration: stmgr.UpgradeActorsV2,
}}))
client := n[0].FullNode.(*impl.FullNodeAPI) client := n[0].FullNode.(*impl.FullNodeAPI)
miner := sn[0] miner := sn[0]

View File

@ -402,9 +402,12 @@ func testRetrieval(t *testing.T, ctx context.Context, client *impl.FullNodeAPI,
IsCAR: carExport, IsCAR: carExport,
} }
updates, err := client.ClientRetrieveWithEvents(ctx, offers[0].Order(caddr), ref) updates, err := client.ClientRetrieveWithEvents(ctx, offers[0].Order(caddr), ref)
if err != nil {
t.Fatal(err)
}
for update := range updates { for update := range updates {
if update.Err != "" { if update.Err != "" {
t.Fatalf("%v", err) t.Fatalf("retrieval failed: %s", update.Err)
} }
} }

View File

@ -8,17 +8,21 @@ import (
"testing" "testing"
"time" "time"
"github.com/filecoin-project/specs-actors/actors/builtin" builtin0 "github.com/filecoin-project/specs-actors/actors/builtin"
paych0 "github.com/filecoin-project/specs-actors/actors/builtin/paych"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/specs-actors/actors/builtin/paych"
"github.com/ipfs/go-cid" "github.com/ipfs/go-cid"
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
cbor "github.com/ipfs/go-ipld-cbor"
"github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/api"
"github.com/filecoin-project/lotus/api/apibstore"
"github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/build"
"github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/filecoin-project/lotus/chain/actors/builtin/paych"
"github.com/filecoin-project/lotus/chain/events" "github.com/filecoin-project/lotus/chain/events"
"github.com/filecoin-project/lotus/chain/events/state" "github.com/filecoin-project/lotus/chain/events/state"
"github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/types"
@ -133,17 +137,26 @@ func TestPaymentChannels(t *testing.T, b APIBuilder, blocktime time.Duration) {
t.Fatal("Unable to settle payment channel") t.Fatal("Unable to settle payment channel")
} }
creatorStore := adt.WrapStore(ctx, cbor.NewCborStore(apibstore.NewAPIBlockstore(paymentCreator)))
// wait for the receiver to submit their vouchers // wait for the receiver to submit their vouchers
ev := events.NewEvents(ctx, paymentCreator) ev := events.NewEvents(ctx, paymentCreator)
preds := state.NewStatePredicates(paymentCreator) preds := state.NewStatePredicates(paymentCreator)
finished := make(chan struct{}) finished := make(chan struct{})
err = ev.StateChanged(func(ts *types.TipSet) (done bool, more bool, err error) { err = ev.StateChanged(func(ts *types.TipSet) (done bool, more bool, err error) {
act, err := paymentCreator.StateReadState(ctx, channel, ts.Key()) act, err := paymentCreator.StateGetActor(ctx, channel, ts.Key())
if err != nil { if err != nil {
return false, false, err return false, false, err
} }
state := act.State.(paych.State) state, err := paych.Load(creatorStore, act)
if state.ToSend.GreaterThanEqual(abi.NewTokenAmount(6000)) { if err != nil {
return false, false, err
}
toSend, err := state.ToSend()
if err != nil {
return false, false, err
}
if toSend.GreaterThanEqual(abi.NewTokenAmount(6000)) {
return true, false, nil return true, false, nil
} }
return false, true, nil return false, true, nil
@ -156,7 +169,7 @@ func TestPaymentChannels(t *testing.T, b APIBuilder, blocktime time.Duration) {
return true, nil return true, nil
}, func(ctx context.Context, ts *types.TipSet) error { }, func(ctx context.Context, ts *types.TipSet) error {
return nil return nil
}, int(build.MessageConfidence)+1, build.SealRandomnessLookbackLimit, func(oldTs, newTs *types.TipSet) (bool, events.StateChange, error) { }, int(build.MessageConfidence)+1, build.Finality, func(oldTs, newTs *types.TipSet) (bool, events.StateChange, error) {
return preds.OnPaymentChannelActorChanged(channel, preds.OnToSendAmountChanges())(ctx, oldTs.Key(), newTs.Key()) return preds.OnPaymentChannelActorChanged(channel, preds.OnToSendAmountChanges())(ctx, oldTs.Key(), newTs.Key())
}) })
if err != nil { if err != nil {
@ -215,7 +228,7 @@ func TestPaymentChannels(t *testing.T, b APIBuilder, blocktime time.Duration) {
} }
// wait for the settlement period to pass before collecting // wait for the settlement period to pass before collecting
waitForBlocks(ctx, t, bm, paymentReceiver, receiverAddr, paych.SettleDelay) waitForBlocks(ctx, t, bm, paymentReceiver, receiverAddr, paych0.SettleDelay)
creatorPreCollectBalance, err := paymentCreator.WalletBalance(ctx, createrAddr) creatorPreCollectBalance, err := paymentCreator.WalletBalance(ctx, createrAddr)
if err != nil { if err != nil {
@ -271,7 +284,7 @@ func waitForBlocks(ctx context.Context, t *testing.T, bm *BlockMiner, paymentRec
// Add a real block // Add a real block
m, err := paymentReceiver.MpoolPushMessage(ctx, &types.Message{ m, err := paymentReceiver.MpoolPushMessage(ctx, &types.Message{
To: builtin.BurntFundsActorAddr, To: builtin0.BurntFundsActorAddr,
From: receiverAddr, From: receiverAddr,
Value: types.NewInt(0), Value: types.NewInt(0),
}, nil) }, nil)

View File

@ -12,6 +12,7 @@ import (
"github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/api"
"github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/build"
"github.com/filecoin-project/lotus/miner" "github.com/filecoin-project/lotus/miner"
"github.com/filecoin-project/lotus/node"
) )
type TestNode struct { type TestNode struct {
@ -44,7 +45,7 @@ type StorageMiner struct {
// //
// storage array defines storage nodes, numbers in the array specify full node // storage array defines storage nodes, numbers in the array specify full node
// index the storage node 'belongs' to // index the storage node 'belongs' to
type APIBuilder func(t *testing.T, nFull int, storage []StorageMiner) ([]TestNode, []TestStorageNode) type APIBuilder func(t *testing.T, nFull int, storage []StorageMiner, opts ...node.Option) ([]TestNode, []TestStorageNode)
type testSuite struct { type testSuite struct {
makeNodes APIBuilder makeNodes APIBuilder
} }

View File

@ -15,9 +15,11 @@ import (
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/lotus/extern/sector-storage/mock" "github.com/filecoin-project/lotus/extern/sector-storage/mock"
sealing "github.com/filecoin-project/lotus/extern/storage-sealing" sealing "github.com/filecoin-project/lotus/extern/storage-sealing"
"github.com/filecoin-project/lotus/node"
"github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/api"
"github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/build"
"github.com/filecoin-project/lotus/chain/stmgr"
"github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/types"
bminer "github.com/filecoin-project/lotus/miner" bminer "github.com/filecoin-project/lotus/miner"
"github.com/filecoin-project/lotus/node/impl" "github.com/filecoin-project/lotus/node/impl"
@ -114,8 +116,29 @@ func pledgeSectors(t *testing.T, ctx context.Context, miner TestStorageNode, n,
} }
func TestWindowPost(t *testing.T, b APIBuilder, blocktime time.Duration, nSectors int) { func TestWindowPost(t *testing.T, b APIBuilder, blocktime time.Duration, nSectors int) {
ctx := context.Background() for _, height := range []abi.ChainEpoch{
n, sn := b(t, 1, OneMiner) 1, // before
162, // while sealing
5000, // while proving
} {
height := height // copy to satisfy lints
t.Run(fmt.Sprintf("upgrade-%d", height), func(t *testing.T) {
testWindowPostUpgrade(t, b, blocktime, nSectors, height)
})
}
}
func testWindowPostUpgrade(t *testing.T, b APIBuilder, blocktime time.Duration, nSectors int,
upgradeHeight abi.ChainEpoch) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
n, sn := b(t, 1, OneMiner, node.Override(new(stmgr.UpgradeSchedule), stmgr.UpgradeSchedule{{
Network: build.ActorUpgradeNetworkVersion,
Height: upgradeHeight,
Migration: stmgr.UpgradeActorsV2,
}}))
client := n[0].FullNode.(*impl.FullNodeAPI) client := n[0].FullNode.(*impl.FullNodeAPI)
miner := sn[0] miner := sn[0]
@ -129,17 +152,24 @@ func TestWindowPost(t *testing.T, b APIBuilder, blocktime time.Duration, nSector
} }
build.Clock.Sleep(time.Second) build.Clock.Sleep(time.Second)
mine := true
done := make(chan struct{}) done := make(chan struct{})
go func() { go func() {
defer close(done) defer close(done)
for mine { for ctx.Err() == nil {
build.Clock.Sleep(blocktime) build.Clock.Sleep(blocktime)
if err := sn[0].MineOne(ctx, MineNext); err != nil { if err := sn[0].MineOne(ctx, MineNext); err != nil {
if ctx.Err() != nil {
// context was canceled, ignore the error.
return
}
t.Error(err) t.Error(err)
} }
} }
}() }()
defer func() {
cancel()
<-done
}()
pledgeSectors(t, ctx, miner, nSectors, 0, nil) pledgeSectors(t, ctx, miner, nSectors, 0, nil)
@ -159,7 +189,7 @@ func TestWindowPost(t *testing.T, b APIBuilder, blocktime time.Duration, nSector
head, err := client.ChainHead(ctx) head, err := client.ChainHead(ctx)
require.NoError(t, err) require.NoError(t, err)
if head.Height() > di.PeriodStart+(di.WPoStProvingPeriod)+2 { if head.Height() > di.PeriodStart+di.WPoStProvingPeriod+2 {
fmt.Printf("Now head.Height = %d\n", head.Height()) fmt.Printf("Now head.Height = %d\n", head.Height())
break break
} }
@ -289,12 +319,11 @@ func TestWindowPost(t *testing.T, b APIBuilder, blocktime time.Duration, nSector
pledgeSectors(t, ctx, miner, 1, nSectors, nil) pledgeSectors(t, ctx, miner, 1, nSectors, nil)
{ {
// wait a bit more // Wait until proven.
di, err = client.StateMinerProvingDeadline(ctx, maddr, types.EmptyTSK)
head, err := client.ChainHead(ctx)
require.NoError(t, err) require.NoError(t, err)
waitUntil := head.Height() + 10 waitUntil := di.PeriodStart + di.WPoStProvingPeriod + 2
fmt.Printf("End for head.Height > %d\n", waitUntil) fmt.Printf("End for head.Height > %d\n", waitUntil)
for { for {
@ -315,7 +344,4 @@ func TestWindowPost(t *testing.T, b APIBuilder, blocktime time.Duration, nSector
sectors = p.MinerPower.RawBytePower.Uint64() / uint64(ssz) sectors = p.MinerPower.RawBytePower.Uint64() / uint64(ssz)
require.Equal(t, nSectors+GenesisPreseals-2+1, int(sectors)) // -2 not recovered sectors + 1 just pledged require.Equal(t, nSectors+GenesisPreseals-2+1, int(sectors)) // -2 not recovered sectors + 1 just pledged
mine = false
<-done
} }

View File

@ -14,6 +14,7 @@ const BreezeGasTampingDuration = 0
const UpgradeSmokeHeight = -1 const UpgradeSmokeHeight = -1
const UpgradeIgnitionHeight = -2 const UpgradeIgnitionHeight = -2
const UpgradeLiftoffHeight = -3 const UpgradeLiftoffHeight = -3
const UpgradeActorsV2Height = 10
var DrandSchedule = map[abi.ChainEpoch]DrandEnum{ var DrandSchedule = map[abi.ChainEpoch]DrandEnum{
0: DrandMainnet, 0: DrandMainnet,

View File

@ -41,7 +41,7 @@ func DhtProtocolName(netName dtypes.NetworkName) protocol.ID {
func UseNewestNetwork() bool { func UseNewestNetwork() bool {
// TODO: Put these in a container we can iterate over // TODO: Put these in a container we can iterate over
if UpgradeBreezeHeight <= 0 && UpgradeSmokeHeight <= 0 { if UpgradeBreezeHeight <= 0 && UpgradeSmokeHeight <= 0 && UpgradeActorsV2Height <= 0 {
return true return true
} }
return false return false

View File

@ -7,12 +7,12 @@ import (
"os" "os"
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/filecoin-project/lotus/chain/actors/policy"
"github.com/filecoin-project/go-state-types/network" "github.com/filecoin-project/go-state-types/network"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin"
miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner"
) )
// ///// // /////
@ -25,7 +25,7 @@ const UnixfsLinksPerLevel = 1024
// Consensus / Network // Consensus / Network
const AllowableClockDriftSecs = uint64(1) const AllowableClockDriftSecs = uint64(1)
const NewestNetworkVersion = network.Version3 const NewestNetworkVersion = network.Version4
const ActorUpgradeNetworkVersion = network.Version4 const ActorUpgradeNetworkVersion = network.Version4
// Epochs // Epochs
@ -35,7 +35,7 @@ const ForkLengthThreshold = Finality
var BlocksPerEpoch = uint64(builtin.ExpectedLeadersPerEpoch) var BlocksPerEpoch = uint64(builtin.ExpectedLeadersPerEpoch)
// Epochs // Epochs
const Finality = miner0.ChainFinality const Finality = policy.ChainFinality
const MessageConfidence = uint64(5) const MessageConfidence = uint64(5)
// constants for Weight calculation // constants for Weight calculation
@ -47,13 +47,8 @@ const WRatioDen = uint64(2)
// Proofs // Proofs
// Epochs // Epochs
const SealRandomnessLookback = Finality // TODO: unused
const SealRandomnessLookback = policy.SealRandomnessLookback
// Epochs
const SealRandomnessLookbackLimit = SealRandomnessLookback + 2000 // TODO: Get from spec specs-actors
// Maximum lookback that randomness can be sourced from for a seal proof submission
const MaxSealLookback = SealRandomnessLookbackLimit + 2000 // TODO: Get from specs-actors
// ///// // /////
// Mining // Mining

View File

@ -13,7 +13,8 @@ import (
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/network" "github.com/filecoin-project/go-state-types/network"
"github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin"
miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner"
"github.com/filecoin-project/lotus/chain/actors/policy"
) )
var ( var (
@ -32,7 +33,7 @@ var (
AllowableClockDriftSecs = uint64(1) AllowableClockDriftSecs = uint64(1)
Finality = miner0.ChainFinality Finality = policy.ChainFinality
ForkLengthThreshold = Finality ForkLengthThreshold = Finality
SlashablePowerDelay = 20 SlashablePowerDelay = 20
@ -47,9 +48,7 @@ var (
BlsSignatureCacheSize = 40000 BlsSignatureCacheSize = 40000
VerifSigCacheSize = 32000 VerifSigCacheSize = 32000
SealRandomnessLookback = Finality SealRandomnessLookback = policy.SealRandomnessLookback
SealRandomnessLookbackLimit = SealRandomnessLookback + 2000
MaxSealLookback = SealRandomnessLookbackLimit + 2000
TicketRandomnessLookback = abi.ChainEpoch(1) TicketRandomnessLookback = abi.ChainEpoch(1)
WinningPoStSectorSetLookback = abi.ChainEpoch(10) WinningPoStSectorSetLookback = abi.ChainEpoch(10)
@ -77,13 +76,14 @@ var (
UpgradeSmokeHeight abi.ChainEpoch = -1 UpgradeSmokeHeight abi.ChainEpoch = -1
UpgradeIgnitionHeight abi.ChainEpoch = -2 UpgradeIgnitionHeight abi.ChainEpoch = -2
UpgradeLiftoffHeight abi.ChainEpoch = -3 UpgradeLiftoffHeight abi.ChainEpoch = -3
UpgradeActorsV2Height abi.ChainEpoch = 10
DrandSchedule = map[abi.ChainEpoch]DrandEnum{ DrandSchedule = map[abi.ChainEpoch]DrandEnum{
0: DrandMainnet, 0: DrandMainnet,
} }
NewestNetworkVersion = network.Version2 NewestNetworkVersion = network.Version4
ActorUpgradeNetworkVersion = network.Version3 ActorUpgradeNetworkVersion = network.Version4
Devnet = true Devnet = true
) )

View File

@ -23,6 +23,9 @@ const UpgradeSmokeHeight = 51000
const UpgradeIgnitionHeight = 94000 const UpgradeIgnitionHeight = 94000
// TODO: Actual epoch needs to be filled in
const UpgradeActorsV2Height = 128888
// This signals our tentative epoch for mainnet launch. Can make it later, but not earlier. // This signals our tentative epoch for mainnet launch. Can make it later, but not earlier.
// Miners, clients, developers, custodians all need time to prepare. // Miners, clients, developers, custodians all need time to prepare.
// We still have upgrades and state changes to do, but can happen after signaling timing here. // We still have upgrades and state changes to do, but can happen after signaling timing here.

View File

@ -7,8 +7,11 @@ import (
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/cbor" "github.com/filecoin-project/go-state-types/cbor"
"github.com/filecoin-project/go-state-types/network" "github.com/filecoin-project/go-state-types/network"
"github.com/filecoin-project/lotus/chain/actors/builtin"
"github.com/filecoin-project/lotus/chain/actors"
adt0 "github.com/filecoin-project/specs-actors/actors/util/adt" adt0 "github.com/filecoin-project/specs-actors/actors/util/adt"
adt2 "github.com/filecoin-project/specs-actors/v2/actors/util/adt"
) )
type Map interface { type Map interface {
@ -21,18 +24,22 @@ type Map interface {
ForEach(v cbor.Unmarshaler, fn func(key string) error) error ForEach(v cbor.Unmarshaler, fn func(key string) error) error
} }
func AsMap(store Store, root cid.Cid, version builtin.Version) (Map, error) { func AsMap(store Store, root cid.Cid, version actors.Version) (Map, error) {
switch version { switch version {
case builtin.Version0: case actors.Version0:
return adt0.AsMap(store, root) return adt0.AsMap(store, root)
case actors.Version2:
return adt2.AsMap(store, root)
} }
return nil, xerrors.Errorf("unknown network version: %d", version) return nil, xerrors.Errorf("unknown network version: %d", version)
} }
func NewMap(store Store, version builtin.Version) (Map, error) { func NewMap(store Store, version actors.Version) (Map, error) {
switch version { switch version {
case builtin.Version0: case actors.Version0:
return adt0.MakeEmptyMap(store), nil return adt0.MakeEmptyMap(store), nil
case actors.Version2:
return adt2.MakeEmptyMap(store), nil
} }
return nil, xerrors.Errorf("unknown network version: %d", version) return nil, xerrors.Errorf("unknown network version: %d", version)
} }
@ -49,17 +56,21 @@ type Array interface {
} }
func AsArray(store Store, root cid.Cid, version network.Version) (Array, error) { func AsArray(store Store, root cid.Cid, version network.Version) (Array, error) {
switch builtin.VersionForNetwork(version) { switch actors.VersionForNetwork(version) {
case builtin.Version0: case actors.Version0:
return adt0.AsArray(store, root) return adt0.AsArray(store, root)
case actors.Version2:
return adt2.AsArray(store, root)
} }
return nil, xerrors.Errorf("unknown network version: %d", version) return nil, xerrors.Errorf("unknown network version: %d", version)
} }
func NewArray(store Store, version builtin.Version) (Array, error) { func NewArray(store Store, version actors.Version) (Array, error) {
switch version { switch version {
case builtin.Version0: case actors.Version0:
return adt0.MakeEmptyArray(store), nil return adt0.MakeEmptyArray(store), nil
case actors.Version2:
return adt2.MakeEmptyArray(store), nil
} }
return nil, xerrors.Errorf("unknown network version: %d", version) return nil, xerrors.Errorf("unknown network version: %d", version)
} }

View File

@ -5,21 +5,31 @@ import (
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/cbor" "github.com/filecoin-project/go-state-types/cbor"
builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/ipfs/go-cid"
"github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/filecoin-project/lotus/chain/actors/builtin"
"github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/types"
builtin0 "github.com/filecoin-project/specs-actors/actors/builtin"
builtin2 "github.com/filecoin-project/specs-actors/v2/actors/builtin"
) )
func init() {
builtin.RegisterActorState(builtin0.AccountActorCodeID, func(store adt.Store, root cid.Cid) (cbor.Marshaler, error) {
return load0(store, root)
})
builtin.RegisterActorState(builtin2.AccountActorCodeID, func(store adt.Store, root cid.Cid) (cbor.Marshaler, error) {
return load2(store, root)
})
}
func Load(store adt.Store, act *types.Actor) (State, error) { func Load(store adt.Store, act *types.Actor) (State, error) {
switch act.Code { switch act.Code {
case builtin0.AccountActorCodeID: case builtin0.AccountActorCodeID:
out := state0{store: store} return load0(store, act.Head)
err := store.Get(store.Context(), act.Head, &out) case builtin2.AccountActorCodeID:
if err != nil { return load2(store, act.Head)
return nil, err
}
return &out, nil
} }
return nil, xerrors.Errorf("unknown actor code %s", act.Code) return nil, xerrors.Errorf("unknown actor code %s", act.Code)
} }

View File

@ -2,14 +2,26 @@ package account
import ( import (
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/ipfs/go-cid"
"github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/filecoin-project/specs-actors/actors/builtin/account"
account0 "github.com/filecoin-project/specs-actors/actors/builtin/account"
) )
var _ State = (*state0)(nil) var _ State = (*state0)(nil)
func load0(store adt.Store, root cid.Cid) (State, error) {
out := state0{store: store}
err := store.Get(store.Context(), root, &out)
if err != nil {
return nil, err
}
return &out, nil
}
type state0 struct { type state0 struct {
account.State account0.State
store adt.Store store adt.Store
} }

View File

@ -0,0 +1,30 @@
package account
import (
"github.com/filecoin-project/go-address"
"github.com/ipfs/go-cid"
"github.com/filecoin-project/lotus/chain/actors/adt"
account2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/account"
)
var _ State = (*state2)(nil)
func load2(store adt.Store, root cid.Cid) (State, error) {
out := state2{store: store}
err := store.Get(store.Context(), root, &out)
if err != nil {
return nil, err
}
return &out, nil
}
type state2 struct {
account2.State
store adt.Store
}
func (s *state2) PubkeyAddress() (address.Address, error) {
return s.Address, nil
}

View File

@ -1,32 +1,25 @@
package builtin package builtin
import ( import (
"fmt" "github.com/ipfs/go-cid"
"golang.org/x/xerrors"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/cbor"
"github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/filecoin-project/lotus/chain/types"
builtin0 "github.com/filecoin-project/specs-actors/actors/builtin"
miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner"
proof0 "github.com/filecoin-project/specs-actors/actors/runtime/proof" proof0 "github.com/filecoin-project/specs-actors/actors/runtime/proof"
smoothing0 "github.com/filecoin-project/specs-actors/actors/util/smoothing" smoothing0 "github.com/filecoin-project/specs-actors/actors/util/smoothing"
builtin2 "github.com/filecoin-project/specs-actors/v2/actors/builtin"
"github.com/filecoin-project/go-state-types/network" smoothing2 "github.com/filecoin-project/specs-actors/v2/actors/util/smoothing"
) )
type Version int var SystemActorAddr = builtin0.SystemActorAddr
var BurntFundsActorAddr = builtin0.BurntFundsActorAddr
const (
Version0 = iota
)
// Converts a network version into a specs-actors version.
func VersionForNetwork(version network.Version) Version {
switch version {
case network.Version0, network.Version1, network.Version2, network.Version3:
return Version0
default:
panic(fmt.Sprintf("unsupported network version %d", version))
}
}
// TODO: Why does actors have 2 different versions of this? // TODO: Why does actors have 2 different versions of this?
type SectorInfo = proof0.SectorInfo type SectorInfo = proof0.SectorInfo
@ -41,3 +34,55 @@ func FromV0FilterEstimate(v0 smoothing0.FilterEstimate) FilterEstimate {
func QAPowerForWeight(size abi.SectorSize, duration abi.ChainEpoch, dealWeight, verifiedWeight abi.DealWeight) abi.StoragePower { func QAPowerForWeight(size abi.SectorSize, duration abi.ChainEpoch, dealWeight, verifiedWeight abi.DealWeight) abi.StoragePower {
return miner0.QAPowerForWeight(size, duration, dealWeight, verifiedWeight) return miner0.QAPowerForWeight(size, duration, dealWeight, verifiedWeight)
} }
func FromV2FilterEstimate(v1 smoothing2.FilterEstimate) FilterEstimate {
return (FilterEstimate)(v1)
}
type ActorStateLoader func(store adt.Store, root cid.Cid) (cbor.Marshaler, error)
var ActorStateLoaders = make(map[cid.Cid]ActorStateLoader)
func RegisterActorState(code cid.Cid, loader ActorStateLoader) {
ActorStateLoaders[code] = loader
}
func Load(store adt.Store, act *types.Actor) (cbor.Marshaler, error) {
loader, found := ActorStateLoaders[act.Code]
if !found {
return nil, xerrors.Errorf("unknown actor code %s", act.Code)
}
return loader(store, act.Head)
}
func ActorNameByCode(c cid.Cid) string {
switch {
case builtin0.IsBuiltinActor(c):
return builtin0.ActorNameByCode(c)
case builtin2.IsBuiltinActor(c):
return builtin2.ActorNameByCode(c)
default:
return "<unknown>"
}
}
func IsBuiltinActor(c cid.Cid) bool {
return builtin0.IsBuiltinActor(c) || builtin2.IsBuiltinActor(c)
}
func IsAccountActor(c cid.Cid) bool {
return c == builtin0.AccountActorCodeID || c == builtin2.AccountActorCodeID
}
func IsStorageMinerActor(c cid.Cid) bool {
return c == builtin0.StorageMinerActorCodeID || c == builtin2.StorageMinerActorCodeID
}
func IsMultisigActor(c cid.Cid) bool {
return c == builtin0.MultisigActorCodeID || c == builtin2.MultisigActorCodeID
}
func IsPaymentChannelActor(c cid.Cid) bool {
return c == builtin0.PaymentChannelActorCodeID || c == builtin2.PaymentChannelActorCodeID
}

View File

@ -6,24 +6,34 @@ import (
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/cbor" "github.com/filecoin-project/go-state-types/cbor"
builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" "github.com/ipfs/go-cid"
"github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/filecoin-project/lotus/chain/actors/builtin"
"github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/types"
"github.com/filecoin-project/lotus/node/modules/dtypes" "github.com/filecoin-project/lotus/node/modules/dtypes"
builtin0 "github.com/filecoin-project/specs-actors/actors/builtin"
builtin2 "github.com/filecoin-project/specs-actors/v2/actors/builtin"
) )
func init() {
builtin.RegisterActorState(builtin0.InitActorCodeID, func(store adt.Store, root cid.Cid) (cbor.Marshaler, error) {
return load0(store, root)
})
builtin.RegisterActorState(builtin2.InitActorCodeID, func(store adt.Store, root cid.Cid) (cbor.Marshaler, error) {
return load2(store, root)
})
}
var Address = builtin0.InitActorAddr var Address = builtin0.InitActorAddr
func Load(store adt.Store, act *types.Actor) (State, error) { func Load(store adt.Store, act *types.Actor) (State, error) {
switch act.Code { switch act.Code {
case builtin0.InitActorCodeID: case builtin0.InitActorCodeID:
out := state0{store: store} return load0(store, act.Head)
err := store.Get(store.Context(), act.Head, &out) case builtin2.InitActorCodeID:
if err != nil { return load2(store, act.Head)
return nil, err
}
return &out, nil
} }
return nil, xerrors.Errorf("unknown actor code %s", act.Code) return nil, xerrors.Errorf("unknown actor code %s", act.Code)
} }
@ -41,4 +51,7 @@ type State interface {
// It should not be used in production code, as init actor entries are // It should not be used in production code, as init actor entries are
// immutable. // immutable.
Remove(addrs ...address.Address) error Remove(addrs ...address.Address) error
// Sets the network's name. This should only be used on upgrade/fork.
SetNetworkName(name string) error
} }

View File

@ -3,21 +3,30 @@ package init
import ( import (
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/ipfs/go-cid"
cbg "github.com/whyrusleeping/cbor-gen" cbg "github.com/whyrusleeping/cbor-gen"
"golang.org/x/xerrors" "golang.org/x/xerrors"
init_ "github.com/filecoin-project/specs-actors/actors/builtin/init"
"github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/filecoin-project/lotus/node/modules/dtypes" "github.com/filecoin-project/lotus/node/modules/dtypes"
init0 "github.com/filecoin-project/specs-actors/actors/builtin/init"
adt0 "github.com/filecoin-project/specs-actors/actors/util/adt" adt0 "github.com/filecoin-project/specs-actors/actors/util/adt"
) )
var _ State = (*state0)(nil) var _ State = (*state0)(nil)
func load0(store adt.Store, root cid.Cid) (State, error) {
out := state0{store: store}
err := store.Get(store.Context(), root, &out)
if err != nil {
return nil, err
}
return &out, nil
}
type state0 struct { type state0 struct {
init_.State init0.State
store adt.Store store adt.Store
} }
@ -48,6 +57,11 @@ func (s *state0) NetworkName() (dtypes.NetworkName, error) {
return dtypes.NetworkName(s.State.NetworkName), nil return dtypes.NetworkName(s.State.NetworkName), nil
} }
func (s *state0) SetNetworkName(name string) error {
s.State.NetworkName = name
return nil
}
func (s *state0) Remove(addrs ...address.Address) (err error) { func (s *state0) Remove(addrs ...address.Address) (err error) {
m, err := adt0.AsMap(s.store, s.State.AddressMap) m, err := adt0.AsMap(s.store, s.State.AddressMap)
if err != nil { if err != nil {

View File

@ -0,0 +1,81 @@
package init
import (
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi"
"github.com/ipfs/go-cid"
cbg "github.com/whyrusleeping/cbor-gen"
"golang.org/x/xerrors"
"github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/filecoin-project/lotus/node/modules/dtypes"
init2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/init"
adt2 "github.com/filecoin-project/specs-actors/v2/actors/util/adt"
)
var _ State = (*state2)(nil)
func load2(store adt.Store, root cid.Cid) (State, error) {
out := state2{store: store}
err := store.Get(store.Context(), root, &out)
if err != nil {
return nil, err
}
return &out, nil
}
type state2 struct {
init2.State
store adt.Store
}
func (s *state2) ResolveAddress(address address.Address) (address.Address, bool, error) {
return s.State.ResolveAddress(s.store, address)
}
func (s *state2) MapAddressToNewID(address address.Address) (address.Address, error) {
return s.State.MapAddressToNewID(s.store, address)
}
func (s *state2) ForEachActor(cb func(id abi.ActorID, address address.Address) error) error {
addrs, err := adt2.AsMap(s.store, s.State.AddressMap)
if err != nil {
return err
}
var actorID cbg.CborInt
return addrs.ForEach(&actorID, func(key string) error {
addr, err := address.NewFromBytes([]byte(key))
if err != nil {
return err
}
return cb(abi.ActorID(actorID), addr)
})
}
func (s *state2) NetworkName() (dtypes.NetworkName, error) {
return dtypes.NetworkName(s.State.NetworkName), nil
}
func (s *state2) SetNetworkName(name string) error {
s.State.NetworkName = name
return nil
}
func (s *state2) Remove(addrs ...address.Address) (err error) {
m, err := adt2.AsMap(s.store, s.State.AddressMap)
if err != nil {
return err
}
for _, addr := range addrs {
if err = m.Delete(abi.AddrKey(addr)); err != nil {
return xerrors.Errorf("failed to delete entry for address: %s; err: %w", addr, err)
}
}
amr, err := m.Root()
if err != nil {
return xerrors.Errorf("failed to get address map root: %w", err)
}
s.State.AddressMap = amr
return nil
}

View File

@ -6,26 +6,35 @@ import (
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/cbor" "github.com/filecoin-project/go-state-types/cbor"
builtin0 "github.com/filecoin-project/specs-actors/actors/builtin"
market0 "github.com/filecoin-project/specs-actors/actors/builtin/market"
"github.com/ipfs/go-cid" "github.com/ipfs/go-cid"
cbg "github.com/whyrusleeping/cbor-gen" cbg "github.com/whyrusleeping/cbor-gen"
builtin0 "github.com/filecoin-project/specs-actors/actors/builtin"
market0 "github.com/filecoin-project/specs-actors/actors/builtin/market"
builtin2 "github.com/filecoin-project/specs-actors/v2/actors/builtin"
"github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/filecoin-project/lotus/chain/actors/builtin"
"github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/types"
) )
func init() {
builtin.RegisterActorState(builtin0.StorageMarketActorCodeID, func(store adt.Store, root cid.Cid) (cbor.Marshaler, error) {
return load0(store, root)
})
builtin.RegisterActorState(builtin2.StorageMarketActorCodeID, func(store adt.Store, root cid.Cid) (cbor.Marshaler, error) {
return load2(store, root)
})
}
var Address = builtin0.StorageMarketActorAddr var Address = builtin0.StorageMarketActorAddr
func Load(store adt.Store, act *types.Actor) (st State, err error) { func Load(store adt.Store, act *types.Actor) (st State, err error) {
switch act.Code { switch act.Code {
case builtin0.StorageMarketActorCodeID: case builtin0.StorageMarketActorCodeID:
out := state0{store: store} return load0(store, act.Head)
err := store.Get(store.Context(), act.Head, &out) case builtin2.StorageMarketActorCodeID:
if err != nil { return load2(store, act.Head)
return nil, err
}
return &out, nil
} }
return nil, xerrors.Errorf("unknown actor code %s", act.Code) return nil, xerrors.Errorf("unknown actor code %s", act.Code)
} }

View File

@ -5,17 +5,29 @@ import (
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/ipfs/go-cid"
cbg "github.com/whyrusleeping/cbor-gen"
"github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/types"
"github.com/filecoin-project/specs-actors/actors/builtin/market"
market0 "github.com/filecoin-project/specs-actors/actors/builtin/market"
adt0 "github.com/filecoin-project/specs-actors/actors/util/adt" adt0 "github.com/filecoin-project/specs-actors/actors/util/adt"
cbg "github.com/whyrusleeping/cbor-gen"
) )
var _ State = (*state0)(nil) var _ State = (*state0)(nil)
func load0(store adt.Store, root cid.Cid) (State, error) {
out := state0{store: store}
err := store.Get(store.Context(), root, &out)
if err != nil {
return nil, err
}
return &out, nil
}
type state0 struct { type state0 struct {
market.State market0.State
store adt.Store store adt.Store
} }
@ -90,7 +102,7 @@ func (s *state0) LockedTable() (BalanceTable, error) {
func (s *state0) VerifyDealsForActivation( func (s *state0) VerifyDealsForActivation(
minerAddr address.Address, deals []abi.DealID, currEpoch, sectorExpiry abi.ChainEpoch, minerAddr address.Address, deals []abi.DealID, currEpoch, sectorExpiry abi.ChainEpoch,
) (weight, verifiedWeight abi.DealWeight, err error) { ) (weight, verifiedWeight abi.DealWeight, err error) {
return market.ValidateDealsForActivation(&s.State, s.store, deals, minerAddr, sectorExpiry, currEpoch) return market0.ValidateDealsForActivation(&s.State, s.store, deals, minerAddr, sectorExpiry, currEpoch)
} }
type balanceTable0 struct { type balanceTable0 struct {
@ -114,7 +126,7 @@ type dealStates0 struct {
} }
func (s *dealStates0) Get(dealID abi.DealID) (*DealState, bool, error) { func (s *dealStates0) Get(dealID abi.DealID) (*DealState, bool, error) {
var deal0 market.DealState var deal0 market0.DealState
found, err := s.Array.Get(uint64(dealID), &deal0) found, err := s.Array.Get(uint64(dealID), &deal0)
if err != nil { if err != nil {
return nil, false, err return nil, false, err
@ -127,14 +139,14 @@ func (s *dealStates0) Get(dealID abi.DealID) (*DealState, bool, error) {
} }
func (s *dealStates0) ForEach(cb func(dealID abi.DealID, ds DealState) error) error { func (s *dealStates0) ForEach(cb func(dealID abi.DealID, ds DealState) error) error {
var ds0 market.DealState var ds0 market0.DealState
return s.Array.ForEach(&ds0, func(idx int64) error { return s.Array.ForEach(&ds0, func(idx int64) error {
return cb(abi.DealID(idx), fromV0DealState(ds0)) return cb(abi.DealID(idx), fromV0DealState(ds0))
}) })
} }
func (s *dealStates0) decode(val *cbg.Deferred) (*DealState, error) { func (s *dealStates0) decode(val *cbg.Deferred) (*DealState, error) {
var ds0 market.DealState var ds0 market0.DealState
if err := ds0.UnmarshalCBOR(bytes.NewReader(val.Raw)); err != nil { if err := ds0.UnmarshalCBOR(bytes.NewReader(val.Raw)); err != nil {
return nil, err return nil, err
} }
@ -146,7 +158,7 @@ func (s *dealStates0) array() adt.Array {
return s.Array return s.Array
} }
func fromV0DealState(v0 market.DealState) DealState { func fromV0DealState(v0 market0.DealState) DealState {
return (DealState)(v0) return (DealState)(v0)
} }
@ -155,7 +167,7 @@ type dealProposals0 struct {
} }
func (s *dealProposals0) Get(dealID abi.DealID) (*DealProposal, bool, error) { func (s *dealProposals0) Get(dealID abi.DealID) (*DealProposal, bool, error) {
var proposal0 market.DealProposal var proposal0 market0.DealProposal
found, err := s.Array.Get(uint64(dealID), &proposal0) found, err := s.Array.Get(uint64(dealID), &proposal0)
if err != nil { if err != nil {
return nil, false, err return nil, false, err
@ -168,14 +180,14 @@ func (s *dealProposals0) Get(dealID abi.DealID) (*DealProposal, bool, error) {
} }
func (s *dealProposals0) ForEach(cb func(dealID abi.DealID, dp DealProposal) error) error { func (s *dealProposals0) ForEach(cb func(dealID abi.DealID, dp DealProposal) error) error {
var dp0 market.DealProposal var dp0 market0.DealProposal
return s.Array.ForEach(&dp0, func(idx int64) error { return s.Array.ForEach(&dp0, func(idx int64) error {
return cb(abi.DealID(idx), fromV0DealProposal(dp0)) return cb(abi.DealID(idx), fromV0DealProposal(dp0))
}) })
} }
func (s *dealProposals0) decode(val *cbg.Deferred) (*DealProposal, error) { func (s *dealProposals0) decode(val *cbg.Deferred) (*DealProposal, error) {
var dp0 market.DealProposal var dp0 market0.DealProposal
if err := dp0.UnmarshalCBOR(bytes.NewReader(val.Raw)); err != nil { if err := dp0.UnmarshalCBOR(bytes.NewReader(val.Raw)); err != nil {
return nil, err return nil, err
} }
@ -187,6 +199,6 @@ func (s *dealProposals0) array() adt.Array {
return s.Array return s.Array
} }
func fromV0DealProposal(v0 market.DealProposal) DealProposal { func fromV0DealProposal(v0 market0.DealProposal) DealProposal {
return (DealProposal)(v0) return (DealProposal)(v0)
} }

View File

@ -0,0 +1,205 @@
package market
import (
"bytes"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi"
"github.com/ipfs/go-cid"
cbg "github.com/whyrusleeping/cbor-gen"
"github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/filecoin-project/lotus/chain/types"
market2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/market"
adt2 "github.com/filecoin-project/specs-actors/v2/actors/util/adt"
)
var _ State = (*state2)(nil)
func load2(store adt.Store, root cid.Cid) (State, error) {
out := state2{store: store}
err := store.Get(store.Context(), root, &out)
if err != nil {
return nil, err
}
return &out, nil
}
type state2 struct {
market2.State
store adt.Store
}
func (s *state2) TotalLocked() (abi.TokenAmount, error) {
fml := types.BigAdd(s.TotalClientLockedCollateral, s.TotalProviderLockedCollateral)
fml = types.BigAdd(fml, s.TotalClientStorageFee)
return fml, nil
}
func (s *state2) BalancesChanged(otherState State) (bool, error) {
otherState2, ok := otherState.(*state2)
if !ok {
// there's no way to compare different versions of the state, so let's
// just say that means the state of balances has changed
return true, nil
}
return !s.State.EscrowTable.Equals(otherState2.State.EscrowTable) || !s.State.LockedTable.Equals(otherState2.State.LockedTable), nil
}
func (s *state2) StatesChanged(otherState State) (bool, error) {
otherState2, ok := otherState.(*state2)
if !ok {
// there's no way to compare different versions of the state, so let's
// just say that means the state of balances has changed
return true, nil
}
return !s.State.States.Equals(otherState2.State.States), nil
}
func (s *state2) States() (DealStates, error) {
stateArray, err := adt2.AsArray(s.store, s.State.States)
if err != nil {
return nil, err
}
return &dealStates2{stateArray}, nil
}
func (s *state2) ProposalsChanged(otherState State) (bool, error) {
otherState2, ok := otherState.(*state2)
if !ok {
// there's no way to compare different versions of the state, so let's
// just say that means the state of balances has changed
return true, nil
}
return !s.State.Proposals.Equals(otherState2.State.Proposals), nil
}
func (s *state2) Proposals() (DealProposals, error) {
proposalArray, err := adt2.AsArray(s.store, s.State.Proposals)
if err != nil {
return nil, err
}
return &dealProposals2{proposalArray}, nil
}
func (s *state2) EscrowTable() (BalanceTable, error) {
bt, err := adt2.AsBalanceTable(s.store, s.State.EscrowTable)
if err != nil {
return nil, err
}
return &balanceTable2{bt}, nil
}
func (s *state2) LockedTable() (BalanceTable, error) {
bt, err := adt2.AsBalanceTable(s.store, s.State.LockedTable)
if err != nil {
return nil, err
}
return &balanceTable2{bt}, nil
}
func (s *state2) VerifyDealsForActivation(
minerAddr address.Address, deals []abi.DealID, currEpoch, sectorExpiry abi.ChainEpoch,
) (weight, verifiedWeight abi.DealWeight, err error) {
w, vw, _, err := market2.ValidateDealsForActivation(&s.State, s.store, deals, minerAddr, sectorExpiry, currEpoch)
return w, vw, err
}
type balanceTable2 struct {
*adt2.BalanceTable
}
func (bt *balanceTable2) ForEach(cb func(address.Address, abi.TokenAmount) error) error {
asMap := (*adt2.Map)(bt.BalanceTable)
var ta abi.TokenAmount
return asMap.ForEach(&ta, func(key string) error {
a, err := address.NewFromBytes([]byte(key))
if err != nil {
return err
}
return cb(a, ta)
})
}
type dealStates2 struct {
adt.Array
}
func (s *dealStates2) Get(dealID abi.DealID) (*DealState, bool, error) {
var deal2 market2.DealState
found, err := s.Array.Get(uint64(dealID), &deal2)
if err != nil {
return nil, false, err
}
if !found {
return nil, false, nil
}
deal := fromV2DealState(deal2)
return &deal, true, nil
}
func (s *dealStates2) ForEach(cb func(dealID abi.DealID, ds DealState) error) error {
var ds1 market2.DealState
return s.Array.ForEach(&ds1, func(idx int64) error {
return cb(abi.DealID(idx), fromV2DealState(ds1))
})
}
func (s *dealStates2) decode(val *cbg.Deferred) (*DealState, error) {
var ds1 market2.DealState
if err := ds1.UnmarshalCBOR(bytes.NewReader(val.Raw)); err != nil {
return nil, err
}
ds := fromV2DealState(ds1)
return &ds, nil
}
func (s *dealStates2) array() adt.Array {
return s.Array
}
func fromV2DealState(v1 market2.DealState) DealState {
return (DealState)(v1)
}
type dealProposals2 struct {
adt.Array
}
func (s *dealProposals2) Get(dealID abi.DealID) (*DealProposal, bool, error) {
var proposal2 market2.DealProposal
found, err := s.Array.Get(uint64(dealID), &proposal2)
if err != nil {
return nil, false, err
}
if !found {
return nil, false, nil
}
proposal := fromV2DealProposal(proposal2)
return &proposal, true, nil
}
func (s *dealProposals2) ForEach(cb func(dealID abi.DealID, dp DealProposal) error) error {
var dp1 market2.DealProposal
return s.Array.ForEach(&dp1, func(idx int64) error {
return cb(abi.DealID(idx), fromV2DealProposal(dp1))
})
}
func (s *dealProposals2) decode(val *cbg.Deferred) (*DealProposal, error) {
var dp1 market2.DealProposal
if err := dp1.UnmarshalCBOR(bytes.NewReader(val.Raw)); err != nil {
return nil, err
}
dp := fromV2DealProposal(dp1)
return &dp, nil
}
func (s *dealProposals2) array() adt.Array {
return s.Array
}
func fromV2DealProposal(v1 market2.DealProposal) DealProposal {
return (DealProposal)(v1)
}

View File

@ -11,14 +11,26 @@ import (
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/cbor" "github.com/filecoin-project/go-state-types/cbor"
"github.com/filecoin-project/go-state-types/dline" "github.com/filecoin-project/go-state-types/dline"
builtin0 "github.com/filecoin-project/specs-actors/actors/builtin"
miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner"
"github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/filecoin-project/lotus/chain/actors/builtin"
"github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/types"
builtin0 "github.com/filecoin-project/specs-actors/actors/builtin"
miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner"
builtin2 "github.com/filecoin-project/specs-actors/v2/actors/builtin"
) )
// Unchanged between v0 and v1 actors func init() {
builtin.RegisterActorState(builtin0.StorageMinerActorCodeID, func(store adt.Store, root cid.Cid) (cbor.Marshaler, error) {
return load0(store, root)
})
builtin.RegisterActorState(builtin2.StorageMinerActorCodeID, func(store adt.Store, root cid.Cid) (cbor.Marshaler, error) {
return load2(store, root)
})
}
// Unchanged between v0 and v2 actors
var WPoStProvingPeriod = miner0.WPoStProvingPeriod var WPoStProvingPeriod = miner0.WPoStProvingPeriod
var WPoStPeriodDeadlines = miner0.WPoStPeriodDeadlines var WPoStPeriodDeadlines = miner0.WPoStPeriodDeadlines
var WPoStChallengeWindow = miner0.WPoStChallengeWindow var WPoStChallengeWindow = miner0.WPoStChallengeWindow
@ -30,12 +42,9 @@ const MinSectorExpiration = miner0.MinSectorExpiration
func Load(store adt.Store, act *types.Actor) (st State, err error) { func Load(store adt.Store, act *types.Actor) (st State, err error) {
switch act.Code { switch act.Code {
case builtin0.StorageMinerActorCodeID: case builtin0.StorageMinerActorCodeID:
out := state0{store: store} return load0(store, act.Head)
err := store.Get(store.Context(), act.Head, &out) case builtin2.StorageMinerActorCodeID:
if err != nil { return load2(store, act.Head)
return nil, err
}
return &out, nil
} }
return nil, xerrors.Errorf("unknown actor code %s", act.Code) return nil, xerrors.Errorf("unknown actor code %s", act.Code)
} }

View File

@ -4,22 +4,32 @@ import (
"bytes" "bytes"
"errors" "errors"
"github.com/libp2p/go-libp2p-core/peer"
cbg "github.com/whyrusleeping/cbor-gen"
"golang.org/x/xerrors"
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-bitfield" "github.com/filecoin-project/go-bitfield"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/dline" "github.com/filecoin-project/go-state-types/dline"
miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" "github.com/ipfs/go-cid"
adt0 "github.com/filecoin-project/specs-actors/actors/util/adt" "github.com/libp2p/go-libp2p-core/peer"
cbg "github.com/whyrusleeping/cbor-gen"
"golang.org/x/xerrors"
"github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/actors/adt"
miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner"
adt0 "github.com/filecoin-project/specs-actors/actors/util/adt"
) )
var _ State = (*state0)(nil) var _ State = (*state0)(nil)
func load0(store adt.Store, root cid.Cid) (State, error) {
out := state0{store: store}
err := store.Get(store.Context(), root, &out)
if err != nil {
return nil, err
}
return &out, nil
}
type state0 struct { type state0 struct {
miner0.State miner0.State
store adt.Store store adt.Store

View File

@ -0,0 +1,402 @@
package miner
import (
"bytes"
"errors"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-bitfield"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/dline"
"github.com/ipfs/go-cid"
"github.com/libp2p/go-libp2p-core/peer"
cbg "github.com/whyrusleeping/cbor-gen"
"golang.org/x/xerrors"
"github.com/filecoin-project/lotus/chain/actors/adt"
miner2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/miner"
adt2 "github.com/filecoin-project/specs-actors/v2/actors/util/adt"
)
var _ State = (*state2)(nil)
func load2(store adt.Store, root cid.Cid) (State, error) {
out := state2{store: store}
err := store.Get(store.Context(), root, &out)
if err != nil {
return nil, err
}
return &out, nil
}
type state2 struct {
miner2.State
store adt.Store
}
type deadline2 struct {
miner2.Deadline
store adt.Store
}
type partition2 struct {
miner2.Partition
store adt.Store
}
func (s *state2) AvailableBalance(bal abi.TokenAmount) (abi.TokenAmount, error) {
return s.GetAvailableBalance(bal), nil
}
func (s *state2) VestedFunds(epoch abi.ChainEpoch) (abi.TokenAmount, error) {
return s.CheckVestedFunds(s.store, epoch)
}
func (s *state2) LockedFunds() (LockedFunds, error) {
return LockedFunds{
VestingFunds: s.State.LockedFunds,
InitialPledgeRequirement: s.State.InitialPledge,
PreCommitDeposits: s.State.PreCommitDeposits,
}, nil
}
func (s *state2) InitialPledge() (abi.TokenAmount, error) {
return s.State.InitialPledge, nil
}
func (s *state2) PreCommitDeposits() (abi.TokenAmount, error) {
return s.State.PreCommitDeposits, nil
}
func (s *state2) GetSector(num abi.SectorNumber) (*SectorOnChainInfo, error) {
info, ok, err := s.State.GetSector(s.store, num)
if !ok || err != nil {
return nil, err
}
ret := fromV2SectorOnChainInfo(*info)
return &ret, nil
}
func (s *state2) FindSector(num abi.SectorNumber) (*SectorLocation, error) {
dlIdx, partIdx, err := s.State.FindSector(s.store, num)
if err != nil {
return nil, err
}
return &SectorLocation{
Deadline: dlIdx,
Partition: partIdx,
}, nil
}
func (s *state2) NumLiveSectors() (uint64, error) {
dls, err := s.State.LoadDeadlines(s.store)
if err != nil {
return 0, err
}
var total uint64
if err := dls.ForEach(s.store, func(dlIdx uint64, dl *miner2.Deadline) error {
total += dl.LiveSectors
return nil
}); err != nil {
return 0, err
}
return total, nil
}
// GetSectorExpiration returns the effective expiration of the given sector.
//
// If the sector does not expire early, the Early expiration field is 0.
func (s *state2) GetSectorExpiration(num abi.SectorNumber) (*SectorExpiration, error) {
dls, err := s.State.LoadDeadlines(s.store)
if err != nil {
return nil, err
}
// NOTE: this can be optimized significantly.
// 1. If the sector is non-faulty, it will either expire on-time (can be
// learned from the sector info), or in the next quantized expiration
// epoch (i.e., the first element in the partition's expiration queue.
// 2. If it's faulty, it will expire early within the first 14 entries
// of the expiration queue.
stopErr := errors.New("stop")
out := SectorExpiration{}
err = dls.ForEach(s.store, func(dlIdx uint64, dl *miner2.Deadline) error {
partitions, err := dl.PartitionsArray(s.store)
if err != nil {
return err
}
quant := s.State.QuantSpecForDeadline(dlIdx)
var part miner2.Partition
return partitions.ForEach(&part, func(partIdx int64) error {
if found, err := part.Sectors.IsSet(uint64(num)); err != nil {
return err
} else if !found {
return nil
}
if found, err := part.Terminated.IsSet(uint64(num)); err != nil {
return err
} else if found {
// already terminated
return stopErr
}
q, err := miner2.LoadExpirationQueue(s.store, part.ExpirationsEpochs, quant)
if err != nil {
return err
}
var exp miner2.ExpirationSet
return q.ForEach(&exp, func(epoch int64) error {
if early, err := exp.EarlySectors.IsSet(uint64(num)); err != nil {
return err
} else if early {
out.Early = abi.ChainEpoch(epoch)
return nil
}
if onTime, err := exp.OnTimeSectors.IsSet(uint64(num)); err != nil {
return err
} else if onTime {
out.OnTime = abi.ChainEpoch(epoch)
return stopErr
}
return nil
})
})
})
if err == stopErr {
err = nil
}
if err != nil {
return nil, err
}
if out.Early == 0 && out.OnTime == 0 {
return nil, xerrors.Errorf("failed to find sector %d", num)
}
return &out, nil
}
func (s *state2) GetPrecommittedSector(num abi.SectorNumber) (*SectorPreCommitOnChainInfo, error) {
info, ok, err := s.State.GetPrecommittedSector(s.store, num)
if !ok || err != nil {
return nil, err
}
ret := fromV2SectorPreCommitOnChainInfo(*info)
return &ret, nil
}
func (s *state2) LoadSectors(snos *bitfield.BitField) ([]*SectorOnChainInfo, error) {
sectors, err := miner2.LoadSectors(s.store, s.State.Sectors)
if err != nil {
return nil, err
}
// If no sector numbers are specified, load all.
if snos == nil {
infos := make([]*SectorOnChainInfo, 0, sectors.Length())
var info2 miner2.SectorOnChainInfo
if err := sectors.ForEach(&info2, func(_ int64) error {
info := fromV2SectorOnChainInfo(info2)
infos = append(infos, &info)
return nil
}); err != nil {
return nil, err
}
return infos, nil
}
// Otherwise, load selected.
infos2, err := sectors.Load(*snos)
if err != nil {
return nil, err
}
infos := make([]*SectorOnChainInfo, len(infos2))
for i, info2 := range infos2 {
info := fromV2SectorOnChainInfo(*info2)
infos[i] = &info
}
return infos, nil
}
func (s *state2) IsAllocated(num abi.SectorNumber) (bool, error) {
var allocatedSectors bitfield.BitField
if err := s.store.Get(s.store.Context(), s.State.AllocatedSectors, &allocatedSectors); err != nil {
return false, err
}
return allocatedSectors.IsSet(uint64(num))
}
func (s *state2) LoadDeadline(idx uint64) (Deadline, error) {
dls, err := s.State.LoadDeadlines(s.store)
if err != nil {
return nil, err
}
dl, err := dls.LoadDeadline(s.store, idx)
if err != nil {
return nil, err
}
return &deadline2{*dl, s.store}, nil
}
func (s *state2) ForEachDeadline(cb func(uint64, Deadline) error) error {
dls, err := s.State.LoadDeadlines(s.store)
if err != nil {
return err
}
return dls.ForEach(s.store, func(i uint64, dl *miner2.Deadline) error {
return cb(i, &deadline2{*dl, s.store})
})
}
func (s *state2) NumDeadlines() (uint64, error) {
return miner2.WPoStPeriodDeadlines, nil
}
func (s *state2) DeadlinesChanged(other State) (bool, error) {
other2, ok := other.(*state2)
if !ok {
// treat an upgrade as a change, always
return true, nil
}
return s.State.Deadlines.Equals(other2.Deadlines), nil
}
func (s *state2) Info() (MinerInfo, error) {
info, err := s.State.GetInfo(s.store)
if err != nil {
return MinerInfo{}, err
}
var pid *peer.ID
if peerID, err := peer.IDFromBytes(info.PeerId); err == nil {
pid = &peerID
}
mi := MinerInfo{
Owner: info.Owner,
Worker: info.Worker,
ControlAddresses: info.ControlAddresses,
NewWorker: address.Undef,
WorkerChangeEpoch: -1,
PeerId: pid,
Multiaddrs: info.Multiaddrs,
SealProofType: info.SealProofType,
SectorSize: info.SectorSize,
WindowPoStPartitionSectors: info.WindowPoStPartitionSectors,
}
if info.PendingWorkerKey != nil {
mi.NewWorker = info.PendingWorkerKey.NewWorker
mi.WorkerChangeEpoch = info.PendingWorkerKey.EffectiveAt
}
return mi, nil
}
func (s *state2) DeadlineInfo(epoch abi.ChainEpoch) (*dline.Info, error) {
return s.State.DeadlineInfo(epoch), nil
}
func (s *state2) sectors() (adt.Array, error) {
return adt2.AsArray(s.store, s.Sectors)
}
func (s *state2) decodeSectorOnChainInfo(val *cbg.Deferred) (SectorOnChainInfo, error) {
var si miner2.SectorOnChainInfo
err := si.UnmarshalCBOR(bytes.NewReader(val.Raw))
if err != nil {
return SectorOnChainInfo{}, err
}
return fromV2SectorOnChainInfo(si), nil
}
func (s *state2) precommits() (adt.Map, error) {
return adt2.AsMap(s.store, s.PreCommittedSectors)
}
func (s *state2) decodeSectorPreCommitOnChainInfo(val *cbg.Deferred) (SectorPreCommitOnChainInfo, error) {
var sp miner2.SectorPreCommitOnChainInfo
err := sp.UnmarshalCBOR(bytes.NewReader(val.Raw))
if err != nil {
return SectorPreCommitOnChainInfo{}, err
}
return fromV2SectorPreCommitOnChainInfo(sp), nil
}
func (d *deadline2) LoadPartition(idx uint64) (Partition, error) {
p, err := d.Deadline.LoadPartition(d.store, idx)
if err != nil {
return nil, err
}
return &partition2{*p, d.store}, nil
}
func (d *deadline2) ForEachPartition(cb func(uint64, Partition) error) error {
ps, err := d.Deadline.PartitionsArray(d.store)
if err != nil {
return err
}
var part miner2.Partition
return ps.ForEach(&part, func(i int64) error {
return cb(uint64(i), &partition2{part, d.store})
})
}
func (d *deadline2) PartitionsChanged(other Deadline) (bool, error) {
other2, ok := other.(*deadline2)
if !ok {
// treat an upgrade as a change, always
return true, nil
}
return d.Deadline.Partitions.Equals(other2.Deadline.Partitions), nil
}
func (d *deadline2) PostSubmissions() (bitfield.BitField, error) {
return d.Deadline.PostSubmissions, nil
}
func (p *partition2) AllSectors() (bitfield.BitField, error) {
return p.Partition.Sectors, nil
}
func (p *partition2) FaultySectors() (bitfield.BitField, error) {
return p.Partition.Faults, nil
}
func (p *partition2) RecoveringSectors() (bitfield.BitField, error) {
return p.Partition.Recoveries, nil
}
func fromV2SectorOnChainInfo(v2 miner2.SectorOnChainInfo) SectorOnChainInfo {
return SectorOnChainInfo{
SectorNumber: v2.SectorNumber,
SealProof: v2.SealProof,
SealedCID: v2.SealedCID,
DealIDs: v2.DealIDs,
Activation: v2.Activation,
Expiration: v2.Expiration,
DealWeight: v2.DealWeight,
VerifiedDealWeight: v2.VerifiedDealWeight,
InitialPledge: v2.InitialPledge,
ExpectedDayReward: v2.ExpectedDayReward,
ExpectedStoragePledge: v2.ExpectedStoragePledge,
}
}
func fromV2SectorPreCommitOnChainInfo(v2 miner2.SectorPreCommitOnChainInfo) SectorPreCommitOnChainInfo {
return SectorPreCommitOnChainInfo{
Info: (SectorPreCommitInfo)(v2.Info),
PreCommitDeposit: v2.PreCommitDeposit,
PreCommitEpoch: v2.PreCommitEpoch,
DealWeight: v2.DealWeight,
VerifiedDealWeight: v2.VerifiedDealWeight,
}
}

View File

@ -0,0 +1,70 @@
package multisig
import (
"fmt"
"github.com/minio/blake2b-simd"
"golang.org/x/xerrors"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi"
multisig2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/multisig"
"github.com/filecoin-project/lotus/chain/actors"
"github.com/filecoin-project/lotus/chain/types"
)
func Message(version actors.Version, from address.Address) MessageBuilder {
switch version {
case actors.Version0:
return message0{from}
case actors.Version2:
return message2{message0{from}}
default:
panic(fmt.Sprintf("unsupported actors version: %d", version))
}
}
type MessageBuilder interface {
// Create a new multisig with the specified parameters.
Create(signers []address.Address, threshold uint64,
vestingStart, vestingDuration abi.ChainEpoch,
initialAmount abi.TokenAmount) (*types.Message, error)
// Propose a transaction to the given multisig.
Propose(msig, target address.Address, amt abi.TokenAmount,
method abi.MethodNum, params []byte) (*types.Message, error)
// Approve a multisig transaction. The "hash" is optional.
Approve(msig address.Address, txID uint64, hash *ProposalHashData) (*types.Message, error)
// Cancel a multisig transaction. The "hash" is optional.
Cancel(msig address.Address, txID uint64, hash *ProposalHashData) (*types.Message, error)
}
// this type is the same between v0 and v2
type ProposalHashData = multisig2.ProposalHashData
func txnParams(id uint64, data *ProposalHashData) ([]byte, error) {
params := multisig2.TxnIDParams{ID: multisig2.TxnID(id)}
if data != nil {
if data.Requester.Protocol() != address.ID {
return nil, xerrors.Errorf("proposer address must be an ID address, was %s", data.Requester)
}
if data.Value.Sign() == -1 {
return nil, xerrors.Errorf("proposal value must be non-negative, was %s", data.Value)
}
if data.To == address.Undef {
return nil, xerrors.Errorf("proposed destination address must be set")
}
pser, err := data.Serialize()
if err != nil {
return nil, err
}
hash := blake2b.Sum256(pser)
params.ProposalHash = hash[:]
}
return actors.SerializeParams(&params)
}

View File

@ -0,0 +1,142 @@
package multisig
import (
"golang.org/x/xerrors"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi"
builtin0 "github.com/filecoin-project/specs-actors/actors/builtin"
init0 "github.com/filecoin-project/specs-actors/actors/builtin/init"
multisig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig"
"github.com/filecoin-project/lotus/chain/actors"
init_ "github.com/filecoin-project/lotus/chain/actors/builtin/init"
"github.com/filecoin-project/lotus/chain/types"
)
type message0 struct{ from address.Address }
func (m message0) Create(
signers []address.Address, threshold uint64,
unlockStart, unlockDuration abi.ChainEpoch,
initialAmount abi.TokenAmount,
) (*types.Message, error) {
lenAddrs := uint64(len(signers))
if lenAddrs < threshold {
return nil, xerrors.Errorf("cannot require signing of more addresses than provided for multisig")
}
if threshold == 0 {
threshold = lenAddrs
}
if m.from == address.Undef {
return nil, xerrors.Errorf("must provide source address")
}
if unlockStart != 0 {
return nil, xerrors.Errorf("actors v0 does not support a non-zero vesting start time")
}
// Set up constructor parameters for multisig
msigParams := &multisig0.ConstructorParams{
Signers: signers,
NumApprovalsThreshold: threshold,
UnlockDuration: unlockDuration,
}
enc, actErr := actors.SerializeParams(msigParams)
if actErr != nil {
return nil, actErr
}
// new actors are created by invoking 'exec' on the init actor with the constructor params
execParams := &init0.ExecParams{
CodeCID: builtin0.MultisigActorCodeID,
ConstructorParams: enc,
}
enc, actErr = actors.SerializeParams(execParams)
if actErr != nil {
return nil, actErr
}
return &types.Message{
To: init_.Address,
From: m.from,
Method: builtin0.MethodsInit.Exec,
Params: enc,
Value: initialAmount,
}, nil
}
func (m message0) Propose(msig, to address.Address, amt abi.TokenAmount,
method abi.MethodNum, params []byte) (*types.Message, error) {
if msig == address.Undef {
return nil, xerrors.Errorf("must provide a multisig address for proposal")
}
if to == address.Undef {
return nil, xerrors.Errorf("must provide a target address for proposal")
}
if amt.Sign() == -1 {
return nil, xerrors.Errorf("must provide a non-negative amount for proposed send")
}
if m.from == address.Undef {
return nil, xerrors.Errorf("must provide source address")
}
enc, actErr := actors.SerializeParams(&multisig0.ProposeParams{
To: to,
Value: amt,
Method: method,
Params: params,
})
if actErr != nil {
return nil, xerrors.Errorf("failed to serialize parameters: %w", actErr)
}
return &types.Message{
To: msig,
From: m.from,
Value: abi.NewTokenAmount(0),
Method: builtin0.MethodsMultisig.Propose,
Params: enc,
}, nil
}
func (m message0) Approve(msig address.Address, txID uint64, hashData *ProposalHashData) (*types.Message, error) {
enc, err := txnParams(txID, hashData)
if err != nil {
return nil, err
}
return &types.Message{
To: msig,
From: m.from,
Value: types.NewInt(0),
Method: builtin0.MethodsMultisig.Approve,
Params: enc,
}, nil
}
func (m message0) Cancel(msig address.Address, txID uint64, hashData *ProposalHashData) (*types.Message, error) {
enc, err := txnParams(txID, hashData)
if err != nil {
return nil, err
}
return &types.Message{
To: msig,
From: m.from,
Value: types.NewInt(0),
Method: builtin0.MethodsMultisig.Cancel,
Params: enc,
}, nil
}

View File

@ -0,0 +1,71 @@
package multisig
import (
"golang.org/x/xerrors"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi"
builtin2 "github.com/filecoin-project/specs-actors/v2/actors/builtin"
init2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/init"
multisig2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/multisig"
"github.com/filecoin-project/lotus/chain/actors"
init_ "github.com/filecoin-project/lotus/chain/actors/builtin/init"
"github.com/filecoin-project/lotus/chain/types"
)
type message2 struct{ message0 }
func (m message2) Create(
signers []address.Address, threshold uint64,
unlockStart, unlockDuration abi.ChainEpoch,
initialAmount abi.TokenAmount,
) (*types.Message, error) {
lenAddrs := uint64(len(signers))
if lenAddrs < threshold {
return nil, xerrors.Errorf("cannot require signing of more addresses than provided for multisig")
}
if threshold == 0 {
threshold = lenAddrs
}
if m.from == address.Undef {
return nil, xerrors.Errorf("must provide source address")
}
// Set up constructor parameters for multisig
msigParams := &multisig2.ConstructorParams{
Signers: signers,
NumApprovalsThreshold: threshold,
UnlockDuration: unlockDuration,
StartEpoch: unlockStart,
}
enc, actErr := actors.SerializeParams(msigParams)
if actErr != nil {
return nil, actErr
}
// new actors are created by invoking 'exec' on the init actor with the constructor params
execParams := &init2.ExecParams{
CodeCID: builtin2.MultisigActorCodeID,
ConstructorParams: enc,
}
enc, actErr = actors.SerializeParams(execParams)
if actErr != nil {
return nil, actErr
}
return &types.Message{
To: init_.Address,
From: m.from,
Method: builtin2.MethodsInit.Exec,
Params: enc,
Value: initialAmount,
}, nil
}

View File

@ -6,23 +6,32 @@ import (
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/cbor" "github.com/filecoin-project/go-state-types/cbor"
"github.com/ipfs/go-cid"
builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" builtin0 "github.com/filecoin-project/specs-actors/actors/builtin"
msig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig" msig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig"
builtin2 "github.com/filecoin-project/specs-actors/v2/actors/builtin"
"github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/filecoin-project/lotus/chain/actors/builtin"
"github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/types"
) )
func init() {
builtin.RegisterActorState(builtin0.MultisigActorCodeID, func(store adt.Store, root cid.Cid) (cbor.Marshaler, error) {
return load0(store, root)
})
builtin.RegisterActorState(builtin2.MultisigActorCodeID, func(store adt.Store, root cid.Cid) (cbor.Marshaler, error) {
return load2(store, root)
})
}
func Load(store adt.Store, act *types.Actor) (State, error) { func Load(store adt.Store, act *types.Actor) (State, error) {
switch act.Code { switch act.Code {
case builtin0.MultisigActorCodeID: case builtin0.MultisigActorCodeID:
out := state0{store: store} return load0(store, act.Head)
err := store.Get(store.Context(), act.Head, &out) case builtin2.MultisigActorCodeID:
if err != nil { return load2(store, act.Head)
return nil, err
}
return &out, nil
} }
return nil, xerrors.Errorf("unknown actor code %s", act.Code) return nil, xerrors.Errorf("unknown actor code %s", act.Code)
} }

View File

@ -5,15 +5,26 @@ import (
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/lotus/chain/actors/adt" "github.com/ipfs/go-cid"
"golang.org/x/xerrors" "golang.org/x/xerrors"
"github.com/filecoin-project/lotus/chain/actors/adt"
msig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig" msig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig"
adt0 "github.com/filecoin-project/specs-actors/actors/util/adt" adt0 "github.com/filecoin-project/specs-actors/actors/util/adt"
) )
var _ State = (*state0)(nil) var _ State = (*state0)(nil)
func load0(store adt.Store, root cid.Cid) (State, error) {
out := state0{store: store}
err := store.Get(store.Context(), root, &out)
if err != nil {
return nil, err
}
return &out, nil
}
type state0 struct { type state0 struct {
msig0.State msig0.State
store adt.Store store adt.Store

View File

@ -0,0 +1,70 @@
package multisig
import (
"encoding/binary"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi"
"github.com/ipfs/go-cid"
"golang.org/x/xerrors"
"github.com/filecoin-project/lotus/chain/actors/adt"
msig2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/multisig"
adt2 "github.com/filecoin-project/specs-actors/v2/actors/util/adt"
)
var _ State = (*state2)(nil)
func load2(store adt.Store, root cid.Cid) (State, error) {
out := state2{store: store}
err := store.Get(store.Context(), root, &out)
if err != nil {
return nil, err
}
return &out, nil
}
type state2 struct {
msig2.State
store adt.Store
}
func (s *state2) LockedBalance(currEpoch abi.ChainEpoch) (abi.TokenAmount, error) {
return s.State.AmountLocked(currEpoch - s.State.StartEpoch), nil
}
func (s *state2) StartEpoch() (abi.ChainEpoch, error) {
return s.State.StartEpoch, nil
}
func (s *state2) UnlockDuration() (abi.ChainEpoch, error) {
return s.State.UnlockDuration, nil
}
func (s *state2) InitialBalance() (abi.TokenAmount, error) {
return s.State.InitialBalance, nil
}
func (s *state2) Threshold() (uint64, error) {
return s.State.NumApprovalsThreshold, nil
}
func (s *state2) Signers() ([]address.Address, error) {
return s.State.Signers, nil
}
func (s *state2) ForEachPendingTxn(cb func(id int64, txn Transaction) error) error {
arr, err := adt2.AsMap(s.store, s.State.PendingTxns)
if err != nil {
return err
}
var out msig2.Transaction
return arr.ForEach(&out, func(key string) error {
txid, n := binary.Varint([]byte(key))
if n <= 0 {
return xerrors.Errorf("invalid pending transaction key: %v", key)
}
return cb(txid, (Transaction)(out))
})
}

View File

@ -0,0 +1,28 @@
package paych
import (
"fmt"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/lotus/chain/actors"
"github.com/filecoin-project/lotus/chain/types"
)
func Message(version actors.Version, from address.Address) MessageBuilder {
switch version {
case actors.Version0:
return message0{from}
case actors.Version2:
return message2{from}
default:
panic(fmt.Sprintf("unsupported actors version: %d", version))
}
}
type MessageBuilder interface {
Create(to address.Address, initialAmount abi.TokenAmount) (*types.Message, error)
Update(paych address.Address, voucher *SignedVoucher, secret []byte) (*types.Message, error)
Settle(paych address.Address) (*types.Message, error)
Collect(paych address.Address) (*types.Message, error)
}

View File

@ -0,0 +1,74 @@
package paych
import (
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi"
builtin0 "github.com/filecoin-project/specs-actors/actors/builtin"
init0 "github.com/filecoin-project/specs-actors/actors/builtin/init"
paych0 "github.com/filecoin-project/specs-actors/actors/builtin/paych"
"github.com/filecoin-project/lotus/chain/actors"
init_ "github.com/filecoin-project/lotus/chain/actors/builtin/init"
"github.com/filecoin-project/lotus/chain/types"
)
type message0 struct{ from address.Address }
func (m message0) Create(to address.Address, initialAmount abi.TokenAmount) (*types.Message, error) {
params, aerr := actors.SerializeParams(&paych0.ConstructorParams{From: m.from, To: to})
if aerr != nil {
return nil, aerr
}
enc, aerr := actors.SerializeParams(&init0.ExecParams{
CodeCID: builtin0.PaymentChannelActorCodeID,
ConstructorParams: params,
})
if aerr != nil {
return nil, aerr
}
return &types.Message{
To: init_.Address,
From: m.from,
Value: initialAmount,
Method: builtin0.MethodsInit.Exec,
Params: enc,
}, nil
}
func (m message0) Update(paych address.Address, sv *SignedVoucher, secret []byte) (*types.Message, error) {
params, aerr := actors.SerializeParams(&paych0.UpdateChannelStateParams{
Sv: *sv,
Secret: secret,
})
if aerr != nil {
return nil, aerr
}
return &types.Message{
To: paych,
From: m.from,
Value: abi.NewTokenAmount(0),
Method: builtin0.MethodsPaych.UpdateChannelState,
Params: params,
}, nil
}
func (m message0) Settle(paych address.Address) (*types.Message, error) {
return &types.Message{
To: paych,
From: m.from,
Value: abi.NewTokenAmount(0),
Method: builtin0.MethodsPaych.Settle,
}, nil
}
func (m message0) Collect(paych address.Address) (*types.Message, error) {
return &types.Message{
To: paych,
From: m.from,
Value: abi.NewTokenAmount(0),
Method: builtin0.MethodsPaych.Collect,
}, nil
}

View File

@ -0,0 +1,74 @@
package paych
import (
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi"
builtin2 "github.com/filecoin-project/specs-actors/v2/actors/builtin"
init2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/init"
paych2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/paych"
"github.com/filecoin-project/lotus/chain/actors"
init_ "github.com/filecoin-project/lotus/chain/actors/builtin/init"
"github.com/filecoin-project/lotus/chain/types"
)
type message2 struct{ from address.Address }
func (m message2) Create(to address.Address, initialAmount abi.TokenAmount) (*types.Message, error) {
params, aerr := actors.SerializeParams(&paych2.ConstructorParams{From: m.from, To: to})
if aerr != nil {
return nil, aerr
}
enc, aerr := actors.SerializeParams(&init2.ExecParams{
CodeCID: builtin2.PaymentChannelActorCodeID,
ConstructorParams: params,
})
if aerr != nil {
return nil, aerr
}
return &types.Message{
To: init_.Address,
From: m.from,
Value: initialAmount,
Method: builtin2.MethodsInit.Exec,
Params: enc,
}, nil
}
func (m message2) Update(paych address.Address, sv *SignedVoucher, secret []byte) (*types.Message, error) {
params, aerr := actors.SerializeParams(&paych2.UpdateChannelStateParams{
Sv: *sv,
Secret: secret,
})
if aerr != nil {
return nil, aerr
}
return &types.Message{
To: paych,
From: m.from,
Value: abi.NewTokenAmount(0),
Method: builtin2.MethodsPaych.UpdateChannelState,
Params: params,
}, nil
}
func (m message2) Settle(paych address.Address) (*types.Message, error) {
return &types.Message{
To: paych,
From: m.from,
Value: abi.NewTokenAmount(0),
Method: builtin2.MethodsPaych.Settle,
}, nil
}
func (m message2) Collect(paych address.Address) (*types.Message, error) {
return &types.Message{
To: paych,
From: m.from,
Value: abi.NewTokenAmount(0),
Method: builtin2.MethodsPaych.Collect,
}, nil
}

View File

@ -1,29 +1,42 @@
package paych package paych
import ( import (
"encoding/base64"
"golang.org/x/xerrors" "golang.org/x/xerrors"
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
big "github.com/filecoin-project/go-state-types/big" big "github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/go-state-types/cbor" "github.com/filecoin-project/go-state-types/cbor"
"github.com/ipfs/go-cid"
ipldcbor "github.com/ipfs/go-ipld-cbor"
builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" builtin0 "github.com/filecoin-project/specs-actors/actors/builtin"
paych0 "github.com/filecoin-project/specs-actors/actors/builtin/paych" paych0 "github.com/filecoin-project/specs-actors/actors/builtin/paych"
builtin2 "github.com/filecoin-project/specs-actors/v2/actors/builtin"
"github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/filecoin-project/lotus/chain/actors/builtin"
"github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/types"
) )
func init() {
builtin.RegisterActorState(builtin0.PaymentChannelActorCodeID, func(store adt.Store, root cid.Cid) (cbor.Marshaler, error) {
return load0(store, root)
})
builtin.RegisterActorState(builtin2.PaymentChannelActorCodeID, func(store adt.Store, root cid.Cid) (cbor.Marshaler, error) {
return load2(store, root)
})
}
// Load returns an abstract copy of payment channel state, irregardless of actor version // Load returns an abstract copy of payment channel state, irregardless of actor version
func Load(store adt.Store, act *types.Actor) (State, error) { func Load(store adt.Store, act *types.Actor) (State, error) {
switch act.Code { switch act.Code {
case builtin0.PaymentChannelActorCodeID: case builtin0.PaymentChannelActorCodeID:
out := state0{store: store} return load0(store, act.Head)
err := store.Get(store.Context(), act.Head, &out) case builtin2.PaymentChannelActorCodeID:
if err != nil { return load2(store, act.Head)
return nil, err
}
return &out, nil
} }
return nil, xerrors.Errorf("unknown actor code %s", act.Code) return nil, xerrors.Errorf("unknown actor code %s", act.Code)
} }
@ -58,3 +71,18 @@ type LaneState interface {
type SignedVoucher = paych0.SignedVoucher type SignedVoucher = paych0.SignedVoucher
type ModVerifyParams = paych0.ModVerifyParams type ModVerifyParams = paych0.ModVerifyParams
// DecodeSignedVoucher decodes base64 encoded signed voucher.
func DecodeSignedVoucher(s string) (*SignedVoucher, error) {
data, err := base64.RawURLEncoding.DecodeString(s)
if err != nil {
return nil, err
}
var sv SignedVoucher
if err := ipldcbor.DecodeInto(data, &sv); err != nil {
return nil, err
}
return &sv, nil
}

View File

@ -1,18 +1,31 @@
package paych package paych
import ( import (
"github.com/ipfs/go-cid"
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
big "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/filecoin-project/specs-actors/actors/builtin/paych"
paych0 "github.com/filecoin-project/specs-actors/actors/builtin/paych"
adt0 "github.com/filecoin-project/specs-actors/actors/util/adt" adt0 "github.com/filecoin-project/specs-actors/actors/util/adt"
) )
var _ State = (*state0)(nil) var _ State = (*state0)(nil)
func load0(store adt.Store, root cid.Cid) (State, error) {
out := state0{store: store}
err := store.Get(store.Context(), root, &out)
if err != nil {
return nil, err
}
return &out, nil
}
type state0 struct { type state0 struct {
paych.State paych0.State
store adt.Store store adt.Store
lsAmt *adt0.Array lsAmt *adt0.Array
} }
@ -72,14 +85,14 @@ func (s *state0) ForEachLaneState(cb func(idx uint64, dl LaneState) error) error
// Note: we use a map instead of an array to store laneStates because the // Note: we use a map instead of an array to store laneStates because the
// client sets the lane ID (the index) and potentially they could use a // client sets the lane ID (the index) and potentially they could use a
// very large index. // very large index.
var ls paych.LaneState var ls paych0.LaneState
return lsamt.ForEach(&ls, func(i int64) error { return lsamt.ForEach(&ls, func(i int64) error {
return cb(uint64(i), &laneState0{ls}) return cb(uint64(i), &laneState0{ls})
}) })
} }
type laneState0 struct { type laneState0 struct {
paych.LaneState paych0.LaneState
} }
func (ls *laneState0) Redeemed() (big.Int, error) { func (ls *laneState0) Redeemed() (big.Int, error) {

View File

@ -0,0 +1,104 @@
package paych
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"
"github.com/filecoin-project/lotus/chain/actors/adt"
paych2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/paych"
adt2 "github.com/filecoin-project/specs-actors/v2/actors/util/adt"
)
var _ State = (*state2)(nil)
func load2(store adt.Store, root cid.Cid) (State, error) {
out := state2{store: store}
err := store.Get(store.Context(), root, &out)
if err != nil {
return nil, err
}
return &out, nil
}
type state2 struct {
paych2.State
store adt.Store
lsAmt *adt2.Array
}
// Channel owner, who has funded the actor
func (s *state2) From() (address.Address, error) {
return s.State.From, nil
}
// Recipient of payouts from channel
func (s *state2) To() (address.Address, error) {
return s.State.To, nil
}
// Height at which the channel can be `Collected`
func (s *state2) SettlingAt() (abi.ChainEpoch, error) {
return s.State.SettlingAt, nil
}
// Amount successfully redeemed through the payment channel, paid out on `Collect()`
func (s *state2) ToSend() (abi.TokenAmount, error) {
return s.State.ToSend, nil
}
func (s *state2) getOrLoadLsAmt() (*adt2.Array, error) {
if s.lsAmt != nil {
return s.lsAmt, nil
}
// Get the lane state from the chain
lsamt, err := adt2.AsArray(s.store, s.State.LaneStates)
if err != nil {
return nil, err
}
s.lsAmt = lsamt
return lsamt, nil
}
// Get total number of lanes
func (s *state2) LaneCount() (uint64, error) {
lsamt, err := s.getOrLoadLsAmt()
if err != nil {
return 0, err
}
return lsamt.Length(), nil
}
// Iterate lane states
func (s *state2) ForEachLaneState(cb func(idx uint64, dl LaneState) error) error {
// Get the lane state from the chain
lsamt, err := s.getOrLoadLsAmt()
if err != nil {
return err
}
// Note: we use a map instead of an array to store laneStates because the
// client sets the lane ID (the index) and potentially they could use a
// very large index.
var ls paych2.LaneState
return lsamt.ForEach(&ls, func(i int64) error {
return cb(uint64(i), &laneState2{ls})
})
}
type laneState2 struct {
paych2.LaneState
}
func (ls *laneState2) Redeemed() (big.Int, error) {
return ls.LaneState.Redeemed, nil
}
func (ls *laneState2) Nonce() (uint64, error) {
return ls.LaneState.Nonce, nil
}

View File

@ -2,28 +2,37 @@ package power
import ( import (
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/ipfs/go-cid"
"golang.org/x/xerrors" "golang.org/x/xerrors"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/cbor" "github.com/filecoin-project/go-state-types/cbor"
builtin0 "github.com/filecoin-project/specs-actors/actors/builtin"
"github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/filecoin-project/lotus/chain/actors/builtin" "github.com/filecoin-project/lotus/chain/actors/builtin"
"github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/types"
builtin0 "github.com/filecoin-project/specs-actors/actors/builtin"
builtin2 "github.com/filecoin-project/specs-actors/v2/actors/builtin"
) )
func init() {
builtin.RegisterActorState(builtin0.StoragePowerActorCodeID, func(store adt.Store, root cid.Cid) (cbor.Marshaler, error) {
return load0(store, root)
})
builtin.RegisterActorState(builtin2.StoragePowerActorCodeID, func(store adt.Store, root cid.Cid) (cbor.Marshaler, error) {
return load2(store, root)
})
}
var Address = builtin0.StoragePowerActorAddr var Address = builtin0.StoragePowerActorAddr
func Load(store adt.Store, act *types.Actor) (st State, err error) { func Load(store adt.Store, act *types.Actor) (st State, err error) {
switch act.Code { switch act.Code {
case builtin0.StoragePowerActorCodeID: case builtin0.StoragePowerActorCodeID:
out := state0{store: store} return load0(store, act.Head)
err := store.Get(store.Context(), act.Head, &out) case builtin2.StoragePowerActorCodeID:
if err != nil { return load2(store, act.Head)
return nil, err
}
return &out, nil
} }
return nil, xerrors.Errorf("unknown actor code %s", act.Code) return nil, xerrors.Errorf("unknown actor code %s", act.Code)
} }

View File

@ -3,13 +3,26 @@ package power
import ( import (
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/ipfs/go-cid"
"github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/filecoin-project/lotus/chain/actors/builtin" "github.com/filecoin-project/lotus/chain/actors/builtin"
power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" power0 "github.com/filecoin-project/specs-actors/actors/builtin/power"
"github.com/filecoin-project/specs-actors/actors/util/adt" adt0 "github.com/filecoin-project/specs-actors/actors/util/adt"
) )
var _ State = (*state0)(nil) var _ State = (*state0)(nil)
func load0(store adt.Store, root cid.Cid) (State, error) {
out := state0{store: store}
err := store.Get(store.Context(), root, &out)
if err != nil {
return nil, err
}
return &out, nil
}
type state0 struct { type state0 struct {
power0.State power0.State
store adt.Store store adt.Store
@ -35,7 +48,7 @@ func (s *state0) TotalCommitted() (Claim, error) {
} }
func (s *state0) MinerPower(addr address.Address) (Claim, bool, error) { func (s *state0) MinerPower(addr address.Address) (Claim, bool, error) {
claims, err := adt.AsMap(s.store, s.Claims) claims, err := adt0.AsMap(s.store, s.Claims)
if err != nil { if err != nil {
return Claim{}, false, err return Claim{}, false, err
} }
@ -63,7 +76,7 @@ func (s *state0) MinerCounts() (uint64, uint64, error) {
} }
func (s *state0) ListAllMiners() ([]address.Address, error) { func (s *state0) ListAllMiners() ([]address.Address, error) {
claims, err := adt.AsMap(s.store, s.Claims) claims, err := adt0.AsMap(s.store, s.Claims)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -0,0 +1,98 @@
package power
import (
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi"
"github.com/ipfs/go-cid"
"github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/filecoin-project/lotus/chain/actors/builtin"
power2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/power"
adt2 "github.com/filecoin-project/specs-actors/v2/actors/util/adt"
)
var _ State = (*state2)(nil)
func load2(store adt.Store, root cid.Cid) (State, error) {
out := state2{store: store}
err := store.Get(store.Context(), root, &out)
if err != nil {
return nil, err
}
return &out, nil
}
type state2 struct {
power2.State
store adt.Store
}
func (s *state2) TotalLocked() (abi.TokenAmount, error) {
return s.TotalPledgeCollateral, nil
}
func (s *state2) TotalPower() (Claim, error) {
return Claim{
RawBytePower: s.TotalRawBytePower,
QualityAdjPower: s.TotalQualityAdjPower,
}, nil
}
// Committed power to the network. Includes miners below the minimum threshold.
func (s *state2) TotalCommitted() (Claim, error) {
return Claim{
RawBytePower: s.TotalBytesCommitted,
QualityAdjPower: s.TotalQABytesCommitted,
}, nil
}
func (s *state2) MinerPower(addr address.Address) (Claim, bool, error) {
claims, err := adt2.AsMap(s.store, s.Claims)
if err != nil {
return Claim{}, false, err
}
var claim power2.Claim
ok, err := claims.Get(abi.AddrKey(addr), &claim)
if err != nil {
return Claim{}, false, err
}
return Claim{
RawBytePower: claim.RawBytePower,
QualityAdjPower: claim.QualityAdjPower,
}, ok, nil
}
func (s *state2) MinerNominalPowerMeetsConsensusMinimum(a address.Address) (bool, error) {
return s.State.MinerNominalPowerMeetsConsensusMinimum(s.store, a)
}
func (s *state2) TotalPowerSmoothed() (builtin.FilterEstimate, error) {
return builtin.FromV2FilterEstimate(s.State.ThisEpochQAPowerSmoothed), nil
}
func (s *state2) MinerCounts() (uint64, uint64, error) {
return uint64(s.State.MinerAboveMinPowerCount), uint64(s.State.MinerCount), nil
}
func (s *state2) ListAllMiners() ([]address.Address, error) {
claims, err := adt2.AsMap(s.store, s.Claims)
if err != nil {
return nil, err
}
var miners []address.Address
err = claims.ForEach(nil, func(k string) error {
a, err := address.NewFromBytes([]byte(k))
if err != nil {
return err
}
miners = append(miners, a)
return nil
})
if err != nil {
return nil, err
}
return miners, nil
}

View File

@ -3,27 +3,35 @@ package reward
import ( import (
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
reward0 "github.com/filecoin-project/specs-actors/actors/builtin/reward" reward0 "github.com/filecoin-project/specs-actors/actors/builtin/reward"
"github.com/ipfs/go-cid"
"golang.org/x/xerrors" "golang.org/x/xerrors"
"github.com/filecoin-project/go-state-types/cbor" "github.com/filecoin-project/go-state-types/cbor"
builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" builtin0 "github.com/filecoin-project/specs-actors/actors/builtin"
builtin2 "github.com/filecoin-project/specs-actors/v2/actors/builtin"
"github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/filecoin-project/lotus/chain/actors/builtin" "github.com/filecoin-project/lotus/chain/actors/builtin"
"github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/types"
) )
func init() {
builtin.RegisterActorState(builtin0.RewardActorCodeID, func(store adt.Store, root cid.Cid) (cbor.Marshaler, error) {
return load0(store, root)
})
builtin.RegisterActorState(builtin2.RewardActorCodeID, func(store adt.Store, root cid.Cid) (cbor.Marshaler, error) {
return load2(store, root)
})
}
var Address = builtin0.RewardActorAddr var Address = builtin0.RewardActorAddr
func Load(store adt.Store, act *types.Actor) (st State, err error) { func Load(store adt.Store, act *types.Actor) (st State, err error) {
switch act.Code { switch act.Code {
case builtin0.RewardActorCodeID: case builtin0.RewardActorCodeID:
out := state0{store: store} return load0(store, act.Head)
err := store.Get(store.Context(), act.Head, &out) case builtin2.RewardActorCodeID:
if err != nil { return load2(store, act.Head)
return nil, err
}
return &out, nil
} }
return nil, xerrors.Errorf("unknown actor code %s", act.Code) return nil, xerrors.Errorf("unknown actor code %s", act.Code)
} }

View File

@ -2,17 +2,29 @@ package reward
import ( import (
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/ipfs/go-cid"
"github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/filecoin-project/lotus/chain/actors/builtin" "github.com/filecoin-project/lotus/chain/actors/builtin"
miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner"
"github.com/filecoin-project/specs-actors/actors/builtin/reward" reward0 "github.com/filecoin-project/specs-actors/actors/builtin/reward"
"github.com/filecoin-project/specs-actors/actors/util/adt" smoothing0 "github.com/filecoin-project/specs-actors/actors/util/smoothing"
"github.com/filecoin-project/specs-actors/actors/util/smoothing"
) )
var _ State = (*state0)(nil) var _ State = (*state0)(nil)
func load0(store adt.Store, root cid.Cid) (State, error) {
out := state0{store: store}
err := store.Get(store.Context(), root, &out)
if err != nil {
return nil, err
}
return &out, nil
}
type state0 struct { type state0 struct {
reward.State reward0.State
store adt.Store store adt.Store
} }
@ -54,7 +66,7 @@ func (s *state0) InitialPledgeForPower(sectorWeight abi.StoragePower, networkTot
s.State.ThisEpochBaselinePower, s.State.ThisEpochBaselinePower,
networkTotalPledge, networkTotalPledge,
s.State.ThisEpochRewardSmoothed, s.State.ThisEpochRewardSmoothed,
&smoothing.FilterEstimate{ &smoothing0.FilterEstimate{
PositionEstimate: networkQAPower.PositionEstimate, PositionEstimate: networkQAPower.PositionEstimate,
VelocityEstimate: networkQAPower.VelocityEstimate, VelocityEstimate: networkQAPower.VelocityEstimate,
}, },
@ -63,7 +75,7 @@ func (s *state0) InitialPledgeForPower(sectorWeight abi.StoragePower, networkTot
func (s *state0) PreCommitDepositForPower(networkQAPower builtin.FilterEstimate, sectorWeight abi.StoragePower) (abi.TokenAmount, error) { func (s *state0) PreCommitDepositForPower(networkQAPower builtin.FilterEstimate, sectorWeight abi.StoragePower) (abi.TokenAmount, error) {
return miner0.PreCommitDepositForPower(s.State.ThisEpochRewardSmoothed, return miner0.PreCommitDepositForPower(s.State.ThisEpochRewardSmoothed,
&smoothing.FilterEstimate{ &smoothing0.FilterEstimate{
PositionEstimate: networkQAPower.PositionEstimate, PositionEstimate: networkQAPower.PositionEstimate,
VelocityEstimate: networkQAPower.VelocityEstimate, VelocityEstimate: networkQAPower.VelocityEstimate,
}, },

View File

@ -0,0 +1,86 @@
package reward
import (
"github.com/filecoin-project/go-state-types/abi"
"github.com/ipfs/go-cid"
"github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/filecoin-project/lotus/chain/actors/builtin"
miner2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/miner"
reward2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/reward"
smoothing2 "github.com/filecoin-project/specs-actors/v2/actors/util/smoothing"
)
var _ State = (*state2)(nil)
func load2(store adt.Store, root cid.Cid) (State, error) {
out := state2{store: store}
err := store.Get(store.Context(), root, &out)
if err != nil {
return nil, err
}
return &out, nil
}
type state2 struct {
reward2.State
store adt.Store
}
func (s *state2) ThisEpochReward() (abi.StoragePower, error) {
return s.State.ThisEpochReward, nil
}
func (s *state2) ThisEpochRewardSmoothed() (builtin.FilterEstimate, error) {
return builtin.FilterEstimate{
PositionEstimate: s.State.ThisEpochRewardSmoothed.PositionEstimate,
VelocityEstimate: s.State.ThisEpochRewardSmoothed.VelocityEstimate,
}, nil
}
func (s *state2) ThisEpochBaselinePower() (abi.StoragePower, error) {
return s.State.ThisEpochBaselinePower, nil
}
func (s *state2) TotalStoragePowerReward() (abi.TokenAmount, error) {
return s.State.TotalStoragePowerReward, nil
}
func (s *state2) EffectiveBaselinePower() (abi.StoragePower, error) {
return s.State.EffectiveBaselinePower, nil
}
func (s *state2) EffectiveNetworkTime() (abi.ChainEpoch, error) {
return s.State.EffectiveNetworkTime, nil
}
func (s *state2) CumsumBaseline() (abi.StoragePower, error) {
return s.State.CumsumBaseline, nil
}
func (s *state2) CumsumRealized() (abi.StoragePower, error) {
return s.State.CumsumBaseline, nil
}
func (s *state2) InitialPledgeForPower(qaPower abi.StoragePower, networkTotalPledge abi.TokenAmount, networkQAPower *builtin.FilterEstimate, circSupply abi.TokenAmount) (abi.TokenAmount, error) {
return miner2.InitialPledgeForPower(
qaPower,
s.State.ThisEpochBaselinePower,
s.State.ThisEpochRewardSmoothed,
smoothing2.FilterEstimate{
PositionEstimate: networkQAPower.PositionEstimate,
VelocityEstimate: networkQAPower.VelocityEstimate,
},
circSupply,
), nil
}
func (s *state2) PreCommitDepositForPower(networkQAPower builtin.FilterEstimate, sectorWeight abi.StoragePower) (abi.TokenAmount, error) {
return miner2.PreCommitDepositForPower(s.State.ThisEpochRewardSmoothed,
smoothing2.FilterEstimate{
PositionEstimate: networkQAPower.PositionEstimate,
VelocityEstimate: networkQAPower.VelocityEstimate,
},
sectorWeight), nil
}

View File

@ -0,0 +1,46 @@
package verifreg
import (
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/lotus/chain/actors"
"github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/ipfs/go-cid"
"golang.org/x/xerrors"
)
func getDataCap(store adt.Store, ver actors.Version, root cid.Cid, addr address.Address) (bool, abi.StoragePower, error) {
if addr.Protocol() != address.ID {
return false, big.Zero(), xerrors.Errorf("can only look up ID addresses")
}
vh, err := adt.AsMap(store, root, ver)
if err != nil {
return false, big.Zero(), xerrors.Errorf("loading verifreg: %w", err)
}
var dcap abi.StoragePower
if found, err := vh.Get(abi.AddrKey(addr), &dcap); err != nil {
return false, big.Zero(), xerrors.Errorf("looking up addr: %w", err)
} else if !found {
return false, big.Zero(), nil
}
return true, dcap, nil
}
func forEachCap(store adt.Store, ver actors.Version, root cid.Cid, cb func(addr address.Address, dcap abi.StoragePower) error) error {
vh, err := adt.AsMap(store, root, ver)
if err != nil {
return xerrors.Errorf("loading verified clients: %w", err)
}
var dcap abi.StoragePower
return vh.ForEach(&dcap, func(key string) error {
a, err := address.NewFromBytes([]byte(key))
if err != nil {
return err
}
return cb(a, dcap)
})
}

View File

@ -3,73 +3,46 @@ package verifreg
import ( import (
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg"
adt0 "github.com/filecoin-project/specs-actors/actors/util/adt"
"github.com/ipfs/go-cid" "github.com/ipfs/go-cid"
"golang.org/x/xerrors"
"github.com/filecoin-project/lotus/chain/actors"
"github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/actors/adt"
verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg"
) )
var _ State = (*state0)(nil) var _ State = (*state0)(nil)
func load0(store adt.Store, root cid.Cid) (State, error) {
out := state0{store: store}
err := store.Get(store.Context(), root, &out)
if err != nil {
return nil, err
}
return &out, nil
}
type state0 struct { type state0 struct {
verifreg0.State verifreg0.State
store adt.Store store adt.Store
} }
func getDataCap(store adt.Store, root cid.Cid, addr address.Address) (bool, abi.StoragePower, error) {
if addr.Protocol() != address.ID {
return false, big.Zero(), xerrors.Errorf("can only look up ID addresses")
}
vh, err := adt0.AsMap(store, root)
if err != nil {
return false, big.Zero(), xerrors.Errorf("loading verifreg: %w", err)
}
var dcap abi.StoragePower
if found, err := vh.Get(abi.AddrKey(addr), &dcap); err != nil {
return false, big.Zero(), xerrors.Errorf("looking up addr: %w", err)
} else if !found {
return false, big.Zero(), nil
}
return true, dcap, nil
}
func (s *state0) RootKey() (address.Address, error) { func (s *state0) RootKey() (address.Address, error) {
return s.State.RootKey, nil return s.State.RootKey, nil
} }
func (s *state0) VerifiedClientDataCap(addr address.Address) (bool, abi.StoragePower, error) { func (s *state0) VerifiedClientDataCap(addr address.Address) (bool, abi.StoragePower, error) {
return getDataCap(s.store, s.State.VerifiedClients, addr) return getDataCap(s.store, actors.Version0, s.State.VerifiedClients, addr)
} }
func (s *state0) VerifierDataCap(addr address.Address) (bool, abi.StoragePower, error) { func (s *state0) VerifierDataCap(addr address.Address) (bool, abi.StoragePower, error) {
return getDataCap(s.store, s.State.Verifiers, addr) return getDataCap(s.store, actors.Version0, s.State.Verifiers, addr)
}
func forEachCap(store adt.Store, root cid.Cid, cb func(addr address.Address, dcap abi.StoragePower) error) error {
vh, err := adt0.AsMap(store, root)
if err != nil {
return xerrors.Errorf("loading verified clients: %w", err)
}
var dcap abi.StoragePower
return vh.ForEach(&dcap, func(key string) error {
a, err := address.NewFromBytes([]byte(key))
if err != nil {
return err
}
return cb(a, dcap)
})
} }
func (s *state0) ForEachVerifier(cb func(addr address.Address, dcap abi.StoragePower) error) error { func (s *state0) ForEachVerifier(cb func(addr address.Address, dcap abi.StoragePower) error) error {
return forEachCap(s.store, s.State.Verifiers, cb) return forEachCap(s.store, actors.Version0, s.State.Verifiers, cb)
} }
func (s *state0) ForEachClient(cb func(addr address.Address, dcap abi.StoragePower) error) error { func (s *state0) ForEachClient(cb func(addr address.Address, dcap abi.StoragePower) error) error {
return forEachCap(s.store, s.State.VerifiedClients, cb) return forEachCap(s.store, actors.Version0, s.State.VerifiedClients, cb)
} }

View File

@ -0,0 +1,48 @@
package verifreg
import (
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi"
"github.com/ipfs/go-cid"
"github.com/filecoin-project/lotus/chain/actors"
"github.com/filecoin-project/lotus/chain/actors/adt"
verifreg2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/verifreg"
)
var _ State = (*state2)(nil)
func load2(store adt.Store, root cid.Cid) (State, error) {
out := state2{store: store}
err := store.Get(store.Context(), root, &out)
if err != nil {
return nil, err
}
return &out, nil
}
type state2 struct {
verifreg2.State
store adt.Store
}
func (s *state2) RootKey() (address.Address, error) {
return s.State.RootKey, nil
}
func (s *state2) VerifiedClientDataCap(addr address.Address) (bool, abi.StoragePower, error) {
return getDataCap(s.store, actors.Version2, s.State.VerifiedClients, addr)
}
func (s *state2) VerifierDataCap(addr address.Address) (bool, abi.StoragePower, error) {
return getDataCap(s.store, actors.Version2, s.State.Verifiers, addr)
}
func (s *state2) ForEachVerifier(cb func(addr address.Address, dcap abi.StoragePower) error) error {
return forEachCap(s.store, actors.Version2, s.State.Verifiers, cb)
}
func (s *state2) ForEachClient(cb func(addr address.Address, dcap abi.StoragePower) error) error {
return forEachCap(s.store, actors.Version2, s.State.VerifiedClients, cb)
}

View File

@ -3,26 +3,35 @@ package verifreg
import ( import (
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/ipfs/go-cid"
"golang.org/x/xerrors" "golang.org/x/xerrors"
"github.com/filecoin-project/go-state-types/cbor" "github.com/filecoin-project/go-state-types/cbor"
builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" builtin0 "github.com/filecoin-project/specs-actors/actors/builtin"
builtin2 "github.com/filecoin-project/specs-actors/v2/actors/builtin"
"github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/filecoin-project/lotus/chain/actors/builtin"
"github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/types"
) )
func init() {
builtin.RegisterActorState(builtin0.VerifiedRegistryActorCodeID, func(store adt.Store, root cid.Cid) (cbor.Marshaler, error) {
return load0(store, root)
})
builtin.RegisterActorState(builtin2.VerifiedRegistryActorCodeID, func(store adt.Store, root cid.Cid) (cbor.Marshaler, error) {
return load2(store, root)
})
}
var Address = builtin0.VerifiedRegistryActorAddr var Address = builtin0.VerifiedRegistryActorAddr
func Load(store adt.Store, act *types.Actor) (State, error) { func Load(store adt.Store, act *types.Actor) (State, error) {
switch act.Code { switch act.Code {
case builtin0.VerifiedRegistryActorCodeID: case builtin0.VerifiedRegistryActorCodeID:
out := state0{store: store} return load0(store, act.Head)
err := store.Get(store.Context(), act.Head, &out) case builtin2.VerifiedRegistryActorCodeID:
if err != nil { return load2(store, act.Head)
return nil, err
}
return &out, nil
} }
return nil, xerrors.Errorf("unknown actor code %s", act.Code) return nil, xerrors.Errorf("unknown actor code %s", act.Code)
} }

View File

@ -2,10 +2,22 @@ package policy
import ( import (
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/network"
"github.com/filecoin-project/lotus/chain/actors"
market0 "github.com/filecoin-project/specs-actors/actors/builtin/market"
miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner"
power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" power0 "github.com/filecoin-project/specs-actors/actors/builtin/power"
verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg" verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg"
builtin2 "github.com/filecoin-project/specs-actors/v2/actors/builtin"
market2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/market"
miner2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/miner"
verifreg2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/verifreg"
)
const (
ChainFinality = miner0.ChainFinality
SealRandomnessLookback = ChainFinality
) )
// SetSupportedProofTypes sets supported proof types, across all actor versions. // SetSupportedProofTypes sets supported proof types, across all actor versions.
@ -17,6 +29,7 @@ func SetSupportedProofTypes(types ...abi.RegisteredSealProof) {
} }
// Set for all miner versions. // Set for all miner versions.
miner0.SupportedProofTypes = newTypes miner0.SupportedProofTypes = newTypes
miner2.SupportedProofTypes = newTypes
} }
// AddSupportedProofTypes sets supported proof types, across all actor versions. // AddSupportedProofTypes sets supported proof types, across all actor versions.
@ -25,6 +38,7 @@ func AddSupportedProofTypes(types ...abi.RegisteredSealProof) {
for _, t := range types { for _, t := range types {
// Set for all miner versions. // Set for all miner versions.
miner0.SupportedProofTypes[t] = struct{}{} miner0.SupportedProofTypes[t] = struct{}{}
miner2.SupportedProofTypes[t] = struct{}{}
} }
} }
@ -33,6 +47,7 @@ func AddSupportedProofTypes(types ...abi.RegisteredSealProof) {
func SetPreCommitChallengeDelay(delay abi.ChainEpoch) { func SetPreCommitChallengeDelay(delay abi.ChainEpoch) {
// Set for all miner versions. // Set for all miner versions.
miner0.PreCommitChallengeDelay = delay miner0.PreCommitChallengeDelay = delay
miner2.PreCommitChallengeDelay = delay
} }
// TODO: this function shouldn't really exist. Instead, the API should expose the precommit delay. // TODO: this function shouldn't really exist. Instead, the API should expose the precommit delay.
@ -45,10 +60,50 @@ func GetPreCommitChallengeDelay() abi.ChainEpoch {
// for testing. // for testing.
func SetConsensusMinerMinPower(p abi.StoragePower) { func SetConsensusMinerMinPower(p abi.StoragePower) {
power0.ConsensusMinerMinPower = p power0.ConsensusMinerMinPower = p
for _, policy := range builtin2.SealProofPolicies {
policy.ConsensusMinerMinPower = p
}
} }
// SetMinVerifiedDealSize sets the minimum size of a verified deal. This should // SetMinVerifiedDealSize sets the minimum size of a verified deal. This should
// only be used for testing. // only be used for testing.
func SetMinVerifiedDealSize(size abi.StoragePower) { func SetMinVerifiedDealSize(size abi.StoragePower) {
verifreg0.MinVerifiedDealSize = size verifreg0.MinVerifiedDealSize = size
verifreg2.MinVerifiedDealSize = size
}
func GetMaxProveCommitDuration(ver actors.Version, t abi.RegisteredSealProof) abi.ChainEpoch {
switch ver {
case actors.Version0:
return miner0.MaxSealDuration[t]
case actors.Version2:
return miner2.MaxProveCommitDuration[t]
default:
panic("unsupported actors version")
}
}
func DealProviderCollateralBounds(
size abi.PaddedPieceSize, verified bool,
rawBytePower, qaPower, baselinePower abi.StoragePower,
circulatingFil abi.TokenAmount, nwVer network.Version,
) (min, max abi.TokenAmount) {
switch actors.VersionForNetwork(nwVer) {
case actors.Version0:
return market0.DealProviderCollateralBounds(size, verified, rawBytePower, qaPower, baselinePower, circulatingFil, nwVer)
case actors.Version2:
return market2.DealProviderCollateralBounds(size, verified, rawBytePower, qaPower, baselinePower, circulatingFil)
default:
panic("unsupported network version")
}
}
// Sets the challenge window and scales the proving period to match (such that
// there are always 48 challenge windows in a proving period).
func SetWPoStChallengeWindow(period abi.ChainEpoch) {
miner0.WPoStChallengeWindow = period
miner0.WPoStProvingPeriod = period * abi.ChainEpoch(miner0.WPoStPeriodDeadlines)
miner2.WPoStChallengeWindow = period
miner2.WPoStProvingPeriod = period * abi.ChainEpoch(miner2.WPoStPeriodDeadlines)
} }

View File

@ -7,6 +7,9 @@ import (
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner"
verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg"
miner2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/miner"
verifreg2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/verifreg"
) )
func TestSupportedProofTypes(t *testing.T) { func TestSupportedProofTypes(t *testing.T) {
@ -34,3 +37,14 @@ func TestSupportedProofTypes(t *testing.T) {
}, },
) )
} }
// Tests assumptions about policies being the same between actor versions.
func TestAssumptions(t *testing.T) {
require.EqualValues(t, miner0.SupportedProofTypes, miner2.SupportedProofTypes)
require.Equal(t, miner0.PreCommitChallengeDelay, miner2.PreCommitChallengeDelay)
require.Equal(t, miner0.ChainFinality, miner2.ChainFinality)
require.Equal(t, miner0.WPoStChallengeWindow, miner2.WPoStChallengeWindow)
require.Equal(t, miner0.WPoStProvingPeriod, miner2.WPoStProvingPeriod)
require.Equal(t, miner0.WPoStPeriodDeadlines, miner2.WPoStPeriodDeadlines)
require.True(t, verifreg0.MinVerifiedDealSize.Equals(verifreg2.MinVerifiedDealSize))
}

26
chain/actors/version.go Normal file
View File

@ -0,0 +1,26 @@
package actors
import (
"fmt"
"github.com/filecoin-project/go-state-types/network"
)
type Version int
const (
Version0 = 0
Version2 = 2
)
// Converts a network version into an actors adt version.
func VersionForNetwork(version network.Version) Version {
switch version {
case network.Version0, network.Version1, network.Version2, network.Version3:
return Version0
case network.Version4:
return Version2
default:
panic(fmt.Sprintf("unsupported network version %d", version))
}
}

View File

@ -9,6 +9,7 @@ import (
"time" "time"
"github.com/filecoin-project/specs-actors/actors/runtime/proof" "github.com/filecoin-project/specs-actors/actors/runtime/proof"
"github.com/google/uuid"
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
@ -224,7 +225,7 @@ func NewGeneratorWithSectors(numSectors int) (*ChainGen, error) {
}, },
VerifregRootKey: DefaultVerifregRootkeyActor, VerifregRootKey: DefaultVerifregRootkeyActor,
RemainderAccount: DefaultRemainderAccountActor, RemainderAccount: DefaultRemainderAccountActor,
NetworkName: "", NetworkName: uuid.New().String(),
Timestamp: uint64(build.Clock.Now().Add(-500 * time.Duration(build.BlockDelaySecs) * time.Second).Unix()), Timestamp: uint64(build.Clock.Now().Add(-500 * time.Duration(build.BlockDelaySecs) * time.Second).Unix()),
} }

View File

@ -24,7 +24,7 @@ import (
adt0 "github.com/filecoin-project/specs-actors/actors/util/adt" adt0 "github.com/filecoin-project/specs-actors/actors/util/adt"
"github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/build"
"github.com/filecoin-project/lotus/chain/actors/builtin" "github.com/filecoin-project/lotus/chain/actors"
"github.com/filecoin-project/lotus/chain/state" "github.com/filecoin-project/lotus/chain/state"
"github.com/filecoin-project/lotus/chain/store" "github.com/filecoin-project/lotus/chain/store"
"github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/types"
@ -115,7 +115,7 @@ func MakeInitialStateTree(ctx context.Context, bs bstore.Blockstore, template ge
return nil, nil, xerrors.Errorf("putting empty object: %w", err) return nil, nil, xerrors.Errorf("putting empty object: %w", err)
} }
state, err := state.NewStateTree(cst, builtin.Version0) state, err := state.NewStateTree(cst, actors.Version0)
if err != nil { if err != nil {
return nil, nil, xerrors.Errorf("making new state tree: %w", err) return nil, nil, xerrors.Errorf("making new state tree: %w", err)
} }

View File

@ -10,7 +10,9 @@ import (
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/specs-actors/actors/builtin"
builtin0 "github.com/filecoin-project/specs-actors/actors/builtin"
builtin2 "github.com/filecoin-project/specs-actors/v2/actors/builtin"
) )
type ActorLookup func(context.Context, address.Address, types.TipSetKey) (*types.Actor, error) type ActorLookup func(context.Context, address.Address, types.TipSetKey) (*types.Actor, error)
@ -27,19 +29,33 @@ type CostKey struct {
} }
var Costs = map[CostKey]int64{ var Costs = map[CostKey]int64{
{builtin.InitActorCodeID, 2}: 8916753, {builtin0.InitActorCodeID, 2}: 8916753,
{builtin.StorageMarketActorCodeID, 2}: 6955002, {builtin0.StorageMarketActorCodeID, 2}: 6955002,
{builtin.StorageMarketActorCodeID, 4}: 245436108, {builtin0.StorageMarketActorCodeID, 4}: 245436108,
{builtin.StorageMinerActorCodeID, 4}: 2315133, {builtin0.StorageMinerActorCodeID, 4}: 2315133,
{builtin.StorageMinerActorCodeID, 5}: 1600271356, {builtin0.StorageMinerActorCodeID, 5}: 1600271356,
{builtin.StorageMinerActorCodeID, 6}: 22864493, {builtin0.StorageMinerActorCodeID, 6}: 22864493,
{builtin.StorageMinerActorCodeID, 7}: 142002419, {builtin0.StorageMinerActorCodeID, 7}: 142002419,
{builtin.StorageMinerActorCodeID, 10}: 23008274, {builtin0.StorageMinerActorCodeID, 10}: 23008274,
{builtin.StorageMinerActorCodeID, 11}: 19303178, {builtin0.StorageMinerActorCodeID, 11}: 19303178,
{builtin.StorageMinerActorCodeID, 14}: 566356835, {builtin0.StorageMinerActorCodeID, 14}: 566356835,
{builtin.StorageMinerActorCodeID, 16}: 5325185, {builtin0.StorageMinerActorCodeID, 16}: 5325185,
{builtin.StorageMinerActorCodeID, 18}: 2328637, {builtin0.StorageMinerActorCodeID, 18}: 2328637,
{builtin.StoragePowerActorCodeID, 2}: 23600956, {builtin0.StoragePowerActorCodeID, 2}: 23600956,
// TODO: Just reuse v0 values for now, this isn't actually used
{builtin2.InitActorCodeID, 2}: 8916753,
{builtin2.StorageMarketActorCodeID, 2}: 6955002,
{builtin2.StorageMarketActorCodeID, 4}: 245436108,
{builtin2.StorageMinerActorCodeID, 4}: 2315133,
{builtin2.StorageMinerActorCodeID, 5}: 1600271356,
{builtin2.StorageMinerActorCodeID, 6}: 22864493,
{builtin2.StorageMinerActorCodeID, 7}: 142002419,
{builtin2.StorageMinerActorCodeID, 10}: 23008274,
{builtin2.StorageMinerActorCodeID, 11}: 19303178,
{builtin2.StorageMinerActorCodeID, 14}: 566356835,
{builtin2.StorageMinerActorCodeID, 16}: 5325185,
{builtin2.StorageMinerActorCodeID, 18}: 2328637,
{builtin2.StoragePowerActorCodeID, 2}: 23600956,
} }
func failedGuess(msg *types.SignedMessage) int64 { func failedGuess(msg *types.SignedMessage) int64 {
@ -51,7 +67,8 @@ func failedGuess(msg *types.SignedMessage) int64 {
} }
func GuessGasUsed(ctx context.Context, tsk types.TipSetKey, msg *types.SignedMessage, al ActorLookup) (int64, error) { func GuessGasUsed(ctx context.Context, tsk types.TipSetKey, msg *types.SignedMessage, al ActorLookup) (int64, error) {
if msg.Message.Method == builtin.MethodSend { // MethodSend is the same in all versions.
if msg.Message.Method == builtin0.MethodSend {
switch msg.Message.From.Protocol() { switch msg.Message.From.Protocol() {
case address.BLS: case address.BLS:
return 1298450, nil return 1298450, nil

View File

@ -13,7 +13,7 @@ import (
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/lotus/chain/actors/builtin" "github.com/filecoin-project/lotus/chain/actors"
init_ "github.com/filecoin-project/lotus/chain/actors/builtin/init" init_ "github.com/filecoin-project/lotus/chain/actors/builtin/init"
cbg "github.com/whyrusleeping/cbor-gen" cbg "github.com/whyrusleeping/cbor-gen"
@ -26,7 +26,7 @@ var log = logging.Logger("statetree")
// StateTree stores actors state by their ID. // StateTree stores actors state by their ID.
type StateTree struct { type StateTree struct {
root adt.Map root adt.Map
version builtin.Version // TODO version actors.Version // TODO
info cid.Cid info cid.Cid
Store cbor.IpldStore Store cbor.IpldStore
@ -120,11 +120,17 @@ func (ss *stateSnaps) deleteActor(addr address.Address) {
ss.layers[len(ss.layers)-1].actors[addr] = streeOp{Delete: true} ss.layers[len(ss.layers)-1].actors[addr] = streeOp{Delete: true}
} }
func NewStateTree(cst cbor.IpldStore, version builtin.Version) (*StateTree, error) { func NewStateTree(cst cbor.IpldStore, version actors.Version) (*StateTree, error) {
var info cid.Cid var info cid.Cid
switch version { switch version {
case builtin.Version0: case actors.Version0:
// info is undefined // info is undefined
case actors.Version2:
var err error
info, err = cst.Put(context.TODO(), new(types.StateInfo))
if err != nil {
return nil, err
}
default: default:
return nil, xerrors.Errorf("unsupported state tree version: %d", version) return nil, xerrors.Errorf("unsupported state tree version: %d", version)
} }
@ -148,30 +154,28 @@ func LoadStateTree(cst cbor.IpldStore, c cid.Cid) (*StateTree, error) {
if err := cst.Get(context.TODO(), c, &root); err != nil { if err := cst.Get(context.TODO(), c, &root); err != nil {
// We failed to decode as the new version, must be an old version. // We failed to decode as the new version, must be an old version.
root.Actors = c root.Actors = c
root.Version = builtin.Version0 root.Version = actors.Version0
} }
// If that fails, load as an old-style state-tree (direct hampt, version 0. switch root.Version {
nd, err := adt.AsMap(adt.WrapStore(context.TODO(), cst), root.Actors, builtin.Version(root.Version)) case actors.Version0, actors.Version2:
// Load the actual state-tree HAMT.
nd, err := adt.AsMap(adt.WrapStore(context.TODO(), cst), root.Actors, actors.Version(root.Version))
if err != nil { if err != nil {
log.Errorf("loading hamt node %s failed: %s", c, err) log.Errorf("loading hamt node %s failed: %s", c, err)
return nil, err return nil, err
} }
switch root.Version {
case builtin.Version0:
// supported
default:
return nil, xerrors.Errorf("unsupported state tree version: %d", root.Version)
}
return &StateTree{ return &StateTree{
root: nd, root: nd,
info: root.Info, info: root.Info,
version: builtin.Version(root.Version), version: actors.Version(root.Version),
Store: cst, Store: cst,
snaps: newStateSnaps(), snaps: newStateSnaps(),
}, nil }, nil
default:
return nil, xerrors.Errorf("unsupported state tree version: %d", root.Version)
}
} }
func (st *StateTree) SetActor(addr address.Address, act *types.Actor) error { func (st *StateTree) SetActor(addr address.Address, act *types.Actor) error {
@ -305,7 +309,7 @@ func (st *StateTree) Flush(ctx context.Context) (cid.Cid, error) {
return cid.Undef, xerrors.Errorf("failed to flush state-tree hamt: %w", err) return cid.Undef, xerrors.Errorf("failed to flush state-tree hamt: %w", err)
} }
// If we're version 0, return a raw tree. // If we're version 0, return a raw tree.
if st.version == builtin.Version0 { if st.version == actors.Version0 {
return root, nil return root, nil
} }
// Otherwise, return a versioned tree. // Otherwise, return a versioned tree.
@ -396,7 +400,7 @@ func (st *StateTree) ForEach(f func(address.Address, *types.Actor) error) error
} }
// Version returns the version of the StateTree data structure in use. // Version returns the version of the StateTree data structure in use.
func (st *StateTree) Version() builtin.Version { func (st *StateTree) Version() actors.Version {
return st.version return st.version
} }

View File

@ -9,16 +9,17 @@ import (
cbor "github.com/ipfs/go-ipld-cbor" cbor "github.com/ipfs/go-ipld-cbor"
address "github.com/filecoin-project/go-address" address "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/network"
"github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin"
"github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/build"
builtin2 "github.com/filecoin-project/lotus/chain/actors/builtin" "github.com/filecoin-project/lotus/chain/actors"
"github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/types"
) )
func BenchmarkStateTreeSet(b *testing.B) { func BenchmarkStateTreeSet(b *testing.B) {
cst := cbor.NewMemCborStore() cst := cbor.NewMemCborStore()
st, err := NewStateTree(cst, builtin2.VersionForNetwork(build.NewestNetworkVersion)) st, err := NewStateTree(cst, actors.VersionForNetwork(build.NewestNetworkVersion))
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
} }
@ -45,7 +46,7 @@ func BenchmarkStateTreeSet(b *testing.B) {
func BenchmarkStateTreeSetFlush(b *testing.B) { func BenchmarkStateTreeSetFlush(b *testing.B) {
cst := cbor.NewMemCborStore() cst := cbor.NewMemCborStore()
st, err := NewStateTree(cst, builtin2.VersionForNetwork(build.NewestNetworkVersion)) st, err := NewStateTree(cst, actors.VersionForNetwork(build.NewestNetworkVersion))
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
} }
@ -75,7 +76,7 @@ func BenchmarkStateTreeSetFlush(b *testing.B) {
func BenchmarkStateTree10kGetActor(b *testing.B) { func BenchmarkStateTree10kGetActor(b *testing.B) {
cst := cbor.NewMemCborStore() cst := cbor.NewMemCborStore()
st, err := NewStateTree(cst, builtin2.VersionForNetwork(build.NewestNetworkVersion)) st, err := NewStateTree(cst, actors.VersionForNetwork(build.NewestNetworkVersion))
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
} }
@ -117,7 +118,7 @@ func BenchmarkStateTree10kGetActor(b *testing.B) {
func TestSetCache(t *testing.T) { func TestSetCache(t *testing.T) {
cst := cbor.NewMemCborStore() cst := cbor.NewMemCborStore()
st, err := NewStateTree(cst, builtin2.VersionForNetwork(build.NewestNetworkVersion)) st, err := NewStateTree(cst, actors.VersionForNetwork(build.NewestNetworkVersion))
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -154,7 +155,7 @@ func TestSetCache(t *testing.T) {
func TestSnapshots(t *testing.T) { func TestSnapshots(t *testing.T) {
ctx := context.Background() ctx := context.Background()
cst := cbor.NewMemCborStore() cst := cbor.NewMemCborStore()
st, err := NewStateTree(cst, builtin2.VersionForNetwork(build.NewestNetworkVersion)) st, err := NewStateTree(cst, actors.VersionForNetwork(build.NewestNetworkVersion))
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -237,7 +238,8 @@ func assertNotHas(t *testing.T, st *StateTree, addr address.Address) {
func TestStateTreeConsistency(t *testing.T) { func TestStateTreeConsistency(t *testing.T) {
cst := cbor.NewMemCborStore() cst := cbor.NewMemCborStore()
st, err := NewStateTree(cst, builtin2.VersionForNetwork(build.NewestNetworkVersion)) // TODO: ActorUpgrade: this test tests pre actors v2
st, err := NewStateTree(cst, actors.VersionForNetwork(network.Version3))
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@ -5,7 +5,6 @@ import (
"fmt" "fmt"
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/go-state-types/crypto"
"github.com/ipfs/go-cid" "github.com/ipfs/go-cid"
"go.opencensus.io/trace" "go.opencensus.io/trace"
@ -18,14 +17,26 @@ import (
"github.com/filecoin-project/lotus/chain/vm" "github.com/filecoin-project/lotus/chain/vm"
) )
func (sm *StateManager) CallRaw(ctx context.Context, msg *types.Message, bstate cid.Cid, r vm.Rand, bheight abi.ChainEpoch) (*api.InvocResult, error) { func (sm *StateManager) Call(ctx context.Context, msg *types.Message, ts *types.TipSet) (*api.InvocResult, error) {
ctx, span := trace.StartSpan(ctx, "statemanager.CallRaw") ctx, span := trace.StartSpan(ctx, "statemanager.Call")
defer span.End() defer span.End()
if ts == nil {
ts = sm.cs.GetHeaviestTipSet()
}
bstate := ts.ParentState()
bheight := ts.Height()
bstate, err := sm.handleStateForks(ctx, bstate, bheight-1, nil, ts)
if err != nil {
return nil, fmt.Errorf("failed to handle fork: %w", err)
}
vmopt := &vm.VMOpts{ vmopt := &vm.VMOpts{
StateBase: bstate, StateBase: bstate,
Epoch: bheight, Epoch: bheight,
Rand: r, Rand: store.NewChainRand(sm.cs, ts.Cids()),
Bstore: sm.cs.Blockstore(), Bstore: sm.cs.Blockstore(),
Syscalls: sm.cs.VMSys(), Syscalls: sm.cs.VMSys(),
CircSupplyCalc: sm.GetCirculatingSupply, CircSupplyCalc: sm.GetCirculatingSupply,
@ -89,18 +100,6 @@ func (sm *StateManager) CallRaw(ctx context.Context, msg *types.Message, bstate
} }
func (sm *StateManager) Call(ctx context.Context, msg *types.Message, ts *types.TipSet) (*api.InvocResult, error) {
if ts == nil {
ts = sm.cs.GetHeaviestTipSet()
}
state := ts.ParentState()
r := store.NewChainRand(sm.cs, ts.Cids())
return sm.CallRaw(ctx, msg, state, r, ts.Height())
}
func (sm *StateManager) CallWithGas(ctx context.Context, msg *types.Message, priorMsgs []types.ChainMsg, ts *types.TipSet) (*api.InvocResult, error) { func (sm *StateManager) CallWithGas(ctx context.Context, msg *types.Message, priorMsgs []types.ChainMsg, ts *types.TipSet) (*api.InvocResult, error) {
ctx, span := trace.StartSpan(ctx, "statemanager.CallWithGas") ctx, span := trace.StartSpan(ctx, "statemanager.CallWithGas")
defer span.End() defer span.End()
@ -114,6 +113,11 @@ func (sm *StateManager) CallWithGas(ctx context.Context, msg *types.Message, pri
return nil, xerrors.Errorf("computing tipset state: %w", err) return nil, xerrors.Errorf("computing tipset state: %w", err)
} }
state, err = sm.handleStateForks(ctx, state, ts.Height(), nil, ts)
if err != nil {
return nil, fmt.Errorf("failed to handle fork: %w", err)
}
r := store.NewChainRand(sm.cs, ts.Cids()) r := store.NewChainRand(sm.cs, ts.Cids())
if span.IsRecordingEvents() { if span.IsRecordingEvents() {

View File

@ -6,43 +6,108 @@ import (
"encoding/binary" "encoding/binary"
"math" "math"
multisig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig"
"github.com/filecoin-project/lotus/chain/actors/builtin/multisig"
"github.com/filecoin-project/lotus/chain/state"
"github.com/filecoin-project/specs-actors/actors/migration/nv3"
"github.com/ipfs/go-cid"
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/go-state-types/network"
"github.com/ipfs/go-cid"
cbor "github.com/ipfs/go-ipld-cbor"
"golang.org/x/xerrors"
builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" builtin0 "github.com/filecoin-project/specs-actors/actors/builtin"
init0 "github.com/filecoin-project/specs-actors/actors/builtin/init"
miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner"
multisig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig"
power0 "github.com/filecoin-project/specs-actors/actors/builtin/power" power0 "github.com/filecoin-project/specs-actors/actors/builtin/power"
adt0 "github.com/filecoin-project/specs-actors/actors/util/adt" adt0 "github.com/filecoin-project/specs-actors/actors/util/adt"
"github.com/filecoin-project/specs-actors/actors/migration/nv3"
m2 "github.com/filecoin-project/specs-actors/v2/actors/migration"
states2 "github.com/filecoin-project/specs-actors/v2/actors/states"
"github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/build"
"github.com/filecoin-project/lotus/chain/actors"
"github.com/filecoin-project/lotus/chain/actors/adt"
init_ "github.com/filecoin-project/lotus/chain/actors/builtin/init"
"github.com/filecoin-project/lotus/chain/actors/builtin/multisig"
"github.com/filecoin-project/lotus/chain/state"
"github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/types"
"github.com/filecoin-project/lotus/chain/vm" "github.com/filecoin-project/lotus/chain/vm"
cbor "github.com/ipfs/go-ipld-cbor"
"golang.org/x/xerrors"
) )
var ForksAtHeight = map[abi.ChainEpoch]func(context.Context, *StateManager, ExecCallback, cid.Cid, *types.TipSet) (cid.Cid, error){ type UpgradeFunc func(context.Context, *StateManager, ExecCallback, cid.Cid, *types.TipSet) (cid.Cid, error)
build.UpgradeBreezeHeight: UpgradeFaucetBurnRecovery,
build.UpgradeIgnitionHeight: UpgradeIgnition, type Upgrade struct {
build.UpgradeLiftoffHeight: UpgradeLiftoff, Height abi.ChainEpoch
Network network.Version
Migration UpgradeFunc
}
type UpgradeSchedule []Upgrade
func DefaultUpgradeSchedule() UpgradeSchedule {
var us UpgradeSchedule
for _, u := range []Upgrade{{
Height: build.UpgradeBreezeHeight,
Network: network.Version1,
Migration: UpgradeFaucetBurnRecovery,
}, {
Height: build.UpgradeSmokeHeight,
Network: network.Version2,
Migration: nil,
}, {
Height: build.UpgradeIgnitionHeight,
Network: network.Version3,
Migration: UpgradeIgnition,
}, {
Height: build.UpgradeActorsV2Height,
Network: network.Version4,
Migration: UpgradeActorsV2,
}, {
Height: build.UpgradeLiftoffHeight,
Network: network.Version4,
Migration: UpgradeLiftoff,
}} {
if u.Height < 0 {
// upgrade disabled
continue
}
us = append(us, u)
}
return us
}
func (us UpgradeSchedule) Validate() error {
// Make sure we're not trying to upgrade to version 0.
for _, u := range us {
if u.Network <= 0 {
return xerrors.Errorf("cannot upgrade to version <= 0: %d", u.Network)
}
}
// Make sure all the upgrades make sense.
for i := 1; i < len(us); i++ {
prev := &us[i-1]
curr := &us[i]
if !(prev.Network <= curr.Network) {
return xerrors.Errorf("cannot downgrade from version %d to version %d", prev.Network, curr.Network)
}
// Make sure the heights make sense.
if prev.Height < 0 {
// Previous upgrade was disabled.
continue
}
if !(prev.Height < curr.Height) {
return xerrors.Errorf("upgrade heights must be strictly increasing: upgrade %d was at height %d, followed by upgrade %d at height %d", i-1, prev.Height, i, curr.Height)
}
}
return nil
} }
func (sm *StateManager) handleStateForks(ctx context.Context, root cid.Cid, height abi.ChainEpoch, cb ExecCallback, ts *types.TipSet) (cid.Cid, error) { func (sm *StateManager) handleStateForks(ctx context.Context, root cid.Cid, height abi.ChainEpoch, cb ExecCallback, ts *types.TipSet) (cid.Cid, error) {
retCid := root retCid := root
var err error var err error
f, ok := ForksAtHeight[height] f, ok := sm.stateMigrations[height]
if ok { if ok {
retCid, err = f(ctx, sm, cb, root, ts) retCid, err = f(ctx, sm, cb, root, ts)
if err != nil { if err != nil {
@ -370,7 +435,13 @@ func UpgradeFaucetBurnRecovery(ctx context.Context, sm *StateManager, cb ExecCal
func UpgradeIgnition(ctx context.Context, sm *StateManager, cb ExecCallback, root cid.Cid, ts *types.TipSet) (cid.Cid, error) { func UpgradeIgnition(ctx context.Context, sm *StateManager, cb ExecCallback, root cid.Cid, ts *types.TipSet) (cid.Cid, error) {
store := sm.cs.Store(ctx) store := sm.cs.Store(ctx)
nst, err := nv3.MigrateStateTree(ctx, store, root, build.UpgradeIgnitionHeight) epoch := ts.Height() - 1
if build.UpgradeLiftoffHeight <= epoch {
return cid.Undef, xerrors.Errorf("liftoff height must be beyond ignition height")
}
nst, err := nv3.MigrateStateTree(ctx, store, root, epoch)
if err != nil { if err != nil {
return cid.Undef, xerrors.Errorf("migrating actors state: %w", err) return cid.Undef, xerrors.Errorf("migrating actors state: %w", err)
} }
@ -395,7 +466,7 @@ func UpgradeIgnition(ctx context.Context, sm *StateManager, cb ExecCallback, roo
return cid.Undef, xerrors.Errorf("second split address: %w", err) return cid.Undef, xerrors.Errorf("second split address: %w", err)
} }
err = resetGenesisMsigs(ctx, sm, store, tree) err = resetGenesisMsigs(ctx, sm, store, tree, build.UpgradeLiftoffHeight)
if err != nil { if err != nil {
return cid.Undef, xerrors.Errorf("resetting genesis msig start epochs: %w", err) return cid.Undef, xerrors.Errorf("resetting genesis msig start epochs: %w", err)
} }
@ -410,7 +481,7 @@ func UpgradeIgnition(ctx context.Context, sm *StateManager, cb ExecCallback, roo
return cid.Undef, xerrors.Errorf("splitting second msig: %w", err) return cid.Undef, xerrors.Errorf("splitting second msig: %w", err)
} }
err = nv3.CheckStateTree(ctx, store, nst, build.UpgradeIgnitionHeight, builtin0.TotalFilecoin) err = nv3.CheckStateTree(ctx, store, nst, epoch, builtin0.TotalFilecoin)
if err != nil { if err != nil {
return cid.Undef, xerrors.Errorf("sanity check after ignition upgrade failed: %w", err) return cid.Undef, xerrors.Errorf("sanity check after ignition upgrade failed: %w", err)
} }
@ -418,6 +489,58 @@ func UpgradeIgnition(ctx context.Context, sm *StateManager, cb ExecCallback, roo
return tree.Flush(ctx) return tree.Flush(ctx)
} }
func UpgradeActorsV2(ctx context.Context, sm *StateManager, cb ExecCallback, root cid.Cid, ts *types.TipSet) (cid.Cid, error) {
store := sm.cs.Store(ctx)
epoch := ts.Height() - 1
info, err := store.Put(ctx, new(types.StateInfo))
if err != nil {
return cid.Undef, xerrors.Errorf("failed to create new state info for actors v2: %w", err)
}
newHamtRoot, err := m2.MigrateStateTree(ctx, store, root, epoch, m2.DefaultConfig())
if err != nil {
return cid.Undef, xerrors.Errorf("upgrading to actors v2: %w", err)
}
newStateTree, err := states2.LoadTree(store, newHamtRoot)
if err != nil {
return cid.Undef, xerrors.Errorf("failed to load new state tree: %w", err)
}
// Check all state-tree invariants.
if msgs, err := states2.CheckStateInvariants(newStateTree, types.TotalFilecoinInt); err != nil {
return cid.Undef, xerrors.Errorf("failed to check new state tree: %w", err)
} else if !msgs.IsEmpty() {
// This error is going to be really nasty.
return cid.Undef, xerrors.Errorf("network upgrade failed: %v", msgs.Messages())
}
newRoot, err := store.Put(ctx, &types.StateRoot{
// TODO: ActorUpgrade: should be state-tree specific, not just the actors version.
Version: actors.Version2,
Actors: newHamtRoot,
Info: info,
})
if err != nil {
return cid.Undef, xerrors.Errorf("failed to persist new state root: %w", err)
}
// perform some basic sanity checks to make sure everything still works.
if newSm, err := state.LoadStateTree(store, newRoot); err != nil {
return cid.Undef, xerrors.Errorf("state tree sanity load failed: %w", err)
} else if newRoot2, err := newSm.Flush(ctx); err != nil {
return cid.Undef, xerrors.Errorf("state tree sanity flush failed: %w", err)
} else if newRoot2 != newRoot {
return cid.Undef, xerrors.Errorf("state-root mismatch: %s != %s", newRoot, newRoot2)
} else if _, err := newSm.GetActor(builtin0.InitActorAddr); err != nil {
return cid.Undef, xerrors.Errorf("failed to load init actor after upgrade: %w", err)
}
return newRoot, nil
}
func UpgradeLiftoff(ctx context.Context, sm *StateManager, cb ExecCallback, root cid.Cid, ts *types.TipSet) (cid.Cid, error) { func UpgradeLiftoff(ctx context.Context, sm *StateManager, cb ExecCallback, root cid.Cid, ts *types.TipSet) (cid.Cid, error) {
tree, err := sm.StateTree(root) tree, err := sm.StateTree(root)
if err != nil { if err != nil {
@ -432,20 +555,22 @@ func UpgradeLiftoff(ctx context.Context, sm *StateManager, cb ExecCallback, root
return tree.Flush(ctx) return tree.Flush(ctx)
} }
func setNetworkName(ctx context.Context, store adt0.Store, tree *state.StateTree, name string) error { func setNetworkName(ctx context.Context, store adt.Store, tree *state.StateTree, name string) error {
ia, err := tree.GetActor(builtin0.InitActorAddr) ia, err := tree.GetActor(builtin0.InitActorAddr)
if err != nil { if err != nil {
return xerrors.Errorf("getting init actor: %w", err) return xerrors.Errorf("getting init actor: %w", err)
} }
var initState init0.State initState, err := init_.Load(store, ia)
if err := store.Get(ctx, ia.Head, &initState); err != nil { if err != nil {
return xerrors.Errorf("reading init state: %w", err) return xerrors.Errorf("reading init state: %w", err)
} }
initState.NetworkName = name if err := initState.SetNetworkName(name); err != nil {
return xerrors.Errorf("setting network name: %w", err)
}
ia.Head, err = store.Put(ctx, &initState) ia.Head, err = store.Put(ctx, initState)
if err != nil { if err != nil {
return xerrors.Errorf("writing new init state: %w", err) return xerrors.Errorf("writing new init state: %w", err)
} }
@ -574,7 +699,7 @@ func makeKeyAddr(splitAddr address.Address, count uint64) (address.Address, erro
return addr, nil return addr, nil
} }
func resetGenesisMsigs(ctx context.Context, sm *StateManager, store adt0.Store, tree *state.StateTree) error { func resetGenesisMsigs(ctx context.Context, sm *StateManager, store adt0.Store, tree *state.StateTree, startEpoch abi.ChainEpoch) error {
gb, err := sm.cs.GetGenesis() gb, err := sm.cs.GetGenesis()
if err != nil { if err != nil {
return xerrors.Errorf("getting genesis block: %w", err) return xerrors.Errorf("getting genesis block: %w", err)
@ -603,7 +728,7 @@ func resetGenesisMsigs(ctx context.Context, sm *StateManager, store adt0.Store,
return xerrors.Errorf("reading multisig state: %w", err) return xerrors.Errorf("reading multisig state: %w", err)
} }
currState.StartEpoch = build.UpgradeLiftoffHeight currState.StartEpoch = startEpoch
currActor.Head, err = store.Put(ctx, &currState) currActor.Head, err = store.Put(ctx, &currState)
if err != nil { if err != nil {

View File

@ -8,6 +8,7 @@ import (
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/cbor"
"github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin"
init_ "github.com/filecoin-project/specs-actors/actors/builtin/init" init_ "github.com/filecoin-project/specs-actors/actors/builtin/init"
"github.com/filecoin-project/specs-actors/actors/runtime" "github.com/filecoin-project/specs-actors/actors/runtime"
@ -18,7 +19,6 @@ import (
lotusinit "github.com/filecoin-project/lotus/chain/actors/builtin/init" lotusinit "github.com/filecoin-project/lotus/chain/actors/builtin/init"
"github.com/filecoin-project/lotus/chain/actors/policy" "github.com/filecoin-project/lotus/chain/actors/policy"
"github.com/filecoin-project/lotus/chain/gen" "github.com/filecoin-project/lotus/chain/gen"
"github.com/filecoin-project/lotus/chain/stmgr"
. "github.com/filecoin-project/lotus/chain/stmgr" . "github.com/filecoin-project/lotus/chain/stmgr"
"github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/types"
"github.com/filecoin-project/lotus/chain/vm" "github.com/filecoin-project/lotus/chain/vm"
@ -26,7 +26,7 @@ import (
_ "github.com/filecoin-project/lotus/lib/sigs/secp" _ "github.com/filecoin-project/lotus/lib/sigs/secp"
"github.com/ipfs/go-cid" "github.com/ipfs/go-cid"
cbor "github.com/ipfs/go-ipld-cbor" ipldcbor "github.com/ipfs/go-ipld-cbor"
logging "github.com/ipfs/go-log" logging "github.com/ipfs/go-log"
cbg "github.com/whyrusleeping/cbor-gen" cbg "github.com/whyrusleeping/cbor-gen"
) )
@ -42,6 +42,10 @@ const testForkHeight = 40
type testActor struct { type testActor struct {
} }
// must use existing actor that an account is allowed to exec.
func (testActor) Code() cid.Cid { return builtin.PaymentChannelActorCodeID }
func (testActor) State() cbor.Er { return new(testActorState) }
type testActorState struct { type testActorState struct {
HasUpgraded uint64 HasUpgraded uint64
} }
@ -62,7 +66,7 @@ func (tas *testActorState) UnmarshalCBOR(r io.Reader) error {
return nil return nil
} }
func (ta *testActor) Exports() []interface{} { func (ta testActor) Exports() []interface{} {
return []interface{}{ return []interface{}{
1: ta.Constructor, 1: ta.Constructor,
2: ta.TestMethod, 2: ta.TestMethod,
@ -105,18 +109,19 @@ func TestForkHeightTriggers(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
sm := NewStateManager(cg.ChainStore())
inv := vm.NewInvoker()
// predicting the address here... may break if other assumptions change // predicting the address here... may break if other assumptions change
taddr, err := address.NewIDAddress(1002) taddr, err := address.NewIDAddress(1002)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
stmgr.ForksAtHeight[testForkHeight] = func(ctx context.Context, sm *StateManager, cb ExecCallback, root cid.Cid, ts *types.TipSet) (cid.Cid, error) { sm, err := NewStateManagerWithUpgradeSchedule(
cst := cbor.NewCborStore(sm.ChainStore().Blockstore()) cg.ChainStore(), UpgradeSchedule{{
Network: 1,
Height: testForkHeight,
Migration: func(ctx context.Context, sm *StateManager, cb ExecCallback,
root cid.Cid, ts *types.TipSet) (cid.Cid, error) {
cst := ipldcbor.NewCborStore(sm.ChainStore().Blockstore())
st, err := sm.StateTree(root) st, err := sm.StateTree(root)
if err != nil { if err != nil {
@ -147,9 +152,14 @@ func TestForkHeightTriggers(t *testing.T) {
} }
return st.Flush(ctx) return st.Flush(ctx)
}}})
if err != nil {
t.Fatal(err)
} }
inv.Register(builtin.PaymentChannelActorCodeID, &testActor{}, &testActorState{}) inv := vm.NewActorRegistry()
inv.Register(nil, testActor{})
sm.SetVMConstructor(func(ctx context.Context, vmopt *vm.VMOpts) (*vm.VM, error) { sm.SetVMConstructor(func(ctx context.Context, vmopt *vm.VMOpts) (*vm.VM, error) {
nvm, err := vm.NewVM(ctx, vmopt) nvm, err := vm.NewVM(ctx, vmopt)
if err != nil { if err != nil {
@ -163,7 +173,7 @@ func TestForkHeightTriggers(t *testing.T) {
var msgs []*types.SignedMessage var msgs []*types.SignedMessage
enc, err := actors.SerializeParams(&init_.ExecParams{CodeCID: builtin.PaymentChannelActorCodeID}) enc, err := actors.SerializeParams(&init_.ExecParams{CodeCID: (testActor{}).Code()})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@ -5,6 +5,8 @@ import (
"fmt" "fmt"
"sync" "sync"
"github.com/filecoin-project/lotus/chain/actors/builtin"
builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" builtin0 "github.com/filecoin-project/specs-actors/actors/builtin"
msig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig" msig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig"
@ -24,7 +26,6 @@ import (
"github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/build"
"github.com/filecoin-project/lotus/chain/actors" "github.com/filecoin-project/lotus/chain/actors"
"github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/filecoin-project/lotus/chain/actors/builtin"
"github.com/filecoin-project/lotus/chain/actors/builtin/market" "github.com/filecoin-project/lotus/chain/actors/builtin/market"
"github.com/filecoin-project/lotus/chain/actors/builtin/multisig" "github.com/filecoin-project/lotus/chain/actors/builtin/multisig"
"github.com/filecoin-project/lotus/chain/actors/builtin/paych" "github.com/filecoin-project/lotus/chain/actors/builtin/paych"
@ -38,9 +39,21 @@ import (
var log = logging.Logger("statemgr") var log = logging.Logger("statemgr")
type versionSpec struct {
networkVersion network.Version
atOrBelow abi.ChainEpoch
}
type StateManager struct { type StateManager struct {
cs *store.ChainStore cs *store.ChainStore
// Determines the network version at any given epoch.
networkVersions []versionSpec
latestVersion network.Version
// Maps chain epochs to upgrade functions.
stateMigrations map[abi.ChainEpoch]UpgradeFunc
stCache map[string][]cid.Cid stCache map[string][]cid.Cid
compWait map[string]chan struct{} compWait map[string]chan struct{}
stlk sync.Mutex stlk sync.Mutex
@ -51,12 +64,49 @@ type StateManager struct {
} }
func NewStateManager(cs *store.ChainStore) *StateManager { func NewStateManager(cs *store.ChainStore) *StateManager {
sm, err := NewStateManagerWithUpgradeSchedule(cs, DefaultUpgradeSchedule())
if err != nil {
panic(fmt.Sprintf("default upgrade schedule is invalid: %s", err))
}
return sm
}
func NewStateManagerWithUpgradeSchedule(cs *store.ChainStore, us UpgradeSchedule) (*StateManager, error) {
// If we have upgrades, make sure they're in-order and make sense.
if err := us.Validate(); err != nil {
return nil, err
}
stateMigrations := make(map[abi.ChainEpoch]UpgradeFunc, len(us))
var networkVersions []versionSpec
lastVersion := network.Version0
if len(us) > 0 {
// If we have any upgrades, process them and create a version
// schedule.
for _, upgrade := range us {
if upgrade.Migration != nil {
stateMigrations[upgrade.Height] = upgrade.Migration
}
networkVersions = append(networkVersions, versionSpec{
networkVersion: lastVersion,
atOrBelow: upgrade.Height,
})
lastVersion = upgrade.Network
}
} else {
// Otherwise, go directly to the latest version.
lastVersion = build.NewestNetworkVersion
}
return &StateManager{ return &StateManager{
networkVersions: networkVersions,
latestVersion: lastVersion,
stateMigrations: stateMigrations,
newVM: vm.NewVM, newVM: vm.NewVM,
cs: cs, cs: cs,
stCache: make(map[string][]cid.Cid), stCache: make(map[string][]cid.Cid),
compWait: make(map[string]chan struct{}), compWait: make(map[string]chan struct{}),
} }, nil
} }
func cidsToKey(cids []cid.Cid) string { func cidsToKey(cids []cid.Cid) string {
@ -279,7 +329,7 @@ func (sm *StateManager) ApplyBlocks(ctx context.Context, parentEpoch abi.ChainEp
sysAct, actErr := vmi.StateTree().GetActor(builtin0.SystemActorAddr) sysAct, actErr := vmi.StateTree().GetActor(builtin0.SystemActorAddr)
if actErr != nil { if actErr != nil {
return cid.Undef, cid.Undef, xerrors.Errorf("failed to get system actor: %w", err) return cid.Undef, cid.Undef, xerrors.Errorf("failed to get system actor: %w", actErr)
} }
rwMsg := &types.Message{ rwMsg := &types.Message{
@ -295,7 +345,7 @@ func (sm *StateManager) ApplyBlocks(ctx context.Context, parentEpoch abi.ChainEp
} }
ret, actErr := vmi.ApplyImplicitMessage(ctx, rwMsg) ret, actErr := vmi.ApplyImplicitMessage(ctx, rwMsg)
if actErr != nil { if actErr != nil {
return cid.Undef, cid.Undef, xerrors.Errorf("failed to apply reward message for miner %s: %w", b.Miner, err) return cid.Undef, cid.Undef, xerrors.Errorf("failed to apply reward message for miner %s: %w", b.Miner, actErr)
} }
if cb != nil { if cb != nil {
if err := cb(rwMsg.Cid(), rwMsg, ret); err != nil { if err := cb(rwMsg.Cid(), rwMsg, ret); err != nil {
@ -313,7 +363,7 @@ func (sm *StateManager) ApplyBlocks(ctx context.Context, parentEpoch abi.ChainEp
} }
// XXX: Is the height correct? Or should it be epoch-1? // XXX: Is the height correct? Or should it be epoch-1?
rectarr, err := adt.NewArray(sm.cs.Store(ctx), builtin.VersionForNetwork(sm.GetNtwkVersion(ctx, epoch))) rectarr, err := adt.NewArray(sm.cs.Store(ctx), actors.VersionForNetwork(sm.GetNtwkVersion(ctx, epoch)))
if err != nil { if err != nil {
return cid.Undef, cid.Undef, xerrors.Errorf("failed to create receipts amt: %w", err) return cid.Undef, cid.Undef, xerrors.Errorf("failed to create receipts amt: %w", err)
} }
@ -859,7 +909,7 @@ func (sm *StateManager) setupGenesisActors(ctx context.Context) error {
totalsByEpoch := make(map[abi.ChainEpoch]abi.TokenAmount) totalsByEpoch := make(map[abi.ChainEpoch]abi.TokenAmount)
err = sTree.ForEach(func(kaddr address.Address, act *types.Actor) error { err = sTree.ForEach(func(kaddr address.Address, act *types.Actor) error {
if act.IsMultisigActor() { if builtin.IsMultisigActor(act.Code) {
s, err := multisig.Load(sm.cs.Store(ctx), act) s, err := multisig.Load(sm.cs.Store(ctx), act)
if err != nil { if err != nil {
return err return err
@ -891,7 +941,7 @@ func (sm *StateManager) setupGenesisActors(ctx context.Context) error {
totalsByEpoch[ud] = ib totalsByEpoch[ud] = ib
} }
} else if act.IsAccountActor() { } else if builtin.IsAccountActor(act.Code) {
// should exclude burnt funds actor and "remainder account actor" // should exclude burnt funds actor and "remainder account actor"
// should only ever be "faucet" accounts in testnets // should only ever be "faucet" accounts in testnets
if kaddr == builtin0.BurntFundsActorAddr { if kaddr == builtin0.BurntFundsActorAddr {
@ -1258,25 +1308,14 @@ func (sm *StateManager) GetCirculatingSupply(ctx context.Context, height abi.Cha
} }
func (sm *StateManager) GetNtwkVersion(ctx context.Context, height abi.ChainEpoch) network.Version { func (sm *StateManager) GetNtwkVersion(ctx context.Context, height abi.ChainEpoch) network.Version {
// TODO: move hard fork epoch checks to a schedule defined in build/ // The epochs here are the _last_ epoch for every version, or -1 if the
// version is disabled.
if build.UseNewestNetwork() { for _, spec := range sm.networkVersions {
return build.NewestNetworkVersion if height <= spec.atOrBelow {
return spec.networkVersion
} }
if height <= build.UpgradeBreezeHeight {
return network.Version0
} }
return sm.latestVersion
if height <= build.UpgradeSmokeHeight {
return network.Version1
}
if height <= build.UpgradeIgnitionHeight {
return network.Version2
}
return build.NewestNetworkVersion
} }
func (sm *StateManager) GetPaychState(ctx context.Context, addr address.Address, ts *types.TipSet) (*types.Actor, paych.State, error) { func (sm *StateManager) GetPaychState(ctx context.Context, addr address.Address, ts *types.TipSet) (*types.Actor, paych.State, error) {

View File

@ -17,19 +17,12 @@ import (
"github.com/filecoin-project/go-bitfield" "github.com/filecoin-project/go-bitfield"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/go-state-types/crypto"
"github.com/filecoin-project/go-state-types/rt"
builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" builtin0 "github.com/filecoin-project/specs-actors/actors/builtin"
account0 "github.com/filecoin-project/specs-actors/actors/builtin/account" exported0 "github.com/filecoin-project/specs-actors/actors/builtin/exported"
cron0 "github.com/filecoin-project/specs-actors/actors/builtin/cron"
init0 "github.com/filecoin-project/specs-actors/actors/builtin/init"
market0 "github.com/filecoin-project/specs-actors/actors/builtin/market"
miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner"
msig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig"
paych0 "github.com/filecoin-project/specs-actors/actors/builtin/paych"
power0 "github.com/filecoin-project/specs-actors/actors/builtin/power"
reward0 "github.com/filecoin-project/specs-actors/actors/builtin/reward"
verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg"
proof0 "github.com/filecoin-project/specs-actors/actors/runtime/proof" proof0 "github.com/filecoin-project/specs-actors/actors/runtime/proof"
exported2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/exported"
"github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/api"
"github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/build"
@ -534,42 +527,23 @@ type MethodMeta struct {
var MethodsMap = map[cid.Cid]map[abi.MethodNum]MethodMeta{} var MethodsMap = map[cid.Cid]map[abi.MethodNum]MethodMeta{}
func init() { func init() {
cidToMethods := map[cid.Cid][2]interface{}{ // TODO: combine with the runtime actor registry.
// builtin.SystemActorCodeID: {builtin.MethodsSystem, system.Actor{} }- apparently it doesn't have methods var actors []rt.VMActor
builtin0.InitActorCodeID: {builtin0.MethodsInit, init0.Actor{}}, actors = append(actors, exported0.BuiltinActors()...)
builtin0.CronActorCodeID: {builtin0.MethodsCron, cron0.Actor{}}, actors = append(actors, exported2.BuiltinActors()...)
builtin0.AccountActorCodeID: {builtin0.MethodsAccount, account0.Actor{}},
builtin0.StoragePowerActorCodeID: {builtin0.MethodsPower, power0.Actor{}},
builtin0.StorageMinerActorCodeID: {builtin0.MethodsMiner, miner0.Actor{}},
builtin0.StorageMarketActorCodeID: {builtin0.MethodsMarket, market0.Actor{}},
builtin0.PaymentChannelActorCodeID: {builtin0.MethodsPaych, paych0.Actor{}},
builtin0.MultisigActorCodeID: {builtin0.MethodsMultisig, msig0.Actor{}},
builtin0.RewardActorCodeID: {builtin0.MethodsReward, reward0.Actor{}},
builtin0.VerifiedRegistryActorCodeID: {builtin0.MethodsVerifiedRegistry, verifreg0.Actor{}},
}
for c, m := range cidToMethods { for _, actor := range actors {
exports := m[1].(vm.Invokee).Exports() exports := actor.Exports()
methods := make(map[abi.MethodNum]MethodMeta, len(exports)) methods := make(map[abi.MethodNum]MethodMeta, len(exports))
// Explicitly add send, it's special. // Explicitly add send, it's special.
// Note that builtin2.MethodSend = builtin0.MethodSend = 0.
methods[builtin0.MethodSend] = MethodMeta{ methods[builtin0.MethodSend] = MethodMeta{
Name: "Send", Name: "Send",
Params: reflect.TypeOf(new(abi.EmptyValue)), Params: reflect.TypeOf(new(abi.EmptyValue)),
Ret: reflect.TypeOf(new(abi.EmptyValue)), Ret: reflect.TypeOf(new(abi.EmptyValue)),
} }
// Learn method names from the builtin.Methods* structs.
rv := reflect.ValueOf(m[0])
rt := rv.Type()
nf := rt.NumField()
methodToName := make([]string, len(exports))
for i := 0; i < nf; i++ {
name := rt.Field(i).Name
number := rv.Field(i).Interface().(abi.MethodNum)
methodToName[number] = name
}
// Iterate over exported methods. Some of these _may_ be nil and // Iterate over exported methods. Some of these _may_ be nil and
// must be skipped. // must be skipped.
for number, export := range exports { for number, export := range exports {
@ -580,22 +554,19 @@ func init() {
ev := reflect.ValueOf(export) ev := reflect.ValueOf(export)
et := ev.Type() et := ev.Type()
// Make sure the method name is correct. // Extract the method names using reflection. These
// This is just a nice sanity check. // method names always match the field names in the
// `builtin.Method*` structs (tested in the specs-actors
// tests).
fnName := runtime.FuncForPC(ev.Pointer()).Name() fnName := runtime.FuncForPC(ev.Pointer()).Name()
fnName = strings.TrimSuffix(fnName[strings.LastIndexByte(fnName, '.')+1:], "-fm") fnName = strings.TrimSuffix(fnName[strings.LastIndexByte(fnName, '.')+1:], "-fm")
mName := methodToName[number]
if mName != fnName {
panic(fmt.Sprintf(
"actor method name is %s but exported method name is %s",
fnName, mName,
))
}
switch abi.MethodNum(number) { switch abi.MethodNum(number) {
case builtin0.MethodSend: case builtin0.MethodSend:
// Note that builtin2.MethodSend = builtin0.MethodSend = 0.
panic("method 0 is reserved for Send") panic("method 0 is reserved for Send")
case builtin0.MethodConstructor: case builtin0.MethodConstructor:
// Note that builtin2.MethodConstructor = builtin0.MethodConstructor = 1.
if fnName != "Constructor" { if fnName != "Constructor" {
panic("method 1 is reserved for Constructor") panic("method 1 is reserved for Constructor")
} }
@ -607,7 +578,7 @@ func init() {
Ret: et.Out(0), Ret: et.Out(0),
} }
} }
MethodsMap[c] = methods MethodsMap[actor.Code()] = methods
} }
} }

View File

@ -46,7 +46,7 @@ func ComputeNextBaseFee(baseFee types.BigInt, gasLimitUsed int64, noOfBlocks int
} }
func (cs *ChainStore) ComputeBaseFee(ctx context.Context, ts *types.TipSet) (abi.TokenAmount, error) { func (cs *ChainStore) ComputeBaseFee(ctx context.Context, ts *types.TipSet) (abi.TokenAmount, error) {
if ts.Height() > build.UpgradeBreezeHeight && ts.Height() < build.UpgradeBreezeHeight+build.BreezeGasTampingDuration { if build.UpgradeBreezeHeight >= 0 && ts.Height() > build.UpgradeBreezeHeight && ts.Height() < build.UpgradeBreezeHeight+build.BreezeGasTampingDuration {
return abi.NewTokenAmount(100), nil return abi.NewTokenAmount(100), nil
} }

View File

@ -14,21 +14,24 @@ func TestBaseFee(t *testing.T) {
basefee uint64 basefee uint64
limitUsed int64 limitUsed int64
noOfBlocks int noOfBlocks int
output uint64 preSmoke, postSmoke uint64
}{ }{
{100e6, 0, 1, 87.5e6}, {100e6, 0, 1, 87.5e6, 87.5e6},
{100e6, 0, 5, 87.5e6}, {100e6, 0, 5, 87.5e6, 87.5e6},
{100e6, build.BlockGasTarget, 1, 103.125e6}, {100e6, build.BlockGasTarget, 1, 103.125e6, 100e6},
{100e6, build.BlockGasTarget * 2, 2, 103.125e6}, {100e6, build.BlockGasTarget * 2, 2, 103.125e6, 100e6},
{100e6, build.BlockGasLimit * 2, 2, 112.5e6}, {100e6, build.BlockGasLimit * 2, 2, 112.5e6, 112.5e6},
{100e6, build.BlockGasLimit * 1.5, 2, 110937500}, {100e6, build.BlockGasLimit * 1.5, 2, 110937500, 106.250e6},
} }
for _, test := range tests { for _, test := range tests {
test := test test := test
t.Run(fmt.Sprintf("%v", test), func(t *testing.T) { t.Run(fmt.Sprintf("%v", test), func(t *testing.T) {
output := ComputeNextBaseFee(types.NewInt(test.basefee), test.limitUsed, test.noOfBlocks, 0) preSmoke := ComputeNextBaseFee(types.NewInt(test.basefee), test.limitUsed, test.noOfBlocks, build.UpgradeSmokeHeight-1)
assert.Equal(t, fmt.Sprintf("%d", test.output), output.String()) assert.Equal(t, fmt.Sprintf("%d", test.preSmoke), preSmoke.String())
postSmoke := ComputeNextBaseFee(types.NewInt(test.basefee), test.limitUsed, test.noOfBlocks, build.UpgradeSmokeHeight+1)
assert.Equal(t, fmt.Sprintf("%d", test.postSmoke), postSmoke.String())
}) })
} }
} }

View File

@ -17,11 +17,13 @@ import (
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin"
"github.com/filecoin-project/specs-actors/actors/util/adt" adt0 "github.com/filecoin-project/specs-actors/actors/util/adt"
"github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/api"
"github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/build"
"github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/filecoin-project/lotus/chain/vm" "github.com/filecoin-project/lotus/chain/vm"
"github.com/filecoin-project/lotus/journal" "github.com/filecoin-project/lotus/journal"
bstore "github.com/filecoin-project/lotus/lib/blockstore" bstore "github.com/filecoin-project/lotus/lib/blockstore"
@ -757,7 +759,8 @@ func (cs *ChainStore) GetSignedMessage(c cid.Cid) (*types.SignedMessage, error)
func (cs *ChainStore) readAMTCids(root cid.Cid) ([]cid.Cid, error) { func (cs *ChainStore) readAMTCids(root cid.Cid) ([]cid.Cid, error) {
ctx := context.TODO() ctx := context.TODO()
a, err := adt.AsArray(cs.Store(ctx), root) // block headers use adt0, for now.
a, err := adt0.AsArray(cs.Store(ctx), root)
if err != nil { if err != nil {
return nil, xerrors.Errorf("amt load: %w", err) return nil, xerrors.Errorf("amt load: %w", err)
} }
@ -950,7 +953,8 @@ func (cs *ChainStore) MessagesForBlock(b *types.BlockHeader) ([]*types.Message,
func (cs *ChainStore) GetParentReceipt(b *types.BlockHeader, i int) (*types.MessageReceipt, error) { func (cs *ChainStore) GetParentReceipt(b *types.BlockHeader, i int) (*types.MessageReceipt, error) {
ctx := context.TODO() ctx := context.TODO()
a, err := adt.AsArray(cs.Store(ctx), b.ParentMessageReceipts) // block headers use adt0, for now.
a, err := adt0.AsArray(cs.Store(ctx), b.ParentMessageReceipts)
if err != nil { if err != nil {
return nil, xerrors.Errorf("amt load: %w", err) return nil, xerrors.Errorf("amt load: %w", err)
} }

View File

@ -10,7 +10,6 @@ import (
"golang.org/x/xerrors" "golang.org/x/xerrors"
address "github.com/filecoin-project/go-address" address "github.com/filecoin-project/go-address"
"github.com/filecoin-project/specs-actors/actors/util/adt"
lru "github.com/hashicorp/golang-lru" lru "github.com/hashicorp/golang-lru"
blocks "github.com/ipfs/go-block-format" blocks "github.com/ipfs/go-block-format"
bserv "github.com/ipfs/go-blockservice" bserv "github.com/ipfs/go-blockservice"
@ -24,6 +23,8 @@ import (
"go.opencensus.io/stats" "go.opencensus.io/stats"
"go.opencensus.io/tag" "go.opencensus.io/tag"
adt0 "github.com/filecoin-project/specs-actors/actors/util/adt"
"github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/build"
"github.com/filecoin-project/lotus/chain" "github.com/filecoin-project/lotus/chain"
"github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/actors/builtin/miner"
@ -384,9 +385,10 @@ func (bv *BlockValidator) isChainNearSynced() bool {
func (bv *BlockValidator) validateMsgMeta(ctx context.Context, msg *types.BlockMsg) error { func (bv *BlockValidator) validateMsgMeta(ctx context.Context, msg *types.BlockMsg) error {
// TODO there has to be a simpler way to do this without the blockstore dance // TODO there has to be a simpler way to do this without the blockstore dance
store := adt.WrapStore(ctx, cbor.NewCborStore(blockstore.NewTemporary())) // block headers use adt0
bmArr := adt.MakeEmptyArray(store) store := adt0.WrapStore(ctx, cbor.NewCborStore(blockstore.NewTemporary()))
smArr := adt.MakeEmptyArray(store) bmArr := adt0.MakeEmptyArray(store)
smArr := adt0.MakeEmptyArray(store)
for i, m := range msg.BlsMessages { for i, m := range msg.BlsMessages {
c := cbg.CborCid(m) c := cbg.CborCid(m)

View File

@ -11,6 +11,8 @@ import (
"sync" "sync"
"time" "time"
"github.com/filecoin-project/lotus/chain/actors/builtin"
"github.com/filecoin-project/lotus/node/modules/dtypes" "github.com/filecoin-project/lotus/node/modules/dtypes"
"github.com/filecoin-project/specs-actors/actors/runtime/proof" "github.com/filecoin-project/specs-actors/actors/runtime/proof"
@ -33,9 +35,10 @@ import (
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/go-state-types/crypto"
"github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper" "github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper"
"github.com/filecoin-project/specs-actors/actors/util/adt"
blst "github.com/supranational/blst/bindings/go" blst "github.com/supranational/blst/bindings/go"
adt0 "github.com/filecoin-project/specs-actors/actors/util/adt"
"github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/api"
"github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/build"
"github.com/filecoin-project/lotus/chain/actors/builtin/power" "github.com/filecoin-project/lotus/chain/actors/builtin/power"
@ -455,9 +458,10 @@ func zipTipSetAndMessages(bs cbor.IpldStore, ts *types.TipSet, allbmsgs []*types
// computeMsgMeta computes the root CID of the combined arrays of message CIDs // computeMsgMeta computes the root CID of the combined arrays of message CIDs
// of both types (BLS and Secpk). // of both types (BLS and Secpk).
func computeMsgMeta(bs cbor.IpldStore, bmsgCids, smsgCids []cid.Cid) (cid.Cid, error) { func computeMsgMeta(bs cbor.IpldStore, bmsgCids, smsgCids []cid.Cid) (cid.Cid, error) {
store := adt.WrapStore(context.TODO(), bs) // block headers use adt0
bmArr := adt.MakeEmptyArray(store) store := adt0.WrapStore(context.TODO(), bs)
smArr := adt.MakeEmptyArray(store) bmArr := adt0.MakeEmptyArray(store)
smArr := adt0.MakeEmptyArray(store)
for i, m := range bmsgCids { for i, m := range bmsgCids {
c := cbg.CborCid(m) c := cbg.CborCid(m)
@ -1087,7 +1091,7 @@ func (syncer *Syncer) checkBlockMessages(ctx context.Context, b *types.FullBlock
return xerrors.Errorf("failed to get actor: %w", err) return xerrors.Errorf("failed to get actor: %w", err)
} }
if !act.IsAccountActor() { if !builtin.IsAccountActor(act.Code) {
return xerrors.New("Sender must be an account actor") return xerrors.New("Sender must be an account actor")
} }
nonces[m.From] = act.Nonce nonces[m.From] = act.Nonce
@ -1101,9 +1105,9 @@ func (syncer *Syncer) checkBlockMessages(ctx context.Context, b *types.FullBlock
return nil return nil
} }
store := adt.WrapStore(ctx, cst) store := adt0.WrapStore(ctx, cst)
bmArr := adt.MakeEmptyArray(store) bmArr := adt0.MakeEmptyArray(store)
for i, m := range b.BlsMessages { for i, m := range b.BlsMessages {
if err := checkMsg(m); err != nil { if err := checkMsg(m); err != nil {
return xerrors.Errorf("block had invalid bls message at index %d: %w", i, err) return xerrors.Errorf("block had invalid bls message at index %d: %w", i, err)
@ -1115,7 +1119,7 @@ func (syncer *Syncer) checkBlockMessages(ctx context.Context, b *types.FullBlock
} }
} }
smArr := adt.MakeEmptyArray(store) smArr := adt0.MakeEmptyArray(store)
for i, m := range b.SecpkMessages { for i, m := range b.SecpkMessages {
if err := checkMsg(m); err != nil { if err := checkMsg(m); err != nil {
return xerrors.Errorf("block had invalid secpk message at index %d: %w", i, err) return xerrors.Errorf("block had invalid secpk message at index %d: %w", i, err)

View File

@ -4,8 +4,6 @@ import (
"errors" "errors"
"github.com/ipfs/go-cid" "github.com/ipfs/go-cid"
builtin0 "github.com/filecoin-project/specs-actors/actors/builtin"
) )
var ErrActorNotFound = errors.New("actor not found") var ErrActorNotFound = errors.New("actor not found")
@ -17,19 +15,3 @@ type Actor struct {
Nonce uint64 Nonce uint64
Balance BigInt Balance BigInt
} }
func (a *Actor) IsAccountActor() bool {
return a.Code == builtin0.AccountActorCodeID
}
func (a *Actor) IsStorageMinerActor() bool {
return a.Code == builtin0.StorageMinerActorCodeID
}
func (a *Actor) IsMultisigActor() bool {
return a.Code == builtin0.MultisigActorCodeID
}
func (a *Actor) IsPaymentChannelActor() bool {
return a.Code == builtin0.PaymentChannelActorCodeID
}

View File

@ -1,22 +0,0 @@
package types
import (
"encoding/base64"
"github.com/filecoin-project/specs-actors/actors/builtin/paych"
cbor "github.com/ipfs/go-ipld-cbor"
)
func DecodeSignedVoucher(s string) (*paych.SignedVoucher, error) {
data, err := base64.RawURLEncoding.DecodeString(s)
if err != nil {
return nil, err
}
var sv paych.SignedVoucher
if err := cbor.DecodeInto(data, &sv); err != nil {
return nil, err
}
return &sv, nil
}

View File

@ -6,28 +6,25 @@ import (
"math/rand" "math/rand"
"os" "os"
power0 "github.com/filecoin-project/specs-actors/actors/builtin/power"
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"golang.org/x/xerrors" "golang.org/x/xerrors"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/go-state-types/crypto"
"github.com/filecoin-project/lotus/chain/actors/policy"
"github.com/filecoin-project/lotus/chain/gen" "github.com/filecoin-project/lotus/chain/gen"
"github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/types"
"github.com/filecoin-project/lotus/chain/types/mock" "github.com/filecoin-project/lotus/chain/types/mock"
"github.com/filecoin-project/lotus/chain/vectors" "github.com/filecoin-project/lotus/chain/vectors"
"github.com/filecoin-project/lotus/chain/wallet" "github.com/filecoin-project/lotus/chain/wallet"
verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg"
_ "github.com/filecoin-project/lotus/lib/sigs/bls" _ "github.com/filecoin-project/lotus/lib/sigs/bls"
_ "github.com/filecoin-project/lotus/lib/sigs/secp" _ "github.com/filecoin-project/lotus/lib/sigs/secp"
) )
func init() { func init() {
verifreg0.MinVerifiedDealSize = big.NewInt(2048) policy.SetMinVerifiedDealSize(abi.NewStoragePower(2048))
power0.ConsensusMinerMinPower = big.NewInt(2048) policy.SetConsensusMinerMinPower(abi.NewStoragePower(2048))
} }
func MakeHeaderVectors() []vectors.HeaderVector { func MakeHeaderVectors() []vectors.HeaderVector {

View File

@ -9,7 +9,6 @@ import (
addr "github.com/filecoin-project/go-address" addr "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/go-state-types/crypto"
"github.com/filecoin-project/specs-actors/actors/runtime"
vmr "github.com/filecoin-project/specs-actors/actors/runtime" vmr "github.com/filecoin-project/specs-actors/actors/runtime"
"github.com/ipfs/go-cid" "github.com/ipfs/go-cid"
) )
@ -210,7 +209,7 @@ func (ps pricedSyscalls) VerifyPoSt(vi proof.WindowPoStVerifyInfo) error {
// the "parent grinding fault", in which case it must be the sibling of h1 (same parent tipset) and one of the // the "parent grinding fault", in which case it must be the sibling of h1 (same parent tipset) and one of the
// blocks in the parent of h2 (i.e. h2's grandparent). // blocks in the parent of h2 (i.e. h2's grandparent).
// Returns nil and an error if the headers don't prove a fault. // Returns nil and an error if the headers don't prove a fault.
func (ps pricedSyscalls) VerifyConsensusFault(h1 []byte, h2 []byte, extra []byte) (*runtime.ConsensusFault, error) { func (ps pricedSyscalls) VerifyConsensusFault(h1 []byte, h2 []byte, extra []byte) (*vmr.ConsensusFault, error) {
ps.chargeGas(ps.pl.OnVerifyConsensusFault()) ps.chargeGas(ps.pl.OnVerifyConsensusFault())
defer ps.chargeGas(gasOnActorExec) defer ps.chargeGas(gasOnActorExec)

View File

@ -8,7 +8,7 @@ import (
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/go-state-types/crypto"
"github.com/filecoin-project/specs-actors/actors/builtin" builtin0 "github.com/filecoin-project/specs-actors/actors/builtin"
) )
type scalingCost struct { type scalingCost struct {
@ -112,14 +112,14 @@ func (pl *pricelistV0) OnMethodInvocation(value abi.TokenAmount, methodNum abi.M
if big.Cmp(value, abi.NewTokenAmount(0)) != 0 { if big.Cmp(value, abi.NewTokenAmount(0)) != 0 {
ret += pl.sendTransferFunds ret += pl.sendTransferFunds
if methodNum == builtin.MethodSend { if methodNum == builtin0.MethodSend {
// transfer only // transfer only
ret += pl.sendTransferOnlyPremium ret += pl.sendTransferOnlyPremium
} }
extra += "t" extra += "t"
} }
if methodNum != builtin.MethodSend { if methodNum != builtin0.MethodSend {
extra += "i" extra += "i"
// running actors is cheaper becase we hand over to actors // running actors is cheaper becase we hand over to actors
ret += pl.sendInvokeMethod ret += pl.sendInvokeMethod

View File

@ -6,91 +6,126 @@ import (
"fmt" "fmt"
"reflect" "reflect"
"github.com/filecoin-project/lotus/chain/actors/builtin"
"github.com/ipfs/go-cid" "github.com/ipfs/go-cid"
cbg "github.com/whyrusleeping/cbor-gen" cbg "github.com/whyrusleeping/cbor-gen"
"golang.org/x/xerrors" "golang.org/x/xerrors"
builtin0 "github.com/filecoin-project/specs-actors/actors/builtin" exported0 "github.com/filecoin-project/specs-actors/actors/builtin/exported"
account0 "github.com/filecoin-project/specs-actors/actors/builtin/account" exported2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/exported"
cron0 "github.com/filecoin-project/specs-actors/actors/builtin/cron" vmr "github.com/filecoin-project/specs-actors/v2/actors/runtime"
init0 "github.com/filecoin-project/specs-actors/actors/builtin/init"
market0 "github.com/filecoin-project/specs-actors/actors/builtin/market"
miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner"
msig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig"
paych0 "github.com/filecoin-project/specs-actors/actors/builtin/paych"
power0 "github.com/filecoin-project/specs-actors/actors/builtin/power"
reward0 "github.com/filecoin-project/specs-actors/actors/builtin/reward"
system0 "github.com/filecoin-project/specs-actors/actors/builtin/system"
verifreg0 "github.com/filecoin-project/specs-actors/actors/builtin/verifreg"
vmr "github.com/filecoin-project/specs-actors/actors/runtime"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/exitcode" "github.com/filecoin-project/go-state-types/exitcode"
rtt "github.com/filecoin-project/go-state-types/rt"
"github.com/filecoin-project/lotus/chain/actors"
"github.com/filecoin-project/lotus/chain/actors/aerrors" "github.com/filecoin-project/lotus/chain/actors/aerrors"
"github.com/filecoin-project/lotus/chain/types"
) )
type Invoker struct { type ActorRegistry struct {
builtInCode map[cid.Cid]nativeCode actors map[cid.Cid]*actorInfo
builtInState map[cid.Cid]reflect.Type }
// An ActorPredicate returns an error if the given actor is not valid for the given runtime environment (e.g., chain height, version, etc.).
type ActorPredicate func(vmr.Runtime, rtt.VMActor) error
func ActorsVersionPredicate(ver actors.Version) ActorPredicate {
return func(rt vmr.Runtime, v rtt.VMActor) error {
nver := actors.VersionForNetwork(rt.NetworkVersion())
if nver != ver {
return xerrors.Errorf("actor %s is a version %d actor; chain only supports actor version %d at height %d", v.Code(), ver, nver, rt.CurrEpoch())
}
return nil
}
} }
type invokeFunc func(rt vmr.Runtime, params []byte) ([]byte, aerrors.ActorError) type invokeFunc func(rt vmr.Runtime, params []byte) ([]byte, aerrors.ActorError)
type nativeCode []invokeFunc type nativeCode []invokeFunc
func NewInvoker() *Invoker { type actorInfo struct {
inv := &Invoker{ methods nativeCode
builtInCode: make(map[cid.Cid]nativeCode), vmActor rtt.VMActor
builtInState: make(map[cid.Cid]reflect.Type), // TODO: consider making this a network version range?
} predicate ActorPredicate
}
func NewActorRegistry() *ActorRegistry {
inv := &ActorRegistry{actors: make(map[cid.Cid]*actorInfo)}
// TODO: define all these properties on the actors themselves, in specs-actors.
// add builtInCode using: register(cid, singleton) // add builtInCode using: register(cid, singleton)
// NETUPGRADE: register code IDs for v2, etc. inv.Register(ActorsVersionPredicate(actors.Version0), exported0.BuiltinActors()...)
inv.Register(builtin0.SystemActorCodeID, system0.Actor{}, abi.EmptyValue{}) inv.Register(ActorsVersionPredicate(actors.Version2), exported2.BuiltinActors()...)
inv.Register(builtin0.InitActorCodeID, init0.Actor{}, init0.State{})
inv.Register(builtin0.RewardActorCodeID, reward0.Actor{}, reward0.State{})
inv.Register(builtin0.CronActorCodeID, cron0.Actor{}, cron0.State{})
inv.Register(builtin0.StoragePowerActorCodeID, power0.Actor{}, power0.State{})
inv.Register(builtin0.StorageMarketActorCodeID, market0.Actor{}, market0.State{})
inv.Register(builtin0.StorageMinerActorCodeID, miner0.Actor{}, miner0.State{})
inv.Register(builtin0.MultisigActorCodeID, msig0.Actor{}, msig0.State{})
inv.Register(builtin0.PaymentChannelActorCodeID, paych0.Actor{}, paych0.State{})
inv.Register(builtin0.VerifiedRegistryActorCodeID, verifreg0.Actor{}, verifreg0.State{})
inv.Register(builtin0.AccountActorCodeID, account0.Actor{}, account0.State{})
return inv return inv
} }
func (inv *Invoker) Invoke(codeCid cid.Cid, rt vmr.Runtime, method abi.MethodNum, params []byte) ([]byte, aerrors.ActorError) { func (ar *ActorRegistry) Invoke(codeCid cid.Cid, rt vmr.Runtime, method abi.MethodNum, params []byte) ([]byte, aerrors.ActorError) {
act, ok := ar.actors[codeCid]
code, ok := inv.builtInCode[codeCid]
if !ok { if !ok {
log.Errorf("no code for actor %s (Addr: %s)", codeCid, rt.Receiver()) log.Errorf("no code for actor %s (Addr: %s)", codeCid, rt.Receiver())
return nil, aerrors.Newf(exitcode.SysErrorIllegalActor, "no code for actor %s(%d)(%s)", codeCid, method, hex.EncodeToString(params)) return nil, aerrors.Newf(exitcode.SysErrorIllegalActor, "no code for actor %s(%d)(%s)", codeCid, method, hex.EncodeToString(params))
} }
if method >= abi.MethodNum(len(code)) || code[method] == nil { if method >= abi.MethodNum(len(act.methods)) || act.methods[method] == nil {
return nil, aerrors.Newf(exitcode.SysErrInvalidMethod, "no method %d on actor", method) return nil, aerrors.Newf(exitcode.SysErrInvalidMethod, "no method %d on actor", method)
} }
return code[method](rt, params) if err := act.predicate(rt, act.vmActor); err != nil {
return nil, aerrors.Newf(exitcode.SysErrInvalidMethod, "unsupported actor: %s", err)
}
func (inv *Invoker) Register(c cid.Cid, instance Invokee, state interface{}) {
code, err := inv.transform(instance)
if err != nil {
panic(xerrors.Errorf("%s: %w", string(c.Hash()), err))
} }
inv.builtInCode[c] = code return act.methods[method](rt, params)
inv.builtInState[c] = reflect.TypeOf(state)
} }
type Invokee interface { func (ar *ActorRegistry) Register(pred ActorPredicate, actors ...rtt.VMActor) {
if pred == nil {
pred = func(vmr.Runtime, rtt.VMActor) error { return nil }
}
for _, a := range actors {
code, err := ar.transform(a)
if err != nil {
panic(xerrors.Errorf("%s: %w", string(a.Code().Hash()), err))
}
ar.actors[a.Code()] = &actorInfo{
methods: code,
vmActor: a,
predicate: pred,
}
}
}
func (ar *ActorRegistry) Create(codeCid cid.Cid, rt vmr.Runtime) (*types.Actor, aerrors.ActorError) {
act, ok := ar.actors[codeCid]
if !ok {
return nil, aerrors.Newf(exitcode.SysErrorIllegalArgument, "Can only create built-in actors.")
}
if err := act.predicate(rt, act.vmActor); err != nil {
return nil, aerrors.Newf(exitcode.SysErrorIllegalArgument, "Cannot create actor: %w", err)
}
if rtt.IsSingletonActor(act.vmActor) {
return nil, aerrors.Newf(exitcode.SysErrorIllegalArgument, "Can only have one instance of singleton actors.")
}
return &types.Actor{
Code: codeCid,
Head: EmptyObjectCid,
Nonce: 0,
Balance: abi.NewTokenAmount(0),
}, nil
}
type invokee interface {
Exports() []interface{} Exports() []interface{}
} }
func (*Invoker) transform(instance Invokee) (nativeCode, error) { func (*ActorRegistry) transform(instance invokee) (nativeCode, error) {
itype := reflect.TypeOf(instance) itype := reflect.TypeOf(instance)
exports := instance.Exports() exports := instance.Exports()
runtimeType := reflect.TypeOf((*vmr.Runtime)(nil)).Elem()
for i, m := range exports { for i, m := range exports {
i := i i := i
newErr := func(format string, args ...interface{}) error { newErr := func(format string, args ...interface{}) error {
@ -111,7 +146,7 @@ func (*Invoker) transform(instance Invokee) (nativeCode, error) {
return nil, newErr("wrong number of inputs should be: " + return nil, newErr("wrong number of inputs should be: " +
"vmr.Runtime, <parameter>") "vmr.Runtime, <parameter>")
} }
if t.In(0) != reflect.TypeOf((*vmr.Runtime)(nil)).Elem() { if !runtimeType.Implements(t.In(0)) {
return nil, newErr("first arguemnt should be vmr.Runtime") return nil, newErr("first arguemnt should be vmr.Runtime")
} }
if t.In(1).Kind() != reflect.Ptr { if t.In(1).Kind() != reflect.Ptr {
@ -176,27 +211,22 @@ func DecodeParams(b []byte, out interface{}) error {
return um.UnmarshalCBOR(bytes.NewReader(b)) return um.UnmarshalCBOR(bytes.NewReader(b))
} }
func DumpActorState(code cid.Cid, b []byte) (interface{}, error) { func DumpActorState(act *types.Actor, b []byte) (interface{}, error) {
if code == builtin0.AccountActorCodeID { // Account code special case if builtin.IsAccountActor(act.Code) { // Account code special case
return nil, nil return nil, nil
} }
i := NewInvoker() // TODO: register builtins in init block i := NewActorRegistry() // TODO: register builtins in init block
typ, ok := i.builtInState[code] actInfo, ok := i.actors[act.Code]
if !ok { if !ok {
return nil, xerrors.Errorf("state type for actor %s not found", code) return nil, xerrors.Errorf("state type for actor %s not found", act.Code)
}
rv := reflect.New(typ)
um, ok := rv.Interface().(cbg.CBORUnmarshaler)
if !ok {
return nil, xerrors.New("state type does not implement CBORUnmarshaler")
} }
um := actInfo.vmActor.State()
if err := um.UnmarshalCBOR(bytes.NewReader(b)); err != nil { if err := um.UnmarshalCBOR(bytes.NewReader(b)); err != nil {
return nil, xerrors.Errorf("unmarshaling actor state: %w", err) return nil, xerrors.Errorf("unmarshaling actor state: %w", err)
} }
return rv.Elem().Interface(), nil return um, nil
} }

View File

@ -77,7 +77,7 @@ func (basicContract) InvokeSomething10(rt runtime.Runtime, params *basicParams)
} }
func TestInvokerBasic(t *testing.T) { func TestInvokerBasic(t *testing.T) {
inv := Invoker{} inv := ActorRegistry{}
code, err := inv.transform(basicContract{}) code, err := inv.transform(basicContract{})
assert.NoError(t, err) assert.NoError(t, err)

View File

@ -6,11 +6,13 @@ import (
"github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/go-state-types/exitcode" "github.com/filecoin-project/go-state-types/exitcode"
"github.com/filecoin-project/lotus/chain/actors" "github.com/filecoin-project/lotus/chain/actors"
"github.com/filecoin-project/specs-actors/actors/builtin"
"github.com/ipfs/go-cid" "github.com/ipfs/go-cid"
cbor "github.com/ipfs/go-ipld-cbor" cbor "github.com/ipfs/go-ipld-cbor"
builtin0 "github.com/filecoin-project/specs-actors/actors/builtin"
builtin2 "github.com/filecoin-project/specs-actors/v2/actors/builtin"
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/filecoin-project/lotus/chain/actors/aerrors" "github.com/filecoin-project/lotus/chain/actors/aerrors"
"github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/types"
@ -39,7 +41,7 @@ func TryCreateAccountActor(rt *Runtime, addr address.Address) (*types.Actor, aer
return nil, aerrors.Escalate(err, "registering actor address") return nil, aerrors.Escalate(err, "registering actor address")
} }
act, aerr := makeActor(addr) act, aerr := makeActor(actors.VersionForNetwork(rt.NetworkVersion()), addr)
if aerr != nil { if aerr != nil {
return nil, aerr return nil, aerr
} }
@ -54,7 +56,7 @@ func TryCreateAccountActor(rt *Runtime, addr address.Address) (*types.Actor, aer
} }
// call constructor on account // call constructor on account
_, aerr = rt.internalSend(builtin.SystemActorAddr, addrID, builtin.MethodsAccount.Constructor, big.Zero(), p) _, aerr = rt.internalSend(builtin0.SystemActorAddr, addrID, builtin0.MethodsAccount.Constructor, big.Zero(), p)
if aerr != nil { if aerr != nil {
return nil, aerrors.Wrap(aerr, "failed to invoke account constructor") return nil, aerrors.Wrap(aerr, "failed to invoke account constructor")
} }
@ -66,12 +68,10 @@ func TryCreateAccountActor(rt *Runtime, addr address.Address) (*types.Actor, aer
return act, nil return act, nil
} }
func makeActor(addr address.Address) (*types.Actor, aerrors.ActorError) { func makeActor(ver actors.Version, addr address.Address) (*types.Actor, aerrors.ActorError) {
switch addr.Protocol() { switch addr.Protocol() {
case address.BLS: case address.BLS, address.SECP256K1:
return NewBLSAccountActor(), nil return newAccountActor(ver), nil
case address.SECP256K1:
return NewSecp256k1AccountActor(), nil
case address.ID: case address.ID:
return nil, aerrors.Newf(exitcode.SysErrInvalidReceiver, "no actor with given ID: %s", addr) return nil, aerrors.Newf(exitcode.SysErrInvalidReceiver, "no actor with given ID: %s", addr)
case address.Actor: case address.Actor:
@ -81,19 +81,19 @@ func makeActor(addr address.Address) (*types.Actor, aerrors.ActorError) {
} }
} }
func NewBLSAccountActor() *types.Actor { func newAccountActor(ver actors.Version) *types.Actor {
// TODO: ActorsUpgrade use a global actor registry?
var code cid.Cid
switch ver {
case actors.Version0:
code = builtin0.AccountActorCodeID
case actors.Version2:
code = builtin2.AccountActorCodeID
default:
panic("unsupported actors version")
}
nact := &types.Actor{ nact := &types.Actor{
Code: builtin.AccountActorCodeID, Code: code,
Balance: types.NewInt(0),
Head: EmptyObjectCid,
}
return nact
}
func NewSecp256k1AccountActor() *types.Actor {
nact := &types.Actor{
Code: builtin.AccountActorCodeID,
Balance: types.NewInt(0), Balance: types.NewInt(0),
Head: EmptyObjectCid, Head: EmptyObjectCid,
} }

View File

@ -9,14 +9,13 @@ import (
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/go-state-types/cbor" "github.com/filecoin-project/go-state-types/cbor"
"github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/go-state-types/crypto"
"github.com/filecoin-project/go-state-types/exitcode" "github.com/filecoin-project/go-state-types/exitcode"
"github.com/filecoin-project/go-state-types/network" "github.com/filecoin-project/go-state-types/network"
rtt "github.com/filecoin-project/go-state-types/rt" rtt "github.com/filecoin-project/go-state-types/rt"
"github.com/filecoin-project/specs-actors/actors/builtin"
rt0 "github.com/filecoin-project/specs-actors/actors/runtime" rt0 "github.com/filecoin-project/specs-actors/actors/runtime"
rt2 "github.com/filecoin-project/specs-actors/v2/actors/runtime"
"github.com/ipfs/go-cid" "github.com/ipfs/go-cid"
ipldcbor "github.com/ipfs/go-ipld-cbor" ipldcbor "github.com/ipfs/go-ipld-cbor"
"go.opencensus.io/trace" "go.opencensus.io/trace"
@ -110,6 +109,7 @@ func (rt *Runtime) StorePut(x cbor.Marshaler) cid.Cid {
} }
var _ rt0.Runtime = (*Runtime)(nil) var _ rt0.Runtime = (*Runtime)(nil)
var _ rt2.Runtime = (*Runtime)(nil)
func (rt *Runtime) shimCall(f func() interface{}) (rval []byte, aerr aerrors.ActorError) { func (rt *Runtime) shimCall(f func() interface{}) (rval []byte, aerr aerrors.ActorError) {
defer func() { defer func() {
@ -215,12 +215,9 @@ func (rt *Runtime) NewActorAddress() address.Address {
} }
func (rt *Runtime) CreateActor(codeID cid.Cid, address address.Address) { func (rt *Runtime) CreateActor(codeID cid.Cid, address address.Address) {
if !builtin.IsBuiltinActor(codeID) { act, aerr := rt.vm.areg.Create(codeID, rt)
rt.Abortf(exitcode.SysErrorIllegalArgument, "Can only create built-in actors.") if aerr != nil {
} rt.Abortf(aerr.RetCode(), aerr.Error())
if builtin.IsSingletonActor(codeID) {
rt.Abortf(exitcode.SysErrorIllegalArgument, "Can only have one instance of singleton actors.")
} }
_, err := rt.state.GetActor(address) _, err := rt.state.GetActor(address)
@ -230,12 +227,7 @@ func (rt *Runtime) CreateActor(codeID cid.Cid, address address.Address) {
rt.chargeGas(rt.Pricelist().OnCreateActor()) rt.chargeGas(rt.Pricelist().OnCreateActor())
err = rt.state.SetActor(address, &types.Actor{ err = rt.state.SetActor(address, act)
Code: codeID,
Head: EmptyObjectCid,
Nonce: 0,
Balance: big.Zero(),
})
if err != nil { if err != nil {
panic(aerrors.Fatalf("creating actor entry: %v", err)) panic(aerrors.Fatalf("creating actor entry: %v", err))
} }

View File

@ -8,6 +8,8 @@ import (
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/filecoin-project/lotus/chain/actors/builtin"
block "github.com/ipfs/go-block-format" block "github.com/ipfs/go-block-format"
cid "github.com/ipfs/go-cid" cid "github.com/ipfs/go-cid"
cbor "github.com/ipfs/go-ipld-cbor" cbor "github.com/ipfs/go-ipld-cbor"
@ -23,7 +25,6 @@ import (
"github.com/filecoin-project/go-state-types/crypto" "github.com/filecoin-project/go-state-types/crypto"
"github.com/filecoin-project/go-state-types/exitcode" "github.com/filecoin-project/go-state-types/exitcode"
"github.com/filecoin-project/go-state-types/network" "github.com/filecoin-project/go-state-types/network"
"github.com/filecoin-project/specs-actors/actors/builtin"
"github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/build"
"github.com/filecoin-project/lotus/chain/actors/adt" "github.com/filecoin-project/lotus/chain/actors/adt"
@ -152,7 +153,7 @@ type VM struct {
cst *cbor.BasicIpldStore cst *cbor.BasicIpldStore
buf *bufbstore.BufferedBS buf *bufbstore.BufferedBS
blockHeight abi.ChainEpoch blockHeight abi.ChainEpoch
inv *Invoker areg *ActorRegistry
rand Rand rand Rand
circSupplyCalc CircSupplyCalculator circSupplyCalc CircSupplyCalculator
ntwkVersion NtwkVersionGetter ntwkVersion NtwkVersionGetter
@ -186,7 +187,7 @@ func NewVM(ctx context.Context, opts *VMOpts) (*VM, error) {
cst: cst, cst: cst,
buf: buf, buf: buf,
blockHeight: opts.Epoch, blockHeight: opts.Epoch,
inv: NewInvoker(), areg: NewActorRegistry(),
rand: opts.Rand, // TODO: Probably should be a syscall rand: opts.Rand, // TODO: Probably should be a syscall
circSupplyCalc: opts.CircSupplyCalc, circSupplyCalc: opts.CircSupplyCalc,
ntwkVersion: opts.NtwkVersion, ntwkVersion: opts.NtwkVersion,
@ -403,7 +404,7 @@ func (vm *VM) ApplyMessage(ctx context.Context, cmsg types.ChainMsg) (*ApplyRet,
} }
// this should never happen, but is currently still exercised by some tests // this should never happen, but is currently still exercised by some tests
if !fromActor.IsAccountActor() { if !builtin.IsAccountActor(fromActor.Code) {
gasOutputs := ZeroGasOutputs() gasOutputs := ZeroGasOutputs()
gasOutputs.MinerPenalty = minerPenaltyAmount gasOutputs.MinerPenalty = minerPenaltyAmount
return &ApplyRet{ return &ApplyRet{
@ -741,15 +742,15 @@ func (vm *VM) Invoke(act *types.Actor, rt *Runtime, method abi.MethodNum, params
defer func() { defer func() {
rt.ctx = oldCtx rt.ctx = oldCtx
}() }()
ret, err := vm.inv.Invoke(act.Code, rt, method, params) ret, err := vm.areg.Invoke(act.Code, rt, method, params)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return ret, nil return ret, nil
} }
func (vm *VM) SetInvoker(i *Invoker) { func (vm *VM) SetInvoker(i *ActorRegistry) {
vm.inv = i vm.areg = i
} }
func (vm *VM) GetNtwkVersion(ctx context.Context, ce abi.ChainEpoch) network.Version { func (vm *VM) GetNtwkVersion(ctx context.Context, ce abi.ChainEpoch) network.Version {

View File

@ -9,6 +9,10 @@ import (
"strconv" "strconv"
"text/tabwriter" "text/tabwriter"
builtin2 "github.com/filecoin-project/specs-actors/v2/actors/builtin"
"github.com/filecoin-project/lotus/chain/actors/builtin"
"github.com/filecoin-project/lotus/chain/actors" "github.com/filecoin-project/lotus/chain/actors"
"github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/big"
@ -20,7 +24,6 @@ import (
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"golang.org/x/xerrors" "golang.org/x/xerrors"
"github.com/filecoin-project/specs-actors/actors/builtin"
init0 "github.com/filecoin-project/specs-actors/actors/builtin/init" init0 "github.com/filecoin-project/specs-actors/actors/builtin/init"
msig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig" msig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig"
@ -356,7 +359,7 @@ var msigProposeCmd = &cli.Command{
return fmt.Errorf("failed to look up multisig %s: %w", msig, err) return fmt.Errorf("failed to look up multisig %s: %w", msig, err)
} }
if !act.IsMultisigActor() { if !builtin.IsMultisigActor(act.Code) {
return fmt.Errorf("actor %s is not a multisig actor", msig) return fmt.Errorf("actor %s is not a multisig actor", msig)
} }
@ -1029,7 +1032,7 @@ var msigLockProposeCmd = &cli.Command{
return actErr return actErr
} }
msgCid, err := api.MsigPropose(ctx, msig, msig, big.Zero(), from, uint64(builtin.MethodsMultisig.LockBalance), params) msgCid, err := api.MsigPropose(ctx, msig, msig, big.Zero(), from, uint64(builtin2.MethodsMultisig.LockBalance), params)
if err != nil { if err != nil {
return err return err
} }
@ -1126,7 +1129,7 @@ var msigLockApproveCmd = &cli.Command{
return actErr return actErr
} }
msgCid, err := api.MsigApprove(ctx, msig, txid, prop, msig, big.Zero(), from, uint64(builtin.MethodsMultisig.LockBalance), params) msgCid, err := api.MsigApprove(ctx, msig, txid, prop, msig, big.Zero(), from, uint64(builtin2.MethodsMultisig.LockBalance), params)
if err != nil { if err != nil {
return err return err
} }
@ -1218,7 +1221,7 @@ var msigLockCancelCmd = &cli.Command{
return actErr return actErr
} }
msgCid, err := api.MsigCancel(ctx, msig, txid, msig, big.Zero(), from, uint64(builtin.MethodsMultisig.LockBalance), params) msgCid, err := api.MsigCancel(ctx, msig, txid, msig, big.Zero(), from, uint64(builtin2.MethodsMultisig.LockBalance), params)
if err != nil { if err != nil {
return err return err
} }

View File

@ -14,10 +14,10 @@ import (
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/build"
"github.com/filecoin-project/specs-actors/actors/builtin/paych"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
types "github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/actors/builtin/paych"
"github.com/filecoin-project/lotus/chain/types"
) )
var paychCmd = &cli.Command{ var paychCmd = &cli.Command{
@ -404,7 +404,7 @@ var paychVoucherCheckCmd = &cli.Command{
return err return err
} }
sv, err := types.DecodeSignedVoucher(cctx.Args().Get(1)) sv, err := paych.DecodeSignedVoucher(cctx.Args().Get(1))
if err != nil { if err != nil {
return err return err
} }
@ -440,7 +440,7 @@ var paychVoucherAddCmd = &cli.Command{
return err return err
} }
sv, err := types.DecodeSignedVoucher(cctx.Args().Get(1)) sv, err := paych.DecodeSignedVoucher(cctx.Args().Get(1))
if err != nil { if err != nil {
return err return err
} }
@ -598,7 +598,7 @@ var paychVoucherSubmitCmd = &cli.Command{
return err return err
} }
sv, err := types.DecodeSignedVoucher(cctx.Args().Get(1)) sv, err := paych.DecodeSignedVoucher(cctx.Args().Get(1))
if err != nil { if err != nil {
return err return err
} }

View File

@ -14,7 +14,7 @@ import (
"strings" "strings"
"time" "time"
"github.com/filecoin-project/specs-actors/actors/runtime" "github.com/filecoin-project/lotus/chain/actors/builtin"
"github.com/multiformats/go-multiaddr" "github.com/multiformats/go-multiaddr"
@ -30,8 +30,6 @@ import (
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/go-state-types/exitcode" "github.com/filecoin-project/go-state-types/exitcode"
"github.com/filecoin-project/specs-actors/actors/builtin"
"github.com/filecoin-project/specs-actors/actors/builtin/exported"
"github.com/filecoin-project/lotus/api" "github.com/filecoin-project/lotus/api"
"github.com/filecoin-project/lotus/api/apibstore" "github.com/filecoin-project/lotus/api/apibstore"
@ -1534,28 +1532,18 @@ func parseParamsForMethod(act cid.Cid, method uint64, args []string) ([]byte, er
return nil, nil return nil, nil
} }
var target runtime.Invokee // TODO: consider moving this to a dedicated helper
for _, actor := range exported.BuiltinActors() { actMeta, ok := stmgr.MethodsMap[act]
if actor.Code() == act { if !ok {
target = actor
}
}
if target == nil {
return nil, fmt.Errorf("unknown actor %s", act) return nil, fmt.Errorf("unknown actor %s", act)
} }
methods := target.Exports()
if uint64(len(methods)) <= method || methods[method] == nil { methodMeta, ok := actMeta[abi.MethodNum(method)]
if !ok {
return nil, fmt.Errorf("unknown method %d for actor %s", method, act) return nil, fmt.Errorf("unknown method %d for actor %s", method, act)
} }
f := methods[method] paramObj := methodMeta.Params
rf := reflect.TypeOf(f)
if rf.NumIn() != 2 {
return nil, fmt.Errorf("expected referenced method to have three arguments")
}
paramObj := rf.In(1).Elem()
if paramObj.NumField() != len(args) { if paramObj.NumField() != len(args) {
return nil, fmt.Errorf("not enough arguments given to call that method (expecting %d)", paramObj.NumField()) return nil, fmt.Errorf("not enough arguments given to call that method (expecting %d)", paramObj.NumField())
} }

View File

@ -9,12 +9,15 @@ import (
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/ipfs/go-cid"
builtin2 "github.com/filecoin-project/specs-actors/v2/actors/builtin"
"github.com/filecoin-project/lotus/chain/actors/builtin"
_init "github.com/filecoin-project/lotus/chain/actors/builtin/init" _init "github.com/filecoin-project/lotus/chain/actors/builtin/init"
"github.com/filecoin-project/lotus/chain/events/state" "github.com/filecoin-project/lotus/chain/events/state"
"github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/types"
cw_util "github.com/filecoin-project/lotus/cmd/lotus-chainwatch/util" cw_util "github.com/filecoin-project/lotus/cmd/lotus-chainwatch/util"
"github.com/filecoin-project/specs-actors/actors/builtin"
"github.com/ipfs/go-cid"
) )
func (p *Processor) setupCommonActors() error { func (p *Processor) setupCommonActors() error {
@ -135,15 +138,15 @@ func (p Processor) storeActorAddresses(ctx context.Context, actors map[cid.Cid]A
addressToID := map[address.Address]address.Address{} addressToID := map[address.Address]address.Address{}
// HACK until genesis storage is figured out: // HACK until genesis storage is figured out:
addressToID[builtin.SystemActorAddr] = builtin.SystemActorAddr addressToID[builtin2.SystemActorAddr] = builtin2.SystemActorAddr
addressToID[builtin.InitActorAddr] = builtin.InitActorAddr addressToID[builtin2.InitActorAddr] = builtin2.InitActorAddr
addressToID[builtin.RewardActorAddr] = builtin.RewardActorAddr addressToID[builtin2.RewardActorAddr] = builtin2.RewardActorAddr
addressToID[builtin.CronActorAddr] = builtin.CronActorAddr addressToID[builtin2.CronActorAddr] = builtin2.CronActorAddr
addressToID[builtin.StoragePowerActorAddr] = builtin.StoragePowerActorAddr addressToID[builtin2.StoragePowerActorAddr] = builtin2.StoragePowerActorAddr
addressToID[builtin.StorageMarketActorAddr] = builtin.StorageMarketActorAddr addressToID[builtin2.StorageMarketActorAddr] = builtin2.StorageMarketActorAddr
addressToID[builtin.VerifiedRegistryActorAddr] = builtin.VerifiedRegistryActorAddr addressToID[builtin2.VerifiedRegistryActorAddr] = builtin2.VerifiedRegistryActorAddr
addressToID[builtin.BurntFundsActorAddr] = builtin.BurntFundsActorAddr addressToID[builtin2.BurntFundsActorAddr] = builtin2.BurntFundsActorAddr
initActor, err := p.node.StateGetActor(ctx, builtin.InitActorAddr, types.EmptyTSK) initActor, err := p.node.StateGetActor(ctx, builtin2.InitActorAddr, types.EmptyTSK)
if err != nil { if err != nil {
return err return err
} }

View File

@ -14,7 +14,9 @@ import (
"strconv" "strconv"
"time" "time"
"github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/lotus/chain/actors/builtin"
builtin0 "github.com/filecoin-project/specs-actors/actors/builtin"
miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner" miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner"
"github.com/filecoin-project/go-state-types/network" "github.com/filecoin-project/go-state-types/network"
@ -850,14 +852,14 @@ func (r *refunder) ProcessTipset(ctx context.Context, tipset *types.TipSet, refu
continue continue
} }
if !a.IsStorageMinerActor() { if !builtin.IsStorageMinerActor(a.Code) {
continue continue
} }
var messageMethod string var messageMethod string
switch m.Method { switch m.Method {
case builtin.MethodsMiner.ProveCommitSector: case builtin0.MethodsMiner.ProveCommitSector:
if !r.proveCommitEnabled { if !r.proveCommitEnabled {
continue continue
} }
@ -904,7 +906,7 @@ func (r *refunder) ProcessTipset(ctx context.Context, tipset *types.TipSet, refu
} }
refundValue = collateral refundValue = collateral
case builtin.MethodsMiner.PreCommitSector: case builtin0.MethodsMiner.PreCommitSector:
if !r.preCommitEnabled { if !r.preCommitEnabled {
continue continue
} }

View File

@ -6,7 +6,7 @@ import (
"strconv" "strconv"
"github.com/docker/go-units" "github.com/docker/go-units"
lotusbuiltin "github.com/filecoin-project/lotus/chain/actors/builtin" "github.com/filecoin-project/lotus/chain/actors/builtin"
"github.com/filecoin-project/lotus/chain/actors/builtin/power" "github.com/filecoin-project/lotus/chain/actors/builtin/power"
"github.com/filecoin-project/lotus/chain/actors/builtin/reward" "github.com/filecoin-project/lotus/chain/actors/builtin/reward"
@ -97,7 +97,7 @@ var chainBalanceCmd = &cli.Command{
Type: string(act.Code.Hash()[2:]), Type: string(act.Code.Hash()[2:]),
} }
if act.IsStorageMinerActor() { if builtin.IsStorageMinerActor(act.Code) {
pow, err := api.StateMinerPower(ctx, addr, tsk) pow, err := api.StateMinerPower(ctx, addr, tsk)
if err != nil { if err != nil {
return xerrors.Errorf("failed to get power: %w", err) return xerrors.Errorf("failed to get power: %w", err)
@ -198,7 +198,7 @@ var chainBalanceStateCmd = &cli.Command{
PreCommits: types.FIL(big.NewInt(0)), PreCommits: types.FIL(big.NewInt(0)),
} }
if minerInfo && act.IsStorageMinerActor() { if minerInfo && builtin.IsStorageMinerActor(act.Code) {
pow, _, _, err := stmgr.GetPowerRaw(ctx, sm, sroot, addr) pow, _, _, err := stmgr.GetPowerRaw(ctx, sm, sroot, addr)
if err != nil { if err != nil {
return xerrors.Errorf("failed to get power: %w", err) return xerrors.Errorf("failed to get power: %w", err)
@ -322,7 +322,7 @@ var chainPledgeCmd = &cli.Command{
} }
var ( var (
powerSmoothed lotusbuiltin.FilterEstimate powerSmoothed builtin.FilterEstimate
pledgeCollateral abi.TokenAmount pledgeCollateral abi.TokenAmount
) )
if act, err := state.GetActor(power.Address); err != nil { if act, err := state.GetActor(power.Address); err != nil {

View File

@ -6,6 +6,8 @@ import (
"os" "os"
"sort" "sort"
"github.com/filecoin-project/lotus/chain/actors/builtin"
"github.com/fatih/color" "github.com/fatih/color"
"github.com/ipfs/go-datastore" "github.com/ipfs/go-datastore"
cbor "github.com/ipfs/go-ipld-cbor" cbor "github.com/ipfs/go-ipld-cbor"
@ -95,14 +97,14 @@ var genesisVerifyCmd = &cli.Command{
if err := stree.ForEach(func(addr address.Address, act *types.Actor) error { if err := stree.ForEach(func(addr address.Address, act *types.Actor) error {
switch { switch {
case act.IsStorageMinerActor(): case builtin.IsStorageMinerActor(act.Code):
_, err := miner.Load(store, act) _, err := miner.Load(store, act)
if err != nil { if err != nil {
return xerrors.Errorf("miner actor: %w", err) return xerrors.Errorf("miner actor: %w", err)
} }
// TODO: actually verify something here? // TODO: actually verify something here?
kminers[addr] = minerInfo{} kminers[addr] = minerInfo{}
case act.IsMultisigActor(): case builtin.IsMultisigActor(act.Code):
st, err := multisig.Load(store, act) st, err := multisig.Load(store, act)
if err != nil { if err != nil {
return xerrors.Errorf("multisig actor: %w", err) return xerrors.Errorf("multisig actor: %w", err)
@ -123,7 +125,7 @@ var genesisVerifyCmd = &cli.Command{
Threshold: threshold, Threshold: threshold,
} }
msigAddrs = append(msigAddrs, addr) msigAddrs = append(msigAddrs, addr)
case act.IsAccountActor(): case builtin.IsAccountActor(act.Code):
st, err := account.Load(store, act) st, err := account.Load(store, act)
if err != nil { if err != nil {
// TODO: magik6k: this _used_ to log instead of failing, why? // TODO: magik6k: this _used_ to log instead of failing, why?

View File

@ -18,6 +18,7 @@ import (
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
lapi "github.com/filecoin-project/lotus/api" lapi "github.com/filecoin-project/lotus/api"
"github.com/filecoin-project/lotus/chain/actors/builtin"
"github.com/filecoin-project/lotus/chain/types" "github.com/filecoin-project/lotus/chain/types"
lcli "github.com/filecoin-project/lotus/cli" lcli "github.com/filecoin-project/lotus/cli"
) )
@ -122,7 +123,7 @@ var mpoolStatsCmd = &cli.Command{
return false, err return false, err
} }
ism := act.IsStorageMinerActor() ism := builtin.IsStorageMinerActor(act.Code)
mcache[addr] = ism mcache[addr] = ism
return ism, nil return ism, nil
} }

View File

@ -1,44 +0,0 @@
package main
import (
"reflect"
"github.com/filecoin-project/specs-actors/actors/builtin"
"github.com/ipfs/go-cid"
"github.com/multiformats/go-multihash"
)
var ActorMethodTable = make(map[string][]string, 64)
var Actors = map[cid.Cid]interface{}{
builtin.InitActorCodeID: builtin.MethodsInit,
builtin.CronActorCodeID: builtin.MethodsCron,
builtin.AccountActorCodeID: builtin.MethodsAccount,
builtin.StoragePowerActorCodeID: builtin.MethodsPower,
builtin.StorageMinerActorCodeID: builtin.MethodsMiner,
builtin.StorageMarketActorCodeID: builtin.MethodsMarket,
builtin.PaymentChannelActorCodeID: builtin.MethodsPaych,
builtin.MultisigActorCodeID: builtin.MethodsMultisig,
builtin.RewardActorCodeID: builtin.MethodsReward,
builtin.VerifiedRegistryActorCodeID: builtin.MethodsVerifiedRegistry,
}
func init() {
for code, methods := range Actors {
cmh, err := multihash.Decode(code.Hash()) // identity hash.
if err != nil {
panic(err)
}
var (
aname = string(cmh.Digest)
rt = reflect.TypeOf(methods)
nf = rt.NumField()
)
ActorMethodTable[aname] = append(ActorMethodTable[aname], "Send")
for i := 0; i < nf; i++ {
ActorMethodTable[aname] = append(ActorMethodTable[aname], rt.Field(i).Name)
}
}
}

View File

@ -12,10 +12,14 @@ import (
"strings" "strings"
"github.com/fatih/color" "github.com/fatih/color"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/exitcode" "github.com/filecoin-project/go-state-types/exitcode"
"github.com/hashicorp/go-multierror" "github.com/hashicorp/go-multierror"
"github.com/ipfs/go-cid"
"github.com/multiformats/go-multihash"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"github.com/filecoin-project/lotus/chain/stmgr"
lcli "github.com/filecoin-project/lotus/cli" lcli "github.com/filecoin-project/lotus/cli"
) )
@ -118,6 +122,8 @@ func runExtractMany(c *cli.Context) error {
log.Println(color.GreenString("csv sanity check succeeded; header contains fields: %v", header)) log.Println(color.GreenString("csv sanity check succeeded; header contains fields: %v", header))
} }
codeCidBuilder := cid.V1Builder{Codec: cid.Raw, MhType: multihash.IDENTITY}
var ( var (
generated []string generated []string
merr = new(multierror.Error) merr = new(multierror.Error)
@ -133,7 +139,7 @@ func runExtractMany(c *cli.Context) error {
return fmt.Errorf("failed to read row: %w", err) return fmt.Errorf("failed to read row: %w", err)
} }
var ( var (
cid = row[0] mcid = row[0]
actorcode = row[1] actorcode = row[1]
methodnumstr = row[2] methodnumstr = row[2]
exitcodestr = row[3] exitcodestr = row[3]
@ -155,13 +161,18 @@ func runExtractMany(c *cli.Context) error {
return fmt.Errorf("invalid method number: %s", methodnumstr) return fmt.Errorf("invalid method number: %s", methodnumstr)
} }
codeCid, err := codeCidBuilder.Sum([]byte(actorcode))
if err != nil {
return fmt.Errorf("failed to compute actor code CID")
}
// Lookup the method in actor method table. // Lookup the method in actor method table.
if m, ok := ActorMethodTable[actorcode]; !ok { if m, ok := stmgr.MethodsMap[codeCid]; !ok {
return fmt.Errorf("unrecognized actor: %s", actorcode) return fmt.Errorf("unrecognized actor: %s", actorcode)
} else if methodnum >= len(m) { } else if methodnum >= len(m) {
return fmt.Errorf("unrecognized method number for actor %s: %d", actorcode, methodnum) return fmt.Errorf("unrecognized method number for actor %s: %d", actorcode, methodnum)
} else { } else {
methodname = m[methodnum] methodname = m[abi.MethodNum(methodnum)].Name
} }
// exitcode string representations are of kind ErrType(0); strip out // exitcode string representations are of kind ErrType(0); strip out
@ -181,14 +192,14 @@ func runExtractMany(c *cli.Context) error {
id: id, id: id,
block: block, block: block,
class: "message", class: "message",
cid: cid, cid: mcid,
file: file, file: file,
retain: "accessed-cids", retain: "accessed-cids",
precursor: PrecursorSelectSender, precursor: PrecursorSelectSender,
} }
if err := doExtract(ctx, fapi, opts); err != nil { if err := doExtract(ctx, fapi, opts); err != nil {
log.Println(color.RedString("failed to extract vector for message %s: %s; queuing for 'canonical' precursor selection", cid, err)) log.Println(color.RedString("failed to extract vector for message %s: %s; queuing for 'canonical' precursor selection", mcid, err))
retry = append(retry, opts) retry = append(retry, opts)
continue continue
} }

View File

@ -3,7 +3,9 @@ package chaos
import ( import (
"github.com/filecoin-project/go-address" "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/cbor"
"github.com/filecoin-project/go-state-types/exitcode" "github.com/filecoin-project/go-state-types/exitcode"
"github.com/filecoin-project/go-state-types/rt"
"github.com/filecoin-project/specs-actors/actors/builtin" "github.com/filecoin-project/specs-actors/actors/builtin"
"github.com/filecoin-project/specs-actors/actors/runtime" "github.com/filecoin-project/specs-actors/actors/runtime"
"github.com/ipfs/go-cid" "github.com/ipfs/go-cid"
@ -86,7 +88,11 @@ func (a Actor) Exports() []interface{} {
} }
} }
var _ runtime.Invokee = Actor{} func (a Actor) Code() cid.Cid { return ChaosActorCodeCID }
func (a Actor) State() cbor.Er { return new(State) }
func (a Actor) IsSingleton() bool { return true }
var _ rt.VMActor = Actor{}
// SendArgs are the arguments for the Send method. // SendArgs are the arguments for the Send method.
type SendArgs struct { type SendArgs struct {

View File

@ -167,7 +167,7 @@ func (d *Driver) ExecuteMessage(bs blockstore.Blockstore, params ExecuteMessageP
// dummy state manager; only to reference the GetNetworkVersion method, // dummy state manager; only to reference the GetNetworkVersion method,
// which does not depend on state. // which does not depend on state.
sm := new(stmgr.StateManager) sm := stmgr.NewStateManager(nil)
vmOpts := &vm.VMOpts{ vmOpts := &vm.VMOpts{
StateBase: params.Preroot, StateBase: params.Preroot,
@ -187,11 +187,11 @@ func (d *Driver) ExecuteMessage(bs blockstore.Blockstore, params ExecuteMessageP
return nil, cid.Undef, err return nil, cid.Undef, err
} }
invoker := vm.NewInvoker() invoker := vm.NewActorRegistry()
// register the chaos actor if required by the vector. // register the chaos actor if required by the vector.
if chaosOn, ok := d.selector["chaos_actor"]; ok && chaosOn == "true" { if chaosOn, ok := d.selector["chaos_actor"]; ok && chaosOn == "true" {
invoker.Register(chaos.ChaosActorCodeCID, chaos.Actor{}, chaos.State{}) invoker.Register(nil, chaos.Actor{})
} }
lvm.SetInvoker(invoker) lvm.SetInvoker(invoker)

View File

@ -233,8 +233,13 @@ func writeStateToTempCAR(bs blockstore.Blockstore, roots ...cid.Cid) (string, er
if link.Cid.Prefix().Codec == cid.FilCommitmentSealed || link.Cid.Prefix().Codec == cid.FilCommitmentUnsealed { if link.Cid.Prefix().Codec == cid.FilCommitmentSealed || link.Cid.Prefix().Codec == cid.FilCommitmentUnsealed {
continue continue
} }
// ignore things we don't have, the state tree is incomplete.
if has, err := bs.Has(link.Cid); err != nil {
return nil, err
} else if has {
out = append(out, link) out = append(out, link)
} }
}
return out, nil return out, nil
} }

View File

@ -3863,7 +3863,7 @@ Inputs:
] ]
``` ```
Response: `3` Response: `4`
### StateReadState ### StateReadState
StateReadState returns the indicated actor's state. StateReadState returns the indicated actor's state.

2
extern/fil-blst vendored

@ -1 +1 @@
Subproject commit 8609119cf4595d1741139c24378fcd8bc4f1c475 Subproject commit 5f93488fc0dbfb450f2355269f18fc67010d59bb

2
extern/filecoin-ffi vendored

@ -1 +1 @@
Subproject commit 57e38efe4943f09d3127dcf6f0edd614e6acf68e Subproject commit f640612a1a1f7a2dd8b3a49e1531db0aa0f63447

2
extern/oni vendored

@ -1 +1 @@
Subproject commit 9a0d5cd739de77b357589ac1fc8b756ed27299be Subproject commit dbee44e4f940a502971f17116ccbba61ceaf2674

View File

@ -4,11 +4,9 @@ import (
"bytes" "bytes"
"context" "context"
"github.com/filecoin-project/lotus/chain/actors"
"github.com/filecoin-project/lotus/chain/actors/policy" "github.com/filecoin-project/lotus/chain/actors/policy"
"github.com/filecoin-project/lotus/build"
miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner"
proof0 "github.com/filecoin-project/specs-actors/actors/runtime/proof" proof0 "github.com/filecoin-project/specs-actors/actors/runtime/proof"
"golang.org/x/xerrors" "golang.org/x/xerrors"
@ -102,16 +100,10 @@ func checkPrecommit(ctx context.Context, maddr address.Address, si SectorInfo, t
return &ErrApi{xerrors.Errorf("calling StateNetworkVersion: %w", err)} return &ErrApi{xerrors.Errorf("calling StateNetworkVersion: %w", err)}
} }
var msd abi.ChainEpoch msd := policy.GetMaxProveCommitDuration(actors.VersionForNetwork(nv), si.SectorType)
if nv < build.ActorUpgradeNetworkVersion {
msd = miner0.MaxSealDuration[si.SectorType]
} else {
// TODO: ActorUpgrade(use MaxProveCommitDuration)
msd = 0
}
if height-(si.TicketEpoch+SealRandomnessLookback) > msd { if height-(si.TicketEpoch+policy.SealRandomnessLookback) > msd {
return &ErrExpiredTicket{xerrors.Errorf("ticket expired: seal height: %d, head: %d", si.TicketEpoch+SealRandomnessLookback, height)} return &ErrExpiredTicket{xerrors.Errorf("ticket expired: seal height: %d, head: %d", si.TicketEpoch+policy.SealRandomnessLookback, height)}
} }
pci, err := api.StateSectorPreCommitInfo(ctx, maddr, si.SectorNumber, tok) pci, err := api.StateSectorPreCommitInfo(ctx, maddr, si.SectorNumber, tok)

View File

@ -1,11 +1,4 @@
package sealing package sealing
import (
miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner"
)
// Epochs
const SealRandomnessLookback = miner0.ChainFinality
// Epochs // Epochs
const InteractivePoRepConfidence = 6 const InteractivePoRepConfidence = 6

View File

@ -4,14 +4,14 @@ import (
"bytes" "bytes"
"time" "time"
"github.com/filecoin-project/lotus/chain/actors/builtin/miner"
"golang.org/x/xerrors" "golang.org/x/xerrors"
"github.com/filecoin-project/lotus/chain/actors/builtin/market"
"github.com/filecoin-project/lotus/chain/actors/builtin/miner"
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/exitcode" "github.com/filecoin-project/go-state-types/exitcode"
"github.com/filecoin-project/go-statemachine" "github.com/filecoin-project/go-statemachine"
"github.com/filecoin-project/specs-actors/actors/builtin/market"
"github.com/filecoin-project/lotus/extern/sector-storage/zerocomm" "github.com/filecoin-project/lotus/extern/sector-storage/zerocomm"
) )

View File

@ -4,10 +4,9 @@ import (
"bytes" "bytes"
"context" "context"
"github.com/filecoin-project/lotus/build" "github.com/filecoin-project/lotus/chain/actors"
"github.com/filecoin-project/lotus/chain/actors/builtin/miner" "github.com/filecoin-project/lotus/chain/actors/builtin/miner"
"github.com/filecoin-project/lotus/chain/actors/policy" "github.com/filecoin-project/lotus/chain/actors/policy"
miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner"
"golang.org/x/xerrors" "golang.org/x/xerrors"
@ -60,7 +59,7 @@ func (m *Sealing) getTicket(ctx statemachine.Context, sector SectorInfo) (abi.Se
return nil, 0, nil return nil, 0, nil
} }
ticketEpoch := epoch - SealRandomnessLookback ticketEpoch := epoch - policy.SealRandomnessLookback
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
if err := m.maddr.MarshalCBOR(buf); err != nil { if err := m.maddr.MarshalCBOR(buf); err != nil {
return nil, 0, err return nil, 0, err
@ -189,13 +188,7 @@ func (m *Sealing) handlePreCommitting(ctx statemachine.Context, sector SectorInf
return ctx.Send(SectorSealPreCommit1Failed{xerrors.Errorf("failed to get network version: %w", err)}) return ctx.Send(SectorSealPreCommit1Failed{xerrors.Errorf("failed to get network version: %w", err)})
} }
var msd abi.ChainEpoch msd := policy.GetMaxProveCommitDuration(actors.VersionForNetwork(nv), sector.SectorType)
if nv < build.ActorUpgradeNetworkVersion {
msd = miner0.MaxSealDuration[sector.SectorType]
} else {
// TODO: ActorUpgrade(use MaxProveCommitDuration)
msd = 0
}
if minExpiration := height + msd + miner.MinSectorExpiration + 10; expiration < minExpiration { if minExpiration := height + msd + miner.MinSectorExpiration + 10; expiration < minExpiration {
expiration = minExpiration expiration = minExpiration

View File

@ -9,7 +9,7 @@ import (
"github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/go-state-types/exitcode" "github.com/filecoin-project/go-state-types/exitcode"
"github.com/filecoin-project/specs-actors/actors/builtin/miner" miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner"
"github.com/filecoin-project/specs-storage/storage" "github.com/filecoin-project/specs-storage/storage"
sectorstorage "github.com/filecoin-project/lotus/extern/sector-storage" sectorstorage "github.com/filecoin-project/lotus/extern/sector-storage"
@ -82,7 +82,7 @@ type SectorInfo struct {
CommR *cid.Cid CommR *cid.Cid
Proof []byte Proof []byte
PreCommitInfo *miner.SectorPreCommitInfo PreCommitInfo *miner0.SectorPreCommitInfo
PreCommitDeposit big.Int PreCommitDeposit big.Int
PreCommitMessage *cid.Cid PreCommitMessage *cid.Cid
PreCommitTipSet TipSetToken PreCommitTipSet TipSetToken

5
go.mod
View File

@ -33,11 +33,12 @@ require (
github.com/filecoin-project/go-multistore v0.0.3 github.com/filecoin-project/go-multistore v0.0.3
github.com/filecoin-project/go-padreader v0.0.0-20200903213702-ed5fae088b20 github.com/filecoin-project/go-padreader v0.0.0-20200903213702-ed5fae088b20
github.com/filecoin-project/go-paramfetch v0.0.2-0.20200701152213-3e0f0afdc261 github.com/filecoin-project/go-paramfetch v0.0.2-0.20200701152213-3e0f0afdc261
github.com/filecoin-project/go-state-types v0.0.0-20200911004822-964d6c679cfc github.com/filecoin-project/go-state-types v0.0.0-20200928172055-2df22083d8ab
github.com/filecoin-project/go-statemachine v0.0.0-20200925024713-05bd7c71fbfe github.com/filecoin-project/go-statemachine v0.0.0-20200925024713-05bd7c71fbfe
github.com/filecoin-project/go-statestore v0.1.0 github.com/filecoin-project/go-statestore v0.1.0
github.com/filecoin-project/go-storedcounter v0.0.0-20200421200003-1c99c62e8a5b github.com/filecoin-project/go-storedcounter v0.0.0-20200421200003-1c99c62e8a5b
github.com/filecoin-project/specs-actors v0.9.11 github.com/filecoin-project/specs-actors v0.9.12
github.com/filecoin-project/specs-actors/v2 v2.0.0-20201002200957-bdd876b3bbe9
github.com/filecoin-project/specs-storage v0.1.1-0.20200907031224-ed2e5cd13796 github.com/filecoin-project/specs-storage v0.1.1-0.20200907031224-ed2e5cd13796
github.com/filecoin-project/test-vectors/schema v0.0.3 github.com/filecoin-project/test-vectors/schema v0.0.3
github.com/gbrlsnchs/jwt/v3 v3.0.0-beta.1 github.com/gbrlsnchs/jwt/v3 v3.0.0-beta.1

13
go.sum
View File

@ -248,6 +248,8 @@ github.com/filecoin-project/go-hamt-ipld v0.1.5 h1:uoXrKbCQZ49OHpsTCkrThPNelC4W3
github.com/filecoin-project/go-hamt-ipld v0.1.5 h1:uoXrKbCQZ49OHpsTCkrThPNelC4W3LPEk0OrS/ytIBM= github.com/filecoin-project/go-hamt-ipld v0.1.5 h1:uoXrKbCQZ49OHpsTCkrThPNelC4W3LPEk0OrS/ytIBM=
github.com/filecoin-project/go-hamt-ipld v0.1.5/go.mod h1:6Is+ONR5Cd5R6XZoCse1CWaXZc0Hdb/JeX+EQCQzX24= github.com/filecoin-project/go-hamt-ipld v0.1.5/go.mod h1:6Is+ONR5Cd5R6XZoCse1CWaXZc0Hdb/JeX+EQCQzX24=
github.com/filecoin-project/go-hamt-ipld v0.1.5/go.mod h1:6Is+ONR5Cd5R6XZoCse1CWaXZc0Hdb/JeX+EQCQzX24= github.com/filecoin-project/go-hamt-ipld v0.1.5/go.mod h1:6Is+ONR5Cd5R6XZoCse1CWaXZc0Hdb/JeX+EQCQzX24=
github.com/filecoin-project/go-hamt-ipld/v2 v2.0.0 h1:b3UDemBYN2HNfk3KOXNuxgTTxlWi3xVvbQP0IT38fvM=
github.com/filecoin-project/go-hamt-ipld/v2 v2.0.0/go.mod h1:7aWZdaQ1b16BVoQUYR+eEvrDCGJoPLxFpDynFjYfBjI=
github.com/filecoin-project/go-jsonrpc v0.1.2-0.20200822201400-474f4fdccc52 h1:FXtCp0ybqdQL9knb3OGDpkNTaBbPxgkqPeWKotUwkH0= github.com/filecoin-project/go-jsonrpc v0.1.2-0.20200822201400-474f4fdccc52 h1:FXtCp0ybqdQL9knb3OGDpkNTaBbPxgkqPeWKotUwkH0=
github.com/filecoin-project/go-jsonrpc v0.1.2-0.20200822201400-474f4fdccc52/go.mod h1:XBBpuKIMaXIIzeqzO1iucq4GvbF8CxmXRFoezRh+Cx4= github.com/filecoin-project/go-jsonrpc v0.1.2-0.20200822201400-474f4fdccc52/go.mod h1:XBBpuKIMaXIIzeqzO1iucq4GvbF8CxmXRFoezRh+Cx4=
github.com/filecoin-project/go-multistore v0.0.3 h1:vaRBY4YiA2UZFPK57RNuewypB8u0DzzQwqsL0XarpnI= github.com/filecoin-project/go-multistore v0.0.3 h1:vaRBY4YiA2UZFPK57RNuewypB8u0DzzQwqsL0XarpnI=
@ -259,8 +261,8 @@ github.com/filecoin-project/go-paramfetch v0.0.2-0.20200701152213-3e0f0afdc261/g
github.com/filecoin-project/go-state-types v0.0.0-20200903145444-247639ffa6ad/go.mod h1:IQ0MBPnonv35CJHtWSN3YY1Hz2gkPru1Q9qoaYLxx9I= github.com/filecoin-project/go-state-types v0.0.0-20200903145444-247639ffa6ad/go.mod h1:IQ0MBPnonv35CJHtWSN3YY1Hz2gkPru1Q9qoaYLxx9I=
github.com/filecoin-project/go-state-types v0.0.0-20200904021452-1883f36ca2f4/go.mod h1:IQ0MBPnonv35CJHtWSN3YY1Hz2gkPru1Q9qoaYLxx9I= github.com/filecoin-project/go-state-types v0.0.0-20200904021452-1883f36ca2f4/go.mod h1:IQ0MBPnonv35CJHtWSN3YY1Hz2gkPru1Q9qoaYLxx9I=
github.com/filecoin-project/go-state-types v0.0.0-20200905071437-95828685f9df/go.mod h1:IQ0MBPnonv35CJHtWSN3YY1Hz2gkPru1Q9qoaYLxx9I= github.com/filecoin-project/go-state-types v0.0.0-20200905071437-95828685f9df/go.mod h1:IQ0MBPnonv35CJHtWSN3YY1Hz2gkPru1Q9qoaYLxx9I=
github.com/filecoin-project/go-state-types v0.0.0-20200911004822-964d6c679cfc h1:1vr/LoqGq5m5g37Q3sNSAjfwF1uJY0zmiHcvnxY6hik= github.com/filecoin-project/go-state-types v0.0.0-20200928172055-2df22083d8ab h1:cEDC5Ei8UuT99hPWhCjA72SM9AuRtnpvdSTIYbnzN8I=
github.com/filecoin-project/go-state-types v0.0.0-20200911004822-964d6c679cfc/go.mod h1:ezYnPf0bNkTsDibL/psSz5dy4B5awOJ/E7P2Saeep8g= github.com/filecoin-project/go-state-types v0.0.0-20200928172055-2df22083d8ab/go.mod h1:ezYnPf0bNkTsDibL/psSz5dy4B5awOJ/E7P2Saeep8g=
github.com/filecoin-project/go-statemachine v0.0.0-20200714194326-a77c3ae20989/go.mod h1:FGwQgZAt2Gh5mjlwJUlVB62JeYdo+if0xWxSEfBD9ig= github.com/filecoin-project/go-statemachine v0.0.0-20200714194326-a77c3ae20989/go.mod h1:FGwQgZAt2Gh5mjlwJUlVB62JeYdo+if0xWxSEfBD9ig=
github.com/filecoin-project/go-statemachine v0.0.0-20200925024713-05bd7c71fbfe h1:dF8u+LEWeIcTcfUcCf3WFVlc81Fr2JKg8zPzIbBDKDw= github.com/filecoin-project/go-statemachine v0.0.0-20200925024713-05bd7c71fbfe h1:dF8u+LEWeIcTcfUcCf3WFVlc81Fr2JKg8zPzIbBDKDw=
github.com/filecoin-project/go-statemachine v0.0.0-20200925024713-05bd7c71fbfe/go.mod h1:FGwQgZAt2Gh5mjlwJUlVB62JeYdo+if0xWxSEfBD9ig= github.com/filecoin-project/go-statemachine v0.0.0-20200925024713-05bd7c71fbfe/go.mod h1:FGwQgZAt2Gh5mjlwJUlVB62JeYdo+if0xWxSEfBD9ig=
@ -270,8 +272,10 @@ github.com/filecoin-project/go-storedcounter v0.0.0-20200421200003-1c99c62e8a5b
github.com/filecoin-project/go-storedcounter v0.0.0-20200421200003-1c99c62e8a5b/go.mod h1:Q0GQOBtKf1oE10eSXSlhN45kDBdGvEcVOqMiffqX+N8= github.com/filecoin-project/go-storedcounter v0.0.0-20200421200003-1c99c62e8a5b/go.mod h1:Q0GQOBtKf1oE10eSXSlhN45kDBdGvEcVOqMiffqX+N8=
github.com/filecoin-project/specs-actors v0.9.4/go.mod h1:BStZQzx5x7TmCkLv0Bpa07U6cPKol6fd3w9KjMPZ6Z4= github.com/filecoin-project/specs-actors v0.9.4/go.mod h1:BStZQzx5x7TmCkLv0Bpa07U6cPKol6fd3w9KjMPZ6Z4=
github.com/filecoin-project/specs-actors v0.9.7/go.mod h1:wM2z+kwqYgXn5Z7scV1YHLyd1Q1cy0R8HfTIWQ0BFGU= github.com/filecoin-project/specs-actors v0.9.7/go.mod h1:wM2z+kwqYgXn5Z7scV1YHLyd1Q1cy0R8HfTIWQ0BFGU=
github.com/filecoin-project/specs-actors v0.9.11 h1:TnpG7HAeiUrfj0mJM7UaPW0P2137H62RGof7ftT5Mas= github.com/filecoin-project/specs-actors v0.9.12 h1:iIvk58tuMtmloFNHhAOQHG+4Gci6Lui0n7DYQGi3cJk=
github.com/filecoin-project/specs-actors v0.9.11/go.mod h1:czlvLQGEX0fjLLfdNHD7xLymy6L3n7aQzRWzsYGf+ys= github.com/filecoin-project/specs-actors v0.9.12/go.mod h1:TS1AW/7LbG+615j4NsjMK1qlpAwaFsG9w0V2tg2gSao=
github.com/filecoin-project/specs-actors/v2 v2.0.0-20201002200957-bdd876b3bbe9 h1:UXVcGwUD9GJYNcgfGbf7ok790wrunvUhl5ZlgApGhGs=
github.com/filecoin-project/specs-actors/v2 v2.0.0-20201002200957-bdd876b3bbe9/go.mod h1:52FuQUNDXq2WDg+6+UOhkqBuNc2e62h9BCIB67Bluxg=
github.com/filecoin-project/specs-storage v0.1.1-0.20200907031224-ed2e5cd13796 h1:dJsTPWpG2pcTeojO2pyn0c6l+x/3MZYCBgo/9d11JEk= github.com/filecoin-project/specs-storage v0.1.1-0.20200907031224-ed2e5cd13796 h1:dJsTPWpG2pcTeojO2pyn0c6l+x/3MZYCBgo/9d11JEk=
github.com/filecoin-project/specs-storage v0.1.1-0.20200907031224-ed2e5cd13796/go.mod h1:nJRRM7Aa9XVvygr3W9k6xGF46RWzr2zxF/iGoAIfA/g= github.com/filecoin-project/specs-storage v0.1.1-0.20200907031224-ed2e5cd13796/go.mod h1:nJRRM7Aa9XVvygr3W9k6xGF46RWzr2zxF/iGoAIfA/g=
github.com/filecoin-project/test-vectors/schema v0.0.3 h1:1zuBo25B3016inbygYLgYFdpJ2m1BDTbAOCgABRleiU= github.com/filecoin-project/test-vectors/schema v0.0.3 h1:1zuBo25B3016inbygYLgYFdpJ2m1BDTbAOCgABRleiU=
@ -1396,6 +1400,7 @@ github.com/whyrusleeping/cbor-gen v0.0.0-20200414195334-429a0b5e922e/go.mod h1:X
github.com/whyrusleeping/cbor-gen v0.0.0-20200504204219-64967432584d/go.mod h1:W5MvapuoHRP8rz4vxjwCK1pDqF1aQcWsV5PZ+AHbqdg= github.com/whyrusleeping/cbor-gen v0.0.0-20200504204219-64967432584d/go.mod h1:W5MvapuoHRP8rz4vxjwCK1pDqF1aQcWsV5PZ+AHbqdg=
github.com/whyrusleeping/cbor-gen v0.0.0-20200710004633-5379fc63235d/go.mod h1:fgkXqYy7bV2cFeIEOkVTZS/WjXARfBqSH6Q2qHL33hQ= github.com/whyrusleeping/cbor-gen v0.0.0-20200710004633-5379fc63235d/go.mod h1:fgkXqYy7bV2cFeIEOkVTZS/WjXARfBqSH6Q2qHL33hQ=
github.com/whyrusleeping/cbor-gen v0.0.0-20200715143311-227fab5a2377/go.mod h1:fgkXqYy7bV2cFeIEOkVTZS/WjXARfBqSH6Q2qHL33hQ= github.com/whyrusleeping/cbor-gen v0.0.0-20200715143311-227fab5a2377/go.mod h1:fgkXqYy7bV2cFeIEOkVTZS/WjXARfBqSH6Q2qHL33hQ=
github.com/whyrusleeping/cbor-gen v0.0.0-20200806213330-63aa96ca5488/go.mod h1:fgkXqYy7bV2cFeIEOkVTZS/WjXARfBqSH6Q2qHL33hQ=
github.com/whyrusleeping/cbor-gen v0.0.0-20200810223238-211df3b9e24c/go.mod h1:fgkXqYy7bV2cFeIEOkVTZS/WjXARfBqSH6Q2qHL33hQ= github.com/whyrusleeping/cbor-gen v0.0.0-20200810223238-211df3b9e24c/go.mod h1:fgkXqYy7bV2cFeIEOkVTZS/WjXARfBqSH6Q2qHL33hQ=
github.com/whyrusleeping/cbor-gen v0.0.0-20200812213548-958ddffe352c/go.mod h1:fgkXqYy7bV2cFeIEOkVTZS/WjXARfBqSH6Q2qHL33hQ= github.com/whyrusleeping/cbor-gen v0.0.0-20200812213548-958ddffe352c/go.mod h1:fgkXqYy7bV2cFeIEOkVTZS/WjXARfBqSH6Q2qHL33hQ=
github.com/whyrusleeping/cbor-gen v0.0.0-20200826160007-0b9f6c5fb163 h1:TtcUeY2XZSriVWR1pXyfCBWIf/NGC2iUdNw1lofUjUU= github.com/whyrusleeping/cbor-gen v0.0.0-20200826160007-0b9f6c5fb163 h1:TtcUeY2XZSriVWR1pXyfCBWIf/NGC2iUdNw1lofUjUU=

View File

@ -14,7 +14,7 @@ func TestDisabledEvents(t *testing.T) {
registry := NewEventTypeRegistry(dis) registry := NewEventTypeRegistry(dis)
reg1 := registry.RegisterEventType("system1", "disabled1") reg1 := registry.RegisterEventType("system1", "disabled1")
reg2 := registry.RegisterEventType("system2", "disabled2") reg2 := registry.RegisterEventType("system1", "disabled2")
req.False(reg1.Enabled()) req.False(reg1.Enabled())
req.False(reg2.Enabled()) req.False(reg2.Enabled())
@ -29,21 +29,21 @@ func TestDisabledEvents(t *testing.T) {
t.Run("direct", test(DisabledEvents{ t.Run("direct", test(DisabledEvents{
EventType{System: "system1", Event: "disabled1"}, EventType{System: "system1", Event: "disabled1"},
EventType{System: "system2", Event: "disabled2"}, EventType{System: "system1", Event: "disabled2"},
})) }))
dis, err := ParseDisabledEvents("system1:disabled1,system2:disabled2") dis, err := ParseDisabledEvents("system1:disabled1,system1:disabled2")
req.NoError(err) req.NoError(err)
t.Run("parsed", test(dis)) t.Run("parsed", test(dis))
dis, err = ParseDisabledEvents(" system1:disabled1 , system2:disabled2 ") dis, err = ParseDisabledEvents(" system1:disabled1 , system1:disabled2 ")
req.NoError(err) req.NoError(err)
t.Run("parsed_spaces", test(dis)) t.Run("parsed_spaces", test(dis))
} }
func TestParseDisableEvents(t *testing.T) { func TestParseDisableEvents(t *testing.T) {
_, err := ParseDisabledEvents("system1:disabled1:failed,system2:disabled2") _, err := ParseDisabledEvents("system1:disabled1:failed,system1:disabled2")
require.Error(t, err) require.Error(t, err)
} }

View File

@ -22,7 +22,7 @@ var (
// DisabledEvents is the set of event types whose journaling is suppressed. // DisabledEvents is the set of event types whose journaling is suppressed.
type DisabledEvents []EventType type DisabledEvents []EventType
// ParseDisabledEvents parses a string of the form: "system1:event1,system2:event2[,...]" // ParseDisabledEvents parses a string of the form: "system1:event1,system1:event2[,...]"
// into a DisabledEvents object, returning an error if the string failed to parse. // into a DisabledEvents object, returning an error if the string failed to parse.
// //
// It sanitizes strings via strings.TrimSpace. // It sanitizes strings via strings.TrimSpace.

Some files were not shown because too many files have changed in this diff Show More