emulator

package module
v0.38.1 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2022 License: Apache-2.0 Imports: 31 Imported by: 11

README


Logo

The Flow Emulator is a lightweight tool that emulates the behaviour of the real Flow network.
Read the docs»

Report Bug · Contribute



The Emulator

The emulator exposes a gRPC server that implements the Flow Access API, which is designed to have near feature parity with the real network API.

The Flowser Emulator Explorer

There is also a block explorer GUI for the emulator, that will help you speed up development when using the emulator.

Running

Configuration

The Flow Emulator can be run in different modes and settings, all of them are described in the table bellow.

Please note that if you will run the emulator using the Flow CLI you must use flags to pass configuration values and if you plan to run the emulator with Docker you must use the environment variables (Env) to pass configuration values.

Flag Env Default Description
--port, -p FLOW_PORT 3569 gRPC port to listen on
--rest-port FLOW_RESTPORT 8888 REST API port to listen on
--admin-port FLOW_ADMINPORT 8080 Admin API port to listen on
--verbose, -v FLOW_VERBOSE false Enable verbose logging (useful for debugging)
--log-format FLOW_LOGFORMAT text Output log format (valid values text, JSON)
--block-time, -b FLOW_BLOCKTIME 0 Time between sealed blocks. Valid units are ns, us (or µs), ms, s, m, h
--contracts FLOW_WITHCONTRACTS false Start with contracts like FUSD, NFT and an NFT Marketplace, when the emulator starts
--service-priv-key FLOW_SERVICEPRIVATEKEY random Private key used for the service account
--service-sig-algo FLOW_SERVICEKEYSIGALGO ECDSA_P256 Service account key signature algorithm
--service-hash-algo FLOW_SERVICEKEYHASHALGO SHA3_256 Service account key hash algorithm
--init FLOW_INIT false Generate and set a new service account
--rest-debug FLOW_RESTDEBUG false Enable REST API debugging output
--grpc-debug FLOW_GRPCDEBUG false Enable gRPC server reflection for debugging with grpc_cli
--persist FLOW_PERSIST false Enable persistence of the state between restarts
--snapshot FLOW_SNAPSHOT false Enable snapshot support ( this option automatically enables persistence )
--dbpath FLOW_DBPATH ./flowdb Specify path for the database file persisting the state
--simple-addresses FLOW_SIMPLEADDRESSES false Use sequential addresses starting with 0x1
--token-supply FLOW_TOKENSUPPLY 1000000000.0 Initial FLOW token supply
--transaction-expiry FLOW_TRANSACTIONEXPIRY 10 Transaction expiry, measured in blocks
--storage-limit FLOW_STORAGELIMITENABLED true Enable account storage limit
--storage-per-flow FLOW_STORAGEMBPERFLOW Specify size of the storage in MB for each FLOW in account balance. Default value from the flow-go
--min-account-balance FLOW_MINIMUMACCOUNTBALANCE Specify minimum balance the account must have. Default value from the flow-go
--transaction-fees FLOW_TRANSACTIONFEESENABLED false Enable variable transaction fees and execution effort metering
as decribed in Variable Transaction Fees: Execution Effort FLIP
--transaction-max-gas-limit FLOW_TRANSACTIONMAXGASLIMIT 9999 Maximum gas limit for transactions
--script-gas-limit FLOW_SCRIPTGASLIMIT 100000 Specify gas limit for script execution
--with-contracts FLOW_WITHCONTRACTS false Deploy common contracts when emulator starts
--skip-transaction-validation FLOW_SKIPTRANSACTIONVALIDATION false Skip verification of transaction signatures and sequence numbers
--host FLOW_HOST 127.0.0.1 Host to listen on for emulator GRPC/REST/Admin servers
--chain-id FLOW_CHAINID emulator Chain to emulate for address generation. Valid values are: 'emulator', 'testnet', 'mainnet'

Running the emulator with the Flow CLI

The emulator is bundled with the Flow CLI, a command-line interface for working with Flow.

Installation

Follow these steps to install the Flow CLI.

Starting the server

Starting the emulator by using Flow CLI also leverages CLI configuration file flow.json. You can use the flow.json to specify the service account which will be reused between restarts. Read more about CLI configuration here.

You can start the emulator with the Flow CLI:

flow emulator --init

Using the emulator in a project

You can start the emulator in your project context by running the above command in the same directory as flow.json. This will configure the emulator with your project's service account, meaning you can use it to sign and submit transactions. Read more about the project and configuration here.

Using Emulator in Go

You can use the emulator as a module in your Go project. To install emulator, use go get:

