evm

package
v0.1.12 Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2022 License: GPL-3.0, LGPL-3.0 Imports: 87 Imported by: 1

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.1.12"
)

Codec does serialization and deserialization

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

Functions

func CorethFormat

func CorethFormat(prefix string, doCopy bool) log.Format

func GetEthAddress

func GetEthAddress(privKey *crypto.PrivateKeySECP256K1R) common.Address

GetEthAddress returns the ethereum address derived from [privKey]

func IsSortedAndUniqueEVMInputs

func IsSortedAndUniqueEVMInputs(inputs []EVMInput) bool

IsSortedAndUniqueEVMInputs returns true if the EVM Inputs are sorted and unique based on the account addresses

func IsSortedAndUniqueEVMOutputs

func IsSortedAndUniqueEVMOutputs(outputs []EVMOutput) bool

IsSortedAndUniqueEVMOutputs returns true if the EVMOutputs are sorted and unique based on the account addresses and assetIDs

func IsSortedEVMOutputs

func IsSortedEVMOutputs(outputs []EVMOutput) bool

IsSortedEVMOutputs returns true if the EVMOutputs are sorted based on the account addresses and assetIDs

func NewAtomicTxRepository

func NewAtomicTxRepository(db *versiondb.Database, codec codec.Manager, lastAcceptedHeight uint64) (*atomicTxRepository, error)

func ParseEthAddress

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

ParseEthAddress parses [addrStr] and returns an Ethereum address

func PublicKeyToEthAddress

func PublicKeyToEthAddress(pubKey *crypto.PublicKeySECP256K1R) common.Address

PublicKeyToEthAddress returns the ethereum address derived from [pubKey]

func SortEVMInputsAndSigners

func SortEVMInputsAndSigners(inputs []EVMInput, signers [][]*crypto.PrivateKeySECP256K1R)

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

func SortEVMOutputs

func SortEVMOutputs(outputs []EVMOutput)

SortEVMOutputs sorts the list of EVMOutputs based on the addresses and assetIDs of the outputs

Types

type Admin

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

Admin is the API service for admin API calls

func NewAdminService

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

func (*Admin) GetVMConfig

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

func (*Admin) LockProfile

func (p *Admin) LockProfile(r *http.Request, args *struct{}, reply *api.SuccessResponse) error

LockProfile runs a mutex profile writing to the specified file

func (*Admin) MemoryProfile

func (p *Admin) MemoryProfile(r *http.Request, args *struct{}, reply *api.SuccessResponse) error

MemoryProfile runs a memory profile writing to the specified file

func (*Admin) SetLogLevel

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

func (*Admin) StartCPUProfiler

func (p *Admin) StartCPUProfiler(r *http.Request, args *struct{}, reply *api.SuccessResponse) error

StartCPUProfiler starts a cpu profile writing to the specified file

func (*Admin) StopCPUProfiler

func (p *Admin) StopCPUProfiler(r *http.Request, args *struct{}, reply *api.SuccessResponse) error

StopCPUProfiler stops the cpu profile

type AtomicTrie

type AtomicTrie interface {
	// Index indexes the given atomicOps at the specified block height
	// Atomic trie is committed if the block height is multiple of commit interval
	Index(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)

	// 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) Syncer
}

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.

func NewAtomicTrie

func NewAtomicTrie(
	db *versiondb.Database, sharedMemory atomic.SharedMemory,
	bonusBlocks map[uint64]ids.ID, repo AtomicTxRepository, codec codec.Manager, lastAcceptedHeight uint64, commitHeightInterval uint64,
) (AtomicTrie, error)

NewAtomicTrie returns a new instance of a atomicTrie with the default commitHeightInterval. Initializes the trie before returning it. If the cursor set by MarkApplyToSharedMemoryCursor exists, the atomic operations are applied synchronously during initialization (blocks until ApplyToSharedMemory completes).

type AtomicTrieIterator

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

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

type AtomicTxRepository

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(uint64) database.Iterator

	IsBonusBlocksRepaired() (bool, error)
	MarkBonusBlocksRepaired(repairedEntries uint64) error
}

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

type AxcAPI

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

AxcAPI offers Axia network related API methods

func (*AxcAPI) Export

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

Export exports an asset from the AXChain to the SwapChain It must be imported on the SwapChain to complete the transfer

func (*AxcAPI) ExportAXC

func (service *AxcAPI) ExportAXC(_ *http.Request, args *ExportAXCArgs, response *api.JSONTxID) error

ExportAXC exports AXC from the AXChain to the SwapChain It must be imported on the SwapChain to complete the transfer

func (*AxcAPI) ExportKey

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

ExportKey returns a private key from the provided user

func (*AxcAPI) GetAtomicTx

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

