github.com/filecoin-project/specs-actors/v4@v4.0.2/actors/runtime/runtime.go (about)

     1  package runtime
     2  
     3  import (
     4  	"context"
     5  
     6  	addr "github.com/filecoin-project/go-address"
     7  	"github.com/filecoin-project/go-state-types/abi"
     8  	"github.com/filecoin-project/go-state-types/cbor"
     9  	"github.com/filecoin-project/go-state-types/crypto"
    10  	"github.com/filecoin-project/go-state-types/exitcode"
    11  	"github.com/filecoin-project/go-state-types/network"
    12  	"github.com/filecoin-project/go-state-types/rt"
    13  	cid "github.com/ipfs/go-cid"
    14  
    15  	"github.com/filecoin-project/specs-actors/v4/actors/runtime/proof"
    16  )
    17  
    18  // Interfaces for the runtime.
    19  // These interfaces are not aliased onto prior versions even if they match exactly.
    20  // Go's implicit interface satisfaction should mean that a single concrete type can satisfy
    21  // many versions at the same time.
    22  
    23  // Runtime is the interface to the execution environment for actor methods..
    24  // This is everything that is accessible to actors, beyond parameters.
    25  type Runtime interface {
    26  	// Information related to the current message being executed.
    27  	// When an actor invokes a method on another actor as a sub-call, these values reflect
    28  	// the sub-call context, rather than the top-level context.
    29  	Message
    30  
    31  	// Provides a handle for the actor's state object.
    32  	StateHandle
    33  
    34  	// Provides IPLD storage for actor state
    35  	Store
    36  
    37  	// Provides the system call interface.
    38  	Syscalls
    39  
    40  	// The network protocol version number at the current epoch.
    41  	NetworkVersion() network.Version
    42  
    43  	// The current chain epoch number. The genesis block has epoch zero.
    44  	CurrEpoch() abi.ChainEpoch
    45  
    46  	// Satisfies the requirement that every exported actor method must invoke at least one caller validation
    47  	// method before returning, without making any assertions about the caller.
    48  	ValidateImmediateCallerAcceptAny()
    49  
    50  	// Validates that the immediate caller's address exactly matches one of a set of expected addresses,
    51  	// aborting if it does not.
    52  	// The caller address is always normalized to an ID address, so expected addresses must be
    53  	// ID addresses to have any expectation of passing validation.
    54  	ValidateImmediateCallerIs(addrs ...addr.Address)
    55  
    56  	// Validates that the immediate caller is an actor with code CID matching one of a set of
    57  	// expected CIDs, aborting if it does not.
    58  	ValidateImmediateCallerType(types ...cid.Cid)
    59  
    60  	// The balance of the receiver. Always >= zero.
    61  	CurrentBalance() abi.TokenAmount
    62  
    63  	// Resolves an address of any protocol to an ID address (via the Init actor's table).
    64  	// This allows resolution of externally-provided SECP, BLS, or actor addresses to the canonical form.
    65  	// If the argument is an ID address it is returned directly.
    66  	ResolveAddress(address addr.Address) (addr.Address, bool)
    67  
    68  	// Look up the code ID at an actor address.
    69  	// The address will be resolved as if via ResolveAddress, if necessary, so need not be an ID-address.
    70  	GetActorCodeCID(addr addr.Address) (ret cid.Cid, ok bool)
    71  
    72  	// GetRandomnessFromBeacon returns a (pseudo)random byte array drawing from a random beacon at a prior epoch.
    73  	// The beacon value is combined with the personalization tag, epoch number, and explicitly provided entropy.
    74  	// The personalization tag may be any int64 value.
    75  	// The epoch must be less than the current epoch. The epoch may be negative, in which case
    76  	// it addresses the beacon value from genesis block.
    77  	// The entropy may be any byte array, or nil.
    78  	GetRandomnessFromBeacon(personalization crypto.DomainSeparationTag, randEpoch abi.ChainEpoch, entropy []byte) abi.Randomness
    79  
    80  	// GetRandomnessFromTickets samples randomness from the ticket chain. Randomess
    81  	// sampled through this method is unique per potential fork, and as a
    82  	// result, processes relying on this randomness are tied to whichever fork
    83  	// they choose.
    84  	// See GetRandomnessFromBeacon for notes about the personalization tag, epoch, and entropy.
    85  	GetRandomnessFromTickets(personalization crypto.DomainSeparationTag, randEpoch abi.ChainEpoch, entropy []byte) abi.Randomness
    86  
    87  	// Sends a message to another actor, returning the exit code and return value envelope.
    88  	// If the invoked method does not return successfully, its state changes (and that of any messages it sent in turn)
    89  	// will be rolled back.
    90  	Send(toAddr addr.Address, methodNum abi.MethodNum, params cbor.Marshaler, value abi.TokenAmount, out cbor.Er) exitcode.ExitCode
    91  
    92  	// Halts execution upon an error from which the receiver cannot recover. The caller will receive the exitcode and
    93  	// an empty return value. State changes made within this call will be rolled back.
    94  	// This method does not return.
    95  	// The provided exit code must be >= exitcode.FirstActorExitCode.
    96  	// The message and args are for diagnostic purposes and do not persist on chain. They should be suitable for
    97  	// passing to fmt.Errorf(msg, args...).
    98  	Abortf(errExitCode exitcode.ExitCode, msg string, args ...interface{})
    99  
   100  	// Computes an address for a new actor. The returned address is intended to uniquely refer to
   101  	// the actor even in the event of a chain re-org (whereas an ID-address might refer to a
   102  	// different actor after messages are re-ordered).
   103  	// Always an ActorExec address.
   104  	NewActorAddress() addr.Address
   105  
   106  	// Creates an actor with code `codeID` and address `address`, with empty state.
   107  	// May only be called by Init actor.
   108  	// Aborts if the provided address has previously been created.
   109  	CreateActor(codeId cid.Cid, address addr.Address)
   110  
   111  	// Deletes the executing actor from the state tree, transferring any balance to beneficiary.
   112  	// Aborts if the beneficiary does not exist or is the calling actor.
   113  	// May only be called by the actor itself.
   114  	DeleteActor(beneficiary addr.Address)
   115  
   116  	// Returns the total token supply in circulation at the beginning of the current epoch.
   117  	// The circulating supply is the sum of:
   118  	// - rewards emitted by the reward actor,
   119  	// - funds vested from lock-ups in the genesis state,
   120  	// less the sum of:
   121  	// - funds burnt,
   122  	// - pledge collateral locked in storage miner actors (recorded in the storage power actor)
   123  	// - deal collateral locked by the storage market actor
   124  	TotalFilCircSupply() abi.TokenAmount
   125  
   126  	// Provides a Go context for use by HAMT, etc.
   127  	// The VM is intended to provide an idealised machine abstraction, with infinite storage etc, so this context
   128  	// should not be used by actor code directly.
   129  	Context() context.Context
   130  
   131  	// Starts a new tracing span. The span must be End()ed explicitly by invoking or deferring EndSpan
   132  	StartSpan(name string) (EndSpan func())
   133  
   134  	// ChargeGas charges specified amount of `gas` for execution.
   135  	// `name` provides information about gas charging point
   136  	// `virtual` sets virtual amount of gas to charge, this amount is not counted
   137  	// toward execution cost. This functionality is used for observing global changes
   138  	// in total gas charged if amount of gas charged was to be changed.
   139  	ChargeGas(name string, gas int64, virtual int64)
   140  
   141  	// Note events that may make debugging easier
   142  	Log(level rt.LogLevel, msg string, args ...interface{})
   143  }
   144  
   145  // Store defines the storage module exposed to actors.
   146  type Store interface {
   147  	// Retrieves and deserializes an object from the store into `o`. Returns whether successful.
   148  	StoreGet(c cid.Cid, o cbor.Unmarshaler) bool
   149  	// Serializes and stores an object, returning its CID.
   150  	StorePut(x cbor.Marshaler) cid.Cid
   151  }
   152  
   153  // Message contains information available to the actor about the executing message.
   154  // These values are fixed for the duration of an invocation.
   155  type Message interface {
   156  	// The address of the immediate calling actor. Always an ID-address.
   157  	// If an actor invokes its own method, Caller() == Receiver().
   158  	Caller() addr.Address
   159  
   160  	// The address of the actor receiving the message. Always an ID-address.
   161  	Receiver() addr.Address
   162  
   163  	// The value attached to the message being processed, implicitly added to CurrentBalance()
   164  	// of Receiver() before method invocation.
   165  	// This value came from Caller().
   166  	ValueReceived() abi.TokenAmount
   167  }
   168  
   169  // Pure functions implemented as primitives by the runtime.
   170  type Syscalls interface {
   171  	// Verifies that a signature is valid for an address and plaintext.
   172  	// If the address is a public-key type address, it is used directly.
   173  	// If it's an ID-address, the actor is looked up in state. It must be an account actor, and the
   174  	// public key is obtained from it's state.
   175  	VerifySignature(signature crypto.Signature, signer addr.Address, plaintext []byte) error
   176  	// Hashes input data using blake2b with 256 bit output.
   177  	HashBlake2b(data []byte) [32]byte
   178  	// Computes an unsealed sector CID (CommD) from its constituent piece CIDs (CommPs) and sizes.
   179  	ComputeUnsealedSectorCID(reg abi.RegisteredSealProof, pieces []abi.PieceInfo) (cid.Cid, error)
   180  	// Verifies a sector seal proof.
   181  	// Deprecated and un-used.
   182  	VerifySeal(vi proof.SealVerifyInfo) error
   183  
   184  	BatchVerifySeals(vis map[addr.Address][]proof.SealVerifyInfo) (map[addr.Address][]bool, error)
   185  
   186  	// Verifies a proof of spacetime.
   187  	VerifyPoSt(vi proof.WindowPoStVerifyInfo) error
   188  	// Verifies that two block headers provide proof of a consensus fault:
   189  	// - both headers mined by the same actor
   190  	// - headers are different
   191  	// - first header is of the same or lower epoch as the second
   192  	// - the headers provide evidence of a fault (see the spec for the different fault types).
   193  	// The parameters are all serialized block headers. The third "extra" parameter is consulted only for
   194  	// the "parent grinding fault", in which case it must be the sibling of h1 (same parent tipset) and one of the
   195  	// blocks in an ancestor of h2.
   196  	// Returns nil and an error if the headers don't prove a fault.
   197  	VerifyConsensusFault(h1, h2, extra []byte) (*ConsensusFault, error)
   198  }
   199  
   200  // StateHandle provides mutable, exclusive access to actor state.
   201  type StateHandle interface {
   202  	// Create initializes the state object.
   203  	// This is only valid in a constructor function and when the state has not yet been initialized.
   204  	StateCreate(obj cbor.Marshaler)
   205  
   206  	// Readonly loads a readonly copy of the state into the argument.
   207  	//
   208  	// Any modification to the state is illegal and will result in an abort.
   209  	StateReadonly(obj cbor.Unmarshaler)
   210  
   211  	// Transaction loads a mutable version of the state into the `obj` argument and protects
   212  	// the execution from side effects (including message send).
   213  	//
   214  	// The second argument is a function which allows the caller to mutate the state.
   215  	//
   216  	// If the state is modified after this function returns, execution will abort.
   217  	//
   218  	// The gas cost of this method is that of a Store.Put of the mutated state object.
   219  	//
   220  	// Note: the Go signature is not ideal due to lack of type system power.
   221  	//
   222  	// # Usage
   223  	// ```go
   224  	// var state SomeState
   225  	// rt.StateTransaction(&state, func() {
   226  	// 	// make some changes
   227  	// 	state.ImLoaded = true
   228  	// })
   229  	// // state.ImLoaded = false // BAD!! state is readonly outside the lambda, it will panic
   230  	// ```
   231  	StateTransaction(obj cbor.Er, f func())
   232  }