cosmos-sdk/docs/core/context.md
Denis Fadeev 13378bd2cf Docs: hide frontmatter, bugfixes (#5413)
* encoding

* working on baseapp doc

* baseapp work

* reorg

* almost there

* finish first draft

* remove old files

* module doc start

* finish intro

* working

* workinnn

* add transactions into core

* hans comments

* add transactions into core

* working

* gautier comments

* clean

* working

* consolidate intro

* querier

* workiiiing

* refactor for new module interface

* karoly review

* working on baseapp doc

* baseapp work

* reorg

* almost there

* finish first draft

* remove old files

* finish intro

* workinnn

* initial commit after rebase

* query-lifecycle and started modules-interfaces

* query-lifecycle first draft done

* module interfaces first draft

* rest and intro skeletons

* rest and intro done

* small edits and links

* comments

* revisions

* cli.md comments

* comments

* minor edits

* better flow for query lifecycle

* add transactions into core

* hans comments

* add transactions into core

* checkout master-docs files

* deleted some

* remove modules readme

* cli.md comments

* comments

* module-interfaces comments

* Merge PR #4857: Add Context concept doc

* working

* working

* finish messages and queries

* handler

* querier

* last comments!

* punctuation

* querier2

* consolidate intro

* querier

* workiiiing

* refactor for new module interface

* karoly review

* working on baseapp doc

* baseapp work

* reorg

* almost there

* finish first draft

* remove old files

* finish intro

* workinnn

* initial commit after rebase

* query-lifecycle and started modules-interfaces

* query-lifecycle first draft done

* module interfaces first draft

* rest and intro skeletons

* rest and intro done

* small edits and links

* comments

* revisions

* cli.md comments

* comments

* minor edits

* better flow for query lifecycle

* checkout master-docs files

* deleted some

* remove modules readme

* cli.md comments

* comments

* module-interfaces comments

* keeper

* genesis

* finish

* Apply suggestions from code review

Co-Authored-By: Hans Schoenburg <hschoenburg@users.noreply.github.com>

* hans review

* Update docs/core/baseapp.md

Co-Authored-By: Hans Schoenburg <hschoenburg@users.noreply.github.com>

* working

* last comment

* workin

* Apply suggestions from code review

* encoding and node

* almost finish store

* finish docs

* fixes

* fede comments + permalinks

* hans review

* add more permalinks

* update docs theme version (#5239)

* R4R: Docs Cleanup (#5246)

* start

* work

* work

* work

* remove table of content

* links intro

* fix links

* remove junk

* cleanup

* cleanup

* work

* finish cleanup

* addback readmes

* remove nft

* fix links

* remove dup

* remove dup

* remove dup

* remove dup

* remove dup

* fix links

* add subscribe events

* refine rest

* index page

* sidebar

* theme version

* theme version

* testing netlify

* theme version

* tooltip example

* version

* testing code embedding

* reverting back

* theme version

* version

* version

* version

* readme and version

* cleanup

* redo app anatomy

* modules readme, theme version

* theme version

* fix modules list

* theme version

* new snippets

* modules readme

* update docs readme

* modify synopsis

* version

* fix yaml

* version

* version

* version

* version

* version

* version

* version

* version

* version

* version

* add hide banner

* version

* version

* version

* small fixes

* modules readme, version

* remove hotkeys dep, version

* version

* version

* version

* version

* version

* version

* version

* slight notice

* fix links and hide

* permalinks

* small clean

* version

* resolve conflicts, add google analytics

* fix merge remants

* version

* changelog 1/2

* Changelog: docs UI

* version

* remove merge conflicts

* Code: Update link for Contributing to the docs to docs_readme

* HTML/CSS: Update layout of homepage footer to match new layout in Figma

* version

* final modifs

* modules, version

* modules readme

* link to module list from homepage

* version

* building modules link

* version

* version

* fonts

* version

* version

* fix link

* fix package.json

* links in explore sdk section

* core concepts

* version

* change delimeters for frontmatter

* frontmatter in comments

* version

* temp add tiny-cookie

* fixed link issues

* fixed styling issues, copy

* hide frontmatter

* hide frontmatter

* layout fixes, padded ascii diagram

* fira sans font for code
2019-12-17 08:44:44 -03:00

7.7 KiB

Context

Pre-requisites Readings {hide}

Context Definition

The SDK Context is a custom data structure that contains Go's stdlib context as its base, and has many additional types within its definition that are specific to the Cosmos SDK. he Context is integral to transaction processing in that it allows modules to easily access their respective store in the multistore and retrieve transactional context such as the block header and gas meter.

type Context struct {
  ctx           context.Context
  ms            MultiStore
  header        abci.Header
  chainID       string
  txBytes       []byte
  logger        log.Logger
  voteInfo      []abci.VoteInfo
  gasMeter      GasMeter
  blockGasMeter GasMeter
  checkTx       bool
  minGasPrice   DecCoins
  consParams    *abci.ConsensusParams
  eventManager  *EventManager
}
  • Context: The base type is a Go Context, which is explained further in the Go Context Package section below.
  • Multistore: Every application's BaseApp contains a CommitMultiStore which is provided when a Context is created. Calling the KVStore() and TransientStore() methods allows modules to fetch their respective KVStore using their unique StoreKey.
  • ABCI Header: The header is an ABCI type. It carries important information about the state of the blockchain, such as block height and proposer of the current block.
  • Chain ID: The unique identification number of the blockchain a block pertains to.
  • Transaction Bytes: The []byte representation of a transaction being processed using the context. Every transaction is processed by various parts of the SDK and consensus engine (e.g. Tendermint) throughout its lifecycle, some of which to not have any understanding of transaction types. Thus, transactions are marshaled into the generic []byte type using some kind of encoding format such as Amino.
  • Logger: A logger from the Tendermint libraries. Learn more about logs here. Modules call this method to create their own unique module-specific logger.
  • VoteInfo: A list of the ABCI type VoteInfo, which includes the name of a validator and a boolean indicating whether they have signed the block.
  • Gas Meters: Specifically, a gasMeter for the transaction currently being processed using the context and a blockGasMeter for the entire block it belongs to. Users specify how much in fees they wish to pay for the execution of their transaction; these gas meters keep track of how much gas has been used in the transaction or block so far. If the gas meter runs out, execution halts.
  • CheckTx Mode: A boolean value indicating whether a transaction should be processed in CheckTx or DeliverTx mode.
  • Min Gas Price: The minimum gas price a node is willing to take in order to include a transaction in its block. This price is a local value configured by each node individually, and should therefore not be used in any functions used in sequences leading to state-transitions.
  • Consensus Params: The ABCI type Consensus Parameters, which specify certain limits for the blockchain, such as maximum gas for a block.
  • Event Manager: The event manager allows any caller with access to a Context to emit Events. Modules may define module specific Events by defining various Types and Attributes or use the common definitions found in types/. Clients can subscribe or query for these Events. These Events are collected throughout DeliverTx, BeginBlock, and EndBlock and are returned to Tendermint for indexing. For example:
ctx.EventManager().EmitEvent(sdk.NewEvent(
    sdk.EventTypeMessage,
    sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory)),
)

Go Context Package

A basic Context is defined in the Golang Context Package. A Context is an immutable data structure that carries request-scoped data across APIs and processes. Contexts are also designed to enable concurrency and to be used in goroutines.

Contexts are intended to be immutable; they should never be edited. Instead, the convention is to create a child context from its parent using a With function. For example:

childCtx = parentCtx.WithBlockHeader(header)

The Golang Context Package documentation instructs developers to explicitly pass a context ctx as the first argument of a process.

Cache Wrapping

The Context contains a MultiStore, which allows for cache-wrapping functionality: a CacheMultiStore where each KVStore is is wrapped with an ephemeral cache. Processes are free to write changes to the CacheMultiStore, then write the changes back to the original state or disregard them if something goes wrong. The pattern of usage for a Context is as follows:

  1. A process receives a Context ctx from its parent process, which provides information needed to perform the process.
  2. The ctx.ms is cache wrapped, i.e. a cached copy of the multistore is made so that the process can make changes to the state as it executes, without changing the originalctx.ms. This is useful to protect the underlying multistore in case the changes need to be reverted at some point in the execution.
  3. The process may read and write from ctx as it is executing. It may call a subprocess and pass ctx to it as needed.
  4. When a subprocess returns, it checks if the result is a success or failure. If a failure, nothing needs to be done - the cache wrapped ctx is simply discarded. If successful, the changes made to the cache-wrapped MultiStore can be committed to the original ctx.ms via Write().

For example, here is a snippet from the runTx function in baseapp:

runMsgCtx, msCache := app.cacheTxContext(ctx, txBytes)
result = app.runMsgs(runMsgCtx, msgs, mode)
result.GasWanted = gasWanted

if mode != runTxModeDeliver {
  return result
}

if result.IsOK() {
  msCache.Write()
}

Here is the process:

  1. Prior to calling runMsgs on the message(s) in the transaction, it uses app.cacheTxContext() to cache-wrap the context and multistore.
  2. The cache-wrapped context, runMsgCtx, is used in runMsgs to return a result.
  3. If the process is running in checkTxMode, there is no need to write the changes - the result is returned immediately.
  4. If the process is running in deliverTxMode and the result indicates a successful run over all the messages, the cached multistore is written back to the original.

Next {hide}

Learn about the node client {hide}