GetAtomicTx returns the specified transaction

func (*AxcAPI) GetAtomicTxStatus

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

GetAtomicTxStatus returns the status of the specified transaction

func (*AxcAPI) GetUTXOs

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

GetUTXOs gets all utxos for passed in addresses

func (*AxcAPI) Import

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

Import issues a transaction to import AXC from the SwapChain. The AXC must have already been exported from the SwapChain.

func (*AxcAPI) ImportAXC

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

ImportAXC is a deprecated name for Import.

func (*AxcAPI) ImportKey

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

ImportKey adds a private key to the provided user

func (*AxcAPI) IssueTx

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

IssueTx ...

func (*AxcAPI) Version

func (service *AxcAPI) Version(r *http.Request, args *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

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() error

Accept implements the snowman.Block interface

func (*Block) Bytes

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

Bytes implements the snowman.Block interface

func (*Block) Height

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() error

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

func (*Block) SetStatus

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

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

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

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

Timestamp implements the snowman.Block interface

func (*Block) Verify

func (b *Block) Verify() error

Verify implements the snowman.Block interface

type BlockValidator

type BlockValidator interface {
	SyntacticVerify(b *Block) error
}

type BuildGenesisReply

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

BuildGenesisReply is the reply from BuildGenesis

type Client

type Client interface {
	IssueTx(ctx context.Context, txBytes []byte) (ids.ID, error)
	GetAtomicTxStatus(ctx context.Context, txID ids.ID) (Status, error)
	GetAtomicTx(ctx context.Context, txID ids.ID) ([]byte, error)
	GetAtomicUTXOs(ctx context.Context, addrs []string, sourceChain string, limit uint32, startAddress, startUTXOID string) ([][]byte, api.Index, error)
	ListAddresses(ctx context.Context, userPass api.UserPass) ([]string, error)
	ExportKey(ctx context.Context, userPass api.UserPass, addr string) (*crypto.PrivateKeySECP256K1R, string, error)
	ImportKey(ctx context.Context, userPass api.UserPass, privateKey *crypto.PrivateKeySECP256K1R) (string, error)
	Import(ctx context.Context, userPass api.UserPass, to string, sourceChain string) (ids.ID, error)
	ExportAXC(ctx context.Context, userPass api.UserPass, amount uint64, to string) (ids.ID, error)
	Export(ctx context.Context, userPass api.UserPass, amount uint64, to string, assetID string) (ids.ID, error)
	StartCPUProfiler(ctx context.Context) (bool, error)
	StopCPUProfiler(ctx context.Context) (bool, error)
	MemoryProfile(ctx context.Context) (bool, error)
	LockProfile(ctx context.Context) (bool, error)
	SetLogLevel(ctx context.Context, level log.Lvl) (bool, error)
	GetVMConfig(ctx context.Context) (*Config, error)
}

Client interface for interacting with EVM chain

func NewAXChainClient added in v0.1.6

func NewAXChainClient(uri string) Client

NewAXChainClient returns a Client for interacting with the C Chain

func NewClient

func NewClient(uri, chain string) Client

NewClient returns a Client for interacting with EVM chain

type Config

type Config struct {
	// Coreth APIs
	SnowmanAPIEnabled     bool   `json:"snowman-api-enabled"`
	CorethAdminAPIEnabled bool   `json:"coreth-admin-api-enabled"`
	CorethAdminAPIDir     string `json:"coreth-admin-api-dir"`

	// 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"`

	// Eth Settings
	Preimages      bool `json:"preimages-enabled"`
	SnapshotAsync  bool `json:"snapshot-async"`
	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.

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

	// API Settings
	LocalTxsEnabled         bool     `json:"local-txs-enabled"`
	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"`

	// 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
	RemoteTxGossipOnlyEnabled bool     `json:"remote-tx-gossip-only-enabled"`
	TxRegossipFrequency       Duration `json:"tx-regossip-frequency"`
	TxRegossipMaxSize         int      `json:"tx-regossip-max-size"`

	// Log level
	LogLevel string `json:"log-level"`

	// 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"`

	// Sync settings
	StateSyncEnabled         bool   `json:"state-sync-enabled"`
	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"`
	StateSyncDisableRequests bool   `json:"state-sync-disable-requests"` // Disables serving state sync data on incoming requests
}

Config ...

func (Config) EthAPIs

func (c Config) EthAPIs() []string

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

func (Config) EthBackendSettings

func (c Config) EthBackendSettings() eth.Settings

func (*Config) SetDefaults

func (c *Config) SetDefaults()

func (*Config) Validate

func (c *Config) Validate() error

Validate returns an error if this is an invalid config.

type ConfigReply

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

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) 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

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

Stat implements ethdb.Database

type Duration

