evm

package
v0.12.9-rc.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 8, 2023 License: GPL-3.0, LGPL-3.0 Imports: 104 Imported by: 18

README

EVM Package

The EVM package implements the AvalancheGo VM interface.

VM

The VM creates the Ethereum backend and provides basic block building, parsing, and retrieval logic to the consensus engine.

APIs

The VM creates APIs for the node through the function CreateHandlers(). CreateHandlers returns the Service struct to serve Coreth specific APIs. Additionally, the Ethereum backend APIs are also returned at the /rpc extension.

Block Handling

The VM implements buildBlock, parseBlock, and getBlock and uses the chain package from AvalancheGo to construct a metered state, which uses these functions to implement an efficient caching layer and maintain the required invariants for blocks that get returned to the consensus engine.

To do this, the VM uses a modified version of the Ethereum RLP block type here and uses the core package's BlockChain type here to handle the insertion and storage of blocks into the chain.

Block

The Block type implements the AvalancheGo ChainVM Block interface. The key functions for this interface are Verify(), Accept(), Reject(), and Status().

The Block type wraps the stateless block type here and implements these functions to allow the consensus engine to verify blocks as valid, perform consensus, and mark them as accepted or rejected. See the documentation in AvalancheGo for the more detailed VM invariants that are maintained here.

Atomic Transactions

Atomic transactions utilize Shared Memory (documented here) to send assets to the P-Chain and X-Chain.

Operations on shared memory cannot be reverted, so atomic transactions must separate their verification and processing into two stages: verifying the transaction as valid to be performed within its block and actually performing the operation. For example, once an export transaction is accepted, there is no way for the C-Chain to take that asset back and it can be imported immediately by the recipient chain.

The C-Chain uses the account model for its own state, but atomic transactions must be compatible with the P-Chain and X-Chain, such that C-Chain atomic transactions must transform between the account model and the UTXO model.

Documentation

Index

Constants

View Source
const (
	GenesisTestAddr = "0x751a0b96e1042bee789452ecb20253fba40dbe85"
	GenesisTestKey  = "0xabd71b35d559563fea757f0f5edbde286fb8c043105b15abb7cd57189306d7d1"
)

test constants

Variables

Constants for calculating the gas consumed by atomic transactions

View Source
var (
	// GitCommit is set by the build script
	GitCommit string
	// Version is the version of Coreth
	Version string = "v0.12.9"
)

Codec does serialization and deserialization

View Source
var (
	// ID this VM should be referenced by
	ID = ids.ID{'e', 'v', 'm'}
)

Functions

func CalculateDynamicFee added in v0.12.5

func CalculateDynamicFee(cost uint64, baseFee *big.Int) (uint64, error)

calculates the amount of AVAX that must be burned by an atomic transaction that consumes [cost] at [baseFee].

func CorethJSONFormat added in v0.8.15

func CorethJSONFormat(alias string) log.Format

func CorethTermFormat added in v0.8.15

func CorethTermFormat(alias string) log.Format

func GetEthAddress added in v0.8.13

func GetEthAddress(privKey *secp256k1.PrivateKey) common.Address

GetEthAddress returns the ethereum address derived from [privKey]

func NewAtomicTxRepository added in v0.8.13

func NewAtomicTxRepository(
	db *versiondb.Database, codec codec.Manager, lastAcceptedHeight uint64,
	bonusBlocks map[uint64]ids.ID, canonicalBlocks []uint64,
	getAtomicTxFromBlockByHeight func(height uint64) (*Tx, error),
) (*atomicTxRepository, error)

func NewSharedMemoryWriter

func NewSharedMemoryWriter() *sharedMemoryWriter

func ParseEthAddress added in v0.8.13

func ParseEthAddress(addrStr string) (common.Address, error)

ParseEthAddress parses [addrStr] and returns an Ethereum address

func PublicKeyToEthAddress added in v0.8.13

func PublicKeyToEthAddress(pubKey *secp256k1.PublicKey) common.Address

PublicKeyToEthAddress returns the ethereum address derived from [pubKey]

func SortEVMInputsAndSigners added in v0.8.13

func SortEVMInputsAndSigners(inputs []EVMInput, signers [][]*secp256k1.PrivateKey)

SortEVMInputsAndSigners sorts the list of EVMInputs based on the addresses and assetIDs

Types

type Admin added in v0.8.13

type Admin struct {
	// contains filtered or unexported fields
}

Admin is the API service for admin API calls

func NewAdminService added in v0.8.13

func NewAdminService(vm *VM, performanceDir string) *Admin

func (*Admin) GetVMConfig added in v0.8.13

func (p *Admin) GetVMConfig(_ *http.Request, _ *struct{}, reply *ConfigReply) error

func (*Admin) LockProfile added in v0.8.13

func (p *Admin) LockProfile(_ *http.Request, _ *struct{}, _ *api.EmptyReply) error

LockProfile runs a mutex profile writing to the specified file

func (*Admin) MemoryProfile added in v0.8.13

func (p *Admin) MemoryProfile(_ *http.Request, _ *struct{}, _ *api.EmptyReply) error

MemoryProfile runs a memory profile writing to the specified file

func (*Admin) SetLogLevel added in v0.8.13

func (p *Admin) SetLogLevel(_ *http.Request, args *SetLogLevelArgs, reply *api.EmptyReply) error

func (*Admin) StartCPUProfiler added in v0.8.13

func (p *Admin) StartCPUProfiler(_ *http.Request, _ *struct{}, _ *api.EmptyReply) error

StartCPUProfiler starts a cpu profile writing to the specified file

func (*Admin) StopCPUProfiler added in v0.8.13

func (p *Admin) StopCPUProfiler(r *http.Request, _ *struct{}, _ *api.EmptyReply) error

StopCPUProfiler stops the cpu profile

type AtomicBackend added in v0.10.0

type AtomicBackend interface {
	// InsertTxs calculates the root of the atomic trie that would
	// result from applying [txs] to the atomic trie, starting at the state
	// corresponding to previously verified block [parentHash].
	// If [blockHash] is provided, the modified atomic trie is pinned in memory
	// and it's the caller's responsibility to call either Accept or Reject on
	// the AtomicState which can be retreived from GetVerifiedAtomicState to commit the
	// changes or abort them and free memory.
	InsertTxs(blockHash common.Hash, blockHeight uint64, parentHash common.Hash, txs []*Tx) (common.Hash, error)

	// Returns an AtomicState corresponding to a block hash that has been inserted
	// but not Accepted or Rejected yet.
	GetVerifiedAtomicState(blockHash common.Hash) (AtomicState, error)

	// AtomicTrie returns the atomic trie managed by this backend.
	AtomicTrie() AtomicTrie

	// ApplyToSharedMemory applies the atomic operations that have been indexed into the trie
	// but not yet applied to shared memory for heights less than or equal to [lastAcceptedBlock].
	// This executes operations in the range [cursorHeight+1, lastAcceptedBlock].
	// The cursor is initially set by  MarkApplyToSharedMemoryCursor to signal to the atomic trie
	// the range of operations that were added to the trie without being executed on shared memory.
	ApplyToSharedMemory(lastAcceptedBlock uint64) error

	// MarkApplyToSharedMemoryCursor marks the atomic trie as containing atomic ops that
	// have not been executed on shared memory starting at [previousLastAcceptedHeight+1].
	// This is used when state sync syncs the atomic trie, such that the atomic operations
	// from [previousLastAcceptedHeight+1] to the [lastAcceptedHeight] set by state sync
	// will not have been executed on shared memory.
	MarkApplyToSharedMemoryCursor(previousLastAcceptedHeight uint64) error

	// Syncer creates and returns a new Syncer object that can be used to sync the
	// state of the atomic trie from peers
	Syncer(client syncclient.LeafClient, targetRoot common.Hash, targetHeight uint64, requestSize uint16) (Syncer, error)

	// SetLastAccepted is used after state-sync to reset the last accepted block.
	SetLastAccepted(lastAcceptedHash common.Hash)

	// IsBonus returns true if the block for atomicState is a bonus block
	IsBonus(blockHeight uint64, blockHash common.Hash) bool
}