go get github.com/onflow/flow-emulator

After installing the emulator module you can initialize it in the code:

var opts []emulator.Option
privKey, err := crypto.DecodePrivateKeyHex(crypto.ECDSA_P256, "")

opts = append(opts, emulator.WithServicePublicKey(
  privKey.PublicKey(),
  crypto.ECDSA_P256,
  crypto.SHA3_256,
))

blockchain, err := emulator.NewBlockchain(opts...)

You can then access all methods of the blockchain like so:

account, err := blockchain.GetAccount(address) 

Managing emulator state

It's possible to manage emulator state by using the admin API. You can at any point create a new named snapshot of the state and then at any later point revert emulator state to that reference.

In order to use the state management functionality you need to run the emulator with persistent state:

flow emulator --persist

Create a new snapshot by doing an HTTP request:

GET http://localhost:8080/emulator/snapshot/{name}

Please note the example above uses the default admin API port

At any later point you can reload to that snapshot by executing the same HTTP request as before. You need to use the same value for name parameter.

The snapshot functionality is a great tool for testing where you can first initialize a base snapshot with seed values, execute the test and then revert to that initialized state.

Running the emulator with Docker

Docker builds for the emulator are automatically built and pushed to gcr.io/flow-container-registry/emulator, tagged by commit and semantic version. You can also build the image locally.

docker run gcr.io/flow-container-registry/emulator

The full list of environment variables can be found here. You can pass any environment variable by using -e docker flag and pass the valid value.

Custom Configuration Example:

docker run -e FLOW_PORT=9001 -e FLOW_VERBOSE=true -e FLOW_SERVICEPRIVATEKEY=<hex-encoded key> gcr.io/flow-container-registry/emulator

To generate a service key, use the keys generate command in the Flow CLI.

flow keys generate

Development

Read contributing document.

Documentation

Overview

  • Flow Emulator *
  • Copyright 2019 Dapper Labs, Inc. *
  • Licensed under the Apache License, Version 2.0 (the "License");
  • you may not use this file except in compliance with the License.
  • You may obtain a copy of the License at *
  • http://www.apache.org/licenses/LICENSE-2.0 *
  • Unless required by applicable law or agreed to in writing, software
  • distributed under the License is distributed on an "AS IS" BASIS,
  • WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  • See the License for the specific language governing permissions and
  • limitations under the License.

Package emulator provides an emulated version of the Flow blockchain that can be used for development purposes.

This package can be used as a library or as a standalone application.

When used as a library, this package provides tools to write programmatic tests for Flow applications.

When used as a standalone application, this package implements the Flow Access API and is fully-compatible with Flow gRPC client libraries.

Index

Constants

View Source
const DefaultServiceKeyHashAlgo = sdkcrypto.SHA3_256
View Source
const DefaultServiceKeySigAlgo = sdkcrypto.ECDSA_P256
View Source
const MaxViewIncrease = 3

MaxViewIncrease represents the largest difference in view number between two consecutive blocks. The minimum view increment is 1.

Variables

This section is empty.

Functions

This section is empty.

Types

type AccountNotFoundError

type AccountNotFoundError struct {
	Address flowgo.Address
}

An AccountNotFoundError indicates that an account could not be found.

func (*AccountNotFoundError) Error

func (e *AccountNotFoundError) Error() string

type AccountStorage added in v0.34.0

type AccountStorage struct {
	Address sdk.Address
	Private StorageItem
	Public  StorageItem
	Storage StorageItem
	Account *flow.Account
}

func NewAccountStorage added in v0.34.0

func NewAccountStorage(
	address sdk.Address,
	account *flow.Account,
	storage *runtime.Storage,
	inter *interpreter.Interpreter,
) (*AccountStorage, error)

NewAccountStorage creates an instance of the storage that holds the values for each storage path.

type BlockNotFoundByHeightError

type BlockNotFoundByHeightError struct {
	Height uint64
}

A BlockNotFoundByHeightError indicates that a block could not be found at the specified height.

func (*BlockNotFoundByHeightError) Error

type BlockNotFoundByIDError

type BlockNotFoundByIDError struct {
	ID flowsdk.Identifier
}

A BlockNotFoundByIDError indicates that a block with the specified ID could not be found.

func (*BlockNotFoundByIDError) Error

func (e *BlockNotFoundByIDError) Error() string

type BlockNotFoundError

type BlockNotFoundError interface {
	// contains filtered or unexported methods
}

A BlockNotFoundError indicates that a block could not be found.

type Blockchain

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

Blockchain emulates the functionality of the Flow blockchain.