type Duration struct {
	time.Duration
}

func (*Duration) UnmarshalJSON

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

type EVMInput

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) Verify

func (in *EVMInput) Verify() error

Verify ...

type EVMOutput

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) Verify

func (out *EVMOutput) Verify() error

Verify ...

type ExportAXCArgs

type ExportAXCArgs 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"`

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

ExportAXCArgs are the arguments to ExportAXC

type ExportArgs

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

ExportArgs are the arguments to Export

type ExportKeyArgs

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

ExportKeyArgs are arguments for ExportKey

type ExportKeyReply

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

ExportKeyReply is the response for ExportKey

type Factory

type Factory struct{}

func (*Factory) New

func (f *Factory) New(*snow.Context) (interface{}, error)

type FormattedTx

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

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

GetAtomicTxStatusReply defines the GetAtomicTxStatus replies returned from the API

type GossipHandler

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

GossipHandler handles incoming gossip messages

func NewGossipHandler

func NewGossipHandler(vm *VM) *GossipHandler

func (*GossipHandler) HandleAtomicTx

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

func (*GossipHandler) HandleEthTxs

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

type Gossiper

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

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 string `json:"to"`
}

ImportArgs are arguments for passing into Import requests

type ImportKeyArgs

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

ImportKeyArgs are arguments for ImportKey

type Mempool

type Mempool struct {

	// AXCAssetID is the fee paying currency of any atomic transaction
	AXCAssetID ids.ID

	// 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

func NewMempool(AXCAssetID ids.ID, maxSize int) *Mempool

NewMempool returns a Mempool with [maxSize]

func (*Mempool) AddTx

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

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

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

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

func (m *Mempool) DiscardCurrentTxs()

DiscardCurrentTxs marks all txs in [currentTxs] as discarded.

func (*Mempool) ForceAddTx

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

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

func (*Mempool) GetNewTxs

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

GetNewTxs returns the array of [newTxs] and replaces it with a new array.

func (*Mempool) GetPendingTx

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

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

func (m *Mempool) IssueCurrentTxs()

IssueCurrentTx marks [currentTx] as issued if there is one

func (*Mempool) Len

func (m *Mempool) Len() int

Len returns the number of transactions in the mempool

func (*Mempool) NextTx

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

NextTx returns a transaction to be issued from the mempool.

func (*Mempool) RemoveTx

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

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

type SetLogLevelArgs

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

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

IssueBlock to the chain

type StateSyncClient

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

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

func NewStateSyncClient

func NewStateSyncClient(config *stateSyncClientConfig) StateSyncClient

type StateSyncServer

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

func NewStateSyncServer

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

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

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

MarshalJSON ...

func (Status) String

func (s Status) String() string

func (*Status) UnmarshalJSON

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

UnmarshalJSON ...

func (Status) Valid

func (s Status) Valid() error

Valid returns nil if the status is a valid status.

type Syncer

type Syncer interface {
	Start(ctx context.Context)
	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 TestTx

type TestTx 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
	BytesV                      []byte
	InputUTXOsV                 ids.Set
	SemanticVerifyV             error
	EVMStateTransferV           error
}

func (*TestTx) AtomicOps

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

AtomicOps implements the UnsignedAtomicTx interface

func (*TestTx) Burned

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

Burned implements the UnsignedAtomicTx interface

func (*TestTx) Bytes

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

Bytes implements the UnsignedAtomicTx interface

func (*TestTx) EVMStateTransfer

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

EVMStateTransfer implements the UnsignedAtomicTx interface

func (*TestTx) GasUsed

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

GasUsed implements the UnsignedAtomicTx interface

func (*TestTx) ID

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

ID implements the UnsignedAtomicTx interface

func (*TestTx) Initialize

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

Initialize implements the UnsignedAtomicTx interface

func (*TestTx) InputUTXOs

func (t *TestTx) InputUTXOs() ids.Set

InputUTXOs implements the UnsignedAtomicTx interface

func (*TestTx) SemanticVerify

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

SemanticVerify implements the UnsignedAtomicTx interface

func (*TestTx) UnsignedBytes

func (t *TestTx) UnsignedBytes() []byte

UnsignedBytes implements the UnsignedAtomicTx interface

func (*TestTx) Verify

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

Verify implements the UnsignedAtomicTx interface

type Tx

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

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

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

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

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

BlockFeeContribution calculates how much AXC towards the block fee contribution was paid for via this transaction denominated in [axcAssetID] 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) Sign

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

Sign this transaction with the provided signers

type UnsignedAtomicTx