AtomicBackend abstracts the verification and processing of atomic transactions

func NewAtomicBackend added in v0.10.0

func NewAtomicBackend(
	db *versiondb.Database, sharedMemory atomic.SharedMemory,
	bonusBlocks map[uint64]ids.ID, repo AtomicTxRepository,
	lastAcceptedHeight uint64, lastAcceptedHash common.Hash, commitInterval uint64,
) (AtomicBackend, error)

NewAtomicBackend creates an AtomicBackend from the specified dependencies

type AtomicState added in v0.10.0

type AtomicState interface {
	// Root of the atomic trie after applying the state change.
	Root() common.Hash
	// Accept applies the state change to VM's persistent storage
	// Changes are persisted atomically along with the provided [commitBatch].
	Accept(commitBatch database.Batch, requests map[ids.ID]*atomic.Requests) error
	// Reject frees memory associated with the state change.
	Reject() error
}

AtomicState is an abstraction created through AtomicBackend and can be used to apply the VM's state change for atomic txs or reject them to free memory. The root of the atomic trie after applying the state change is accessible through this interface as well.

type AtomicTrie added in v0.8.13

type AtomicTrie interface {
	// OpenTrie returns a modifiable instance of the atomic trie backed by trieDB
	// opened at hash.
	OpenTrie(hash common.Hash) (*trie.Trie, error)

	// UpdateTrie updates [tr] to inlude atomicOps for height.
	UpdateTrie(tr *trie.Trie, height uint64, atomicOps map[ids.ID]*atomic.Requests) error

	// Iterator returns an AtomicTrieIterator to iterate the trie at the given
	// root hash starting at [cursor].
	Iterator(hash common.Hash, cursor []byte) (AtomicTrieIterator, error)

	// LastCommitted returns the last committed hash and corresponding block height
	LastCommitted() (common.Hash, uint64)

	// TrieDB returns the underlying trie database
	TrieDB() *trie.Database

	// Root returns hash if it exists at specified height
	// if trie was not committed at provided height, it returns
	// common.Hash{} instead
	Root(height uint64) (common.Hash, error)

	// LastAcceptedRoot returns the most recent accepted root of the atomic trie,
	// or the root it was initialized to if no new tries were accepted yet.
	LastAcceptedRoot() common.Hash

	// InsertTrie updates the trieDB with the provided node set and adds a reference
	// to root in the trieDB. Once InsertTrie is called, it is expected either
	// AcceptTrie or RejectTrie be called for the same root.
	InsertTrie(nodes *trienode.NodeSet, root common.Hash) error

	// AcceptTrie marks root as the last accepted atomic trie root, and
	// commits the trie to persistent storage if height is divisible by
	// the commit interval. Returns true if the trie was committed.
	AcceptTrie(height uint64, root common.Hash) (bool, error)

	// RejectTrie dereferences root from the trieDB, freeing memory.
	RejectTrie(root common.Hash) error
}

AtomicTrie maintains an index of atomic operations by blockchainIDs for every block height containing atomic transactions. The backing data structure for this index is a Trie. The keys of the trie are block heights and the values (leaf nodes) are the atomic operations applied to shared memory while processing the block accepted at the corresponding height.

type AtomicTrieIterator added in v0.8.13

type AtomicTrieIterator interface {
	// Next advances the iterator to the next node in the atomic trie and
	// returns true if there are more leaves to iterate
	Next() bool

	// Key returns the current database key that the iterator is iterating
	// returned []byte can be freely modified
	Key() []byte

	// BlockNumber returns the current block number
	BlockNumber() uint64

	// BlockchainID returns the current blockchain ID at the current block number
	BlockchainID() ids.ID

	// AtomicOps returns a map of blockchainIDs to the set of atomic requests
	// for that blockchainID at the current block number
	AtomicOps() *atomic.Requests

	// Error returns error, if any encountered during this iteration
	Error() error
}

AtomicTrieIterator is a stateful iterator that iterates the leafs of an AtomicTrie

func NewAtomicTrieIterator added in v0.8.13

func NewAtomicTrieIterator(trieIterator *trie.Iterator, codec codec.Manager) AtomicTrieIterator

type AtomicTxRepository added in v0.8.13

type AtomicTxRepository interface {
	GetIndexHeight() (uint64, error)
	GetByTxID(txID ids.ID) (*Tx, uint64, error)
	GetByHeight(height uint64) ([]*Tx, error)
	Write(height uint64, txs []*Tx) error
	WriteBonus(height uint64, txs []*Tx) error

	IterateByHeight(start uint64) database.Iterator
	Codec() codec.Manager
}

AtomicTxRepository defines an entity that manages storage and indexing of atomic transactions

type AvaxAPI added in v0.8.13

type AvaxAPI struct {
	// contains filtered or unexported fields
}

AvaxAPI offers Avalanche network related API methods

func (*AvaxAPI) Export added in v0.8.13

func (service *AvaxAPI) Export(_ *http.Request, args *ExportArgs, response *api.JSONTxID) error

Export exports an asset from the C-Chain to the X-Chain It must be imported on the X-Chain to complete the transfer

func (*AvaxAPI) ExportAVAX added in v0.8.13

func (service *AvaxAPI) ExportAVAX(_ *http.Request, args *ExportAVAXArgs, response *api.JSONTxID) error

ExportAVAX exports AVAX from the C-Chain to the X-Chain It must be imported on the X-Chain to complete the transfer

func (*AvaxAPI) ExportKey added in v0.8.13

func (service *AvaxAPI) ExportKey(r *http.Request, args *ExportKeyArgs, reply *ExportKeyReply) error

ExportKey returns a private key from the provided user

func (*AvaxAPI) GetAtomicTx added in v0.8.13

func (service *AvaxAPI) GetAtomicTx(r *http.Request, args *api.GetTxArgs, reply *FormattedTx) error

GetAtomicTx returns the specified transaction

func (*AvaxAPI) GetAtomicTxStatus added in v0.8.13

func (service *AvaxAPI) GetAtomicTxStatus(r *http.Request, args *api.JSONTxID, reply *GetAtomicTxStatusReply) error

GetAtomicTxStatus returns the status of the specified transaction

func (*AvaxAPI) GetUTXOs added in v0.8.13

func (service *AvaxAPI) GetUTXOs(r *http.Request, args *api.GetUTXOsArgs, reply *api.GetUTXOsReply) error

GetUTXOs gets all utxos for passed in addresses

func (*AvaxAPI) Import added in v0.8.13

func (service *AvaxAPI) Import(_ *http.Request, args *ImportArgs, response *api.JSONTxID) error

Import issues a transaction to import AVAX from the X-chain. The AVAX must have already been exported from the X-Chain.

func (*AvaxAPI) ImportAVAX added in v0.8.13

func (service *AvaxAPI) ImportAVAX(_ *http.Request, args *ImportArgs, response *api.JSONTxID) error

ImportAVAX is a deprecated name for Import.

func (*AvaxAPI) ImportKey added in v0.8.13

func (service *AvaxAPI) ImportKey(r *http.Request, args *ImportKeyArgs, reply *api.JSONAddress) error

ImportKey adds a private key to the provided user

func (*AvaxAPI) IssueTx added in v0.8.13

func (service *AvaxAPI) IssueTx(r *http.Request, args *api.FormattedTx, response *api.JSONTxID) error

func (*AvaxAPI) Version added in v0.8.13

func (service *AvaxAPI) Version(r *http.Request, _ *struct{}, reply *VersionReply) error

ClientVersion returns the version of the VM running

type Batch

type Batch struct{ database.Batch }

Batch implements ethdb.Batch

func (Batch) Replay

func (batch Batch) Replay(w ethdb.KeyValueWriter) error

Replay implements ethdb.Batch

func (Batch) ValueSize added in v0.8.13

func (batch Batch) ValueSize() int

ValueSize implements ethdb.Batch

type Block

type Block struct {
	// contains filtered or unexported fields
}

Block implements the snowman.Block interface

func (*Block) Accept

func (b *Block) Accept(context.Context) error

Accept implements the snowman.Block interface

func (*Block) Bytes

func (b *Block) Bytes() []byte