func NewBlockchain

func NewBlockchain(opts ...Option) (*Blockchain, error)

NewBlockchain instantiates a new emulated blockchain with the provided options.

func (*Blockchain) AddTransaction

func (b *Blockchain) AddTransaction(tx sdk.Transaction) error

AddTransaction validates a transaction and adds it to the current pending block.

func (*Blockchain) CommitBlock

func (b *Blockchain) CommitBlock() (*flowgo.Block, error)

CommitBlock seals the current pending block and saves it to storage.

This function clears the pending transaction pool and resets the pending block.

func (*Blockchain) CreateAccount

func (b *Blockchain) CreateAccount(publicKeys []*sdk.AccountKey, contracts []templates.Contract) (sdk.Address, error)

CreateAccount submits a transaction to create a new account with the given account keys and contracts. The transaction is paid by the service account.

func (*Blockchain) ExecuteAndCommitBlock

func (b *Blockchain) ExecuteAndCommitBlock() (*flowgo.Block, []*types.TransactionResult, error)

ExecuteAndCommitBlock is a utility that combines ExecuteBlock with CommitBlock.

func (*Blockchain) ExecuteBlock

func (b *Blockchain) ExecuteBlock() ([]*types.TransactionResult, error)

ExecuteBlock executes the remaining transactions in pending block.

func (*Blockchain) ExecuteNextTransaction

func (b *Blockchain) ExecuteNextTransaction() (*types.TransactionResult, error)

ExecuteNextTransaction executes the next indexed transaction in pending block.

func (*Blockchain) ExecuteScript

func (b *Blockchain) ExecuteScript(script []byte, arguments [][]byte) (*types.ScriptResult, error)

ExecuteScript executes a read-only script against the world state and returns the result.

func (*Blockchain) ExecuteScriptAtBlock

func (b *Blockchain) ExecuteScriptAtBlock(script []byte, arguments [][]byte, blockHeight uint64) (*types.ScriptResult, error)

func (*Blockchain) GetAccount

func (b *Blockchain) GetAccount(address sdk.Address) (*sdk.Account, error)

GetAccount returns the account for the given address.

func (*Blockchain) GetAccountAtBlock

func (b *Blockchain) GetAccountAtBlock(address sdk.Address, blockHeight uint64) (*sdk.Account, error)

GetAccountAtBlock returns the account for the given address at specified block height.

func (*Blockchain) GetAccountStorage added in v0.34.0

func (b *Blockchain) GetAccountStorage(address sdk.Address) (*AccountStorage, error)

func (*Blockchain) GetBlockByHeight

func (b *Blockchain) GetBlockByHeight(height uint64) (*flowgo.Block, error)

GetBlockByHeight gets a block by height.

func (*Blockchain) GetBlockByID

func (b *Blockchain) GetBlockByID(id sdk.Identifier) (*flowgo.Block, error)

GetBlockByID gets a block by ID.

func (*Blockchain) GetChain added in v0.14.2

func (b *Blockchain) GetChain() flowgo.Chain

func (*Blockchain) GetCollection

func (b *Blockchain) GetCollection(colID sdk.Identifier) (*sdk.Collection, error)

func (*Blockchain) GetEventsByHeight

func (b *Blockchain) GetEventsByHeight(blockHeight uint64, eventType string) ([]sdk.Event, error)

GetEventsByHeight returns the events in the block at the given height, optionally filtered by type.

func (*Blockchain) GetLatestBlock

func (b *Blockchain) GetLatestBlock() (*flowgo.Block, error)

GetLatestBlock gets the latest sealed block.

func (*Blockchain) GetTransaction

func (b *Blockchain) GetTransaction(id sdk.Identifier) (*sdk.Transaction, error)

GetTransaction gets an existing transaction by ID.

The function first looks in the pending block, then the current blockchain state.

func (*Blockchain) GetTransactionResult

func (b *Blockchain) GetTransactionResult(ID sdk.Identifier) (*sdk.TransactionResult, error)

func (*Blockchain) PendingBlockID

func (b *Blockchain) PendingBlockID() flowgo.Identifier

PendingBlockID returns the ID of the pending block.

func (*Blockchain) PendingBlockTimestamp

func (b *Blockchain) PendingBlockTimestamp() time.Time

PendingBlockTimestamp returns the Timestamp of the pending block.

func (*Blockchain) PendingBlockView added in v0.17.2

func (b *Blockchain) PendingBlockView() uint64

PendingBlockView returns the view of the pending block.

func (*Blockchain) ResetPendingBlock

func (b *Blockchain) ResetPendingBlock() error