type UnsignedAtomicTx interface {
	UnsignedTx

	// InputUTXOs returns the UTXOs this tx consumes
	InputUTXOs() ids.Set
	// 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

type UnsignedExportTx struct {
	axc.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 []*axc.TransferableOutput `serialize:"true" json:"exportedOutputs"`
}

UnsignedExportTx is an unsigned ExportTx

func (*UnsignedExportTx) AtomicOps

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

AtomicOps returns the atomic operations for this transaction.

func (*UnsignedExportTx) Burned

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

Amount of [assetID] burned by this transaction

func (*UnsignedExportTx) EVMStateTransfer

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

EVMStateTransfer executes the state update from the atomic export transaction

func (*UnsignedExportTx) GasUsed

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

func (*UnsignedExportTx) InputUTXOs

func (tx *UnsignedExportTx) InputUTXOs() ids.Set

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

func (*UnsignedExportTx) SemanticVerify

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

SemanticVerify this transaction is valid.

func (*UnsignedExportTx) Verify

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

Verify this transaction is well-formed

type UnsignedImportTx

type UnsignedImportTx struct {
	axc.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 []*axc.TransferableInput `serialize:"true" json:"importedInputs"`
	// Outputs
	Outs []EVMOutput `serialize:"true" json:"outputs"`
}

UnsignedImportTx is an unsigned ImportTx

func (*UnsignedImportTx) AtomicOps

func (tx *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

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

Amount of [assetID] burned by this transaction

func (*UnsignedImportTx) EVMStateTransfer

func (tx *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

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

func (*UnsignedImportTx) InputUTXOs

func (tx *UnsignedImportTx) InputUTXOs() ids.Set

InputUTXOs returns the UTXOIDs of the imported funds

func (*UnsignedImportTx) SemanticVerify

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

SemanticVerify this transaction is valid.

func (*UnsignedImportTx) Verify

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

Verify this transaction is well-formed

type UnsignedTx

type UnsignedTx interface {
	Initialize(unsignedBytes, signedBytes []byte)
	ID() ids.ID
	GasUsed(fixedFee bool) (uint64, error)
	Burned(assetID ids.ID) (uint64, error)
	UnsignedBytes() []byte
	Bytes() []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

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

Clock implements the secp256k1fx interface

func (*VM) Codec

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

Codec implements the secp256k1fx interface

func (*VM) CodecRegistry

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

CodecRegistry implements the secp256k1fx interface

func (*VM) CreateHandlers

func (vm *VM) CreateHandlers() (map[string]*commonEng.HTTPHandler, error)

CreateHandlers makes new http handlers that can handle API calls

func (*VM) CreateStaticHandlers

func (vm *VM) CreateStaticHandlers() (map[string]*commonEng.HTTPHandler, error)

CreateStaticHandlers makes new http handlers that can handle API calls

func (*VM) FormatAddress

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

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

FormatLocalAddress takes in a raw address and produces the formatted address

func (*VM) GetActivationTime

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

implements SnowmanPlusPlusVM interface

func (*VM) GetAtomicUTXOs

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

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

func (*VM) GetBlockIDAtHeight

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

GetBlockIDAtHeight retrieves the blkID of the canonical block at [blkHeight] if [blkHeight] is less than the height of the last accepted block, this will return a canonical block. Otherwise, it may return a blkID that has not yet been accepted.

func (*VM) GetCurrentNonce

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

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

func (*VM) GetSpendableAXCWithFee

func (vm *VM) GetSpendableAXCWithFee(
	keys []*crypto.PrivateKeySECP256K1R,
	amount uint64,
	cost uint64,
	baseFee *big.Int,
) ([]EVMInput, [][]*crypto.PrivateKeySECP256K1R, error)

GetSpendableAXCWithFee returns a list of EVMInputs and keys (in corresponding order) to total [amount] + [fee] of [AXC] 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 [][]*crypto.PrivateKeySECP256K1R 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

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

GetSpendableFunds returns a list of EVMInputs and keys (in corresponding order) to total [amount] of [assetID] owned by [keys]. Note: we return [][]*crypto.PrivateKeySECP256K1R 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

func (vm *VM) HealthCheck() (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(
	ctx *snow.Context,
	dbManager manager.Manager,
	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

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

Logger implements the secp256k1fx interface

func (*VM) NewBlockBuilder

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

func (*VM) ParseAddress

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

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

func (*VM) ParseLocalAddress

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

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

func (*VM) SetPreference

func (vm *VM) SetPreference(blkID ids.ID) error

SetPreference sets what the current tail of the chain is

func (*VM) SetState

func (vm *VM) SetState(state snow.State) error

func (*VM) Shutdown

func (vm *VM) Shutdown() error

Shutdown implements the snowman.ChainVM interface

func (*VM) VerifyHeightIndex

func (vm *VM) VerifyHeightIndex() error

func (*VM) Version

func (vm *VM) Version() (string, error)

type VersionReply

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