Bytes implements the snowman.Block interface

func (*Block) Height added in v0.8.13

func (b *Block) Height() uint64

Height implements the snowman.Block interface

func (*Block) ID

func (b *Block) ID() ids.ID

ID implements the snowman.Block interface

func (*Block) Parent

func (b *Block) Parent() ids.ID

Parent implements the snowman.Block interface

func (*Block) Reject

func (b *Block) Reject(context.Context) error

Reject implements the snowman.Block interface If [b] contains an atomic transaction, attempt to re-issue it

func (*Block) SetStatus added in v0.8.13

func (b *Block) SetStatus(status choices.Status)

SetStatus implements the InternalBlock interface allowing ChainState to set the status on an existing block

func (*Block) ShouldVerifyWithContext

func (b *Block) ShouldVerifyWithContext(context.Context) (bool, error)

ShouldVerifyWithContext implements the block.WithVerifyContext interface

func (*Block) Status

func (b *Block) Status() choices.Status

Status implements the snowman.Block interface

func (*Block) String

func (b *Block) String() string

func (*Block) Timestamp added in v0.8.13

func (b *Block) Timestamp() time.Time

Timestamp implements the snowman.Block interface

func (*Block) Verify

func (b *Block) Verify(context.Context) error

Verify implements the snowman.Block interface

func (*Block) VerifyWithContext

func (b *Block) VerifyWithContext(ctx context.Context, proposerVMBlockCtx *block.Context) error

VerifyWithContext implements the block.WithVerifyContext interface

type BlockValidator added in v0.8.13

type BlockValidator interface {
	SyntacticVerify(b *Block, rules params.Rules) error
}

func NewBlockValidator added in v0.10.0

func NewBlockValidator(extDataHashes map[common.Hash]common.Hash) BlockValidator

type BuildGenesisReply added in v0.8.13

type BuildGenesisReply struct {
	Bytes    string              `json:"bytes"`
	Encoding formatting.Encoding `json:"encoding"`
}

BuildGenesisReply is the reply from BuildGenesis

type Client added in v0.8.13

type Client interface {
	IssueTx(ctx context.Context, txBytes []byte, options ...rpc.Option) (ids.ID, error)
	GetAtomicTxStatus(ctx context.Context, txID ids.ID, options ...rpc.Option) (Status, error)
	GetAtomicTx(ctx context.Context, txID ids.ID, options ...rpc.Option) ([]byte, error)
	GetAtomicUTXOs(ctx context.Context, addrs []ids.ShortID, sourceChain string, limit uint32, startAddress ids.ShortID, startUTXOID ids.ID, options ...rpc.Option) ([][]byte, ids.ShortID, ids.ID, error)
	ExportKey(ctx context.Context, userPass api.UserPass, addr common.Address, options ...rpc.Option) (*secp256k1.PrivateKey, string, error)
	ImportKey(ctx context.Context, userPass api.UserPass, privateKey *secp256k1.PrivateKey, options ...rpc.Option) (common.Address, error)
	Import(ctx context.Context, userPass api.UserPass, to common.Address, sourceChain string, options ...rpc.Option) (ids.ID, error)
	ExportAVAX(ctx context.Context, userPass api.UserPass, amount uint64, to ids.ShortID, targetChain string, options ...rpc.Option) (ids.ID, error)
	Export(ctx context.Context, userPass api.UserPass, amount uint64, to ids.ShortID, targetChain string, assetID string, options ...rpc.Option) (ids.ID, error)
	StartCPUProfiler(ctx context.Context, options ...rpc.Option) error
	StopCPUProfiler(ctx context.Context, options ...rpc.Option) error
	MemoryProfile(ctx context.Context, options ...rpc.Option) error
	LockProfile(ctx context.Context, options ...rpc.Option) error
	SetLogLevel(ctx context.Context, level log.Lvl, options ...rpc.Option) error
	GetVMConfig(ctx context.Context, options ...rpc.Option) (*Config, error)
}

Client interface for interacting with EVM chain

func NewCChainClient added in v0.8.13

func NewCChainClient(uri string) Client

NewCChainClient returns a Client for interacting with the C Chain

func NewClient added in v0.8.13

func NewClient(uri, chain string) Client

NewClient returns a Client for interacting with EVM chain

type Config added in v0.8.13