ResetPendingBlock clears the transactions in pending block.

func (*Blockchain) ServiceKey

func (b *Blockchain) ServiceKey() ServiceKey

ServiceKey returns the service private key for this blockchain.

type CollectionNotFoundError

type CollectionNotFoundError struct {
	ID flowsdk.Identifier
}

A CollectionNotFoundError indicates that a collection could not be found.

func (*CollectionNotFoundError) Error

func (e *CollectionNotFoundError) Error() string

type DuplicateTransactionError

type DuplicateTransactionError struct {
	TxID flowgo.Identifier
}

A DuplicateTransactionError indicates that a transaction has already been submitted.

func (*DuplicateTransactionError) Error

func (e *DuplicateTransactionError) Error() string

type ExecutionError

type ExecutionError struct {
	Code    int
	Message string
}

An ExecutionError occurs when a transaction fails to execute.

func (*ExecutionError) Error

func (e *ExecutionError) Error() string

type ExpiredTransactionError

type ExpiredTransactionError struct {
	RefHeight, FinalHeight uint64
}

ExpiredTransactionError indicates that a transaction has expired.

func (*ExpiredTransactionError) Error

func (e *ExpiredTransactionError) Error() string

type IncompleteTransactionError

type IncompleteTransactionError struct {
	MissingFields []string
}

IncompleteTransactionError indicates that a transaction is missing one or more required fields.

func (*IncompleteTransactionError) Error

type IndexedTransactionResult

type IndexedTransactionResult struct {
	Transaction *fvm.TransactionProcedure
	Index       uint32
}

type InvalidStateVersionError

type InvalidStateVersionError struct {
	Version crypto.Hash
}

An InvalidStateVersionError indicates that a state version hash provided is invalid.

func (*InvalidStateVersionError) Error

func (e *InvalidStateVersionError) Error() string

type InvalidTransactionGasLimitError

type InvalidTransactionGasLimitError struct {
	Maximum uint64
	Actual  uint64
}

InvalidTransactionGasLimitError indicates that a transaction specifies a gas limit that exceeds the maximum.

func (*InvalidTransactionGasLimitError) Error

type InvalidTransactionScriptError

type InvalidTransactionScriptError struct {
	ParserErr error
}

InvalidTransactionScriptError indicates that a transaction contains an invalid Cadence script.

func (*InvalidTransactionScriptError) Error

func (*InvalidTransactionScriptError) Unwrap

type NotFoundError

type NotFoundError interface {
	// contains filtered or unexported methods
}

A NotFoundError indicates that an entity could not be found.

type Option

type Option func(*config)

Option is a function applying a change to the emulator config.

func WithChainID added in v0.36.0

func WithChainID(chainID flowgo.ChainID) Option

WithChainID sets chain type for address generation The default is emulator.

func WithGenesisTokenSupply

func WithGenesisTokenSupply(supply cadence.UFix64) Option

WithGenesisTokenSupply sets the genesis token supply.

func WithLogger added in v0.33.4

func WithLogger(
	logger zerolog.Logger,
) Option

WithLogger sets the logger

func WithMinimumStorageReservation added in v0.23.0

func WithMinimumStorageReservation(minimumStorageReservation cadence.UFix64) Option

WithMinimumStorageReservation sets the minimum account balance.

The cost of creating new accounts is also set to this value. The default is taken from fvm.DefaultMinimumStorageReservation

func WithScriptGasLimit

func WithScriptGasLimit(limit uint64) Option

WithScriptGasLimit sets the gas limit for scripts.

This limit does not affect transactions, which declare their own limit. Use WithTransactionMaxGasLimit to set the maximum gas limit for transactions.

func WithServicePrivateKey added in v0.27.3

func WithServicePrivateKey(
	privateKey sdkcrypto.PrivateKey,
	sigAlgo sdkcrypto.SignatureAlgorithm,
	hashAlgo sdkcrypto.HashAlgorithm,
) Option

WithServicePrivateKey sets the service key from private key.

func WithServicePublicKey

func WithServicePublicKey(
	servicePublicKey sdkcrypto.PublicKey,
	sigAlgo sdkcrypto.SignatureAlgorithm,
	hashAlgo sdkcrypto.HashAlgorithm,
) Option

WithServicePublicKey sets the service key from a public key.

func WithSimpleAddresses

func WithSimpleAddresses() Option

WithSimpleAddresses enables simple addresses, which are sequential starting with 0x01.

func WithStorageLimitEnabled added in v0.14.0

func WithStorageLimitEnabled(enabled bool) Option

