lotus/chain/state/statetree.go

665 lines
16 KiB
Go
Raw Normal View History

package state
2019-07-05 14:29:17 +00:00
import (
2020-09-21 19:50:12 +00:00
"bytes"
2019-07-05 14:29:17 +00:00
"context"
"fmt"
2019-07-05 14:29:17 +00:00
"github.com/ipfs/go-cid"
2020-02-04 22:19:05 +00:00
cbor "github.com/ipfs/go-ipld-cbor"
logging "github.com/ipfs/go-log/v2"
2022-06-14 15:00:51 +00:00
cbg "github.com/whyrusleeping/cbor-gen"
"go.opencensus.io/trace"
2019-09-10 02:05:24 +00:00
"golang.org/x/xerrors"
"github.com/filecoin-project/go-address"
2020-09-14 11:14:06 +00:00
"github.com/filecoin-project/go-state-types/abi"
2022-11-09 08:44:51 +00:00
builtin_types "github.com/filecoin-project/go-state-types/builtin"
"github.com/filecoin-project/go-state-types/network"
states0 "github.com/filecoin-project/specs-actors/actors/states"
states2 "github.com/filecoin-project/specs-actors/v2/actors/states"
states3 "github.com/filecoin-project/specs-actors/v3/actors/states"
states4 "github.com/filecoin-project/specs-actors/v4/actors/states"
2021-05-17 20:02:23 +00:00
states5 "github.com/filecoin-project/specs-actors/v5/actors/states"
2022-06-14 15:00:51 +00:00
"github.com/filecoin-project/lotus/chain/actors/adt"
init_ "github.com/filecoin-project/lotus/chain/actors/builtin/init"
"github.com/filecoin-project/lotus/chain/types"
2019-07-05 14:29:17 +00:00
)
var log = logging.Logger("statetree")
// StateTree stores actors state by their ID.
2019-07-05 14:29:17 +00:00
type StateTree struct {
root adt.Map
version types.StateTreeVersion
info cid.Cid
Store cbor.IpldStore
lookupIDFun func(address.Address) (address.Address, error)
2019-07-05 14:29:17 +00:00
snaps *stateSnaps
}
type stateSnaps struct {
layers []*stateSnapLayer
lastMaybeNonEmptyResolveCache int
}
type stateSnapLayer struct {
actors map[address.Address]streeOp
resolveCache map[address.Address]address.Address
}
func newStateSnapLayer() *stateSnapLayer {
return &stateSnapLayer{
actors: make(map[address.Address]streeOp),
resolveCache: make(map[address.Address]address.Address),
}
}
type streeOp struct {
Act types.Actor
Delete bool
}
func newStateSnaps() *stateSnaps {
ss := &stateSnaps{}
ss.addLayer()
return ss
}
func (ss *stateSnaps) addLayer() {
ss.layers = append(ss.layers, newStateSnapLayer())
}
func (ss *stateSnaps) dropLayer() {
ss.layers[len(ss.layers)-1] = nil // allow it to be GCed
ss.layers = ss.layers[:len(ss.layers)-1]
if ss.lastMaybeNonEmptyResolveCache == len(ss.layers) {
ss.lastMaybeNonEmptyResolveCache = len(ss.layers) - 1
}
}
func (ss *stateSnaps) mergeLastLayer() {
last := ss.layers[len(ss.layers)-1]
nextLast := ss.layers[len(ss.layers)-2]
for k, v := range last.actors {
nextLast.actors[k] = v
}
for k, v := range last.resolveCache {
nextLast.resolveCache[k] = v
}
ss.dropLayer()
}
func (ss *stateSnaps) resolveAddress(addr address.Address) (address.Address, bool) {
for i := ss.lastMaybeNonEmptyResolveCache; i >= 0; i-- {
if len(ss.layers[i].resolveCache) == 0 {
if ss.lastMaybeNonEmptyResolveCache == i {
ss.lastMaybeNonEmptyResolveCache = i - 1
}
continue
}
resa, ok := ss.layers[i].resolveCache[addr]
if ok {
return resa, true
}
}
return address.Undef, false
}
func (ss *stateSnaps) cacheResolveAddress(addr, resa address.Address) {
ss.layers[len(ss.layers)-1].resolveCache[addr] = resa
ss.lastMaybeNonEmptyResolveCache = len(ss.layers) - 1
}
func (ss *stateSnaps) getActor(addr address.Address) (*types.Actor, error) {
for i := len(ss.layers) - 1; i >= 0; i-- {
act, ok := ss.layers[i].actors[addr]
if ok {
if act.Delete {
return nil, types.ErrActorNotFound
}
return &act.Act, nil
}
}
return nil, nil
}
func (ss *stateSnaps) setActor(addr address.Address, act *types.Actor) {
ss.layers[len(ss.layers)-1].actors[addr] = streeOp{Act: *act}
}
func (ss *stateSnaps) deleteActor(addr address.Address) {
ss.layers[len(ss.layers)-1].actors[addr] = streeOp{Delete: true}
2019-07-05 14:29:17 +00:00
}
// VersionForNetwork returns the state tree version for the given network
// version.
func VersionForNetwork(ver network.Version) (types.StateTreeVersion, error) {
switch ver {
case network.Version0, network.Version1, network.Version2, network.Version3:
return types.StateTreeVersion0, nil
case network.Version4, network.Version5, network.Version6, network.Version7, network.Version8, network.Version9:
return types.StateTreeVersion1, nil
case network.Version10, network.Version11:
return types.StateTreeVersion2, nil
case network.Version12:
return types.StateTreeVersion3, nil
2021-10-18 15:46:50 +00:00
case network.Version13, network.Version14, network.Version15, network.Version16, network.Version17:
return types.StateTreeVersion4, nil
2021-10-18 15:46:50 +00:00
case network.Version18, network.Version19, network.Version20:
return types.StateTreeVersion5, nil
2021-10-18 15:46:50 +00:00
default:
panic(fmt.Sprintf("unsupported network version %d", ver))
}
}
func NewStateTree(cst cbor.IpldStore, ver types.StateTreeVersion) (*StateTree, error) {
2020-09-14 22:43:12 +00:00
var info cid.Cid
switch ver {
case types.StateTreeVersion0:
2020-09-14 22:43:12 +00:00
// info is undefined
2022-11-09 08:44:51 +00:00
case types.StateTreeVersion1, types.StateTreeVersion2, types.StateTreeVersion3, types.StateTreeVersion4, types.StateTreeVersion5:
2020-09-25 19:55:10 +00:00
var err error
info, err = cst.Put(context.TODO(), new(types.StateInfo0))
2020-09-25 19:55:10 +00:00
if err != nil {
return nil, err
}
2020-09-14 22:43:12 +00:00
default:
return nil, xerrors.Errorf("unsupported state tree version: %d", ver)
2020-09-14 22:43:12 +00:00
}
store := adt.WrapStore(context.TODO(), cst)
var hamt adt.Map
switch ver {
case types.StateTreeVersion0:
tree, err := states0.NewTree(store)
if err != nil {
return nil, xerrors.Errorf("failed to create state tree: %w", err)
}
hamt = tree.Map
case types.StateTreeVersion1:
tree, err := states2.NewTree(store)
if err != nil {
return nil, xerrors.Errorf("failed to create state tree: %w", err)
}
hamt = tree.Map
case types.StateTreeVersion2:
tree, err := states3.NewTree(store)
if err != nil {
return nil, xerrors.Errorf("failed to create state tree: %w", err)
}
hamt = tree.Map
case types.StateTreeVersion3:
tree, err := states4.NewTree(store)
if err != nil {
return nil, xerrors.Errorf("failed to create state tree: %w", err)
}
hamt = tree.Map
2021-05-17 20:02:23 +00:00
case types.StateTreeVersion4:
tree, err := states5.NewTree(store)
if err != nil {
return nil, xerrors.Errorf("failed to create state tree: %w", err)
}
hamt = tree.Map
2022-11-09 08:44:51 +00:00
case types.StateTreeVersion5:
tree, err := builtin_types.NewTree(store)
if err != nil {
return nil, xerrors.Errorf("failed to create state tree: %w", err)
}
hamt = tree.Map
default:
return nil, xerrors.Errorf("unsupported state tree version: %d", ver)
2020-09-14 11:14:06 +00:00
}
s := &StateTree{
root: hamt,
2020-09-14 22:43:12 +00:00
info: info,
version: ver,
2020-09-14 22:43:12 +00:00
Store: cst,
snaps: newStateSnaps(),
}
s.lookupIDFun = s.lookupIDinternal
return s, nil
2019-07-05 14:29:17 +00:00
}
2020-09-14 22:43:12 +00:00
func LoadStateTree(cst cbor.IpldStore, c cid.Cid) (*StateTree, error) {
var root types.StateRoot
// Try loading as a new-style state-tree (version/actors tuple).
if err := cst.Get(context.TODO(), c, &root); err != nil {
// We failed to decode as the new version, must be an old version.
root.Actors = c
root.Version = types.StateTreeVersion0
2020-09-14 22:43:12 +00:00
}
store := adt.WrapStore(context.TODO(), cst)
2021-01-19 01:10:14 +00:00
var (
hamt adt.Map
err error
)
switch root.Version {
case types.StateTreeVersion0:
2021-01-19 01:10:14 +00:00
var tree *states0.Tree
tree, err = states0.LoadTree(store, root.Actors)
if tree != nil {
hamt = tree.Map
}
case types.StateTreeVersion1:
2021-01-19 01:10:14 +00:00
var tree *states2.Tree
tree, err = states2.LoadTree(store, root.Actors)
if tree != nil {
hamt = tree.Map
}
case types.StateTreeVersion2:
2021-01-19 01:10:14 +00:00
var tree *states3.Tree
tree, err = states3.LoadTree(store, root.Actors)
if tree != nil {
hamt = tree.Map
}
case types.StateTreeVersion3:
var tree *states4.Tree
tree, err = states4.LoadTree(store, root.Actors)
if tree != nil {
hamt = tree.Map
}
2021-05-17 20:02:23 +00:00
case types.StateTreeVersion4:
var tree *states5.Tree
tree, err = states5.LoadTree(store, root.Actors)
if tree != nil {
hamt = tree.Map
}
2022-11-09 08:44:51 +00:00
case types.StateTreeVersion5:
var tree *builtin_types.ActorTree
tree, err = builtin_types.LoadTree(store, root.Actors)
if tree != nil {
hamt = tree.Map
}
2020-09-14 22:43:12 +00:00
default:
return nil, xerrors.Errorf("unsupported state tree version: %d", root.Version)
}
2021-01-19 01:10:14 +00:00
if err != nil {
log.Errorf("failed to load state tree: %s", err)
return nil, xerrors.Errorf("failed to load state tree %s: %w", c, err)
2021-01-19 01:10:14 +00:00
}
s := &StateTree{
root: hamt,
info: root.Info,
version: root.Version,
Store: cst,
snaps: newStateSnaps(),
}
s.lookupIDFun = s.lookupIDinternal
return s, nil
2019-07-05 14:29:17 +00:00
}
func (st *StateTree) SetActor(addr address.Address, act *types.Actor) error {
2019-11-15 16:39:43 +00:00
iaddr, err := st.LookupID(addr)
if err != nil {
return xerrors.Errorf("ID lookup failed: %w", err)
2019-07-05 14:29:17 +00:00
}
2019-11-15 16:39:43 +00:00
addr = iaddr
2019-07-05 14:29:17 +00:00
st.snaps.setActor(addr, act)
return nil
2019-07-05 14:29:17 +00:00
}
func (st *StateTree) lookupIDinternal(addr address.Address) (address.Address, error) {
2020-09-14 22:43:12 +00:00
act, err := st.GetActor(init_.Address)
2019-07-05 14:29:17 +00:00
if err != nil {
2019-09-10 02:05:24 +00:00
return address.Undef, xerrors.Errorf("getting init actor: %w", err)
2019-07-05 14:29:17 +00:00
}
2020-09-14 11:14:06 +00:00
ias, err := init_.Load(&AdtStore{st.Store}, act)
if err != nil {
2019-09-10 02:05:24 +00:00
return address.Undef, xerrors.Errorf("loading init actor state: %w", err)
2019-07-05 14:29:17 +00:00
}
a, found, err := ias.ResolveAddress(addr)
if err == nil && !found {
err = types.ErrActorNotFound
}
2020-02-22 13:10:46 +00:00
if err != nil {
return address.Undef, xerrors.Errorf("resolve address %s: %w", addr, err)
}
return a, err
}
// LookupID gets the ID address of this actor's `addr` stored in the `InitActor`.
func (st *StateTree) LookupID(addr address.Address) (address.Address, error) {
if addr.Protocol() == address.ID {
return addr, nil
}
resa, ok := st.snaps.resolveAddress(addr)
if ok {
return resa, nil
}
a, err := st.lookupIDFun(addr)
if err != nil {
return a, err
}
st.snaps.cacheResolveAddress(addr, a)
2020-02-22 13:10:46 +00:00
return a, nil
2019-07-05 14:29:17 +00:00
}
// GetActor returns the actor from any type of `addr` provided.
func (st *StateTree) GetActor(addr address.Address) (*types.Actor, error) {
if addr == address.Undef {
return nil, fmt.Errorf("GetActor called on undefined address")
}
// Transform `addr` to its ID format.
2019-11-15 16:39:43 +00:00
iaddr, err := st.LookupID(addr)
if err != nil {
if xerrors.Is(err, types.ErrActorNotFound) {
2020-02-22 13:10:46 +00:00
return nil, xerrors.Errorf("resolution lookup failed (%s): %w", addr, err)
2019-07-05 14:29:17 +00:00
}
2019-11-15 16:39:43 +00:00
return nil, xerrors.Errorf("address resolution: %w", err)
2019-07-05 14:29:17 +00:00
}
2019-11-15 16:39:43 +00:00
addr = iaddr
2019-07-05 14:29:17 +00:00
snapAct, err := st.snaps.getActor(addr)
if err != nil {
return nil, err
}
if snapAct != nil {
return snapAct, nil
2019-07-05 14:29:17 +00:00
}
2019-09-17 01:56:37 +00:00
var act types.Actor
2022-11-09 08:44:51 +00:00
var found bool
if st.version <= types.StateTreeVersion4 {
var act4 types.ActorV4
found, err = st.root.Get(abi.AddrKey(addr), &act4)
if found {
act = *types.AsActorV5(&act4)
}
} else {
found, err = st.root.Get(abi.AddrKey(addr), &act)
}
if err != nil {
2019-09-30 23:55:35 +00:00
return nil, xerrors.Errorf("hamt find failed: %w", err)
} else if !found {
return nil, types.ErrActorNotFound
2019-07-05 14:29:17 +00:00
}
st.snaps.setActor(addr, &act)
2019-07-05 14:29:17 +00:00
return &act, nil
}
func (st *StateTree) DeleteActor(addr address.Address) error {
if addr == address.Undef {
return xerrors.Errorf("DeleteActor called on undefined address")
}
iaddr, err := st.LookupID(addr)
if err != nil {
if xerrors.Is(err, types.ErrActorNotFound) {
return xerrors.Errorf("resolution lookup failed (%s): %w", addr, err)
}
return xerrors.Errorf("address resolution: %w", err)
}
addr = iaddr
_, err = st.GetActor(addr)
if err != nil {
return err
}
st.snaps.deleteActor(addr)
return nil
}
func (st *StateTree) Flush(ctx context.Context) (cid.Cid, error) {
ctx, span := trace.StartSpan(ctx, "stateTree.Flush") //nolint:staticcheck
defer span.End()
if len(st.snaps.layers) != 1 {
return cid.Undef, xerrors.Errorf("tried to flush state tree with snapshots on the stack")
}
for addr, sto := range st.snaps.layers[0].actors {
if sto.Delete {
2020-09-14 11:14:06 +00:00
if err := st.root.Delete(abi.AddrKey(addr)); err != nil {
return cid.Undef, err
}
} else {
2022-11-09 08:44:51 +00:00
if st.version <= types.StateTreeVersion4 {
act4 := types.AsActorV4(&sto.Act)
if err := st.root.Put(abi.AddrKey(addr), act4); err != nil {
return cid.Undef, err
}
} else {
if err := st.root.Put(abi.AddrKey(addr), &sto.Act); err != nil {
return cid.Undef, err
}
}
2019-07-05 14:29:17 +00:00
}
}
2020-09-14 22:43:12 +00:00
root, err := st.root.Root()
if err != nil {
return cid.Undef, xerrors.Errorf("failed to flush state-tree hamt: %w", err)
}
// If we're version 0, return a raw tree.
if st.version == types.StateTreeVersion0 {
2020-09-14 22:43:12 +00:00
return root, nil
}
// Otherwise, return a versioned tree.
return st.Store.Put(ctx, &types.StateRoot{Version: st.version, Actors: root, Info: st.info})
2019-07-05 14:29:17 +00:00
}
func (st *StateTree) Snapshot(ctx context.Context) error {
ctx, span := trace.StartSpan(ctx, "stateTree.SnapShot") //nolint:staticcheck
defer span.End()
st.snaps.addLayer()
2019-07-05 14:29:17 +00:00
return nil
}
func (st *StateTree) ClearSnapshot() {
st.snaps.mergeLastLayer()
}
func (st *StateTree) RegisterNewAddress(addr address.Address) (address.Address, error) {
2019-07-05 14:29:17 +00:00
var out address.Address
2020-09-14 22:43:12 +00:00
err := st.MutateActor(init_.Address, func(initact *types.Actor) error {
2020-09-14 11:14:06 +00:00
ias, err := init_.Load(&AdtStore{st.Store}, initact)
if err != nil {
2019-07-05 14:29:17 +00:00
return err
}
oaddr, err := ias.MapAddressToNewID(addr)
2019-07-05 14:29:17 +00:00
if err != nil {
return err
}
out = oaddr
ncid, err := st.Store.Put(context.TODO(), ias)
2019-07-05 14:29:17 +00:00
if err != nil {
return err
}
initact.Head = ncid
return nil
})
if err != nil {
return address.Undef, err
}
return out, nil
}
2020-02-18 21:37:59 +00:00
type AdtStore struct{ cbor.IpldStore }
2020-02-12 07:22:55 +00:00
2020-02-18 21:37:59 +00:00
func (a *AdtStore) Context() context.Context {
2020-02-12 07:22:55 +00:00
return context.TODO()
}
2020-02-18 21:37:59 +00:00
var _ adt.Store = (*AdtStore)(nil)
2020-02-12 07:22:55 +00:00
2019-07-05 14:29:17 +00:00
func (st *StateTree) Revert() error {
st.snaps.dropLayer()
st.snaps.addLayer()
2019-07-05 14:29:17 +00:00
return nil
}
func (st *StateTree) MutateActor(addr address.Address, f func(*types.Actor) error) error {
2019-07-05 14:29:17 +00:00
act, err := st.GetActor(addr)
if err != nil {
return err
}
if err := f(act); err != nil {
return err
}
return st.SetActor(addr, act)
}
func (st *StateTree) ForEach(f func(address.Address, *types.Actor) error) error {
// Walk through layers, if any.
seen := make(map[address.Address]struct{})
for i := len(st.snaps.layers) - 1; i >= 0; i-- {
for addr, op := range st.snaps.layers[i].actors {
if _, ok := seen[addr]; ok {
continue
}
seen[addr] = struct{}{}
if op.Delete {
continue
}
act := op.Act // copy
if err := f(addr, &act); err != nil {
return err
}
}
}
// Now walk through the saved actors.
2022-11-09 08:44:51 +00:00
if st.version <= types.StateTreeVersion4 {
var act types.ActorV4
return st.root.ForEach(&act, func(k string) error {
act := act // copy
addr, err := address.NewFromBytes([]byte(k))
if err != nil {
return xerrors.Errorf("invalid address (%x) found in state tree key: %w", []byte(k), err)
}
2022-11-09 08:44:51 +00:00
// no need to record anything here, there are no duplicates in the actors HAMT
// iself.
if _, ok := seen[addr]; ok {
return nil
}
2022-11-09 08:44:51 +00:00
return f(addr, types.AsActorV5(&act))
})
2022-11-09 09:38:16 +00:00
}
2022-11-09 08:44:51 +00:00
2022-11-09 09:38:16 +00:00
var act types.Actor
return st.root.ForEach(&act, func(k string) error {
act := act // copy
addr, err := address.NewFromBytes([]byte(k))
if err != nil {
return xerrors.Errorf("invalid address (%x) found in state tree key: %w", []byte(k), err)
}
2022-11-09 08:44:51 +00:00
2022-11-09 09:38:16 +00:00
// no need to record anything here, there are no duplicates in the actors HAMT
// iself.
if _, ok := seen[addr]; ok {
return nil
}
return f(addr, &act)
})
}
2020-09-21 19:50:12 +00:00
// Version returns the version of the StateTree data structure in use.
func (st *StateTree) Version() types.StateTreeVersion {
return st.version
}
func Diff(ctx context.Context, oldTree, newTree *StateTree) (map[string]types.Actor, error) {
2020-09-21 19:50:12 +00:00
out := map[string]types.Actor{}
var (
ncval, ocval cbg.Deferred
buf = bytes.NewReader(nil)
)
if err := newTree.root.ForEach(&ncval, func(k string) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
addr, err := address.NewFromBytes([]byte(k))
if err != nil {
return xerrors.Errorf("address in state tree was not valid: %w", err)
}
2020-09-21 19:50:12 +00:00
found, err := oldTree.root.Get(abi.AddrKey(addr), &ocval)
if err != nil {
return err
}
2020-09-21 19:50:12 +00:00
if found && bytes.Equal(ocval.Raw, ncval.Raw) {
return nil // not changed
}
2020-09-21 19:50:12 +00:00
2022-11-09 08:44:51 +00:00
if newTree.version <= types.StateTreeVersion4 {
var act types.ActorV4
2020-09-21 19:50:12 +00:00
2022-11-09 08:44:51 +00:00
buf.Reset(ncval.Raw)
err = act.UnmarshalCBOR(buf)
buf.Reset(nil)
if err != nil {
return err
}
2020-09-21 19:50:12 +00:00
2022-11-09 08:44:51 +00:00
out[addr.String()] = *types.AsActorV5(&act)
} else {
var act types.Actor
buf.Reset(ncval.Raw)
err = act.UnmarshalCBOR(buf)
buf.Reset(nil)
if err != nil {
return err
}
out[addr.String()] = act
}
2020-09-21 19:50:12 +00:00
return nil
}
2020-09-21 19:50:12 +00:00
}); err != nil {
return nil, err
}
return out, nil
}