type Config struct {
	// Coreth APIs
	SnowmanAPIEnabled     bool   `json:"snowman-api-enabled"`
	AdminAPIEnabled       bool   `json:"admin-api-enabled"`
	AdminAPIDir           string `json:"admin-api-dir"`
	CorethAdminAPIEnabled bool   `json:"coreth-admin-api-enabled"` // Deprecated: use AdminAPIEnabled instead
	CorethAdminAPIDir     string `json:"coreth-admin-api-dir"`     // Deprecated: use AdminAPIDir instead
	WarpAPIEnabled        bool   `json:"warp-api-enabled"`

	// EnabledEthAPIs is a list of Ethereum services that should be enabled
	// If none is specified, then we use the default list [defaultEnabledAPIs]
	EnabledEthAPIs []string `json:"eth-apis"`

	// Continuous Profiler
	ContinuousProfilerDir       string   `json:"continuous-profiler-dir"`       // If set to non-empty string creates a continuous profiler
	ContinuousProfilerFrequency Duration `json:"continuous-profiler-frequency"` // Frequency to run continuous profiler if enabled
	ContinuousProfilerMaxFiles  int      `json:"continuous-profiler-max-files"` // Maximum number of files to maintain

	// Coreth API Gas/Price Caps
	RPCGasCap   uint64  `json:"rpc-gas-cap"`
	RPCTxFeeCap float64 `json:"rpc-tx-fee-cap"`

	// Cache settings
	TrieCleanCache            int      `json:"trie-clean-cache"`            // Size of the trie clean cache (MB)
	TrieCleanJournal          string   `json:"trie-clean-journal"`          // Directory to use to save the trie clean cache (must be populated to enable journaling the trie clean cache)
	TrieCleanRejournal        Duration `json:"trie-clean-rejournal"`        // Frequency to re-journal the trie clean cache to disk (minimum 1 minute, must be populated to enable journaling the trie clean cache)
	TrieDirtyCache            int      `json:"trie-dirty-cache"`            // Size of the trie dirty cache (MB)
	TrieDirtyCommitTarget     int      `json:"trie-dirty-commit-target"`    // Memory limit to target in the dirty cache before performing a commit (MB)
	TriePrefetcherParallelism int      `json:"trie-prefetcher-parallelism"` // Max concurrent disk reads trie prefetcher should perform at once
	SnapshotCache             int      `json:"snapshot-cache"`              // Size of the snapshot disk layer clean cache (MB)

	// Eth Settings
	Preimages      bool `json:"preimages-enabled"`
	SnapshotWait   bool `json:"snapshot-wait"`
	SnapshotVerify bool `json:"snapshot-verification-enabled"`

	// Pruning Settings
	Pruning                         bool    `json:"pruning-enabled"`                    // If enabled, trie roots are only persisted every 4096 blocks
	AcceptorQueueLimit              int     `json:"accepted-queue-limit"`               // Maximum blocks to queue before blocking during acceptance
	CommitInterval                  uint64  `json:"commit-interval"`                    // Specifies the commit interval at which to persist EVM and atomic tries.
	AllowMissingTries               bool    `json:"allow-missing-tries"`                // If enabled, warnings preventing an incomplete trie index are suppressed
	PopulateMissingTries            *uint64 `json:"populate-missing-tries,omitempty"`   // Sets the starting point for re-populating missing tries. Disables re-generation if nil.
	PopulateMissingTriesParallelism int     `json:"populate-missing-tries-parallelism"` // Number of concurrent readers to use when re-populating missing tries on startup.
	PruneWarpDB                     bool    `json:"prune-warp-db-enabled"`              // Determines if the warpDB should be cleared on startup

	// Metric Settings
	MetricsExpensiveEnabled bool `json:"metrics-expensive-enabled"` // Debug-level metrics that might impact runtime performance

	// API Settings
	LocalTxsEnabled bool `json:"local-txs-enabled"`

	TxPoolJournal      string   `json:"tx-pool-journal"`
	TxPoolRejournal    Duration `json:"tx-pool-rejournal"`
	TxPoolPriceLimit   uint64   `json:"tx-pool-price-limit"`
	TxPoolPriceBump    uint64   `json:"tx-pool-price-bump"`
	TxPoolAccountSlots uint64   `json:"tx-pool-account-slots"`
	TxPoolGlobalSlots  uint64   `json:"tx-pool-global-slots"`
	TxPoolAccountQueue uint64   `json:"tx-pool-account-queue"`
	TxPoolGlobalQueue  uint64   `json:"tx-pool-global-queue"`

	APIMaxDuration           Duration      `json:"api-max-duration"`
	WSCPURefillRate          Duration      `json:"ws-cpu-refill-rate"`
	WSCPUMaxStored           Duration      `json:"ws-cpu-max-stored"`
	MaxBlocksPerRequest      int64         `json:"api-max-blocks-per-request"`
	AllowUnfinalizedQueries  bool          `json:"allow-unfinalized-queries"`
	AllowUnprotectedTxs      bool          `json:"allow-unprotected-txs"`
	AllowUnprotectedTxHashes []common.Hash `json:"allow-unprotected-tx-hashes"`

	// Keystore Settings
	KeystoreDirectory             string `json:"keystore-directory"` // both absolute and relative supported
	KeystoreExternalSigner        string `json:"keystore-external-signer"`
	KeystoreInsecureUnlockAllowed bool   `json:"keystore-insecure-unlock-allowed"`

	// Gossip Settings
	RemoteGossipOnlyEnabled   bool     `json:"remote-gossip-only-enabled"`
	RegossipFrequency         Duration `json:"regossip-frequency"`
	RegossipMaxTxs            int      `json:"regossip-max-txs"`
	RemoteTxGossipOnlyEnabled bool     `json:"remote-tx-gossip-only-enabled"` // Deprecated: use RemoteGossipOnlyEnabled instead
	TxRegossipFrequency       Duration `json:"tx-regossip-frequency"`         // Deprecated: use RegossipFrequency instead
	TxRegossipMaxSize         int      `json:"tx-regossip-max-size"`          // Deprecated: use RegossipMaxTxs instead

	// Log
	LogLevel      string `json:"log-level"`
	LogJSONFormat bool   `json:"log-json-format"`

	// Offline Pruning Settings
	OfflinePruning                bool   `json:"offline-pruning-enabled"`
	OfflinePruningBloomFilterSize uint64 `json:"offline-pruning-bloom-filter-size"`
	OfflinePruningDataDirectory   string `json:"offline-pruning-data-directory"`

	// VM2VM network
	MaxOutboundActiveRequests           int64 `json:"max-outbound-active-requests"`
	MaxOutboundActiveCrossChainRequests int64 `json:"max-outbound-active-cross-chain-requests"`

	// Sync settings
	StateSyncEnabled         *bool  `json:"state-sync-enabled"`     // Pointer distinguishes false (no state sync) and not set (state sync only at genesis).
	StateSyncSkipResume      bool   `json:"state-sync-skip-resume"` // Forces state sync to use the highest available summary block
	StateSyncServerTrieCache int    `json:"state-sync-server-trie-cache"`
	StateSyncIDs             string `json:"state-sync-ids"`
	StateSyncCommitInterval  uint64 `json:"state-sync-commit-interval"`
	StateSyncMinBlocks       uint64 `json:"state-sync-min-blocks"`
	StateSyncRequestSize     uint16 `json:"state-sync-request-size"`

	// Database Settings
	InspectDatabase bool `json:"inspect-database"` // Inspects the database on startup if enabled.

	// SkipUpgradeCheck disables checking that upgrades must take place before the last
	// accepted block. Skipping this check is useful when a node operator does not update
	// their node before the network upgrade and their node accepts blocks that have
	// identical state with the pre-upgrade ruleset.
	SkipUpgradeCheck bool `json:"skip-upgrade-check"`

	// AcceptedCacheSize is the depth to keep in the accepted headers cache and the
	// accepted logs cache at the accepted tip.
	//
	// This is particularly useful for improving the performance of eth_getLogs
	// on RPC nodes.
	AcceptedCacheSize int `json:"accepted-cache-size"`

	// TxLookupLimit is the maximum number of blocks from head whose tx indices
	// are reserved:
	//  * 0:   means no limit
	//  * N:   means N block limit [HEAD-N+1, HEAD] and delete extra indexes
	TxLookupLimit uint64 `json:"tx-lookup-limit"`

	// SkipTxIndexing skips indexing transactions.
	// This is useful for validators that don't need to index transactions.
	// TxLookupLimit can be still used to control unindexing old transactions.
	SkipTxIndexing bool `json:"skip-tx-indexing"`
}

Config ...

func (*Config) Deprecate added in v0.12.5

func (c *Config) Deprecate() string

func (Config) EthAPIs added in v0.8.13

func (c Config) EthAPIs() []string

EthAPIs returns an array of strings representing the Eth APIs that should be enabled

func (Config) EthBackendSettings added in v0.8.13

func (c Config) EthBackendSettings() eth.Settings

func (*Config) SetDefaults added in v0.8.13

func (c *Config) SetDefaults()

func (*Config) Validate added in v0.8.13

func (c *Config) Validate() error

Validate returns an error if this is an invalid config.

type ConfigReply added in v0.8.13

type ConfigReply struct {
	Config *Config `json:"config"`
}

type CorethLogger added in v0.8.15

type CorethLogger struct {
	log.Handler
}

func InitLogger added in v0.8.15

func InitLogger(alias string, level string, jsonFormat bool, writer io.Writer) (CorethLogger, error)

InitLogger initializes logger with alias and sets the log level and format with the original os.StdErr interface along with the context logger.

func (*CorethLogger) SetLogLevel added in v0.8.15

func (c *CorethLogger) SetLogLevel(level string) error

SetLogLevel sets the log level of initialized log handler.

type Database

type Database struct{ database.Database }

Database implements ethdb.Database

func (Database) NewBatch

func (db Database) NewBatch() ethdb.Batch

NewBatch implements ethdb.Database

func (Database) NewBatchWithSize added in v0.8.13

func (db Database) NewBatchWithSize(size int) ethdb.Batch

NewBatchWithSize implements ethdb.Database TODO: propagate size through avalanchego Database interface

func (Database) NewIterator

func (db Database) NewIterator(prefix []byte, start []byte) ethdb.Iterator

NewIterator implements ethdb.Database

Note: This method assumes that the prefix is NOT part of the start, so there's no need for the caller to prepend the prefix to the start.

func (Database) NewIteratorWithStart

func (db Database) NewIteratorWithStart(start []byte) ethdb.Iterator

NewIteratorWithStart implements ethdb.Database

func (Database) Stat added in v0.8.13

func (db Database) Stat(string) (string, error)

Stat implements ethdb.Database

type Duration added in v0.8.13

type Duration struct {
	time.Duration
}

func (Duration) MarshalJSON added in v0.10.0

func (d Duration) MarshalJSON() ([]byte, error)

String implements the stringer interface.

func (Duration) String added in v0.10.0

func (d Duration) String() string

String implements the stringer interface.

func (*Duration) UnmarshalJSON added in v0.8.13

func (d *Duration) UnmarshalJSON(data []byte) (err error)

type EVMInput added in v0.8.13

type EVMInput struct {
	Address common.Address `serialize:"true" json:"address"`
	Amount  uint64         `serialize:"true" json:"amount"`
	AssetID ids.ID         `serialize:"true" json:"assetID"`
	Nonce   uint64         `serialize:"true" json:"nonce"`
}

EVMInput defines an input created from the EVM state to fund export transactions

func (EVMInput) Less added in v0.12.5

func (i EVMInput) Less(other EVMInput) bool

func (*EVMInput) Verify added in v0.8.13

func (in *EVMInput) Verify() error

Verify ...

type EVMOutput added in v0.8.13

type EVMOutput struct {
	Address common.Address `serialize:"true" json:"address"`
	Amount  uint64         `serialize:"true" json:"amount"`
	AssetID ids.ID         `serialize:"true" json:"assetID"`
}