WithStorageLimitEnabled enables/disables limiting account storage used to their storage capacity.

If set to false, accounts can store any amount of data, otherwise they can only store as much as their storage capacity. The default is true.

func WithStorageMBPerFLOW added in v0.23.0

func WithStorageMBPerFLOW(storageMBPerFLOW cadence.UFix64) Option

WithStorageMBPerFLOW sets the cost of a megabyte of storage in FLOW

the default is taken from fvm.DefaultStorageMBPerFLOW

func WithStore

func WithStore(store storage.Store) Option

WithStore sets the persistent storage provider.

func WithTransactionExpiry

func WithTransactionExpiry(expiry uint) Option

WithTransactionExpiry sets the transaction expiry measured in blocks.

If set to zero, transaction expiry is disabled and the reference block ID field is not required.

func WithTransactionFeesEnabled added in v0.14.2

func WithTransactionFeesEnabled(enabled bool) Option

WithTransactionFeesEnabled enables/disables transaction fees.

If set to false transactions don't cost any flow. The default is false.

func WithTransactionMaxGasLimit added in v0.12.4

func WithTransactionMaxGasLimit(maxLimit uint64) Option

WithTransactionMaxGasLimit sets the maximum gas limit for transactions.

Individual transactions will still be bounded by the limit they declare. This function sets the maximum limit that any transaction can declare.

This limit does not affect script executions. Use WithScriptGasLimit to set the gas limit for script executions.

func WithTransactionValidationEnabled added in v0.34.0

func WithTransactionValidationEnabled(enabled bool) Option

WithTransactionValidationEnabled enables/disables transaction validation.

If set to false, the emulator will not verify transaction signatures or validate sequence numbers.

The default is true.

type PendingBlockCommitBeforeExecutionError

type PendingBlockCommitBeforeExecutionError struct {
	BlockID flowgo.Identifier
}

A PendingBlockCommitBeforeExecutionError indicates that the current pending block has not been executed (cannot commit).

func (*PendingBlockCommitBeforeExecutionError) Error

type PendingBlockMidExecutionError

type PendingBlockMidExecutionError struct {
	BlockID flowgo.Identifier
}

A PendingBlockMidExecutionError indicates that the current pending block is mid-execution.

func (*PendingBlockMidExecutionError) Error

type PendingBlockTransactionsExhaustedError

type PendingBlockTransactionsExhaustedError struct {
	BlockID flowgo.Identifier
}

A PendingBlockTransactionsExhaustedError indicates that the current pending block has finished executing (no more transactions to execute).

func (*PendingBlockTransactionsExhaustedError) Error

type ServiceKey

type ServiceKey struct {
	Index          int
	Address        sdk.Address
	SequenceNumber uint64
	PrivateKey     sdkcrypto.PrivateKey
	PublicKey      sdkcrypto.PublicKey
	HashAlgo       sdkcrypto.HashAlgorithm
	SigAlgo        sdkcrypto.SignatureAlgorithm
	Weight         int
}

func DefaultServiceKey

func DefaultServiceKey() ServiceKey

func GenerateDefaultServiceKey

func GenerateDefaultServiceKey(
	sigAlgo sdkcrypto.SignatureAlgorithm,
	hashAlgo sdkcrypto.HashAlgorithm,
) ServiceKey

func (ServiceKey) AccountKey

func (s ServiceKey) AccountKey() *sdk.AccountKey

func (ServiceKey) Signer

func (s ServiceKey) Signer() (sdkcrypto.Signer, error)

type StorageError

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

A StorageError indicates that an error occurred in the storage provider.

func (*StorageError) Error

func (e *StorageError) Error() string

func (*StorageError) Unwrap

func (e *StorageError) Unwrap() error

type StorageItem added in v0.34.0

type StorageItem map[string]cadence.Value

func (StorageItem) Get added in v0.34.0

func (s StorageItem) Get(key string) cadence.Value

type TransactionNotFoundError

type TransactionNotFoundError struct {
	ID flowgo.Identifier
}

A TransactionNotFoundError indicates that a transaction could not be found.

func (*TransactionNotFoundError) Error

func (e *TransactionNotFoundError) Error() string

type TransactionValidationError

type TransactionValidationError interface {
	// contains filtered or unexported methods
}

A TransactionValidationError indicates that a submitted transaction is invalid.

Directories

Path Synopsis
cmd
sdk
backend/mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
Package storage defines the interface and implementations for interacting with persistent chain state.
Package storage defines the interface and implementations for interacting with persistent chain state.
mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
utils

Jump to

Keyboard shortcuts

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