cosmwasm

package module
v2.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 17, 2024 License: Apache-2.0 Imports: 6 Imported by: 14

README

wasmvm

This is a wrapper around the CosmWasm VM. It allows you to compile, initialize and execute CosmWasm smart contracts from Go applications, in particular from x/wasm.

More information on what is CosmWasm and how to use it can be found here: CosmWasm Docs. To generate and show the Rust part documentation you can run make doc-rust.

Structure

This repo contains both Rust and Go code. The Rust code is compiled into a library (shared .dll/.dylib/.so or static .a) to be linked via cgo and wrapped with a pleasant Go API. The full build step involves compiling Rust -> C library, and linking that library to the Go code. For ergonomics of the user, we will include pre-compiled libraries to easily link with, and Go developers should just be able to import this directly.

Rust code

The Rust code lives in a sub-folder ./libwasmvm. This folder compiles to a library that can be used via FFI. It is compiled like this:

# Run unit tests
(cd libwasmvm && cargo test)

# Create release build for your current system. Uses whatever default Rust
# version you have installed.
make build-libwasmvm

# Create reproducible release builds for other systems (slow, don't use for development)
make release-build-alpine
make release-build-linux
make release-build-macos
make release-build-windows
Go code

The Go code consists of three packages:

  1. The types (the github.com/CosmWasm/wasmvm/types import), using package types
  2. The internal package internal/api, using package api
  3. This repo (the github.com/CosmWasm/wasmvm import), using package cosmwasm

The dependencies between them are as follows:

graph TD;
    api-->types;
    cosmwasm-->types;
    cosmwasm-->api;

The Go code is built like this:

make build-go
make test
Package github.com/CosmWasm/wasmvm/types

This packages contains types used by the two other packages. It can be compiled without cgo.

# Build
go build ./types
# Build without CGO
CGO_ENABLED=0 go build ./types
Package internal/api

This package contains the code binding the libwasmvm build to the Go code. All low level FFI handling code belongs there. This package can only be built using cgo. Uing the internal/ convention makes this package fully private.

Package github.com/CosmWasm/wasmvm

This is the package users import. It can be compiled without cgo, but when you do so, a lot of functionality is removed.

# Build
go build .
# Build without CGO
CGO_ENABLED=0 go build .

In the case that it may be desirable to compile with cgo, but with libwasmvm linking disabled an additional build tag is available.

# Build with CGO, but with libwasmvm linking disabled
go build -tags "nolink_libwasmvm"

Supported Platforms

See COMPILER_VERSIONS.md for information on Go and Rust compiler support.

The Rust implementation of the VM is compiled to a library called libwasmvm. This is then linked to the Go code when the final binary is built. For that reason not all systems supported by Go are supported by this project.