EVMOutput defines an output that is added to the EVM state created by import transactions

func (EVMOutput) Less added in v0.12.5

func (o EVMOutput) Less(other EVMOutput) bool

func (*EVMOutput) Verify added in v0.8.13

func (out *EVMOutput) Verify() error

Verify ...

type ExportAVAXArgs added in v0.8.13

type ExportAVAXArgs struct {
	api.UserPass

	// Fee that should be used when creating the tx
	BaseFee *hexutil.Big `json:"baseFee"`

	// Amount of asset to send
	Amount json.Uint64 `json:"amount"`

	// Chain the funds are going to. Optional. Used if To address does not
	// include the chainID.
	TargetChain string `json:"targetChain"`

	// ID of the address that will receive the AVAX. This address may include
	// the chainID, which is used to determine what the destination chain is.
	To string `json:"to"`
}

ExportAVAXArgs are the arguments to ExportAVAX

type ExportArgs added in v0.8.13

type ExportArgs struct {
	ExportAVAXArgs
	// AssetID of the tokens
	AssetID string `json:"assetID"`
}

ExportArgs are the arguments to Export

type ExportKeyArgs added in v0.8.13

type ExportKeyArgs struct {
	api.UserPass
	Address string `json:"address"`
}

ExportKeyArgs are arguments for ExportKey

type ExportKeyReply added in v0.8.13

type ExportKeyReply struct {
	// The decrypted PrivateKey for the Address provided in the arguments
	PrivateKey    *secp256k1.PrivateKey `json:"privateKey"`
	PrivateKeyHex string                `json:"privateKeyHex"`
}

ExportKeyReply is the response for ExportKey

type Factory

type Factory struct{}

func (*Factory) New

func (*Factory) New(logging.Logger) (interface{}, error)

type FormattedTx added in v0.8.13

type FormattedTx struct {
	api.FormattedTx
	BlockHeight *json.Uint64 `json:"blockHeight,omitempty"`
}

type GetAcceptedFrontReply

type GetAcceptedFrontReply struct {
	Hash   common.Hash `json:"hash"`
	Number *big.Int    `json:"number"`
}

GetAcceptedFrontReply defines the reply that will be sent from the GetAcceptedFront API call

type GetAtomicTxStatusReply added in v0.8.13

type GetAtomicTxStatusReply struct {
	Status      Status       `json:"status"`
	BlockHeight *json.Uint64 `json:"blockHeight,omitempty"`
}

GetAtomicTxStatusReply defines the GetAtomicTxStatus replies returned from the API

type GossipAtomicTx added in v0.12.5

type GossipAtomicTx struct {
	Tx *Tx
}

func (*GossipAtomicTx) GetID added in v0.12.5

func (tx *GossipAtomicTx) GetID() ids.ID

func (*GossipAtomicTx) Marshal added in v0.12.5

func (tx *GossipAtomicTx) Marshal() ([]byte, error)

func (*GossipAtomicTx) Unmarshal added in v0.12.5

func (tx *GossipAtomicTx) Unmarshal(bytes []byte) error

type GossipEthTx added in v0.12.5

type GossipEthTx struct {
	Tx *types.Transaction
}

func (*GossipEthTx) GetID added in v0.12.5

func (tx *GossipEthTx) GetID() ids.ID

func (*GossipEthTx) Marshal added in v0.12.5

func (tx *GossipEthTx) Marshal() ([]byte, error)

func (*GossipEthTx) Unmarshal added in v0.12.5

func (tx *GossipEthTx) Unmarshal(bytes []byte) error

type GossipEthTxPool added in v0.12.5

type GossipEthTxPool struct {
	// contains filtered or unexported fields
}

func NewGossipEthTxPool added in v0.12.5

func NewGossipEthTxPool(mempool *txpool.TxPool) (*GossipEthTxPool, error)

func (*GossipEthTxPool) Add added in v0.12.5

func (g *GossipEthTxPool) Add(tx *GossipEthTx) error

Add enqueues the transaction to the mempool. Subscribe should be called to receive an event if tx is actually added to the mempool or not.

func (*GossipEthTxPool) GetFilter added in v0.12.5

func (g *GossipEthTxPool) GetFilter() ([]byte, []byte, error)

func (*GossipEthTxPool) Iterate added in v0.12.5

func (g *GossipEthTxPool) Iterate(f func(tx *GossipEthTx) bool)

func (*GossipEthTxPool) Subscribe added in v0.12.5

func (g *GossipEthTxPool) Subscribe(ctx context.Context)

type GossipHandler added in v0.8.13

type GossipHandler struct {
	// contains filtered or unexported fields
}

GossipHandler handles incoming gossip messages

func NewGossipHandler added in v0.8.13

func NewGossipHandler(vm *VM, stats GossipReceivedStats) *GossipHandler

func (*GossipHandler) HandleAtomicTx added in v0.8.13

func (h *GossipHandler) HandleAtomicTx(nodeID ids.NodeID, msg message.AtomicTxGossip) error

func (*GossipHandler) HandleEthTxs added in v0.8.13

func (h *GossipHandler) HandleEthTxs(nodeID ids.NodeID, msg message.EthTxsGossip) error

type GossipReceivedStats added in v0.8.13

type GossipReceivedStats interface {
	IncAtomicGossipReceived()
	IncEthTxsGossipReceived()

	// new vs. known txs received
	IncAtomicGossipReceivedDropped()
	IncAtomicGossipReceivedError()
	IncAtomicGossipReceivedKnown()
	IncAtomicGossipReceivedNew()
	IncEthTxsGossipReceivedKnown()
	IncEthTxsGossipReceivedNew()
}

GossipReceivedStats groups functions for incoming gossip stats.

type GossipSentStats added in v0.8.13

type GossipSentStats interface {
	IncAtomicGossipSent()
	IncEthTxsGossipSent()

	// regossip
	IncEthTxsRegossipQueued()
	IncEthTxsRegossipQueuedLocal(count int)
	IncEthTxsRegossipQueuedRemote(count int)
}

GossipSentStats groups functions for outgoing gossip stats.

type GossipStats added in v0.8.13

type GossipStats interface {
	GossipReceivedStats
	GossipSentStats
}

GossipStats contains methods for updating incoming and outgoing gossip stats.

func NewGossipStats added in v0.8.13

func NewGossipStats() GossipStats

type Gossiper added in v0.8.13

type Gossiper interface {
	// GossipAtomicTxs sends AppGossip message containing the given [txs]
	GossipAtomicTxs(txs []*Tx) error
	// GossipEthTxs sends AppGossip message containing the given [txs]
	GossipEthTxs(txs []*types.Transaction) error
}

Gossiper handles outgoing gossip of transactions

type ImportArgs added in v0.8.13

type ImportArgs struct {
	api.UserPass

	// Fee that should be used when creating the tx
	BaseFee *hexutil.Big `json:"baseFee"`

	// Chain the funds are coming from
	SourceChain string `json:"sourceChain"`

	// The address that will receive the imported funds
	To common.Address `json:"to"`
}

ImportArgs are arguments for passing into Import requests

type ImportKeyArgs added in v0.8.13

type ImportKeyArgs struct {
	api.UserPass
	PrivateKey *secp256k1.PrivateKey `json:"privateKey"`
}

ImportKeyArgs are arguments for ImportKey

type Mempool added in v0.8.13

type Mempool struct {

	// Pending is a channel of length one, which the mempool ensures has an item on
	// it as long as there is an unissued transaction remaining in [txs]
	Pending chan struct{}
	// contains filtered or unexported fields
}

Mempool is a simple mempool for atomic transactions

func NewMempool added in v0.8.13

func NewMempool(ctx *snow.Context, maxSize int, verify func(tx *Tx) error) (*Mempool, error)

NewMempool returns a Mempool with [maxSize]

func (*Mempool) Add added in v0.12.5

func (m *Mempool) Add(tx *GossipAtomicTx) error

func (*Mempool) AddLocalTx

func (m *Mempool) AddLocalTx(tx *Tx) error

func (*Mempool) AddTx added in v0.8.13

func (m *Mempool) AddTx(tx *Tx) error

