cosmos-sdk/types/context.go

95 lines
2.2 KiB
Go
Raw Normal View History

2017-11-26 02:19:17 -08:00
package types
import (
"context"
abci "github.com/tendermint/abci/types"
2017-11-26 02:19:17 -08:00
)
type Context struct {
2017-11-26 02:19:17 -08:00
context.Context
// Don't add any other fields here,
// it's probably not what you want to do.
2017-11-26 02:19:17 -08:00
}
func NewContext(header tm.Header, isCheckTx bool, txBytes []byte) Context {
c := Context{
2017-11-26 02:19:17 -08:00
Context: context.Background(),
}
c = c.setBlockHeader(header)
c = c.setBlockHeight(int64(header.Height))
c = c.setChainID(header.ChainID)
c = c.setIsCheckTx(isCheckTx)
c = c.setTxBytes(txBytes)
2017-11-26 02:19:17 -08:00
return c
}
// The original context.Context API.
func (c Context) WithValue(key interface{}, value interface{}) context.Context {
return context.WithValue(c.Context, key, value)
2017-11-26 02:19:17 -08:00
}
// Like WithValue() but retains this API.
func (c Context) WithValueSDK(key interface{}, value interface{}) Context {
return Context{
Context: context.WithValue(c.Context, key, value),
}
2017-11-26 02:19:17 -08:00
}
//----------------------------------------
// Our extensions
type contextKey int // local to the context module
const (
contextKeyBlockHeader contextKey = iota
contextKeyBlockHeight
contextKeyChainID
contextKeyIsCheckTx
contextKeyTxBytes
2017-11-26 02:19:17 -08:00
)
func (c Context) BlockHeader() tm.Header {
2017-11-26 02:19:17 -08:00
return c.Value(contextKeyBlockHeader).(tm.Header)
}
func (c Context) BlockHeight() int64 {
2017-11-26 20:29:17 -08:00
return c.Value(contextKeyBlockHeight).(int64)
}
func (c Context) ChainID() string {
2017-11-26 20:29:17 -08:00
return c.Value(contextKeyChainID).(string)
}
func (c Context) IsCheckTx() bool {
return c.Value(contextKeyIsCheckTx).(bool)
}
func (c Context) TxBytes() []byte {
return c.Value(contextKeyTxBytes).([]byte)
}
2017-11-26 02:19:17 -08:00
// Unexposed to prevent overriding.
func (c Context) setBlockHeader(header tm.Header) Context {
2017-11-26 02:19:17 -08:00
return c.WithValueSDK(contextKeyBlockHeader, header)
}
// Unexposed to prevent overriding.
func (c Context) setBlockHeight(height int64) Context {
2017-11-26 02:19:17 -08:00
return c.WithValueSDK(contextKeyBlockHeight, header)
}
// Unexposed to prevent overriding.
func (c Context) setChainID(chainID string) Context {
2017-11-26 02:19:17 -08:00
return c.WithValueSDK(contextKeyChainID, header)
}
// Unexposed to prevent overriding.
func (c Context) setIsCheckTx(isCheckTx bool) Context {
return c.WithValueSDK(contextKeyIsCheckTx, isCheckTx)
}
// Unexposed to prevent overriding.
func (c Context) setTxBytes(txBytes []byte) Context {
return c.WithValueSDK(contextKeyTxBytes, txBytes)
}