Linux (tested on Ubuntu, Debian, Alpine) and macOS is supported. We are working on Windows support with very low priority (#288).

Builds of libwasmvm

Our system currently supports the following builds. In general we can only support targets that are supported by Wasmer's singlepass backend, which for example excludes all 32 bit systems.

OS family Arch Linking Supported Note
Linux (glibc) x86_64 shared ✅​libwasmvm.x86_64.so
Linux (glibc) x86_64 static 🚫​ Would link libwasmvm statically but glibc dynamically as static glibc linking is not recommended. Potentially interesting for Osmosis.
Linux (glibc) aarch64 shared ✅​libwasmvm.aarch64.so
Linux (glibc) aarch64 static 🚫​
Linux (musl) x86_64 shared 🚫​ Possible but not needed
Linux (musl) x86_64 static ✅​libwasmvm_muslc.x86_64.a
Linux (musl) aarch64 shared 🚫​ Possible but not needed
Linux (musl) aarch64 static ✅​libwasmvm_muslc.aarch64.a
macOS x86_64 shared ✅​libwasmvm.dylib Fat/universal library with multiple archs (#294)
macOS x86_64 static ✅​libwasmvmstatic_darwin.a Fat/universal library with multiple archs (#407)
macOS aarch64 shared ✅​libwasmvm.dylib Fat/universal library with multiple archs (#294)
macOS aarch64 static ✅​libwasmvmstatic_darwin.a Fat/universal library with multiple archs (#407)
Windows (mingw) x86_64 shared 🏗​wasmvm.dll Shared library linking not working on Windows (#389)
Windows (mingw) x86_64 static 🚫​ Unclear if this can work using a cross compiler; needs research on .lib (MSVC toolchain) vs. .a (GNU toolchain). (#389)
Windows (mingw) aarch64 shared 🚫​ Shared library linking not working on Windows (#389)
Windows (mingw) aarch64 static 🚫​ Unclear if this can work using a cross compiler; needs research on .lib (MSVC toolchain) vs. .a (GNU toolchain). (#389)

Development

There are two halves to this code - go and rust. The first step is to ensure that there is a proper dll built for your platform. This should be api/libwasmvm.X, where X is:

  • so for Linux systems
  • dylib for MacOS
  • dll for Windows - Not currently supported due to upstream dependency

If this is present, then make test will run the Go test suite and you can import this code freely. If it is not present you will have to build it for your system, and ideally add it to this repo with a PR (on your fork). We will set up a proper CI system for building these binaries, but we are not there yet.

To build the rust side, try make build-libwasmvm and wait for it to compile. This depends on cargo being installed with rustc version 1.47+. Generally, you can just use rustup to install all this with no problems.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DeserializeResponse

func DeserializeResponse(gasLimit uint64, deserCost types.UFraction, gasReport *types.GasReport, data []byte, response any) error

func LibwasmvmVersion

func LibwasmvmVersion() (string, error)

LibwasmvmVersion returns the version of the loaded library at runtime. This can be used for debugging to verify the loaded version matches the expected version.

When cgo is disabled at build time, this returns an error at runtime.

Types

type Checksum

type Checksum = types.Checksum

Checksum represents a hash of the Wasm bytecode that serves as an ID. Must be generated from this library.

func CreateChecksum

func CreateChecksum(wasm []byte) (Checksum, error)

CreateChecksum performs the hashing of Wasm bytes to obtain the CosmWasm checksum.

Ony Wasm blobs are allowed as inputs and a magic byte check will be performed to avoid accidental misusage.

type GasMeter

type GasMeter = types.GasMeter

GasMeter is a read-only version of the sdk gas meter

type GoAPI

type GoAPI = types.GoAPI

GoAPI is a reference to some "precompiles", go callbacks

type KVStore

type KVStore = types.KVStore

KVStore is a reference to some sub-kvstore that is valid for one instance of a code

type Querier

type Querier = types.Querier

Querier lets us make read-only queries on other modules

type VM

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

VM is the main entry point to this library. You should create an instance with its own subdirectory to manage state inside, and call it for all cosmwasm code related actions.

func NewVM

func NewVM(dataDir string, supportedCapabilities []string, memoryLimit uint32, printDebug bool, cacheSize uint32) (*VM, error)

NewVM creates a new VM.

`dataDir` is a base directory for Wasm blobs and various caches. `supportedCapabilities` is a list of capabilities supported by the chain. `memoryLimit` is the memory limit of each contract execution (in MiB) `printDebug` is a flag to enable/disable printing debug logs from the contract to STDOUT. This should be false in production environments. `cacheSize` sets the size in MiB of an in-memory cache for e.g. module caching. Set to 0 to disable. `deserCost` sets the gas cost of deserializing one byte of data.

func NewVMWithConfig added in v2.2.0

func NewVMWithConfig(config types.VMConfig, printDebug bool) (*VM, error)

NewVMWithConfig creates a new VM with a custom configuration. This allows for more fine-grained control over the VM's behavior compared to NewVM and can be extended more easily in the future.

func (*VM) AnalyzeCode

func (vm *VM) AnalyzeCode(checksum Checksum) (*types.AnalysisReport, error)

Returns a report of static analysis of the wasm contract (uncompiled). This contract must have been stored in the cache previously (via Create). Only info currently returned is if it exposes all ibc entry points, but this may grow later

func (*VM) Cleanup

func (vm *VM) Cleanup()

Cleanup should be called when no longer using this instances. It frees resources in libwasmvm (the Rust part) and releases a lock in the base directory.

func (*VM) Execute

func (vm *VM) Execute(
	checksum Checksum,
	env types.Env,
	info types.MessageInfo,
	executeMsg []byte,
	store KVStore,
	goapi GoAPI,
	querier Querier,
	gasMeter GasMeter,
	gasLimit uint64,
	deserCost types.UFraction,
) (*types.ContractResult, uint64, error)

Execute calls a given contract. Since the only difference between contracts with the same Checksum is the data in their local storage, and their address in the outside world, we need no ContractID here. (That is a detail for the external, sdk-facing, side).

The caller is responsible for passing the correct `store` (which must have been initialized exactly once), and setting the env with relevant info on this instance (address, balance, etc)

func (*VM) GetCode

func (vm *VM) GetCode(checksum Checksum) (WasmCode, error)

GetCode will load the original Wasm code for the given checksum. This will only succeed if that checksum was previously returned from a call to StoreCode.

This can be used so that the (short) checksum is stored in the iavl tree and the larger binary blobs (wasm and compiled modules) are all managed by libwasmvm/cosmwasm-vm (Rust part).

func (*VM) GetMetrics

func (vm *VM) GetMetrics() (*types.Metrics, error)

GetMetrics some internal metrics for monitoring purposes.

func (*VM) GetPinnedMetrics added in v2.1.0

func (vm *VM) GetPinnedMetrics() (*types.PinnedMetrics, error)

GetPinnedMetrics returns some internal metrics of pinned contracts for monitoring purposes. The order of entries is non-deterministic and the values are node-specific. Don't use this in consensus-critical contexts.

func (*VM) IBCChannelClose

func (vm *VM) IBCChannelClose(
	checksum Checksum,
	env types.Env,
	msg types.IBCChannelCloseMsg,
	store KVStore,
	goapi GoAPI,
	querier Querier,
	gasMeter GasMeter,
	gasLimit uint64,
	deserCost types.UFraction,
) (*types.IBCBasicResult, uint64, error)

IBCChannelClose is available on IBC-enabled contracts and is a hook to call into at the end of the channel lifetime

func (*VM) IBCChannelConnect

func (vm *VM) IBCChannelConnect(
	checksum Checksum,
	env types.Env,
	msg types.IBCChannelConnectMsg,
	store KVStore,
	goapi GoAPI,
	querier Querier,
	gasMeter GasMeter,
	gasLimit uint64,
	deserCost types.UFraction,
) (*types.IBCBasicResult, uint64, error)

IBCChannelConnect is available on IBC-enabled contracts and is a hook to call into during the handshake pahse

func (*VM) IBCChannelOpen

func (vm *VM) IBCChannelOpen(
	checksum Checksum,
	env types.Env,
	msg types.IBCChannelOpenMsg,
	store KVStore,
	goapi GoAPI,
	querier Querier,
	gasMeter GasMeter,
	gasLimit uint64,
	deserCost types.UFraction,
) (*types.IBCChannelOpenResult, uint64, error)

IBCChannelOpen is available on IBC-enabled contracts and is a hook to call into during the handshake pahse

func (*VM) IBCDestinationCallback added in v2.1.0

func (vm *VM) IBCDestinationCallback(
	checksum Checksum,
	env types.Env,
	msg types.IBCDestinationCallbackMsg,
	store KVStore,
	goapi GoAPI,
	querier Querier,
	gasMeter GasMeter,
	gasLimit uint64,
	deserCost types.UFraction,
) (*types.IBCBasicResult, uint64, error)

IBCDestinationCallback is available on IBC-enabled contracts with the corresponding entrypoint and should be called when an incoming callbacks-enabled IBC packet is received.

func (*VM) IBCPacketAck

func (vm *VM) IBCPacketAck(
	checksum Checksum,
	env types.Env,
	msg types.IBCPacketAckMsg,
	store KVStore,
	goapi GoAPI,
	querier Querier,
	gasMeter GasMeter,
	gasLimit uint64,
	deserCost types.UFraction,
) (*types.IBCBasicResult, uint64, error)

IBCPacketAck is available on IBC-enabled contracts and is called when an the response for an outgoing packet (previously sent by this contract) is received

func (*VM) IBCPacketReceive

func (vm *VM) IBCPacketReceive(
	checksum Checksum,
	env types.Env,
	msg types.IBCPacketReceiveMsg,
	store KVStore,
	goapi GoAPI,
	querier Querier,
	gasMeter GasMeter,
	gasLimit uint64,
	deserCost types.UFraction,
) (*types.IBCReceiveResult, uint64, error)

IBCPacketReceive is available on IBC-enabled contracts and is called when an incoming packet is received on a channel belonging to this contract

func (*VM) IBCPacketTimeout

func (vm *VM) IBCPacketTimeout(
	checksum Checksum,
	env types.Env,
	msg types.IBCPacketTimeoutMsg,
	store KVStore,
	goapi GoAPI,
	querier Querier,
	gasMeter GasMeter,
	gasLimit uint64,
	deserCost types.UFraction,
) (*types.IBCBasicResult, uint64, error)

IBCPacketTimeout is available on IBC-enabled contracts and is called when an outgoing packet (previously sent by this contract) will provably never be executed. Usually handled like ack returning an error

func (*VM) IBCSourceCallback added in v2.1.0

func (vm *VM) IBCSourceCallback(
	checksum Checksum,
	env types.Env,
	msg types.IBCSourceCallbackMsg,
	store KVStore,
	goapi GoAPI,
	querier Querier,
	gasMeter GasMeter,
	gasLimit uint64,
	deserCost types.UFraction,
) (*types.IBCBasicResult, uint64, error)

IBCSourceCallback is available on IBC-enabled contracts with the corresponding entrypoint and should be called when the response (ack or timeout) for an outgoing callbacks-enabled packet (previously sent by this contract) is received.

func (*VM) Instantiate

func (vm *VM) Instantiate(
	checksum Checksum,
	env types.Env,
	info types.MessageInfo,
	initMsg []byte,
	store KVStore,
	goapi GoAPI,
	querier Querier,
	gasMeter GasMeter,
	gasLimit uint64,
	deserCost types.UFraction,
) (*types.ContractResult, uint64, error)

Instantiate will create a new contract based on the given Checksum. We can set the initMsg (contract "genesis") here, and it then receives an account and address and can be invoked (Execute) many times.

Storage should be set with a PrefixedKVStore that this code can safely access.

Under the hood, we may recompile the wasm, use a cached native compile, or even use a cached instance for performance.

func (*VM) Migrate

func (vm *VM) Migrate(
	checksum Checksum,
	env types.Env,
	migrateMsg []byte,
	store KVStore,
	goapi GoAPI,
	querier Querier,
	gasMeter GasMeter,
	gasLimit uint64,
	deserCost types.UFraction,
) (*types.ContractResult, uint64, error)

Migrate will migrate an existing contract to a new code binary. This takes storage of the data from the original contract and the Checksum of the new contract that should replace it. This allows it to run a migration step if needed, or return an error if unable to migrate the given data.

MigrateMsg has some data on how to perform the migration.

func (*VM) MigrateWithInfo added in v2.2.0

func (vm *VM) MigrateWithInfo(
	checksum Checksum,
	env types.Env,
	migrateMsg []byte,
	migrateInfo types.MigrateInfo,
	store KVStore,
	goapi GoAPI,
	querier Querier,
	gasMeter GasMeter,
	gasLimit uint64,
	deserCost types.UFraction,
) (*types.ContractResult, uint64, error)

MigrateWithInfo will migrate an existing contract to a new code binary. This takes storage of the data from the original contract and the Checksum of the new contract that should replace it. This allows it to run a migration step if needed, or return an error if unable to migrate the given data.

MigrateMsg has some data on how to perform the migration.

MigrateWithInfo takes one more argument - `migateInfo`. It consist of an additional data related to the on-chain current contract's state version.

func (*VM) Pin

func (vm *VM) Pin(checksum Checksum) error

Pin pins a code to an in-memory cache, such that is always loaded quickly when executed. Pin is idempotent.

func (*VM) Query

func (vm *VM) Query(
	checksum Checksum,
	env types.Env,
	queryMsg []byte,
	store KVStore,
	goapi GoAPI,
	querier Querier,
	gasMeter GasMeter,
	gasLimit uint64,
	deserCost types.UFraction,
) (*types.QueryResult, uint64, error)

Query allows a client to execute a contract-specific query. If the result is not empty, it should be valid json-encoded data to return to the client. The meaning of path and data can be determined by the code. Path is the suffix of the abci.QueryRequest.Path

func (*VM) RemoveCode

func (vm *VM) RemoveCode(checksum Checksum) error

func (*VM) Reply

func (vm *VM) Reply(
	checksum Checksum,
	env types.Env,
	reply types.Reply,
	store KVStore,
	goapi GoAPI,
	querier Querier,
	gasMeter GasMeter,
	gasLimit uint64,
	deserCost types.UFraction,
) (*types.ContractResult, uint64, error)

Reply allows the native Go wasm modules to make a priviledged call to return the result of executing a SubMsg.

These work much like Sudo (same scenario) but focuses on one specific case (and one message type)

func (*VM) StoreCode

func (vm *VM) StoreCode(code WasmCode, gasLimit uint64) (Checksum, uint64, error)

StoreCode will compile the Wasm code, and store the resulting compiled module as well as the original code. Both can be referenced later via Checksum. This must be done one time for given code, after which it can be instatitated many times, and each instance called many times.

For example, the code for all ERC-20 contracts should be the same. This function stores the code for that contract only once, but it can be instantiated with custom inputs in the future.

Returns both the checksum, as well as the gas cost of compilation (in CosmWasm Gas) or an error.

func (*VM) StoreCodeUnchecked

func (vm *VM) StoreCodeUnchecked(code WasmCode) (Checksum, error)

StoreCodeUnchecked is the same as StoreCode but skips static validation checks. Use this for adding code that was checked before, particularly in the case of state sync.

func (*VM) Sudo

func (vm *VM) Sudo(
	checksum Checksum,
	env types.Env,
	sudoMsg []byte,
	store KVStore,
	goapi GoAPI,
	querier Querier,
	gasMeter GasMeter,
	gasLimit uint64,
	deserCost types.UFraction,
) (*types.ContractResult, uint64, error)

Sudo allows native Go modules to make priviledged (sudo) calls on the contract. The contract can expose entry points that cannot be triggered by any transaction, but only via native Go modules, and delegate the access control to the system.

These work much like Migrate (same scenario) but allows custom apps to extend the priviledged entry points without forking cosmwasm-vm.

func (*VM) Unpin

func (vm *VM) Unpin(checksum Checksum) error

Unpin removes the guarantee of a contract to be pinned (see Pin). After calling this, the code may or may not remain in memory depending on the implementor's choice. Unpin is idempotent.

type WasmCode

type WasmCode []byte

WasmCode is an alias for raw bytes of the wasm compiled code

Directories

Path Synopsis
cmd
internal
api

Jump to

Keyboard shortcuts

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