Add attempts to add [tx] to the mempool and returns an error if it could not be addeed to the mempool.

func (*Mempool) CancelCurrentTx added in v0.8.13

func (m *Mempool) CancelCurrentTx(txID ids.ID)

CancelCurrentTx marks the attempt to issue [txID] as being aborted. This should be called after NextTx returns [txID] and the transaction [txID] cannot be included in the block, but should not be discarded. For example, CancelCurrentTx should be called if including the transaction will put the block above the atomic tx gas limit.

func (*Mempool) CancelCurrentTxs added in v0.8.13

func (m *Mempool) CancelCurrentTxs()

[CancelCurrentTxs] marks the attempt to issue [currentTxs] as being aborted. If this is called after a buildBlock error caused by the atomic transaction, then DiscardCurrentTx should have been called such that this call will have no effect and should not re-issue the invalid tx.

func (*Mempool) DiscardCurrentTx added in v0.8.13

func (m *Mempool) DiscardCurrentTx(txID ids.ID)

DiscardCurrentTx marks a [tx] in the [currentTxs] map as invalid and aborts the attempt to issue it since it failed verification.

func (*Mempool) DiscardCurrentTxs added in v0.8.13

func (m *Mempool) DiscardCurrentTxs()

DiscardCurrentTxs marks all txs in [currentTxs] as discarded.

func (*Mempool) ForceAddTx added in v0.8.13

func (m *Mempool) ForceAddTx(tx *Tx) error

forceAddTx forcibly adds a *Tx to the mempool and bypasses all verification.

func (*Mempool) GetFilter added in v0.12.5

func (m *Mempool) GetFilter() ([]byte, []byte, error)

func (*Mempool) GetNewTxs added in v0.8.13

func (m *Mempool) GetNewTxs() []*Tx

GetNewTxs returns the array of [newTxs] and replaces it with an empty array.

func (*Mempool) GetPendingTx added in v0.8.13

func (m *Mempool) GetPendingTx(txID ids.ID) (*Tx, bool)

GetPendingTx returns the transaction [txID] and true if it is currently in the [txHeap] waiting to be issued into a block. Returns nil, false otherwise.

func (*Mempool) GetTx added in v0.8.13

func (m *Mempool) GetTx(txID ids.ID) (*Tx, bool, bool)

GetTx returns the transaction [txID] if it was issued by this node and returns whether it was dropped and whether it exists.

func (*Mempool) IssueCurrentTxs added in v0.8.13

func (m *Mempool) IssueCurrentTxs()

IssueCurrentTx marks [currentTx] as issued if there is one

func (*Mempool) Iterate added in v0.12.5

func (m *Mempool) Iterate(f func(tx *GossipAtomicTx) bool)

func (*Mempool) Len added in v0.8.13

func (m *Mempool) Len() int

Len returns the number of transactions in the mempool

func (*Mempool) NextTx added in v0.8.13

func (m *Mempool) NextTx() (*Tx, bool)

NextTx returns a transaction to be issued from the mempool.

func (*Mempool) RemoveTx added in v0.8.13

func (m *Mempool) RemoveTx(tx *Tx)

RemoveTx removes [txID] from the mempool completely. Evicts [tx] from the discarded cache if present.

type SetLogLevelArgs added in v0.8.13

type SetLogLevelArgs struct {
	Level string `json:"level"`
}

type SnowmanAPI

type SnowmanAPI struct {
	// contains filtered or unexported fields
}

SnowmanAPI introduces snowman specific functionality to the evm

func (*SnowmanAPI) GetAcceptedFront

func (api *SnowmanAPI) GetAcceptedFront(ctx context.Context) (*GetAcceptedFrontReply, error)

GetAcceptedFront returns the last accepted block's hash and height

func (*SnowmanAPI) IssueBlock added in v0.8.13

func (api *SnowmanAPI) IssueBlock(ctx context.Context) error

IssueBlock to the chain

type StateSyncClient added in v0.8.13

type StateSyncClient interface {
	// methods that implement the client side of [block.StateSyncableVM]
	StateSyncEnabled(context.Context) (bool, error)
	GetOngoingSyncStateSummary(context.Context) (block.StateSummary, error)
	ParseStateSummary(ctx context.Context, summaryBytes []byte) (block.StateSummary, error)

	// additional methods required by the evm package
	StateSyncClearOngoingSummary() error
	Shutdown() error
	Error() error
}

func NewStateSyncClient added in v0.8.13

func NewStateSyncClient(config *stateSyncClientConfig) StateSyncClient

type StateSyncServer added in v0.8.13

type StateSyncServer interface {
	GetLastStateSummary(context.Context) (block.StateSummary, error)
	GetStateSummary(context.Context, uint64) (block.StateSummary, error)
}

func NewStateSyncServer added in v0.8.13

func NewStateSyncServer(config *stateSyncServerConfig) StateSyncServer

type StaticService

type StaticService struct{}

StaticService defines the static API services exposed by the evm

func (*StaticService) BuildGenesis

func (*StaticService) BuildGenesis(_ context.Context, args *core.Genesis) (*BuildGenesisReply, error)

BuildGenesis returns the UTXOs such that at least one address in [args.Addresses] is referenced in the UTXO.

type Status added in v0.8.13

type Status uint32

Status ...

const (
	Unknown Status = iota
	Dropped
	Processing
	Accepted
)

List of possible status values Unknown Zero value, means the status is not known Dropped means the transaction was in the mempool, but was dropped because it failed verification Processing means the transaction is in the mempool Accepted means the transaction was accepted

func (Status) MarshalJSON added in v0.8.13

func (s Status) MarshalJSON() ([]byte, error)

MarshalJSON ...

func (Status) String added in v0.8.13

func (s Status) String() string

func (*Status) UnmarshalJSON added in v0.8.13

func (s *Status) UnmarshalJSON(b []byte) error

UnmarshalJSON ...

func (Status) Valid added in v0.8.13

func (s Status) Valid() error

Valid returns nil if the status is a valid status.

type Syncer added in v0.8.13

type Syncer interface {
	Start(ctx context.Context) error
	Done() <-chan error
}

Syncer represents a step in state sync, along with Start/Done methods to control and monitor progress. Error returns an error if any was encountered.

type TestUnsignedTx added in v0.8.13

type TestUnsignedTx struct {
	GasUsedV                    uint64           `serialize:"true"`
	AcceptRequestsBlockchainIDV ids.ID           `serialize:"true"`
	AcceptRequestsV             *atomic.Requests `serialize:"true"`
	VerifyV                     error
	IDV                         ids.ID `serialize:"true" json:"id"`
	BurnedV                     uint64 `serialize:"true"`
	UnsignedBytesV              []byte
	SignedBytesV                []byte
	InputUTXOsV                 set.Set[ids.ID]
	SemanticVerifyV             error
	EVMStateTransferV           error
}

func (*TestUnsignedTx) AtomicOps added in v0.8.13

func (t *TestUnsignedTx) AtomicOps() (ids.ID, *atomic.Requests, error)

AtomicOps implements the UnsignedAtomicTx interface

func (*TestUnsignedTx) Burned added in v0.8.13

func (t *TestUnsignedTx) Burned(assetID ids.ID) (uint64, error)

Burned implements the UnsignedAtomicTx interface

func (*TestUnsignedTx) Bytes added in v0.8.13

func (t *TestUnsignedTx) Bytes() []byte

Bytes implements the UnsignedAtomicTx interface

func (*TestUnsignedTx) EVMStateTransfer added in v0.8.13

func (t *TestUnsignedTx) EVMStateTransfer(ctx *snow.Context, state *state.StateDB) error

EVMStateTransfer implements the UnsignedAtomicTx interface

func (*TestUnsignedTx) GasUsed added in v0.8.13

func (t *TestUnsignedTx) GasUsed(fixedFee bool) (uint64, error)

GasUsed implements the UnsignedAtomicTx interface

func (*TestUnsignedTx) ID added in v0.8.13

func (t *TestUnsignedTx) ID() ids.ID

ID implements the UnsignedAtomicTx interface

func (*TestUnsignedTx) Initialize added in v0.8.13

func (t *TestUnsignedTx) Initialize(unsignedBytes, signedBytes []byte)

Initialize implements the UnsignedAtomicTx interface

func (*TestUnsignedTx) InputUTXOs added in v0.8.13

func (t *TestUnsignedTx) InputUTXOs() set.Set[ids.ID]

InputUTXOs implements the UnsignedAtomicTx interface

func (*TestUnsignedTx) SemanticVerify added in v0.8.13

func (t *TestUnsignedTx) SemanticVerify(vm *VM, stx *Tx, parent *Block, baseFee *big.Int, rules params.Rules) error

SemanticVerify implements the UnsignedAtomicTx interface

func (*TestUnsignedTx) SignedBytes added in v0.8.13

func (t *TestUnsignedTx) SignedBytes() []byte

SignedBytes implements the UnsignedAtomicTx interface

func (*TestUnsignedTx) Verify added in v0.8.13

func (t *TestUnsignedTx) Verify(ctx *snow.Context, rules params.Rules) error

Verify implements the UnsignedAtomicTx interface

type Tx added in v0.8.13

type Tx struct {
	// The body of this transaction
	UnsignedAtomicTx `serialize:"true" json:"unsignedTx"`

	// The credentials of this transaction
	Creds []verify.Verifiable `serialize:"true" json:"credentials"`
}

Tx is a signed transaction

func ExtractAtomicTx added in v0.8.13

func ExtractAtomicTx(atomicTxBytes []byte, codec codec.Manager) (*Tx, error)

ExtractAtomicTx extracts a singular atomic transaction from [atomicTxBytes] and returns a slice of atomic transactions for compatibility with the type returned post ApricotPhase5. Note: this function assumes [atomicTxBytes] is non-empty.

func ExtractAtomicTxs added in v0.8.13

func ExtractAtomicTxs(atomicTxBytes []byte, batch bool, codec codec.Manager) ([]*Tx, error)

extractAtomicTxs returns the atomic transactions in [atomicTxBytes] if they exist. if [batch] is true, it attempts to unmarshal [atomicTxBytes] as a slice of transactions (post-ApricotPhase5), and if it is false, then it unmarshals it as a single atomic transaction.

func ExtractAtomicTxsBatch added in v0.8.13

func ExtractAtomicTxsBatch(atomicTxBytes []byte, codec codec.Manager) ([]*Tx, error)

ExtractAtomicTxsBatch extracts a slice of atomic transactions from [atomicTxBytes]. Note: this function assumes [atomicTxBytes] is non-empty.

func (*Tx) BlockFeeContribution added in v0.8.13

func (tx *Tx) BlockFeeContribution(fixedFee bool, avaxAssetID ids.ID, baseFee *big.Int) (*big.Int, *big.Int, error)

BlockFeeContribution calculates how much AVAX towards the block fee contribution was paid for via this transaction denominated in [avaxAssetID] with [baseFee] used to calculate the cost of this transaction. This function also returns the [gasUsed] by the transaction for inclusion in the [baseFee] algorithm.

func (*Tx) Less added in v0.12.5

func (tx *Tx) Less(other *Tx) bool

func (*Tx) Sign added in v0.8.13

func (tx *Tx) Sign(c codec.Manager, signers [][]*secp256k1.PrivateKey) error

Sign this transaction with the provided signers

type UnsignedAtomicTx added in v0.8.13

type UnsignedAtomicTx interface {
	UnsignedTx

	// InputUTXOs returns the UTXOs this tx consumes
	InputUTXOs() set.Set[ids.ID]
	// Verify attempts to verify that the transaction is well formed
	Verify(ctx *snow.Context, rules params.Rules) error
	// Attempts to verify this transaction with the provided state.
	SemanticVerify(vm *VM, stx *Tx, parent *Block, baseFee *big.Int, rules params.Rules) error
	// AtomicOps returns the blockchainID and set of atomic requests that
	// must be applied to shared memory for this transaction to be accepted.
	// The set of atomic requests must be returned in a consistent order.
	AtomicOps() (ids.ID, *atomic.Requests, error)

	EVMStateTransfer(ctx *snow.Context, state *state.StateDB) error
}

UnsignedAtomicTx is an unsigned operation that can be atomically accepted

type UnsignedExportTx added in v0.8.13

type UnsignedExportTx struct {
	avax.Metadata
	// ID of the network on which this tx was issued
	NetworkID uint32 `serialize:"true" json:"networkID"`
	// ID of this blockchain.
	BlockchainID ids.ID `serialize:"true" json:"blockchainID"`
	// Which chain to send the funds to
	DestinationChain ids.ID `serialize:"true" json:"destinationChain"`
	// Inputs
	Ins []EVMInput `serialize:"true" json:"inputs"`
	// Outputs that are exported to the chain
	ExportedOutputs []*avax.TransferableOutput `serialize:"true" json:"exportedOutputs"`
}

UnsignedExportTx is an unsigned ExportTx

func (*UnsignedExportTx) AtomicOps added in v0.8.13

func (utx *UnsignedExportTx) AtomicOps() (ids.ID, *atomic.Requests, error)

AtomicOps returns the atomic operations for this transaction.

func (*UnsignedExportTx) Burned added in v0.8.13

func (utx *UnsignedExportTx) Burned(assetID ids.ID) (uint64, error)

Amount of [assetID] burned by this transaction

func (*UnsignedExportTx) EVMStateTransfer added in v0.8.13

func (utx *UnsignedExportTx) EVMStateTransfer(ctx *snow.Context, state *state.StateDB) error

EVMStateTransfer executes the state update from the atomic export transaction

func (*UnsignedExportTx) GasUsed added in v0.8.13

func (utx *UnsignedExportTx) GasUsed(fixedFee bool) (uint64, error)

func (*UnsignedExportTx) InputUTXOs added in v0.8.13

func (utx *UnsignedExportTx) InputUTXOs() set.Set[ids.ID]

InputUTXOs returns a set of all the hash(address:nonce) exporting funds.

func (*UnsignedExportTx) SemanticVerify added in v0.8.13

func (utx *UnsignedExportTx) SemanticVerify(
	vm *VM,
	stx *Tx,
	_ *Block,
	baseFee *big.Int,
	rules params.Rules,
) error

SemanticVerify this transaction is valid.

func (*UnsignedExportTx) Verify added in v0.8.13

func (utx *UnsignedExportTx) Verify(
	ctx *snow.Context,
	rules params.Rules,
) error

Verify this transaction is well-formed

type UnsignedImportTx added in v0.8.13

type UnsignedImportTx struct {
	avax.Metadata
	// ID of the network on which this tx was issued
	NetworkID uint32 `serialize:"true" json:"networkID"`
	// ID of this blockchain.
	BlockchainID ids.ID `serialize:"true" json:"blockchainID"`
	// Which chain to consume the funds from
	SourceChain ids.ID `serialize:"true" json:"sourceChain"`
	// Inputs that consume UTXOs produced on the chain
	ImportedInputs []*avax.TransferableInput `serialize:"true" json:"importedInputs"`
	// Outputs
	Outs []EVMOutput `serialize:"true" json:"outputs"`
}

UnsignedImportTx is an unsigned ImportTx

func (*UnsignedImportTx) AtomicOps added in v0.8.13

func (utx *UnsignedImportTx) AtomicOps() (ids.ID, *atomic.Requests, error)

AtomicOps returns imported inputs spent on this transaction We spend imported UTXOs here rather than in semanticVerify because we don't want to remove an imported UTXO in semanticVerify only to have the transaction not be Accepted. This would be inconsistent. Recall that imported UTXOs are not kept in a versionDB.

func (*UnsignedImportTx) Burned added in v0.8.13

func (utx *UnsignedImportTx) Burned(assetID ids.ID) (uint64, error)

Amount of [assetID] burned by this transaction

func (*UnsignedImportTx) EVMStateTransfer added in v0.8.13

func (utx *UnsignedImportTx) EVMStateTransfer(ctx *snow.Context, state *state.StateDB) error

EVMStateTransfer performs the state transfer to increase the balances of accounts accordingly with the imported EVMOutputs

func (*UnsignedImportTx) GasUsed added in v0.8.13

func (utx *UnsignedImportTx) GasUsed(fixedFee bool) (uint64, error)

func (*UnsignedImportTx) InputUTXOs added in v0.8.13

func (utx *UnsignedImportTx) InputUTXOs() set.Set[ids.ID]

InputUTXOs returns the UTXOIDs of the imported funds

func (*UnsignedImportTx) SemanticVerify added in v0.8.13

func (utx *UnsignedImportTx) SemanticVerify(
	vm *VM,
	stx *Tx,
	parent *Block,
	baseFee *big.Int,
	rules params.Rules,
) error

SemanticVerify this transaction is valid.

func (*UnsignedImportTx) Verify added in v0.8.13

func (utx *UnsignedImportTx) Verify(
	ctx *snow.Context,
	rules params.Rules,
) error

Verify this transaction is well-formed

type UnsignedTx added in v0.8.13

type UnsignedTx interface {
	Initialize(unsignedBytes, signedBytes []byte)
	ID() ids.ID
	GasUsed(fixedFee bool) (uint64, error)
	Burned(assetID ids.ID) (uint64, error)
	Bytes() []byte
	SignedBytes() []byte
}

UnsignedTx is an unsigned transaction

type VM

type VM struct {

	// *chain.State helps to implement the VM interface by wrapping blocks
	// with an efficient caching layer.
	*chain.State

	peer.Network

	IsPlugin bool

	// State sync server and client
	StateSyncServer
	StateSyncClient
	// contains filtered or unexported fields
}

VM implements the snowman.ChainVM interface

func (*VM) Clock added in v0.8.13

func (vm *VM) Clock() *mockable.Clock

Clock implements the secp256k1fx interface

func (*VM) Codec added in v0.8.13

func (vm *VM) Codec() codec.Manager

Codec implements the secp256k1fx interface

func (*VM) CodecRegistry added in v0.8.13

func (vm *VM) CodecRegistry() codec.Registry

CodecRegistry implements the secp256k1fx interface

func (*VM) CreateHandlers

func (vm *VM) CreateHandlers(context.Context) (map[string]http.Handler, error)

CreateHandlers makes new http handlers that can handle API calls

func (*VM) CreateStaticHandlers

func (vm *VM) CreateStaticHandlers(context.Context) (map[string]http.Handler, error)

CreateStaticHandlers makes new http handlers that can handle API calls

func (*VM) FormatAddress added in v0.8.13

func (vm *VM) FormatAddress(chainID ids.ID, addr ids.ShortID) (string, error)

FormatAddress takes in a chainID and a raw address and produces the formatted address

func (*VM) FormatLocalAddress added in v0.8.13

func (vm *VM) FormatLocalAddress(addr ids.ShortID) (string, error)

FormatLocalAddress takes in a raw address and produces the formatted address

func (*VM) GetActivationTime added in v0.8.13

func (vm *VM) GetActivationTime() time.Time

implements SnowmanPlusPlusVM interface

func (*VM) GetAtomicUTXOs added in v0.8.13

func (vm *VM) GetAtomicUTXOs(
	chainID ids.ID,
	addrs set.Set[ids.ShortID],
	startAddr ids.ShortID,
	startUTXOID ids.ID,
	limit int,
) ([]*avax.UTXO, ids.ShortID, ids.ID, error)

GetAtomicUTXOs returns the utxos that at least one of the provided addresses is referenced in.

func (*VM) GetBlockIDAtHeight added in v0.8.13

func (vm *VM) GetBlockIDAtHeight(_ context.Context, blkHeight uint64) (ids.ID, error)

GetBlockAtHeight implements the HeightIndexedChainVM interface and returns the canonical block at [blkHeight]. If [blkHeight] is less than the height of the last accepted block, this will return the block accepted at that height. Otherwise, it may return a blkID that has not yet been accepted. Note: the engine assumes that if a block is not found at [blkHeight], then database.ErrNotFound will be returned. This indicates that the VM has state synced and does not have all historical blocks available.

func (*VM) GetCurrentNonce added in v0.8.13

func (vm *VM) GetCurrentNonce(address common.Address) (uint64, error)

GetCurrentNonce returns the nonce associated with the address at the preferred block

func (*VM) GetSpendableAVAXWithFee added in v0.8.13

func (vm *VM) GetSpendableAVAXWithFee(
	keys []*secp256k1.PrivateKey,
	amount uint64,
	cost uint64,
	baseFee *big.Int,
) ([]EVMInput, [][]*secp256k1.PrivateKey, error)

GetSpendableAVAXWithFee returns a list of EVMInputs and keys (in corresponding order) to total [amount] + [fee] of [AVAX] owned by [keys]. This function accounts for the added cost of the additional inputs needed to create the transaction and makes sure to skip any keys with a balance that is insufficient to cover the additional fee. Note: we return [][]*secp256k1.PrivateKey even though each input corresponds to a single key, so that the signers can be passed in to [tx.Sign] which supports multiple keys on a single input.

func (*VM) GetSpendableFunds added in v0.8.13

func (vm *VM) GetSpendableFunds(
	keys []*secp256k1.PrivateKey,
	assetID ids.ID,
	amount uint64,
) ([]EVMInput, [][]*secp256k1.PrivateKey, error)

GetSpendableFunds returns a list of EVMInputs and keys (in corresponding order) to total [amount] of [assetID] owned by [keys]. Note: we return [][]*secp256k1.PrivateKey even though each input corresponds to a single key, so that the signers can be passed in to [tx.Sign] which supports multiple keys on a single input.

func (*VM) HealthCheck added in v0.8.13

func (vm *VM) HealthCheck(context.Context) (interface{}, error)

Health returns nil if this chain is healthy. Also returns details, which should be one of: string, []byte, map[string]string

func (*VM) Initialize

func (vm *VM) Initialize(
	_ context.Context,
	chainCtx *snow.Context,
	db database.Database,
	genesisBytes []byte,
	upgradeBytes []byte,
	configBytes []byte,
	toEngine chan<- commonEng.Message,
	fxs []*commonEng.Fx,
	appSender commonEng.AppSender,
) error

Initialize implements the snowman.ChainVM interface

func (*VM) Logger added in v0.8.13

func (vm *VM) Logger() logging.Logger

Logger implements the secp256k1fx interface

func (*VM) NewBlockBuilder added in v0.8.13

func (vm *VM) NewBlockBuilder(notifyBuildBlockChan chan<- commonEng.Message) *blockBuilder

func (*VM) ParseAddress added in v0.8.13

func (vm *VM) ParseAddress(addrStr string) (ids.ID, ids.ShortID, error)

ParseAddress takes in an address and produces the ID of the chain it's for the ID of the address

func (*VM) ParseEthBlock added in v0.8.13

func (vm *VM) ParseEthBlock(b []byte) (*types.Block, error)

func (*VM) ParseLocalAddress added in v0.8.13

func (vm *VM) ParseLocalAddress(addrStr string) (ids.ShortID, error)

ParseLocalAddress takes in an address for this chain and produces the ID

func (*VM) ParseServiceAddress added in v0.12.5

func (vm *VM) ParseServiceAddress(addrStr string) (ids.ShortID, error)

ParseServiceAddress get address ID from address string, being it either localized (using address manager, doing also components validations), or not localized. If both attempts fail, reports error from localized address parsing

func (*VM) SetPreference

func (vm *VM) SetPreference(ctx context.Context, blkID ids.ID) error

SetPreference sets what the current tail of the chain is

func (*VM) SetState added in v0.8.13

func (vm *VM) SetState(_ context.Context, state snow.State) error

func (*VM) Shutdown

func (vm *VM) Shutdown(context.Context) error

Shutdown implements the snowman.ChainVM interface

func (*VM) VerifyHeightIndex added in v0.8.13

func (vm *VM) VerifyHeightIndex(context.Context) error

VerifyHeightIndex always returns a nil error since the index is maintained by vm.blockChain.

func (*VM) Version added in v0.8.13

func (vm *VM) Version(context.Context) (string, error)

type VersionReply added in v0.8.13

type VersionReply struct {
	Version string `json:"version"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL